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/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,11 +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
- - 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`.
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.
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.
86
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.
87
91
  - The agent is prompted to create a feature branch first (`git switch -c feat/my-feature`).
88
92
 
89
93
  ### 8. Workspace Boundary Guard
@@ -176,6 +180,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
176
180
 
177
181
  ### 20. Merged Branch & Base Freshness Guard
178
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.
179
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.
180
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.
181
186
 
@@ -184,7 +189,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
184
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`.
185
190
 
186
191
  ### 22. Non-Interactive Shell & TTY Hang Guard
187
- - 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`).
188
193
  - Prevents subshell agents from hanging indefinitely waiting for user stdin in background execution.
189
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`.
190
195
 
@@ -42,6 +42,10 @@ Common issues, root causes, and solutions when using `opencode-workflow-guard`.
42
42
  - **Root Cause:** Policy 7 requires all code modifications to happen on a feature branch.
43
43
  - **Solution:** Switch to a feature branch (`git switch -c feat/my-feature`) before making changes.
44
44
 
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
+
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
+
45
49
  ---
46
50
 
47
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.0",
3
+ "version": "1.20.3",
4
4
  "description": "Deterministic workflow and safety policy enforcement for OpenCode",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -51,6 +51,7 @@ import { branchHasDocumentationChange } from "../policies/docs.ts";
51
51
  import { claimFiles, fileClaimConflictReason, releaseStaleFileClaims } from "../policies/file-claims.ts";
52
52
  import {
53
53
  GIT_BRANCH_CREATE_RE,
54
+ GIT_PULL_RE,
54
55
  GIT_WRITE_RE,
55
56
  PUSH_TO_MAIN_RE,
56
57
  branchGuardReason,
@@ -62,10 +63,13 @@ import {
62
63
  hasUnsafeGitAlias,
63
64
  isBranchAlreadyMergedOrClosed,
64
65
  isGitTreeWriteText,
66
+ isMergedLocalBranchDeletion,
67
+ isProtectedBranchFastForward,
65
68
  normalizeGitCommands,
66
69
  onProtectedBranch,
67
70
  parseGitInvocation,
68
71
  prSourceBranch,
72
+ purgesMergedRemoteBranches,
69
73
  pushedProtectedBranchIn,
70
74
  tagRefspecIn,
71
75
  } from "../policies/git.ts";
@@ -83,12 +87,12 @@ import {
83
87
  effectiveTodos,
84
88
  fetchSessionTodos,
85
89
  hasActiveTodo,
90
+ inspectTodoLifecycle,
86
91
  readOnlyTodoCompletions,
87
92
  recordTodoTaskStarts,
88
93
  subagentMutationBudgetReason,
89
94
  todoCompletionBlockReason,
90
95
  unverifiedTodoCompletions,
91
- validateTodoLifecycle,
92
96
  } from "../policies/todo.ts";
93
97
  import { recordedTodoCapability, reportTodoGateFailOpen } from "./v2-todo.ts";
94
98
 
@@ -226,10 +230,10 @@ export async function guardToolCallImpl(
226
230
  if (Array.isArray(rawTodos)) {
227
231
  const newTodos = rawTodos;
228
232
  const existingTodos = context?.sessionID ? await fetchSessionTodos(context.sessionID) : undefined;
229
- const err = validateTodoLifecycle(newTodos, existingTodos);
230
- if (err) {
231
- logPolicyBlock(`[workflow-guard] ${err}`);
232
- 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);
233
237
  }
234
238
  // Per-task completion evidence. Every task may enter `completed`
235
239
  // only after the session mutated inside that task's window. The
@@ -239,7 +243,7 @@ export async function guardToolCallImpl(
239
243
  if (context?.sessionID) {
240
244
  const starts = todoTaskStarts(context.sessionID);
241
245
  const total = getSessionMutationCount(context.sessionID);
242
- const unverified = unverifiedTodoCompletions(existingTodos, newTodos, starts, total);
246
+ const unverified = unverifiedTodoCompletions(existingTodos, newTodos, starts, total, lifecycle.refinements);
243
247
  if (unverified.length > 0) {
244
248
  const reason = todoCompletionBlockReason(unverified);
245
249
  logPolicyBlock(`[workflow-guard] ${reason}`);
@@ -295,7 +299,18 @@ export async function guardToolCallImpl(
295
299
  // Only an accepted write becomes the task list, so task windows move
296
300
  // and read-only marker use is journaled after every gate has passed.
297
301
  if (context?.sessionID && !context.simulate) {
298
- 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
+ }
299
314
  if (readOnlyCompleted.length > 0) {
300
315
  audit({
301
316
  ts: new Date().toISOString(),
@@ -553,7 +568,13 @@ export async function guardToolCallImpl(
553
568
  }
554
569
  for (const invocation of gitInvocations) {
555
570
  if (tagRefspecIn(`git ${invocation.rest}`, invocation.repoDir)) continue;
556
- if (GIT_WRITE_RE.test(`git ${invocation.rest}`) && onProtectedBranch(invocation.repoDir)) {
571
+ // A fast-forward of a protected branch to its tracked upstream adds no
572
+ // commit and rewrites none, so it is the one history write that cannot
573
+ // skip review. Refusing it leaves the checkout stale with no safe way
574
+ // to sync (#145).
575
+ const gitText = `git ${invocation.rest}`;
576
+ const protectedWrite = GIT_WRITE_RE.test(gitText) || GIT_PULL_RE.test(gitText);
577
+ if (protectedWrite && onProtectedBranch(invocation.repoDir) && !isProtectedBranchFastForward(gitText, invocation.repoDir) && !isMergedLocalBranchDeletion(gitText, invocation.repoDir)) {
557
578
  logPolicyBlock(`[workflow-guard] blocked git write on protected branch: ${command.slice(0, 120)}`);
558
579
  return block("git", "protected_branch", branchGuardReason());
559
580
  }
@@ -679,8 +700,16 @@ export async function guardToolCallImpl(
679
700
  }
680
701
  }
681
702
  for (const invocation of gitInvocations) {
682
- if (!/\bgit\s+push\b/.test(`git ${invocation.rest}`)) continue;
683
- 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;
684
713
  if (onProtectedBranch(invocation.repoDir)) {
685
714
  logPolicyBlock(`[workflow-guard] blocked push from protected branch: ${command}`);
686
715
  return block("git", "protected_branch", branchGuardReason());
@@ -29,7 +29,7 @@
29
29
 
30
30
  import { guardToolCallImpl } from "./guard-dispatcher.ts";
31
31
  import { getSessionBoundWorkspace, runWithRuntimeState } from "./state.ts";
32
- import { GIT_BRANCH_CREATE_RE, GIT_WRITE_RE, PUSH_TO_MAIN_RE, parseGitInvocation } from "../policies/git.ts";
32
+ import { GIT_BRANCH_CREATE_RE, GIT_PULL_RE, GIT_WRITE_RE, PUSH_TO_MAIN_RE, parseGitInvocation } from "../policies/git.ts";
33
33
  import { hasPrCreateInvocation } from "../policies/changelog.ts";
34
34
  import { splitShellSegments } from "./shell.ts";
35
35
  import { mcpMutationTool } from "../policies/mcp.ts";
@@ -93,9 +93,13 @@ function repositoryDependent(command: string): boolean {
93
93
  const rest = `git ${parsed.rest}`;
94
94
  if (parsed.explicitRepoDir) continue;
95
95
  if (PUSH_TO_MAIN_RE.test(rest)) continue;
96
+ // `pull` belongs here because on a protected branch it is a history
97
+ // write, and whether the checkout is protected is exactly the fact this
98
+ // seat cannot see.
96
99
  const repositorySensitive =
97
100
  /\bgit\s+push\b/.test(rest) ||
98
101
  GIT_WRITE_RE.test(rest) ||
102
+ GIT_PULL_RE.test(rest) ||
99
103
  GIT_BRANCH_CREATE_RE.test(rest);
100
104
  if (repositorySensitive) return true;
101
105
  }
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,13 @@ 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
+
177
+ // `pull` is deliberately absent from GIT_WRITE_RE: pulling on a feature branch
178
+ // is how a stale base is refreshed, and that is not a write to protect. On a
179
+ // protected branch it is a history write, so the branch guard tests it there and
180
+ // only `--ff-only` passes.
181
+ export const GIT_PULL_RE = /\bgit\s+pull\b/;
176
182
 
177
183
  /**
178
184
  * True when `text` invokes git in a way that changes a tree's refs or content.
@@ -185,6 +191,181 @@ export function isGitTreeWriteText(text: string): boolean {
185
191
  return GIT_WRITE_RE.test(text) || GIT_BRANCH_CREATE_RE.test(text) || /\bgit\s+push\b/.test(text);
186
192
  }
187
193
 
194
+ /**
195
+ * True when `text` only fast-forwards the current protected branch to a remote
196
+ * ref it is behind: `git merge --ff-only [<ref>]`, `git rebase <ref>`, or
197
+ * `git pull --ff-only`.
198
+ *
199
+ * The branch guard blocks history writes on a protected branch because a local
200
+ * commit has had no review. A fast-forward adds no commit and rewrites none, so
201
+ * refusing it leaves a stale checkout with no way to sync, which is the defect
202
+ * in #145. Two extra facts keep the exemption narrow. The target must be a
203
+ * remote-tracking ref that is the branch's upstream or the remote default, so
204
+ * `merge --ff-only feat/local` cannot move `main` onto unreviewed local work.
205
+ * And `HEAD` must be an ancestor of that ref, so a diverged branch stays
206
+ * blocked, where a rebase would rewrite local commits.
207
+ */
208
+ export function isProtectedBranchFastForward(text: string, root: string): boolean {
209
+ const tokens = unwrapShellWords(text);
210
+ if (tokens[0] !== "git") return false;
211
+ const subcommand = tokens[1];
212
+ let ref: string | undefined;
213
+ if (subcommand === "merge") {
214
+ const args = tokens.slice(2);
215
+ if (!args.includes("--ff-only")) return false;
216
+ const positional = args.filter((arg) => arg !== "--ff-only");
217
+ if (positional.length > 1) return false;
218
+ if (positional.some((arg) => arg.startsWith("-"))) return false;
219
+ ref = positional[0];
220
+ } else if (subcommand === "rebase") {
221
+ const args = tokens.slice(2);
222
+ if (args.length > 1) return false;
223
+ if (args.some((arg) => arg.startsWith("-"))) return false;
224
+ ref = args[0];
225
+ } else if (subcommand === "pull") {
226
+ // `--ff-only` alone, and nothing else: an explicit remote and branch, or
227
+ // a rebasing pull, is not the sync this exemption covers.
228
+ const args = tokens.slice(2);
229
+ if (args.length !== 1 || args[0] !== "--ff-only") return false;
230
+ ref = undefined;
231
+ } else {
232
+ return false;
233
+ }
234
+ const target = ref ?? gitUpstreamRef(root);
235
+ if (!target) return false;
236
+ if (!isRemoteTrackingRef(target, root)) return false;
237
+ if (!isUpstreamOrRemoteDefault(target, root)) return false;
238
+ const ancestor = spawnSync("git", ["merge-base", "--is-ancestor", "HEAD", target], {
239
+ cwd: root,
240
+ encoding: "utf8",
241
+ timeout: 5_000,
242
+ });
243
+ return ancestor.status === 0;
244
+ }
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
+
327
+ /** The ref the current branch tracks, or undefined when it tracks nothing. */
328
+ function gitUpstreamRef(root: string): string | undefined {
329
+ const upstream = spawnSync("git", ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], {
330
+ cwd: root,
331
+ encoding: "utf8",
332
+ timeout: 5_000,
333
+ });
334
+ if (upstream.status !== 0) return undefined;
335
+ const name = upstream.stdout.trim();
336
+ return name && name.includes("/") ? name : undefined;
337
+ }
338
+
339
+ function gitRefExists(ref: string, root: string): boolean {
340
+ const resolved = spawnSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
341
+ cwd: root,
342
+ encoding: "utf8",
343
+ timeout: 5_000,
344
+ });
345
+ return resolved.status === 0;
346
+ }
347
+
348
+ function isRemoteTrackingRef(ref: string, root: string): boolean {
349
+ const symbolic = spawnSync("git", ["rev-parse", "--symbolic-full-name", ref], {
350
+ cwd: root,
351
+ encoding: "utf8",
352
+ timeout: 5_000,
353
+ });
354
+ if (symbolic.status !== 0) return false;
355
+ return symbolic.stdout.trim().startsWith("refs/remotes/") && gitRefExists(ref, root);
356
+ }
357
+
358
+ function isUpstreamOrRemoteDefault(ref: string, root: string): boolean {
359
+ const upstream = gitUpstreamRef(root);
360
+ if (upstream === ref) return true;
361
+ const defaultBranch = spawnSync("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
362
+ cwd: root,
363
+ encoding: "utf8",
364
+ timeout: 5_000,
365
+ });
366
+ return defaultBranch.status === 0 && defaultBranch.stdout.trim() === ref;
367
+ }
368
+
188
369
  export function currentGitBranch(root: string): string | undefined {
189
370
  const result = spawnSync("git", ["branch", "--show-current"], {
190
371
  cwd: root,
@@ -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