opencode-workflow-guard 1.19.6 → 1.20.1
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/README.md +4 -4
- package/docs/policies.md +13 -5
- package/docs/testing.md +4 -3
- package/docs/troubleshooting.md +2 -0
- package/package.json +4 -4
- package/src/lib/custom-tools.ts +30 -1
- package/src/lib/guard-dispatcher.ts +20 -1
- package/src/lib/permission-seat.ts +5 -1
- package/src/policies/delegation.ts +115 -0
- package/src/policies/destructive.ts +3 -1
- package/src/policies/git.ts +100 -0
- package/src/policies/tamper.ts +1 -0
- package/src/workflow-guard.ts +4 -0
- package/test/test.mts +158 -0
package/README.md
CHANGED
|
@@ -43,12 +43,12 @@ WORKFLOW_GUARD_LIVE_E2E=1 npm run test:install # Also run policy probes with Ope
|
|
|
43
43
|
|
|
44
44
|
## Core Guardrails Overview
|
|
45
45
|
|
|
46
|
-
The plugin enforces **
|
|
46
|
+
The plugin enforces **28 deterministic policy rules** across four main pillars:
|
|
47
47
|
|
|
48
|
-
* **Branch & History Protection:** Enforces feature-branch workflows and blocks edits and commits on `main`/`master`. Direct and forced pushes to protected branches are hard-blocked. The guard checks mergeability before PR creation, requires secondary review approval bound to the reviewed worktree content, and requires a PR changelog or changeset. An opt-in dogfood gate can additionally require a recorded run of the change on real hardware before a PR opens. Verdicts follow the tree the command actually runs in: git parsing takes the shell's `workdir` as its base, an in-command `cd`/`pushd`/`popd` and a wrapper `-C`/`-D` move the tree later segments are judged in, and a nested interpreter payload is judged by its own `cd` or `cwd` option. A linked worktree of the same repository is judged rather than boundary-blocked, a PR preflight resolves `--head`/`--source-branch` to the checkout holding that branch, and the V2 permission seat defers cwd-dependent commands to `execute.before` instead of judging the session-bound checkout. A `workdir` in a different repository is not judged: mutations and git writes there are blocked, because relative targets would be validated against the wrong tree.
|
|
48
|
+
* **Branch & History Protection:** Enforces feature-branch workflows and blocks edits and commits on `main`/`master`. The one exception is a sync: `git merge --ff-only`, `git rebase`, and `git pull --ff-only` are allowed on a protected branch when the target is its tracked upstream or the remote default and the branch is strictly behind it, because a fast-forward adds no unreviewed commit. Direct and forced pushes to protected branches are hard-blocked. The guard checks mergeability before PR creation, requires secondary review approval bound to the reviewed worktree content, and requires a PR changelog or changeset. An opt-in dogfood gate can additionally require a recorded run of the change on real hardware before a PR opens. Verdicts follow the tree the command actually runs in: git parsing takes the shell's `workdir` as its base, an in-command `cd`/`pushd`/`popd` and a wrapper `-C`/`-D` move the tree later segments are judged in, and a nested interpreter payload is judged by its own `cd` or `cwd` option. A linked worktree of the same repository is judged rather than boundary-blocked, a PR preflight resolves `--head`/`--source-branch` to the checkout holding that branch, and the V2 permission seat defers cwd-dependent commands to `execute.before` instead of judging the session-bound checkout. A `workdir` in a different repository is not judged: mutations and git writes there are blocked, because relative targets would be validated against the wrong tree.
|
|
49
49
|
* **Task & Verification Discipline:** Gates file mutations on active `todowrite` tasks, which subagents inherit. A task can be marked completed only after its own recorded work. Review and investigation tasks use an audited `[read-only]` marker instead. The guard also blocks concurrent direct edits to the same canonical file across sessions. It requires a same-session fresh read before `edit`/`write` can replace an existing file. Silent task deletion is blocked, and task completion requires fresh test verification evidence. Completion claims and sweeping repository claims are journaled against their evidence. Repeated failures force a live-documentation lookup instead of a guess from training data.
|
|
50
50
|
* **Secrets & Workspace Confinement:** Confines edit tools and recognized shell/git mutations to the workspace root, including symlink and `../` escape checks. Agent subshells have sensitive environment variables scrubbed, and `.env` reads return a safe schema mask. Arbitrary executables are not OS-sandboxed. Use containers or filesystem isolation when hard confinement is required.
|
|
51
|
-
* **Destructive CLI & Environment Safety:** Intercepts destructive cloud, database, and infrastructure commands. Stops script laundering and interpreter evasion, blocks TTY hangs such as `vim`, `nano`, and `sudo`, and guards against dangerous package manager flags.
|
|
51
|
+
* **Destructive CLI, Delegation & Environment Safety:** Intercepts destructive cloud, database, and infrastructure commands. Stops script laundering and interpreter evasion, blocks TTY hangs such as `vim`, `nano`, and `sudo`, and guards against dangerous package manager flags. It also refuses a shell-spawned agent CLI (`claude`, `codex`, `gemini`, `aider`, `opencode run`), because a spawned agent runs outside the guard's hooks; the host's `task` tool is the governed path to a subagent.
|
|
52
52
|
|
|
53
53
|
For complete policy specifications and override rules, see [docs/policies.md](docs/policies.md).
|
|
54
54
|
|
|
@@ -74,7 +74,7 @@ The context modules are project memory, Socratic learning, and recovery checkpoi
|
|
|
74
74
|
|
|
75
75
|
| Guide | Description |
|
|
76
76
|
|---|---|
|
|
77
|
-
| [**Policy Reference**](docs/policies.md) | Specification of all
|
|
77
|
+
| [**Policy Reference**](docs/policies.md) | Specification of all 28 enforced policies, invariants, and the proactive tool surface (`guard_*`, `project_memory_*`, `learning_*`) |
|
|
78
78
|
| [**Installation & Configuration**](docs/installation.md) | Setup options, global and local install, worktree isolation, and project configuration |
|
|
79
79
|
| [**Static Policy Posture**](docs/policy-posture.md) | How the guard emits host-level policies for invariants a repository cannot lift. Covers both host envelopes (`experimental.policies` on 2.0.x, top-level `policies` on 2.1.x), precedence, and residual risk |
|
|
80
80
|
| [**Managed Deployment**](docs/managed-deployment.md) | Administrator-managed OpenCode policy, platform locations, and startup diagnostics |
|
package/docs/policies.md
CHANGED
|
@@ -56,8 +56,8 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
56
56
|
- Helm: `helm uninstall`, `helm rollback`, `helm delete`
|
|
57
57
|
- IaC: `terraform destroy`, `tofu destroy`, `pulumi destroy`
|
|
58
58
|
- Containers: `docker rm`, `docker container/system/image/volume prune`, `docker volume rm`
|
|
59
|
-
- Cloud: `az ... delete/purge`, `aws ... delete/terminate`, `gcloud ... delete/abandon`
|
|
60
|
-
- Hosted Git: `gh repo/issue/pr/release/secret/variable delete|close`
|
|
59
|
+
- Cloud: `az ... delete/purge`, `aws ... delete/terminate`, `gcloud ... delete/abandon`, and Azure RBAC role-assignment changes (`az role assignment` create/delete), which grant privilege rather than removing a resource
|
|
60
|
+
- Hosted Git: `gh repo/issue/pr/release/secret/variable delete|close|merge`, and a raw `DELETE` request through `gh api`
|
|
61
61
|
- Databases: `psql/mysql/mariadb/mongosh/redis-cli/sqlite3` drop, delete, truncate, and flushall, plus `prisma migrate reset`
|
|
62
62
|
- Remote HTTP: `curl -X DELETE` against non-localhost endpoints
|
|
63
63
|
- Git: `git push --force`, `git push +refspec`, `git clean -fdx`
|
|
@@ -73,7 +73,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
73
73
|
- Prevents the agent from weakening its own permission gates **via shell or edit tools**:
|
|
74
74
|
- Shell writes/redirects to `opencode.json[c]`, `~/.config/opencode/*`, `.opencode/*` (including the `.opencode` directory itself), or the guard's own plugin/TUI files (`~/.config/opencode/plugins/*`, `~/.config/opencode/ui/*`)
|
|
75
75
|
- Direct edits of the same paths through the `edit`/`write`/`apply_patch` tools
|
|
76
|
-
- Shell commands invoking `opencode auth`, `opencode config`, `opencode permission`, or `opencode run --auto`
|
|
76
|
+
- Shell commands invoking `opencode auth`, `opencode config`, `opencode permission`, `opencode plugin`, or `opencode mcp` mutations (`add`, `remove`, `install`, and the bare package form), or `opencode run --auto`. Read-only forms such as `opencode plugin list` and `opencode mcp list` stay allowed.
|
|
77
77
|
- Evasion-normalized: quote-concatenation (`open''code.json`), escapes (`open\c\ode`), and glob wildcards (`opencode.jso?`) are stripped before matching.
|
|
78
78
|
- Collaboration commands (`gh issue`, `gh pr`, `glab issue`, `glab pr`, `az repos pr`) and document content mentioning guarded paths are not tampering. Quoted arguments are command data, not shell syntax. The redirect heuristic applies to shell commands only. Write and edit content is guarded by the target path check instead.
|
|
79
79
|
- 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.
|
|
@@ -82,7 +82,8 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
82
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
83
|
|
|
84
84
|
### 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`.
|
|
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`. A `pull` on the protected branch is blocked too, because with `pull.rebase` set it rewrites local commits.
|
|
86
|
+
- **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
87
|
- Git global flags are parsed, so `git -C /repo commit` is gated on `/repo`'s branch, not the workspace's.
|
|
87
88
|
- The agent is prompted to create a feature branch first (`git switch -c feat/my-feature`).
|
|
88
89
|
|
|
@@ -117,7 +118,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
117
118
|
- **Git State & Snapshot Binding:** Verification evidence records the current git commit hash (`git rev-parse HEAD`) and working tree status. If unverified edits or index modifications occur after verification, fresh verification is enforced.
|
|
118
119
|
- **Untracked Special Entries:** The worktree fingerprint binds untracked symlinks by their target string. It follows git semantics, so re-pointing a link moves the fingerprint and changing the link target's contents does not. FIFOs and sockets are bound by path and mode. Unopenable entries are skipped with a `worktree-fingerprint` warning in the audit trail instead of voiding the whole fingerprint. One unreadable scratch symlink or `chmod 000` file can no longer make review or verification evidence permanently unfresh. The PR preflight names the actual cause when an approval cannot be matched: no fingerprint binding, fingerprint mismatch, or uncomputable fingerprint. It no longer shows the generic "review approval required". Documented tradeoff: the contents of a skipped entry are excluded from the fingerprint. A file that stays unreadable to the guard's user across the entire window can therefore change contents without moving the fingerprint. Any readability transition is fingerprint-visible (fail-closed), and each skip is named in the durable audit trail.
|
|
119
120
|
- **Durable Disk Cache:** Passing verification results (`~/.local/state/opencode/workflow-guard/last-verify.json`) and passing secondary review approvals (`~/.local/state/opencode/workflow-guard/last-review.json`) are cached to disk. Session restarts and multi-agent handoffs can therefore retain valid verification and review evidence without redundant test runs. Durable evidence is **workspace-bound**: a cached result is only accepted for the workspace that produced it. A passing run in one project can never satisfy finalization in another.
|
|
120
|
-
- **Evidence Visibility:** `guard_status.lastVerify` reports the command, pass state, freshness, evidence id, commit hash, observation timestamp, and duration, so a green gate leaves a record with a time and the commit it covered. `guard_status.lastReview` adds its observation timestamp plus `recorderSessionID`, `recorderRole` (`root` or `subagent`), and `targetSessionID`. With `requireSubagentReview` on, that lineage shows the approval came from a subagent rather than the root session it was recorded for.
|
|
121
|
+
- **Evidence Visibility:** `guard_status.lastVerify` reports the command, pass state, freshness, evidence id, commit hash, observation timestamp, and `durationMs` (the verification run's wall-clock duration), so a green gate leaves a record with a time, a duration, and the commit it covered. `guard_status.lastReview` adds its observation timestamp plus `recorderSessionID`, `recorderRole` (`root` or `subagent`), and `targetSessionID`. With `requireSubagentReview` on, that lineage shows the approval came from a subagent rather than the root session it was recorded for.
|
|
121
122
|
- If verification fails, finalization is blocked with a structured summary of error markers, stack traces, and failure output.
|
|
122
123
|
- OpenCode's current `lsp.client.diagnostics` event identifies the server and path. It does not expose the diagnostics themselves. The guard therefore does not claim an LSP-clean finalization gate until the SDK provides a supported diagnostics source.
|
|
123
124
|
- The verify command is **disabled** when `WORKFLOW_GUARD_VERIFY` is empty (`""`).
|
|
@@ -227,6 +228,13 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
227
228
|
- Freshness is content-scoped like the review gate, so a nested run in a linked worktree can inherit the binding for identical tracked content. A record for unrelated content never satisfies the gate.
|
|
228
229
|
- `guard_status` reports `lastDogfood` and adds `dogfood` to `outstandingRequirements` when the gate is unsatisfied, naming the matrix hosts still missing a passing run.
|
|
229
230
|
|
|
231
|
+
### 28. Agent Delegation Boundary (`shell`)
|
|
232
|
+
- Blocks spawning another AI agent CLI from a shell. The covered executables are `claude` (also `claude-code`), `codex`, `gemini` (also `gemini-cli`), `aider` (also `aider-chat`), and `opencode run`. The Node runner forms (`npx`, `bunx`, `pnpx`) are covered for the same package names.
|
|
233
|
+
- A shell-spawned agent runs outside this session's hooks. Its file mutations, git history changes, verification runs, and live-system calls never reach the guard, so it is a way around every other policy. The host's `task` tool is the governed path: the guard hooks `execute.before` there and enforces role confinement, todo inheritance, and the mutation budget.
|
|
234
|
+
- Detection is command position only. `grep claude README.md`, `echo "run claude for details"`, and a prose heredoc that mentions a launcher stay allowed. Wrappers (`env`, `sudo`, `timeout`, `command`, `nohup`), a chained segment, a grouping subshell, and an inline interpreter payload are unwrapped first, so `env FOO=1 claude -p x`, `echo hi | claude`, `bash -c 'claude -p x'`, and `eval 'claude -p x'` are refused.
|
|
235
|
+
- The policy has no override. `WORKFLOW_GUARD_ALLOW_LIVE=1` covers live-system commands only, and delegation is a workflow-boundary rule rather than a live mutation.
|
|
236
|
+
- Known limit: indirection this walk does not model, such as `xargs claude` or a script file that invokes a launcher, is not detected. That matches the documented known limits for monitors and destructive commands.
|
|
237
|
+
|
|
230
238
|
### Tool Description Honesty & Cross-Model Adherence
|
|
231
239
|
- Via the `tool.definition` hook, the guard enriches tool descriptions to keep them honest and proactive across all model families. The families are OpenAI, Gemini, Claude, and open-weights models:
|
|
232
240
|
- `todowrite`: Explains its replacement-list lifecycle, finalization verification gate, and directs models to `guard_next_tasks` for roadmap discovery and `guard_status` for gate checks.
|
package/docs/testing.md
CHANGED
|
@@ -45,11 +45,11 @@ npm run test:all
|
|
|
45
45
|
| **Policy 1: Subagent Inheritance** | Verifies subagents walk up the `parentID` hierarchy to inherit parent/grandparent todos, and handles cycle termination. |
|
|
46
46
|
| **Policies 2 & 7: Git Branches** | Verifies push blocking on `main`/`master`, feature-branch editing allowances, and git commit gates. |
|
|
47
47
|
| **Policy 3: PR Changelog** | Verifies `gh pr create` requires a changelog in body or diff. |
|
|
48
|
-
| **Policy 4: Live Commands** | Verifies destructive CLI command blocking across Kubernetes, Terraform, Helm, cloud CLIs, and databases, plus user-set `WORKFLOW_GUARD_ALLOW_LIVE=1` override. |
|
|
48
|
+
| **Policy 4: Live Commands** | Verifies destructive CLI command blocking across Kubernetes, Terraform, Helm, cloud CLIs, and databases, plus user-set `WORKFLOW_GUARD_ALLOW_LIVE=1` override. Also verifies Azure RBAC role-assignment creation, a PR merge through `gh`, and a raw DELETE request through `gh api` are blocked, including wrapped and chained forms, while a role-assignment list and a read-only API call stay allowed. |
|
|
49
49
|
| **Policy 5: MCP Mutations** | Verifies GitHub/Azure mutating MCP tools are blocked while read-only tools pass. |
|
|
50
|
-
| **Policy 6: Settings Tamper** | Verifies protection of `opencode.json`, `~/.config/opencode/*`,
|
|
50
|
+
| **Policy 6: Settings Tamper** | Verifies protection of `opencode.json`, `~/.config/opencode/*`, `opencode auth`, and the plugin and MCP mutating verbs (`plugin add/remove`, `mcp add`), including a global-flag form, while `plugin list` and `mcp list` stay allowed. |
|
|
51
51
|
| **Policy 8: Workspace Boundary** | Verifies path traversal (`../`), symlinks, and absolute path escape protection in `edit`, `write`, `apply_patch`, and shell mutations. Also verifies the `/tmp/opencode` scratch allowance: a real session may write, redirect, patch, and run an interpreter payload there, while a session-less write, a sibling that shares the prefix, a `..` traversal out of it, and a symlink that leaves it stay blocked. |
|
|
52
|
-
| **Policy 10: Evidence Verification** | Verifies isolated verification execution, timeout handling, scrubbed environment, and finalization gating on fresh passing tests. A timeout blocks finalization under its own code, and its reason names the limit and the remedy instead of claiming a failing test. Also verifies `guard_status` names the project config file it read, attributes the effective verify command to `project-config`, `auto-detected`, or neither, and puts the environment ahead of both. A configured command that passes leaves `lastVerify` with a timestamp and commit hash, a later mutation makes it not fresh, and a deliberately failing configured command blocks finalization. |
|
|
52
|
+
| **Policy 10: Evidence Verification** | Verifies isolated verification execution, timeout handling, scrubbed environment, and finalization gating on fresh passing tests. A timeout blocks finalization under its own code, and its reason names the limit and the remedy instead of claiming a failing test. Also verifies `guard_status` names the project config file it read, attributes the effective verify command to `project-config`, `auto-detected`, or neither, and puts the environment ahead of both. A configured command that passes leaves `lastVerify` with a timestamp, a `durationMs`, and a commit hash, a later mutation makes it not fresh, and a deliberately failing configured command blocks finalization. |
|
|
53
53
|
| **File-Claim TTL Reclaim** | Verifies a claim within the TTL blocks and names the reclaim step, an expired claim is reclaimed for the next claimant, the reclaim writes a `claim_ttl_expired` audit with the owner and age, the environment override wins, and project config `claimTtlMs` is honored. |
|
|
54
54
|
| **Shell Mutation Claim Conflicts** | Verifies a redirect into a claimed path is refused with the claim reason, `tee -a` with its flag parsed is refused, a symlink alias is refused, a chained `cd` is judged in the tree it lands in, a multi-operand mutation is refused when any operand is claimed, a `mv` source is refused because the move removes it, a subagent is refused on a path its parent claimed, `guard_why` reports the conflict as a shell mutation without acquiring a claim, an unclaimed path stays allowed, and the path is allowed once the owning edit releases its claim. |
|
|
55
55
|
| **Review Rubric Provenance** | Verifies the rubric names the workspace, base ref, and diff byte count it graded; grades a linked worktree named by `directory` rather than the caller's checkout; refuses when no base yields a diff, naming the workspace, every base tried, and the remedy, without emitting a rubric body over a substitute range; and honors an explicit `HEAD~1` base with `base=HEAD~1 fallback=HEAD~1`. Also verifies the injected workflow guidance names the calling session as the recorder rather than the subagent. |
|
|
@@ -66,4 +66,5 @@ npm run test:all
|
|
|
66
66
|
| **Per-Task Completion Evidence** | Verifies a task cannot move to `completed` without a mutation in its own window, that one mutation cannot vouch for several completions, that staggered windows reject a claim whose window saw no work, that mutations before a task became active never count, that `[read-only]` completes freely and is journaled, that the marker can be appended to an already-planned task without tripping the no-silent-deletion rule, that duplicate content cannot hide a new completion, and that `guard_why` reports the same verdict while moving no window. |
|
|
67
67
|
| **Static Policy Posture** | Verifies the emitted posture is deny-only, emits both host envelopes (`experimental.policies`/`permission` for 2.0.x, top-level `policies`/`tool.use` for 2.1.x), requires both to reach the same verdict for every probed resource, and matches the intended commands under a replica of the host's whole-string glob matcher, including the compound-command evasion it does not cover. |
|
|
68
68
|
| **Dogfood Gate (Policy 27)** | Verifies the gate stays off until a repository opts in, that PR creation is blocked without fresh evidence and allowed with it, that a tracked edit and a new commit each invalidate the record with a named cause, that a HOLD is never durable and removes that host's cached pass so a restart cannot re-satisfy the gate, that a same-millisecond HOLD and PASS resolve to the HOLD in the durable cache so a restart stays unsatisfied, that a later pass on another host cannot resurrect an evicted one, that a HOLD in a cold process or in another workspace leaves unrelated hosts' passes intact, that an out-of-matrix HOLD is not reported as the blocking cause, that a `pass` is refused when any check is skipped or the check list is empty, that a HOLD must name a taxonomy class, that an actor session cannot record its own verdict, that the deploy matrix needs one fresh pass per host, that a newer HOLD on a host reopens the gate, that the PR audit names every covered host, and that per-host retention cannot evict another host's pass. |
|
|
69
|
+
| **Policy 28: Agent Delegation Boundary** | Verifies `claude`, `codex`, `gemini`, `aider`, and `opencode run` are blocked in command position, through wrappers (`env`, `sudo`, `timeout`, `command`), a chained segment, a grouping subshell, `npx`/`bunx` package execution, `bash -c`, `eval`, and a code heredoc; that a read-only and a worker subagent are both refused; and that an argument-only mention, a quoted prose mention, and a prose heredoc stay allowed. |
|
|
69
70
|
| **Modular Exports & Shape** | Verifies V1 `PluginModule` `{ id, server }` structure, modular policy imports, and `output.args` hook contract. |
|
package/docs/troubleshooting.md
CHANGED
|
@@ -42,6 +42,8 @@ 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
|
+
|
|
45
47
|
---
|
|
46
48
|
|
|
47
49
|
### 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.
|
|
3
|
+
"version": "1.20.1",
|
|
4
4
|
"description": "Deterministic workflow and safety policy enforcement for OpenCode",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -51,9 +51,9 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@opencode-ai/plugin": "1.19.5",
|
|
54
|
-
"@opencode/ai": "2.
|
|
55
|
-
"@opencode/plugin": "2.
|
|
56
|
-
"@opentui/solid": "0.
|
|
54
|
+
"@opencode/ai": "2.3.0",
|
|
55
|
+
"@opencode/plugin": "2.3.0",
|
|
56
|
+
"@opentui/solid": "0.9.2",
|
|
57
57
|
"jsonc-parser": "3.3.1"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
package/src/lib/custom-tools.ts
CHANGED
|
@@ -346,7 +346,36 @@ export function createCustomTools(options: {
|
|
|
346
346
|
}
|
|
347
347
|
const ralphOutcome = runWithRuntimeState(root, client, () => getRalphOutcome(toolContext.sessionID));
|
|
348
348
|
const taskEvidence = await runWithRuntimeState(root, client, () => todoEvidenceReport(toolContext.sessionID));
|
|
349
|
-
|
|
349
|
+
const verifySnapshot = lastV && verifyEvidence
|
|
350
|
+
? { command: lastV.command, passed: lastV.passed, fresh: verifyFresh, evidenceId: verifyEvidence.id, commitHash: lastV.commitHash, timestamp: lastV.timestamp, durationMs: lastV.durationMs ?? null }
|
|
351
|
+
: null;
|
|
352
|
+
const reviewSnapshot = lastR && reviewEvidenceRecord
|
|
353
|
+
? { reviewer: lastR.reviewer, passed: lastR.passed, summary: lastR.summary, fresh: reviewFresh, evidenceId: reviewEvidenceRecord.id, timestamp: lastR.timestamp, targetSessionID: lastR.targetSessionID ?? null, recorderSessionID: lastR.recorderSessionID ?? null, recorderRole: lastR.recorderRole ?? null }
|
|
354
|
+
: null;
|
|
355
|
+
const dogfoodSnapshot = lastD && lastDogfoodEvidence
|
|
356
|
+
? { scenarioId: lastD.scenarioId, verdict: lastD.verdict, host: lastD.host.label, taxonomyClass: lastD.taxonomyClass ?? null, runCount: lastD.runCount, fresh: dogfoodGate.required ? dogfoodFresh : null, evidenceId: lastDogfoodEvidence.id, missingHosts: dogfoodGate.missingHosts, coveredHosts: (dogfoodGate.matchedRecords ?? []).map((record) => record.host.label) }
|
|
357
|
+
: null;
|
|
358
|
+
const statusSnapshot = {
|
|
359
|
+
pluginVersion: loadedPluginVersion() ?? null,
|
|
360
|
+
qualifiedHostVersion: qualifiedHostVersion() ?? null,
|
|
361
|
+
hostVersion: hostVersion?.() ?? null,
|
|
362
|
+
workspaceRoot: root,
|
|
363
|
+
branch,
|
|
364
|
+
onProtectedBranch: isProtected,
|
|
365
|
+
todoCapability: todoCapability ? todoCapability() : "available",
|
|
366
|
+
taskEvidence,
|
|
367
|
+
outstandingRequirements,
|
|
368
|
+
recommendedActions,
|
|
369
|
+
lastMutationTimestamp: lastMut,
|
|
370
|
+
mutationCount: getWorkspaceMutationCount(root),
|
|
371
|
+
lastVerify: verifySnapshot,
|
|
372
|
+
lastReview: reviewSnapshot,
|
|
373
|
+
lastDogfood: dogfoodSnapshot,
|
|
374
|
+
ralph: { enabled: isRalphModeEnabled(root), maxIterations: getRalphMaxIterations(root), outcome: ralphOutcome ?? null },
|
|
375
|
+
projectConfig: { configPath: existingProjectConfigPath(root) ?? null, profile: getOperationProfile(root), protectedBranches: cfg.protectedBranches ?? ["main", "master"], verifyCommand: verifyCommand ?? null, verifyCommandSource: verifySource, requireReview: reviewRequired, requireDocumentation: documentationRequired, requireSubagentReview: isSubagentReviewRequired(root), requireDogfood: dogfoodGate.required, dogfoodDeployMatrix: dogfoodGate.required ? getDogfoodDeployMatrix(root) : [], recoveryCheckpoints: isRecoveryCheckpointsEnabled(root) },
|
|
376
|
+
gitHygiene: gitHygieneSnapshot(root) ?? null,
|
|
377
|
+
};
|
|
378
|
+
return JSON.stringify(statusSnapshot, null, 2);
|
|
350
379
|
},
|
|
351
380
|
}),
|
|
352
381
|
guard_audit: tool({ description: "View recent audit entries recorded by opencode-workflow-guard. Use to diagnose policy decisions, blocked commands, or outcome telemetry.", args: { limit: tool.schema.number().optional().describe("Maximum entries to return (default 10)") }, execute: async (args) => JSON.stringify(getRecentAuditEntries(typeof args?.limit === "number" ? Math.min(args.limit, 50) : 10), null, 2) }),
|
|
@@ -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,6 +63,7 @@ import {
|
|
|
62
63
|
hasUnsafeGitAlias,
|
|
63
64
|
isBranchAlreadyMergedOrClosed,
|
|
64
65
|
isGitTreeWriteText,
|
|
66
|
+
isProtectedBranchFastForward,
|
|
65
67
|
normalizeGitCommands,
|
|
66
68
|
onProtectedBranch,
|
|
67
69
|
parseGitInvocation,
|
|
@@ -69,6 +71,7 @@ import {
|
|
|
69
71
|
pushedProtectedBranchIn,
|
|
70
72
|
tagRefspecIn,
|
|
71
73
|
} from "../policies/git.ts";
|
|
74
|
+
import { DELEGATION_REASON, delegationSpawnIn } from "../policies/delegation.ts";
|
|
72
75
|
import { extractInterpreterPayload, outsideWritePathInPayload, secretPathInPayload, writePathsInPayload } from "../policies/interpreter.ts";
|
|
73
76
|
import { mcpMutationTool } from "../policies/mcp.ts";
|
|
74
77
|
import { editTargets } from "../policies/post-edit-validation.ts";
|
|
@@ -489,6 +492,11 @@ export async function guardToolCallImpl(
|
|
|
489
492
|
logPolicyBlock(`[workflow-guard] blocked package supply-chain violation: ${command.slice(0, 100)}`);
|
|
490
493
|
return block("shell-safety", "package_hygiene", `Blocked: '${command.slice(0, 60)}' is a ${packageCheck.name}. ${packageCheck.advice}`);
|
|
491
494
|
}
|
|
495
|
+
const delegated = delegationSpawnIn(raw);
|
|
496
|
+
if (delegated) {
|
|
497
|
+
logPolicyBlock(`[workflow-guard] blocked agent delegation via ${delegated}: ${command.slice(0, 100)}`);
|
|
498
|
+
return block("delegation", "agent_delegation", DELEGATION_REASON);
|
|
499
|
+
}
|
|
492
500
|
const normalizedCommand = normalizeGitCommands(command);
|
|
493
501
|
if (hasUnsafeGitAlias(command)) return block("git", "unsafe_git_alias", "Blocked: per-invocation Git aliases cannot be used because they can hide guarded Git operations.");
|
|
494
502
|
// Each segment is judged in the directory it actually runs in. A `cd`
|
|
@@ -547,7 +555,13 @@ export async function guardToolCallImpl(
|
|
|
547
555
|
}
|
|
548
556
|
for (const invocation of gitInvocations) {
|
|
549
557
|
if (tagRefspecIn(`git ${invocation.rest}`, invocation.repoDir)) continue;
|
|
550
|
-
|
|
558
|
+
// A fast-forward of a protected branch to its tracked upstream adds no
|
|
559
|
+
// commit and rewrites none, so it is the one history write that cannot
|
|
560
|
+
// skip review. Refusing it leaves the checkout stale with no safe way
|
|
561
|
+
// to sync (#145).
|
|
562
|
+
const gitText = `git ${invocation.rest}`;
|
|
563
|
+
const protectedWrite = GIT_WRITE_RE.test(gitText) || GIT_PULL_RE.test(gitText);
|
|
564
|
+
if (protectedWrite && onProtectedBranch(invocation.repoDir) && !isProtectedBranchFastForward(gitText, invocation.repoDir)) {
|
|
551
565
|
logPolicyBlock(`[workflow-guard] blocked git write on protected branch: ${command.slice(0, 120)}`);
|
|
552
566
|
return block("git", "protected_branch", branchGuardReason());
|
|
553
567
|
}
|
|
@@ -631,6 +645,11 @@ export async function guardToolCallImpl(
|
|
|
631
645
|
return block("destructive", "live_mutation_payload", `Blocked: inline interpreter script contains a ${liveCheck}. Interpreter payloads cannot smuggle live destructive commands past the guard.`);
|
|
632
646
|
}
|
|
633
647
|
}
|
|
648
|
+
const delegatedPayload = delegationSpawnIn(payload);
|
|
649
|
+
if (delegatedPayload) {
|
|
650
|
+
logPolicyBlock(`[workflow-guard] blocked agent delegation via ${delegatedPayload} in an inline payload`);
|
|
651
|
+
return block("delegation", "agent_delegation", DELEGATION_REASON);
|
|
652
|
+
}
|
|
634
653
|
if (isSettingsTamper(payload)) return block("tamper", "settings_tamper", PROTECTED_PATH_REASON);
|
|
635
654
|
const secretPath = secretPathInPayload(payload);
|
|
636
655
|
if (secretPath) return block("secrets", "secret_read", `Blocked: reading sensitive credential/secret file '${secretPath}' via inline interpreter script is not permitted.`);
|
|
@@ -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
|
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
import { splitShellSegments, unwrapShellWords } from "../lib/shell.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Agent-delegation boundary.
|
|
6
|
+
*
|
|
7
|
+
* A shell-spawned agent CLI runs outside this session's hooks: its edits,
|
|
8
|
+
* pushes, verification runs, and live-system calls never reach the guard. The
|
|
9
|
+
* host's `task` tool is the governed path to a subagent, because the guard hooks
|
|
10
|
+
* `execute.before` there and enforces role confinement, todo inheritance, and
|
|
11
|
+
* the mutation budget. This policy refuses the shell path, not delegation.
|
|
12
|
+
*
|
|
13
|
+
* Detection is command-position only. `grep claude CHANGELOG.md` and prose that
|
|
14
|
+
* quotes a launcher stay allowed. Wrappers (`env`, `sudo`, `timeout`,
|
|
15
|
+
* `command`), a chained segment, a grouping subshell, and an inline interpreter
|
|
16
|
+
* payload are unwrapped first.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export const DELEGATION_REASON =
|
|
20
|
+
"Blocked: spawning another AI agent CLI from a shell is not allowed. " +
|
|
21
|
+
"The spawned agent runs outside this session's workflow guard, so its file " +
|
|
22
|
+
"mutations, git history changes, and live-system calls are not checked by " +
|
|
23
|
+
"the policies above it. Delegate through the host's task tool so the " +
|
|
24
|
+
"guard's hooks still apply, or ask the user to run the delegated agent.";
|
|
25
|
+
|
|
26
|
+
// Package and executable names for the agent CLIs an agent must not spawn.
|
|
27
|
+
// The value is the name reported in the block reason.
|
|
28
|
+
const AGENT_CLI_BASENAMES = new Map<string, string>([
|
|
29
|
+
["claude", "claude"],
|
|
30
|
+
["claude-code", "claude"],
|
|
31
|
+
["codex", "codex"],
|
|
32
|
+
["gemini", "gemini"],
|
|
33
|
+
["gemini-cli", "gemini"],
|
|
34
|
+
["aider", "aider"],
|
|
35
|
+
["aider-chat", "aider"],
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
// Node package runners that install and execute an agent CLI in one step.
|
|
39
|
+
// `npx claude-code` delegates exactly like `claude` does.
|
|
40
|
+
const NODE_RUNNERS = new Set(["npx", "bunx", "pnpx"]);
|
|
41
|
+
|
|
42
|
+
// OpenCode global flags that consume the following word. The subcommand is the
|
|
43
|
+
// first non-flag word, so the value of one of these must not be read as it.
|
|
44
|
+
const OPENCODE_VALUE_FLAGS = new Set(["-d", "--dir", "-m", "--model", "-l", "--log-level"]);
|
|
45
|
+
// A help or version request runs nothing, so a word after it is data.
|
|
46
|
+
const OPENCODE_INFO_FLAGS = new Set(["-h", "--help", "-v", "--version"]);
|
|
47
|
+
|
|
48
|
+
function executableName(word: string): string {
|
|
49
|
+
return basename(word).toLowerCase();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function opencodeSubcommand(words: readonly string[]): string | undefined {
|
|
53
|
+
let i = 1;
|
|
54
|
+
while (i < words.length) {
|
|
55
|
+
const word = words[i]!;
|
|
56
|
+
if (word === "--") {
|
|
57
|
+
i += 1;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (word.startsWith("-")) {
|
|
61
|
+
const name = word.split("=", 1)[0]!;
|
|
62
|
+
if (OPENCODE_INFO_FLAGS.has(name)) return undefined;
|
|
63
|
+
i += word.includes("=") || !OPENCODE_VALUE_FLAGS.has(name) ? 1 : 2;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
return word;
|
|
67
|
+
}
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function packageName(word: string): string {
|
|
72
|
+
// `claude-code@latest` and `@scope/pkg` both reduce to the package name.
|
|
73
|
+
return executableName(word.replace(/@[^/]*$/, ""));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function npxAgentIn(words: readonly string[]): string | undefined {
|
|
77
|
+
let i = 1;
|
|
78
|
+
while (i < words.length) {
|
|
79
|
+
const word = words[i]!;
|
|
80
|
+
if (word === "-p" || word === "--package") {
|
|
81
|
+
const named = AGENT_CLI_BASENAMES.get(packageName(words[i + 1] ?? ""));
|
|
82
|
+
if (named) return named;
|
|
83
|
+
i += 2;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (word.startsWith("-")) {
|
|
87
|
+
i += 1;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
return AGENT_CLI_BASENAMES.get(packageName(word));
|
|
91
|
+
}
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function agentCliIn(words: readonly string[]): string | undefined {
|
|
96
|
+
if (words.length === 0) return undefined;
|
|
97
|
+
const executable = executableName(words[0]!);
|
|
98
|
+
const direct = AGENT_CLI_BASENAMES.get(executable);
|
|
99
|
+
if (direct) return direct;
|
|
100
|
+
// `opencode run` is a delegated agent turn. Its other verbs are read-only
|
|
101
|
+
// or covered by the settings-tamper policy, so they are not this policy.
|
|
102
|
+
if (executable === "opencode") {
|
|
103
|
+
return opencodeSubcommand(words) === "run" ? "opencode run" : undefined;
|
|
104
|
+
}
|
|
105
|
+
if (NODE_RUNNERS.has(executable)) return npxAgentIn(words);
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function delegationSpawnIn(command: string): string | undefined {
|
|
110
|
+
for (const segment of splitShellSegments(command)) {
|
|
111
|
+
const found = agentCliIn(unwrapShellWords(segment));
|
|
112
|
+
if (found) return found;
|
|
113
|
+
}
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
@@ -35,11 +35,13 @@ export const LIVE_MUTATION_PATTERNS: LivePattern[] = [
|
|
|
35
35
|
{ re: new RegExp(`\\bdocker\\s+volume\\s+${W_RM}\\b`), what: ["docker ", "volume removal"].join("") },
|
|
36
36
|
// Cloud CLI deletions
|
|
37
37
|
{ re: new RegExp(`\\baz\\s+\\S+\\s+(?:${W_DEL}|${W_PURGE})\\b`), what: ["Azure ", "resource deletion"].join("") },
|
|
38
|
+
{ re: /\baz\s+role\s+assignment\s+(?:create|delete)\b/, what: ["Azure RBAC ", "role-assignment change (privilege escalation)"].join("") },
|
|
38
39
|
{ re: new RegExp(`\\baz\\s+(?:devops|repos|pipelines|boards|artifacts)\\s+[\\w-]*\\s*(?:${W_DEL}|${W_ABANDON})\\b`), what: ["Azure ", "DevOps deletion"].join("") },
|
|
39
40
|
{ re: new RegExp(`\\baws\\s+\\S+\\s+(?:${W_DEL}|${W_TERM})-?\\w*\\b`), what: ["AWS ", "resource deletion"].join("") },
|
|
40
41
|
{ re: new RegExp(`\\bgcloud\\s+\\S+\\s+(?:${W_DEL}|${W_ABANDON})\\b`), what: ["GCP ", "resource deletion"].join("") },
|
|
41
42
|
// Hosted repo / PR destruction via CLI
|
|
42
|
-
{ re: new RegExp(`\\bgh\\s+(?:repo|issue|pr|release|secret|variable)\\s+(?:${W_DEL}|close)\\b`), what: ["gh ", "destructive command"].join("") },
|
|
43
|
+
{ re: new RegExp(`\\bgh\\s+(?:repo|issue|pr|release|secret|variable)\\s+(?:${W_DEL}|close|merge)\\b`), what: ["gh ", "destructive command"].join("") },
|
|
44
|
+
{ re: new RegExp(`\\bgh\\s+api\\b[^|;&]*(?:-X|--method)\\s*=?\\s*${W_HTTP_DEL}\\b`), what: ["GitHub API ", "DELETE request"].join("") },
|
|
43
45
|
// Database destruction via CLI clients
|
|
44
46
|
{ re: new RegExp(`\\b(?:psql|mysql|mariadb|mongosh|mongo|redis-cli|sqlite3)\\b[^|;&]*\\b(?:${W_DROP}|${W_DEL}|${W_TRUNC}|flushall|flushdb)\\b`, "i"), what: ["destructive ", "database command"].join("") },
|
|
45
47
|
{ re: new RegExp(`\\b(?:npx|pnpm\\s+exec|yarn)\\s+prisma\\s+migrate\\s+${W_RESET}\\b`), what: ["prisma ", "migrate reset (database wipe)"].join("") },
|
package/src/policies/git.ts
CHANGED
|
@@ -174,6 +174,12 @@ export function normalizeGitCommands(command: string): string {
|
|
|
174
174
|
export const GIT_WRITE_RE =
|
|
175
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/;
|
|
176
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/;
|
|
182
|
+
|
|
177
183
|
/**
|
|
178
184
|
* True when `text` invokes git in a way that changes a tree's refs or content.
|
|
179
185
|
*
|
|
@@ -185,6 +191,100 @@ 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
|
+
/** The ref the current branch tracks, or undefined when it tracks nothing. */
|
|
247
|
+
function gitUpstreamRef(root: string): string | undefined {
|
|
248
|
+
const upstream = spawnSync("git", ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], {
|
|
249
|
+
cwd: root,
|
|
250
|
+
encoding: "utf8",
|
|
251
|
+
timeout: 5_000,
|
|
252
|
+
});
|
|
253
|
+
if (upstream.status !== 0) return undefined;
|
|
254
|
+
const name = upstream.stdout.trim();
|
|
255
|
+
return name && name.includes("/") ? name : undefined;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function gitRefExists(ref: string, root: string): boolean {
|
|
259
|
+
const resolved = spawnSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
|
|
260
|
+
cwd: root,
|
|
261
|
+
encoding: "utf8",
|
|
262
|
+
timeout: 5_000,
|
|
263
|
+
});
|
|
264
|
+
return resolved.status === 0;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function isRemoteTrackingRef(ref: string, root: string): boolean {
|
|
268
|
+
const symbolic = spawnSync("git", ["rev-parse", "--symbolic-full-name", ref], {
|
|
269
|
+
cwd: root,
|
|
270
|
+
encoding: "utf8",
|
|
271
|
+
timeout: 5_000,
|
|
272
|
+
});
|
|
273
|
+
if (symbolic.status !== 0) return false;
|
|
274
|
+
return symbolic.stdout.trim().startsWith("refs/remotes/") && gitRefExists(ref, root);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function isUpstreamOrRemoteDefault(ref: string, root: string): boolean {
|
|
278
|
+
const upstream = gitUpstreamRef(root);
|
|
279
|
+
if (upstream === ref) return true;
|
|
280
|
+
const defaultBranch = spawnSync("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
|
|
281
|
+
cwd: root,
|
|
282
|
+
encoding: "utf8",
|
|
283
|
+
timeout: 5_000,
|
|
284
|
+
});
|
|
285
|
+
return defaultBranch.status === 0 && defaultBranch.stdout.trim() === ref;
|
|
286
|
+
}
|
|
287
|
+
|
|
188
288
|
export function currentGitBranch(root: string): string | undefined {
|
|
189
289
|
const result = spawnSync("git", ["branch", "--show-current"], {
|
|
190
290
|
cwd: root,
|
package/src/policies/tamper.ts
CHANGED
|
@@ -21,6 +21,7 @@ export const SETTINGS_TAMPER_PATTERNS: RegExp[] = [
|
|
|
21
21
|
new RegExp(`(?:^|\\s)(?:${V_LIST})\\s+[^|;&]*?[\\w\\/.~-]*(?:${U_LIST})`, "i"),
|
|
22
22
|
new RegExp(`${GT}\\s*["']?[\\w\\/.~-]*(?:${U_LIST})`, "i"),
|
|
23
23
|
new RegExp("(?:" + "^|\\s)(?:op" + "encode)\\s+(?:-[^|;&]*\\s+)*(?:auth|config|permission)\\b", "i"),
|
|
24
|
+
new RegExp("(?:" + "^|\\s)(?:op" + "encode)\\s+(?:-[^|;&]*\\s+)*(?:plugin|mcp)\\s+(?!(?:list|ls|get|show|status|--help|-h)\\b)", "i"),
|
|
24
25
|
new RegExp("(?:" + "^|\\s)(?:op" + "encode)\\s+(?:run\\s+)?--auto\\b", "i"),
|
|
25
26
|
];
|
|
26
27
|
|
package/src/workflow-guard.ts
CHANGED
|
@@ -385,6 +385,10 @@ import { checkSweepingClaims } from "./policies/sweeping-claims.ts";
|
|
|
385
385
|
|
|
386
386
|
export { checkSweepingClaims };
|
|
387
387
|
|
|
388
|
+
import { DELEGATION_REASON, delegationSpawnIn } from "./policies/delegation.ts";
|
|
389
|
+
|
|
390
|
+
export { DELEGATION_REASON, delegationSpawnIn };
|
|
391
|
+
|
|
388
392
|
import {
|
|
389
393
|
clearLiveDocsFloor,
|
|
390
394
|
isResearchTool,
|
package/test/test.mts
CHANGED
|
@@ -111,6 +111,7 @@ import {
|
|
|
111
111
|
isReadOnlyRole,
|
|
112
112
|
checkInteractiveTtyCommand,
|
|
113
113
|
checkPackageHygiene,
|
|
114
|
+
delegationSpawnIn,
|
|
114
115
|
sendDesktopNotification,
|
|
115
116
|
escapeAppleScriptString,
|
|
116
117
|
createGitWorktree,
|
|
@@ -703,6 +704,15 @@ check("block docker container prune", blocked(await shell("docker container prun
|
|
|
703
704
|
check("block docker system prune", blocked(await shell("docker system prune")));
|
|
704
705
|
check("block docker volume rm", blocked(await shell("docker volume rm data")));
|
|
705
706
|
check(["block gh repo ", "delete"].join(""), blocked(await shell(["gh repo ", "delete owner/repo --yes"].join(""))));
|
|
707
|
+
check(["block gh pr ", "merge"].join(""), blocked(await shell(["gh pr ", "merge 42 --squash"].join(""))));
|
|
708
|
+
check("block a wrapped gh pr merge", blocked(await shell(["env FOO=1 gh pr ", "merge 42"].join(""))));
|
|
709
|
+
check("block a chained gh pr merge", blocked(await shell(["cd /tmp && gh pr ", "merge 42"].join(""))));
|
|
710
|
+
check("block gh api DELETE method", blocked(await shell(["gh api -X ", "DELETE repos/o/r"].join(""))));
|
|
711
|
+
check("block gh api long-form DELETE method", blocked(await shell(["gh api --method=", "DELETE repos/o/r"].join(""))));
|
|
712
|
+
check("allow a read-only gh api request", !(await shell("gh api repos/o/r/pulls/42")));
|
|
713
|
+
const azRoleCreate = ["az role ", "assignment ", "create --role Owner --assignee x"].join("");
|
|
714
|
+
check("block az role assignment create", blocked(await shell(azRoleCreate)));
|
|
715
|
+
check("allow az role assignment list", !(await shell("az role assignment list -g rg")));
|
|
706
716
|
check(["block npx prisma ", "migrate reset"].join(""), blocked(await shell(["npx prisma ", "migrate reset --force"].join(""))));
|
|
707
717
|
check("block mkfs.ext4", blocked(await shell(["mk", "fs.ext4 /dev/sdb1"].join(""))));
|
|
708
718
|
check("block wipefs", blocked(await shell(["wipe", "fs -a /dev/sdb"].join(""))));
|
|
@@ -755,6 +765,12 @@ const ocCli = ["op", "encode"].join("");
|
|
|
755
765
|
check("block auth with global flags (--dir)", blocked(await shell(`${ocCli} --dir /path ${"au" + "th"} login`)));
|
|
756
766
|
check("block config with global flags (-d)", blocked(await shell(`${ocCli} -d . ${"con" + "fig"} edit`)));
|
|
757
767
|
check("block permission with global flags (--workspace)", blocked(await shell(`${ocCli} --workspace . ${"perm" + "ission"} grant`)));
|
|
768
|
+
check("block opencode plugin add", blocked(await shell(`${ocCli} plugin add opencode-workflow-guard@1.20.0`)));
|
|
769
|
+
check("block opencode plugin remove", blocked(await shell(`${ocCli} plugin remove opencode-workflow-guard`)));
|
|
770
|
+
check("block opencode plugin add with global flags", blocked(await shell(`${ocCli} --dir /tmp plugin add opencode-workflow-guard`)));
|
|
771
|
+
check("block opencode mcp add", blocked(await shell(`${ocCli} mcp add --url https://example.invalid/mcp`)));
|
|
772
|
+
check("allow opencode plugin list", !(await shell(`${ocCli} plugin list`)));
|
|
773
|
+
check("allow opencode mcp list", !(await shell(`${ocCli} mcp list`)));
|
|
758
774
|
check("allow normal command", !(await shell("ls -la && git status")));
|
|
759
775
|
const ocDir = ".open" + "code/plans/";
|
|
760
776
|
check("allow gh issue create mentioning .opencode paths (not tamper)", !(await shell(`gh issue create --repo example/proj --title t --body 'see <project>/${ocDir}'`)));
|
|
@@ -800,6 +816,79 @@ setWorkspaceRoot(repo); // point the guard at the repo
|
|
|
800
816
|
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"));
|
|
801
817
|
check("on main: git commit blocked", blocked(await shell("git commit -m test")));
|
|
802
818
|
check("on main: git merge blocked", blocked(await shell("git merge feature/x")));
|
|
819
|
+
// A fast-forward to the tracked upstream is the one history write that adds no
|
|
820
|
+
// unreviewed commit, so it must be allowed or a stale primary checkout can never
|
|
821
|
+
// sync (#145). The control cases keep the exemption narrow.
|
|
822
|
+
const ffBase = mkdtempSync(join(tmpdir(), "wg-ff-"));
|
|
823
|
+
const ffRemote = join(ffBase, "remote.git");
|
|
824
|
+
const ffRepo = join(ffBase, "repo");
|
|
825
|
+
const ffPeer = join(ffBase, "peer");
|
|
826
|
+
const ffGit = (...args: string[]) => spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.invalid", ...args], { encoding: "utf8" });
|
|
827
|
+
mkdirSync(ffRemote, { recursive: true });
|
|
828
|
+
spawnSync("git", ["init", "--bare", "-b", "main", ffRemote]);
|
|
829
|
+
spawnSync("git", ["init", "-b", "main", ffRepo]);
|
|
830
|
+
writeFileSync(join(ffRepo, "a.txt"), "a\n");
|
|
831
|
+
ffGit("-C", ffRepo, "add", "a.txt");
|
|
832
|
+
ffGit("-C", ffRepo, "commit", "-m", "init");
|
|
833
|
+
ffGit("-C", ffRepo, "remote", "add", "origin", ffRemote);
|
|
834
|
+
ffGit("-C", ffRepo, "push", "-u", "origin", "main");
|
|
835
|
+
spawnSync("git", ["clone", ffRemote, ffPeer]);
|
|
836
|
+
writeFileSync(join(ffPeer, "b.txt"), "b\n");
|
|
837
|
+
ffGit("-C", ffPeer, "add", "b.txt");
|
|
838
|
+
ffGit("-C", ffPeer, "commit", "-m", "advance");
|
|
839
|
+
ffGit("-C", ffPeer, "push", "origin", "main");
|
|
840
|
+
ffGit("-C", ffPeer, "branch", "side");
|
|
841
|
+
ffGit("-C", ffPeer, "push", "origin", "side");
|
|
842
|
+
ffGit("-C", ffRepo, "fetch", "origin");
|
|
843
|
+
ffGit("-C", ffRepo, "remote", "set-head", "origin", "main");
|
|
844
|
+
ffGit("-C", ffRepo, "branch", "feat/local");
|
|
845
|
+
setWorkspaceRoot(ffRepo);
|
|
846
|
+
check("on main: merge --ff-only of the tracked upstream allowed", !blocked(await shell("git merge --ff-only origin/main")));
|
|
847
|
+
check("on main: merge without --ff-only still blocked", blocked(await shell("git merge origin/main")));
|
|
848
|
+
check("on main: merge --ff-only of a local branch still blocked", blocked(await shell("git merge --ff-only feat/local")));
|
|
849
|
+
check("on main: merge --ff-only of a non-default remote branch still blocked", blocked(await shell("git merge --ff-only origin/side")));
|
|
850
|
+
check("on main: merge --ff-only with two operands blocked", blocked(await shell("git merge --ff-only origin/main origin/side")));
|
|
851
|
+
check("on main: rebase onto the tracked upstream allowed", !blocked(await shell("git rebase origin/main")));
|
|
852
|
+
check("on main: pull without --ff-only still blocked", blocked(await shell("git pull")));
|
|
853
|
+
check("on main: pull --ff-only allowed", !blocked(await shell("git pull --ff-only")));
|
|
854
|
+
check("on main: pull --ff-only under a rebase config allowed", !blocked(await shell("git -c pull.rebase=false pull --ff-only")));
|
|
855
|
+
check("on main: pull of a named remote branch still blocked", blocked(await shell("git pull --ff-only origin main")));
|
|
856
|
+
check("on main: pull --ff-only with a trailing -- blocked", blocked(await shell("git pull --ff-only --")));
|
|
857
|
+
check("on main: pull --ff-only of a rebasing config still allowed", !blocked(await shell("git -c pull.rebase=true pull --ff-only")));
|
|
858
|
+
// One shell word is what the guard reads, so quote concatenation and a quoted
|
|
859
|
+
// subcommand name must reach the same verdict as the plain form.
|
|
860
|
+
check("on main: quote-concatenated pull subcommand still allowed", !blocked(await shell("git pu''ll --ff-only")));
|
|
861
|
+
check("on main: quoted pull subcommand still allowed", !blocked(await shell('git "pull" --ff-only')));
|
|
862
|
+
check("on main: chained pull --ff-only still allowed", !blocked(await shell("git status >/dev/null && git pull --ff-only")));
|
|
863
|
+
check("on main: pull --ff-only in a chained cd is judged in that tree", !blocked(await shell(`cd ${ffRepo} && git pull --ff-only`)));
|
|
864
|
+
check("on main: -C the same checkout still fast-forwards", !blocked(await shell(`git -C ${ffRepo} merge --ff-only origin/main`)));
|
|
865
|
+
check("on main: -C the same checkout allows a pull", !blocked(await shell(`git -C ${ffRepo} pull --ff-only`)));
|
|
866
|
+
ffGit("-C", ffRepo, "commit", "--allow-empty", "-m", "local work");
|
|
867
|
+
check("on main: merge --ff-only blocked once the branch has diverged", blocked(await shell("git merge --ff-only origin/main")));
|
|
868
|
+
check("on main: rebase blocked once the branch has diverged", blocked(await shell("git rebase origin/main")));
|
|
869
|
+
check("on main: pull --ff-only blocked once the branch has diverged", blocked(await shell("git pull --ff-only")));
|
|
870
|
+
rmSync(ffBase, { recursive: true, force: true });
|
|
871
|
+
// A `pull` names no ref, so the guard derives the target from `@{u}`. That
|
|
872
|
+
// derivation must still prove the ref is remote-tracking; a local upstream is
|
|
873
|
+
// not a remote sync and stays blocked.
|
|
874
|
+
const ffLocalBase = mkdtempSync(join(tmpdir(), "wg-ff-local-"));
|
|
875
|
+
const ffLocalRepo = join(ffLocalBase, "repo");
|
|
876
|
+
spawnSync("git", ["init", "-b", "main", ffLocalRepo]);
|
|
877
|
+
writeFileSync(join(ffLocalRepo, "a.txt"), "a\n");
|
|
878
|
+
ffGit("-C", ffLocalRepo, "add", "a.txt");
|
|
879
|
+
ffGit("-C", ffLocalRepo, "commit", "-m", "c1");
|
|
880
|
+
ffGit("-C", ffLocalRepo, "branch", "feat/local-up");
|
|
881
|
+
ffGit("-C", ffLocalRepo, "switch", "feat/local-up");
|
|
882
|
+
writeFileSync(join(ffLocalRepo, "b.txt"), "b\n");
|
|
883
|
+
ffGit("-C", ffLocalRepo, "add", "b.txt");
|
|
884
|
+
ffGit("-C", ffLocalRepo, "commit", "-m", "c2");
|
|
885
|
+
ffGit("-C", ffLocalRepo, "switch", "main");
|
|
886
|
+
ffGit("-C", ffLocalRepo, "branch", "--set-upstream-to=feat/local-up", "main");
|
|
887
|
+
setWorkspaceRoot(ffLocalRepo);
|
|
888
|
+
check("on main: pull --ff-only from a local upstream branch stays blocked", blocked(await shell("git pull --ff-only")));
|
|
889
|
+
check("on main: merge --ff-only from the local upstream stays blocked", blocked(await shell("git merge --ff-only")));
|
|
890
|
+
rmSync(ffLocalBase, { recursive: true, force: true });
|
|
891
|
+
setWorkspaceRoot(repo);
|
|
803
892
|
check("on main: git checkout path mutation blocked", blocked(await shell("git checkout -- tracked.txt")));
|
|
804
893
|
check("on main: git checkout path mutation without separator blocked", blocked(await shell("git checkout tracked.txt")));
|
|
805
894
|
check("on main: git checkout -B reset blocked", blocked(await shell("git checkout -B main HEAD~1")));
|
|
@@ -5841,6 +5930,53 @@ check("shell tool blocks global npm install", blocked(await shell("npm i -g tsx"
|
|
|
5841
5930
|
check("shell tool blocks direct npm publish", blocked(await shell("npm publish --access public")));
|
|
5842
5931
|
check("shell tool allows regular npm install", !(await shell("npm install lodash")));
|
|
5843
5932
|
|
|
5933
|
+
// 18. Policy 28: Agent Delegation Boundary
|
|
5934
|
+
console.log("- Policy 28: Agent Delegation Boundary -");
|
|
5935
|
+
check("delegationSpawnIn detects claude", delegationSpawnIn('claude -p "summarise"') === "claude");
|
|
5936
|
+
check("delegationSpawnIn detects codex", delegationSpawnIn("codex exec 'run tests'") === "codex");
|
|
5937
|
+
check("delegationSpawnIn detects gemini", delegationSpawnIn("gemini -p 'x'") === "gemini");
|
|
5938
|
+
check("delegationSpawnIn detects aider", delegationSpawnIn("aider --message 'x'") === "aider");
|
|
5939
|
+
check("delegationSpawnIn detects opencode run", delegationSpawnIn("opencode run 'x'") === "opencode run");
|
|
5940
|
+
check("delegationSpawnIn detects opencode run behind a global flag", delegationSpawnIn("opencode --dir /tmp run 'x'") === "opencode run");
|
|
5941
|
+
check("delegationSpawnIn detects opencode run behind a value flag", delegationSpawnIn("opencode --log-level debug run 'x'") === "opencode run");
|
|
5942
|
+
check("delegationSpawnIn permits an opencode help request naming run", delegationSpawnIn("opencode --help run") === undefined);
|
|
5943
|
+
check("delegationSpawnIn permits another opencode subcommand", delegationSpawnIn("opencode export ses_abc") === undefined);
|
|
5944
|
+
check("delegationSpawnIn does not read a plugin argument as the subcommand", delegationSpawnIn("opencode --model x plugin add run") === undefined);
|
|
5945
|
+
check("delegationSpawnIn detects a path-qualified executable", delegationSpawnIn("/usr/local/bin/claude -p x") === "claude");
|
|
5946
|
+
check("delegationSpawnIn unwraps env assignments", delegationSpawnIn("env FOO=1 claude -p x") === "claude");
|
|
5947
|
+
check("delegationSpawnIn unwraps sudo options", delegationSpawnIn("sudo -u deploy claude -p x") === "claude");
|
|
5948
|
+
check("delegationSpawnIn unwraps timeout", delegationSpawnIn("timeout 30 codex exec x") === "codex");
|
|
5949
|
+
check("delegationSpawnIn unwraps command builtin", delegationSpawnIn("command claude -p x") === "claude");
|
|
5950
|
+
check("delegationSpawnIn detects a chained segment", delegationSpawnIn("echo hi | claude -p x") === "claude");
|
|
5951
|
+
check("delegationSpawnIn detects a cd-prefixed segment", delegationSpawnIn("cd /tmp && claude -p x") === "claude");
|
|
5952
|
+
check("delegationSpawnIn detects a grouping subshell", delegationSpawnIn("ls && (claude -p x)") === "claude");
|
|
5953
|
+
check("delegationSpawnIn detects npx package execution", delegationSpawnIn("npx -y claude-code -p x") === "claude");
|
|
5954
|
+
check("delegationSpawnIn detects scoped npx package", delegationSpawnIn("npx @openai/codex exec x") === "codex");
|
|
5955
|
+
check("delegationSpawnIn detects bunx package execution", delegationSpawnIn("bunx gemini-cli -p x") === "gemini");
|
|
5956
|
+
check("delegationSpawnIn detects a versioned npx package", delegationSpawnIn("npx claude-code@latest -p x") === "claude");
|
|
5957
|
+
check("delegationSpawnIn permits an argument-only mention", delegationSpawnIn("grep claude README.md") === undefined);
|
|
5958
|
+
check("delegationSpawnIn permits a quoted argument mention", delegationSpawnIn('echo "run claude for details"') === undefined);
|
|
5959
|
+
check("delegationSpawnIn permits a git log grep value", delegationSpawnIn("git log --grep=codex") === undefined);
|
|
5960
|
+
check("delegationSpawnIn permits an npx plugin flag value", delegationSpawnIn("npx prettier --plugin claude --write src") === undefined);
|
|
5961
|
+
check("delegationSpawnIn permits a read-only opencode verb", delegationSpawnIn("opencode plugin list") === undefined);
|
|
5962
|
+
|
|
5963
|
+
check("shell tool blocks direct claude spawn", blocked(await shell('claude -p "summarise"')),);
|
|
5964
|
+
check("delegation block reason names the escape", ((await shell("claude -p x")) ?? "").includes("outside this session's workflow guard"));
|
|
5965
|
+
check("shell tool blocks opencode run", blocked(await shell("opencode run 'do the work'")));
|
|
5966
|
+
check("shell tool blocks a wrapped codex spawn", blocked(await shell("env FOO=1 timeout 30 codex exec x")));
|
|
5967
|
+
check("shell tool blocks a chained aider spawn", blocked(await shell("git status && aider --message x")));
|
|
5968
|
+
check("shell tool blocks an npx claude-code spawn", blocked(await shell("npx -y claude-code -p x")));
|
|
5969
|
+
check("shell tool blocks a bash -c claude payload", blocked(await shell("bash -c 'claude -p x'")));
|
|
5970
|
+
check("shell tool blocks a sh -lc codex payload", blocked(await shell("sh -lc 'codex exec x'")));
|
|
5971
|
+
check("shell tool blocks an eval claude payload", blocked(await shell("eval 'claude -p x'")));
|
|
5972
|
+
check("shell tool blocks a heredoc body that runs claude", blocked(await shell("bash <<'EOF'\nclaude -p x\nEOF")));
|
|
5973
|
+
check("shell tool blocks delegation for a read-only subagent", blocked(await call("bash", { command: "claude -p x" }, { sessionID: "s-child", agent: "reviewer" })));
|
|
5974
|
+
check("shell tool blocks delegation for a worker subagent", blocked(await call("bash", { command: "gemini -p x" }, { sessionID: "s-child", agent: "executor" })));
|
|
5975
|
+
check("shell tool allows an argument-only claude mention", !(await shell("grep claude README.md")));
|
|
5976
|
+
check("shell tool allows prose quoting a launcher", !(await shell('echo "run claude for details"')));
|
|
5977
|
+
check("shell tool allows a prose heredoc mentioning claude", !(await shell("cat > notes.md <<'EOF'\nclaude is an agent CLI\nEOF")));
|
|
5978
|
+
check("shell tool allows a read-only subagent to grep a launcher name", !(await call("bash", { command: "grep claude README.md" }, { sessionID: "s-child", agent: "reviewer" })));
|
|
5979
|
+
|
|
5844
5980
|
// Durable Recovery Checkpoints
|
|
5845
5981
|
console.log("- Durable Recovery Checkpoints -");
|
|
5846
5982
|
const checkpointDir = mkdtempSync(join(tmpdir(), "wg-checkpoint-"));
|
|
@@ -7393,6 +7529,28 @@ try {
|
|
|
7393
7529
|
"seat no longer denies a cwd-dependent push from a protected session checkout",
|
|
7394
7530
|
protectedCheckoutSeat.effect === "abstain" && protectedCheckoutSeat.decision?.code === "repository_unidentified",
|
|
7395
7531
|
);
|
|
7532
|
+
// `pull` is a history write only on a protected branch, and the seat cannot
|
|
7533
|
+
// see which checkout the command runs in, so it defers rather than blocking
|
|
7534
|
+
// a sync that a linked feature worktree would allow.
|
|
7535
|
+
const pullSeat = await evaluatePermissionSeat(
|
|
7536
|
+
{ ...seatEvent(["git pull --ff-only"]), sessionID: "s-seat-pull" },
|
|
7537
|
+
{ workspaceRoot: seatMainRepo, client: fakeClient as unknown },
|
|
7538
|
+
);
|
|
7539
|
+
check(
|
|
7540
|
+
"seat defers a cwd-dependent pull instead of judging the session checkout",
|
|
7541
|
+
pullSeat.effect === "abstain" && pullSeat.decision?.code === "repository_unidentified",
|
|
7542
|
+
);
|
|
7543
|
+
// An explicit `-C` puts the repository back in the command text, so the seat
|
|
7544
|
+
// judges it for real: a protected checkout with no upstream is a block, not
|
|
7545
|
+
// a deferral.
|
|
7546
|
+
const explicitPullSeat = await evaluatePermissionSeat(
|
|
7547
|
+
{ ...seatEvent([`git -C ${seatMainRepo} pull --ff-only`]), sessionID: "s-seat-explicit-pull" },
|
|
7548
|
+
{ workspaceRoot: seatMainRepo, client: fakeClient as unknown },
|
|
7549
|
+
);
|
|
7550
|
+
check(
|
|
7551
|
+
"seat still denies an explicitly named protected pull",
|
|
7552
|
+
explicitPullSeat.effect === "deny" && explicitPullSeat.decision?.policy === "git",
|
|
7553
|
+
);
|
|
7396
7554
|
// A push whose DESTINATION is protected is a finding in every checkout, so
|
|
7397
7555
|
// the workdir cannot change the verdict and the seat keeps its denial.
|
|
7398
7556
|
const protectedDestSeat = await evaluatePermissionSeat(
|