opencode-workflow-guard 1.20.0 → 1.20.3

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
@@ -89,6 +89,7 @@ import {
89
89
  stripJsonComments,
90
90
  extractInterpreterPayload,
91
91
  isBranchAlreadyMergedOrClosed,
92
+ purgesMergedRemoteBranches,
92
93
  checkMergeConflicts,
93
94
  checkBranchBaseIsUpToDate,
94
95
  findWorktreeForBranch,
@@ -110,6 +111,7 @@ import {
110
111
  getSubagentMutationBudget,
111
112
  isReadOnlyRole,
112
113
  checkInteractiveTtyCommand,
114
+ shellHasSudoWrapper,
113
115
  checkPackageHygiene,
114
116
  delegationSpawnIn,
115
117
  sendDesktopNotification,
@@ -153,7 +155,7 @@ import { WorkflowGuardTui, WorkflowGuardTuiV2, formatBadge, readProjectOption, r
153
155
  import { scanSessionTodos, toolPartName, detectTodoCapability, recordedTodoCapability, recordTodoCapability, reportTodoGateFailOpen, resetTodoCapabilityForTesting } from "../src/lib/v2-todo.ts";
154
156
  import { buildPolicyPosture, renderPolicyPosture } from "../src/lib/policy-posture.ts";
155
157
  import { pluginKeyFor, preparePluginUpdate } from "../src/lib/config-writer.mjs";
156
- import { effectiveTodosWithOwner, isReadOnlyTodo, readOnlyTodoCompletions, recordTodoTaskStarts, todoEvidenceReport, unverifiedTodoCompletions, validateTodoLifecycle } from "../src/policies/todo.ts";
158
+ import { effectiveTodosWithOwner, inspectTodoLifecycle, isReadOnlyTodo, readOnlyTodoCompletions, recordTodoTaskStarts, todoEvidenceReport, unverifiedTodoCompletions, validateTodoLifecycle } from "../src/policies/todo.ts";
157
159
  import {
158
160
  LiveDocsResearchFloor,
159
161
  clearLiveDocsFloor,
@@ -412,6 +414,58 @@ check("completion evidence: a task that is only the marker has no identity and i
412
414
  check("lifecycle: appending the read-only marker to a planned task is not a silent deletion", !validateTodoLifecycle([item("Review the diff [read-only]", "completed")], [item("Review the diff", "in_progress")]));
413
415
  check("lifecycle: appending the marker to a still-active task retains it", !validateTodoLifecycle([item("Review the diff [read-only]", "in_progress")], [item("Review the diff", "in_progress")]));
414
416
 
417
+ // A sharpened task is the same work item, not a dropped one. A removed active
418
+ // task whose tokens all survive in an active successor is a refinement. The
419
+ // three shapes below are lifted from the audit journal's todo_lifecycle reasons.
420
+ check("lifecycle: added wording in a reworded task is a refinement", !validateTodoLifecycle([item("Verify the doc change, pass review, and open its PR", "in_progress")], [item("Verify the doc change and open its PR", "in_progress")]));
421
+ check("lifecycle: a reworded PR task with a new preposition is a refinement", !validateTodoLifecycle([item("Push the branch, open PR for #245 with Fixes #245", "in_progress")], [item("Push the branch, open PR #245 with Fixes #245", "in_progress")]));
422
+ check("lifecycle: a prefixed clause on an existing task is a refinement", !validateTodoLifecycle([item("Re-run review, record verdict, open PR for issue #42 and clean up the branch", "in_progress")], [item("Open PR for issue #42 and clean up the branch", "in_progress")]));
423
+ // The strict boundary still holds: no token superset means no refinement.
424
+ check("lifecycle: an unrelated equal-length replacement still blocks", !!validateTodoLifecycle([item("Run the test suite", "in_progress")], [item("Write the release notes", "in_progress")]));
425
+ check("lifecycle: a removed task with no successor still blocks", !!validateTodoLifecycle([item("other work", "in_progress")], [item("Write the release notes", "in_progress")]));
426
+ check("lifecycle: a one-word reword stays strict", !!validateTodoLifecycle([item("tests", "in_progress")], [item("tests please", "in_progress")]));
427
+ check("lifecycle: one successor cannot absorb two removed tasks", !!validateTodoLifecycle([item("deploy the service", "in_progress")], [item("write the fix, then deploy the service", "in_progress"), item("deploy the service", "in_progress")]));
428
+
429
+ // A refinement keeps the predecessor's mutation window, so recorded work still
430
+ // vouches for the reworded task. The pairing is the lifecycle verdict's, so the
431
+ // window carry and the completion gate cannot disagree about it.
432
+ const refinePrev = [item("Verify the doc change and open its PR", "in_progress")];
433
+ const refineNext = [item("Verify the doc change, pass review, and open its PR", "in_progress")];
434
+ const refinePairing = inspectTodoLifecycle(refineNext, refinePrev).refinements;
435
+ check("lifecycle: the refinement verdict names its predecessor and successor", refinePairing.length === 1 && refinePairing[0]!.from === "Verify the doc change and open its PR" && refinePairing[0]!.to === "Verify the doc change, pass review, and open its PR");
436
+ const refineStarts = new Map<string, number>();
437
+ recordTodoTaskStarts(refineStarts, undefined, refinePrev, 0);
438
+ recordTodoTaskStarts(refineStarts, refinePrev, refineNext, 3, refinePairing);
439
+ check("refinement: the reworded task inherits the predecessor's window", refineStarts.get("Verify the doc change, pass review, and open its PR") === 0 && !refineStarts.has("Verify the doc change and open its PR"));
440
+ const refinedComplete = [item("Verify the doc change, pass review, and open its PR", "completed")];
441
+ check("refinement: the carried window vouches for the refined completion", unverifiedTodoCompletions(refinePrev, refinedComplete, refineStarts, 1, refinePairing).length === 0);
442
+ const preCarry = new Map([["Verify the doc change and open its PR", 2]]);
443
+ check("refinement: completion evidence sees the inherited window before the map moves", unverifiedTodoCompletions(refinePrev, refinedComplete, preCarry, 3, refinePairing).length === 0);
444
+ check("refinement: a carried window still needs a mutation inside it", JSON.stringify(unverifiedTodoCompletions(refinePrev, refinedComplete, preCarry, 2, refinePairing)) === JSON.stringify(["Verify the doc change, pass review, and open its PR"]));
445
+ const lateCarry = new Map([["Verify the doc change and open its PR", 5]]);
446
+ check("refinement: mutations before the inherited window never count", JSON.stringify(unverifiedTodoCompletions(refinePrev, refinedComplete, lateCarry, 5, refinePairing)) === JSON.stringify(["Verify the doc change, pass review, and open its PR"]));
447
+ check("refinement: a reword with no recorded work does not complete freely", JSON.stringify(unverifiedTodoCompletions(refinePrev, refinedComplete, new Map(), 0, refinePairing)) === JSON.stringify(["Verify the doc change, pass review, and open its PR"]));
448
+
449
+ // One predecessor cannot carry its window to two successors. The verdict pairs
450
+ // it once, and the window map follows that pairing rather than guessing again.
451
+ const splitPrev = [item("add the retry loop", "in_progress")];
452
+ const splitNext = [item("add the retry loop for uploads", "in_progress"), item("add the retry loop for downloads", "in_progress")];
453
+ const splitPairing = inspectTodoLifecycle(splitNext, splitPrev).refinements;
454
+ check("lifecycle: one predecessor pairs with one successor", splitPairing.length === 1 && splitPairing[0]!.toKey === "add the retry loop for uploads");
455
+ const splitStarts = new Map([["add the retry loop", 4]]);
456
+ recordTodoTaskStarts(splitStarts, splitPrev, splitNext, 9, splitPairing);
457
+ check("refinement: one predecessor's window carries to one successor only", splitStarts.get("add the retry loop for uploads") === 4 && splitStarts.get("add the retry loop for downloads") === 9);
458
+
459
+ // Two predecessors and two successors pair one-to-one, so neither window is
460
+ // guessed from the other. Each successor is matched by its own tokens.
461
+ const pairPrev = [item("write the parser", "in_progress"), item("run the parser tests", "in_progress")];
462
+ const pairNext = [item("write the parser and add fixtures", "in_progress"), item("run the parser tests and triage failures", "in_progress")];
463
+ const pairVerdict = inspectTodoLifecycle(pairNext, pairPrev).refinements;
464
+ check("lifecycle: two reworded tasks pair with two distinct successors", pairVerdict.length === 2 && new Set(pairVerdict.map((r) => r.fromKey)).size === 2 && new Set(pairVerdict.map((r) => r.toKey)).size === 2);
465
+ const pairStarts = new Map([["write the parser", 1], ["run the parser tests", 6]]);
466
+ recordTodoTaskStarts(pairStarts, pairPrev, pairNext, 8, pairVerdict);
467
+ check("refinement: each predecessor's window moves to its own successor", pairStarts.get("write the parser and add fixtures") === 1 && pairStarts.get("run the parser tests and triage failures") === 6);
468
+
415
469
  // Marker escape, and the transitions that are not new claims.
416
470
  check("completion evidence: the read-only marker is recognized", isReadOnlyTodo(item("Review the diff [read-only]", "completed")) && !isReadOnlyTodo(item("Review the diff", "completed")));
417
471
  check("completion evidence: a marked read-only task completes with no mutation", unverifiedTodoCompletions([item("Review the diff [read-only]", "in_progress")], [item("Review the diff [read-only]", "completed")], new Map(), 0).length === 0);
@@ -448,6 +502,15 @@ const auditBeforeBlocked = getRecentAuditEntries(50).filter((entry) => entry.rea
448
502
  await call("todowrite", { todos: [item("real work [read-only]", "completed"), item("brand new", "completed")] }, { sessionID: "s-evidence-audit-order" });
449
503
  check("a blocked todowrite does not journal a read-only completion", getRecentAuditEntries(50).filter((entry) => entry.reason === "todo_completed_read_only").length === auditBeforeBlocked);
450
504
 
505
+ // End to end: reworded work passes the lifecycle gate and leaves a trail, while
506
+ // a genuine removal is still refused.
507
+ todo("s-refine", item("Verify the doc change and open its PR", "in_progress"));
508
+ check("dispatcher allows a reworded active task", !(await call("todowrite", { todos: [item("Verify the doc change, pass review, and open its PR", "in_progress")] }, { sessionID: "s-refine" })));
509
+ const refineAudit = getRecentAuditEntries(50).filter((entry) => entry.reason === "todo_refined");
510
+ check("dispatcher journals the refinement", refineAudit.length > 0 && JSON.stringify((refineAudit.at(-1)?.input as { refinements?: unknown })?.refinements) === JSON.stringify([{ from: "Verify the doc change and open its PR", to: "Verify the doc change, pass review, and open its PR" }]));
511
+ todo("s-refine-drop", item("Write the release notes", "in_progress"));
512
+ check("dispatcher still blocks a genuine task removal", blocked(await call("todowrite", { todos: [item("Publish the release", "in_progress")] }, { sessionID: "s-refine-drop" })));
513
+
451
514
  // guard_status surfaces the requirement before it bites.
452
515
  todo("s-evidence-report", item("write the fix", "in_progress"), item("Review the diff [read-only]", "in_progress"), item("done already", "completed"));
453
516
  const evidenceReport = await todoEvidenceReport("s-evidence-report");
@@ -816,6 +879,142 @@ setWorkspaceRoot(repo); // point the guard at the repo
816
879
  check("on main: edit blocked (branch reason, todos active)", ((await call("edit", { filePath: join(repo, "a.ts"), content: "x" }, { sessionID: "s-active" })) ?? "").includes("protected branch"));
817
880
  check("on main: git commit blocked", blocked(await shell("git commit -m test")));
818
881
  check("on main: git merge blocked", blocked(await shell("git merge feature/x")));
882
+ // A fast-forward to the tracked upstream is the one history write that adds no
883
+ // unreviewed commit, so it must be allowed or a stale primary checkout can never
884
+ // sync (#145). The control cases keep the exemption narrow.
885
+ const ffBase = mkdtempSync(join(tmpdir(), "wg-ff-"));
886
+ const ffRemote = join(ffBase, "remote.git");
887
+ const ffRepo = join(ffBase, "repo");
888
+ const ffPeer = join(ffBase, "peer");
889
+ const ffGit = (...args: string[]) => spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.invalid", ...args], { encoding: "utf8" });
890
+ mkdirSync(ffRemote, { recursive: true });
891
+ spawnSync("git", ["init", "--bare", "-b", "main", ffRemote]);
892
+ spawnSync("git", ["init", "-b", "main", ffRepo]);
893
+ writeFileSync(join(ffRepo, "a.txt"), "a\n");
894
+ ffGit("-C", ffRepo, "add", "a.txt");
895
+ ffGit("-C", ffRepo, "commit", "-m", "init");
896
+ ffGit("-C", ffRepo, "remote", "add", "origin", ffRemote);
897
+ ffGit("-C", ffRepo, "push", "-u", "origin", "main");
898
+ spawnSync("git", ["clone", ffRemote, ffPeer]);
899
+ writeFileSync(join(ffPeer, "b.txt"), "b\n");
900
+ ffGit("-C", ffPeer, "add", "b.txt");
901
+ ffGit("-C", ffPeer, "commit", "-m", "advance");
902
+ ffGit("-C", ffPeer, "push", "origin", "main");
903
+ ffGit("-C", ffPeer, "branch", "side");
904
+ ffGit("-C", ffPeer, "push", "origin", "side");
905
+ ffGit("-C", ffRepo, "fetch", "origin");
906
+ ffGit("-C", ffRepo, "remote", "set-head", "origin", "main");
907
+ ffGit("-C", ffRepo, "branch", "feat/local");
908
+ setWorkspaceRoot(ffRepo);
909
+ check("on main: merge --ff-only of the tracked upstream allowed", !blocked(await shell("git merge --ff-only origin/main")));
910
+ check("on main: merge without --ff-only still blocked", blocked(await shell("git merge origin/main")));
911
+ check("on main: merge --ff-only of a local branch still blocked", blocked(await shell("git merge --ff-only feat/local")));
912
+ check("on main: merge --ff-only of a non-default remote branch still blocked", blocked(await shell("git merge --ff-only origin/side")));
913
+ check("on main: merge --ff-only with two operands blocked", blocked(await shell("git merge --ff-only origin/main origin/side")));
914
+ check("on main: rebase onto the tracked upstream allowed", !blocked(await shell("git rebase origin/main")));
915
+ check("on main: pull without --ff-only still blocked", blocked(await shell("git pull")));
916
+ check("on main: pull --ff-only allowed", !blocked(await shell("git pull --ff-only")));
917
+ check("on main: pull --ff-only under a rebase config allowed", !blocked(await shell("git -c pull.rebase=false pull --ff-only")));
918
+ check("on main: pull of a named remote branch still blocked", blocked(await shell("git pull --ff-only origin main")));
919
+ check("on main: pull --ff-only with a trailing -- blocked", blocked(await shell("git pull --ff-only --")));
920
+ check("on main: pull --ff-only of a rebasing config still allowed", !blocked(await shell("git -c pull.rebase=true pull --ff-only")));
921
+ // One shell word is what the guard reads, so quote concatenation and a quoted
922
+ // subcommand name must reach the same verdict as the plain form.
923
+ check("on main: quote-concatenated pull subcommand still allowed", !blocked(await shell("git pu''ll --ff-only")));
924
+ check("on main: quoted pull subcommand still allowed", !blocked(await shell('git "pull" --ff-only')));
925
+ check("on main: chained pull --ff-only still allowed", !blocked(await shell("git status >/dev/null && git pull --ff-only")));
926
+ check("on main: pull --ff-only in a chained cd is judged in that tree", !blocked(await shell(`cd ${ffRepo} && git pull --ff-only`)));
927
+ check("on main: -C the same checkout still fast-forwards", !blocked(await shell(`git -C ${ffRepo} merge --ff-only origin/main`)));
928
+ check("on main: -C the same checkout allows a pull", !blocked(await shell(`git -C ${ffRepo} pull --ff-only`)));
929
+ ffGit("-C", ffRepo, "commit", "--allow-empty", "-m", "local work");
930
+ check("on main: merge --ff-only blocked once the branch has diverged", blocked(await shell("git merge --ff-only origin/main")));
931
+ check("on main: rebase blocked once the branch has diverged", blocked(await shell("git rebase origin/main")));
932
+ check("on main: pull --ff-only blocked once the branch has diverged", blocked(await shell("git pull --ff-only")));
933
+ rmSync(ffBase, { recursive: true, force: true });
934
+ // A `pull` names no ref, so the guard derives the target from `@{u}`. That
935
+ // derivation must still prove the ref is remote-tracking; a local upstream is
936
+ // not a remote sync and stays blocked.
937
+ const ffLocalBase = mkdtempSync(join(tmpdir(), "wg-ff-local-"));
938
+ const ffLocalRepo = join(ffLocalBase, "repo");
939
+ spawnSync("git", ["init", "-b", "main", ffLocalRepo]);
940
+ writeFileSync(join(ffLocalRepo, "a.txt"), "a\n");
941
+ ffGit("-C", ffLocalRepo, "add", "a.txt");
942
+ ffGit("-C", ffLocalRepo, "commit", "-m", "c1");
943
+ ffGit("-C", ffLocalRepo, "branch", "feat/local-up");
944
+ ffGit("-C", ffLocalRepo, "switch", "feat/local-up");
945
+ writeFileSync(join(ffLocalRepo, "b.txt"), "b\n");
946
+ ffGit("-C", ffLocalRepo, "add", "b.txt");
947
+ ffGit("-C", ffLocalRepo, "commit", "-m", "c2");
948
+ ffGit("-C", ffLocalRepo, "switch", "main");
949
+ ffGit("-C", ffLocalRepo, "branch", "--set-upstream-to=feat/local-up", "main");
950
+ setWorkspaceRoot(ffLocalRepo);
951
+ check("on main: pull --ff-only from a local upstream branch stays blocked", blocked(await shell("git pull --ff-only")));
952
+ check("on main: merge --ff-only from the local upstream stays blocked", blocked(await shell("git merge --ff-only")));
953
+ rmSync(ffLocalBase, { recursive: true, force: true });
954
+ // The cleanup a merged PR requires used to be impossible for the agent: both
955
+ // halves were blocked whenever the checkout sat on the protected branch that
956
+ // received the merge. A merged-only delete publishes no commit, so it is
957
+ // exempt, and every form that could drop unmerged commits stays blocked.
958
+ const cleanupBase = mkdtempSync(join(tmpdir(), "wg-cleanup-"));
959
+ const cleanupRemote = join(cleanupBase, "remote.git");
960
+ const cleanupRepo = join(cleanupBase, "repo");
961
+ spawnSync("git", ["init", "--bare", "-b", "main", cleanupRemote]);
962
+ spawnSync("git", ["init", "-b", "main", cleanupRepo]);
963
+ writeFileSync(join(cleanupRepo, "a.txt"), "a\n");
964
+ ffGit("-C", cleanupRepo, "add", "a.txt");
965
+ ffGit("-C", cleanupRepo, "commit", "-m", "init");
966
+ ffGit("-C", cleanupRepo, "remote", "add", "origin", cleanupRemote);
967
+ ffGit("-C", cleanupRepo, "push", "-u", "origin", "main");
968
+ ffGit("-C", cleanupRepo, "branch", "feat/merged");
969
+ ffGit("-C", cleanupRepo, "push", "origin", "feat/merged");
970
+ ffGit("-C", cleanupRepo, "switch", "-c", "feat/unmerged");
971
+ writeFileSync(join(cleanupRepo, "b.txt"), "b\n");
972
+ ffGit("-C", cleanupRepo, "add", "b.txt");
973
+ ffGit("-C", cleanupRepo, "commit", "-m", "unmerged work");
974
+ ffGit("-C", cleanupRepo, "switch", "main");
975
+ ffGit("-C", cleanupRepo, "fetch", "origin");
976
+ setWorkspaceRoot(cleanupRepo);
977
+ check("on main: branch -d of a merged branch allowed", !blocked(await shell("git branch -d feat/merged")));
978
+ check("on main: branch --delete of a merged branch allowed", !blocked(await shell("git branch --delete feat/merged")));
979
+ check("on main: branch -D stays blocked", blocked(await shell("git branch -D feat/merged")));
980
+ check("on main: branch -d --force stays blocked", blocked(await shell("git branch -d --force feat/merged")));
981
+ check("on main: branch -d of a protected name stays blocked", blocked(await shell("git branch -d main")));
982
+ check("on main: branch --delete of a protected name stays blocked", blocked(await shell("git branch --delete main")));
983
+ check("on main: branch --delete --force stays blocked", blocked(await shell("git branch --delete --force feat/merged")));
984
+ check("on main: branch -fd stays blocked", blocked(await shell("git branch -fd feat/merged")));
985
+ check("on main: branch -rd of a merged branch allowed", !blocked(await shell("git branch -rd feat/merged")));
986
+ check("on main: branch -d with no branch named stays blocked", blocked(await shell("git branch -d")));
987
+ check("on main: ordinary push still blocked from the protected checkout", blocked(await shell("git push origin feat/merged")));
988
+ check("on main: delete of a merged remote branch allowed", !blocked(await shell("git push origin --delete feat/merged")));
989
+ check("on main: :refs/heads delete of a merged remote branch allowed", !blocked(await shell("git push origin :refs/heads/feat/merged")));
990
+ check("on main: delete of an unmerged remote branch blocked", blocked(await shell("git push origin --delete feat/unmerged")));
991
+ check("on main: :refspec delete of an unmerged remote branch blocked", blocked(await shell("git push origin :feat/unmerged")));
992
+ check("on main: delete of a protected remote branch blocked", blocked(await shell("git push origin --delete main")));
993
+ check("on main: push --prune stays blocked", blocked(await shell("git push origin --prune")));
994
+ check("on main: push --mirror stays blocked", blocked(await shell("git push --mirror origin")));
995
+ check("purge helper rejects a plain refspec", !purgesMergedRemoteBranches("git push origin feat/merged", cleanupRepo));
996
+ check("purge helper accepts a merged delete", purgesMergedRemoteBranches("git push origin --delete feat/merged", cleanupRepo));
997
+ check("purge helper rejects a tag refspec", !purgesMergedRemoteBranches("git push origin :refs/tags/feat/merged", cleanupRepo));
998
+ // A tag that shares the branch namespace must not satisfy the merged check.
999
+ // The helper names refs/heads and refs/remotes/origin explicitly, so the tag
1000
+ // alone resolves to nothing and the deletion stays blocked.
1001
+ ffGit("-C", cleanupRepo, "tag", "feat/onlytag", "main");
1002
+ check("purge helper rejects a tag short name with no branch of that name", !purgesMergedRemoteBranches("git push origin :feat/onlytag", cleanupRepo));
1003
+ check("on main: delete of a tag short name with no branch stays blocked", blocked(await shell("git push origin --delete feat/onlytag")));
1004
+ ffGit("-C", cleanupRepo, "branch", "-D", "feat/merged");
1005
+ check("on main: delete of a merged branch whose local ref is gone allowed", !blocked(await shell("git push origin --delete feat/merged")));
1006
+ // A configured protected name is protected here too, so the cleanup
1007
+ // exemption cannot become a way around `protectedBranches`.
1008
+ mkdirSync(join(cleanupRepo, ".opencode"), { recursive: true });
1009
+ writeFileSync(join(cleanupRepo, ".opencode", "workflow-guard.json"), JSON.stringify({ protectedBranches: ["feat/merged"] }));
1010
+ reloadProjectConfig(cleanupRepo);
1011
+ check("on main: branch -d of a configured protected branch blocked", blocked(await shell("git branch -d feat/merged")));
1012
+ check("on main: delete of a configured protected remote branch blocked", blocked(await shell("git push origin --delete feat/merged")));
1013
+ // The exemption must not become a way around the destination-side rule that
1014
+ // protects a configured branch from ordinary pushes.
1015
+ check("on main: ordinary push to a configured protected branch blocked", blocked(await shell("git push origin feat/merged")));
1016
+ rmSync(cleanupBase, { recursive: true, force: true });
1017
+ setWorkspaceRoot(repo);
819
1018
  check("on main: git checkout path mutation blocked", blocked(await shell("git checkout -- tracked.txt")));
820
1019
  check("on main: git checkout path mutation without separator blocked", blocked(await shell("git checkout tracked.txt")));
821
1020
  check("on main: git checkout -B reset blocked", blocked(await shell("git checkout -B main HEAD~1")));
@@ -5817,6 +6016,33 @@ check("checkInteractiveTtyCommand permits npm init --yes", !checkInteractiveTtyC
5817
6016
  check("checkInteractiveTtyCommand detects apt-get install without -y", checkInteractiveTtyCommand("apt-get install curl").isInteractive);
5818
6017
  check("checkInteractiveTtyCommand permits apt-get install -y", !checkInteractiveTtyCommand("apt-get install -y curl").isInteractive);
5819
6018
  check("checkInteractiveTtyCommand permits regular non-interactive command", !checkInteractiveTtyCommand("ls -la && git status").isInteractive);
6019
+ // Command position, not raw text: a pattern word in an argument is data.
6020
+ check("checkInteractiveTtyCommand permits sudo inside a grep pattern", !checkInteractiveTtyCommand(`grep -rn "sudo" docs/`).isInteractive);
6021
+ check("checkInteractiveTtyCommand permits an exact grep for sudo", !checkInteractiveTtyCommand("grep -n sudo file.txt").isInteractive);
6022
+ check("checkInteractiveTtyCommand permits sudo in a piped grep pattern", !checkInteractiveTtyCommand("journalctl --user -u x -n 20 --no-pager 2>&1 | grep -i sudo").isInteractive);
6023
+ check("checkInteractiveTtyCommand permits an interactive rebase pattern in a grep pattern", !checkInteractiveTtyCommand(`grep -n "git rebase -i" test/test.mts`).isInteractive);
6024
+ check("checkInteractiveTtyCommand permits npm init as grep data", !checkInteractiveTtyCommand(`grep -n "npm init" README.md`).isInteractive);
6025
+ check("checkInteractiveTtyCommand permits an editor name in a printf string", !checkInteractiveTtyCommand(`printf "%s\\n" "vim is not installed"`).isInteractive);
6026
+ check("checkInteractiveTtyCommand permits git log grep for interactive rebase", !checkInteractiveTtyCommand(`git log --grep="rebase -i"`).isInteractive);
6027
+ check("checkInteractiveTtyCommand permits a command name fed to a filter", !checkInteractiveTtyCommand(`echo "apt-get install curl" | cat`).isInteractive);
6028
+ // The same commands still block at command position.
6029
+ check("checkInteractiveTtyCommand still detects a chained editor", checkInteractiveTtyCommand("cd /repo && nano notes.txt").isInteractive);
6030
+ check("checkInteractiveTtyCommand still detects a shell -c editor", checkInteractiveTtyCommand("sh -c 'vim notes.txt'").isInteractive);
6031
+ check("checkInteractiveTtyCommand still detects eval npm init", checkInteractiveTtyCommand("eval 'npm init'").isInteractive);
6032
+ check("checkInteractiveTtyCommand still detects a wrapped sudo", checkInteractiveTtyCommand("env FOO=1 sudo ls").isInteractive);
6033
+ check("checkInteractiveTtyCommand still detects sudo before an editor", checkInteractiveTtyCommand("sudo vim notes.txt").isInteractive);
6034
+ check("checkInteractiveTtyCommand still detects a wrapped sudo before an editor", checkInteractiveTtyCommand("env A=1 sudo vim notes.txt").isInteractive);
6035
+ check("checkInteractiveTtyCommand still detects a timeout-wrapped sudo", checkInteractiveTtyCommand("timeout 5 sudo ls").isInteractive);
6036
+ check("checkInteractiveTtyCommand still detects sudo as a loop body", checkInteractiveTtyCommand("while true; do sudo ls; done").isInteractive);
6037
+ check("checkInteractiveTtyCommand still detects sudo after command", checkInteractiveTtyCommand("command sudo ls").isInteractive);
6038
+ check("checkInteractiveTtyCommand still detects git add -p", checkInteractiveTtyCommand("git add -p").isInteractive);
6039
+ check("checkInteractiveTtyCommand still detects yum install without -y", checkInteractiveTtyCommand("yum install curl").isInteractive);
6040
+ check("checkInteractiveTtyCommand still detects an apt install in a then body", checkInteractiveTtyCommand("if true; then apt-get install curl; fi").isInteractive);
6041
+ check("checkInteractiveTtyCommand still detects an apt install in a nested shell", checkInteractiveTtyCommand("bash -lc 'apt-get install curl'").isInteractive);
6042
+ check("checkInteractiveTtyCommand still detects busybox vi", checkInteractiveTtyCommand("busybox vi notes.txt").isInteractive);
6043
+ check("shellHasSudoWrapper reports a bare sudo", shellHasSudoWrapper("sudo ls"));
6044
+ check("shellHasSudoWrapper reports a sudo behind env", shellHasSudoWrapper("env FOO=1 sudo ls"));
6045
+ check("shellHasSudoWrapper ignores sudo as an argument", !shellHasSudoWrapper("grep -n sudo file.txt"));
5820
6046
 
5821
6047
  check("shell tool blocks nano", blocked(await shell("nano README.md")));
5822
6048
  check("shell tool blocks less", blocked(await shell("less package.json")));
@@ -7456,6 +7682,28 @@ try {
7456
7682
  "seat no longer denies a cwd-dependent push from a protected session checkout",
7457
7683
  protectedCheckoutSeat.effect === "abstain" && protectedCheckoutSeat.decision?.code === "repository_unidentified",
7458
7684
  );
7685
+ // `pull` is a history write only on a protected branch, and the seat cannot
7686
+ // see which checkout the command runs in, so it defers rather than blocking
7687
+ // a sync that a linked feature worktree would allow.
7688
+ const pullSeat = await evaluatePermissionSeat(
7689
+ { ...seatEvent(["git pull --ff-only"]), sessionID: "s-seat-pull" },
7690
+ { workspaceRoot: seatMainRepo, client: fakeClient as unknown },
7691
+ );
7692
+ check(
7693
+ "seat defers a cwd-dependent pull instead of judging the session checkout",
7694
+ pullSeat.effect === "abstain" && pullSeat.decision?.code === "repository_unidentified",
7695
+ );
7696
+ // An explicit `-C` puts the repository back in the command text, so the seat
7697
+ // judges it for real: a protected checkout with no upstream is a block, not
7698
+ // a deferral.
7699
+ const explicitPullSeat = await evaluatePermissionSeat(
7700
+ { ...seatEvent([`git -C ${seatMainRepo} pull --ff-only`]), sessionID: "s-seat-explicit-pull" },
7701
+ { workspaceRoot: seatMainRepo, client: fakeClient as unknown },
7702
+ );
7703
+ check(
7704
+ "seat still denies an explicitly named protected pull",
7705
+ explicitPullSeat.effect === "deny" && explicitPullSeat.decision?.policy === "git",
7706
+ );
7459
7707
  // A push whose DESTINATION is protected is a finding in every checkout, so
7460
7708
  // the workdir cannot change the verdict and the seat keeps its denial.
7461
7709
  const protectedDestSeat = await evaluatePermissionSeat(
@@ -8060,9 +8308,43 @@ const ocJson = "open" + "code.json";
8060
8308
  const ocJsonc = "open" + "code.jsonc";
8061
8309
  setWorkspaceRoot(root);
8062
8310
 
8063
- // Legacy (no live roots configured): the copy SOURCE under a config path alone
8064
- // blocks the command — the F3 false positive, pinned as current behavior.
8065
- check("legacy: cp FROM a .config/opencode source is blocked without live roots", blocked(await call("bash", { command: `cp ${livePlane}/agent/x.md ./draft.md` }, { sessionID: "s-active" })));
8311
+ // Legacy (no live roots configured): a copy-like verb reads its sources and
8312
+ // writes only its destination, so a guarded SOURCE alone is a read. This is the
8313
+ // F3 false positive, now allowed in both modes.
8314
+ const legacyCpFrom = (command: string) => call("bash", { command }, { sessionID: "s-active" });
8315
+ check("legacy: cp FROM a .config/opencode source is allowed without live roots", !blocked(await legacyCpFrom(`cp ${livePlane}/agent/x.md ./draft.md`)));
8316
+ check("legacy: cp FROM a .config/opencode source with a redirect is allowed", !blocked(await legacyCpFrom(`cp ${livePlane}/agent/x.md ./draft.md 2>/dev/null`)));
8317
+ check("legacy: a multi-source cp with one guarded source is allowed", !blocked(await legacyCpFrom(`cp ./notes.md ${livePlane}/agent/x.md ./draft.md`)));
8318
+ check("legacy: ln -s FROM a .config/opencode source is allowed", !blocked(await legacyCpFrom(`ln -s ${livePlane}/agent/x.md ./draft-link.md`)));
8319
+ check("legacy: cp -s FROM a .config/opencode source is allowed", !blocked(await legacyCpFrom(`cp -s ${livePlane}/agent/x.md ./draft-link.md`)));
8320
+ // A hard link is a second writable name for the guarded inode, so it stays a
8321
+ // mutation of the guarded file even when the link lands in the workspace.
8322
+ check("legacy: a hard link FROM a .config/opencode path is still blocked", blocked(await legacyCpFrom(`ln ${livePlane}/agent/x.md ./hard-link.md`)));
8323
+ check("legacy: cp -l FROM a .config/opencode path is still blocked", blocked(await legacyCpFrom(`cp -l ${livePlane}/agent/x.md ./hard-link.md`)));
8324
+ check("legacy: cp --link FROM a .config/opencode path is still blocked", blocked(await legacyCpFrom(`cp --link ${livePlane}/agent/x.md ./hard-link.md`)));
8325
+ // The true positives hold: a guarded destination is still a mutation.
8326
+ check("legacy: cp INTO a .config/opencode path is still blocked", blocked(await legacyCpFrom(`cp ./draft.md ${livePlane}/agent/x.md`)));
8327
+ check("legacy: cp with a guarded source and destination is still blocked", blocked(await legacyCpFrom(`cp ${livePlane}/agent/x.md ${livePlane}/agent/y.md`)));
8328
+ check("legacy: cp INTO a guarded path with a redirect is still blocked", blocked(await legacyCpFrom(`cp ./draft.md ${livePlane}/agent/x.md 2>/dev/null`)));
8329
+ check("legacy: cp -t a guarded directory is still blocked", blocked(await legacyCpFrom(`cp -t ${livePlane}/agent ./draft.md`)));
8330
+ check("legacy: cp --target-directory=a guarded directory is still blocked", blocked(await legacyCpFrom(`cp --target-directory=${livePlane}/agent ./draft.md`)));
8331
+ check("legacy: a multi-source cp into a guarded directory is still blocked", blocked(await legacyCpFrom(`cp ./a.md ./b.md ${livePlane}/agent`)));
8332
+ check("legacy: a wrapped cp into a guarded path is still blocked", blocked(await legacyCpFrom(`env FOO=1 cp ./draft.md ${livePlane}/agent/x.md`)));
8333
+ check("legacy: command-prefixed cp into a guarded path is still blocked", blocked(await legacyCpFrom(`command cp ./draft.md ${livePlane}/agent/x.md`)));
8334
+ check("legacy: fd duplication after a guarded cp destination is still blocked", blocked(await legacyCpFrom(`cp ./draft.md ${livePlane}/agent/x.md 2>&1`)));
8335
+ check("legacy: fd duplication before a guarded cp destination is still blocked", blocked(await legacyCpFrom(`cp ./draft.md 2>&1 ${livePlane}/agent/x.md`)));
8336
+ check("legacy: a discarded redirect before a guarded cp destination is still blocked", blocked(await legacyCpFrom(`cp ./draft.md >/dev/null 2>&1 ${livePlane}/agent/x.md`)));
8337
+ check("legacy: fd duplication does not mask a guarded redirect", blocked(await legacyCpFrom(`echo x 2>&1 > ${livePlane}/agent/x.md`)));
8338
+ check("legacy: fd duplication with no guarded path is allowed", !blocked(await legacyCpFrom(`cp ./draft.md ./copy.md 2>&1`)));
8339
+ check("legacy: ln -sfn FROM a .config/opencode source is allowed", !blocked(await legacyCpFrom(`ln -sfn ${livePlane}/agent/x.md ./draft-link.md`)));
8340
+ check("legacy: install -d -t a guarded directory is still blocked", blocked(await legacyCpFrom(`install -d -t ${livePlane}/plugins ./build`)));
8341
+ check("legacy: ln INTO a .config/opencode path is still blocked", blocked(await legacyCpFrom(`ln -s ./draft-link.md ${livePlane}/agent/x.md`)));
8342
+ check("legacy: install -d a guarded directory is still blocked", blocked(await legacyCpFrom(`install -d ${livePlane}/plugins`)));
8343
+ check("legacy: install -d a workspace directory is allowed", !blocked(await legacyCpFrom(`install -d ./build/out`)));
8344
+ // mv removes its source, so a guarded source stays a mutation.
8345
+ check("legacy: mv FROM a .config/opencode path is still blocked", blocked(await legacyCpFrom(`mv ${livePlane}/agent/x.md ./draft.md`)));
8346
+ check("legacy: tee INTO a .config/opencode path is still blocked", blocked(await legacyCpFrom(`echo x | tee ${livePlane}/agent/x.md`)));
8347
+ check("legacy: a redirect INTO a .config/opencode path is still blocked", blocked(await legacyCpFrom(`echo x > ${livePlane}/agent/x.md`)));
8066
8348
 
8067
8349
  // Declare the live control plane via project config, then reload.
8068
8350
  writeFileSync(join(lcpRoot, ".opencode", "workflow-guard.json"), JSON.stringify({ liveControlPlanePaths: [livePlane] }));