opencode-workflow-guard 1.20.1 → 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/docs/policies.md CHANGED
@@ -16,6 +16,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
16
16
  - **Pre-edit Gate:** All file-editing tools (`edit`, `write`, `apply_patch`) are blocked while the session's effective todo list is known and contains no active task. On OpenCode 1.x the list comes from the native todo system (`todowrite`, persisted at `GET /session/:id/todo`). Before 2.1.0, the OpenCode 2.x builtin tool registry has no `todowrite`, and there is no todo endpoint. The list is then reconstructed from the newest applied `todowrite` tool call in the session history, which ACP agents may supply. OpenCode 2.1.x reintroduces a builtin `todowrite` behind the `experimental.todo` config key. The guard detects that capability by probing the host tool registry rather than inferring it from history. Verified on 2.1.3: `ctx.tool.list()` exposes `todowrite` when the flag is on, and omits it when off. The gate distinguishes a **definitively empty** list from an **undeterminable** one. A definitively empty list means the capability exists and reports no active task, which stays blocked. An undeterminable list means no todo capability, or the history cannot be read. The gate then fails open and records that once per session at warn level. This keeps builtin-only V2 sessions usable instead of deadlocking every edit forever.
17
17
  - **Flexible Task Execution:** Tasks can be completed in any order as work concludes without artificial sequential blockers, maintaining maximum pair-programming DX.
18
18
  - **No Silent Deletion:** Each `todowrite` update replaces the complete list. Active tasks must remain in subsequent updates until they are explicitly marked `completed` or `cancelled`.
19
+ - **Refinement, not deletion:** An active task may be reworded when its replacement keeps every word of the original and adds at least one more. That is the same work item sharpened, so the write passes and the task keeps its original mutation window. Two distinct words is the floor, so a one-word task always needs an exact match. Each replacement absorbs at most one removed task. Every accepted refinement is journaled as `todo_refined`. A reword that drops or substitutes a word is still a removal and blocks.
19
20
  - **Per-Task Completion Evidence (enforced):** Because a `todowrite` call replaces the whole list, a model can mark work `completed` without doing it. A task may therefore enter `completed` only when the session recorded at least one file mutation inside that task's active window. One mutation cannot vouch for several completions, so N completions require N mutations counted from the earliest of them. Mutations spent before a task became active never count toward it. A blocked write names the task and the remedy. The check also runs in simulation, so `guard_why` predicts the gate instead of reporting a falsely permissive verdict. A finished or dropped task releases its window, so reusing the same task text starts clean. Tasks are matched to their prior occurrences by count, so duplicate text cannot hide a new completion behind an already-completed item. The mutation counter records permitted mutation calls, not confirmed byte changes.
20
21
  - **Planned late:** a task first observed already `completed` has no window to judge, so it is scored against the session's mutation history instead. This is the deliberate path for an agent that did the work before writing the list. It stays bounded by the one-mutation-per-completion rule.
21
22
  - **Read-only escape:** A task whose text carries `[read-only]`, also `[read_only]` or `[read only]`, completes without a mutation. Review, investigation, and reading are legitimate work that changes no file. The marker is an annotation, not part of task identity, so it can be appended to an already-planned task without reading as a deletion. Every use is journaled as `todo_completed_read_only`, so relabeling real work as read-only stays visible in the audit trail. In a repository with no detectable verify command, that journal is the only counterweight. Work that was deliberately dropped uses `cancelled` instead.
@@ -79,12 +80,14 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
79
80
  - Quoted data spans are not shell syntax. Pattern matching runs on the quote-stripped residue, where redirect targets are honored quoted or not, and quote-concatenated paths keep normalizing. A quoted span containing a guarded path is never treated as a redirect or command verb. Unquoted redirects into guarded paths stay blocked.
80
81
  - Plan files under `.opencode/plans/` are exempt: opencode's plan mode writes agent-authored plan markdown there, and plans are content, not configuration. Everything else under `.opencode/` (including the directory itself) stays protected.
81
82
  - **Read-only access is allowed** (`cat`, `less`, `grep`, `head`, `tail` on config files) - only modification attempts trigger the guard.
82
- - **Live control-plane facts (`liveControlPlanePaths`, opt-in):** Declare the absolute paths of the live control plane in `.opencode/workflow-guard.json` or via `WORKFLOW_GUARD_LIVE_CONTROL_PLANE_PATHS` (comma-separated). Examples are `~/.config/opencode` and the guard's own install. When set, config-path protection classifies by runtime consumption instead of filename segments. Only targets that resolve under a live root are protected (symlink-aware). Copying **from** a config path into a sanctioned workspace draft is therefore no longer blocked, because the copy destination is what matters. Versioned drafts such as a project `.opencode/` or a dotfiles `.config/opencode` are editable. Roots must be absolute (`~`/`$HOME` are expanded). An unusable root rejects the whole set and falls back to the legacy fail-closed segment matching. Unset keeps the legacy behavior.
83
+ - **Live control-plane facts (`liveControlPlanePaths`, opt-in):** Declare the absolute paths of the live control plane in `.opencode/workflow-guard.json` or via `WORKFLOW_GUARD_LIVE_CONTROL_PLANE_PATHS` (comma-separated). Examples are `~/.config/opencode` and the guard's own install. When set, config-path protection classifies by runtime consumption instead of filename segments. Only targets that resolve under a live root are protected (symlink-aware). Copying **from** a config path into a sanctioned workspace draft is therefore no longer blocked, because the copy destination is what matters. Versioned drafts such as a project `.opencode/` or a dotfiles `.config/opencode` are editable. Roots must be absolute (`~`/`$HOME` are expanded). An unusable root rejects the whole set and falls back to the legacy segment matching. Unset keeps the legacy behavior.
84
+ - **Copy sources in legacy mode:** Without declared roots, a copy-like verb (`cp`, `ln`, `install`) is judged by its destination operand. That is the last operand, or the `-t`/`--target-directory` value. A guarded path used only as a source is a read, so `cp ~/.config/opencode/templates/x ./draft.md` is allowed. A guarded destination still blocks, including through `-t`, `--target-directory=`, and `install -d`, because that mode creates every directory it names. A hard link is not a read, because it is a second writable name for the same inode: `ln` without `-s`, and `cp -l`/`--link`, keep the broad match. `mv` keeps the broad any-operand match, because the move removes its source. Every other mutating verb, and any copy whose destination cannot be identified, keeps the fail-closed behavior.
83
85
 
84
86
  ### 7. Feature-Branch Workflow
85
87
  - When the workspace git repository is on `main` or `master`, all file mutations and history-changing git commands are blocked. Those commands are `commit`, `merge`, `rebase`, `cherry-pick`, `revert`, `apply`, `am`, `reset`, `restore`, `stash pop`, `update-ref`, `filter-branch`, and `branch -D/-M`. A `pull` on the protected branch is blocked too, because with `pull.rebase` set it rewrites local commits.
86
88
  - **Sync exemption:** `git merge --ff-only [<ref>]`, `git rebase <ref>`, and `git pull --ff-only` are allowed on the protected branch when two facts hold. The target is a remote-tracking ref that is the branch's tracked upstream or the remote default (`origin/HEAD`). And `HEAD` is already an ancestor of that ref, so the branch carries no local commit to replay. A fast-forward adds no commit and rewrites none, so it cannot skip review; refusing it left a stale primary checkout with no way to sync (#145). `merge` without `--ff-only`, a bare `pull`, a local branch, another remote branch, a named remote and branch, and a diverged branch stay blocked. A `-c` override is accepted, because the command is judged by its subcommand and flags. Both `git -c pull.rebase=false pull --ff-only` and `git -c pull.rebase=true pull --ff-only` fast-forward a branch that is strictly behind. A `pull` derives its target from `@{u}`, and that derivation must still resolve to a remote-tracking ref, so a branch tracking a local branch stays blocked.
87
89
  - Git global flags are parsed, so `git -C /repo commit` is gated on `/repo`'s branch, not the workspace's.
90
+ - **Merged-branch cleanup exemption:** `git branch -d <branch>` and `git branch --delete <branch>` are allowed on the protected branch, provided no protected name is named and no `-D` or `--force` appears. Git itself refuses `-d` unless every named branch is fully merged, so the deletion cannot drop an unreviewed commit. `-D`, `--force`, and a protected name stay blocked. This is the local half of the cleanup a merged PR requires, which used to be impossible for the agent whenever the checkout sat on the branch that received the merge.
88
91
  - The agent is prompted to create a feature branch first (`git switch -c feat/my-feature`).
89
92
 
90
93
  ### 8. Workspace Boundary Guard
@@ -177,6 +180,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
177
180
 
178
181
  ### 20. Merged Branch & Base Freshness Guard
179
182
  - Blocks pushing to branches already merged or associated with closed PRs in GitHub or Azure DevOps.
183
+ - **Merged-branch cleanup exemption:** A push that only deletes remote branches already merged into the remote default is allowed: `git push <remote> --delete <branch>` and the `:<branch>` or `:refs/heads/<branch>` refspec. Deleting a merged branch's remote ref publishes no commit, so it is the remote half of the cleanup a merged PR requires. Every named branch must resolve to a local `refs/heads/<branch>` or `refs/remotes/origin/<branch>` that is an ancestor of the remote default, so an unmerged branch keeps its commits reachable and an unknown branch stays blocked. A protected name is refused. Any ordinary refspec, a forced refspec, `--force`, `--prune`, and `--mirror` stay blocked, because each deletes or publishes more than the named branches. A fully-qualified refspec outside `refs/heads/` stays blocked, so tag deletion is unaffected.
180
184
  - Blocks creating feature branches (`git switch -c`, `git checkout -b`) from a stale base. Without an explicit start point, the current branch must be fresh against the remote default. An explicit start point that already contains the remote default (`origin/HEAD`) is accepted, because the new branch is fresh by construction. Start points that cannot be resolved fail closed. Block reasons name the branch actually checked. They also name remedies that work under the guard: rebase or ff-merge the branch, or branch from the remote default directly. Shell redirections attached to or following a branch creation are ignored when classifying the start point. Those redirections are stdout and stderr redirection and fd duplication such as `2>&1`. They never determine which commit the branch is created from.
181
185
  - Tag push refspecs are exempt. Publishing an existing tag (`git push origin v1.2.0`, `git push origin refs/tags/v1.2.0`) and creating tags (`git tag v1.2.0`, `git tag -a -m ...`) are release operations, not branch mutations. Only tag deletions (`git tag -d`, `git push origin :refs/tags/v1.2.0`, `--delete`) stay blocked.
182
186
 
@@ -185,7 +189,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
185
189
  - Only **README.md** (root or package level) and files under **`docs/`** count as documentation updates. Arbitrary markdown does not satisfy this gate. That includes `.changeset/*.md` fragments and `CHANGELOG.md`.
186
190
 
187
191
  ### 22. Non-Interactive Shell & TTY Hang Guard
188
- - Blocks commands that spawn interactive text editors (`nano`, `vim`, `emacs`), interactive pagers (`less`, `more`) including through common shell wrappers, and interactive monitors (`top`, `htop`). It also blocks interactive rebase and patch prompts (`git rebase -i`, `git add -p`), `sudo`, and package managers missing non-interactive confirmation flags (`npm init` without `-y`, `apt-get` without `-y`). Pager and monitor names appearing only as command arguments are not treated as pager or monitor execution. Examples are `az keyvault secret show --name top` and `echo top`. Monitors are only flagged in command position. That means after wrappers such as `sudo`/`env`/`timeout`, through `eval` and `sh -c`, and via `busybox`. `top` batch mode stays allowed. Indirection this does not model is a known limitation. It covers `watch`/`xargs`/`man`, `find -exec`/`su -c`, and shell loop bodies such as `while true; do top; done`.
192
+ - Blocks commands that spawn interactive text editors (`nano`, `vim`, `emacs`), interactive pagers (`less`, `more`) including through common shell wrappers, and interactive monitors (`top`, `htop`). It also blocks interactive rebase and patch prompts (`git rebase -i`, `git add -p`), `sudo`, and package managers missing non-interactive confirmation flags (`npm init` without `-y`, `apt-get` without `-y`). **Every one of those names is judged at command position.** A name that appears only as an argument is data, so `az keyvault secret show --name top`, `echo top`, `grep -n 'sudo'`, and `grep -n 'git rebase -i'` are all allowed. A command word is read after wrapper and assignment stripping (`env`, `timeout`, `command`, `exec`, `nice`, `nohup`, `stdbuf`, `time`), so `env FOO=1 sudo ls` and `timeout 5 sudo ls` still block. Control-flow prefixes (`then`, `else`, `elif`, `do`, `while`, `for`, `!`) are skipped, so a loop or conditional body is judged too. `eval` and shell `-c` payloads recurse, and `busybox` applets are matched. `top` batch mode stays allowed. Indirection this does not model is a known limitation. It covers `watch`/`xargs`/`man`, `find -exec`/`su -c`, shell loop bodies for monitors such as `while true; do top; done`, and a command name delivered to a shell as stdin data (`echo 'vim x' | sh`).
189
193
  - Prevents subshell agents from hanging indefinitely waiting for user stdin in background execution.
190
194
  - **Desktop Notifications:** Emits native OS notifications when a policy blocks a command or when verification runs finish. The backends are Linux `notify-send` and macOS `osascript`. This keeps developers informed when their terminal is backgrounded. Configure it via `WORKFLOW_GUARD_NOTIFY=0`.
191
195
 
@@ -44,6 +44,8 @@ Common issues, root causes, and solutions when using `opencode-workflow-guard`.
44
44
 
45
45
  A checkout that is only behind its remote is not blocked. `git merge --ff-only <upstream>`, `git rebase <upstream>`, and `git pull --ff-only` are allowed on the protected branch when the ref is the branch's tracked upstream or the remote default, and `HEAD` is already an ancestor of it. That adds no commit and rewrites none, so a stale primary checkout can sync without a feature branch. `git merge` without `--ff-only`, a bare `git pull`, a local branch target, a different remote branch, a named remote and branch, and a branch with its own commits stay blocked. On a host where `pull.rebase` is set, run `git -c pull.rebase=false pull --ff-only`; the guard accepts that form.
46
46
 
47
+ The cleanup a merged PR requires is also allowed on the protected branch. `git branch -d <branch>` and `git branch --delete <branch>` pass, because git itself refuses them unless the branch is fully merged. A remote branch that is already merged can be deleted with `git push origin --delete <branch>` or `git push origin :<branch>`. A forced deletion, `git branch -D`, a protected branch name, an unmerged branch, and the options that delete more than the named branches (`--prune`, `--mirror`) stay blocked.
48
+
47
49
  ---
48
50
 
49
51
  ### 6. Edits Blocked: `Blocked: file path '...' escapes workspace root`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-workflow-guard",
3
- "version": "1.20.1",
3
+ "version": "1.20.3",
4
4
  "description": "Deterministic workflow and safety policy enforcement for OpenCode",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -63,11 +63,13 @@ import {
63
63
  hasUnsafeGitAlias,
64
64
  isBranchAlreadyMergedOrClosed,
65
65
  isGitTreeWriteText,
66
+ isMergedLocalBranchDeletion,
66
67
  isProtectedBranchFastForward,
67
68
  normalizeGitCommands,
68
69
  onProtectedBranch,
69
70
  parseGitInvocation,
70
71
  prSourceBranch,
72
+ purgesMergedRemoteBranches,
71
73
  pushedProtectedBranchIn,
72
74
  tagRefspecIn,
73
75
  } from "../policies/git.ts";
@@ -85,12 +87,12 @@ import {
85
87
  effectiveTodos,
86
88
  fetchSessionTodos,
87
89
  hasActiveTodo,
90
+ inspectTodoLifecycle,
88
91
  readOnlyTodoCompletions,
89
92
  recordTodoTaskStarts,
90
93
  subagentMutationBudgetReason,
91
94
  todoCompletionBlockReason,
92
95
  unverifiedTodoCompletions,
93
- validateTodoLifecycle,
94
96
  } from "../policies/todo.ts";
95
97
  import { recordedTodoCapability, reportTodoGateFailOpen } from "./v2-todo.ts";
96
98
 
@@ -228,10 +230,10 @@ export async function guardToolCallImpl(
228
230
  if (Array.isArray(rawTodos)) {
229
231
  const newTodos = rawTodos;
230
232
  const existingTodos = context?.sessionID ? await fetchSessionTodos(context.sessionID) : undefined;
231
- const err = validateTodoLifecycle(newTodos, existingTodos);
232
- if (err) {
233
- logPolicyBlock(`[workflow-guard] ${err}`);
234
- return block("todo", "todo_lifecycle", err);
233
+ const lifecycle = inspectTodoLifecycle(newTodos, existingTodos);
234
+ if (lifecycle.error) {
235
+ logPolicyBlock(`[workflow-guard] ${lifecycle.error}`);
236
+ return block("todo", "todo_lifecycle", lifecycle.error);
235
237
  }
236
238
  // Per-task completion evidence. Every task may enter `completed`
237
239
  // only after the session mutated inside that task's window. The
@@ -241,7 +243,7 @@ export async function guardToolCallImpl(
241
243
  if (context?.sessionID) {
242
244
  const starts = todoTaskStarts(context.sessionID);
243
245
  const total = getSessionMutationCount(context.sessionID);
244
- const unverified = unverifiedTodoCompletions(existingTodos, newTodos, starts, total);
246
+ const unverified = unverifiedTodoCompletions(existingTodos, newTodos, starts, total, lifecycle.refinements);
245
247
  if (unverified.length > 0) {
246
248
  const reason = todoCompletionBlockReason(unverified);
247
249
  logPolicyBlock(`[workflow-guard] ${reason}`);
@@ -297,7 +299,18 @@ export async function guardToolCallImpl(
297
299
  // Only an accepted write becomes the task list, so task windows move
298
300
  // and read-only marker use is journaled after every gate has passed.
299
301
  if (context?.sessionID && !context.simulate) {
300
- recordTodoTaskStarts(todoTaskStarts(context.sessionID), existingTodos, newTodos, getSessionMutationCount(context.sessionID));
302
+ recordTodoTaskStarts(todoTaskStarts(context.sessionID), existingTodos, newTodos, getSessionMutationCount(context.sessionID), lifecycle.refinements);
303
+ if (lifecycle.refinements.length > 0) {
304
+ audit({
305
+ ts: new Date().toISOString(),
306
+ sessionID: context.sessionID,
307
+ tool: "todowrite",
308
+ decision: "allow",
309
+ phase: "event",
310
+ reason: "todo_refined",
311
+ input: { refinements: lifecycle.refinements.map(({ from, to }) => ({ from, to })) },
312
+ });
313
+ }
301
314
  if (readOnlyCompleted.length > 0) {
302
315
  audit({
303
316
  ts: new Date().toISOString(),
@@ -561,7 +574,7 @@ export async function guardToolCallImpl(
561
574
  // to sync (#145).
562
575
  const gitText = `git ${invocation.rest}`;
563
576
  const protectedWrite = GIT_WRITE_RE.test(gitText) || GIT_PULL_RE.test(gitText);
564
- if (protectedWrite && onProtectedBranch(invocation.repoDir) && !isProtectedBranchFastForward(gitText, invocation.repoDir)) {
577
+ if (protectedWrite && onProtectedBranch(invocation.repoDir) && !isProtectedBranchFastForward(gitText, invocation.repoDir) && !isMergedLocalBranchDeletion(gitText, invocation.repoDir)) {
565
578
  logPolicyBlock(`[workflow-guard] blocked git write on protected branch: ${command.slice(0, 120)}`);
566
579
  return block("git", "protected_branch", branchGuardReason());
567
580
  }
@@ -687,8 +700,16 @@ export async function guardToolCallImpl(
687
700
  }
688
701
  }
689
702
  for (const invocation of gitInvocations) {
690
- if (!/\bgit\s+push\b/.test(`git ${invocation.rest}`)) continue;
691
- if (tagRefspecIn(`git ${invocation.rest}`, invocation.repoDir)) continue;
703
+ const pushText = `git ${invocation.rest}`;
704
+ if (!/\bgit\s+push\b/.test(pushText)) continue;
705
+ if (tagRefspecIn(pushText, invocation.repoDir)) continue;
706
+ // A push that only deletes remote branches already merged into the
707
+ // remote default publishes no commit. That is the remote half of the
708
+ // cleanup a merged PR requires, so neither the protected checkout nor
709
+ // the merged-current-branch rule has anything to protect. Every other
710
+ // push, including --prune, --mirror, a forced refspec, and an unmerged
711
+ // branch, stays blocked below.
712
+ if (purgesMergedRemoteBranches(pushText, invocation.repoDir)) continue;
692
713
  if (onProtectedBranch(invocation.repoDir)) {
693
714
  logPolicyBlock(`[workflow-guard] blocked push from protected branch: ${command}`);
694
715
  return block("git", "protected_branch", branchGuardReason());
package/src/lib/shell.ts CHANGED
@@ -545,7 +545,7 @@ export function splitShellSegments(command: string): string[] {
545
545
  return segments;
546
546
  }
547
547
 
548
- function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: boolean; cwdTarget?: string; assignments: string[] } {
548
+ function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: boolean; cwdTarget?: string; assignments: string[]; sudo: boolean } {
549
549
  let cleanCmd = decodeShellEscapes(command.trim());
550
550
  // Strip outer grouping parentheses/braces if present e.g. ( git commit ) or { git commit; }
551
551
  while (
@@ -569,6 +569,9 @@ function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: b
569
569
  // assignment, and treating it as one would claim a repository that the
570
570
  // invocation never named.
571
571
  const assignments: string[] = [];
572
+ // A `sudo` wrapper is stripped before the command word, so a caller that
573
+ // needs to know the command runs privileged asks for it here.
574
+ let sudo = false;
572
575
  while (i < words.length) {
573
576
  const rawWord = words[i]!;
574
577
  const word = rawWord.replace(/^[\({]+/, "").replace(/[\)};]+$/, "");
@@ -635,6 +638,7 @@ function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: b
635
638
  continue;
636
639
  }
637
640
  if (word === "sudo" || word === "doas") {
641
+ if (word === "sudo") sudo = true;
638
642
  i++;
639
643
  const valueOptions = new Set([
640
644
  "-u",
@@ -747,13 +751,18 @@ function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: b
747
751
  return { words: words
748
752
  .slice(i)
749
753
  .map((w) => w.replace(/^[\({]+/, "").replace(/[\)};]+$/, ""))
750
- .filter(Boolean), changesCwd, cwdTarget, assignments };
754
+ .filter(Boolean), changesCwd, cwdTarget, assignments, sudo };
751
755
  }
752
756
 
753
757
  export function unwrapShellWords(command: string): string[] {
754
758
  return unwrapShellWordsImpl(command).words;
755
759
  }
756
760
 
761
+ /** True when a `sudo` wrapper was stripped ahead of the command word. */
762
+ export function shellHasSudoWrapper(command: string): boolean {
763
+ return unwrapShellWordsImpl(command).sudo;
764
+ }
765
+
757
766
  /**
758
767
  * The directory a wrapper (`env -C`, `sudo -D`) runs its command in, if it
759
768
  * names one. The target is left unexpanded: the caller knows the directory it
@@ -826,7 +835,7 @@ export function expandCwdTarget(target: string): string | undefined {
826
835
  }
827
836
 
828
837
  /** Words that carry no directory of their own; a control-flow body follows them. */
829
- const TRANSPARENT_PREFIX = new Set([
838
+ export const TRANSPARENT_PREFIX = new Set([
830
839
  "builtin",
831
840
  "command",
832
841
  "then",
@@ -172,7 +172,7 @@ export function normalizeGitCommands(command: string): string {
172
172
  }
173
173
 
174
174
  export const GIT_WRITE_RE =
175
- /\bgit\s+(add|rm|mv|commit|merge|rebase|cherry-pick|revert|stash\s+pop|apply|am|restore|reset|update-ref|filter-branch)\b|\bgit\s+tag\s+(?!--?list\b|-l\b)(?:[^|;&]*\s)?(?:-d\b|--delete\b)|\bgit\s+checkout\s+(?!-b\b)|\bgit\s+branch\s+(?:[^|;&]*\s)?-[dDM]\b/;
175
+ /\bgit\s+(add|rm|mv|commit|merge|rebase|cherry-pick|revert|stash\s+pop|apply|am|restore|reset|update-ref|filter-branch)\b|\bgit\s+tag\s+(?!--?list\b|-l\b)(?:[^|;&]*\s)?(?:-d\b|--delete\b)|\bgit\s+checkout\s+(?!-b\b)|\bgit\s+branch\s+(?:[^|;&]*\s)?(?:-[A-Za-z]*[dDM][A-Za-z]*\b|--delete\b)/;
176
176
 
177
177
  // `pull` is deliberately absent from GIT_WRITE_RE: pulling on a feature branch
178
178
  // is how a stale base is refreshed, and that is not a write to protect. On a
@@ -243,6 +243,87 @@ export function isProtectedBranchFastForward(text: string, root: string): boolea
243
243
  return ancestor.status === 0;
244
244
  }
245
245
 
246
+ /**
247
+ * True when `text` deletes local branches with git's merged-only form,
248
+ * `git branch -d`. `-D` and `--force` stay blocked, because they can drop
249
+ * unmerged commits. `-d` cannot: the manual states the branch "must be fully
250
+ * merged" in its upstream, or in HEAD when no upstream is set, so git refuses
251
+ * the deletion itself and the protected-branch rule has nothing to protect.
252
+ *
253
+ * This is the local half of the cleanup a merged PR requires. It was blocked
254
+ * whenever the checkout sat on the protected branch that receives the merge,
255
+ * which left the operator as the only actor who could finish it.
256
+ */
257
+ export function isMergedLocalBranchDeletion(text: string, root: string): boolean {
258
+ const tokens = unwrapShellWords(text);
259
+ if (tokens[0] !== "git" || tokens[1] !== "branch") return false;
260
+ const args = tokens.slice(2);
261
+ // Short flags arrive as clusters (`-d`, `-rd`, `-Df`). Read the letters
262
+ // once so the delete and force rules cannot disagree about a cluster.
263
+ const shortFlags = args.filter((arg) => /^-[A-Za-z]+$/.test(arg)).join("");
264
+ const deletes = args.includes("--delete") || shortFlags.includes("d") || shortFlags.includes("D");
265
+ if (!deletes) return false;
266
+ if (args.includes("--force") || /[Df]/.test(shortFlags)) return false;
267
+ const names = args.filter((arg) => !arg.startsWith("-"));
268
+ if (names.length === 0) return false;
269
+ const protectedBranches = getProtectedBranches(root);
270
+ return names.every((name) => !protectedBranches.has(name));
271
+ }
272
+
273
+ /**
274
+ * True when `text` pushes nothing but deletions of remote branches that are
275
+ * already merged into the remote default: `git push <remote> --delete <branch>`
276
+ * or a `:<branch>` refspec.
277
+ *
278
+ * Deleting a merged branch's remote ref publishes no commit, so it is the other
279
+ * half of the cleanup a merged PR requires. The rules stay narrow. Every named
280
+ * branch must be an ancestor of the remote default, so an unmerged branch keeps
281
+ * its commits reachable. Protected names are refused. Options that delete more
282
+ * than the named refs (`--prune`, `--mirror`, `--force`) and any ordinary
283
+ * refspec keep the push blocked. The branch resolves through `refs/heads/`
284
+ * first, then `refs/remotes/origin/<branch>`, because deleting the local ref
285
+ * first is the normal order. Both namespaces are explicit, so a local branch
286
+ * whose remote ref is already gone stays blocked instead of guessing.
287
+ */
288
+ export function purgesMergedRemoteBranches(text: string, root: string): boolean {
289
+ const tokens = unwrapShellWords(text);
290
+ if (tokens[0] !== "git" || tokens[1] !== "push") return false;
291
+ const args = tokens.slice(2);
292
+ const targets: string[] = [];
293
+ let deleteFlag = false;
294
+ let remoteSeen = false;
295
+ for (const arg of args) {
296
+ if (arg.startsWith("-")) {
297
+ if (arg === "-d" || arg === "--delete") {
298
+ deleteFlag = true;
299
+ continue;
300
+ }
301
+ return false;
302
+ }
303
+ if (!remoteSeen && !arg.startsWith(":")) {
304
+ remoteSeen = true;
305
+ continue;
306
+ }
307
+ const name = arg.startsWith(":") ? arg.slice(1) : deleteFlag ? arg : "";
308
+ if (!name) return false;
309
+ // A fully-qualified ref is only a branch refspec under refs/heads/.
310
+ // Deleting a tag, or any other namespace, stays blocked.
311
+ if (name.startsWith("refs/") && !name.startsWith("refs/heads/")) return false;
312
+ const branch = name.replace(/^refs\/heads\//, "");
313
+ if (!branch || getProtectedBranches(root).has(branch)) return false;
314
+ targets.push(branch);
315
+ }
316
+ if (targets.length === 0) return false;
317
+ return targets.every((branch) => {
318
+ // Name the ref namespaces explicitly. A bare short name also matches a
319
+ // tag of the same name, and a tag deletion is not branch cleanup.
320
+ const localRef = `refs/heads/${branch}`;
321
+ const ref = gitRefExists(localRef, root) ? localRef : `refs/remotes/origin/${branch}`;
322
+ if (!gitRefExists(ref, root)) return false;
323
+ return isBranchAlreadyMergedOrClosed(root, ref, false).merged;
324
+ });
325
+ }
326
+
246
327
  /** The ref the current branch tracks, or undefined when it tracks nothing. */
247
328
  function gitUpstreamRef(root: string): string | undefined {
248
329
  const upstream = spawnSync("git", ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], {
@@ -1,6 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { basename } from "node:path";
3
- import { splitShellSegments, unwrapShellWords } from "../lib/shell.ts";
3
+ import { shellHasSudoWrapper, splitShellSegments, TRANSPARENT_PREFIX, unwrapShellWords } from "../lib/shell.ts";
4
4
 
5
5
  // AI agents frequently run dangerous package manager flags (e.g. npm audit fix --force,
6
6
  // npm install -g, pip install --force-reinstall, agent-driven publish) that introduce
@@ -40,43 +40,40 @@ export function checkPackageHygiene(command: string): { isViolating: boolean; na
40
40
 
41
41
  // AI agents running in non-interactive terminal subshells hang indefinitely when an
42
42
  // interactive prompt (vim, nano, less, top, sudo, npm init without -y, apt without -y,
43
- // git rebase -i) waits for TTY input. Process monitors are handled separately in
44
- // checkProcessMonitorCommand because `top` can run in a safe batch mode, while the
45
- // other monitors cannot.
43
+ // git rebase -i) waits for TTY input. Every one of those names is judged at command
44
+ // position, because the same word in an argument is data: `echo top`, a grep pattern
45
+ // like `grep -n 'sudo'`, or a printf string must not read as a hang. Process monitors
46
+ // and pagers already work that way; the patterns below follow the same rule.
46
47
 
47
- const INTERACTIVE_COMMAND_PATTERNS: Array<{ regex: RegExp; name: string; advice: string }> = [
48
- {
49
- regex: /\b(?:nano|vim?|emacs|pico|joe|micro)\b/i,
50
- name: "interactive text editor",
51
- advice: "Use the edit, write, or apply_patch tools instead of interactive terminal editors.",
52
- },
53
- {
54
- regex: /\bsudo\b/i,
55
- name: "sudo with password prompt",
56
- advice: "Avoid sudo in agent sessions; run commands directly or request user execution.",
57
- },
48
+ const INTERACTIVE_EDITORS = new Set(["nano", "vi", "vim", "emacs", "pico", "joe", "micro"]);
49
+ const EDITOR_ADVICE = "Use the edit, write, or apply_patch tools instead of interactive terminal editors.";
50
+ const SUDO_NAME = "sudo with password prompt";
51
+ const SUDO_ADVICE = "Avoid sudo in agent sessions; run commands directly or request user execution.";
52
+
53
+ // Anchored on the command word, so a `git rebase -i` inside a grep pattern stays data.
54
+ const INTERACTIVE_VERB_PATTERNS: Array<{ regex: RegExp; name: string; advice: string }> = [
58
55
  {
59
- regex: /\bgit\s+rebase\s+-[a-zA-Z]*i/i,
56
+ regex: /^git\s+rebase\s+-[a-zA-Z]*i/i,
60
57
  name: "git interactive rebase",
61
58
  advice: "Use non-interactive git commands or explicit cherry-pick/merge sequences.",
62
59
  },
63
60
  {
64
- regex: /\bgit\s+add\s+-[a-zA-Z]*p/i,
61
+ regex: /^git\s+add\s+-[a-zA-Z]*p/i,
65
62
  name: "git interactive patch",
66
63
  advice: "Use git add <file> or git apply rather than interactive patch selection.",
67
64
  },
68
65
  {
69
- regex: /\bnpm\s+init\b(?!\s+(?:-y|--yes|--force))\b/i,
66
+ regex: /^npm\s+init\b(?!\s+(?:-y|--yes|--force))\b/i,
70
67
  name: "npm init without non-interactive flag",
71
68
  advice: "Add -y or --yes flag: npm init -y",
72
69
  },
73
70
  {
74
- regex: /\b(?:apt|apt-get)\s+(?:install|remove|purge|upgrade|dist-upgrade)\b(?!\s+(?:-y|--yes|--assume-yes))\b/i,
71
+ regex: /^(?:apt|apt-get)\s+(?:install|remove|purge|upgrade|dist-upgrade)\b(?!\s+(?:-y|--yes|--assume-yes))\b/i,
75
72
  name: "apt command without non-interactive flag",
76
73
  advice: "Add -y flag to avoid interactive confirmation prompts (e.g. apt-get install -y <pkg>).",
77
74
  },
78
75
  {
79
- regex: /\b(?:yum|dnf)\s+(?:install|remove|upgrade)\b(?!\s+-y)\b/i,
76
+ regex: /^(?:yum|dnf)\s+(?:install|remove|upgrade)\b(?!\s+-y)\b/i,
80
77
  name: "yum/dnf command without non-interactive flag",
81
78
  advice: "Add -y flag to avoid interactive confirmation prompts (e.g. dnf install -y <pkg>).",
82
79
  },
@@ -140,17 +137,45 @@ function containsPagerCommand(command: string, depth = 0): boolean {
140
137
  return false;
141
138
  }
142
139
 
140
+ function containsInteractivePattern(command: string, depth = 0): { name: string; advice: string } | undefined {
141
+ if (depth >= 16) return undefined;
142
+ for (const segment of splitShellSegments(command)) {
143
+ // Unwrapping strips `sudo` before the command word, so ask the unwrapper.
144
+ if (shellHasSudoWrapper(segment)) return { name: SUDO_NAME, advice: SUDO_ADVICE };
145
+ const words = unwrapShellWords(segment);
146
+ while (words.length > 0 && (words[0] === "--" || TRANSPARENT_PREFIX.has(words[0]!))) words.shift();
147
+ if (words[0] === "sudo") return { name: SUDO_NAME, advice: SUDO_ADVICE };
148
+ const executable = basename(words[0] ?? "").toLowerCase();
149
+ const busybox = executable === "busybox";
150
+ const candidate = busybox ? basename(words[1] ?? "").toLowerCase() : executable;
151
+ if (INTERACTIVE_EDITORS.has(candidate)) return { name: "interactive text editor", advice: EDITOR_ADVICE };
152
+ const commandText = words.slice(busybox ? 1 : 0).join(" ");
153
+ for (const { regex, name, advice } of INTERACTIVE_VERB_PATTERNS) {
154
+ if (regex.test(commandText)) return { name, advice };
155
+ }
156
+ if (executable === "eval" && words.length > 1) {
157
+ const nested = containsInteractivePattern(words.slice(1).join(" "), depth + 1);
158
+ if (nested) return nested;
159
+ }
160
+ if (/^(?:ba|z|da|k)?sh$/i.test(executable)) {
161
+ const commandFlag = words.findIndex((word, index) => index > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(word));
162
+ if (commandFlag >= 0 && words[commandFlag + 1]) {
163
+ const nested = containsInteractivePattern(words[commandFlag + 1]!, depth + 1);
164
+ if (nested) return nested;
165
+ }
166
+ }
167
+ }
168
+ return undefined;
169
+ }
170
+
143
171
  export function checkInteractiveTtyCommand(command: string): { isInteractive: boolean; name?: string; advice?: string } {
144
172
  const monitor = checkProcessMonitorCommand(command);
145
173
  if (monitor.isInteractive) return monitor;
146
174
  if (containsPagerCommand(command)) {
147
175
  return { isInteractive: true, name: "terminal pager", advice: PAGER_ADVICE };
148
176
  }
149
- for (const { regex, name, advice } of INTERACTIVE_COMMAND_PATTERNS) {
150
- if (regex.test(command)) {
151
- return { isInteractive: true, name, advice };
152
- }
153
- }
177
+ const pattern = containsInteractivePattern(command);
178
+ if (pattern) return { isInteractive: true, ...pattern };
154
179
  return { isInteractive: false };
155
180
  }
156
181
 
@@ -33,6 +33,11 @@ export const SETTINGS_TAMPER_PATTERNS: RegExp[] = [
33
33
  // still executes the verb.
34
34
  const PATH_PATTERNS = SETTINGS_TAMPER_PATTERNS.slice(0, 4);
35
35
  const VERB_PATTERNS = SETTINGS_TAMPER_PATTERNS.slice(4);
36
+ // Patterns 1 and 3 match a redirect into a guarded path; patterns 0 and 2
37
+ // match a mutating verb whose operands include one. A redirect writes its
38
+ // target whatever verb carries it, so legacy mode judges it before it
39
+ // discounts any copy source.
40
+ const REDIRECT_PATH_PATTERNS = [PATH_PATTERNS[1]!, PATH_PATTERNS[3]!];
36
41
 
37
42
  export function normalizeShellEvasion(text: string): string {
38
43
  return decodeShellEscapes(text)
@@ -58,22 +63,109 @@ export function isCollaborationInvocation(segment: string): boolean {
58
63
  return COLLABORATION_INVOCATION_PATTERNS.some((re) => re.test(segment));
59
64
  }
60
65
 
66
+ const GUARDED_OPERAND_RE = new RegExp(`(?:${C_LIST}|${U_LIST})`, "i");
67
+
68
+ // Copy-like verbs read their sources and write only their destination. Legacy
69
+ // mode therefore judges the destination operand, so a guarded source is a read
70
+ // rather than a mutation. Every other mutating verb touches each operand it
71
+ // names, and a copy whose destination cannot be identified stays with that
72
+ // fail-closed set.
73
+ const COPY_INVOCATION_RE = /(?:^|[\s;&|])(?:cp|ln|install)\s+([^|;&]+)/gi;
74
+
75
+ // A redirect span is not a copy operand. Dropping it here keeps `cp src dst 2>
76
+ // log` from reading the log path as the destination.
77
+ const REDIRECT_SPAN_RE = /(?:^|\s)(?:&|\d*)?(?:>>?|&>)\s*\S*/g;
78
+
79
+ function classifyCopyInvocation(invocation: string): { safe: boolean; tamper: boolean } {
80
+ const args = invocation
81
+ .replace(REDIRECT_SPAN_RE, " ")
82
+ .trim()
83
+ .split(/\s+/)
84
+ .filter(Boolean);
85
+ const verb = (args.shift() ?? "").toLowerCase();
86
+ const operands: string[] = [];
87
+ let targetDir: string | undefined;
88
+ for (let index = 0; index < args.length; index++) {
89
+ const token = args[index]!;
90
+ if (token === "-t" || token === "--target-directory") {
91
+ targetDir = args[++index];
92
+ continue;
93
+ }
94
+ const longAttached = /^--target-directory=(.*)$/.exec(token);
95
+ if (longAttached) {
96
+ targetDir = longAttached[1];
97
+ continue;
98
+ }
99
+ const shortAttached = /^-t(.+)$/.exec(token);
100
+ if (shortAttached) {
101
+ targetDir = shortAttached[1];
102
+ continue;
103
+ }
104
+ if (token.startsWith("-")) continue;
105
+ operands.push(token);
106
+ }
107
+ const guarded = (token: string | undefined) => token !== undefined && GUARDED_OPERAND_RE.test(token);
108
+ // `install -d` treats every argument as a directory name, so all operands
109
+ // and any target directory are targets rather than sources.
110
+ if (verb === "install" && args.some((arg) => /^-[a-zA-Z]*d[a-zA-Z0-9]*$/.test(arg))) {
111
+ return { safe: false, tamper: operands.some(guarded) || guarded(targetDir) };
112
+ }
113
+ // A hard link is a second writable name for the source inode, so a later
114
+ // write to the workspace link would mutate the guarded file. Only a
115
+ // symbolic link keeps the guarded path behind a resolution the guard can
116
+ // follow, so `ln -s` and `cp -s` are reads while `ln`, `cp -l`, and
117
+ // `cp --link` stay on the fail-closed any-operand match. A bundled short
118
+ // cluster is classified by its letters: `s` is ln's symbolic-link flag and
119
+ // `l` is cp's link flag, so `-sfn` is symbolic and `-al` is a hard link.
120
+ // GNU rejects cp's `-l` together with `-s`, and the fail-closed branch wins
121
+ // there.
122
+ const shortFlag = (letter: string) => new RegExp(`^-[a-zA-Z]*${letter}[a-zA-Z]*$`);
123
+ const hardLink =
124
+ verb === "ln"
125
+ ? !args.some((arg) => arg === "--symbolic" || shortFlag("s").test(arg))
126
+ : verb === "cp" && args.some((arg) => arg === "--link" || shortFlag("l").test(arg));
127
+ if (hardLink) return { safe: false, tamper: operands.some(guarded) };
128
+ const destination = targetDir ?? (operands.length >= 2 ? operands[operands.length - 1] : undefined);
129
+ if (destination === undefined) return { safe: false, tamper: false };
130
+ if (guarded(destination)) return { safe: false, tamper: true };
131
+ return { safe: true, tamper: false };
132
+ }
133
+
134
+ function legacyPathTamper(residue: string): boolean {
135
+ if (REDIRECT_PATH_PATTERNS.some((re) => re.test(residue))) return true;
136
+ let tamper = false;
137
+ const rest = residue.replace(COPY_INVOCATION_RE, (match) => {
138
+ const verdict = classifyCopyInvocation(match);
139
+ if (verdict.tamper) tamper = true;
140
+ return verdict.safe ? " " : match;
141
+ });
142
+ if (tamper) return true;
143
+ return PATH_PATTERNS.some((re) => re.test(rest));
144
+ }
145
+
61
146
  export function isSettingsTamper(command: string, liveControlPlaneRoots?: readonly string[]): boolean {
62
147
  // When the host declares its live control-plane roots, path-shaped tamper is
63
148
  // decided by the mutation TARGET's runtime location (`isProtectedPath`), not
64
149
  // by matching any operand's raw text. That stops a copy/move SOURCE under a
65
150
  // config path from being flagged while the destination is a sanctioned draft
66
151
  // (finding F3). The opencode CLI verb patterns still apply. Callers that scan
67
- // written content (edit payloads) pass no roots and keep the legacy
68
- // fail-closed path matching.
152
+ // written content (edit payloads) pass no roots, so they keep the legacy
153
+ // matching: every mutating verb touches each operand, while a copy-like verb
154
+ // is judged by its destination only and fails closed when it has none.
69
155
  const factMode = liveControlPlaneRoots !== undefined && liveControlPlaneRoots.length > 0;
70
- return command.split(/[\n|;&]+/).some((s) => {
156
+ // `2>&1` and `2>&-` duplicate or close a file descriptor. They never name a
157
+ // write target, but their `&` would split the command and strand the
158
+ // operand after them in a fragment with no verb. Drop them before
159
+ // segmenting. A word after `>&` that is not a descriptor stays, because
160
+ // bash reads it as a file redirect.
161
+ const normalized = command.replace(/\d*>&(?:\d+(?![\w.])|-)/g, " ");
162
+ return normalized.split(/[\n|;&]+/).some((s) => {
71
163
  if (isCollaborationInvocation(s)) return false;
72
164
  const flattened = normalizeGlobPathEvasion(normalizeShellEvasion(s));
73
165
  if (VERB_PATTERNS.some((re) => re.test(flattened))) return true;
74
166
  if (factMode) return false;
75
167
  const residue = normalizeGlobPathEvasion(normalizeShellEvasion(prepareRedirectResidue(s)));
76
- return PATH_PATTERNS.some((re) => re.test(residue));
168
+ return legacyPathTamper(residue);
77
169
  });
78
170
  }
79
171