diff --git a/.github/scripts/arc-ci-coverage.cjs b/.github/scripts/arc-ci-coverage.cjs index 9186e5da7a7a..ec7fc9cf6089 100644 --- a/.github/scripts/arc-ci-coverage.cjs +++ b/.github/scripts/arc-ci-coverage.cjs @@ -23,6 +23,7 @@ const REQUIRED_TESTS = [ "apps/server/src/orchestration-v2/ModelAlertReactor.test.ts", "apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts", "apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts", + "apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts", "packages/shared/src/threadPlacement.test.ts", "apps/server/src/peer/RemoteDelegation.test.ts", "apps/server/src/mcp/OrchestratorMcpService.test.ts", diff --git a/.github/scripts/arc-ci-coverage.test.cjs b/.github/scripts/arc-ci-coverage.test.cjs index 747cf63ab398..288a27be8ed1 100644 --- a/.github/scripts/arc-ci-coverage.test.cjs +++ b/.github/scripts/arc-ci-coverage.test.cjs @@ -83,3 +83,11 @@ test("a covering step with any step-level if: fails the check", () => { ); } }); + +test("compaction delivery integration suite is required by the coverage guard (CLO-1096)", () => { + const suite = "apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts"; + assert.ok(REQUIRED_TESTS.includes(suite)); + const dropped = workflow.replace(` ${suite} \\\n`, ""); + assert.notEqual(dropped, workflow); + assert.ok(checkCoverage(dropped).some((problem) => problem.includes(suite))); +}); diff --git a/.github/workflows/closura-arc-ci.yml b/.github/workflows/closura-arc-ci.yml index 8402e32f9407..d17bc6c7190e 100644 --- a/.github/workflows/closura-arc-ci.yml +++ b/.github/workflows/closura-arc-ci.yml @@ -183,6 +183,10 @@ jobs: 'packages/client-runtime/src/state/threadListFilter.ts': ['matchesPrimaryInbox', 'matchesListedInboxes', 'hiddenEnvironmentIds'], 'apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx': ['Kameron', 'Jeff', 'Agents', 'Environments'], 'apps/web/src/components/sidebar/threadListFilter.logic.ts': ['matchesListedInboxes', 'hiddenEnvironmentIds'], + 'apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts': [ + 'promoting %s into a compaction stops it and sends it next', + 'settles a steered completion wake whose parent run is before the last compaction (restart by intent: %s)', + ], }; for (const [file, needles] of Object.entries(required)) { const source = readFileSync(file, 'utf8'); @@ -221,6 +225,7 @@ jobs: apps/server/src/orchestration-v2/ModelAlertReactor.test.ts \ apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts \ apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts \ + apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts \ packages/shared/src/threadPlacement.test.ts \ apps/server/src/peer/RemoteDelegation.test.ts \ apps/server/src/mcp/OrchestratorMcpService.test.ts \ diff --git a/apps/desktop/src/app/DesktopAppIdentity.test.ts b/apps/desktop/src/app/DesktopAppIdentity.test.ts index 74d134c0b100..299921ed3301 100644 --- a/apps/desktop/src/app/DesktopAppIdentity.test.ts +++ b/apps/desktop/src/app/DesktopAppIdentity.test.ts @@ -154,7 +154,7 @@ describe("DesktopAppIdentity", () => { const identity = yield* DesktopAppIdentity.DesktopAppIdentity; const userDataPath = yield* identity.resolveUserDataPath; - assert.equal(userDataPath, "/Users/alice/Library/Application Support/t3code-v2"); + assert.equal(userDataPath, "/Users/alice/Library/Application Support/closura-t3code-v2"); }), { legacyPathExists: true }, ), diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts index c17cb00869a3..5e4b0e0f5599 100644 --- a/apps/desktop/src/app/DesktopClerk.test.ts +++ b/apps/desktop/src/app/DesktopClerk.test.ts @@ -123,19 +123,19 @@ describe("DesktopClerk", () => { name: "packaged macOS", isDevelopment: false, platform: "darwin" as const, - userData: "/tmp/app-data/t3code-v2", + userData: "/tmp/app-data/closura-t3code-v2", }, { name: "packaged Linux", isDevelopment: false, platform: "linux" as const, - userData: "/tmp/app-data/t3code-v2", + userData: "/tmp/app-data/closura-t3code-v2", }, { name: "packaged Windows", isDevelopment: false, platform: "win32" as const, - userData: "/tmp/app-data/t3code-v2", + userData: "/tmp/app-data/closura-t3code-v2", }, { name: "development", @@ -300,7 +300,7 @@ describe("DesktopClerk", () => { assert.isTrue(Exit.hasInterrupts(exit)); assert.deepEqual(events, [ - "setPath:userData:/tmp/app-data/t3code-v2", + "setPath:userData:/tmp/app-data/closura-t3code-v2", "requestSingleInstanceLock", "quit", ]); diff --git a/apps/desktop/src/app/DesktopUserData.test.ts b/apps/desktop/src/app/DesktopUserData.test.ts index 53e548bd1d41..a5b858ba936b 100644 --- a/apps/desktop/src/app/DesktopUserData.test.ts +++ b/apps/desktop/src/app/DesktopUserData.test.ts @@ -5,7 +5,108 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; -import { clearStaleGpuCaches, resolveUserDataPath } from "./DesktopUserData.ts"; +import { + CLOSURA_FORK_USER_DATA_DIR, + clearStaleGpuCaches, + resolveUserDataPath, +} from "./DesktopUserData.ts"; + +it.effect.each(["linux", "darwin", "win32"] as const)( + "uses a distinct Closura fork user-data directory on %s and migrates existing t3code-v2 state once (CLO-1100)", + (platform) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-closura-profile-" }); + const stockDir = path.join(directory, "t3code-v2"); + const forkDir = path.join(directory, CLOSURA_FORK_USER_DATA_DIR); + + yield* fs.makeDirectory(path.join(stockDir, "Local Storage"), { recursive: true }); + yield* fs.makeDirectory(path.join(stockDir, "GPUCache"), { recursive: true }); + yield* fs.writeFileString(path.join(stockDir, "Preferences"), '{"fork":true}'); + yield* fs.writeFileString(path.join(stockDir, "Local Storage", "data"), "saved-state"); + yield* fs.writeFileString(path.join(stockDir, "Local Storage", "LOCK"), "locked"); + yield* fs.writeFileString(path.join(stockDir, "SingletonLock"), "pid"); + yield* fs.writeFileString(path.join(stockDir, "GPUCache", "data_0"), "stale-gpu"); + + const firstPath = yield* resolveUserDataPath({ + appDataDirectory: directory, + isDevelopment: false, + platform, + }); + assert.equal(firstPath, forkDir); + assert.notEqual(firstPath, stockDir); + assert.equal(yield* fs.readFileString(path.join(forkDir, "Preferences")), '{"fork":true}'); + assert.equal( + yield* fs.readFileString(path.join(forkDir, "Local Storage", "data")), + "saved-state", + ); + assert.isFalse(yield* fs.exists(path.join(forkDir, "SingletonLock"))); + assert.isFalse(yield* fs.exists(path.join(forkDir, "Local Storage", "LOCK"))); + assert.isFalse(yield* fs.exists(path.join(forkDir, "GPUCache"))); + assert.isTrue(yield* fs.exists(path.join(forkDir, ".migrated-from-t3code-v2"))); + // Stock profile remains intact for side-by-side stock T3 Code installs. + assert.equal(yield* fs.readFileString(path.join(stockDir, "Preferences")), '{"fork":true}'); + + // Subsequent launches must not overwrite fork state even if stock profile changes. + yield* fs.writeFileString(path.join(forkDir, "Preferences"), '{"fork":"updated"}'); + yield* fs.writeFileString(path.join(stockDir, "Preferences"), '{"stock":"mutated"}'); + const secondPath = yield* resolveUserDataPath({ + appDataDirectory: directory, + isDevelopment: false, + platform, + }); + assert.equal(secondPath, forkDir); + assert.equal( + yield* fs.readFileString(path.join(forkDir, "Preferences")), + '{"fork":"updated"}', + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect( + "redoes an interrupted t3code-v2 migration instead of keeping a partial fork profile (CLO-1100)", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-closura-partial-" }); + const stockDir = path.join(directory, "t3code-v2"); + const forkDir = path.join(directory, CLOSURA_FORK_USER_DATA_DIR); + const stagingDir = `${forkDir}.migrating`; + yield* fs.makeDirectory(path.join(stockDir, "IndexedDB"), { recursive: true }); + yield* fs.writeFileString(path.join(stockDir, "Preferences"), "prefs"); + yield* fs.writeFileString(path.join(stockDir, "IndexedDB", "db"), "indexed"); + yield* fs.writeFileString(path.join(stockDir, "Cookies"), "cookies"); + + // A copy that failed partway leaves only its staging directory behind. + yield* fs.makeDirectory(stagingDir, { recursive: true }); + yield* fs.writeFileString(path.join(stagingDir, "Preferences"), "prefs"); + const cookies = path.join(stockDir, "Cookies"); + yield* fs.chmod(cookies, 0o000); + const failure = yield* Effect.flip( + resolveUserDataPath({ + appDataDirectory: directory, + isDevelopment: false, + platform: "linux", + }), + ); + assert.equal(failure._tag, "DesktopUserDataInitializationError"); + assert.isFalse(yield* fs.exists(forkDir)); + + yield* fs.chmod(cookies, 0o644); + const resolved = yield* resolveUserDataPath({ + appDataDirectory: directory, + isDevelopment: false, + platform: "linux", + }); + assert.equal(resolved, forkDir); + assert.isFalse(yield* fs.exists(stagingDir)); + assert.equal(yield* fs.readFileString(path.join(forkDir, "IndexedDB", "db")), "indexed"); + assert.equal(yield* fs.readFileString(path.join(forkDir, "Cookies")), "cookies"); + assert.isTrue(yield* fs.exists(path.join(forkDir, ".migrated-from-t3code-v2"))); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); it.effect.each(["t3code", "T3 Code (Alpha)"])( "preserves Windows credential keys from %s without copying browser databases", @@ -15,7 +116,7 @@ it.effect.each(["t3code", "T3 Code (Alpha)"])( const path = yield* Path.Path; const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-profile-" }); const source = path.join(directory, sourceName); - const destination = path.join(directory, "t3code-v2"); + const destination = path.join(directory, CLOSURA_FORK_USER_DATA_DIR); const state = '{"os_crypt":{"encrypted_key":"test-encrypted-key"}}'; yield* fs.makeDirectory(path.join(directory, "T3 Code (Alpha)"), { recursive: true }); yield* fs.makeDirectory(path.join(source, "IndexedDB"), { recursive: true }); diff --git a/apps/desktop/src/app/DesktopUserData.ts b/apps/desktop/src/app/DesktopUserData.ts index 0124aa72e0ad..1c5cf0559bea 100644 --- a/apps/desktop/src/app/DesktopUserData.ts +++ b/apps/desktop/src/app/DesktopUserData.ts @@ -7,7 +7,14 @@ import * as Schema from "effect/Schema"; export class DesktopUserDataInitializationError extends Schema.TaggedError()( "DesktopUserDataInitializationError", { - operation: Schema.Literals(["inspect", "read", "create-directory", "write"]), + operation: Schema.Literals([ + "inspect", + "read", + "create-directory", + "write", + "remove", + "rename", + ]), resourcePath: Schema.String, category: Schema.String, cause: Schema.Defect(), @@ -31,6 +38,67 @@ export class DesktopUserDataInitializationError extends Schema.TaggedError { + yield* fs + .makeDirectory(targetDir, { recursive: true }) + .pipe( + Effect.mapError((cause) => + DesktopUserDataInitializationError.fromFileSystem(cause, "create-directory", targetDir), + ), + ); + const entries = yield* fs + .readDirectory(sourceDir) + .pipe( + Effect.mapError((cause) => + DesktopUserDataInitializationError.fromFileSystem(cause, "read", sourceDir), + ), + ); + for (const name of entries) { + if (MIGRATION_SKIP_NAMES.has(name)) continue; + const src = path.join(sourceDir, name); + const dst = path.join(targetDir, name); + const info = yield* fs + .stat(src) + .pipe( + Effect.mapError((cause) => + DesktopUserDataInitializationError.fromFileSystem(cause, "inspect", src), + ), + ); + if (info.type === "Directory") { + yield* copyProfileTree(fs, path, src, dst); + } else if (info.type === "File") { + yield* fs + .copyFile(src, dst) + .pipe( + Effect.mapError((cause) => + DesktopUserDataInitializationError.fromFileSystem(cause, "write", dst), + ), + ); + } + } +}); + export const resolveUserDataPath = Effect.fn("desktop.userData.resolveUserDataPath")( function* (input: { readonly appDataDirectory: string; @@ -41,7 +109,7 @@ export const resolveUserDataPath = Effect.fn("desktop.userData.resolveUserDataPa const path = yield* Path.Path; const names = input.isDevelopment ? { current: "t3code-dev", legacy: "T3 Code (Dev)" } - : { current: "t3code-v2", legacy: "T3 Code (Alpha)" }; + : { current: CLOSURA_FORK_USER_DATA_DIR, legacy: "T3 Code (Alpha)" }; const destinationPath = path.join(input.appDataDirectory, names.current); const legacyPath = path.join(input.appDataDirectory, names.legacy); const inspect = (resourcePath: string) => @@ -55,6 +123,39 @@ export const resolveUserDataPath = Effect.fn("desktop.userData.resolveUserDataPa if (input.isDevelopment) { return (yield* inspect(legacyPath)) ? legacyPath : destinationPath; } + // Isolate the Closura fork profile from stock `t3code-v2` so side-by-side installs + // never corrupt each other. If the fork profile does not exist yet and a prior + // `t3code-v2` profile is present, copy it once and leave `t3code-v2` untouched. + const stockV2Path = path.join(input.appDataDirectory, STOCK_V2_USER_DATA_DIR); + if (!(yield* inspect(destinationPath)) && (yield* inspect(stockV2Path))) { + // Stage the copy and rename it into place so an interrupted migration never + // leaves a partial fork profile that later launches would treat as complete. + const stagingPath = `${destinationPath}.migrating`; + yield* fs + .remove(stagingPath, { recursive: true, force: true }) + .pipe( + Effect.mapError((cause) => + DesktopUserDataInitializationError.fromFileSystem(cause, "remove", stagingPath), + ), + ); + yield* copyProfileTree(fs, path, stockV2Path, stagingPath); + const markerPath = path.join(stagingPath, MIGRATION_MARKER_FILE); + yield* fs + .writeFileString(markerPath, "migrated\n") + .pipe( + Effect.mapError((cause) => + DesktopUserDataInitializationError.fromFileSystem(cause, "write", markerPath), + ), + ); + yield* fs + .rename(stagingPath, destinationPath) + .pipe( + Effect.mapError((cause) => + DesktopUserDataInitializationError.fromFileSystem(cause, "rename", destinationPath), + ), + ); + return destinationPath; + } // Chromium databases require their own profile for each running version. if (input.platform !== "win32") return destinationPath; const destinationState = path.join(destinationPath, "Local State"); diff --git a/scripts/build-cli-archive.test.ts b/scripts/build-cli-archive.test.ts index 45ce12deb32c..9533e8850ca1 100644 --- a/scripts/build-cli-archive.test.ts +++ b/scripts/build-cli-archive.test.ts @@ -1,3 +1,5 @@ +import * as Crypto from "node:crypto"; +import * as NodeFs from "node:fs"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as ConfigProvider from "effect/ConfigProvider"; @@ -9,7 +11,12 @@ import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; -import { awaitCliNotarization, signMacArchiveContents } from "./build-cli-archive.ts"; +import { + awaitCliNotarization, + createDeterministicTarGz, + resolveSourceDateEpoch, + signMacArchiveContents, +} from "./build-cli-archive.ts"; const signedEnv = { T3CODE_CLI_MAC_SIGN_IDENTITY: "Developer ID Application: Test (TEAM)", @@ -213,4 +220,66 @@ it.layer(NodeServices.layer)("build-cli-archive notarization", (it) => { assert.isTrue(notarySubcommands(stub.calls)[0]?.includes("--wait")); }).pipe(Effect.scoped), ); + + it.effect("produces byte-identical SHA-256 tarballs across distinct build orders and mtimes (CLO-1100)", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + assert.equal(resolveSourceDateEpoch(undefined), "0"); + assert.equal(resolveSourceDateEpoch("invalid"), "0"); + assert.equal(resolveSourceDateEpoch("1700000000"), "1700000000"); + + const workspace = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-repro-" }); + const stem = "t3-0.1.10-linux-x64"; + const stageA = path.join(workspace, "stage-a"); + const stageB = path.join(workspace, "stage-b"); + const dirA = path.join(stageA, stem); + const dirB = path.join(stageB, stem); + + yield* fs.makeDirectory(path.join(dirA, "client"), { recursive: true }); + yield* fs.makeDirectory(path.join(dirB, "client"), { recursive: true }); + + // Write identical contents in opposite order with different file mtimes. + yield* fs.writeFileString(path.join(dirA, "t3"), "binary-payload"); + yield* fs.writeFileString(path.join(dirA, "client", "a.js"), "console.log('a');\n"); + yield* fs.writeFileString(path.join(dirA, "client", "z.js"), "console.log('z');\n"); + NodeFs.utimesSync(path.join(dirA, "t3"), 1700000001, 1700000001); + NodeFs.utimesSync(path.join(dirA, "client", "a.js"), 1700000002, 1700000002); + NodeFs.utimesSync(path.join(dirA, "client", "z.js"), 1700000003, 1700000003); + + yield* fs.writeFileString(path.join(dirB, "client", "z.js"), "console.log('z');\n"); + yield* fs.writeFileString(path.join(dirB, "client", "a.js"), "console.log('a');\n"); + yield* fs.writeFileString(path.join(dirB, "t3"), "binary-payload"); + NodeFs.utimesSync(path.join(dirB, "t3"), 1750000010, 1750000010); + NodeFs.utimesSync(path.join(dirB, "client", "a.js"), 1750000020, 1750000020); + NodeFs.utimesSync(path.join(dirB, "client", "z.js"), 1750000030, 1750000030); + + const archiveA = path.join(workspace, "a.tar.gz"); + const archiveB = path.join(workspace, "b.tar.gz"); + yield* createDeterministicTarGz({ + archivePath: archiveA, + stageRoot: stageA, + stem, + platform: "linux", + hostPlatform: process.platform, + sourceDateEpoch: "1700000000", + }); + yield* createDeterministicTarGz({ + archivePath: archiveB, + stageRoot: stageB, + stem, + platform: "linux", + hostPlatform: process.platform, + sourceDateEpoch: "1700000000", + }); + + const bytesA = yield* fs.readFile(archiveA); + const bytesB = yield* fs.readFile(archiveB); + const shaA = Crypto.createHash("sha256").update(bytesA).digest("hex"); + const shaB = Crypto.createHash("sha256").update(bytesB).digest("hex"); + assert.equal(shaA, shaB); + // Gzip header bytes 4..7 hold MTIME; gzip -n zeroes them for reproducibility. + assert.deepEqual(Array.from(bytesA.subarray(4, 8)), [0, 0, 0, 0]); + }).pipe(Effect.scoped), + ); }); diff --git a/scripts/build-cli-archive.ts b/scripts/build-cli-archive.ts index d55d8799f6c9..6769e543e45e 100644 --- a/scripts/build-cli-archive.ts +++ b/scripts/build-cli-archive.ts @@ -99,6 +99,90 @@ export function cliArchiveStem(version: string, platform: BuildPlatform, arch: B return `t3-${version}-${cliArchivePlatformKey(platform, arch)}`; } +export const DEFAULT_SOURCE_DATE_EPOCH = "0"; + +export function resolveSourceDateEpoch(envValue: string | undefined): string { + const trimmed = envValue?.trim(); + if (trimmed && /^\d+$/.test(trimmed)) return trimmed; + return DEFAULT_SOURCE_DATE_EPOCH; +} + +export const createDeterministicTarGz = Effect.fn("createDeterministicTarGz")(function* (input: { + readonly archivePath: string; + readonly stageRoot: string; + readonly stem: string; + readonly platform: BuildPlatform; + readonly hostPlatform: NodeJS.Platform; + readonly sourceDateEpoch?: string; +}) { + const epoch = resolveSourceDateEpoch(input.sourceDateEpoch ?? process.env.SOURCE_DATE_EPOCH); + if (input.hostPlatform === "darwin") { + // macOS ships bsdtar: normalize owner/group and strip the gzip header timestamp. + yield* runCommand( + ChildProcess.make( + "tar", + [ + "--uid", + "0", + "--gid", + "0", + "--uname", + "", + "--gname", + "", + "--options", + "gzip:!timestamp", + "-czf", + input.archivePath, + "-C", + input.stageRoot, + input.stem, + ], + { + env: { + ...process.env, + TZ: "UTC", + LC_ALL: "C", + }, + }, + ), + "tar (deterministic gzip)", + ); + return; + } + // GNU tar on Linux: sorted entries, fixed mtime, numeric uid/gid 0, and gzip -n (no header mtime). + // npm rejects Linux hardlink entries; macOS pnpm clones and bsdtar lacks --hard-dereference. + yield* runCommand( + ChildProcess.make( + "tar", + [ + "--sort=name", + `--mtime=@${epoch}`, + "--owner=0", + "--group=0", + "--numeric-owner", + "--format=gnu", + ...(input.platform === "linux" ? ["--hard-dereference"] : []), + "-I", + "gzip -n", + "-cf", + input.archivePath, + "-C", + input.stageRoot, + input.stem, + ], + { + env: { + ...process.env, + TZ: "UTC", + LC_ALL: "C", + }, + }, + ), + "tar (deterministic gzip)", + ); +}); + export function cliArchiveFileName(version: string, platform: BuildPlatform, arch: BuildArch) { // Minimal hosts may lack xz, but tar and Node zlib handle gzip without it. return `${cliArchiveStem(version, platform, arch)}.${platform === "win" ? "zip" : "tar.gz"}`; @@ -692,18 +776,13 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: { "tar (zip)", ); } else { - // npm rejects Linux hardlink entries; macOS pnpm clones and bsdtar lacks this flag. - yield* runCommand( - ChildProcess.make("tar", [ - ...(input.platform === "linux" ? ["--hard-dereference"] : []), - "-czf", - archivePath, - "-C", - stageRoot, - stem, - ]), - "tar (gzip)", - ); + yield* createDeterministicTarGz({ + archivePath, + stageRoot, + stem, + platform: input.platform, + hostPlatform, + }); } const stat = yield* fs.stat(archivePath); yield* Effect.log(`[cli-archive] Wrote ${archivePath} (${String(stat.size)} bytes).`);