opencode-workflow-guard 1.19.2 → 1.19.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/test/test.mts CHANGED
@@ -144,6 +144,7 @@ import { prBodyIncludesChangelog } from "../src/policies/changelog.ts";
144
144
  import { terminateProcessTree } from "../src/lib/verify.ts";
145
145
  import { audit } from "../src/lib/audit.ts";
146
146
  import { evaluatePermissionSeat } from "../src/lib/permission-seat.ts";
147
+ import { createCustomTools } from "../src/lib/custom-tools.ts";
147
148
  import { isProjectMemoryFreshAsync } from "../src/lib/project-memory.ts";
148
149
  import { ToolOutcomeTracker } from "../src/lib/tool-outcomes.ts";
149
150
  import { createRecoveryCheckpoint, finalizeRecoveryCheckpoint, listRecoveryCheckpoints, restoreRecoveryCheckpoint, setCheckpointGitForTesting } from "../src/lib/checkpoint.ts";
@@ -171,6 +172,10 @@ import { createHostWorktreePort } from "../src/lib/host-worktree.ts";
171
172
  import { validateHostWorktreeDirectory } from "../src/lib/worktree.ts";
172
173
  import { guardedTokensFromServerName, listHostMcpServerNames, recordHostMcpServers } from "../src/lib/mcp-inventory.ts";
173
174
  import { addGuardedMcpTokens, guardedMcpServers, mcpMutationTool, resetGuardedMcpTokensForTesting } from "../src/policies/mcp.ts";
175
+ import { DEFAULT_FILE_CLAIM_TTL_MS, fileClaimTtlMs } from "../src/policies/file-claims.ts";
176
+ import { OPENCODE_SCRATCH_DIR, isAllowedScratchTarget } from "../src/policies/boundary.ts";
177
+ import { existingProjectConfigPath } from "../src/lib/project-config.ts";
178
+ import { verifyCommandSource } from "../src/lib/verify.ts";
174
179
 
175
180
  let pass = 0;
176
181
  let fail = 0;
@@ -915,16 +920,34 @@ const unresolvableMv = await call("bash", { command: "mv $D/foo.txt ./bar.txt" }
915
920
  check("mv source with unresolvable $VAR names the variable cause", blocked(unresolvableMv) && String(unresolvableMv).includes("unresolvable variable reference"));
916
921
  const unresolvableGit = await call("bash", { command: "git -C $OTHER_REPO commit -m x" }, { sessionID: "s-active" });
917
922
  check("git repoDir with unresolvable $VAR names the variable cause", blocked(unresolvableGit) && String(unresolvableGit).includes("unresolvable variable reference"));
918
- // Scratch-directory cause attribution: /tmp/opencode is the environment's
919
- // designated scratch space, but the workspace boundary is workspace-absolute
920
- // and does not cover it; the message explains that instead of reading as a
921
- // guard bug (6 of the device audit's boundary blocks were this class).
922
- const scratchWrite = await call("write", { filePath: "/tmp/opencode/scratch.txt", content: "x" }, { sessionID: "s-active" });
923
- check("scratch-dir write attributes the environment scratch cause", blocked(scratchWrite) && String(scratchWrite).includes("environment scratch directory") && String(scratchWrite).includes("/tmp/opencode") && !String(scratchWrite).includes("unresolvable variable reference"));
924
- const scratchRedirect = await call("bash", { command: "echo x > /tmp/opencode/out.md" }, { sessionID: "s-active" });
925
- check("scratch-dir redirect attributes the environment scratch cause", blocked(scratchRedirect) && String(scratchRedirect).includes("environment scratch directory"));
926
- const scratchPatch = await call("apply_patch", { patchText: "*** Add File: /tmp/opencode/scratch.ts\n+scratch\n" }, { sessionID: "s-active" });
927
- check("scratch-dir apply_patch attributes the environment scratch cause", blocked(scratchPatch) && String(scratchPatch).includes("environment scratch directory"));
923
+ // Scratch-directory allowance: /tmp/opencode is the environment's designated
924
+ // agent scratch space. Writes there are sanctioned for a real session and only
925
+ // while the canonical target stays inside that exact directory; a symlink that
926
+ // leaves it, a sibling with a shared prefix, and a traversal out of it are all
927
+ // still boundary escapes. Execution itself is unchanged.
928
+ mkdirSync(OPENCODE_SCRATCH_DIR, { recursive: true });
929
+ const scratchTag = `wg-scratch-${process.pid}-${String(Date.now())}`;
930
+ todo("s-scratch", item("write scratch notes", "in_progress"));
931
+ const scratchFile = join(OPENCODE_SCRATCH_DIR, `${scratchTag}.txt`);
932
+ const scratchPatchFile = join(OPENCODE_SCRATCH_DIR, `${scratchTag}.ts`);
933
+ const scratchRedirectFile = join(OPENCODE_SCRATCH_DIR, `${scratchTag}.md`);
934
+ check("scratch-dir write is allowed for a session", allowed(await call("write", { filePath: scratchFile, content: "x" }, { sessionID: "s-scratch" })));
935
+ check("scratch-dir redirect is allowed for a session", allowed(await call("bash", { command: `echo x > ${scratchRedirectFile}` }, { sessionID: "s-scratch" })));
936
+ check("scratch-dir apply_patch is allowed for a session", allowed(await call("apply_patch", { patchText: `*** Add File: ${scratchPatchFile}\n+scratch\n` }, { sessionID: "s-scratch" })));
937
+ check("scratch-dir interpreter payload write is allowed", allowed(await call("bash", { command: `python3 -c "open('${scratchFile}', 'w').write('x')"` }, { sessionID: "s-scratch" })));
938
+ check("scratch-dir cd redirect is allowed", allowed(await call("bash", { command: `cd ${OPENCODE_SCRATCH_DIR} && echo x > ${scratchTag}-cd.md` }, { sessionID: "s-scratch" })));
939
+ const sessionlessScratch = await call("write", { filePath: scratchFile, content: "x" });
940
+ check("scratch-dir write needs a session id", blocked(sessionlessScratch) && String(sessionlessScratch).includes("environment scratch directory"));
941
+ const scratchPrefixPeer = await call("write", { filePath: `${OPENCODE_SCRATCH_DIR}-evil/out.txt`, content: "x" }, { sessionID: "s-scratch" });
942
+ check("a sibling sharing the scratch prefix is still blocked", blocked(scratchPrefixPeer) && String(scratchPrefixPeer).includes("escapes workspace root"));
943
+ const scratchTraversal = await call("write", { filePath: `${OPENCODE_SCRATCH_DIR}/../wg-escape.txt`, content: "x" }, { sessionID: "s-scratch" });
944
+ check("a traversal out of the scratch dir is blocked", blocked(scratchTraversal) && String(scratchTraversal).includes("escapes workspace root"));
945
+ const scratchEscapeDir = mkdtempSync(join(tmpdir(), "wg-scratch-escape-"));
946
+ symlinkSync(scratchEscapeDir, join(OPENCODE_SCRATCH_DIR, `${scratchTag}-link`), "dir");
947
+ const symlinkScratch = await call("write", { filePath: join(OPENCODE_SCRATCH_DIR, `${scratchTag}-link`, "out.txt"), content: "x" }, { sessionID: "s-scratch" });
948
+ check("a symlink out of the scratch dir is blocked", blocked(symlinkScratch) && String(symlinkScratch).includes("scratch allowance does not cover it"));
949
+ rmSync(join(OPENCODE_SCRATCH_DIR, `${scratchTag}-link`), { force: true });
950
+ rmSync(scratchEscapeDir, { recursive: true, force: true });
928
951
  const otherOutsideWrite = await call("write", { filePath: "/var/tmp/elsewhere.txt", content: "x" }, { sessionID: "s-active" });
929
952
  check("non-scratch outside path keeps the generic escape message", blocked(otherOutsideWrite) && String(otherOutsideWrite).includes("escapes workspace root") && !String(otherOutsideWrite).includes("scratch directory"));
930
953
  check("allow apply_patch within workspace", !(await call("apply_patch", { patchText: "*** Update File: src/app.ts\n" }, { sessionID: "s-active" })));
@@ -1111,7 +1134,7 @@ let claimConflict = false;
1111
1134
  try {
1112
1135
  await claimsBefore?.({ tool: "edit", sessionID: "s-claim-b", callID: "claim-b" }, { args: { filePath: join(claimsDir, "shared-link.ts"), content: "b" } });
1113
1136
  } catch (error) {
1114
- claimConflict = String(error).includes("claimed by another active session");
1137
+ claimConflict = String(error).includes("is claimed by session");
1115
1138
  }
1116
1139
  check("concurrent file claims block another session through a symlink alias", claimConflict);
1117
1140
  const whyClaimConflict = JSON.parse(String(await claimsHooks.tool?.guard_why?.execute(
@@ -1142,7 +1165,7 @@ let danglingConflict = false;
1142
1165
  try {
1143
1166
  await claimsBefore?.({ tool: "write", sessionID: "s-claim-b", callID: "claim-dangling-alias" }, { args: { filePath: join(claimsDir, "future-link.ts"), content: "b" } });
1144
1167
  } catch (error) {
1145
- danglingConflict = String(error).includes("claimed by another active session");
1168
+ danglingConflict = String(error).includes("is claimed by session");
1146
1169
  }
1147
1170
  check("concurrent file claims canonicalize dangling final symlinks", danglingConflict);
1148
1171
  await claimsHooks.event?.({ event: { type: "session.idle", properties: { sessionID: "s-claim-a" } } } as any);
@@ -1161,7 +1184,7 @@ let patchConflict = false;
1161
1184
  try {
1162
1185
  await claimsBefore?.({ tool: "apply_patch", sessionID: "s-claim-b", callID: "claim-patch" }, { args: { patchText: "*** Begin Patch\n*** Update File: other.ts\n-old\n+new\n*** Update File: shared.ts\n-old\n+new\n*** End Patch" } });
1163
1186
  } catch (error) {
1164
- patchConflict = String(error).includes("claimed by another active session");
1187
+ patchConflict = String(error).includes("is claimed by session");
1165
1188
  }
1166
1189
  check("apply_patch claims all targets atomically when one target conflicts", patchConflict);
1167
1190
  todo("s-claim-c", item("edit unclaimed file", "in_progress"));
@@ -1236,7 +1259,7 @@ let liveClaimBlocked = false;
1236
1259
  try {
1237
1260
  await takeoverBefore?.({ tool: "edit", sessionID: "s-claimant", callID: "live-blocked" }, { args: { filePath: join(takeoverDir, "live.ts"), content: "c" } });
1238
1261
  } catch (error) {
1239
- liveClaimBlocked = String(error).includes("claimed by another active session");
1262
+ liveClaimBlocked = String(error).includes("is claimed by session");
1240
1263
  }
1241
1264
  check("a live owner without an idle timestamp keeps its claim", liveClaimBlocked);
1242
1265
  await takeoverAfter?.({ tool: "edit", sessionID: "s-live-owner", callID: "live-claim", args: {} }, { title: "edit", output: "edited", metadata: {} });
@@ -1255,7 +1278,7 @@ let refreshClaimBlocked = false;
1255
1278
  try {
1256
1279
  await takeoverBefore?.({ tool: "edit", sessionID: "s-claimant", callID: "refresh-conflict" }, { args: { filePath: join(takeoverDir, "refresh.ts"), content: "f" } });
1257
1280
  } catch (error) {
1258
- refreshClaimBlocked = String(error).includes("claimed by another active session");
1281
+ refreshClaimBlocked = String(error).includes("is claimed by session");
1259
1282
  }
1260
1283
  check("a same-session re-claim refreshes past the owner's idle so it is not taken over mid-turn", refreshClaimBlocked);
1261
1284
  await takeoverAfter?.({ tool: "edit", sessionID: "s-stale-owner", callID: "refresh-claim-2", args: {} }, { title: "edit", output: "edited", metadata: {} });
@@ -1300,6 +1323,59 @@ await takeoverAfter?.({ tool: "edit", sessionID: "s-claimant", callID: "multi-ta
1300
1323
  const takeoverAudits = getRecentAuditEntries(30).filter((entry) => entry.reason === "stale_claim_takeover" && typeof entry.evidence?.targetPath === "string" && entry.evidence.targetPath.includes("multi-"));
1301
1324
  check("each released stale path has its own audited takeover entry", takeoverAudits.length === 2 && takeoverAudits.every((entry) => entry.evidence?.claimOwnerSessionID === "s-stale-owner"));
1302
1325
 
1326
+ // File-claim TTL reclaim (missed idle release with no readable owner record):
1327
+ // a claim older than the effective TTL cannot belong to an in-flight call, so
1328
+ // it is released with an audited reclaim. A fresh claim still blocks and the
1329
+ // block advertises the reclaim step.
1330
+ console.log("- File-claim TTL reclaim -");
1331
+ const ttlDir = mkdtempSync(join(tmpdir(), "wg-claim-ttl-"));
1332
+ writeFileSync(join(ttlDir, "ttl.ts"), "before");
1333
+ const ttlHooks = await pluginFn({
1334
+ directory: ttlDir,
1335
+ client: fakeClient as any,
1336
+ project: {} as any,
1337
+ worktree: ttlDir,
1338
+ experimental_workspace: {} as any,
1339
+ serverUrl: new URL("http://localhost:4096"),
1340
+ $: undefined as any,
1341
+ });
1342
+ const ttlBefore = ttlHooks["tool.execute.before"];
1343
+ const ttlAfter = ttlHooks["tool.execute.after"];
1344
+ todo("s-ttl-owner", item("edit ttl file", "in_progress"));
1345
+ todo("s-ttl-claimant", item("take over ttl claim", "in_progress"));
1346
+ await recordRead(ttlBefore, ttlAfter, "s-ttl-owner", join(ttlDir, "ttl.ts"), "ttl-read-owner");
1347
+ await ttlBefore?.({ tool: "edit", sessionID: "s-ttl-owner", callID: "ttl-claim" }, { args: { filePath: join(ttlDir, "ttl.ts"), content: "a" } });
1348
+ const previousClaimTtl = process.env.WORKFLOW_GUARD_CLAIM_TTL_MS;
1349
+ process.env.WORKFLOW_GUARD_CLAIM_TTL_MS = "25";
1350
+ check("claim TTL honours the environment override", fileClaimTtlMs(ttlDir) === 25);
1351
+ await recordRead(ttlBefore, ttlAfter, "s-ttl-claimant", join(ttlDir, "ttl.ts"), "ttl-read-claimant");
1352
+ let freshTtlBlocked = false;
1353
+ try {
1354
+ await ttlBefore?.({ tool: "edit", sessionID: "s-ttl-claimant", callID: "ttl-blocked" }, { args: { filePath: join(ttlDir, "ttl.ts"), content: "b" } });
1355
+ } catch (error) {
1356
+ freshTtlBlocked = String(error).includes("is claimed by session") && String(error).includes("Reclaim step");
1357
+ }
1358
+ check("a claim within the TTL still blocks and names the reclaim step", freshTtlBlocked);
1359
+ await new Promise((resolve) => setTimeout(resolve, 60));
1360
+ let expiredTtlAllowed = true;
1361
+ try {
1362
+ await ttlBefore?.({ tool: "edit", sessionID: "s-ttl-claimant", callID: "ttl-reclaimed" }, { args: { filePath: join(ttlDir, "ttl.ts"), content: "c" } });
1363
+ } catch {
1364
+ expiredTtlAllowed = false;
1365
+ }
1366
+ check("an expired claim is reclaimed for the next claimant", expiredTtlAllowed);
1367
+ const ttlAudit = getRecentAuditEntries(40).find((entry) => entry.reason === "claim_ttl_expired" && typeof entry.evidence?.targetPath === "string" && entry.evidence.targetPath.endsWith("ttl.ts"));
1368
+ check("TTL reclaim is audited with the released path, owner, and age", ttlAudit?.decision === "allow" && ttlAudit.evidence?.claimOwnerSessionID === "s-ttl-owner" && typeof ttlAudit.evidence?.claimAgeMs === "number" && ttlAudit.evidence.claimAgeMs >= 25);
1369
+ await ttlAfter?.({ tool: "edit", sessionID: "s-ttl-claimant", callID: "ttl-reclaimed", args: {} }, { title: "edit", output: "edited", metadata: {} });
1370
+ if (previousClaimTtl === undefined) delete process.env.WORKFLOW_GUARD_CLAIM_TTL_MS;
1371
+ else process.env.WORKFLOW_GUARD_CLAIM_TTL_MS = previousClaimTtl;
1372
+ const ttlConfigDir = mkdtempSync(join(tmpdir(), "wg-claim-ttl-cfg-"));
1373
+ mkdirSync(join(ttlConfigDir, ".opencode"), { recursive: true });
1374
+ writeFileSync(join(ttlConfigDir, ".opencode", "workflow-guard.json"), JSON.stringify({ claimTtlMs: 1234 }));
1375
+ reloadProjectConfig(ttlConfigDir);
1376
+ check("project config claimTtlMs sets the claim TTL", fileClaimTtlMs(ttlConfigDir) === 1234);
1377
+ check("default claim TTL is five minutes", DEFAULT_FILE_CLAIM_TTL_MS === 300_000);
1378
+
1303
1379
  // Fail-closed: no session lookup on the client, and a lookup that throws.
1304
1380
  const noLookupDir = mkdtempSync(join(tmpdir(), "wg-claim-nolookup-"));
1305
1381
  writeFileSync(join(noLookupDir, "file.ts"), "before");
@@ -1315,7 +1391,7 @@ let noLookupBlocked = false;
1315
1391
  try {
1316
1392
  await noLookupBefore?.({ tool: "edit", sessionID: "s-nolookup-claimant", callID: "nolookup-claimant" }, { args: { filePath: join(noLookupDir, "file.ts"), content: "b" } });
1317
1393
  } catch (error) {
1318
- noLookupBlocked = String(error).includes("claimed by another active session");
1394
+ noLookupBlocked = String(error).includes("is claimed by session");
1319
1395
  }
1320
1396
  check("stale takeover fails closed when the client has no session lookup", noLookupBlocked);
1321
1397
 
@@ -1333,7 +1409,7 @@ let throwLookupBlocked = false;
1333
1409
  try {
1334
1410
  await throwLookupBefore?.({ tool: "edit", sessionID: "s-throwlookup-claimant", callID: "throwlookup-claimant" }, { args: { filePath: join(throwLookupDir, "file.ts"), content: "b" } });
1335
1411
  } catch (error) {
1336
- throwLookupBlocked = String(error).includes("claimed by another active session");
1412
+ throwLookupBlocked = String(error).includes("is claimed by session");
1337
1413
  }
1338
1414
  check("stale takeover fails closed when the session lookup throws", throwLookupBlocked);
1339
1415
 
@@ -3605,6 +3681,17 @@ check("plugin registers guard_audit tool", typeof customPlugin.tool?.guard_audit
3605
3681
  check("plugin registers guard_why tool", typeof customPlugin.tool?.guard_why?.execute === "function");
3606
3682
  check("plugin registers record_review tool", typeof customPlugin.tool?.record_review?.execute === "function");
3607
3683
 
3684
+ // G2 regression: record_review is offered to every session regardless of the
3685
+ // review gate, so the only thing that can withhold it is the host's per-agent
3686
+ // permission list. A reviewer agent with a deny-all list must be granted it in
3687
+ // its own frontmatter; the guard cannot inject it past host permissions.
3688
+ const noReviewRoot = mkdtempSync(join(tmpdir(), "wg-record-review-gate-off-"));
3689
+ mkdirSync(join(noReviewRoot, ".opencode"), { recursive: true });
3690
+ writeFileSync(join(noReviewRoot, ".opencode", "workflow-guard.json"), JSON.stringify({ requireReview: false }));
3691
+ const noReviewPlugin = await (defaultExport?.server ?? WorkflowGuard)({ directory: noReviewRoot, worktree: noReviewRoot, client: fakeClient as any, project: {} as any, experimental_workspace: {} as any, serverUrl: new URL("http://localhost:4096"), $: undefined as any });
3692
+ check("record_review stays registered with the review gate off, so only host permissions gate the call", typeof noReviewPlugin.tool?.record_review?.execute === "function" && typeof noReviewPlugin.tool?.record_review?.description === "string");
3693
+ rmSync(noReviewRoot, { recursive: true, force: true });
3694
+
3608
3695
  const statusResult = await customPlugin.tool?.guard_status?.execute({}, {} as any);
3609
3696
  check("guard_status executes and returns JSON string", typeof statusResult === "string" && statusResult.includes("workspaceRoot"));
3610
3697
  const parsedStatus = JSON.parse(statusResult as string);
@@ -3624,6 +3711,37 @@ const requirementsPlugin = await (defaultExport?.server ?? WorkflowGuard)({ dire
3624
3711
  setWorkspaceRoot(root);
3625
3712
  const requirementsStatus = JSON.parse(String(await requirementsPlugin.tool?.guard_status?.execute({}, {} as any)));
3626
3713
  check("guard_status reports configured unsatisfied requirements directly", requirementsStatus.workspaceRoot === requirementsRoot && ["verification", "review", "documentation"].every((requirement) => requirementsStatus.outstandingRequirements.includes(requirement)));
3714
+ check(
3715
+ "guard_status names the project config file it read",
3716
+ typeof requirementsStatus.projectConfig.configPath === "string" &&
3717
+ requirementsStatus.projectConfig.configPath.endsWith("/.opencode/workflow-guard.json") &&
3718
+ requirementsStatus.projectConfig.verifyCommand === "node -e 'process.exit(0)'" &&
3719
+ requirementsStatus.projectConfig.verifyCommandSource === "project-config",
3720
+ );
3721
+
3722
+ const noConfigRoot = mkdtempSync(join(tmpdir(), "wg-status-no-config-"));
3723
+ spawnSync("git", ["init", "-b", "feature/no-config"], { cwd: noConfigRoot });
3724
+ const noConfigPlugin = await (defaultExport?.server ?? WorkflowGuard)({ directory: noConfigRoot, worktree: noConfigRoot, client: fakeClient as any, project: {} as any, experimental_workspace: {} as any, serverUrl: new URL("http://localhost:4096"), $: undefined as any });
3725
+ const noConfigStatus = JSON.parse(String(await noConfigPlugin.tool?.guard_status?.execute({}, {} as any)));
3726
+ check(
3727
+ "guard_status distinguishes no config and no detectable verify command",
3728
+ noConfigStatus.projectConfig.configPath === null && noConfigStatus.projectConfig.verifyCommand === null && noConfigStatus.projectConfig.verifyCommandSource === null,
3729
+ );
3730
+
3731
+ const autoDetectRoot = mkdtempSync(join(tmpdir(), "wg-status-autodetect-"));
3732
+ spawnSync("git", ["init", "-b", "feature/autodetect"], { cwd: autoDetectRoot });
3733
+ writeFileSync(join(autoDetectRoot, "package.json"), JSON.stringify({ scripts: { test: "node -e 'process.exit(0)'" } }));
3734
+ const autoDetectPlugin = await (defaultExport?.server ?? WorkflowGuard)({ directory: autoDetectRoot, worktree: autoDetectRoot, client: fakeClient as any, project: {} as any, experimental_workspace: {} as any, serverUrl: new URL("http://localhost:4096"), $: undefined as any });
3735
+ const autoDetectStatus = JSON.parse(String(await autoDetectPlugin.tool?.guard_status?.execute({}, {} as any)));
3736
+ check(
3737
+ "guard_status attributes an auto-detected verify command to detection, not config",
3738
+ autoDetectStatus.projectConfig.configPath === null && autoDetectStatus.projectConfig.verifyCommand === "npm test" && autoDetectStatus.projectConfig.verifyCommandSource === "auto-detected",
3739
+ );
3740
+ check("verifyCommandSource reports project config directly", verifyCommandSource(requirementsRoot) === "project-config" && verifyCommandSource(autoDetectRoot) === "auto-detected" && verifyCommandSource(noConfigRoot) === null);
3741
+ check("existingProjectConfigPath returns null-ish for a repo without config", existingProjectConfigPath(noConfigRoot) === undefined);
3742
+ rmSync(noConfigRoot, { recursive: true, force: true });
3743
+ rmSync(autoDetectRoot, { recursive: true, force: true });
3744
+ reloadProjectConfig(root);
3627
3745
 
3628
3746
  const conflictingConfigRoot = mkdtempSync(join(tmpdir(), "wg-status-conflicting-config-"));
3629
3747
  mkdirSync(join(conflictingConfigRoot, ".opencode"), { recursive: true });
@@ -4581,6 +4699,16 @@ const linkedAbsoluteWrite = await call("bash", { command: `echo x > ${join(wtRep
4581
4699
  check("an absolute target in the primary checkout stays allowed from a linked worktree", !blocked(linkedAbsoluteWrite));
4582
4700
  const linkedOutsideWrite = await call("bash", { command: `echo x > ${join(foreignWtRepo, "outside.txt")}`, workdir: wtLinked }, { sessionID: "s-wt-foreign", worktree: wtRepo, directory: wtRepo });
4583
4701
  check("an absolute target outside both checkouts is still blocked from a linked worktree", blocked(linkedOutsideWrite));
4702
+ // A session bound to the primary checkout must not silently edit into a sibling
4703
+ // worktree. The mutation still stays refused (a tool-call path never re-anchors
4704
+ // the boundary), but the block names the mismatch and the host move, or the
4705
+ // agent works around the guard through the shell.
4706
+ todo("s-wt-mismatch", item("edit in the linked worktree", "in_progress"));
4707
+ const mismatchWrite = await call("write", { filePath: join(wtLinked, "mismatch.ts"), content: "x" }, { sessionID: "s-wt-mismatch", worktree: wtRepo, directory: wtRepo });
4708
+ check(
4709
+ "an edit into a linked worktree names the worktree mismatch and the move",
4710
+ blocked(mismatchWrite) && String(mismatchWrite).includes(wtLinked) && String(mismatchWrite).includes("session_move"),
4711
+ );
4584
4712
 
4585
4713
  // An in-command `cd` moves the tree later segments run in, so the walk has to
4586
4714
  // follow it. Judging every segment against the shell's initial `workdir` let
@@ -7908,5 +8036,138 @@ const serverEventTypes = new Set<string>([...EventManifest.ServerDefinitions].ma
7908
8036
  await runWithRuntimeState(root, bothClient, () => clearContinuationState(bothSession));
7909
8037
  }
7910
8038
 
8039
+ // E7: the subscription's `types` filter is a host-side narrowing, so a type
8040
+ // missing from the list is never delivered and its feature becomes dead code
8041
+ // that still compiles. Assert the list matches the handler's comparisons in
8042
+ // both directions, and that every entry is actually delivered.
8043
+ {
8044
+ const { V2_EVENT_TYPES } = v2EventModule;
8045
+ const pluginSource = readFileSync("src/lib/v2-plugin.ts", "utf8");
8046
+ const handled = new Set(
8047
+ [...pluginSource.matchAll(/event\??\.type\s*(?:===|!==)\s*"([^"]+)"/g)].map((match) => match[1]),
8048
+ );
8049
+ const subscribed = new Set<string>(V2_EVENT_TYPES);
8050
+ const missingFromFilter = [...handled].filter((type) => !subscribed.has(type));
8051
+ const unusedInHandler = [...subscribed].filter((type) => !handled.has(type));
8052
+ // The scan is a regex, so a refactor to `switch (event.type)` would match
8053
+ // nothing and leave both checks green while every feature went dead. Assert
8054
+ // it matched real comparisons, matching the E5 block's non-vacuity guard.
8055
+ check("the event-type scan matched real handler comparisons", handled.size >= 5);
8056
+ check("the event filter covers every type the handler acts on", missingFromFilter.length === 0);
8057
+ check("the event filter names no type the handler ignores", unusedInHandler.length === 0);
8058
+ if (missingFromFilter.length > 0) console.log(` not subscribed: ${missingFromFilter.join(", ")}`);
8059
+ if (unusedInHandler.length > 0) console.log(` subscribed but unhandled: ${unusedInHandler.join(", ")}`);
8060
+ const undeliveredFilter = [...subscribed].filter((type) => !serverEventTypes.has(type));
8061
+ check("every filtered event type is in EventManifest.ServerDefinitions", undeliveredFilter.length === 0);
8062
+ check("the event filter keeps both idle triggers", subscribed.has("session.status") && subscribed.has("session.idle"));
8063
+ }
8064
+
8065
+ // E8: an interrupted session cancels a guard tool that has not started yet.
8066
+ // The host supplies `signal` per call on V2; a tool that ignores it runs to its
8067
+ // own timeout after the user has already stopped the session.
8068
+ {
8069
+ const abortRoot = mkdtempSync(join(tmpdir(), "wg-tool-signal-"));
8070
+ mkdirSync(join(abortRoot, ".opencode"));
8071
+ const tools = createCustomTools({
8072
+ effectiveRoot: abortRoot,
8073
+ projectMemoryEnabled: false,
8074
+ learningEnabled: false,
8075
+ projectMemory: undefined,
8076
+ followupStore: undefined,
8077
+ portableMemoryPath: join(abortRoot, "memory.jsonl"),
8078
+ learningInterventions: new Map(),
8079
+ client: fakeClient,
8080
+ });
8081
+ const cancel = new AbortController();
8082
+ cancel.abort();
8083
+ const callTool = async (name: string, input: unknown, signal?: AbortSignal) => {
8084
+ const definition = (tools as Record<string, any>)[name];
8085
+ return await definition.execute(input, { sessionID: "s-abort", directory: abortRoot, ...(signal ? { signal } : {}) });
8086
+ };
8087
+ const aborted = await callTool("guard_worktree_create", { branch: "feat/never-created" }, cancel.signal);
8088
+ check("an aborted call cancels a worktree creation before it runs", String(aborted).includes("Cancelled"));
8089
+ const abortedCleanup = await callTool("guard_worktree_cleanup", { worktreePath: join(abortRoot, "nope") }, cancel.signal);
8090
+ check("an aborted call cancels a worktree cleanup before it runs", String(abortedCleanup).includes("Cancelled"));
8091
+ const abortedRubric = await callTool("guard_review_rubric", {}, cancel.signal);
8092
+ check("an aborted call cancels the diff-spawning rubric before it runs", String(abortedRubric).includes("Cancelled"));
8093
+ // A live signal must not change behavior: the guard's own gates still run.
8094
+ const live = new AbortController();
8095
+ const liveRubric = await callTool("guard_review_rubric", {}, live.signal);
8096
+ check("a live signal leaves the rubric path unchanged", !String(liveRubric).includes("Cancelled"));
8097
+ // OpenCode 1 names the same signal `abort`, so honoring only `signal` would
8098
+ // leave an interrupted V1 session running to its timeout.
8099
+ const abortedViaAbortKey = await (tools as Record<string, any>).guard_review_rubric.execute(
8100
+ {},
8101
+ { sessionID: "s-abort", directory: abortRoot, abort: cancel.signal },
8102
+ );
8103
+ check("an aborted call is cancelled through the V1 `abort` key", String(abortedViaAbortKey).includes("Cancelled"));
8104
+ // Recovery restore spawns git too, and it is only registered when the
8105
+ // project enables checkpoints, so cover it under its own config.
8106
+ writeFileSync(join(abortRoot, ".opencode", "workflow-guard.json"), JSON.stringify({ recoveryCheckpoints: true }));
8107
+ const recoveryTools = createCustomTools({
8108
+ effectiveRoot: abortRoot,
8109
+ projectMemoryEnabled: false,
8110
+ learningEnabled: false,
8111
+ projectMemory: undefined,
8112
+ followupStore: undefined,
8113
+ portableMemoryPath: join(abortRoot, "memory.jsonl"),
8114
+ learningInterventions: new Map(),
8115
+ client: fakeClient,
8116
+ });
8117
+ const abortedRecovery = await (recoveryTools as Record<string, any>).guard_recovery_restore.execute(
8118
+ { run: 1 },
8119
+ { sessionID: "s-abort", directory: abortRoot, signal: cancel.signal },
8120
+ );
8121
+ check("an aborted call cancels a recovery restore before it runs", String(abortedRecovery).includes("Cancelled"));
8122
+ rmSync(abortRoot, { recursive: true, force: true });
8123
+ }
8124
+
8125
+ // E9: the title settle wait ends as soon as the host renames the session,
8126
+ // instead of always sleeping the full poll interval. `session.renamed` is
8127
+ // delivered when the title commits; the model-request `title` hook runs before
8128
+ // the write, so it cannot report this.
8129
+ {
8130
+ const renameSession = "s-v2-rename-wake";
8131
+ todo(renameSession, item("unfinished work", "pending"));
8132
+ const racedPrompts: string[] = [];
8133
+ // The fake title reflects host state: it stays the placeholder until the
8134
+ // rename event lands, exactly as the real async title generation behaves.
8135
+ let titleSettled = false;
8136
+ let reads = 0;
8137
+ const racedClient = {
8138
+ session: {
8139
+ todo: async ({ path }: { path: { id: string } }) => ({ data: fakeTodos.get(path.id) ?? [] }),
8140
+ get: async ({ path }: { path: { id: string } }) => {
8141
+ reads++;
8142
+ const title = titleSettled ? "Native generated title" : "New session - 2026-08-27T12:00:00.000Z";
8143
+ return { data: { id: path.id, parentID: fakeParents.get(path.id), title } };
8144
+ },
8145
+ promptAsync: async ({ path }: { path: { id: string } }) => { racedPrompts.push(path.id); },
8146
+ },
8147
+ };
8148
+ const racedState = {
8149
+ effectiveRoot: root,
8150
+ client: racedClient,
8151
+ toolLifecycle: new ToolInvocationLifecycle(),
8152
+ toolOutcomes: new ToolOutcomeTracker(),
8153
+ };
8154
+ const started = Date.now();
8155
+ const continuation = handleV2Event(
8156
+ { type: "session.status", data: { sessionID: renameSession, status: { type: "idle" } } },
8157
+ racedState as any,
8158
+ );
8159
+ // The settle loop reads the session before it waits, so a read means the
8160
+ // waiter is registered. Firing the rename before that would test a gap the
8161
+ // real host cannot hit, because title generation is always slower.
8162
+ while (reads === 0) await new Promise((resolve) => setTimeout(resolve, 1));
8163
+ titleSettled = true;
8164
+ await handleV2Event({ type: "session.renamed", data: { sessionID: renameSession, title: "Native generated title" } }, racedState as any);
8165
+ await continuation;
8166
+ const elapsed = Date.now() - started;
8167
+ check("a session rename wakes the pending title settle", elapsed < 200);
8168
+ check("the woken continuation still delivers its prompt", racedPrompts.join(",") === renameSession);
8169
+ await runWithRuntimeState(root, racedClient, () => clearContinuationState(renameSession));
8170
+ }
8171
+
7911
8172
  console.log(`\n${pass} passed, ${fail} failed`);
7912
8173
  process.exitCode = fail ? 1 : 0;