opencode-workflow-guard 1.19.5 → 1.20.0
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 +14 -5
- package/docs/testing.md +6 -3
- package/package.json +4 -4
- package/src/lib/custom-tools.ts +50 -8
- package/src/lib/guard-dispatcher.ts +11 -0
- package/src/lib/review.ts +29 -3
- package/src/policies/boundary.ts +29 -1
- package/src/policies/delegation.ts +115 -0
- package/src/policies/destructive.ts +3 -1
- package/src/policies/tamper.ts +1 -0
- package/src/workflow-guard.ts +4 -0
- package/test/test.mts +246 -2
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
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.
|
|
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
|
|
|
@@ -59,7 +59,7 @@ For complete policy specifications and override rules, see [docs/policies.md](do
|
|
|
59
59
|
Enforcement is only half the surface. The plugin also registers first-class agent tools under the same names on OpenCode 1.x and 2.x, so disciplined workflow is the path of least resistance:
|
|
60
60
|
|
|
61
61
|
* **Task Planning:** `guard_next_tasks` surfaces durable repository planning context at session start or during planning. It reads `TODO.md`, `ROADMAP.md`, `PLAN.md`, `TASKS.md`, `BACKLOG.md`, their `docs/` counterparts, and plans under `docs/plans/`. `guard_status` reports active guardrails, branch protection, mutation counts, outstanding verification and review gates, a read-only git-hygiene snapshot, and the loaded `pluginVersion`.
|
|
62
|
-
* **Review & Verification:** before PR creation, a secondary reviewer subagent evaluates the diff against `guard_review_rubric`. The rubric covers five axes: test integrity, task completeness, cleanliness, security, and platform. The
|
|
62
|
+
* **Review & Verification:** before PR creation, a secondary reviewer subagent evaluates the diff against `guard_review_rubric`. The rubric covers five axes: test integrity, task completeness, cleanliness, security, and platform, and its first line names the workspace, base ref, and diff size it graded. When no listed base yields a diff the tool refuses and names what it tried instead of grading a substitute range. The calling session records the subagent's verdict with `record_review`, and approvals bind to the reviewed worktree content. An opt-in dogfood gate adds a recorded end-to-end run on real hardware with `record_dogfood`.
|
|
63
63
|
* **Worktree Isolation:** `guard_worktree_create` and `guard_worktree_cleanup` give parallel subagents isolated linked worktrees, so concurrent mutations never collide.
|
|
64
64
|
* **Technical Debt:** `guard_review_followups` lists open P2/P3 durable review follow-ups. `guard_review_followup_resolve` closes one after the underlying issue is fixed and verified.
|
|
65
65
|
* **Policy Simulation:** `guard_why` returns the structured policy decision for a tool call or command without performing it. `guard_audit` shows recent audited policy entries.
|
|
@@ -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
|
@@ -26,7 +26,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
26
26
|
- **Handoff Safety:** An idle subagent whose effective todos are inherited from its parent is not auto-continued. Inherited work belongs to the parent and can be handed back normally.
|
|
27
27
|
- **Durable Planning Context Discovery:** `guard_next_tasks` prefers a repository-root `TODO.md`. When it is absent, it reads conventional `ROADMAP.md`, `PLAN.md`, `TASKS.md`, `BACKLOG.md`, their `docs/` counterparts, and Markdown files under `docs/plans/`. The tool exposes candidate planning context without selecting, prioritizing, or sequencing tasks. These files never replace OpenCode's native runtime todo state.
|
|
28
28
|
- **Subagent Mutation Budget:** Subagent sessions are protected by a mutation safety budget (`maxSubagentMutations` in project config or `WORKFLOW_GUARD_MAX_SUBAGENT_MUTATIONS` env, default 100). The budget terminates runaway edit loops deterministically.
|
|
29
|
-
- **Concurrent File Claims:** Direct `edit`, `write`, and `apply_patch` calls claim each canonical target for the tool-call lifetime. A different active session is blocked from racing the same file, including through symlink aliases. Claims are released after the call, with session idle/deletion as stale-claim cleanup when an after hook is missed. Two provable staleness rules reclaim a leaked claim, each audited, and both stay scoped to the contended paths so a long-running command elsewhere keeps its claim. The idle rule releases a claim created before its owner's last recorded idle timestamp, because that call finished before the turn ended. It writes a `stale_claim_takeover` entry. The TTL rule releases a claim older than the effective claim TTL, which covers a deleted session and a server restart where the owner record cannot be read at all. It writes a `claim_ttl_expired` entry with the owner and claim age. The TTL defaults to five minutes, is raised or lowered with `claimTtlMs` in `.opencode/workflow-guard.json`, and `WORKFLOW_GUARD_CLAIM_TTL_MS` wins over project config. A non-positive or unparseable value falls back to the default. Owners still mid-session within the TTL, clients without a session lookup, and failed lookups keep the block (fail-closed). The block names the owner, the claim age, and the reclaim step. `guard_why` stays read-only and still reports the conflict as blocked. Shell writers
|
|
29
|
+
- **Concurrent File Claims:** Direct `edit`, `write`, and `apply_patch` calls claim each canonical target for the tool-call lifetime. A different active session is blocked from racing the same file, including through symlink aliases. Claims are released after the call, with session idle/deletion as stale-claim cleanup when an after hook is missed. Two provable staleness rules reclaim a leaked claim, each audited, and both stay scoped to the contended paths so a long-running command elsewhere keeps its claim. The idle rule releases a claim created before its owner's last recorded idle timestamp, because that call finished before the turn ended. It writes a `stale_claim_takeover` entry. The TTL rule releases a claim older than the effective claim TTL, which covers a deleted session and a server restart where the owner record cannot be read at all. It writes a `claim_ttl_expired` entry with the owner and claim age. The TTL defaults to five minutes, is raised or lowered with `claimTtlMs` in `.opencode/workflow-guard.json`, and `WORKFLOW_GUARD_CLAIM_TTL_MS` wins over project config. A non-positive or unparseable value falls back to the default. Owners still mid-session within the TTL, clients without a session lookup, and failed lookups keep the block (fail-closed). The block names the owner, the claim age, and the reclaim step. `guard_why` stays read-only and still reports the conflict as blocked. A recognized shell writer is refused with the same reason when its target is claimed: redirection, `tee`, `sed -i`, `cp`/`mv`/`ln`, `rm`, `truncate`, `dd of=`, `git apply`, and `git am`. A `mv` source is checked too, because the move removes it. The check resolves a relative target against the tree the segment actually runs in, so a chained `cd` and a symlink alias are judged where the write lands. A shell write never acquires a claim, so it cannot strand one the edit path must later reclaim, and the provably stale rules release before the conflict is reported. Shell writers remain outside the write-observation and stale-write pre-check, and isolated worktrees remain the better choice for substantial parallel mutations.
|
|
30
30
|
- **Stale-Write Protection:** A successful `read` records a same-session fingerprint for an existing regular file from five fields. Those fields are canonical path, filesystem identity, size, nanosecond mtime, and SHA-256 content digest. A successful `edit`/`write` also records the resulting bytes, and only when the file actually changed. The session authored those bytes, so iterating on a just-created or just-modified file needs no redundant re-read. Before `edit` or `write` replaces an existing file, that fingerprint must exist and still match. Otherwise the call is blocked and must re-read. New-file creation is allowed without a prior read. Fingerprints are not inherited between parent and subagent sessions, and they are cleared on session idle or deletion. `apply_patch` and shell writers sit deliberately outside this bounded mechanism. An `apply_patch` result still seeds the session observation, but its clobbering itself is not pre-checked. The pre-execution comparison also cannot make external changes between the check and OpenCode's write atomic.
|
|
31
31
|
- **Shell-redirect seeding:** An allowed shell command that redirects into a workspace file (`cmd > file`, `cmd >> file`, fd forms) seeds the session's observation of the resulting bytes. It does so in the same change-gated way as direct edits. A file this session just created or rewrote via a shell redirect can therefore be edited without a redundant re-read. Redirects to `/dev/null`, the `/tmp/opencode` scratch directory, or outside the workspace seed nothing. An identical-byte (no-op) redirect does not seed. The not-read block message also suggests coordinating when another session may own the file. Shell writers themselves remain outside the bounded pre-check, so only the observation seeding applies.
|
|
32
32
|
|
|
@@ -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.
|
|
@@ -117,7 +117,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
117
117
|
- **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
118
|
- **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
119
|
- **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.
|
|
120
|
+
- **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
121
|
- If verification fails, finalization is blocked with a structured summary of error markers, stack traces, and failure output.
|
|
122
122
|
- 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
123
|
- The verify command is **disabled** when `WORKFLOW_GUARD_VERIFY` is empty (`""`).
|
|
@@ -227,6 +227,13 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
227
227
|
- 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
228
|
- `guard_status` reports `lastDogfood` and adds `dogfood` to `outstandingRequirements` when the gate is unsatisfied, naming the matrix hosts still missing a passing run.
|
|
229
229
|
|
|
230
|
+
### 28. Agent Delegation Boundary (`shell`)
|
|
231
|
+
- 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.
|
|
232
|
+
- 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.
|
|
233
|
+
- 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.
|
|
234
|
+
- 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.
|
|
235
|
+
- 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.
|
|
236
|
+
|
|
230
237
|
### Tool Description Honesty & Cross-Model Adherence
|
|
231
238
|
- 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
239
|
- `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.
|
|
@@ -264,6 +271,8 @@ Besides enforcement hooks, the guard registers companion tools in OpenCode:
|
|
|
264
271
|
- `guard_status`, `guard_audit`, `guard_why`, `guard_review_rubric`, `record_review`, `guard_review_followups`, and `guard_review_followup_resolve` provide runtime introspection. They cover guardrail state, audit entries, block explanations, reviewer rubric definitions, reviewer decisions, and durable local review debt. `guard_status` also exposes the effective Ralph opt-in, its iteration budget, and the calling-session outcome when applicable. It reports a read-only `gitHygiene` snapshot (local branches already merged into the mainline, prunable worktree admin entries, and the current branch's base-behind distance). Hygiene itself stays manual: the guard reports, it never prunes or deletes branches. `guard_status` also reports `pluginVersion`, the version of the loaded guard package, so a stale installation is visible.
|
|
265
272
|
- On OpenCode 2 the same report is also reachable as the server-side `/guard-status` command (`ctx.command.transform`). It delivers the JSON as a synthetic message with no model turn. That path needs no separately installed TUI companion.
|
|
266
273
|
- **Priority-Ranked Review Gate:** Secondary review approval (`requireReview`) is enforced by default during PR preflight (`gh pr create` / `az repos pr create`). Before creating a pull request, a secondary reviewer subagent must evaluate the changes using `guard_review_rubric` and record approval with `record_review`. Approvals that include active P0 (blocker) or P1 (major defect) issues are rejected until blockers are resolved. Projects can opt out via `.opencode/workflow-guard.json` (`{ "requireReview": false }`) or environment variable `WORKFLOW_GUARD_REQUIRE_REVIEW=0`. Conversely, `WORKFLOW_GUARD_REQUIRE_REVIEW=1` forces the review requirement regardless of project config.
|
|
274
|
+
- **The rubric names what it graded:** `guard_review_rubric` prefixes the prompt with `Provenance: workspace=<abs root> base=<ref> diff=<n> bytes fallback=<none|HEAD~1>`. A session's own checkout and the checkout holding the change are not always the same tree, so the caller checks those three facts before trusting the prompt. Pass `directory` to grade another worktree and `base` to name another base. When no listed base yields a diff, the tool refuses with the workspace, every base it tried, and the remedy. It does not run `git diff HEAD~1` behind the caller's back, because that graded a substitute range and named nothing. `HEAD~1` is graded only when the caller passes `base: "HEAD~1"`, and the provenance line then says `base=HEAD~1 fallback=HEAD~1`.
|
|
275
|
+
- **The calling session records the verdict:** A reviewer agent is often configured with a toolset that omits `record_review`, so the injected guidance and both tool descriptions say the calling session records the subagent's verdict. `record_review` binds that verdict to the recorder's resolved directory or an explicit `directory`.
|
|
267
276
|
- **Review binding is content, not session identity:** A recorded approval satisfies the PR preflight when its binding matches the tree the PR would publish. The binding covers the repository, the commit hash, and the tracked-content worktree fingerprint. Any session may record the verdict or create the PR. Reviewers record from subagent sessions, binding the verdict to their parent or their own directory. Sessions can move between directories (`session_move`), and subagents can spawn from other roots. Keying the gate on the PR-creating session's ID would make the documented flow impossible to satisfy from linked worktrees. Freshness is scoped to the reviewed diff, which is tracked content. Untracked scratch-file cleanup and mutations in sibling worktrees cannot invalidate an approval. Any tracked edit or new commit does.
|
|
268
277
|
- **Commit before you verify and review:** Both evidence gates bind to the HEAD commit hash, so a commit after either one invalidates it. Finish every tracked change first, then run verification, then record the review, then open the PR. That order satisfies both gates in one pass. Any other order costs a re-run. A review recorded before its change is committed keeps the same tracked fingerprint. The preflight then names the commit drift specifically and asks for the review again at the current commit.
|
|
269
278
|
- **`record_review` accepts any recorder session:** Reviewer agents are often configured with a read-only toolset, for example glob, grep, read, and webfetch only. Such a reviewer cannot call `record_review` itself. The tool therefore accepts recorders of any session type and binds the verdict to the recording session's resolved directory. The tool result echoes that binding. The audit entry (`record_review.verdict`) records the binding key and recorder lineage (`recorderRole: root | subagent`), and `guard_status.lastReview` reports the same lineage beside the parent it was recorded for. Prefer relaying through an independent secondary reviewer subagent. The tool result reminds the recorder when it runs from a root session. A verdict recorded against a directory without a computable tracked fingerprint (not a git repository) is rejected loudly and never recorded.
|
package/docs/testing.md
CHANGED
|
@@ -45,12 +45,14 @@ 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
|
+
| **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
|
+
| **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. |
|
|
54
56
|
| **record_review Registration** | Verifies `record_review` stays registered when the review gate is disabled, so a reviewer agent's host permission list, not project config, is what can withhold the call. Under `requireSubagentReview`, verifies a root approval is rejected and `guard_status.lastReview` names the subagent recorder and its parent separately. |
|
|
55
57
|
| **Adversarial Invariants** | Verifies defense against compound shell mutations, symlink escapes, chained git normalization, verify script abuse, and external repo mutations. |
|
|
56
58
|
| **Audit & Permission Events** | Verifies the typed `permission.ask` hook, permission replies, and command journaling in the audit trail. |
|
|
@@ -64,4 +66,5 @@ npm run test:all
|
|
|
64
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. |
|
|
65
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. |
|
|
66
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. |
|
|
67
70
|
| **Modular Exports & Shape** | Verifies V1 `PluginModule` `{ id, server }` structure, modular policy imports, and `output.args` hook contract. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-workflow-guard",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.20.0",
|
|
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
|
@@ -44,7 +44,7 @@ import { todoEvidenceReport } from "../policies/todo.ts";
|
|
|
44
44
|
import { existingProjectConfigPath, findGitRoot, loadProjectConfig, projectRootKey } from "./project-config.ts";
|
|
45
45
|
import { detectVerifyCommand, getCurrentGitCommitHash, getGitWorktreeFingerprint, getTrackedWorktreeFingerprint, verifyCommandSource } from "./verify.ts";
|
|
46
46
|
import { evaluateDogfoodGate } from "./dogfood.ts";
|
|
47
|
-
import { buildReviewRubric } from "./review.ts";
|
|
47
|
+
import { buildReviewRubric, type RubricProvenance } from "./review.ts";
|
|
48
48
|
import { createGitWorktree, cleanupGitWorktree, validateHostWorktreeDirectory } from "./worktree.ts";
|
|
49
49
|
import type { HostWorktreePort } from "./host-worktree.ts";
|
|
50
50
|
import { branchHasDocumentationChange } from "../policies/docs.ts";
|
|
@@ -94,7 +94,7 @@ export function buildWorkflowGuardSystemGuidance(options: {
|
|
|
94
94
|
|
|
95
95
|
if (!options.isReadOnly) {
|
|
96
96
|
sections.push(
|
|
97
|
-
"- Review & Verification: Before completing tasks or creating PRs, run tests to produce fresh verification evidence, retrieve the review rubric via `guard_review_rubric` (5 core axes: test integrity, task completeness, cleanliness, security, platform), and spawn a reviewer subagent via `task
|
|
97
|
+
"- Review & Verification: Before completing tasks or creating PRs, run tests to produce fresh verification evidence, retrieve the review rubric via `guard_review_rubric` (5 core axes: test integrity, task completeness, cleanliness, security, platform), and spawn a reviewer subagent via `task`. The calling session records that subagent's verdict with `record_review`: a reviewer agent's own toolset may not carry the tool, so the caller owns the record.",
|
|
98
98
|
"- Worktree Isolation: When orchestrating parallel subagent tasks with `task`, call `guard_worktree_create` to prevent concurrent file conflicts, and `guard_worktree_cleanup` when finished.",
|
|
99
99
|
);
|
|
100
100
|
}
|
|
@@ -346,13 +346,42 @@ 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) }),
|
|
353
382
|
guard_why: tool({ description: "Simulate and return the structured policy decision for a specific tool call or command. Proactively use before executing questionable or complex commands to check if they would be blocked by guard policies.", args: { tool: tool.schema.string().describe("Tool name (e.g. bash, edit, write, read, apply_patch)"), input: tool.schema.record(tool.schema.string(), tool.schema.any()).optional().describe("Tool input arguments") }, execute: async (args, toolContext) => JSON.stringify(await runWithRuntimeState(await resolveCallWorkspace(toolContext), client, () => guardToolCallImpl(args.tool, args.input ?? {}, { sessionID: toolContext.sessionID, worktree: toolContext.worktree, directory: toolContext.directory, simulate: true })), null, 2) }),
|
|
354
383
|
record_review: tool({
|
|
355
|
-
description: "Record a secondary reviewer agent's approval or critique of the current changes. The summary must reference the 5 core review axes from guard_review_rubric (test integrity, task completeness, cleanliness, security, platform). Projects with requireSubagentReview enabled only accept APPROVALS recorded from a subagent session (one with a parent session), never from the root session itself.",
|
|
384
|
+
description: "Record a secondary reviewer agent's approval or critique of the current changes. Call it from the session that owns the verdict: a reviewer subagent may not carry this tool at all, because host permissions decide an agent's toolset. The summary must reference the 5 core review axes from guard_review_rubric (test integrity, task completeness, cleanliness, security, platform). Projects with requireSubagentReview enabled only accept APPROVALS recorded from a subagent session (one with a parent session), never from the root session itself.",
|
|
356
385
|
args: {
|
|
357
386
|
reviewer: tool.schema.string().describe("Identifier/name of the reviewer subagent"),
|
|
358
387
|
summary: tool.schema.string().describe("Review findings summary across the 5 core review axes"),
|
|
@@ -547,7 +576,7 @@ export function createCustomTools(options: {
|
|
|
547
576
|
guard_review_followups: tool({ description: "List durable local P2/P3 review follow-ups (technical debt) for this project. Proactively check during planning or before final verification to address open findings.", args: {}, execute: async () => JSON.stringify(followupStore ? listReviewFollowups(followupStore) : [], null, 2) }),
|
|
548
577
|
guard_review_followup_resolve: tool({ description: "Resolve a durable local review follow-up after the underlying issue has been fixed and verified.", args: { id: tool.schema.string() }, execute: async (args) => followupStore && resolveReviewFollowup(followupStore, args.id) ? `[workflow-guard] Review follow-up ${args.id} resolved.` : `[workflow-guard] Review follow-up ${args.id} was not open or was not found.` }),
|
|
549
578
|
guard_review_rubric: tool({
|
|
550
|
-
description: "Get the secondary-review rubric for
|
|
579
|
+
description: "Get the secondary-review rubric for a branch diff across 5 core review axes (test integrity, task completeness, cleanliness, security, platform). The orchestrator should call this before finalizing work or creating a PR, then spawn a reviewer subagent with the rubric as the prompt. The calling session records that subagent's verdict with record_review. The rubric's first line names the workspace, base ref, and diff size it graded, so check those describe the change under review; pass directory and/or base when the change lives in another checkout.",
|
|
551
580
|
args: {
|
|
552
581
|
base: tool.schema.string().optional().describe("Base ref to diff against (default: origin/main, origin/master, main, master)"),
|
|
553
582
|
directory: tool.schema.string().optional().describe("Target repository directory (defaults to active session directory or workspace root)"),
|
|
@@ -559,11 +588,24 @@ export function createCustomTools(options: {
|
|
|
559
588
|
const bases = sanitizedBase ? [sanitizedBase] : ["origin/main", "origin/master", "main", "master"];
|
|
560
589
|
const rubricWorkspace = await resolveCallWorkspace(toolContext, args?.directory);
|
|
561
590
|
let diffText = "";
|
|
591
|
+
let usedBase: string | undefined;
|
|
562
592
|
// Revision before the trailing `--` (LL-001) so the base ref is
|
|
563
593
|
// always parsed as a revision, never as a pathspec.
|
|
564
|
-
for (const base of bases) { const res = spawnSync("git", ["diff", "--no-ext-diff", `${base}...HEAD`, "--"], { cwd: rubricWorkspace, encoding: "utf8", timeout: 10_000 }); if (res.status === 0 && res.stdout.trim()) { diffText = res.stdout; break; } }
|
|
565
|
-
|
|
566
|
-
|
|
594
|
+
for (const base of bases) { const res = spawnSync("git", ["diff", "--no-ext-diff", `${base}...HEAD`, "--"], { cwd: rubricWorkspace, encoding: "utf8", timeout: 10_000 }); if (res.status === 0 && res.stdout.trim()) { diffText = res.stdout; usedBase = base; break; } }
|
|
595
|
+
// No listed base produced a diff. Grading a substitute range
|
|
596
|
+
// returned a rubric over the wrong change and named nothing, so
|
|
597
|
+
// refuse instead. HEAD~1 is graded only when the caller asks for
|
|
598
|
+
// it, and then the provenance line says which range was graded.
|
|
599
|
+
if (!diffText) {
|
|
600
|
+
return `[workflow-guard] No review diff found: workspace=${rubricWorkspace} bases=${bases.join(", ")} diff=0 bytes. No rubric was produced. Remedy: pass base: "<ref>" naming the base that holds the change (base: "HEAD~1" grades the last commit), and directory: "<absolute checkout>" when the change lives in another worktree.`;
|
|
601
|
+
}
|
|
602
|
+
const provenance: RubricProvenance = {
|
|
603
|
+
workspace: rubricWorkspace,
|
|
604
|
+
base: usedBase ?? null,
|
|
605
|
+
diffBytes: Buffer.byteLength(diffText, "utf8"),
|
|
606
|
+
fallback: usedBase === "HEAD~1" ? "HEAD~1" : "none",
|
|
607
|
+
};
|
|
608
|
+
return buildReviewRubric(diffText, undefined, provenance);
|
|
567
609
|
},
|
|
568
610
|
}),
|
|
569
611
|
guard_worktree_create: tool({
|
|
@@ -69,6 +69,7 @@ import {
|
|
|
69
69
|
pushedProtectedBranchIn,
|
|
70
70
|
tagRefspecIn,
|
|
71
71
|
} from "../policies/git.ts";
|
|
72
|
+
import { DELEGATION_REASON, delegationSpawnIn } from "../policies/delegation.ts";
|
|
72
73
|
import { extractInterpreterPayload, outsideWritePathInPayload, secretPathInPayload, writePathsInPayload } from "../policies/interpreter.ts";
|
|
73
74
|
import { mcpMutationTool } from "../policies/mcp.ts";
|
|
74
75
|
import { editTargets } from "../policies/post-edit-validation.ts";
|
|
@@ -489,6 +490,11 @@ export async function guardToolCallImpl(
|
|
|
489
490
|
logPolicyBlock(`[workflow-guard] blocked package supply-chain violation: ${command.slice(0, 100)}`);
|
|
490
491
|
return block("shell-safety", "package_hygiene", `Blocked: '${command.slice(0, 60)}' is a ${packageCheck.name}. ${packageCheck.advice}`);
|
|
491
492
|
}
|
|
493
|
+
const delegated = delegationSpawnIn(raw);
|
|
494
|
+
if (delegated) {
|
|
495
|
+
logPolicyBlock(`[workflow-guard] blocked agent delegation via ${delegated}: ${command.slice(0, 100)}`);
|
|
496
|
+
return block("delegation", "agent_delegation", DELEGATION_REASON);
|
|
497
|
+
}
|
|
492
498
|
const normalizedCommand = normalizeGitCommands(command);
|
|
493
499
|
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
500
|
// Each segment is judged in the directory it actually runs in. A `cd`
|
|
@@ -631,6 +637,11 @@ export async function guardToolCallImpl(
|
|
|
631
637
|
return block("destructive", "live_mutation_payload", `Blocked: inline interpreter script contains a ${liveCheck}. Interpreter payloads cannot smuggle live destructive commands past the guard.`);
|
|
632
638
|
}
|
|
633
639
|
}
|
|
640
|
+
const delegatedPayload = delegationSpawnIn(payload);
|
|
641
|
+
if (delegatedPayload) {
|
|
642
|
+
logPolicyBlock(`[workflow-guard] blocked agent delegation via ${delegatedPayload} in an inline payload`);
|
|
643
|
+
return block("delegation", "agent_delegation", DELEGATION_REASON);
|
|
644
|
+
}
|
|
634
645
|
if (isSettingsTamper(payload)) return block("tamper", "settings_tamper", PROTECTED_PATH_REASON);
|
|
635
646
|
const secretPath = secretPathInPayload(payload);
|
|
636
647
|
if (secretPath) return block("secrets", "secret_read", `Blocked: reading sensitive credential/secret file '${secretPath}' via inline interpreter script is not permitted.`);
|
package/src/lib/review.ts
CHANGED
|
@@ -8,8 +8,32 @@ import {
|
|
|
8
8
|
|
|
9
9
|
export { recordReviewResult, getLastReviewResult, resetReviewState, lastReview, sessionReviews };
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* What a rubric actually graded. A session's own checkout and the checkout
|
|
13
|
+
* holding the change are not always the same tree, so the rubric must name the
|
|
14
|
+
* tree it read and the base it compared against.
|
|
15
|
+
*/
|
|
16
|
+
export interface RubricProvenance {
|
|
17
|
+
/** Absolute workspace root the diff was taken from. */
|
|
18
|
+
workspace: string;
|
|
19
|
+
/** Base ref actually used, or null when the rubric was not produced. */
|
|
20
|
+
base: string | null;
|
|
21
|
+
/** Bytes in the diff the rubric grades, before its own truncation. */
|
|
22
|
+
diffBytes: number;
|
|
23
|
+
/**
|
|
24
|
+
* `HEAD~1` when the graded range is the last commit rather than a branch
|
|
25
|
+
* base. It says which range was graded, not who asked for it: an explicit
|
|
26
|
+
* `base: "HEAD~1"` marks it too, because the range is the same either way.
|
|
27
|
+
*/
|
|
28
|
+
fallback: "none" | "HEAD~1";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function rubricProvenanceLine(provenance: RubricProvenance): string {
|
|
32
|
+
return `Provenance: workspace=${provenance.workspace} base=${provenance.base ?? "none"} diff=${provenance.diffBytes} bytes fallback=${provenance.fallback}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function buildReviewRubric(diffText: string, taskPrompt?: string, provenance?: RubricProvenance): string {
|
|
36
|
+
const lines = [
|
|
13
37
|
"# Secondary Review Agent Quality Gate",
|
|
14
38
|
"",
|
|
15
39
|
"Evaluate this code change independently with fresh context across these 5 core axes:",
|
|
@@ -47,5 +71,7 @@ export function buildReviewRubric(diffText: string, taskPrompt?: string): string
|
|
|
47
71
|
"```",
|
|
48
72
|
"",
|
|
49
73
|
"Provide your verdict: `[APPROVE]` or `[REQUEST_CHANGES]` with concise, actionable findings ranked by priority (P0-P3).",
|
|
50
|
-
]
|
|
74
|
+
];
|
|
75
|
+
if (provenance) lines.unshift(rubricProvenanceLine(provenance), "");
|
|
76
|
+
return lines.join("\n");
|
|
51
77
|
}
|
package/src/policies/boundary.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { isCollaborationInvocation, isProtectedPath, PROTECTED_PATH_REASON } fro
|
|
|
12
12
|
import { isSecretPath, secretIn } from "./secrets.ts";
|
|
13
13
|
import { isGitTreeWriteText, branchGuardReason, onProtectedBranch, parseGitInvocation } from "./git.ts";
|
|
14
14
|
import { findGitRoot, isSameGitRepo, projectRootKey } from "../lib/project-config.ts";
|
|
15
|
-
import { canonicalPath } from "./file-claims.ts";
|
|
15
|
+
import { canonicalPath, fileClaimConflictReason, releaseStaleFileClaims } from "./file-claims.ts";
|
|
16
16
|
import {
|
|
17
17
|
effectiveTodos,
|
|
18
18
|
effectiveTodoOwnerSessionID,
|
|
@@ -798,6 +798,23 @@ export async function guardShellMutation(
|
|
|
798
798
|
// that no command executes is prose, so its lines are not judged either.
|
|
799
799
|
const masked = maskDataHeredocBodies(segment);
|
|
800
800
|
const cleanSegment = isCollaborationInvocation(masked) ? stripQuotedSpans(masked) : masked;
|
|
801
|
+
// Claims are keyed by canonical absolute path, so a relative or
|
|
802
|
+
// `~`-relative target is resolved against the tree this segment runs in
|
|
803
|
+
// before comparing. A provably stale claim is released first, exactly as
|
|
804
|
+
// the edit path does, so the remedy in the conflict message is reachable
|
|
805
|
+
// from the shell too. Shell writes never acquire a claim.
|
|
806
|
+
const claimConflictForTarget = async (candidate: string): Promise<string | undefined> => {
|
|
807
|
+
if (!sessionID) return undefined;
|
|
808
|
+
const expanded = expandShellTargetPath(candidate);
|
|
809
|
+
if (expanded === null) return undefined;
|
|
810
|
+
const claimPath = resolve(runRoot, expanded);
|
|
811
|
+
let conflict = fileClaimConflictReason([claimPath], sessionID, runRoot);
|
|
812
|
+
if (conflict && record) {
|
|
813
|
+
await releaseStaleFileClaims([claimPath], sessionID, runRoot);
|
|
814
|
+
conflict = fileClaimConflictReason([claimPath], sessionID, runRoot);
|
|
815
|
+
}
|
|
816
|
+
return conflict;
|
|
817
|
+
};
|
|
801
818
|
const secretSource = secretSourceInFilesystemCommand(cleanSegment);
|
|
802
819
|
if (secretSource) {
|
|
803
820
|
return `Blocked: shell command would copy, move, or link sensitive file '${secretSource}' under a non-secret name.`;
|
|
@@ -818,6 +835,10 @@ export async function guardShellMutation(
|
|
|
818
835
|
}
|
|
819
836
|
return `Blocked: mv would remove source '${source}' from outside the workspace root (${workspaceRoot}). File mutations must stay within the workspace.`;
|
|
820
837
|
}
|
|
838
|
+
// A move removes its source, so a source another session is
|
|
839
|
+
// editing is a conflict even though the destination is fine.
|
|
840
|
+
const sourceConflict = await claimConflictForTarget(source);
|
|
841
|
+
if (sourceConflict) return sourceConflict;
|
|
821
842
|
}
|
|
822
843
|
}
|
|
823
844
|
const simpleMutations = simpleFilesystemMutations(cleanSegment);
|
|
@@ -867,6 +888,13 @@ export async function guardShellMutation(
|
|
|
867
888
|
if (onProtectedBranch(runRoot)) {
|
|
868
889
|
return branchGuardReason();
|
|
869
890
|
}
|
|
891
|
+
// A direct edit claims its target for the tool-call lifetime so two
|
|
892
|
+
// sessions cannot race it. A shell writer changes the same file, so
|
|
893
|
+
// the same conflict is refused here, with the same reason.
|
|
894
|
+
if (target) {
|
|
895
|
+
const claimConflict = await claimConflictForTarget(target);
|
|
896
|
+
if (claimConflict) return claimConflict;
|
|
897
|
+
}
|
|
870
898
|
const todos = await effectiveTodos(sessionID);
|
|
871
899
|
if (todos !== undefined && !hasActiveTodo(todos)) {
|
|
872
900
|
return (
|
|
@@ -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/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}'`)));
|
|
@@ -1197,6 +1213,70 @@ try {
|
|
|
1197
1213
|
}
|
|
1198
1214
|
check("blocked multi-target patch leaves no partial claims", !partialPatchClaim);
|
|
1199
1215
|
|
|
1216
|
+
// A shell write mutates the same path a direct edit claims, and the claim was
|
|
1217
|
+
// consulted only in the edit branch: `edit` was refused for a path while a
|
|
1218
|
+
// redirect to that same file was allowed at the same moment. A shell write is
|
|
1219
|
+
// a conflict check only (it never acquires a claim), so it cannot strand one.
|
|
1220
|
+
console.log("- Shell mutation claim conflicts -");
|
|
1221
|
+
writeFileSync(join(claimsDir, "shell-target.ts"), "before");
|
|
1222
|
+
writeFileSync(join(claimsDir, "shell-multi.ts"), "before");
|
|
1223
|
+
writeFileSync(join(claimsDir, "shell-multi2.ts"), "before");
|
|
1224
|
+
symlinkSync(join(claimsDir, "shell-target.ts"), join(claimsDir, "shell-target-link.ts"));
|
|
1225
|
+
await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-target.ts"), "claim-shell-read-target");
|
|
1226
|
+
await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-owner" }, { args: { filePath: join(claimsDir, "shell-target.ts"), content: "a" } });
|
|
1227
|
+
const shellBlockReason = async (command: string): Promise<string> => {
|
|
1228
|
+
try {
|
|
1229
|
+
await claimsBefore?.({ tool: "bash", sessionID: "s-claim-b", callID: "claim-shell-attempt" }, { args: { command } });
|
|
1230
|
+
return "";
|
|
1231
|
+
} catch (error) {
|
|
1232
|
+
return String(error);
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
const shellRedirectReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target.ts")}`);
|
|
1236
|
+
check("a shell redirect into a claimed path is refused with the claim reason", shellRedirectReason.includes("is claimed by session") && shellRedirectReason.includes("Reclaim step"));
|
|
1237
|
+
const shellTeeReason = await shellBlockReason(`printf x | tee -a ${join(claimsDir, "shell-target.ts")}`);
|
|
1238
|
+
check("a tee append into a claimed path is refused, with the tee flag parsed", shellTeeReason.includes("is claimed by session"));
|
|
1239
|
+
const shellSymlinkReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target-link.ts")}`);
|
|
1240
|
+
check("a shell write through a symlink alias of a claimed path is refused", shellSymlinkReason.includes("is claimed by session"));
|
|
1241
|
+
const shellChainedReason = await shellBlockReason(`cd ${claimsDir} && echo x > shell-target.ts`);
|
|
1242
|
+
check("a chained shell write into a claimed path is judged in the tree it lands in", shellChainedReason.includes("is claimed by session"));
|
|
1243
|
+
await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-multi2.ts"), "claim-shell-read-multi");
|
|
1244
|
+
await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-multi" }, { args: { filePath: join(claimsDir, "shell-multi2.ts"), content: "a" } });
|
|
1245
|
+
const shellMultiReason = await shellBlockReason(`rm ${join(claimsDir, "shell-multi.ts")} ${join(claimsDir, "shell-multi2.ts")}`);
|
|
1246
|
+
check("a multi-operand shell mutation is refused when any operand is claimed", shellMultiReason.includes("is claimed by session") && shellMultiReason.includes("shell-multi2.ts"));
|
|
1247
|
+
const shellSubagentReason = await (async (): Promise<string> => {
|
|
1248
|
+
fakeParents.set("s-claim-subagent", "s-claim-a");
|
|
1249
|
+
try {
|
|
1250
|
+
await claimsBefore?.({ tool: "bash", sessionID: "s-claim-subagent", callID: "claim-shell-subagent" }, { args: { command: `echo x > ${join(claimsDir, "shell-target.ts")}` } });
|
|
1251
|
+
return "";
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
return String(error);
|
|
1254
|
+
}
|
|
1255
|
+
})();
|
|
1256
|
+
check("a subagent shell write into a path its parent claimed is refused", shellSubagentReason.includes("is claimed by session"));
|
|
1257
|
+
// mv removes its source, so a claimed source is a conflict even when the
|
|
1258
|
+
// destination is unclaimed.
|
|
1259
|
+
writeFileSync(join(claimsDir, "shell-move-source.ts"), "before");
|
|
1260
|
+
await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-move-source.ts"), "claim-shell-read-move");
|
|
1261
|
+
await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-move" }, { args: { filePath: join(claimsDir, "shell-move-source.ts"), content: "a" } });
|
|
1262
|
+
const shellMoveSourceReason = await shellBlockReason(`mv ${join(claimsDir, "shell-move-source.ts")} ${join(claimsDir, "shell-moved-away.ts")}`);
|
|
1263
|
+
check("a mv of a claimed source is refused", shellMoveSourceReason.includes("is claimed by session") && shellMoveSourceReason.includes("shell-move-source.ts"));
|
|
1264
|
+
await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-move", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
1265
|
+
const shellWhy = JSON.parse(String(await claimsHooks.tool?.guard_why?.execute(
|
|
1266
|
+
{ tool: "bash", input: { command: `echo x > ${join(claimsDir, "shell-target.ts")}` } },
|
|
1267
|
+
{ sessionID: "s-claim-b", worktree: claimsDir, directory: claimsDir } as any,
|
|
1268
|
+
)));
|
|
1269
|
+
check(
|
|
1270
|
+
"guard_why reports a shell claim conflict as a shell mutation",
|
|
1271
|
+
shellWhy.code === "shell_mutation" && String(shellWhy.message).includes("is claimed by session"),
|
|
1272
|
+
);
|
|
1273
|
+
const shellUnclaimedReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-multi.ts")}`);
|
|
1274
|
+
check("a shell write to an unclaimed path stays allowed", shellUnclaimedReason === "");
|
|
1275
|
+
await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-owner", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
1276
|
+
await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-multi", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
1277
|
+
const shellAfterReleaseReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target.ts")}`);
|
|
1278
|
+
check("a shell write is allowed once the owning edit releases its claim", shellAfterReleaseReason === "");
|
|
1279
|
+
|
|
1200
1280
|
// Stale claim takeover (missed idle release): a claim created BEFORE its
|
|
1201
1281
|
// owner's last recorded idle timestamp cannot belong to an in-flight tool
|
|
1202
1282
|
// call, so a leaked claim must not block another session forever. Owners that
|
|
@@ -3980,13 +4060,32 @@ check(
|
|
|
3980
4060
|
typeof p0ReviewResult === "string" && p0ReviewResult.includes("P0 or P1 blockers"),
|
|
3981
4061
|
);
|
|
3982
4062
|
|
|
3983
|
-
// The rubric tool emits a real prompt with
|
|
4063
|
+
// The rubric tool emits a real prompt with a real diff. A fixture keeps this
|
|
4064
|
+
// independent of the checkout the suite runs in: once no base yields a diff the
|
|
4065
|
+
// tool now refuses instead of grading a substitute, so an ambient checkout with
|
|
4066
|
+
// nothing to review would assert the wrong thing.
|
|
3984
4067
|
check("plugin registers guard_review_rubric tool", typeof customPlugin.tool?.guard_review_rubric?.execute === "function");
|
|
3985
|
-
const
|
|
4068
|
+
const rubricAxesRepo = join(root, "wg-review-rubric-axes");
|
|
4069
|
+
mkdirSync(rubricAxesRepo, { recursive: true });
|
|
4070
|
+
spawnSync("git", ["init", "-b", "main"], { cwd: rubricAxesRepo });
|
|
4071
|
+
spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricAxesRepo });
|
|
4072
|
+
spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricAxesRepo });
|
|
4073
|
+
writeFileSync(join(rubricAxesRepo, "axes.txt"), "base\n");
|
|
4074
|
+
spawnSync("git", ["add", "axes.txt"], { cwd: rubricAxesRepo });
|
|
4075
|
+
spawnSync("git", ["commit", "-m", "base"], { cwd: rubricAxesRepo });
|
|
4076
|
+
spawnSync("git", ["switch", "-c", "feature/rubric-axes"], { cwd: rubricAxesRepo });
|
|
4077
|
+
writeFileSync(join(rubricAxesRepo, "axes.txt"), "base\nchange\n");
|
|
4078
|
+
spawnSync("git", ["add", "axes.txt"], { cwd: rubricAxesRepo });
|
|
4079
|
+
spawnSync("git", ["commit", "-m", "change"], { cwd: rubricAxesRepo });
|
|
4080
|
+
const rubricOut = await customPlugin.tool?.guard_review_rubric?.execute(
|
|
4081
|
+
{ base: "main", directory: rubricAxesRepo },
|
|
4082
|
+
{ sessionID: "s-rubric-axes", worktree: rubricAxesRepo, directory: rubricAxesRepo } as any,
|
|
4083
|
+
);
|
|
3986
4084
|
check(
|
|
3987
4085
|
"guard_review_rubric returns the rubric with axes",
|
|
3988
4086
|
typeof rubricOut === "string" && rubricOut.includes("Test Integrity") && rubricOut.includes("Code Diff Under Review"),
|
|
3989
4087
|
);
|
|
4088
|
+
rmSync(rubricAxesRepo, { recursive: true, force: true });
|
|
3990
4089
|
const rubricOptionFlag = await customPlugin.tool?.guard_review_rubric?.execute({ base: "--output=injected" }, {} as any);
|
|
3991
4090
|
check("guard_review_rubric sanitizes option flags in base ref", typeof rubricOptionFlag === "string" && !existsSync(join(root, "injected")));
|
|
3992
4091
|
|
|
@@ -4045,6 +4144,94 @@ check(
|
|
|
4045
4144
|
);
|
|
4046
4145
|
rmSync(rubricNoOrigin, { recursive: true, force: true });
|
|
4047
4146
|
|
|
4147
|
+
// Provenance: the rubric must name the tree it graded. A session whose own
|
|
4148
|
+
// checkout holds unrelated work must be able to grade a linked worktree, and
|
|
4149
|
+
// the rubric must say which workspace and base it read. Before this fix the
|
|
4150
|
+
// tool returned a rubric over whichever tree it happened to resolve and named
|
|
4151
|
+
// neither, so a real review was graded against the wrong diff.
|
|
4152
|
+
const rubricWtPrimary = join(root, "wg-rubric-wt-primary");
|
|
4153
|
+
mkdirSync(rubricWtPrimary, { recursive: true });
|
|
4154
|
+
spawnSync("git", ["init", "-b", "main"], { cwd: rubricWtPrimary });
|
|
4155
|
+
spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricWtPrimary });
|
|
4156
|
+
spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricWtPrimary });
|
|
4157
|
+
writeFileSync(join(rubricWtPrimary, "seed.txt"), "base\n");
|
|
4158
|
+
spawnSync("git", ["add", "seed.txt"], { cwd: rubricWtPrimary });
|
|
4159
|
+
spawnSync("git", ["commit", "-m", "base"], { cwd: rubricWtPrimary });
|
|
4160
|
+
// The session's own checkout carries unrelated work. Judging THIS tree would
|
|
4161
|
+
// put primaryOnlyMarker in the rubric instead of the worktree's change.
|
|
4162
|
+
spawnSync("git", ["switch", "-c", "feature/primary-unrelated"], { cwd: rubricWtPrimary });
|
|
4163
|
+
writeFileSync(join(rubricWtPrimary, "primary-only.txt"), "primaryOnlyMarker\n");
|
|
4164
|
+
spawnSync("git", ["add", "primary-only.txt"], { cwd: rubricWtPrimary });
|
|
4165
|
+
spawnSync("git", ["commit", "-m", "unrelated primary work"], { cwd: rubricWtPrimary });
|
|
4166
|
+
const rubricWtLinked = join(root, "wg-rubric-wt-linked");
|
|
4167
|
+
spawnSync("git", ["worktree", "add", "-q", "-b", "feature/wt-under-review", rubricWtLinked, "main"], { cwd: rubricWtPrimary });
|
|
4168
|
+
writeFileSync(join(rubricWtLinked, "worktree-change.txt"), "worktreeOnlyMarker\n");
|
|
4169
|
+
spawnSync("git", ["add", "worktree-change.txt"], { cwd: rubricWtLinked });
|
|
4170
|
+
spawnSync("git", ["commit", "-m", "worktree change under review"], { cwd: rubricWtLinked });
|
|
4171
|
+
const rubricWtRoot = String(spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: rubricWtLinked, encoding: "utf8" }).stdout).trim();
|
|
4172
|
+
const rubricWtDiff = String(spawnSync("git", ["diff", "--no-ext-diff", "main...HEAD", "--"], { cwd: rubricWtLinked, encoding: "utf8" }).stdout);
|
|
4173
|
+
const rubricWtOut = await customPlugin.tool?.guard_review_rubric?.execute(
|
|
4174
|
+
{ directory: rubricWtLinked },
|
|
4175
|
+
{ sessionID: "s-rubric-wt", worktree: rubricWtPrimary, directory: rubricWtPrimary } as any,
|
|
4176
|
+
);
|
|
4177
|
+
check(
|
|
4178
|
+
"guard_review_rubric grades the requested worktree and names it in the provenance line",
|
|
4179
|
+
typeof rubricWtOut === "string" &&
|
|
4180
|
+
rubricWtOut.includes(`Provenance: workspace=${rubricWtRoot} base=main `) &&
|
|
4181
|
+
rubricWtOut.includes(`diff=${Buffer.byteLength(rubricWtDiff, "utf8")} bytes`) &&
|
|
4182
|
+
rubricWtOut.includes("worktreeOnlyMarker") &&
|
|
4183
|
+
!rubricWtOut.includes("primaryOnlyMarker"),
|
|
4184
|
+
);
|
|
4185
|
+
|
|
4186
|
+
// No matching base: refuse. The old code ran `git diff HEAD~1` and printed a
|
|
4187
|
+
// rubric over that substitute, so the caller got a confident review of the
|
|
4188
|
+
// wrong range with no indication that its base was never found.
|
|
4189
|
+
const rubricNoBase = join(root, "wg-rubric-no-base");
|
|
4190
|
+
mkdirSync(rubricNoBase, { recursive: true });
|
|
4191
|
+
spawnSync("git", ["init", "-b", "main"], { cwd: rubricNoBase });
|
|
4192
|
+
spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricNoBase });
|
|
4193
|
+
spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricNoBase });
|
|
4194
|
+
writeFileSync(join(rubricNoBase, "seed.txt"), "base\n");
|
|
4195
|
+
spawnSync("git", ["add", "seed.txt"], { cwd: rubricNoBase });
|
|
4196
|
+
spawnSync("git", ["commit", "-m", "base"], { cwd: rubricNoBase });
|
|
4197
|
+
writeFileSync(join(rubricNoBase, "last-commit.txt"), "substituteMarker\n");
|
|
4198
|
+
spawnSync("git", ["add", "last-commit.txt"], { cwd: rubricNoBase });
|
|
4199
|
+
spawnSync("git", ["commit", "-m", "last commit"], { cwd: rubricNoBase });
|
|
4200
|
+
const rubricNoBaseRoot = String(spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: rubricNoBase, encoding: "utf8" }).stdout).trim();
|
|
4201
|
+
const rubricNoBaseOut = await customPlugin.tool?.guard_review_rubric?.execute(
|
|
4202
|
+
{ directory: rubricNoBase },
|
|
4203
|
+
{ sessionID: "s-rubric-no-base", worktree: rubricNoBase, directory: rubricNoBase } as any,
|
|
4204
|
+
);
|
|
4205
|
+
check(
|
|
4206
|
+
"guard_review_rubric refuses when no base yields a diff instead of grading a substitute",
|
|
4207
|
+
typeof rubricNoBaseOut === "string" &&
|
|
4208
|
+
rubricNoBaseOut.includes("No review diff found") &&
|
|
4209
|
+
rubricNoBaseOut.includes(`workspace=${rubricNoBaseRoot}`) &&
|
|
4210
|
+
rubricNoBaseOut.includes("bases=origin/main, origin/master, main, master") &&
|
|
4211
|
+
rubricNoBaseOut.includes("Remedy") &&
|
|
4212
|
+
!rubricNoBaseOut.includes("substituteMarker") &&
|
|
4213
|
+
!rubricNoBaseOut.includes("Code Diff Under Review"),
|
|
4214
|
+
);
|
|
4215
|
+
|
|
4216
|
+
// HEAD~1 is graded only when the caller asks for it, and the provenance line
|
|
4217
|
+
// says which range was graded so a reader can tell it is the last commit.
|
|
4218
|
+
const rubricHead1Out = await customPlugin.tool?.guard_review_rubric?.execute(
|
|
4219
|
+
{ base: "HEAD~1", directory: rubricNoBase },
|
|
4220
|
+
{ sessionID: "s-rubric-head1", worktree: rubricNoBase, directory: rubricNoBase } as any,
|
|
4221
|
+
);
|
|
4222
|
+
check(
|
|
4223
|
+
"an explicit HEAD~1 base is honored and named in the provenance line",
|
|
4224
|
+
typeof rubricHead1Out === "string" &&
|
|
4225
|
+
rubricHead1Out.includes("base=HEAD~1") &&
|
|
4226
|
+
rubricHead1Out.includes("fallback=HEAD~1") &&
|
|
4227
|
+
rubricHead1Out.includes("substituteMarker") &&
|
|
4228
|
+
rubricHead1Out.includes("Code Diff Under Review"),
|
|
4229
|
+
);
|
|
4230
|
+
rmSync(rubricNoBase, { recursive: true, force: true });
|
|
4231
|
+
spawnSync("git", ["worktree", "remove", "--force", rubricWtLinked], { cwd: rubricWtPrimary });
|
|
4232
|
+
rmSync(rubricWtLinked, { recursive: true, force: true });
|
|
4233
|
+
rmSync(rubricWtPrimary, { recursive: true, force: true });
|
|
4234
|
+
|
|
4048
4235
|
// Reviewer-type agents often lack record_review in their toolset entirely, so
|
|
4049
4236
|
// the tool accepts recorders of any session type: the verdict binds to the
|
|
4050
4237
|
// recording session's directory and the audit trail captures the recorder
|
|
@@ -5670,6 +5857,53 @@ check("shell tool blocks global npm install", blocked(await shell("npm i -g tsx"
|
|
|
5670
5857
|
check("shell tool blocks direct npm publish", blocked(await shell("npm publish --access public")));
|
|
5671
5858
|
check("shell tool allows regular npm install", !(await shell("npm install lodash")));
|
|
5672
5859
|
|
|
5860
|
+
// 18. Policy 28: Agent Delegation Boundary
|
|
5861
|
+
console.log("- Policy 28: Agent Delegation Boundary -");
|
|
5862
|
+
check("delegationSpawnIn detects claude", delegationSpawnIn('claude -p "summarise"') === "claude");
|
|
5863
|
+
check("delegationSpawnIn detects codex", delegationSpawnIn("codex exec 'run tests'") === "codex");
|
|
5864
|
+
check("delegationSpawnIn detects gemini", delegationSpawnIn("gemini -p 'x'") === "gemini");
|
|
5865
|
+
check("delegationSpawnIn detects aider", delegationSpawnIn("aider --message 'x'") === "aider");
|
|
5866
|
+
check("delegationSpawnIn detects opencode run", delegationSpawnIn("opencode run 'x'") === "opencode run");
|
|
5867
|
+
check("delegationSpawnIn detects opencode run behind a global flag", delegationSpawnIn("opencode --dir /tmp run 'x'") === "opencode run");
|
|
5868
|
+
check("delegationSpawnIn detects opencode run behind a value flag", delegationSpawnIn("opencode --log-level debug run 'x'") === "opencode run");
|
|
5869
|
+
check("delegationSpawnIn permits an opencode help request naming run", delegationSpawnIn("opencode --help run") === undefined);
|
|
5870
|
+
check("delegationSpawnIn permits another opencode subcommand", delegationSpawnIn("opencode export ses_abc") === undefined);
|
|
5871
|
+
check("delegationSpawnIn does not read a plugin argument as the subcommand", delegationSpawnIn("opencode --model x plugin add run") === undefined);
|
|
5872
|
+
check("delegationSpawnIn detects a path-qualified executable", delegationSpawnIn("/usr/local/bin/claude -p x") === "claude");
|
|
5873
|
+
check("delegationSpawnIn unwraps env assignments", delegationSpawnIn("env FOO=1 claude -p x") === "claude");
|
|
5874
|
+
check("delegationSpawnIn unwraps sudo options", delegationSpawnIn("sudo -u deploy claude -p x") === "claude");
|
|
5875
|
+
check("delegationSpawnIn unwraps timeout", delegationSpawnIn("timeout 30 codex exec x") === "codex");
|
|
5876
|
+
check("delegationSpawnIn unwraps command builtin", delegationSpawnIn("command claude -p x") === "claude");
|
|
5877
|
+
check("delegationSpawnIn detects a chained segment", delegationSpawnIn("echo hi | claude -p x") === "claude");
|
|
5878
|
+
check("delegationSpawnIn detects a cd-prefixed segment", delegationSpawnIn("cd /tmp && claude -p x") === "claude");
|
|
5879
|
+
check("delegationSpawnIn detects a grouping subshell", delegationSpawnIn("ls && (claude -p x)") === "claude");
|
|
5880
|
+
check("delegationSpawnIn detects npx package execution", delegationSpawnIn("npx -y claude-code -p x") === "claude");
|
|
5881
|
+
check("delegationSpawnIn detects scoped npx package", delegationSpawnIn("npx @openai/codex exec x") === "codex");
|
|
5882
|
+
check("delegationSpawnIn detects bunx package execution", delegationSpawnIn("bunx gemini-cli -p x") === "gemini");
|
|
5883
|
+
check("delegationSpawnIn detects a versioned npx package", delegationSpawnIn("npx claude-code@latest -p x") === "claude");
|
|
5884
|
+
check("delegationSpawnIn permits an argument-only mention", delegationSpawnIn("grep claude README.md") === undefined);
|
|
5885
|
+
check("delegationSpawnIn permits a quoted argument mention", delegationSpawnIn('echo "run claude for details"') === undefined);
|
|
5886
|
+
check("delegationSpawnIn permits a git log grep value", delegationSpawnIn("git log --grep=codex") === undefined);
|
|
5887
|
+
check("delegationSpawnIn permits an npx plugin flag value", delegationSpawnIn("npx prettier --plugin claude --write src") === undefined);
|
|
5888
|
+
check("delegationSpawnIn permits a read-only opencode verb", delegationSpawnIn("opencode plugin list") === undefined);
|
|
5889
|
+
|
|
5890
|
+
check("shell tool blocks direct claude spawn", blocked(await shell('claude -p "summarise"')),);
|
|
5891
|
+
check("delegation block reason names the escape", ((await shell("claude -p x")) ?? "").includes("outside this session's workflow guard"));
|
|
5892
|
+
check("shell tool blocks opencode run", blocked(await shell("opencode run 'do the work'")));
|
|
5893
|
+
check("shell tool blocks a wrapped codex spawn", blocked(await shell("env FOO=1 timeout 30 codex exec x")));
|
|
5894
|
+
check("shell tool blocks a chained aider spawn", blocked(await shell("git status && aider --message x")));
|
|
5895
|
+
check("shell tool blocks an npx claude-code spawn", blocked(await shell("npx -y claude-code -p x")));
|
|
5896
|
+
check("shell tool blocks a bash -c claude payload", blocked(await shell("bash -c 'claude -p x'")));
|
|
5897
|
+
check("shell tool blocks a sh -lc codex payload", blocked(await shell("sh -lc 'codex exec x'")));
|
|
5898
|
+
check("shell tool blocks an eval claude payload", blocked(await shell("eval 'claude -p x'")));
|
|
5899
|
+
check("shell tool blocks a heredoc body that runs claude", blocked(await shell("bash <<'EOF'\nclaude -p x\nEOF")));
|
|
5900
|
+
check("shell tool blocks delegation for a read-only subagent", blocked(await call("bash", { command: "claude -p x" }, { sessionID: "s-child", agent: "reviewer" })));
|
|
5901
|
+
check("shell tool blocks delegation for a worker subagent", blocked(await call("bash", { command: "gemini -p x" }, { sessionID: "s-child", agent: "executor" })));
|
|
5902
|
+
check("shell tool allows an argument-only claude mention", !(await shell("grep claude README.md")));
|
|
5903
|
+
check("shell tool allows prose quoting a launcher", !(await shell('echo "run claude for details"')));
|
|
5904
|
+
check("shell tool allows a prose heredoc mentioning claude", !(await shell("cat > notes.md <<'EOF'\nclaude is an agent CLI\nEOF")));
|
|
5905
|
+
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" })));
|
|
5906
|
+
|
|
5673
5907
|
// Durable Recovery Checkpoints
|
|
5674
5908
|
console.log("- Durable Recovery Checkpoints -");
|
|
5675
5909
|
const checkpointDir = mkdtempSync(join(tmpdir(), "wg-checkpoint-"));
|
|
@@ -6580,6 +6814,16 @@ check("tool.definition todowrite enriches with planning and status guidance", to
|
|
|
6580
6814
|
const systemOutput = { system: ["Base system prompt"] };
|
|
6581
6815
|
await defPlugin["experimental.chat.system.transform"]?.({ model: { id: "gemini-flash" } as any }, systemOutput);
|
|
6582
6816
|
check("experimental.chat.system.transform adds workflow guard guidance", systemOutput.system.length === 2 && systemOutput.system[1].includes("## Workflow Guard & Operational Tools") && systemOutput.system[1].includes("guard_next_tasks") && systemOutput.system[1].includes("guard_review_rubric"));
|
|
6817
|
+
// A reviewer agent that denies every action does not carry record_review, so
|
|
6818
|
+
// the injected instruction must name the calling session as the recorder. The
|
|
6819
|
+
// old text told the subagent to record its own verdict, which the fleet
|
|
6820
|
+
// reviewer could not do.
|
|
6821
|
+
check(
|
|
6822
|
+
"injected guidance names the calling session as the review recorder",
|
|
6823
|
+
systemOutput.system[1].includes("The calling session records that subagent's verdict") &&
|
|
6824
|
+
systemOutput.system[1].includes("may not carry the tool") &&
|
|
6825
|
+
!systemOutput.system[1].includes("that records its verdict with `record_review`"),
|
|
6826
|
+
);
|
|
6583
6827
|
const systemOutputIdem = { system: [...systemOutput.system] };
|
|
6584
6828
|
await defPlugin["experimental.chat.system.transform"]?.({ model: { id: "gemini-flash" } as any }, systemOutputIdem);
|
|
6585
6829
|
check("experimental.chat.system.transform is idempotent", systemOutputIdem.system.length === 2);
|