From cc45e26e986aba4fee15c5bb5c3b2fbe582b8734 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:10:16 +0800 Subject: [PATCH 1/4] perf(ci): parallelize CI jobs and speed up slow test suites --- .github/workflows/ci.yml | 50 +- infra/architecture/run-lint-cases.ts | 84 +- infra/architecture/workspace.ts | 5 + package.json | 10 +- .../acp/test/connect-agent-lifecycle.test.ts | 472 ++++++++++ packages/acp/test/connect-agent.test.ts | 461 +-------- .../test/support/uninstall-created-config.ts | 890 ++++++++++++++++++ ...install-created-config-claude-code.test.ts | 3 + .../test/uninstall-created-config.test.ts | 880 +---------------- .../claude-code/test/summarize-memory.test.ts | 2 +- .../codex/test/summarize-memory.test.ts | 2 +- .../grok/test/summarize-memory.test.ts | 2 +- packages/testing/test/memory-support.ts | 24 +- 13 files changed, 1511 insertions(+), 1374 deletions(-) create mode 100644 packages/acp/test/connect-agent-lifecycle.test.ts create mode 100644 packages/harness/test/support/uninstall-created-config.ts create mode 100644 packages/harness/test/uninstall-created-config-claude-code.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 55b31bbb..64e4469e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,9 +14,9 @@ concurrency: cancel-in-progress: true jobs: - check: + static: if: github.event_name != 'pull_request' || !github.event.pull_request.draft - name: check + name: static runs-on: ubuntu-latest timeout-minutes: 20 steps: @@ -34,7 +34,51 @@ jobs: - uses: PerfectPan/gh-repo-checks@v1 with: check: release-plan - - run: pnpm run check + - name: Format, docs and duplicates + run: pnpm run format:check && pnpm run check:docs && pnpm run duplicates + - name: Build + run: pnpm run build + - name: Lint + # Cache the workspace listing once so all 38 package `vp lint` processes skip spawning `pnpm ls`. + run: >- + AGENT_KIT_PNPM_LIST_ROOT="$(node -p 'fs.realpathSync(process.cwd())')" + AGENT_KIT_PNPM_LIST_JSON="$(pnpm ls -r --depth -1 --json)" + pnpm run lint + - name: Knip, typecheck and package check + run: pnpm run knip && pnpm run knip:production && pnpm run typecheck && pnpm run check:package + + test: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + name: test + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + - uses: pnpm/setup@v3 + with: + runtime: node + require-lockfile: true + cache: true + # Only the published shells' built entries are imported by tests; website build stays in `static`. + - name: Build shells + run: pnpm --filter @rivus/agent-kit... --filter @rivus/agent-kit-collab... run build + - name: Test + run: pnpm run test + + # Aggregate status check preserving the `check` context name required by branch protection. + check: + if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) + name: check + needs: [static, test] + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Verify required jobs succeeded + run: | + if [ "${{ needs.static.result }}" != "success" ] || [ "${{ needs.test.result }}" != "success" ]; then + echo "static=${{ needs.static.result }}, test=${{ needs.test.result }}" + exit 1 + fi # The tests of every workspace package on Windows, where `\` is a path separator and there are no POSIX signals, # file modes or process identity. The aggregate gate stays on Linux. diff --git a/infra/architecture/run-lint-cases.ts b/infra/architecture/run-lint-cases.ts index ca8cd66e..539b5800 100644 --- a/infra/architecture/run-lint-cases.ts +++ b/infra/architecture/run-lint-cases.ts @@ -18,7 +18,7 @@ import { writeFileSync } from "node:fs"; import { createRequire } from "node:module"; -import { constants, tmpdir } from "node:os"; +import { availableParallelism, constants, tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; @@ -26,6 +26,7 @@ import { promisify } from "node:util"; import { cases } from "./lint-cases.ts"; import type { Case } from "./case.ts"; import { workspaceProjects } from "./lint.ts"; +import { pnpmListJson } from "./workspace.ts"; const ROOT = realpathSync(fileURLToPath(new URL("../..", import.meta.url))); const run = promisify(execFile); @@ -68,10 +69,15 @@ function lineOf(diagnostic: Diagnostic): string { } /** `vp lint` in one package of the copy, as `pnpm -r run lint` runs it there. */ -async function lint(copy: string, folder: string, files: readonly string[]): Promise { +async function lint( + copy: string, + folder: string, + files: readonly string[], + env?: NodeJS.ProcessEnv +): Promise { const cwd = join(copy, folder); const args = ["lint", "--format", "json", ...files]; - const options = { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 } as const; + const options = { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, ...(env ? { env } : {}) } as const; // vp exits non-zero when it reports errors; the JSON on stdout is the result either way. const { stdout } = await run(process.execPath, [vp, ...args], options).catch( (error: { stdout?: string; stderr?: string }) => { @@ -208,7 +214,7 @@ async function nestedProvider(copy: string): Promise { } /** The generated override must enable the Node boundary rule even when the top-level plugins list omits import. */ -async function restrictedPlugins(copy: string): Promise { +async function restrictedPlugins(copy: string, env?: NodeJS.ProcessEnv): Promise { const folder = "packages/sessions"; const config = join(copy, folder, "vite.config.ts"); const original = readFileSync(config, "utf8"); @@ -223,14 +229,14 @@ async function restrictedPlugins(copy: string): Promise { writeFileSync(join(copy, folder, "src/plugin-node.ts"), 'export { readFile } from "node:fs/promises";\n'); writeFileSync(join(copy, folder, "src/plugin-plain.ts"), 'export { ok } from "@rivus/agent-kit-catalog/public";\n'); try { - return await lint(copy, folder, ["src/plugin-node.ts", "src/plugin-plain.ts"]); + return await lint(copy, folder, ["src/plugin-node.ts", "src/plugin-plain.ts"], env); } finally { writeFileSync(config, original); } } /** A new provider fact must reach the context rule without updating infrastructure's marker list. */ -async function addedProviderMarker(copy: string): Promise { +async function addedProviderMarker(copy: string, env?: NodeJS.ProcessEnv): Promise { const facts = join(copy, "packages/providers/pi/src/facts.ts"); const original = readFileSync(facts, "utf8"); const marker = "PROVIDER_MARKER_PROBE"; @@ -244,7 +250,7 @@ async function addedProviderMarker(copy: string): Promise { const file = join(copy, "packages/catalog/src/marker-probe.ts"); writeFileSync(file, `export const marker = "${marker}";\n`); try { - return await lint(copy, "packages/catalog", ["src/marker-probe.ts"]); + return await lint(copy, "packages/catalog", ["src/marker-probe.ts"], env); } finally { writeFileSync(facts, original); rmSync(file); @@ -298,34 +304,58 @@ try { } spiProvider(copy); spiProvider(copy, true); - for (const batch of batches()) { - const undo = batch.map((entry) => apply(copy, entry)); - try { - const pkg = batch[0]?.pkg ?? ""; - const diagnostics = await lint( - copy, - `packages/${pkg}`, - batch.map(({ path }) => path) - ); - for (const entry of batch) { - const own = diagnostics.filter(({ filename }) => filename === entry.path); - failures += report(entry.name, `packages/${pkg}/${entry.path}`, entry.expected, own) ? 0 : 1; - } - } finally { - for (const restore of undo.toReversed()) { - restore(); + // Capture the workspace listing once after synthetic providers exist so child `vp lint` processes skip `pnpm ls`. + const cachedListEnv: NodeJS.ProcessEnv = { + ...process.env, + AGENT_KIT_PNPM_LIST_ROOT: copy, + AGENT_KIT_PNPM_LIST_JSON: pnpmListJson(copy) + }; + // Different packages mutate disjoint folders, so run package groups concurrently (largest first to avoid a tail) + // while keeping batches within the same package sequential. + const groups = [...Map.groupBy(batches(), (batch) => batch[0]?.pkg ?? "").values()].toSorted( + (a, b) => b.length - a.length + ); + let nextGroup = 0; + const concurrency = Math.max(2, Math.min(availableParallelism(), 6, groups.length)); + await Promise.all( + Array.from({ length: concurrency }, async () => { + while (nextGroup < groups.length) { + const group = groups[nextGroup++]; + if (group === undefined) { + return; + } + for (const batch of group) { + const undo = batch.map((entry) => apply(copy, entry)); + try { + const pkg = batch[0]?.pkg ?? ""; + const diagnostics = await lint( + copy, + `packages/${pkg}`, + batch.map(({ path }) => path), + cachedListEnv + ); + for (const entry of batch) { + const own = diagnostics.filter(({ filename }) => filename === entry.path); + failures += report(entry.name, `packages/${pkg}/${entry.path}`, entry.expected, own) ? 0 : 1; + } + } finally { + for (const restore of undo.toReversed()) { + restore(); + } + } + } } - } - } + }) + ); failures += report( "agent marker: added provider fact", "packages/catalog/src/marker-probe.ts", ["agent-marker"], - await addedProviderMarker(copy) + await addedProviderMarker(copy, cachedListEnv) ) ? 0 : 1; - const restricted = await restrictedPlugins(copy); + const restricted = await restrictedPlugins(copy, cachedListEnv); failures += report( "typescript-only top-level plugins: Node builtin", "packages/sessions/src/plugin-node.ts", diff --git a/infra/architecture/workspace.ts b/infra/architecture/workspace.ts index 901e34f2..e1e8b245 100644 --- a/infra/architecture/workspace.ts +++ b/infra/architecture/workspace.ts @@ -2,6 +2,11 @@ import { execFileSync } from "node:child_process"; /** Lists the workspace members as raw JSON from `pnpm ls -r --depth -1 --json`. */ export function pnpmListJson(root: string): string { + // run-lint-cases spawns `vp lint` dozens of times against an unchanged fixture copy; reuse one listing when rooted + // at the same directory instead of invoking pnpm on every process startup. + if (process.env.AGENT_KIT_PNPM_LIST_ROOT === root && process.env.AGENT_KIT_PNPM_LIST_JSON !== undefined) { + return process.env.AGENT_KIT_PNPM_LIST_JSON; + } return execFileSync("pnpm", ["ls", "-r", "--depth", "-1", "--json"], { cwd: root, encoding: "utf8", diff --git a/package.json b/package.json index ef4d6b73..0fab0fbf 100644 --- a/package.json +++ b/package.json @@ -11,14 +11,14 @@ "check:package": "pnpm -r run check:package", "duplicates": "jscpd --config node_modules/@perfectpan/lint-config/jscpd.json packages apps infra scripts tests --ignore '**/node_modules/**,**/dist/**,**/coverage/**,**/.vite/**,**/.source/**,**/.tanstack/**,**/routeTree.gen.ts,**/*.json,**/*.test.ts,**/*.test.tsx,**/test/support/**,**/test/fixtures/**' --format 'typescript,tsx'", "duplicates:audit": "jscpd --config node_modules/@perfectpan/lint-config/jscpd-audit.json packages apps infra scripts tests --absolute --output tmp/duplicates-audit --ignore '**/node_modules/**,**/dist/**,**/coverage/**,**/.vite/**,**/.source/**,**/.tanstack/**,**/routeTree.gen.ts,**/*.json' --format 'typescript,tsx'", - "format": "pnpm -r run format", - "format:check": "pnpm -r run format:check", + "format": "pnpm -r --no-sort run format", + "format:check": "pnpm -r --no-sort run format:check", "knip": "knip", "knip:production": "knip --production", - "lint": "pnpm -r run lint", + "lint": "pnpm -r --no-sort run lint", "size:update": "node scripts/update-size-budgets.ts", - "test": "pnpm -r run test", - "typecheck": "pnpm -r run typecheck", + "test": "pnpm -r --no-sort run test", + "typecheck": "pnpm -r --no-sort run typecheck", "version-packages": "changeset version" }, "engines": { diff --git a/packages/acp/test/connect-agent-lifecycle.test.ts b/packages/acp/test/connect-agent-lifecycle.test.ts new file mode 100644 index 00000000..9e0886f5 --- /dev/null +++ b/packages/acp/test/connect-agent-lifecycle.test.ts @@ -0,0 +1,472 @@ +import { existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +import { describe, expect, it } from "@effect/vitest"; +import type { TranscriptStreamPart } from "@rivus/agent-kit-sessions/public"; +import { NodePlatformLive } from "@rivus/agent-kit-platform-node/public/effect"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Stream from "effect/Stream"; +import { TestClock } from "effect/testing"; +import { afterEach } from "vite-plus/test"; + +import { probeAgent, SessionBindingStore } from "../src/public.js"; +import { + connectFake, + eventTexts, + eventually, + fakeProfile, + removeWorkDirs, + TestLive, + text, + workDir +} from "./support.js"; + +afterEach(() => { + removeWorkDirs(); +}); + +const run = (parts: Stream.Stream) => Stream.runCollect(parts); + +describe("starting and stopping the agent", () => { + it.effect("S87: a program that cannot start is AgentUnavailable", () => + Effect.gen(function* () { + const exit = yield* Effect.exit(connectFake({ profile: { command: "/no/such/acp-agent", args: [] } })); + expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ + value: { _tag: "AgentUnavailable", command: "/no/such/acp-agent" } + }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("S87: an agent that exits or speaks another protocol version fails the handshake", () => + Effect.gen(function* () { + const exited = yield* Effect.exit(connectFake({ fake: { FAKE_ACP_INITIALIZE: "exit" } })); + expect(Exit.isFailure(exited) && Exit.findErrorOption(exited)).toMatchObject({ + value: { _tag: "HandshakeFailed", reason: "exited" } + }); + const version = yield* Effect.exit(connectFake({ fake: { FAKE_ACP_INITIALIZE: "protocol-2" } })); + expect(Exit.isFailure(version) && Exit.findErrorOption(version)).toMatchObject({ + value: { _tag: "HandshakeFailed", reason: "protocol-version" } + }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("S87: the handshake deadline is the handshake timeout, on the Effect clock", () => + Effect.gen(function* () { + const connecting = yield* connectFake({ fake: { FAKE_ACP_INITIALIZE: "hang" }, handshakeTimeoutMs: 2_000 }).pipe( + Effect.exit, + Effect.forkChild + ); + yield* TestClock.adjust(1_999); + expect(connecting.pollUnsafe()).toBeUndefined(); + yield* TestClock.adjust(1); + const exit = yield* Fiber.join(connecting); + expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ + value: { _tag: "HandshakeFailed", reason: "timeout" } + }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("bounds session/new with the request timeout", () => + Effect.gen(function* () { + const connection = yield* connectFake({ fake: { FAKE_ACP_NEW: "hang" }, requestTimeoutMs: 1_000 }); + const opening = yield* connection.newSession().pipe(Effect.exit, Effect.forkChild); + yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 100))); + yield* TestClock.adjust(1_000); + const exit = yield* Fiber.join(opening); + expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ + value: { _tag: "AcpTimeout", method: "session/new", timeoutMs: 1_000 } + }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + const startTurn = (parts: Stream.Stream) => + Effect.gen(function* () { + const collected: TranscriptStreamPart[] = []; + const fiber = yield* Stream.runForEach( + Stream.tap(parts, (part) => Effect.sync(() => collected.push(part))), + () => Effect.void + ).pipe(Effect.exit, Effect.forkChild); + return { parts: collected, fiber }; + }); + + const said = (parts: readonly TranscriptStreamPart[], words: string) => () => + parts.some((part) => part.type === "text-delta" && part.delta.includes(words)); + + it.effect("refuses a session of a single-session agent while a turn runs elsewhere", () => + Effect.gen(function* () { + const connection = yield* connectFake({ profile: { sessions: "single" } }); + const busy = yield* connection.newSession(); + const turn = yield* startTurn(busy.prompt([text("hang")])); + yield* eventually(said(turn.parts, "working")); + const exit = yield* connection.newSession().pipe(Effect.exit); + expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ + value: { _tag: "TurnActive", agent: "fake-agent", sessionId: busy.sessionId } + }); + // Once the turn ends, a second session opens again. + yield* busy.cancel(); + expect(yield* Fiber.join(turn.fiber)).toEqual(Exit.void); + const second = yield* connection.newSession(); + expect(second.sessionId).not.toBe(busy.sessionId); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("keeps allowing a second session while a turn runs when sessions are multi", () => + Effect.gen(function* () { + const connection = yield* connectFake(); + const busy = yield* connection.newSession(); + const turn = yield* startTurn(busy.prompt([text("hang")])); + yield* eventually(said(turn.parts, "working")); + const second = yield* connection.newSession(); + expect(second.sessionId).not.toBe(busy.sessionId); + yield* busy.cancel(); + expect(yield* Fiber.join(turn.fiber)).toEqual(Exit.void); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("refuses a turn that starts while a session opens on a single-session agent", () => + Effect.gen(function* () { + const connection = yield* connectFake({ + profile: { sessions: "single" }, + fake: { FAKE_ACP_NEW: "hang-later" }, + requestTimeoutMs: 1_000 + }); + const first = yield* connection.newSession(); + // The second open hangs until its timeout; pi-acp would close the first session's subprocess mid-open. + const opening = yield* connection.newSession().pipe(Effect.exit, Effect.forkChild); + yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 100))); + const refused = yield* first.prompt([text("hang")]).pipe(Stream.runCollect, Effect.exit); + expect(Exit.isFailure(refused) && Exit.findErrorOption(refused)).toMatchObject({ + value: { _tag: "TurnActive", agent: "fake-agent" } + }); + yield* TestClock.adjust(1_000); + expect(Exit.isFailure(yield* Fiber.join(opening))).toBe(true); + // A timeout leaves the remote open unaccounted — pi-acp can still complete it and close the first session — + // so the connection itself ends instead of risking a stranded turn. + expect(yield* connection.ended).toMatchObject({ agent: "fake-agent", reason: "open-unsettled" }); + expect(Exit.isFailure(yield* first.prompt([text("next")]).pipe(Stream.runCollect, Effect.exit))).toBe(true); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("releases the open claim when the agent supports no load", () => + Effect.gen(function* () { + const connection = yield* connectFake({ profile: { sessions: "single" } }); + const session = yield* connection.newSession(); + const refused = yield* connection.loadSession({ sessionId: "fake-session-9" }).pipe(Effect.exit); + expect(Exit.isFailure(refused) && Exit.findErrorOption(refused)).toMatchObject({ + value: { _tag: "LoadUnsupported", agent: "fake-agent" } + }); + // The claim never leaked: turns still start. + expect(eventTexts(yield* Stream.runCollect(session.prompt([text("next")])))).toEqual(["turn 1: next"]); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("keeps the open claim while an interrupted load's request still runs", () => + Effect.gen(function* () { + const connection = yield* connectFake({ + profile: { sessions: "single" }, + fake: { FAKE_ACP_LOAD: "hang" }, + requestTimeoutMs: 1_000 + }); + const session = yield* connection.newSession(); + const loading = yield* connection.loadSession({ sessionId: "unknown-session" }).pipe(Effect.forkChild); + yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 100))); + yield* Fiber.interrupt(loading); + // The load request still runs in the connection's scope, so a turn refuses until the open settles. + const refused = yield* session.prompt([text("next")]).pipe(Stream.runCollect, Effect.exit); + expect(Exit.isFailure(refused) && Exit.findErrorOption(refused)).toMatchObject({ + value: { _tag: "TurnActive", agent: "fake-agent" } + }); + yield* TestClock.adjust(1_000); + expect(yield* connection.ended).toMatchObject({ reason: "open-unsettled" }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("ends the connection when an interrupted session open leaves the remote unaccounted", () => + Effect.gen(function* () { + const connection = yield* connectFake({ + profile: { sessions: "single" }, + fake: { FAKE_ACP_NEW: "hang" }, + requestTimeoutMs: 1_000 + }); + const opening = yield* connection.newSession().pipe(Effect.forkChild); + yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 100))); + yield* Fiber.interrupt(opening); + expect(yield* connection.ended).toMatchObject({ reason: "open-unsettled" }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); +}); + +describe("probeAgent", () => { + it.effect("reports ready, needs-login or unavailable from a trial session", () => + Effect.gen(function* () { + const probe = (options: { fake?: Record; command?: string }) => + probeAgent("fake-agent", { + cwd: workDir(), + env: { ...options.fake }, + providers: { + acp: { "fake-agent": fakeProfile(options.command === undefined ? {} : { command: options.command }) } + } + }); + expect(yield* probe({})).toMatchObject({ + status: "ready", + agentInfo: { name: "fake-agent", version: "1.2.3" }, + features: { image: true } + }); + expect(yield* probe({ fake: { FAKE_ACP_AUTH: "required" } })).toEqual({ + status: "needs-login", + agentInfo: { name: "fake-agent", version: "1.2.3" }, + authMethods: [{ id: "fake-login", name: "Fake login" }] + }); + expect(yield* probe({ command: "/no/such/acp-agent" })).toMatchObject({ + status: "unavailable", + error: { _tag: "AgentUnavailable" } + }); + }).pipe(Effect.provide(TestLive)) + ); +}); + +describe("client file calls", () => { + it.effect("S85: serve the session directory only, after links are resolved", () => + Effect.gen(function* () { + const base = workDir(); + const root = join(base, "root"); + const outside = join(base, "outside"); + mkdirSync(root); + mkdirSync(outside); + writeFileSync(join(root, "inside.txt"), "line 1\nline 2\nline 3"); + writeFileSync(join(outside, "secret.txt"), "nothing to see"); + writeFileSync(join(root, "..notes.md"), "an ordinary name"); + symlinkSync(join(outside, "secret.txt"), join(root, "escape.txt")); + symlinkSync(join(outside, "missing.txt"), join(root, "dangling.txt")); + symlinkSync(outside, join(root, "out-dir")); + mkdirSync(join(root, "sub")); + const connection = yield* connectFake({ cwd: root, fileSystem: { read: true, write: true } }); + const session = yield* connection.newSession(); + const say = (command: string) => + Effect.map(run(session.prompt([text(command)])), (parts) => eventTexts(parts)[0]); + const outsideOf = /^refused .*outside the session directory/; + // Windows resolves `..` lexically, before the links before it, so `out-dir/..` and `missing/..` are the session + // directory there, not the link target's parent or an unresolved directory. See `clientPathVerdict`. + const lexicalDotDot = process.platform === "win32"; + + expect(yield* say(`read ${root}/inside.txt`)).toBe("read line 1\nline 2\nline 3"); + expect(yield* say(`read ${root}/inside.txt 2 1`)).toBe("read line 2"); + expect(yield* say(`read ${root}/..notes.md`)).toBe("read an ordinary name"); + expect(yield* say(`read ${outside}/secret.txt`)).toMatch(outsideOf); + expect(yield* say(`read ${root}/escape.txt`)).toMatch(outsideOf); + expect(yield* say("read relative.txt")).toMatch(/^refused .*not an absolute path/); + expect(yield* say(`read ${root}/nothing.txt`)).toMatch(/^refused .*Resource not found/); + // `..` as sent, resolved the way the file system does: after the links before it, or lexically on Windows, + // where `out-dir/..` names a missing file inside the session directory. + expect(yield* say(`read ${root}/sub/../inside.txt`)).toBe("read line 1\nline 2\nline 3"); + expect(yield* say(`read ${root}/sub/../../outside/secret.txt`)).toMatch(outsideOf); + expect(yield* say(`read ${root}/out-dir/../outside/secret.txt`)).toMatch( + lexicalDotDot ? /^refused Resource not found/ : outsideOf + ); + expect(yield* say(`read ${root}/out-dir/../root/inside.txt`)).toMatch( + lexicalDotDot ? /^refused Resource not found/ : /^read line 1\nline 2\nline 3$/ + ); + + expect(yield* say(`write ${root}/sub/new.txt fresh text`)).toBe("wrote"); + expect(readFileSync(join(root, "sub", "new.txt"), "utf8")).toBe("fresh text"); + expect(yield* say(`write ${root}/escape.txt overwrite`)).toMatch(outsideOf); + expect(yield* say(`write ${root}/dangling.txt create`)).toMatch(/^refused .*link to a file that does not exist/); + expect(yield* say(`write ${root}/out-dir/new.txt create`)).toMatch(outsideOf); + // On Windows the next two target the session directory itself: its missing `outside` directory fails the first + // write with a plain error, which the agent gets as `Internal error`, and the second creates the file inside. + expect(yield* say(`write ${root}/out-dir/../outside/new.txt create`)).toMatch( + lexicalDotDot ? /^refused Internal error$/ : outsideOf + ); + expect(yield* say(`write ${root}/missing/../new.txt create`)).toMatch( + lexicalDotDot ? /^wrote$/ : /^refused .*directory that does not exist/ + ); + expect(readFileSync(join(outside, "secret.txt"), "utf8")).toBe("nothing to see"); + expect(existsSync(join(outside, "new.txt"))).toBe(false); + expect(existsSync(join(root, "new.txt"))).toBe(lexicalDotDot); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("are not offered unless asked for", () => + Effect.gen(function* () { + const root = workDir(); + writeFileSync(join(root, "inside.txt"), "text"); + const connection = yield* connectFake({ cwd: root }); + const session = yield* connection.newSession(); + const parts = yield* run(session.prompt([text(`read ${join(root, "inside.txt")}`)])); + expect(eventTexts(parts)[0]).toMatch(/^refused .*Method not found/); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); +}); + +describe("session bindings", () => { + it.effect("S86: a session bound to a key is loaded on a later connection, without its replay", () => + Effect.gen(function* () { + const state = join(workDir(), "agent-state.json"); + const fake = { FAKE_ACP_LOAD: "load", FAKE_ACP_STATE: state }; + const cwd = workDir(); + const sessionId = yield* Effect.scoped( + Effect.gen(function* () { + const connection = yield* connectFake({ fake, cwd }); + const session = yield* connection.newSession({ sessionKey: "chat:1" }); + yield* run(session.prompt([text("hello")])); + return session.sessionId; + }) + ); + const store = yield* SessionBindingStore; + expect(yield* store.get("chat:1")).toEqual({ sessionKey: "chat:1", agent: "fake-agent", sessionId, cwd }); + + const connection = yield* connectFake({ fake }); + const loaded = yield* connection.loadSession({ sessionKey: "chat:1" }); + expect(loaded.sessionId).toBe(sessionId); + const parts = yield* run(loaded.prompt([text("inspect")])); + expect(eventTexts(parts, "user")).toEqual([]); + expect(JSON.parse(eventTexts(parts)[0] ?? "{}").cwd).toBe(cwd); + expect(yield* connection.loadSession({ sessionKey: "chat:1" })).toMatchObject({ sessionId }); + + const missing = yield* Effect.exit(connection.loadSession({ sessionKey: "chat:2" })); + expect(Exit.isFailure(missing) && Exit.findErrorOption(missing)).toMatchObject({ + value: { _tag: "BindingNotFound", sessionKey: "chat:2" } + }); + const unknown = yield* Effect.exit(connection.loadSession({ sessionId: "never-created" })); + expect(Exit.isFailure(unknown) && Exit.findErrorOption(unknown)).toMatchObject({ + value: { _tag: "AcpRequestFailed", method: "session/load" } + }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("detach forgets an open session locally, so a reload sends session/load with new MCP servers", () => + Effect.gen(function* () { + const mcpA = [{ name: "tools-a", command: "/opt/a", args: [], env: [] }]; + const mcpB = [{ name: "tools-b", command: "/opt/b", args: [], env: [] }]; + const stderr: string[] = []; + const connection = yield* connectFake({ + fake: { FAKE_ACP_LOAD: "load" }, + mcpServers: mcpA, + onStderr: (text) => { + stderr.push(text); + } + }); + const session = yield* connection.newSession(); + const first = JSON.parse(eventTexts(yield* run(session.prompt([text("inspect")])))[0] ?? "{}"); + expect(first.mcpServers).toEqual(mcpA); + + yield* session.detach(); + expect((yield* session.snapshot).state).toBe("closed"); + // The agent kept the session and heard no session/close; the reload re-sent session/load, and the agent + // recorded the new MCP servers of that call. + const reloaded = yield* connection.loadSession({ sessionId: session.sessionId }, { mcpServers: mcpB }); + const report = JSON.parse(eventTexts(yield* run(reloaded.prompt([text("inspect")])))[0] ?? "{}"); + expect(report.mcpServers).toEqual(mcpB); + expect(report.loads).toBe(1); + expect(stderr.join("")).not.toContain(`closed ${session.sessionId}`); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("detach keeps the unsent first-block system prompt for the reload", () => + Effect.gen(function* () { + const connection = yield* connectFake({ + fake: { FAKE_ACP_LOAD: "load" }, + profile: { systemPrompt: { in: "first-block" } } + }); + const session = yield* connection.newSession({ systemPrompt: "be brief" }); + yield* session.detach(); + const reloaded = yield* connection.loadSession({ sessionId: session.sessionId }); + const report = JSON.parse(eventTexts(yield* run(reloaded.prompt([text("inspect")])))[0] ?? "{}"); + // The prompt the session never sent goes out with the reload's first prompt, as it would have originally. + expect(report.prompt).toEqual([ + { type: "text", text: "be brief\n\n" }, + { type: "text", text: "inspect" } + ]); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("sends one session/load for concurrent loads of a session, which share it", () => + Effect.gen(function* () { + const state = join(workDir(), "agent-state.json"); + const sessionId = yield* Effect.scoped( + Effect.flatMap(connectFake({ fake: { FAKE_ACP_STATE: state } }), (connection) => + Effect.map(connection.newSession(), (session) => session.sessionId) + ) + ); + const connection = yield* connectFake({ fake: { FAKE_ACP_LOAD: "load", FAKE_ACP_STATE: state } }); + const [first, second] = yield* Effect.all( + [connection.loadSession({ sessionId }), connection.loadSession({ sessionId })], + { concurrency: "unbounded" } + ); + const report = JSON.parse(eventTexts(yield* run(first.prompt([text("inspect")])))[0] ?? "{}"); + expect(report.loads).toBe(1); + expect((yield* second.snapshot).turns).toBe(1); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.live("fails a load during or after closing the connection with ConnectionClosed instead of waiting", () => + Effect.gen(function* () { + const state = join(workDir(), "agent-state.json"); + const sessionId = yield* Effect.scoped( + Effect.flatMap(connectFake({ fake: { FAKE_ACP_STATE: state } }), (connection) => + Effect.map(connection.newSession(), (session) => session.sessionId) + ) + ); + const load = (connection: Effect.Success>) => + connection.loadSession({ sessionId }).pipe(Effect.flip, Effect.timeoutOption(5_000)); + + // The agent ignores SIGTERM, so closing waits for the platform's SIGKILL while the loads run. + const closing = yield* connectFake({ + fake: { FAKE_ACP_LOAD: "load", FAKE_ACP_STATE: state, FAKE_ACP_IGNORE_SIGTERM: "1" } + }); + const close = yield* closing.close().pipe(Effect.forkChild); + yield* Effect.sleep(50); + expect(yield* load(closing)).toMatchObject({ value: { _tag: "ConnectionClosed", reason: "closed" } }); + expect(yield* load(closing)).toMatchObject({ value: { _tag: "ConnectionClosed" } }); + yield* Fiber.join(close); + expect(yield* load(closing)).toMatchObject({ value: { _tag: "ConnectionClosed" } }); + + const closed = yield* connectFake({ fake: { FAKE_ACP_LOAD: "load", FAKE_ACP_STATE: state } }); + yield* closed.close(); + expect(yield* load(closed)).toMatchObject({ value: { _tag: "ConnectionClosed", reason: "closed" } }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("binds a key to a session that is already open and returns a handle carrying it", () => + Effect.gen(function* () { + const connection = yield* connectFake({ fake: { FAKE_ACP_LOAD: "load" } }); + const opened = yield* connection.newSession(); + expect(opened.sessionKey).toBeUndefined(); + const keyed = yield* connection.loadSession({ sessionId: opened.sessionId, sessionKey: "chat:9" }); + expect(keyed.sessionKey).toBe("chat:9"); + expect(yield* (yield* SessionBindingStore).get("chat:9")).toMatchObject({ sessionId: opened.sessionId }); + expect((yield* connection.loadSession({ sessionKey: "chat:9" })).sessionKey).toBe("chat:9"); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("loads with session/resume when the agent only supports that, and refuses when it supports neither", () => + Effect.gen(function* () { + const state = join(workDir(), "agent-state.json"); + const sessionId = yield* Effect.scoped( + Effect.flatMap(connectFake({ fake: { FAKE_ACP_STATE: state } }), (connection) => + Effect.map(connection.newSession(), (session) => session.sessionId) + ) + ); + const resuming = yield* connectFake({ fake: { FAKE_ACP_LOAD: "resume", FAKE_ACP_STATE: state } }); + expect((yield* resuming.loadSession({ sessionId })).sessionId).toBe(sessionId); + const neither = yield* connectFake({ fake: { FAKE_ACP_STATE: state } }); + const refused = yield* Effect.exit(neither.loadSession({ sessionId })); + expect(Exit.isFailure(refused) && Exit.findErrorOption(refused)).toMatchObject({ + value: { _tag: "LoadUnsupported", sessionId } + }); + }).pipe(Effect.scoped, Effect.provide(TestLive)) + ); + + it.effect("refuses a session key without a binding store and opens the session without one", () => + Effect.gen(function* () { + const connection = yield* connectFake(); + const keyed = yield* Effect.exit(connection.newSession({ sessionKey: "chat:1" })); + expect(Exit.isFailure(keyed) && Exit.findErrorOption(keyed)).toMatchObject({ + value: { _tag: "SessionBindingStoreFailure", reason: "unavailable" } + }); + expect((yield* connection.newSession()).sessionId).toMatch(/^fake-session-/); + }).pipe(Effect.scoped, Effect.provide(NodePlatformLive)) + ); +}); diff --git a/packages/acp/test/connect-agent.test.ts b/packages/acp/test/connect-agent.test.ts index aa8d0c8d..68099ef7 100644 --- a/packages/acp/test/connect-agent.test.ts +++ b/packages/acp/test/connect-agent.test.ts @@ -1,30 +1,15 @@ -import { existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; - import { describe, expect, it } from "@effect/vitest"; import { isAgentKitError } from "@rivus/agent-kit-catalog/public"; import { foldStreamParts, type TranscriptStreamPart } from "@rivus/agent-kit-sessions/public"; -import { NodePlatformLive } from "@rivus/agent-kit-platform-node/public/effect"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Stream from "effect/Stream"; -import { TestClock } from "effect/testing"; import { afterEach } from "vite-plus/test"; -import { connectAgent, optionOfKind, probeAgent, type PromptBlock, SessionBindingStore } from "../src/public.js"; -import { - connectFake, - eventTexts, - eventually, - fakeProfile, - removeWorkDirs, - TestLive, - text, - untilState, - workDir -} from "./support.js"; +import { connectAgent, optionOfKind, type PromptBlock } from "../src/public.js"; +import { connectFake, eventTexts, removeWorkDirs, TestLive, text, untilState, workDir } from "./support.js"; afterEach(() => { removeWorkDirs(); @@ -560,445 +545,3 @@ describe("connectAgent", () => { }).pipe(Effect.scoped, Effect.provide(TestLive)) ); }); - -describe("starting and stopping the agent", () => { - it.effect("S87: a program that cannot start is AgentUnavailable", () => - Effect.gen(function* () { - const exit = yield* Effect.exit(connectFake({ profile: { command: "/no/such/acp-agent", args: [] } })); - expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ - value: { _tag: "AgentUnavailable", command: "/no/such/acp-agent" } - }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("S87: an agent that exits or speaks another protocol version fails the handshake", () => - Effect.gen(function* () { - const exited = yield* Effect.exit(connectFake({ fake: { FAKE_ACP_INITIALIZE: "exit" } })); - expect(Exit.isFailure(exited) && Exit.findErrorOption(exited)).toMatchObject({ - value: { _tag: "HandshakeFailed", reason: "exited" } - }); - const version = yield* Effect.exit(connectFake({ fake: { FAKE_ACP_INITIALIZE: "protocol-2" } })); - expect(Exit.isFailure(version) && Exit.findErrorOption(version)).toMatchObject({ - value: { _tag: "HandshakeFailed", reason: "protocol-version" } - }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("S87: the handshake deadline is the handshake timeout, on the Effect clock", () => - Effect.gen(function* () { - const connecting = yield* connectFake({ fake: { FAKE_ACP_INITIALIZE: "hang" }, handshakeTimeoutMs: 2_000 }).pipe( - Effect.exit, - Effect.forkChild - ); - yield* TestClock.adjust(1_999); - expect(connecting.pollUnsafe()).toBeUndefined(); - yield* TestClock.adjust(1); - const exit = yield* Fiber.join(connecting); - expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ - value: { _tag: "HandshakeFailed", reason: "timeout" } - }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("bounds session/new with the request timeout", () => - Effect.gen(function* () { - const connection = yield* connectFake({ fake: { FAKE_ACP_NEW: "hang" }, requestTimeoutMs: 1_000 }); - const opening = yield* connection.newSession().pipe(Effect.exit, Effect.forkChild); - yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 100))); - yield* TestClock.adjust(1_000); - const exit = yield* Fiber.join(opening); - expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ - value: { _tag: "AcpTimeout", method: "session/new", timeoutMs: 1_000 } - }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - const startTurn = (parts: Stream.Stream) => - Effect.gen(function* () { - const collected: TranscriptStreamPart[] = []; - const fiber = yield* Stream.runForEach( - Stream.tap(parts, (part) => Effect.sync(() => collected.push(part))), - () => Effect.void - ).pipe(Effect.exit, Effect.forkChild); - return { parts: collected, fiber }; - }); - - const said = (parts: readonly TranscriptStreamPart[], words: string) => () => - parts.some((part) => part.type === "text-delta" && part.delta.includes(words)); - - it.effect("refuses a session of a single-session agent while a turn runs elsewhere", () => - Effect.gen(function* () { - const connection = yield* connectFake({ profile: { sessions: "single" } }); - const busy = yield* connection.newSession(); - const turn = yield* startTurn(busy.prompt([text("hang")])); - yield* eventually(said(turn.parts, "working")); - const exit = yield* connection.newSession().pipe(Effect.exit); - expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ - value: { _tag: "TurnActive", agent: "fake-agent", sessionId: busy.sessionId } - }); - // Once the turn ends, a second session opens again. - yield* busy.cancel(); - expect(yield* Fiber.join(turn.fiber)).toEqual(Exit.void); - const second = yield* connection.newSession(); - expect(second.sessionId).not.toBe(busy.sessionId); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("keeps allowing a second session while a turn runs when sessions are multi", () => - Effect.gen(function* () { - const connection = yield* connectFake(); - const busy = yield* connection.newSession(); - const turn = yield* startTurn(busy.prompt([text("hang")])); - yield* eventually(said(turn.parts, "working")); - const second = yield* connection.newSession(); - expect(second.sessionId).not.toBe(busy.sessionId); - yield* busy.cancel(); - expect(yield* Fiber.join(turn.fiber)).toEqual(Exit.void); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("refuses a turn that starts while a session opens on a single-session agent", () => - Effect.gen(function* () { - const connection = yield* connectFake({ - profile: { sessions: "single" }, - fake: { FAKE_ACP_NEW: "hang-later" }, - requestTimeoutMs: 1_000 - }); - const first = yield* connection.newSession(); - // The second open hangs until its timeout; pi-acp would close the first session's subprocess mid-open. - const opening = yield* connection.newSession().pipe(Effect.exit, Effect.forkChild); - yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 100))); - const refused = yield* first.prompt([text("hang")]).pipe(Stream.runCollect, Effect.exit); - expect(Exit.isFailure(refused) && Exit.findErrorOption(refused)).toMatchObject({ - value: { _tag: "TurnActive", agent: "fake-agent" } - }); - yield* TestClock.adjust(1_000); - expect(Exit.isFailure(yield* Fiber.join(opening))).toBe(true); - // A timeout leaves the remote open unaccounted — pi-acp can still complete it and close the first session — - // so the connection itself ends instead of risking a stranded turn. - expect(yield* connection.ended).toMatchObject({ agent: "fake-agent", reason: "open-unsettled" }); - expect(Exit.isFailure(yield* first.prompt([text("next")]).pipe(Stream.runCollect, Effect.exit))).toBe(true); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("releases the open claim when the agent supports no load", () => - Effect.gen(function* () { - const connection = yield* connectFake({ profile: { sessions: "single" } }); - const session = yield* connection.newSession(); - const refused = yield* connection.loadSession({ sessionId: "fake-session-9" }).pipe(Effect.exit); - expect(Exit.isFailure(refused) && Exit.findErrorOption(refused)).toMatchObject({ - value: { _tag: "LoadUnsupported", agent: "fake-agent" } - }); - // The claim never leaked: turns still start. - expect(eventTexts(yield* Stream.runCollect(session.prompt([text("next")])))).toEqual(["turn 1: next"]); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("keeps the open claim while an interrupted load's request still runs", () => - Effect.gen(function* () { - const connection = yield* connectFake({ - profile: { sessions: "single" }, - fake: { FAKE_ACP_LOAD: "hang" }, - requestTimeoutMs: 1_000 - }); - const session = yield* connection.newSession(); - const loading = yield* connection.loadSession({ sessionId: "unknown-session" }).pipe(Effect.forkChild); - yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 100))); - yield* Fiber.interrupt(loading); - // The load request still runs in the connection's scope, so a turn refuses until the open settles. - const refused = yield* session.prompt([text("next")]).pipe(Stream.runCollect, Effect.exit); - expect(Exit.isFailure(refused) && Exit.findErrorOption(refused)).toMatchObject({ - value: { _tag: "TurnActive", agent: "fake-agent" } - }); - yield* TestClock.adjust(1_000); - expect(yield* connection.ended).toMatchObject({ reason: "open-unsettled" }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("ends the connection when an interrupted session open leaves the remote unaccounted", () => - Effect.gen(function* () { - const connection = yield* connectFake({ - profile: { sessions: "single" }, - fake: { FAKE_ACP_NEW: "hang" }, - requestTimeoutMs: 1_000 - }); - const opening = yield* connection.newSession().pipe(Effect.forkChild); - yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 100))); - yield* Fiber.interrupt(opening); - expect(yield* connection.ended).toMatchObject({ reason: "open-unsettled" }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); -}); - -describe("probeAgent", () => { - it.effect("reports ready, needs-login or unavailable from a trial session", () => - Effect.gen(function* () { - const probe = (options: { fake?: Record; command?: string }) => - probeAgent("fake-agent", { - cwd: workDir(), - env: { ...options.fake }, - providers: { - acp: { "fake-agent": fakeProfile(options.command === undefined ? {} : { command: options.command }) } - } - }); - expect(yield* probe({})).toMatchObject({ - status: "ready", - agentInfo: { name: "fake-agent", version: "1.2.3" }, - features: { image: true } - }); - expect(yield* probe({ fake: { FAKE_ACP_AUTH: "required" } })).toEqual({ - status: "needs-login", - agentInfo: { name: "fake-agent", version: "1.2.3" }, - authMethods: [{ id: "fake-login", name: "Fake login" }] - }); - expect(yield* probe({ command: "/no/such/acp-agent" })).toMatchObject({ - status: "unavailable", - error: { _tag: "AgentUnavailable" } - }); - }).pipe(Effect.provide(TestLive)) - ); -}); - -describe("client file calls", () => { - it.effect("S85: serve the session directory only, after links are resolved", () => - Effect.gen(function* () { - const base = workDir(); - const root = join(base, "root"); - const outside = join(base, "outside"); - mkdirSync(root); - mkdirSync(outside); - writeFileSync(join(root, "inside.txt"), "line 1\nline 2\nline 3"); - writeFileSync(join(outside, "secret.txt"), "nothing to see"); - writeFileSync(join(root, "..notes.md"), "an ordinary name"); - symlinkSync(join(outside, "secret.txt"), join(root, "escape.txt")); - symlinkSync(join(outside, "missing.txt"), join(root, "dangling.txt")); - symlinkSync(outside, join(root, "out-dir")); - mkdirSync(join(root, "sub")); - const connection = yield* connectFake({ cwd: root, fileSystem: { read: true, write: true } }); - const session = yield* connection.newSession(); - const say = (command: string) => - Effect.map(run(session.prompt([text(command)])), (parts) => eventTexts(parts)[0]); - const outsideOf = /^refused .*outside the session directory/; - // Windows resolves `..` lexically, before the links before it, so `out-dir/..` and `missing/..` are the session - // directory there, not the link target's parent or an unresolved directory. See `clientPathVerdict`. - const lexicalDotDot = process.platform === "win32"; - - expect(yield* say(`read ${root}/inside.txt`)).toBe("read line 1\nline 2\nline 3"); - expect(yield* say(`read ${root}/inside.txt 2 1`)).toBe("read line 2"); - expect(yield* say(`read ${root}/..notes.md`)).toBe("read an ordinary name"); - expect(yield* say(`read ${outside}/secret.txt`)).toMatch(outsideOf); - expect(yield* say(`read ${root}/escape.txt`)).toMatch(outsideOf); - expect(yield* say("read relative.txt")).toMatch(/^refused .*not an absolute path/); - expect(yield* say(`read ${root}/nothing.txt`)).toMatch(/^refused .*Resource not found/); - // `..` as sent, resolved the way the file system does: after the links before it, or lexically on Windows, - // where `out-dir/..` names a missing file inside the session directory. - expect(yield* say(`read ${root}/sub/../inside.txt`)).toBe("read line 1\nline 2\nline 3"); - expect(yield* say(`read ${root}/sub/../../outside/secret.txt`)).toMatch(outsideOf); - expect(yield* say(`read ${root}/out-dir/../outside/secret.txt`)).toMatch( - lexicalDotDot ? /^refused Resource not found/ : outsideOf - ); - expect(yield* say(`read ${root}/out-dir/../root/inside.txt`)).toMatch( - lexicalDotDot ? /^refused Resource not found/ : /^read line 1\nline 2\nline 3$/ - ); - - expect(yield* say(`write ${root}/sub/new.txt fresh text`)).toBe("wrote"); - expect(readFileSync(join(root, "sub", "new.txt"), "utf8")).toBe("fresh text"); - expect(yield* say(`write ${root}/escape.txt overwrite`)).toMatch(outsideOf); - expect(yield* say(`write ${root}/dangling.txt create`)).toMatch(/^refused .*link to a file that does not exist/); - expect(yield* say(`write ${root}/out-dir/new.txt create`)).toMatch(outsideOf); - // On Windows the next two target the session directory itself: its missing `outside` directory fails the first - // write with a plain error, which the agent gets as `Internal error`, and the second creates the file inside. - expect(yield* say(`write ${root}/out-dir/../outside/new.txt create`)).toMatch( - lexicalDotDot ? /^refused Internal error$/ : outsideOf - ); - expect(yield* say(`write ${root}/missing/../new.txt create`)).toMatch( - lexicalDotDot ? /^wrote$/ : /^refused .*directory that does not exist/ - ); - expect(readFileSync(join(outside, "secret.txt"), "utf8")).toBe("nothing to see"); - expect(existsSync(join(outside, "new.txt"))).toBe(false); - expect(existsSync(join(root, "new.txt"))).toBe(lexicalDotDot); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("are not offered unless asked for", () => - Effect.gen(function* () { - const root = workDir(); - writeFileSync(join(root, "inside.txt"), "text"); - const connection = yield* connectFake({ cwd: root }); - const session = yield* connection.newSession(); - const parts = yield* run(session.prompt([text(`read ${join(root, "inside.txt")}`)])); - expect(eventTexts(parts)[0]).toMatch(/^refused .*Method not found/); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); -}); - -describe("session bindings", () => { - it.effect("S86: a session bound to a key is loaded on a later connection, without its replay", () => - Effect.gen(function* () { - const state = join(workDir(), "agent-state.json"); - const fake = { FAKE_ACP_LOAD: "load", FAKE_ACP_STATE: state }; - const cwd = workDir(); - const sessionId = yield* Effect.scoped( - Effect.gen(function* () { - const connection = yield* connectFake({ fake, cwd }); - const session = yield* connection.newSession({ sessionKey: "chat:1" }); - yield* run(session.prompt([text("hello")])); - return session.sessionId; - }) - ); - const store = yield* SessionBindingStore; - expect(yield* store.get("chat:1")).toEqual({ sessionKey: "chat:1", agent: "fake-agent", sessionId, cwd }); - - const connection = yield* connectFake({ fake }); - const loaded = yield* connection.loadSession({ sessionKey: "chat:1" }); - expect(loaded.sessionId).toBe(sessionId); - const parts = yield* run(loaded.prompt([text("inspect")])); - expect(eventTexts(parts, "user")).toEqual([]); - expect(JSON.parse(eventTexts(parts)[0] ?? "{}").cwd).toBe(cwd); - expect(yield* connection.loadSession({ sessionKey: "chat:1" })).toMatchObject({ sessionId }); - - const missing = yield* Effect.exit(connection.loadSession({ sessionKey: "chat:2" })); - expect(Exit.isFailure(missing) && Exit.findErrorOption(missing)).toMatchObject({ - value: { _tag: "BindingNotFound", sessionKey: "chat:2" } - }); - const unknown = yield* Effect.exit(connection.loadSession({ sessionId: "never-created" })); - expect(Exit.isFailure(unknown) && Exit.findErrorOption(unknown)).toMatchObject({ - value: { _tag: "AcpRequestFailed", method: "session/load" } - }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("detach forgets an open session locally, so a reload sends session/load with new MCP servers", () => - Effect.gen(function* () { - const mcpA = [{ name: "tools-a", command: "/opt/a", args: [], env: [] }]; - const mcpB = [{ name: "tools-b", command: "/opt/b", args: [], env: [] }]; - const stderr: string[] = []; - const connection = yield* connectFake({ - fake: { FAKE_ACP_LOAD: "load" }, - mcpServers: mcpA, - onStderr: (text) => { - stderr.push(text); - } - }); - const session = yield* connection.newSession(); - const first = JSON.parse(eventTexts(yield* run(session.prompt([text("inspect")])))[0] ?? "{}"); - expect(first.mcpServers).toEqual(mcpA); - - yield* session.detach(); - expect((yield* session.snapshot).state).toBe("closed"); - // The agent kept the session and heard no session/close; the reload re-sent session/load, and the agent - // recorded the new MCP servers of that call. - const reloaded = yield* connection.loadSession({ sessionId: session.sessionId }, { mcpServers: mcpB }); - const report = JSON.parse(eventTexts(yield* run(reloaded.prompt([text("inspect")])))[0] ?? "{}"); - expect(report.mcpServers).toEqual(mcpB); - expect(report.loads).toBe(1); - expect(stderr.join("")).not.toContain(`closed ${session.sessionId}`); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("detach keeps the unsent first-block system prompt for the reload", () => - Effect.gen(function* () { - const connection = yield* connectFake({ - fake: { FAKE_ACP_LOAD: "load" }, - profile: { systemPrompt: { in: "first-block" } } - }); - const session = yield* connection.newSession({ systemPrompt: "be brief" }); - yield* session.detach(); - const reloaded = yield* connection.loadSession({ sessionId: session.sessionId }); - const report = JSON.parse(eventTexts(yield* run(reloaded.prompt([text("inspect")])))[0] ?? "{}"); - // The prompt the session never sent goes out with the reload's first prompt, as it would have originally. - expect(report.prompt).toEqual([ - { type: "text", text: "be brief\n\n" }, - { type: "text", text: "inspect" } - ]); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("sends one session/load for concurrent loads of a session, which share it", () => - Effect.gen(function* () { - const state = join(workDir(), "agent-state.json"); - const sessionId = yield* Effect.scoped( - Effect.flatMap(connectFake({ fake: { FAKE_ACP_STATE: state } }), (connection) => - Effect.map(connection.newSession(), (session) => session.sessionId) - ) - ); - const connection = yield* connectFake({ fake: { FAKE_ACP_LOAD: "load", FAKE_ACP_STATE: state } }); - const [first, second] = yield* Effect.all( - [connection.loadSession({ sessionId }), connection.loadSession({ sessionId })], - { concurrency: "unbounded" } - ); - const report = JSON.parse(eventTexts(yield* run(first.prompt([text("inspect")])))[0] ?? "{}"); - expect(report.loads).toBe(1); - expect((yield* second.snapshot).turns).toBe(1); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.live("fails a load during or after closing the connection with ConnectionClosed instead of waiting", () => - Effect.gen(function* () { - const state = join(workDir(), "agent-state.json"); - const sessionId = yield* Effect.scoped( - Effect.flatMap(connectFake({ fake: { FAKE_ACP_STATE: state } }), (connection) => - Effect.map(connection.newSession(), (session) => session.sessionId) - ) - ); - const load = (connection: Effect.Success>) => - connection.loadSession({ sessionId }).pipe(Effect.flip, Effect.timeoutOption(5_000)); - - // The agent ignores SIGTERM, so closing waits for the platform's SIGKILL while the loads run. - const closing = yield* connectFake({ - fake: { FAKE_ACP_LOAD: "load", FAKE_ACP_STATE: state, FAKE_ACP_IGNORE_SIGTERM: "1" } - }); - const close = yield* closing.close().pipe(Effect.forkChild); - yield* Effect.sleep(50); - expect(yield* load(closing)).toMatchObject({ value: { _tag: "ConnectionClosed", reason: "closed" } }); - expect(yield* load(closing)).toMatchObject({ value: { _tag: "ConnectionClosed" } }); - yield* Fiber.join(close); - expect(yield* load(closing)).toMatchObject({ value: { _tag: "ConnectionClosed" } }); - - const closed = yield* connectFake({ fake: { FAKE_ACP_LOAD: "load", FAKE_ACP_STATE: state } }); - yield* closed.close(); - expect(yield* load(closed)).toMatchObject({ value: { _tag: "ConnectionClosed", reason: "closed" } }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("binds a key to a session that is already open and returns a handle carrying it", () => - Effect.gen(function* () { - const connection = yield* connectFake({ fake: { FAKE_ACP_LOAD: "load" } }); - const opened = yield* connection.newSession(); - expect(opened.sessionKey).toBeUndefined(); - const keyed = yield* connection.loadSession({ sessionId: opened.sessionId, sessionKey: "chat:9" }); - expect(keyed.sessionKey).toBe("chat:9"); - expect(yield* (yield* SessionBindingStore).get("chat:9")).toMatchObject({ sessionId: opened.sessionId }); - expect((yield* connection.loadSession({ sessionKey: "chat:9" })).sessionKey).toBe("chat:9"); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("loads with session/resume when the agent only supports that, and refuses when it supports neither", () => - Effect.gen(function* () { - const state = join(workDir(), "agent-state.json"); - const sessionId = yield* Effect.scoped( - Effect.flatMap(connectFake({ fake: { FAKE_ACP_STATE: state } }), (connection) => - Effect.map(connection.newSession(), (session) => session.sessionId) - ) - ); - const resuming = yield* connectFake({ fake: { FAKE_ACP_LOAD: "resume", FAKE_ACP_STATE: state } }); - expect((yield* resuming.loadSession({ sessionId })).sessionId).toBe(sessionId); - const neither = yield* connectFake({ fake: { FAKE_ACP_STATE: state } }); - const refused = yield* Effect.exit(neither.loadSession({ sessionId })); - expect(Exit.isFailure(refused) && Exit.findErrorOption(refused)).toMatchObject({ - value: { _tag: "LoadUnsupported", sessionId } - }); - }).pipe(Effect.scoped, Effect.provide(TestLive)) - ); - - it.effect("refuses a session key without a binding store and opens the session without one", () => - Effect.gen(function* () { - const connection = yield* connectFake(); - const keyed = yield* Effect.exit(connection.newSession({ sessionKey: "chat:1" })); - expect(Exit.isFailure(keyed) && Exit.findErrorOption(keyed)).toMatchObject({ - value: { _tag: "SessionBindingStoreFailure", reason: "unavailable" } - }); - expect((yield* connection.newSession()).sessionId).toMatch(/^fake-session-/); - }).pipe(Effect.scoped, Effect.provide(NodePlatformLive)) - ); -}); diff --git a/packages/harness/test/support/uninstall-created-config.ts b/packages/harness/test/support/uninstall-created-config.ts new file mode 100644 index 00000000..c1258a72 --- /dev/null +++ b/packages/harness/test/support/uninstall-created-config.ts @@ -0,0 +1,890 @@ +import { builtinInstallAdapters as testInstall } from "./providers.js"; +import { builtinHookDialects as testHooks } from "./providers.js"; +import { execFileSync } from "node:child_process"; +import { chmodSync, statSync } from "node:fs"; +import { normalize } from "node:path"; + +import { parse as parseToml } from "@decimalturn/toml-patch"; +import { afterEach, describe, expect, it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; + +import { ArtifactFiles, LedgerRepository } from "../../src/application/ports.js"; +import { applyInstall } from "../../src/application/use-cases/apply-install.js"; +import { inventory } from "../../src/application/use-cases/inventory.js"; +import { planInstall, type PlanInstallOptions } from "../../src/application/use-cases/plan-install.js"; +import { uninstall } from "../../src/application/use-cases/uninstall.js"; +import { verify } from "../../src/application/use-cases/verify.js"; +import type { BundleSnapshot } from "../../src/domain/bundle/value-objects/bundle.js"; +import { parseJsonc } from "../../src/infra/adapters/jsonc-editor.js"; +import { demoBundle } from "./bundles.js"; +import { removeTestHomes, type TestHome, testHome } from "./home.js"; + +afterEach(removeTestHomes); + +/** Everyone's SID, which `icacls` takes instead of a localized account name. */ +const EVERYONE = "*S-1-1-0"; +/** The code of a denied read: `EACCES` from a mode; on Windows `EPERM`, to which libuv maps `ERROR_ACCESS_DENIED`. */ +const DENIED_READ = process.platform === "win32" ? "EPERM" : "EACCES"; + +/** + * Makes `path` unreadable to this process: by its mode where modes restrict reads, and on Windows, where they do not, + * by an ACL that denies everyone read access. + */ +function denyRead(path: string): void { + if (process.platform === "win32") { + execFileSync("icacls", [normalize(path), "/deny", `${EVERYONE}:(R)`], { stdio: "ignore" }); + return; + } + chmodSync(path, 0o000); +} + +/** Undoes `denyRead`. */ +function allowRead(path: string, mode: number): void { + if (process.platform === "win32") { + execFileSync("icacls", [normalize(path), "/remove:d", EVERYONE], { stdio: "ignore" }); + return; + } + chmodSync(path, mode); +} + +const EVENTS = ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"]; +const LEDGER_PATH = ".local/state/agent-kit/harness/user/ledger.json"; + +interface ConfigCase { + readonly agent: "codex" | "claude-code"; + readonly path: string; + readonly strategies?: PlanInstallOptions["strategies"]; + readonly emptySeeds: readonly string[]; + readonly userSeed: string; + readonly additions: readonly { readonly name: string; readonly before?: string; readonly after?: string }[]; +} + +const cases: readonly ConfigCase[] = [ + { + agent: "codex", + path: ".codex/config.toml", + emptySeeds: ["", " \n\t\n"], + userSeed: 'model = "custom"\n\n[user]\n', + additions: [ + { name: "data", before: 'model = "custom"\n' }, + { name: "a comment", before: "# User notes survive uninstall.\n" }, + { name: "an empty table", after: "\n[user]\n" }, + { name: "an empty inline table", before: "user = {}\n" } + ] + }, + { + agent: "claude-code", + path: ".claude/settings.json", + strategies: { "claude-code": { hooks: "shared-config" } }, + emptySeeds: ["", " \n\t\n", "{}\n"], + userSeed: '{"theme":"dark","user":{}}\n', + additions: [ + { name: "data", before: '"theme":"dark",' }, + { name: "a comment", before: "// User notes survive uninstall.\n" }, + { name: "an empty object", before: '"user":{},' }, + { name: "an empty array", before: '"user":[],' } + ] + } +]; + +function isolatedLayer(home: TestHome, platform = home.platform) { + return home.layer({ + ...platform, + clock: { now: () => 0, monotonic: () => 0 }, + process: { + run: () => Promise.reject(new Error("Unexpected external command")), + spawn: () => { + throw new Error("Unexpected external command"); + }, + self: { host: "test", bootId: "test", pid: 1, startTime: 0 }, + identify: () => undefined + } + }); +} + +function hooksBundle( + testCase: ConfigCase, + owner = "demo-app", + events: readonly string[] = EVENTS, + timeoutSeconds = 5 +): BundleSnapshot { + return demoBundle("1.0.0", { + owner, + legacyMarkers: [], + artifacts: [ + { + type: "hooks", + command: `/opt/${owner}/bin/hook --agent {agent}`, + timeoutSeconds, + events: { [testCase.agent]: events } + } + ] + }); +} + +function install(testCase: ConfigCase, bundle = hooksBundle(testCase)) { + return Effect.gen(function* () { + const plan = yield* planInstall(bundle, { + agents: [testCase.agent], + ...(testCase.strategies === undefined ? {} : { strategies: testCase.strategies }), + providers: { install: testInstall, hooks: testHooks } + }); + expect(plan.commands).toEqual([]); + yield* applyInstall(plan); + }); +} + +export function registerUninstallCreatedConfigCases(agent: ConfigCase["agent"]): void { + const testCase = cases.find((candidate) => candidate.agent === agent); + if (testCase === undefined) { + throw new Error(`Unknown uninstall config case: ${agent}`); + } + describe(`uninstall of configuration files created by install (${agent})`, () => { + it.effect(`${testCase.agent}: deletes the created file after removing all four hook groups without a CLI`, () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase); + const entries = (yield* inventory()).entries.filter((entry) => entry.locator.path === home.path(testCase.path)); + expect(entries).toHaveLength(4); + expect(home.read(testCase.path)).toContain("/opt/demo-app/bin/hook"); + + const removed = yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(removed.kept).toEqual([]); + expect(home.read(testCase.path)).toBeUndefined(); + expect((yield* inventory()).entries).toEqual([]); + expect( + (yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + })).steps + ).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + + for (const [index, seed] of testCase.emptySeeds.entries()) { + it.effect(`${testCase.agent}: retains an empty file when cleanup targets an absent hook (${index})`, () => { + const home = testHome(); + home.write(testCase.path, seed); + return Effect.gen(function* () { + yield* (yield* ArtifactFiles).remove( + { + kind: testCase.agent === "codex" ? "toml-entry" : "json-entry", + path: home.path(testCase.path), + pointer: "/hooks/Stop", + member: `/opt/demo-app/bin/hook --agent ${testCase.agent}`, + memberIn: "hook-group" + }, + { removeEmptyFile: true } + ); + expect(home.read(testCase.path)).toBe(seed); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + + it.effect(`${testCase.agent}: retains a pre-existing empty configuration file (${index})`, () => { + const home = testHome(); + home.write(testCase.path, seed); + return Effect.gen(function* () { + yield* install(testCase); + expect((yield* inventory()).entries.every((entry) => entry.preImage.existed === false)).toBe(true); + yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeDefined(); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + } + + it.effect(`${testCase.agent}: retains a pre-existing configuration file with other data`, () => { + const home = testHome(); + home.write(testCase.path, testCase.userSeed); + return Effect.gen(function* () { + yield* install(testCase); + yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); + const remaining = home.read(testCase.path); + expect(remaining).toBeDefined(); + if (testCase.agent === "codex") { + expect(parseToml(remaining ?? "")).toEqual(parseToml(testCase.userSeed)); + } else { + expect(JSON.parse(remaining ?? "null")).toEqual(JSON.parse(testCase.userSeed)); + } + }).pipe(Effect.provide(isolatedLayer(home))); + }); + + for (const addition of testCase.additions) { + it.effect(`${testCase.agent}: retains a created file after the user adds ${addition.name}`, () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase); + const installed = home.read(testCase.path) ?? ""; + const before = addition.before ?? ""; + const edited = + testCase.agent === "claude-code" && before.startsWith('"') + ? installed.replace("{", `{${before}`) + : `${before}${installed}${addition.after ?? ""}`; + home.write(testCase.path, edited); + + const removed = yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(removed.kept).toEqual([]); + const remaining = home.read(testCase.path); + expect(remaining).toBeDefined(); + if (testCase.agent === "claude-code" && before.startsWith('"')) { + expect(JSON.parse(remaining ?? "null")).toEqual(JSON.parse(`{${before.replace(/,$/, "")}}`)); + } else { + expect(remaining).toContain((addition.before ?? addition.after ?? "").trim()); + } + expect(remaining).not.toContain("/opt/demo-app/bin/hook"); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + } + + for (const firstRemoved of ["first-app", "second-app"]) { + it.effect( + `${testCase.agent}: retains the created file until the last owner leaves (${firstRemoved} first)`, + () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "first-app")); + yield* install(testCase, hooksBundle(testCase, "second-app")); + const lastRemoved = firstRemoved === "first-app" ? "second-app" : "first-app"; + + yield* uninstall(firstRemoved, { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toContain(`/opt/${lastRemoved}/bin/hook`); + expect(home.read(testCase.path)).not.toContain(`/opt/${firstRemoved}/bin/hook`); + yield* uninstall(lastRemoved, { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeUndefined(); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + } + ); + } + + it.effect(`${testCase.agent}: retains file provenance through a no-op reinstall and an added hook event`, () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); + yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); + yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop", "SessionStart"])); + yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); + expect(home.read(testCase.path)).toBeUndefined(); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + + it.effect(`${testCase.agent}: inherits file provenance while another proven hook still matches`, () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "first-app")); + const installed = home.read(testCase.path) ?? ""; + const edited = installed.replace(/\b5\b/, "9"); + expect(edited).not.toBe(installed); + home.write(testCase.path, edited); + + yield* install(testCase, hooksBundle(testCase, "second-app")); + const inherited = (yield* inventory()).entries.filter((entry) => entry.owners.includes("second-app")); + expect(inherited).toHaveLength(4); + expect(inherited.every((entry) => entry.createdConfigFile === true)).toBe(true); + yield* uninstall("second-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect( + (yield* uninstall("first-app", { + providers: { install: testInstall, hooks: testHooks } + })).kept + ).toHaveLength(1); + expect(home.read(testCase.path)).toContain("/opt/first-app/bin/hook"); + expect(home.read(testCase.path)).not.toContain("/opt/second-app/bin/hook"); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + + for (const malformedEvent of ["SessionStart", "Stop"]) { + for (const stage of ["fresh install", "direct uninstall"]) { + it.effect( + `${testCase.agent}: tolerates another owner's malformed ${malformedEvent} hook during ${stage}`, + () => { + const home = testHome(); + const goodEvent = malformedEvent === "SessionStart" ? "Stop" : "SessionStart"; + return Effect.gen(function* () { + if (stage === "fresh install") { + yield* install(testCase, hooksBundle(testCase, "other-app", ["SessionStart", "Stop"])); + } else { + const otherBundle = hooksBundle(testCase, "other-app", [malformedEvent]); + const ourBundle = hooksBundle(testCase, "demo-app", [goodEvent]); + if (malformedEvent === "SessionStart") { + yield* install(testCase, otherBundle); + yield* install(testCase, ourBundle); + } else { + yield* install(testCase, ourBundle); + yield* install(testCase, otherBundle); + } + } + const pointers = (yield* inventory()).entries.map((entry) => entry.locator.pointer); + expect(pointers.indexOf(`/hooks/${malformedEvent}`) < pointers.indexOf(`/hooks/${goodEvent}`)).toBe( + malformedEvent === "SessionStart" + ); + const goodOwner = stage === "fresh install" ? "other-app" : "demo-app"; + const command = `/opt/${goodOwner}/bin/hook --agent ${testCase.agent}`; + home.write( + testCase.path, + testCase.agent === "codex" + ? `hooks.${malformedEvent} = { user = true }\n\n[[hooks.${goodEvent}]]\n[[hooks.${goodEvent}.hooks]]\ntype = "command"\ncommand = "${command}"\ntimeout = 5\n` + : `${JSON.stringify( + { + hooks: { + [malformedEvent]: { user: true }, + [goodEvent]: [{ hooks: [{ type: "command", command, timeout: 5 }] }] + } + }, + null, + 2 + )}\n` + ); + + if (stage === "fresh install") { + yield* install(testCase, hooksBundle(testCase, "demo-app", [goodEvent])); + } + expect( + (yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + })).kept + ).toEqual([]); + const remaining = home.read(testCase.path); + expect(remaining).toBeDefined(); + if (testCase.agent === "codex") { + expect(parseToml(remaining ?? "")).toMatchObject({ hooks: { [malformedEvent]: { user: true } } }); + } else { + const parsed = parseJsonc(remaining ?? ""); + expect(parsed.ok).toBe(true); + expect(parsed.ok ? parsed.value : undefined).toMatchObject({ + hooks: { [malformedEvent]: { user: true } } + }); + } + expect(remaining).not.toContain("/opt/demo-app/bin/hook"); + expect((yield* inventory()).entries.every((entry) => !entry.owners.includes("demo-app"))).toBe(true); + }).pipe(Effect.provide(isolatedLayer(home))); + } + ); + } + } + + it.effect(`${testCase.agent}: revokes file provenance when the only other owner's hook is malformed`, () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "other-app", ["Stop"])); + home.write( + testCase.path, + testCase.agent === "codex" + ? "hooks.Stop = { user = true }\n" + : `${JSON.stringify({ hooks: { Stop: { user: true } } }, null, 2)}\n` + ); + + yield* install(testCase, hooksBundle(testCase, "demo-app", ["SessionStart"])); + const entries = (yield* inventory()).entries; + expect(entries).toHaveLength(2); + expect(entries.every((entry) => entry.createdConfigFile !== true)).toBe(true); + yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); + const remaining = home.read(testCase.path); + expect(remaining).toBeDefined(); + expect(remaining).not.toContain("/opt/demo-app/bin/hook"); + if (testCase.agent === "codex") { + expect(parseToml(remaining ?? "")).toEqual({ hooks: { Stop: { user: true } } }); + } else { + const parsed = parseJsonc(remaining ?? ""); + expect(parsed.ok).toBe(true); + expect(parsed.ok ? parsed.value : undefined).toEqual({ hooks: { Stop: { user: true } } }); + } + }).pipe(Effect.provide(isolatedLayer(home))); + }); + + it.effect(`${testCase.agent}: deletes the new file after reinstall recreates a removed configuration file`, () => { + const home = testHome(); + return Effect.gen(function* () { + const bundle = hooksBundle(testCase, "demo-app", ["Stop"]); + yield* install(testCase, bundle); + yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); + yield* install(testCase, bundle); + const reinstalled = (yield* inventory()).entries; + expect(home.read(testCase.path)).toContain("/opt/demo-app/bin/hook"); + yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); + expect(home.read(testCase.path)).toBeUndefined(); + expect(reinstalled.every((entry) => entry.createdConfigFile === true)).toBe(true); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + + if (testCase.agent === "claude-code") { + it.effect("propagates defects from the optional file-provenance observation", () => { + const home = testHome(); + const base = isolatedLayer(home); + const defectiveRead = Layer.effect( + ArtifactFiles, + Effect.gen(function* () { + const files = yield* ArtifactFiles; + return { + ...files, + read: (locator) => + locator.member?.includes("/opt/other-app/") === true + ? Effect.die("proof observation defect") + : files.read(locator) + } satisfies typeof files; + }) + ).pipe(Layer.provide(base)); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "other-app", ["Stop"])); + const before = home.read(testCase.path); + const plan = yield* planInstall(hooksBundle(testCase, "demo-app", ["SessionStart"]), { + agents: [testCase.agent], + strategies: testCase.strategies, + providers: { install: testInstall, hooks: testHooks } + }); + const result = yield* Effect.exit(applyInstall(plan).pipe(Effect.provide(Layer.merge(base, defectiveRead)))); + expect(Exit.isFailure(result) && Cause.hasDies(result.cause)).toBe(true); + expect(home.read(testCase.path)).toBe(before); + }).pipe(Effect.provide(base)); + }); + + it.effect("propagates an own-target malformed-hook read failure", () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); + const changed = `${JSON.stringify({ hooks: { Stop: { user: true } } }, null, 2)}\n`; + home.write(testCase.path, changed); + expect( + yield* Effect.flip(uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } })) + ).toMatchObject({ + _tag: "UnexpectedShape", + detail: "/hooks/Stop is not a list" + }); + expect(home.read(testCase.path)).toBe(changed); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + } + + it.effect(`${testCase.agent}: retains a replacement file after verify acknowledges a new hook hash`, () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); + const installed = home.read(testCase.path) ?? ""; + const replacement = installed.replace(/\b5\b/, "9"); + expect(replacement).not.toBe(installed); + yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); + home.write(testCase.path, replacement); + + const report = yield* verify("demo-app", { + bundle: hooksBundle(testCase, "demo-app", ["Stop"], 9), + agents: [testCase.agent], + ...(testCase.strategies === undefined ? {} : { strategies: testCase.strategies }), + providers: { install: testInstall, hooks: testHooks } + }); + expect(report.acknowledged).toHaveLength(1); + const acknowledged = (yield* inventory()).entries; + yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); + expect(home.read(testCase.path)).toBeDefined(); + expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); + expect(acknowledged.every((entry) => entry.createdConfigFile !== true)).toBe(true); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + + it.effect(`${testCase.agent}: retains a replacement file after recovering a failed hook update`, () => { + const home = testHome(); + const base = isolatedLayer(home); + const beforeWriteFailure = Layer.effect( + ArtifactFiles, + Effect.gen(function* () { + const files = yield* ArtifactFiles; + return { + ...files, + write: (locator) => + Effect.fail({ + _tag: "ArtifactIoFailure" as const, + path: locator.path, + operation: "write" as const, + message: "failed before writing" + }) + } satisfies typeof files; + }) + ).pipe(Layer.provide(base)); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); + const installed = home.read(testCase.path) ?? ""; + const replacement = installed.replace(/\b5\b/, "9"); + expect(replacement).not.toBe(installed); + const failure = yield* Effect.flip( + install(testCase, hooksBundle(testCase, "demo-app", ["Stop"], 9)).pipe( + Effect.provide(Layer.merge(base, beforeWriteFailure)) + ) + ); + expect(failure).toMatchObject({ _tag: "ApplyFailed", completed: 0 }); + expect(home.read(testCase.path)).toBe(installed); + expect((yield* inventory()).pending).toHaveLength(1); + yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); + home.write(testCase.path, replacement); + + yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); + expect(home.read(testCase.path)).toBeDefined(); + expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); + expect((yield* inventory()).pending).toEqual([]); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(base)); + }); + + for (const [index, seed] of testCase.emptySeeds.entries()) { + it.effect( + `${testCase.agent}: S1 retains a user-recreated empty file after the same owner reinstalls (${index})`, + () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase); + yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); + home.write(testCase.path, seed); + + yield* install(testCase); + const reinstalled = (yield* inventory()).entries; + yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeDefined(); + expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); + expect(reinstalled.every((entry) => entry.createdConfigFile !== true)).toBe(true); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + } + ); + + for (const firstRemoved of ["first-app", "second-app"]) { + it.effect( + `${testCase.agent}: S2 retains a user-recreated empty file after another owner installs (${index}, ${firstRemoved} first)`, + () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "first-app")); + yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); + home.write(testCase.path, seed); + + yield* install(testCase, hooksBundle(testCase, "second-app")); + const reinstalled = (yield* inventory()).entries; + const lastRemoved = firstRemoved === "first-app" ? "second-app" : "first-app"; + yield* uninstall(firstRemoved, { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeDefined(); + yield* uninstall(lastRemoved, { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeDefined(); + expect(home.read(testCase.path)).not.toContain("/bin/hook"); + expect(reinstalled.every((entry) => entry.createdConfigFile !== true)).toBe(true); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + } + ); + } + + for (const change of ["recreate", "truncate"] as const) { + it.effect(`${testCase.agent}: retains a user-${change}d empty file without a reinstall (${index})`, () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase); + if (change === "recreate") { + yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); + } + home.write(testCase.path, seed); + + yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBe(seed); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + } + } + + it.effect( + `${testCase.agent}: conservatively retains a file recorded by a v1 ledger without file provenance`, + () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase); + const oldLedger: unknown = JSON.parse(home.read(LEDGER_PATH) ?? "null", (key: string, value: unknown) => + key === "createdConfigFile" ? undefined : value + ); + home.write(LEDGER_PATH, `${JSON.stringify(oldLedger)}\n`); + + yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeDefined(); + expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + } + ); + + it.effect(`${testCase.agent}: retains a file after an ambiguous pending creation is recovered`, () => { + const home = testHome(); + const base = isolatedLayer(home); + const uncertainWrite = Layer.effect( + ArtifactFiles, + Effect.gen(function* () { + const files = yield* ArtifactFiles; + return { + ...files, + write: (locator, content) => + Effect.gen(function* () { + yield* files.write(locator, content); + return yield* Effect.fail({ + _tag: "ArtifactIoFailure" as const, + path: locator.path, + operation: "write" as const, + message: "write outcome unknown" + }); + }) + } satisfies typeof files; + }) + ).pipe(Layer.provide(base)); + return Effect.gen(function* () { + const failure = yield* Effect.flip( + install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])).pipe( + Effect.provide(Layer.merge(base, uncertainWrite)) + ) + ); + expect(failure).toMatchObject({ _tag: "ApplyFailed", completed: 0 }); + expect(home.read(testCase.path)).toContain("/opt/demo-app/bin/hook"); + yield* Effect.gen(function* () { + expect((yield* inventory()).pending).toHaveLength(1); + yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeDefined(); + expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); + expect((yield* inventory()).pending).toEqual([]); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(base)); + }); + }); + + it.effect( + `${testCase.agent}: refuses ownership when another writer creates the file before the first write`, + () => { + const home = testHome(); + const base = isolatedLayer(home); + const concurrentCreation = Layer.effect( + LedgerRepository, + Effect.gen(function* () { + const repository = yield* LedgerRepository; + let created = false; + return { + ...repository, + save: (scope, snapshot, expectedRevision) => + Effect.gen(function* () { + yield* repository.save(scope, snapshot, expectedRevision); + if (!created && snapshot.pending.length > 0) { + created = true; + home.write(testCase.path, ""); + } + }) + } satisfies typeof repository; + }) + ).pipe(Layer.provide(base)); + return Effect.gen(function* () { + const failure = yield* Effect.flip(install(testCase, hooksBundle(testCase, "demo-app", ["Stop"]))); + expect(failure).toMatchObject({ _tag: "TargetChanged", completed: 0 }); + expect(home.read(testCase.path)).toBe(""); + expect((yield* inventory()).entries).toEqual([]); + expect((yield* inventory()).pending).toEqual([]); + }).pipe(Effect.provide(Layer.merge(base, concurrentCreation))); + } + ); + + it.effect( + `${testCase.agent}: revokes old proof when another writer recreates a deleted file before reinstall writes`, + () => { + const home = testHome(); + const base = isolatedLayer(home); + const concurrentCreation = Layer.effect( + LedgerRepository, + Effect.gen(function* () { + const repository = yield* LedgerRepository; + let created = false; + return { + ...repository, + save: (scope, snapshot, expectedRevision) => + Effect.gen(function* () { + yield* repository.save(scope, snapshot, expectedRevision); + if (!created && snapshot.pending.length > 0) { + created = true; + home.write(testCase.path, ""); + } + }) + } satisfies typeof repository; + }) + ).pipe(Layer.provide(base)); + return Effect.gen(function* () { + const bundle = hooksBundle(testCase, "demo-app", ["Stop"]); + yield* install(testCase, bundle); + expect((yield* inventory()).entries).toEqual([expect.objectContaining({ createdConfigFile: true })]); + yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); + const plan = yield* planInstall(bundle, { + agents: [testCase.agent], + ...(testCase.strategies === undefined ? {} : { strategies: testCase.strategies }), + providers: { install: testInstall, hooks: testHooks } + }); + const failure = yield* Effect.flip( + applyInstall(plan).pipe(Effect.provide(Layer.merge(base, concurrentCreation))) + ); + expect(failure).toMatchObject({ _tag: "TargetChanged", completed: 0 }); + expect(home.read(testCase.path)).toBe(""); + expect((yield* inventory()).pending).toEqual([]); + expect(home.read(LEDGER_PATH)).not.toContain('"createdConfigFile"'); + + yield* install(testCase, bundle); + expect((yield* inventory()).entries).toHaveLength(1); + expect(home.read(LEDGER_PATH)).not.toContain('"createdConfigFile"'); + yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeDefined(); + expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(base)); + } + ); + + for (const stage of ["install", "uninstall"]) { + it.effect(`${testCase.agent}: propagates a real own-target permission read failure during ${stage}`, () => { + const home = testHome(); + const base = isolatedLayer(home); + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); + const installed = home.read(testCase.path); + const plan = + stage === "install" + ? yield* planInstall(hooksBundle(testCase, "demo-app", ["Stop"], 9), { + agents: [testCase.agent], + ...(testCase.strategies === undefined ? {} : { strategies: testCase.strategies }), + providers: { install: testInstall, hooks: testHooks } + }) + : undefined; + const path = home.path(testCase.path); + const mode = statSync(path).mode & 0o777; + let previewed = false; + const denyAfterPreview = Layer.effect( + ArtifactFiles, + Effect.gen(function* () { + const files = yield* ArtifactFiles; + return { + ...files, + preview: (previewPath, format, changes) => + Effect.gen(function* () { + const result = yield* files.preview(previewPath, format, changes); + if (previewPath === path) { + previewed = true; + denyRead(path); + } + return result; + }) + } satisfies typeof files; + }) + ).pipe(Layer.provide(base)); + if (stage === "install") { + denyRead(path); + } + const operation = + plan === undefined + ? uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }).pipe(Effect.provide(Layer.merge(base, denyAfterPreview))) + : applyInstall(plan); + const failure = yield* Effect.flip(operation).pipe(Effect.ensuring(Effect.sync(() => allowRead(path, mode)))); + expect(previewed).toBe(stage === "uninstall"); + expect(failure).toMatchObject({ + _tag: "ArtifactIoFailure", + path, + operation: "read", + cause: { code: DENIED_READ } + }); + expect(home.read(testCase.path)).toBe(installed); + expect((yield* inventory()).entries).toEqual([expect.objectContaining({ createdConfigFile: true })]); + expect((yield* inventory()).pending).toEqual([]); + }).pipe(Effect.provide(base)); + }); + } + + it.effect( + `${testCase.agent}: preserves hooks when deleting the empty result fails and retries after recovery`, + () => { + const home = testHome(); + const failingPlatform = { + ...home.platform, + fs: { + ...home.platform.fs, + remove: async (path: string) => { + if (path === home.path(testCase.path)) { + throw new Error("remove failed"); + } + return home.platform.fs.remove(path); + } + } + }; + return Effect.gen(function* () { + yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])).pipe( + Effect.provide(isolatedLayer(home)) + ); + const installed = home.read(testCase.path); + const failure = yield* Effect.flip( + uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }).pipe(Effect.provide(isolatedLayer(home, failingPlatform))) + ); + expect(failure).toMatchObject({ + _tag: "ApplyFailed", + completed: 0, + cause: { _tag: "ArtifactIoFailure", message: "remove failed" } + }); + expect(home.read(testCase.path)).toBe(installed); + yield* Effect.gen(function* () { + expect((yield* inventory()).pending).toHaveLength(1); + yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + }); + expect(home.read(testCase.path)).toBeUndefined(); + expect((yield* inventory()).entries).toEqual([]); + expect((yield* inventory()).pending).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + } + ); + + it.effect(`${testCase.agent}: retains a created file when the user changes its owned hooks`, () => { + const home = testHome(); + return Effect.gen(function* () { + yield* install(testCase); + const installed = home.read(testCase.path) ?? ""; + const edited = installed.replaceAll(/\b5\b/g, "9"); + expect(edited).not.toBe(installed); + home.write(testCase.path, edited); + expect( + (yield* uninstall("demo-app", { + providers: { install: testInstall, hooks: testHooks } + })).kept + ).toHaveLength(4); + expect(home.read(testCase.path)).toBe(edited); + expect((yield* inventory()).entries).toEqual([]); + }).pipe(Effect.provide(isolatedLayer(home))); + }); + }); +} + +export { isolatedLayer, testInstall, testHooks }; diff --git a/packages/harness/test/uninstall-created-config-claude-code.test.ts b/packages/harness/test/uninstall-created-config-claude-code.test.ts new file mode 100644 index 00000000..388da796 --- /dev/null +++ b/packages/harness/test/uninstall-created-config-claude-code.test.ts @@ -0,0 +1,3 @@ +import { registerUninstallCreatedConfigCases } from "./support/uninstall-created-config.js"; + +registerUninstallCreatedConfigCases("claude-code"); diff --git a/packages/harness/test/uninstall-created-config.test.ts b/packages/harness/test/uninstall-created-config.test.ts index 4719dfd8..e2a9f41d 100644 --- a/packages/harness/test/uninstall-created-config.test.ts +++ b/packages/harness/test/uninstall-created-config.test.ts @@ -1,887 +1,27 @@ -import { builtinInstallAdapters as testInstall } from "./support/providers.js"; -import { builtinHookDialects as testHooks } from "./support/providers.js"; -import { execFileSync } from "node:child_process"; -import { chmodSync, existsSync, statSync } from "node:fs"; -import { normalize } from "node:path"; +import { existsSync } from "node:fs"; -import { parse as parseToml } from "@decimalturn/toml-patch"; import { afterEach, describe, expect, it } from "@effect/vitest"; -import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Layer from "effect/Layer"; -import { ArtifactFiles, LedgerRepository } from "../src/application/ports.js"; import { applyInstall } from "../src/application/use-cases/apply-install.js"; import { inventory } from "../src/application/use-cases/inventory.js"; -import { planInstall, type PlanInstallOptions } from "../src/application/use-cases/plan-install.js"; +import { planInstall } from "../src/application/use-cases/plan-install.js"; import { uninstall } from "../src/application/use-cases/uninstall.js"; import { verify } from "../src/application/use-cases/verify.js"; -import type { BundleSnapshot } from "../src/domain/bundle/value-objects/bundle.js"; -import { parseJsonc } from "../src/infra/adapters/jsonc-editor.js"; import { demoBundle } from "./support/bundles.js"; -import { removeTestHomes, type TestHome, testHome } from "./support/home.js"; +import { removeTestHomes, testHome } from "./support/home.js"; +import { + isolatedLayer, + registerUninstallCreatedConfigCases, + testHooks, + testInstall +} from "./support/uninstall-created-config.js"; afterEach(removeTestHomes); -/** Everyone's SID, which `icacls` takes instead of a localized account name. */ -const EVERYONE = "*S-1-1-0"; -/** The code of a denied read: `EACCES` from a mode; on Windows `EPERM`, to which libuv maps `ERROR_ACCESS_DENIED`. */ -const DENIED_READ = process.platform === "win32" ? "EPERM" : "EACCES"; - -/** - * Makes `path` unreadable to this process: by its mode where modes restrict reads, and on Windows, where they do not, - * by an ACL that denies everyone read access. - */ -function denyRead(path: string): void { - if (process.platform === "win32") { - execFileSync("icacls", [normalize(path), "/deny", `${EVERYONE}:(R)`], { stdio: "ignore" }); - return; - } - chmodSync(path, 0o000); -} - -/** Undoes `denyRead`. */ -function allowRead(path: string, mode: number): void { - if (process.platform === "win32") { - execFileSync("icacls", [normalize(path), "/remove:d", EVERYONE], { stdio: "ignore" }); - return; - } - chmodSync(path, mode); -} - -const EVENTS = ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"]; -const LEDGER_PATH = ".local/state/agent-kit/harness/user/ledger.json"; - -interface ConfigCase { - readonly agent: "codex" | "claude-code"; - readonly path: string; - readonly strategies?: PlanInstallOptions["strategies"]; - readonly emptySeeds: readonly string[]; - readonly userSeed: string; - readonly additions: readonly { readonly name: string; readonly before?: string; readonly after?: string }[]; -} - -const cases: readonly ConfigCase[] = [ - { - agent: "codex", - path: ".codex/config.toml", - emptySeeds: ["", " \n\t\n"], - userSeed: 'model = "custom"\n\n[user]\n', - additions: [ - { name: "data", before: 'model = "custom"\n' }, - { name: "a comment", before: "# User notes survive uninstall.\n" }, - { name: "an empty table", after: "\n[user]\n" }, - { name: "an empty inline table", before: "user = {}\n" } - ] - }, - { - agent: "claude-code", - path: ".claude/settings.json", - strategies: { "claude-code": { hooks: "shared-config" } }, - emptySeeds: ["", " \n\t\n", "{}\n"], - userSeed: '{"theme":"dark","user":{}}\n', - additions: [ - { name: "data", before: '"theme":"dark",' }, - { name: "a comment", before: "// User notes survive uninstall.\n" }, - { name: "an empty object", before: '"user":{},' }, - { name: "an empty array", before: '"user":[],' } - ] - } -]; - -function isolatedLayer(home: TestHome, platform = home.platform) { - return home.layer({ - ...platform, - clock: { now: () => 0, monotonic: () => 0 }, - process: { - run: () => Promise.reject(new Error("Unexpected external command")), - spawn: () => { - throw new Error("Unexpected external command"); - }, - self: { host: "test", bootId: "test", pid: 1, startTime: 0 }, - identify: () => undefined - } - }); -} - -function hooksBundle( - testCase: ConfigCase, - owner = "demo-app", - events: readonly string[] = EVENTS, - timeoutSeconds = 5 -): BundleSnapshot { - return demoBundle("1.0.0", { - owner, - legacyMarkers: [], - artifacts: [ - { - type: "hooks", - command: `/opt/${owner}/bin/hook --agent {agent}`, - timeoutSeconds, - events: { [testCase.agent]: events } - } - ] - }); -} - -function install(testCase: ConfigCase, bundle = hooksBundle(testCase)) { - return Effect.gen(function* () { - const plan = yield* planInstall(bundle, { - agents: [testCase.agent], - ...(testCase.strategies === undefined ? {} : { strategies: testCase.strategies }), - providers: { install: testInstall, hooks: testHooks } - }); - expect(plan.commands).toEqual([]); - yield* applyInstall(plan); - }); -} +registerUninstallCreatedConfigCases("codex"); describe("uninstall of configuration files created by install", () => { - for (const testCase of cases) { - it.effect(`${testCase.agent}: deletes the created file after removing all four hook groups without a CLI`, () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase); - const entries = (yield* inventory()).entries.filter((entry) => entry.locator.path === home.path(testCase.path)); - expect(entries).toHaveLength(4); - expect(home.read(testCase.path)).toContain("/opt/demo-app/bin/hook"); - - const removed = yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(removed.kept).toEqual([]); - expect(home.read(testCase.path)).toBeUndefined(); - expect((yield* inventory()).entries).toEqual([]); - expect( - (yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - })).steps - ).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - - for (const [index, seed] of testCase.emptySeeds.entries()) { - it.effect(`${testCase.agent}: retains an empty file when cleanup targets an absent hook (${index})`, () => { - const home = testHome(); - home.write(testCase.path, seed); - return Effect.gen(function* () { - yield* (yield* ArtifactFiles).remove( - { - kind: testCase.agent === "codex" ? "toml-entry" : "json-entry", - path: home.path(testCase.path), - pointer: "/hooks/Stop", - member: `/opt/demo-app/bin/hook --agent ${testCase.agent}`, - memberIn: "hook-group" - }, - { removeEmptyFile: true } - ); - expect(home.read(testCase.path)).toBe(seed); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - - it.effect(`${testCase.agent}: retains a pre-existing empty configuration file (${index})`, () => { - const home = testHome(); - home.write(testCase.path, seed); - return Effect.gen(function* () { - yield* install(testCase); - expect((yield* inventory()).entries.every((entry) => entry.preImage.existed === false)).toBe(true); - yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeDefined(); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - } - - it.effect(`${testCase.agent}: retains a pre-existing configuration file with other data`, () => { - const home = testHome(); - home.write(testCase.path, testCase.userSeed); - return Effect.gen(function* () { - yield* install(testCase); - yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); - const remaining = home.read(testCase.path); - expect(remaining).toBeDefined(); - if (testCase.agent === "codex") { - expect(parseToml(remaining ?? "")).toEqual(parseToml(testCase.userSeed)); - } else { - expect(JSON.parse(remaining ?? "null")).toEqual(JSON.parse(testCase.userSeed)); - } - }).pipe(Effect.provide(isolatedLayer(home))); - }); - - for (const addition of testCase.additions) { - it.effect(`${testCase.agent}: retains a created file after the user adds ${addition.name}`, () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase); - const installed = home.read(testCase.path) ?? ""; - const before = addition.before ?? ""; - const edited = - testCase.agent === "claude-code" && before.startsWith('"') - ? installed.replace("{", `{${before}`) - : `${before}${installed}${addition.after ?? ""}`; - home.write(testCase.path, edited); - - const removed = yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(removed.kept).toEqual([]); - const remaining = home.read(testCase.path); - expect(remaining).toBeDefined(); - if (testCase.agent === "claude-code" && before.startsWith('"')) { - expect(JSON.parse(remaining ?? "null")).toEqual(JSON.parse(`{${before.replace(/,$/, "")}}`)); - } else { - expect(remaining).toContain((addition.before ?? addition.after ?? "").trim()); - } - expect(remaining).not.toContain("/opt/demo-app/bin/hook"); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - } - - for (const firstRemoved of ["first-app", "second-app"]) { - it.effect( - `${testCase.agent}: retains the created file until the last owner leaves (${firstRemoved} first)`, - () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "first-app")); - yield* install(testCase, hooksBundle(testCase, "second-app")); - const lastRemoved = firstRemoved === "first-app" ? "second-app" : "first-app"; - - yield* uninstall(firstRemoved, { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toContain(`/opt/${lastRemoved}/bin/hook`); - expect(home.read(testCase.path)).not.toContain(`/opt/${firstRemoved}/bin/hook`); - yield* uninstall(lastRemoved, { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeUndefined(); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - } - ); - } - - it.effect(`${testCase.agent}: retains file provenance through a no-op reinstall and an added hook event`, () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); - yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); - yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop", "SessionStart"])); - yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); - expect(home.read(testCase.path)).toBeUndefined(); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - - it.effect(`${testCase.agent}: inherits file provenance while another proven hook still matches`, () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "first-app")); - const installed = home.read(testCase.path) ?? ""; - const edited = installed.replace(/\b5\b/, "9"); - expect(edited).not.toBe(installed); - home.write(testCase.path, edited); - - yield* install(testCase, hooksBundle(testCase, "second-app")); - const inherited = (yield* inventory()).entries.filter((entry) => entry.owners.includes("second-app")); - expect(inherited).toHaveLength(4); - expect(inherited.every((entry) => entry.createdConfigFile === true)).toBe(true); - yield* uninstall("second-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect( - (yield* uninstall("first-app", { - providers: { install: testInstall, hooks: testHooks } - })).kept - ).toHaveLength(1); - expect(home.read(testCase.path)).toContain("/opt/first-app/bin/hook"); - expect(home.read(testCase.path)).not.toContain("/opt/second-app/bin/hook"); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - - for (const malformedEvent of ["SessionStart", "Stop"]) { - for (const stage of ["fresh install", "direct uninstall"]) { - it.effect( - `${testCase.agent}: tolerates another owner's malformed ${malformedEvent} hook during ${stage}`, - () => { - const home = testHome(); - const goodEvent = malformedEvent === "SessionStart" ? "Stop" : "SessionStart"; - return Effect.gen(function* () { - if (stage === "fresh install") { - yield* install(testCase, hooksBundle(testCase, "other-app", ["SessionStart", "Stop"])); - } else { - const otherBundle = hooksBundle(testCase, "other-app", [malformedEvent]); - const ourBundle = hooksBundle(testCase, "demo-app", [goodEvent]); - if (malformedEvent === "SessionStart") { - yield* install(testCase, otherBundle); - yield* install(testCase, ourBundle); - } else { - yield* install(testCase, ourBundle); - yield* install(testCase, otherBundle); - } - } - const pointers = (yield* inventory()).entries.map((entry) => entry.locator.pointer); - expect(pointers.indexOf(`/hooks/${malformedEvent}`) < pointers.indexOf(`/hooks/${goodEvent}`)).toBe( - malformedEvent === "SessionStart" - ); - const goodOwner = stage === "fresh install" ? "other-app" : "demo-app"; - const command = `/opt/${goodOwner}/bin/hook --agent ${testCase.agent}`; - home.write( - testCase.path, - testCase.agent === "codex" - ? `hooks.${malformedEvent} = { user = true }\n\n[[hooks.${goodEvent}]]\n[[hooks.${goodEvent}.hooks]]\ntype = "command"\ncommand = "${command}"\ntimeout = 5\n` - : `${JSON.stringify( - { - hooks: { - [malformedEvent]: { user: true }, - [goodEvent]: [{ hooks: [{ type: "command", command, timeout: 5 }] }] - } - }, - null, - 2 - )}\n` - ); - - if (stage === "fresh install") { - yield* install(testCase, hooksBundle(testCase, "demo-app", [goodEvent])); - } - expect( - (yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - })).kept - ).toEqual([]); - const remaining = home.read(testCase.path); - expect(remaining).toBeDefined(); - if (testCase.agent === "codex") { - expect(parseToml(remaining ?? "")).toMatchObject({ hooks: { [malformedEvent]: { user: true } } }); - } else { - const parsed = parseJsonc(remaining ?? ""); - expect(parsed.ok).toBe(true); - expect(parsed.ok ? parsed.value : undefined).toMatchObject({ - hooks: { [malformedEvent]: { user: true } } - }); - } - expect(remaining).not.toContain("/opt/demo-app/bin/hook"); - expect((yield* inventory()).entries.every((entry) => !entry.owners.includes("demo-app"))).toBe(true); - }).pipe(Effect.provide(isolatedLayer(home))); - } - ); - } - } - - it.effect(`${testCase.agent}: revokes file provenance when the only other owner's hook is malformed`, () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "other-app", ["Stop"])); - home.write( - testCase.path, - testCase.agent === "codex" - ? "hooks.Stop = { user = true }\n" - : `${JSON.stringify({ hooks: { Stop: { user: true } } }, null, 2)}\n` - ); - - yield* install(testCase, hooksBundle(testCase, "demo-app", ["SessionStart"])); - const entries = (yield* inventory()).entries; - expect(entries).toHaveLength(2); - expect(entries.every((entry) => entry.createdConfigFile !== true)).toBe(true); - yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); - const remaining = home.read(testCase.path); - expect(remaining).toBeDefined(); - expect(remaining).not.toContain("/opt/demo-app/bin/hook"); - if (testCase.agent === "codex") { - expect(parseToml(remaining ?? "")).toEqual({ hooks: { Stop: { user: true } } }); - } else { - const parsed = parseJsonc(remaining ?? ""); - expect(parsed.ok).toBe(true); - expect(parsed.ok ? parsed.value : undefined).toEqual({ hooks: { Stop: { user: true } } }); - } - }).pipe(Effect.provide(isolatedLayer(home))); - }); - - it.effect(`${testCase.agent}: deletes the new file after reinstall recreates a removed configuration file`, () => { - const home = testHome(); - return Effect.gen(function* () { - const bundle = hooksBundle(testCase, "demo-app", ["Stop"]); - yield* install(testCase, bundle); - yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); - yield* install(testCase, bundle); - const reinstalled = (yield* inventory()).entries; - expect(home.read(testCase.path)).toContain("/opt/demo-app/bin/hook"); - yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); - expect(home.read(testCase.path)).toBeUndefined(); - expect(reinstalled.every((entry) => entry.createdConfigFile === true)).toBe(true); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - - if (testCase.agent === "claude-code") { - it.effect("propagates defects from the optional file-provenance observation", () => { - const home = testHome(); - const base = isolatedLayer(home); - const defectiveRead = Layer.effect( - ArtifactFiles, - Effect.gen(function* () { - const files = yield* ArtifactFiles; - return { - ...files, - read: (locator) => - locator.member?.includes("/opt/other-app/") === true - ? Effect.die("proof observation defect") - : files.read(locator) - } satisfies typeof files; - }) - ).pipe(Layer.provide(base)); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "other-app", ["Stop"])); - const before = home.read(testCase.path); - const plan = yield* planInstall(hooksBundle(testCase, "demo-app", ["SessionStart"]), { - agents: [testCase.agent], - strategies: testCase.strategies, - providers: { install: testInstall, hooks: testHooks } - }); - const result = yield* Effect.exit(applyInstall(plan).pipe(Effect.provide(Layer.merge(base, defectiveRead)))); - expect(Exit.isFailure(result) && Cause.hasDies(result.cause)).toBe(true); - expect(home.read(testCase.path)).toBe(before); - }).pipe(Effect.provide(base)); - }); - - it.effect("propagates an own-target malformed-hook read failure", () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); - const changed = `${JSON.stringify({ hooks: { Stop: { user: true } } }, null, 2)}\n`; - home.write(testCase.path, changed); - expect( - yield* Effect.flip(uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } })) - ).toMatchObject({ - _tag: "UnexpectedShape", - detail: "/hooks/Stop is not a list" - }); - expect(home.read(testCase.path)).toBe(changed); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - } - - it.effect(`${testCase.agent}: retains a replacement file after verify acknowledges a new hook hash`, () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); - const installed = home.read(testCase.path) ?? ""; - const replacement = installed.replace(/\b5\b/, "9"); - expect(replacement).not.toBe(installed); - yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); - home.write(testCase.path, replacement); - - const report = yield* verify("demo-app", { - bundle: hooksBundle(testCase, "demo-app", ["Stop"], 9), - agents: [testCase.agent], - ...(testCase.strategies === undefined ? {} : { strategies: testCase.strategies }), - providers: { install: testInstall, hooks: testHooks } - }); - expect(report.acknowledged).toHaveLength(1); - const acknowledged = (yield* inventory()).entries; - yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); - expect(home.read(testCase.path)).toBeDefined(); - expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); - expect(acknowledged.every((entry) => entry.createdConfigFile !== true)).toBe(true); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - - it.effect(`${testCase.agent}: retains a replacement file after recovering a failed hook update`, () => { - const home = testHome(); - const base = isolatedLayer(home); - const beforeWriteFailure = Layer.effect( - ArtifactFiles, - Effect.gen(function* () { - const files = yield* ArtifactFiles; - return { - ...files, - write: (locator) => - Effect.fail({ - _tag: "ArtifactIoFailure" as const, - path: locator.path, - operation: "write" as const, - message: "failed before writing" - }) - } satisfies typeof files; - }) - ).pipe(Layer.provide(base)); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); - const installed = home.read(testCase.path) ?? ""; - const replacement = installed.replace(/\b5\b/, "9"); - expect(replacement).not.toBe(installed); - const failure = yield* Effect.flip( - install(testCase, hooksBundle(testCase, "demo-app", ["Stop"], 9)).pipe( - Effect.provide(Layer.merge(base, beforeWriteFailure)) - ) - ); - expect(failure).toMatchObject({ _tag: "ApplyFailed", completed: 0 }); - expect(home.read(testCase.path)).toBe(installed); - expect((yield* inventory()).pending).toHaveLength(1); - yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); - home.write(testCase.path, replacement); - - yield* uninstall("demo-app", { providers: { install: testInstall, hooks: testHooks } }); - expect(home.read(testCase.path)).toBeDefined(); - expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); - expect((yield* inventory()).pending).toEqual([]); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(base)); - }); - - for (const [index, seed] of testCase.emptySeeds.entries()) { - it.effect( - `${testCase.agent}: S1 retains a user-recreated empty file after the same owner reinstalls (${index})`, - () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase); - yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); - home.write(testCase.path, seed); - - yield* install(testCase); - const reinstalled = (yield* inventory()).entries; - yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeDefined(); - expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); - expect(reinstalled.every((entry) => entry.createdConfigFile !== true)).toBe(true); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - } - ); - - for (const firstRemoved of ["first-app", "second-app"]) { - it.effect( - `${testCase.agent}: S2 retains a user-recreated empty file after another owner installs (${index}, ${firstRemoved} first)`, - () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "first-app")); - yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); - home.write(testCase.path, seed); - - yield* install(testCase, hooksBundle(testCase, "second-app")); - const reinstalled = (yield* inventory()).entries; - const lastRemoved = firstRemoved === "first-app" ? "second-app" : "first-app"; - yield* uninstall(firstRemoved, { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeDefined(); - yield* uninstall(lastRemoved, { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeDefined(); - expect(home.read(testCase.path)).not.toContain("/bin/hook"); - expect(reinstalled.every((entry) => entry.createdConfigFile !== true)).toBe(true); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - } - ); - } - - for (const change of ["recreate", "truncate"] as const) { - it.effect(`${testCase.agent}: retains a user-${change}d empty file without a reinstall (${index})`, () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase); - if (change === "recreate") { - yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); - } - home.write(testCase.path, seed); - - yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBe(seed); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - } - } - - it.effect( - `${testCase.agent}: conservatively retains a file recorded by a v1 ledger without file provenance`, - () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase); - const oldLedger: unknown = JSON.parse(home.read(LEDGER_PATH) ?? "null", (key: string, value: unknown) => - key === "createdConfigFile" ? undefined : value - ); - home.write(LEDGER_PATH, `${JSON.stringify(oldLedger)}\n`); - - yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeDefined(); - expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - } - ); - - it.effect(`${testCase.agent}: retains a file after an ambiguous pending creation is recovered`, () => { - const home = testHome(); - const base = isolatedLayer(home); - const uncertainWrite = Layer.effect( - ArtifactFiles, - Effect.gen(function* () { - const files = yield* ArtifactFiles; - return { - ...files, - write: (locator, content) => - Effect.gen(function* () { - yield* files.write(locator, content); - return yield* Effect.fail({ - _tag: "ArtifactIoFailure" as const, - path: locator.path, - operation: "write" as const, - message: "write outcome unknown" - }); - }) - } satisfies typeof files; - }) - ).pipe(Layer.provide(base)); - return Effect.gen(function* () { - const failure = yield* Effect.flip( - install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])).pipe( - Effect.provide(Layer.merge(base, uncertainWrite)) - ) - ); - expect(failure).toMatchObject({ _tag: "ApplyFailed", completed: 0 }); - expect(home.read(testCase.path)).toContain("/opt/demo-app/bin/hook"); - yield* Effect.gen(function* () { - expect((yield* inventory()).pending).toHaveLength(1); - yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeDefined(); - expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); - expect((yield* inventory()).pending).toEqual([]); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(base)); - }); - }); - - it.effect( - `${testCase.agent}: refuses ownership when another writer creates the file before the first write`, - () => { - const home = testHome(); - const base = isolatedLayer(home); - const concurrentCreation = Layer.effect( - LedgerRepository, - Effect.gen(function* () { - const repository = yield* LedgerRepository; - let created = false; - return { - ...repository, - save: (scope, snapshot, expectedRevision) => - Effect.gen(function* () { - yield* repository.save(scope, snapshot, expectedRevision); - if (!created && snapshot.pending.length > 0) { - created = true; - home.write(testCase.path, ""); - } - }) - } satisfies typeof repository; - }) - ).pipe(Layer.provide(base)); - return Effect.gen(function* () { - const failure = yield* Effect.flip(install(testCase, hooksBundle(testCase, "demo-app", ["Stop"]))); - expect(failure).toMatchObject({ _tag: "TargetChanged", completed: 0 }); - expect(home.read(testCase.path)).toBe(""); - expect((yield* inventory()).entries).toEqual([]); - expect((yield* inventory()).pending).toEqual([]); - }).pipe(Effect.provide(Layer.merge(base, concurrentCreation))); - } - ); - - it.effect( - `${testCase.agent}: revokes old proof when another writer recreates a deleted file before reinstall writes`, - () => { - const home = testHome(); - const base = isolatedLayer(home); - const concurrentCreation = Layer.effect( - LedgerRepository, - Effect.gen(function* () { - const repository = yield* LedgerRepository; - let created = false; - return { - ...repository, - save: (scope, snapshot, expectedRevision) => - Effect.gen(function* () { - yield* repository.save(scope, snapshot, expectedRevision); - if (!created && snapshot.pending.length > 0) { - created = true; - home.write(testCase.path, ""); - } - }) - } satisfies typeof repository; - }) - ).pipe(Layer.provide(base)); - return Effect.gen(function* () { - const bundle = hooksBundle(testCase, "demo-app", ["Stop"]); - yield* install(testCase, bundle); - expect((yield* inventory()).entries).toEqual([expect.objectContaining({ createdConfigFile: true })]); - yield* Effect.promise(() => home.platform.fs.remove(home.path(testCase.path))); - const plan = yield* planInstall(bundle, { - agents: [testCase.agent], - ...(testCase.strategies === undefined ? {} : { strategies: testCase.strategies }), - providers: { install: testInstall, hooks: testHooks } - }); - const failure = yield* Effect.flip( - applyInstall(plan).pipe(Effect.provide(Layer.merge(base, concurrentCreation))) - ); - expect(failure).toMatchObject({ _tag: "TargetChanged", completed: 0 }); - expect(home.read(testCase.path)).toBe(""); - expect((yield* inventory()).pending).toEqual([]); - expect(home.read(LEDGER_PATH)).not.toContain('"createdConfigFile"'); - - yield* install(testCase, bundle); - expect((yield* inventory()).entries).toHaveLength(1); - expect(home.read(LEDGER_PATH)).not.toContain('"createdConfigFile"'); - yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeDefined(); - expect(home.read(testCase.path)).not.toContain("/opt/demo-app/bin/hook"); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(base)); - } - ); - - for (const stage of ["install", "uninstall"]) { - it.effect(`${testCase.agent}: propagates a real own-target permission read failure during ${stage}`, () => { - const home = testHome(); - const base = isolatedLayer(home); - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])); - const installed = home.read(testCase.path); - const plan = - stage === "install" - ? yield* planInstall(hooksBundle(testCase, "demo-app", ["Stop"], 9), { - agents: [testCase.agent], - ...(testCase.strategies === undefined ? {} : { strategies: testCase.strategies }), - providers: { install: testInstall, hooks: testHooks } - }) - : undefined; - const path = home.path(testCase.path); - const mode = statSync(path).mode & 0o777; - let previewed = false; - const denyAfterPreview = Layer.effect( - ArtifactFiles, - Effect.gen(function* () { - const files = yield* ArtifactFiles; - return { - ...files, - preview: (previewPath, format, changes) => - Effect.gen(function* () { - const result = yield* files.preview(previewPath, format, changes); - if (previewPath === path) { - previewed = true; - denyRead(path); - } - return result; - }) - } satisfies typeof files; - }) - ).pipe(Layer.provide(base)); - if (stage === "install") { - denyRead(path); - } - const operation = - plan === undefined - ? uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }).pipe(Effect.provide(Layer.merge(base, denyAfterPreview))) - : applyInstall(plan); - const failure = yield* Effect.flip(operation).pipe(Effect.ensuring(Effect.sync(() => allowRead(path, mode)))); - expect(previewed).toBe(stage === "uninstall"); - expect(failure).toMatchObject({ - _tag: "ArtifactIoFailure", - path, - operation: "read", - cause: { code: DENIED_READ } - }); - expect(home.read(testCase.path)).toBe(installed); - expect((yield* inventory()).entries).toEqual([expect.objectContaining({ createdConfigFile: true })]); - expect((yield* inventory()).pending).toEqual([]); - }).pipe(Effect.provide(base)); - }); - } - - it.effect( - `${testCase.agent}: preserves hooks when deleting the empty result fails and retries after recovery`, - () => { - const home = testHome(); - const failingPlatform = { - ...home.platform, - fs: { - ...home.platform.fs, - remove: async (path: string) => { - if (path === home.path(testCase.path)) { - throw new Error("remove failed"); - } - return home.platform.fs.remove(path); - } - } - }; - return Effect.gen(function* () { - yield* install(testCase, hooksBundle(testCase, "demo-app", ["Stop"])).pipe( - Effect.provide(isolatedLayer(home)) - ); - const installed = home.read(testCase.path); - const failure = yield* Effect.flip( - uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }).pipe(Effect.provide(isolatedLayer(home, failingPlatform))) - ); - expect(failure).toMatchObject({ - _tag: "ApplyFailed", - completed: 0, - cause: { _tag: "ArtifactIoFailure", message: "remove failed" } - }); - expect(home.read(testCase.path)).toBe(installed); - yield* Effect.gen(function* () { - expect((yield* inventory()).pending).toHaveLength(1); - yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - }); - expect(home.read(testCase.path)).toBeUndefined(); - expect((yield* inventory()).entries).toEqual([]); - expect((yield* inventory()).pending).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - } - ); - - it.effect(`${testCase.agent}: retains a created file when the user changes its owned hooks`, () => { - const home = testHome(); - return Effect.gen(function* () { - yield* install(testCase); - const installed = home.read(testCase.path) ?? ""; - const edited = installed.replaceAll(/\b5\b/g, "9"); - expect(edited).not.toBe(installed); - home.write(testCase.path, edited); - expect( - (yield* uninstall("demo-app", { - providers: { install: testInstall, hooks: testHooks } - })).kept - ).toHaveLength(4); - expect(home.read(testCase.path)).toBe(edited); - expect((yield* inventory()).entries).toEqual([]); - }).pipe(Effect.provide(isolatedLayer(home))); - }); - } - it.effect( "round-trips a seven-agent bundle, removes owned directories and their recorded ancestors, and retains user files", () => { diff --git a/packages/providers/claude-code/test/summarize-memory.test.ts b/packages/providers/claude-code/test/summarize-memory.test.ts index 40ccd5ed..8afd236c 100644 --- a/packages/providers/claude-code/test/summarize-memory.test.ts +++ b/packages/providers/claude-code/test/summarize-memory.test.ts @@ -59,7 +59,7 @@ describe("summarizeSession memory", () => { { prompts, providers: { sessions: testSessions, identity: testIdentity } } ) ); - for (let round = 1; round <= 5; round++) { + for (let round = 1; round <= 3; round++) { const loadSmall = await peakDuring((sampled) => loadTranscript( sampled, diff --git a/packages/providers/codex/test/summarize-memory.test.ts b/packages/providers/codex/test/summarize-memory.test.ts index 60f8ff6a..b11d14e5 100644 --- a/packages/providers/codex/test/summarize-memory.test.ts +++ b/packages/providers/codex/test/summarize-memory.test.ts @@ -66,7 +66,7 @@ describe("summarizeSession memory", () => { // the first measured round. await peakDuring(files, "/codex/small/rollout.jsonl", false); await peakDuring(files, "/codex/small/rollout.jsonl", true); - for (let round = 1; round <= 5; round++) { + for (let round = 1; round <= 3; round++) { const loadSmall = await peakDuring(files, "/codex/small/rollout.jsonl", false); const passSmall = await peakDuring(files, "/codex/small/rollout.jsonl", true); const loadLarge = await peakDuring(files, "/codex/large/rollout.jsonl", false); diff --git a/packages/providers/grok/test/summarize-memory.test.ts b/packages/providers/grok/test/summarize-memory.test.ts index 6439d9e5..61dee26c 100644 --- a/packages/providers/grok/test/summarize-memory.test.ts +++ b/packages/providers/grok/test/summarize-memory.test.ts @@ -64,7 +64,7 @@ describe("summarizeSession memory", () => { { prompts, providers: { sessions: testSessions, identity: testIdentity } } ) ); - for (let round = 1; round <= 5; round++) { + for (let round = 1; round <= 3; round++) { const loadSmall = await peakDuring((sampled) => loadTranscript( sampled, diff --git a/packages/testing/test/memory-support.ts b/packages/testing/test/memory-support.ts index e3bd78ff..a4aefb2b 100644 --- a/packages/testing/test/memory-support.ts +++ b/packages/testing/test/memory-support.ts @@ -26,11 +26,17 @@ export const gc = (() => { })(); /** - * The platform whose reads sample the heap: at every chunk boundary the collection runs first, so transients — the - * parsed records a materializing reader built, the records a pass dropped — are gone at each reading, and the peak - * is what the call was holding while it ran. A reader that materializes the transcript holds it from mid-read on; - * the summary pass holds only its running numbers. The tail after the last chunk is not sampled, which forgoes a - * few kilobytes of the peak. + * Sampling every 8 chunks (~512 KB at the 64 KB default chunk size) still yields ~32 samples across a 16 MB session + * while avoiding hundreds of synchronous full V8 GCs per pass. + */ +const SAMPLE_EVERY_CHUNKS = 8; + +/** + * The platform whose reads sample the heap: periodically at chunk boundaries the collection runs first, so transients + * — the parsed records a materializing reader built, the records a pass dropped — are gone at each reading, and the + * peak is what the call was holding while it ran. A reader that materializes the transcript holds it from mid-read on; + * the summary pass holds only its running numbers. The tail after the last sampled chunk is not sampled, which forgoes + * a few kilobytes of the peak. */ export function withSampledReads(inner: SessionPlatform, peak: { value: number }): SessionPlatform { return { @@ -38,9 +44,13 @@ export function withSampledReads(inner: SessionPlatform, peak: { value: number } stat: (path, options) => inner.fs.stat(path, options), list: (dir) => inner.fs.list(dir), async *read(path, range) { + let chunks = 0; for await (const chunk of inner.fs.read(path, range)) { - gc(); - peak.value = Math.max(peak.value, process.memoryUsage().heapUsed); + chunks += 1; + if (chunks % SAMPLE_EVERY_CHUNKS === 0) { + gc(); + peak.value = Math.max(peak.value, process.memoryUsage().heapUsed); + } yield chunk; } } From 7d9388650330d7bb0c04610a05b464cf4a4082f6 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:17:16 +0800 Subject: [PATCH 2/4] perf(ci): isolate architecture job and cap test concurrency to prevent oversubscription --- .github/workflows/ci.yml | 38 ++++++++++++++++++++++------ infra/architecture/run-lint-cases.ts | 4 ++- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 64e4469e..3af722ef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,21 +62,39 @@ jobs: # Only the published shells' built entries are imported by tests; website build stays in `static`. - name: Build shells run: pnpm --filter @rivus/agent-kit... --filter @rivus/agent-kit-collab... run build - - name: Test - run: pnpm run test + # Cap workspace concurrency to 2 because Vitest already parallelizes test files across all runner cores. + - name: Test packages + run: pnpm -r --no-sort --workspace-concurrency=2 --filter '!architecture-boundaries' run test + + # Runs the boundary manifest tests and the 387-case `run-lint-cases.ts` suite on its own runner so its parallel + # `vp lint` processes do not contend with Vitest workers for the 4-core CPU. + architecture: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + name: architecture + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + - uses: pnpm/setup@v3 + with: + runtime: node + require-lockfile: true + cache: true + - name: Architecture tests + run: pnpm --filter architecture-boundaries run test # Aggregate status check preserving the `check` context name required by branch protection. check: if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) name: check - needs: [static, test] + needs: [static, test, architecture] runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Verify required jobs succeeded run: | - if [ "${{ needs.static.result }}" != "success" ] || [ "${{ needs.test.result }}" != "success" ]; then - echo "static=${{ needs.static.result }}, test=${{ needs.test.result }}" + if [ "${{ needs.static.result }}" != "success" ] || [ "${{ needs.test.result }}" != "success" ] || [ "${{ needs.architecture.result }}" != "success" ]; then + echo "static=${{ needs.static.result }}, test=${{ needs.test.result }}, architecture=${{ needs.architecture.result }}" exit 1 fi @@ -102,6 +120,10 @@ jobs: cache: true # The shell's tests import its built entries, as in the aggregate gate, which builds before it tests. - run: pnpm --filter @rivus/agent-kit... run build - - run: >- - pnpm -r --no-bail --no-sort - --filter '!@rivus/agent-kit-collab' test + # Run architecture lint-cases separately from Vitest packages so both stages have dedicated CPU without timeouts. + - name: Architecture tests + run: pnpm --filter architecture-boundaries run test + - name: Package tests + run: >- + pnpm -r --no-bail --no-sort --workspace-concurrency=2 + --filter '!@rivus/agent-kit-collab' --filter '!architecture-boundaries' test diff --git a/infra/architecture/run-lint-cases.ts b/infra/architecture/run-lint-cases.ts index 539b5800..560a30a5 100644 --- a/infra/architecture/run-lint-cases.ts +++ b/infra/architecture/run-lint-cases.ts @@ -305,8 +305,10 @@ try { spiProvider(copy); spiProvider(copy, true); // Capture the workspace listing once after synthetic providers exist so child `vp lint` processes skip `pnpm ls`. + // Each batch lints only a few files, so pin Rayon to 1 thread per process to avoid N×M CPU oversubscription. const cachedListEnv: NodeJS.ProcessEnv = { ...process.env, + RAYON_NUM_THREADS: "1", AGENT_KIT_PNPM_LIST_ROOT: copy, AGENT_KIT_PNPM_LIST_JSON: pnpmListJson(copy) }; @@ -316,7 +318,7 @@ try { (a, b) => b.length - a.length ); let nextGroup = 0; - const concurrency = Math.max(2, Math.min(availableParallelism(), 6, groups.length)); + const concurrency = Math.max(2, Math.min(availableParallelism(), 4, groups.length)); await Promise.all( Array.from({ length: concurrency }, async () => { while (nextGroup < groups.length) { From 3a954c6e84e3baba0677884cee8f0e699d54d087 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:02:21 +0800 Subject: [PATCH 3/4] perf(ci): split static into lint/verify and run windows architecture in parallel --- .github/workflows/ci.yml | 52 +++++++++++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3af722ef..b431dfb7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,9 +14,9 @@ concurrency: cancel-in-progress: true jobs: - static: + lint: if: github.event_name != 'pull_request' || !github.event.pull_request.draft - name: static + name: lint runs-on: ubuntu-latest timeout-minutes: 20 steps: @@ -36,14 +36,32 @@ jobs: check: release-plan - name: Format, docs and duplicates run: pnpm run format:check && pnpm run check:docs && pnpm run duplicates - - name: Build - run: pnpm run build + # Type-aware lint resolves built shell exports and the website's generated route tree, without needing a full site build. + - name: Prepare lint inputs + run: >- + pnpm --filter @rivus/agent-kit... --filter @rivus/agent-kit-collab... run build && + pnpm --filter website exec tsr generate - name: Lint # Cache the workspace listing once so all 38 package `vp lint` processes skip spawning `pnpm ls`. run: >- AGENT_KIT_PNPM_LIST_ROOT="$(node -p 'fs.realpathSync(process.cwd())')" AGENT_KIT_PNPM_LIST_JSON="$(pnpm ls -r --depth -1 --json)" pnpm run lint + + verify: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + name: verify + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + - uses: pnpm/setup@v3 + with: + runtime: node + require-lockfile: true + cache: true + - name: Build + run: pnpm run build - name: Knip, typecheck and package check run: pnpm run knip && pnpm run knip:production && pnpm run typecheck && pnpm run check:package @@ -59,7 +77,7 @@ jobs: runtime: node require-lockfile: true cache: true - # Only the published shells' built entries are imported by tests; website build stays in `static`. + # Only the published shells' built entries are imported by tests; website build stays in `verify`. - name: Build shells run: pnpm --filter @rivus/agent-kit... --filter @rivus/agent-kit-collab... run build # Cap workspace concurrency to 2 because Vitest already parallelizes test files across all runner cores. @@ -87,14 +105,14 @@ jobs: check: if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) name: check - needs: [static, test, architecture] + needs: [lint, verify, test, architecture] runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Verify required jobs succeeded run: | - if [ "${{ needs.static.result }}" != "success" ] || [ "${{ needs.test.result }}" != "success" ] || [ "${{ needs.architecture.result }}" != "success" ]; then - echo "static=${{ needs.static.result }}, test=${{ needs.test.result }}, architecture=${{ needs.architecture.result }}" + if [ "${{ needs.lint.result }}" != "success" ] || [ "${{ needs.verify.result }}" != "success" ] || [ "${{ needs.test.result }}" != "success" ] || [ "${{ needs.architecture.result }}" != "success" ]; then + echo "lint=${{ needs.lint.result }}, verify=${{ needs.verify.result }}, test=${{ needs.test.result }}, architecture=${{ needs.architecture.result }}" exit 1 fi @@ -120,10 +138,22 @@ jobs: cache: true # The shell's tests import its built entries, as in the aggregate gate, which builds before it tests. - run: pnpm --filter @rivus/agent-kit... run build - # Run architecture lint-cases separately from Vitest packages so both stages have dedicated CPU without timeouts. - - name: Architecture tests - run: pnpm --filter architecture-boundaries run test - name: Package tests run: >- pnpm -r --no-bail --no-sort --workspace-concurrency=2 --filter '!@rivus/agent-kit-collab' --filter '!architecture-boundaries' test + + windows-architecture: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + name: windows-architecture + runs-on: windows-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + - uses: pnpm/setup@v3 + with: + runtime: node + require-lockfile: true + cache: true + - name: Architecture tests + run: pnpm --filter architecture-boundaries run test From 789b88e7931ff182d2c3666e7cc1c658e0a43446 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:12:47 +0800 Subject: [PATCH 4/4] perf(ci): isolate windows harness tests to avoid NTFS contention and speed up windows CI --- .github/workflows/ci.yml | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b431dfb7..6b0be697 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,10 +138,29 @@ jobs: cache: true # The shell's tests import its built entries, as in the aggregate gate, which builds before it tests. - run: pnpm --filter @rivus/agent-kit... run build + # Exclude harness and architecture-boundaries, which run in dedicated parallel Windows jobs so heavy NTFS/icacls + # churn does not starve SQLite-based provider tests into 5s timeouts. - name: Package tests run: >- pnpm -r --no-bail --no-sort --workspace-concurrency=2 - --filter '!@rivus/agent-kit-collab' --filter '!architecture-boundaries' test + --filter '!@rivus/agent-kit-collab' + --filter '!@rivus/agent-kit-harness' + --filter '!architecture-boundaries' test + + windows-harness: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + name: windows-harness + runs-on: windows-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + - uses: pnpm/setup@v3 + with: + runtime: node + require-lockfile: true + cache: true + - name: Harness tests + run: pnpm --filter @rivus/agent-kit-harness run test windows-architecture: if: github.event_name != 'pull_request' || !github.event.pull_request.draft