opencode-workflow-guard 1.19.1 → 1.19.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/policies.md +12 -8
- package/docs/testing.md +3 -0
- package/package.json +6 -6
- package/src/lib/custom-tools.ts +28 -1
- package/src/lib/guard-api.ts +85 -0
- package/src/lib/permission-seat.ts +3 -1
- package/src/lib/tool-descriptions.ts +36 -0
- package/src/lib/types.ts +7 -1
- package/src/lib/v2-plugin.ts +236 -135
- package/src/policies/continuation.ts +107 -13
- package/src/workflow-guard.ts +17 -79
- package/test/test-e2e.mts +20 -4
- package/test/test.mts +396 -0
package/docs/policies.md
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
On OpenCode 1.x those hooks are `tool.execute.before`, `experimental.session.compacting`, `shell.env`, `permission.ask`, and `event` journaling. On OpenCode 2.x they are `tool.hook("execute.before"/"execute.after")`, `session.hook("context"/"compaction"/"prompt")`, `command.transform`, `permission.hook("evaluate")`, `shell.hook("create.before")`, and `event.subscribe()`. V1 plugin implementations do not run on OpenCode 2. The two lists therefore describe separate entrypoints, not alternatives for the same host.
|
|
6
6
|
|
|
7
|
+
**A V2 event handler runs only if the host delivers its type.** `ctx.event.subscribe()` is served from `EventManifest.ServerDefinitions`. A type that appears in `EventManifest.Definitions` but not in `ServerDefinitions` is never delivered, so a handler for it is dead code even though it compiles and looks live. Check every `event.type` comparison against that manifest before relying on it. The subscription also passes the `types` filter, so only those types cross the stream at all. The test suite enforces both structurally: a scan of `src/lib/v2-plugin.ts` asserts every compared literal is delivered, and that `V2_EVENT_TYPES` matches the handler's comparisons in both directions.
|
|
8
|
+
|
|
7
9
|
This is a policy and enforcement layer, not an agent harness. Policies may constrain actions, record or explain decisions, and preserve bounded context. They do not plan, prioritize, delegate, or autonomously sequence work. Where Workflow Guard resumes an idle session, it only enforces already-owned todo lifecycle state. It does not choose what the agent works on next.
|
|
8
10
|
|
|
9
11
|
---
|
|
@@ -19,7 +21,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
19
21
|
- **Read-only escape:** A task whose text carries `[read-only]`, also `[read_only]` or `[read only]`, completes without a mutation. Review, investigation, and reading are legitimate work that changes no file. The marker is an annotation, not part of task identity, so it can be appended to an already-planned task without reading as a deletion. Every use is journaled as `todo_completed_read_only`, so relabeling real work as read-only stays visible in the audit trail. In a repository with no detectable verify command, that journal is the only counterweight. Work that was deliberately dropped uses `cancelled` instead.
|
|
20
22
|
- `guard_status` reports `taskEvidence` (`active`, `completed`, `tasksWithoutRecordedWork`, `readOnlyTasks`), so the requirement is visible before it blocks anything. This is not task authority. Fresh verification evidence and the review gate remain the authority on finalization.
|
|
21
23
|
- **Todo Capability Visibility:** Because the gate depends on the host exposing `todowrite` at all, `guard_status` reports `todoCapability` (`available` / `unavailable` / `unknown`). A fail-open gate is therefore visible rather than decorative.
|
|
22
|
-
- **No Silent Early Exit:** When an owning session
|
|
24
|
+
- **No Silent Early Exit:** When an owning session reaches the idle state with unfinished native todos, the guard asynchronously asks OpenCode to resume the existing run. That trigger is `session.status` with `status.type === "idle"` or the deprecated `session.idle`; both are in `EventManifest.ServerDefinitions`, and which one the server publishes is not settled, so neither is relied on alone. A host that emits both for one transition still produces a single continuation prompt, because the send holds a per-session in-flight lock. This enforces the session's existing lifecycle state. Workflow Guard does not choose the next task, reorder work, create work, or delegate it. Ordinary automatic continuations are capped at three consecutive attempts, and the budget resets on genuine user input. User-initiated interrupts (Esc) suspend automatic continuation for that session until genuine user input arrives, mirroring the ralph `user_stopped` semantics. On OpenCode 2 this is driven by `session.execution.interrupted`, and only reason `user` suspends: `shutdown`, `superseded`, and `inactivity` are host-lifecycle events, not user intent, and they leave continuation state alone. The independently opt-in `ralphMode` uses `ralphMaxIterations` (1-100, default 10) instead. Genuine user input terminates an active Ralph run, and unfinished work at the budget limit reports `budget_exhausted` rather than inferring a policy block. Ralph remains disabled by default under every operation profile. Use OpenCode's native `question` tool when user feedback or a decision is required. Question and permission interactions wait inside the active run rather than producing an idle completion.
|
|
23
25
|
- **Subagent Inheritance & Role Confinement:** Subagents inherit active tasks from their parent session via the `parentID` hierarchy. Subagents spawned with read-only roles (`reviewer`, `planner`, `advisor`, `critic`, `explorer`, `scout`, `evaluator`) are hard-confined. File mutations, lifecycle tools, and mutating shell commands are strictly blocked. On OpenCode 2 the confinement is two-layered. `session.hook("context")` deletes the mutating tools (`write`, `edit`, `patch`, `apply_patch`, `shell`, `bash`, `execute`, `todowrite`, `subagent`/`task`, worktree lifecycle tools) from that role's per-request tool snapshot. `execute.before` stays as the backstop for tools supplied outside the snapshot, such as ACP agents and nested Code Mode calls. The pruning is journaled as `session.context` / `read_only_role_tools_pruned`.
|
|
24
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.
|
|
25
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.
|
|
@@ -65,7 +67,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
65
67
|
- MCP tools that mutate live GitHub or Azure/DevOps systems (`create`, `update`, `delete`, `merge`, `push`, `close`, etc.) are blocked.
|
|
66
68
|
- Server names are tokenized on all non-alphanumerics, so `mcp__azure-devops__...`, `mcp__gh__...` and flat legacy names (`azure_devops_*`) are matched.
|
|
67
69
|
- Read-only tools (`get`, `list`, `search`, `query`, etc.) are permitted.
|
|
68
|
-
- On OpenCode 2 the guarded server set is widened from the host's own MCP roster (`ctx.mcp.list()`), refreshed on `mcp.
|
|
70
|
+
- On OpenCode 2 the guarded server set is widened from the host's own MCP roster (`ctx.mcp.list()`), refreshed on `mcp.status.changed`. That is the delivered trigger: `mcp.tools.changed` is an ephemeral host-internal event absent from `EventManifest.ServerDefinitions`, so a handler for it never runs. A renamed or enterprise instance of a guarded product is therefore still matched, including a server that connects mid-session. Widening is one-way by design: removing a server adds nothing, and the static token list stays the floor. Tool names are model-supplied text, and this is a live-system rail.
|
|
69
71
|
|
|
70
72
|
### 6. Settings Tamper Guard
|
|
71
73
|
- Prevents the agent from weakening its own permission gates **via shell or edit tools**:
|
|
@@ -110,8 +112,8 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
110
112
|
- The verification timeout defaults to 30 seconds. Raise it per project with `verifyTimeoutMs` in `.opencode/workflow-guard.json`, or per environment with `WORKFLOW_GUARD_VERIFY_TIMEOUT_MS`, which wins over project config. Non-positive values are ignored and fall back to the default. Raise the timeout for suites that legitimately exceed the default, for example this repository's own unit suite.
|
|
111
113
|
- A timeout is reported as `verification_timed_out`, not `verification_failed`. Both block finalization, because neither produced a passing result. They differ in what the agent is told: a timeout says the result is unknown and names the limit and the remedy, while a failure names the failing output. Calling a timeout a failure sent agents looking for an assertion that never ran, and the fix for a timeout is a longer limit rather than a code change.
|
|
112
114
|
- Project `postEditValidators` can run faster targeted checks after a direct file edit actually changes the target. Each entry accepts a workspace-relative glob `pattern` with `*`, `**`, and `?` wildcards. Brace expansion and character classes are not supported. Each entry also accepts a non-empty `command` and an optional positive `timeoutMs`. Invalid entries are reported as advisory feedback rather than silently ignored. Matching commands run from the workspace root with the same scrubbed verification environment. Validator failures and timeouts are appended to the edit result as advisory feedback. They do not replace the blocking whole-project finalization verification. Multi-file `apply_patch` calls validate every changed target.
|
|
113
|
-
- With project `recoveryCheckpoints: true`, or the `autonomous` operation profile unless explicitly overridden, genuine root-session user runs capture a private Git checkpoint before agent work starts. Checkpoints preserve tracked and untracked state without using the user's stash list. Subagents and generated continuation prompts do not replace them. At `session.idle
|
|
114
|
-
- Automatic continuation remains synthetic. By default, an eligible root session with unfinished owned todos briefly waits for OpenCode's native asynchronous title generation before that continuation is sent.
|
|
115
|
+
- With project `recoveryCheckpoints: true`, or the `autonomous` operation profile unless explicitly overridden, genuine root-session user runs capture a private Git checkpoint before agent work starts. Checkpoints preserve tracked and untracked state without using the user's stash list. Subagents and generated continuation prompts do not replace them. At the idle trigger (`session.status` with `status.type === "idle"`), the run's resulting workspace fingerprint is recorded before automatic continuation. `guard_recovery_restore` is provenance-bound to the same root session and refuses restoration after any intervening workspace change. Operation profiles only set optional workflow defaults and cannot weaken core safety policies.
|
|
116
|
+
- Automatic continuation remains synthetic. By default, an eligible root session with unfinished owned todos briefly waits for OpenCode's native asynchronous title generation before that continuation is sent. The wait ends as soon as the delivered `session.renamed` event reports that the title committed, and falls back to the bounded poll interval on a host that does not emit it. The bounded wait never rewrites titles or provider and model parameters. Set `titleSettleWorkaround: false` to opt out.
|
|
115
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.
|
|
116
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.
|
|
117
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.
|
|
@@ -128,7 +130,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
128
130
|
- This prevents the agent from carrying live credentials by default. The user can still grant access through OpenCode's own permission system if a task genuinely needs it.
|
|
129
131
|
|
|
130
132
|
### 13. Command-Channel Audit
|
|
131
|
-
- User-triggered slash commands (`command.executed` events) are journaled to the audit trail so agents cannot perform hidden work through a user-facing side channel.
|
|
133
|
+
- User-triggered slash commands (`command.executed` events) are journaled to the audit trail so agents cannot perform hidden work through a user-facing side channel. **This audit is V1 only.** On V2 the type sits in `EventManifest.Definitions` but is absent from `ServerDefinitions`, so it is never delivered and no V2 handler can journal it. No delivered V2 event carries a slash-command invocation, so the audit is not re-routed there: `command.updated` reports registry config changes, not invocations.
|
|
132
134
|
|
|
133
135
|
### 14. Audit Trail & Permission Journaling
|
|
134
136
|
- Every block and allow decision is appended to `~/.local/state/opencode/workflow-guard/workflow-guard.jsonl`, with XDG_STATE_HOME respected. Each record carries a timestamp, session id, tool name, decision, subagent and parent session attribution, and reason. This is a durable record.
|
|
@@ -153,8 +155,9 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
153
155
|
- Preserves policy-relevant context across session compactions without assigning, prioritizing, or sequencing tasks for the model.
|
|
154
156
|
|
|
155
157
|
### 16. TUI Visual Feedback & Static Status Badge
|
|
156
|
-
-
|
|
157
|
-
-
|
|
158
|
+
- On OpenCode 1.x, emits real-time warning toasts to the user interface via `tui.showToast` whenever a guard policy blocks a tool call.
|
|
159
|
+
- On OpenCode 2.x there is no client-side `tui.showToast` on the plugin's client shim, so block paths do not attempt a toast. The thrown tool-hook error carries the reason to the model, which is what the model actually acts on. A V2 session therefore has no toast surface, and the reason arrives as the call's failure message.
|
|
160
|
+
- The companion TUI plugin (`workflow-guard-ui.ts`) keeps `Workflow Guard 🛡️` static in the prompt bar. Block details remain in the warning toast rather than changing badge content or color. That companion is installed separately and is not part of the V2 server entrypoint.
|
|
158
161
|
|
|
159
162
|
### 17. Secret-File READ Block & Safe Schema Masking
|
|
160
163
|
- Blocks reading sensitive credential files through the `read` tool, shell commands, or inline interpreter payloads. The credential patterns are `.env*`, `*.pem`, `*.key`, `id_rsa*`, `id_ed25519*`, `*kubeconfig*`, `*credentials*.json`, and `service-account*.json`. The shell commands are `cat`, `less`, `more`, `grep`, `awk`, `head`, `tail`, and `base64`. Interpreter payload examples are `python3 -c "open('.env')"` and `bash -c 'cat id_rsa'`.
|
|
@@ -203,7 +206,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
203
206
|
- **A failed research attempt never accrues debt.** Only non-research failures count. Otherwise a flaky or rate-limited search would deepen the block the agent is trying to escape. The floor would then deadlock a session that followed its own advice.
|
|
204
207
|
- **Research recognition:** the builtin names (`websearch`, `webfetch`, and common aliases) match outright. MCP sources match on documented server names, so `mcp__context7__*`, `mcp__deepwiki__*`, `mcp__tavily__*`, `mcp__brave__*`, and similar docs servers count. A guard inspection tool or a generic file reader cannot clear the debt by name accident. Add an unrecognised server with `researchTools` in project config, or `WORKFLOW_GUARD_RESEARCH_TOOLS` (comma-separated name fragments).
|
|
205
208
|
- Prior art: iterative grounding / De-Hallucinator (arXiv 2401.01701), knowledge-lookup gates for agent writes, and deterministic supersession (STALE, arXiv 2605.06527). Failure-mode context: false/illusory completion (agents self-report done) and temporal obsolescence of training data.
|
|
206
|
-
- Enabled **by default** to force the failover. Disable with `.opencode/workflow-guard.json` (`requireLiveDocs: false`) or `WORKFLOW_GUARD_REQUIRE_LIVE_DOCS=0`. Raise or lower the trigger with `liveDocFailureThreshold` or `WORKFLOW_GUARD_LIVE_DOC_THRESHOLD`. An unparseable, zero, or negative threshold falls back to the default of 3, so a typo cannot silently disable the floor. Decisions are journaled (`reason: live_docs_research_floor`) under both entrypoints. On OpenCode 1.x block feedback also reaches `client.app.log` at warn level. OpenCode 2 has no server-side log API, so V2 journals the decision and
|
|
209
|
+
- Enabled **by default** to force the failover. Disable with `.opencode/workflow-guard.json` (`requireLiveDocs: false`) or `WORKFLOW_GUARD_REQUIRE_LIVE_DOCS=0`. Raise or lower the trigger with `liveDocFailureThreshold` or `WORKFLOW_GUARD_LIVE_DOC_THRESHOLD`. An unparseable, zero, or negative threshold falls back to the default of 3, so a typo cannot silently disable the floor. Decisions are journaled (`reason: live_docs_research_floor`) under both entrypoints. On OpenCode 1.x block feedback also reaches `client.app.log` at warn level and a warning toast. OpenCode 2 has no server-side log API and no client toast, so V2 journals the decision and throws it as the call's failure message.
|
|
207
210
|
- **Known limit:** Code Mode `execute` is not gated, because the nested tools it calls do not pass through guard hooks. A session that reaches the floor can still mutate through that path, the same way it can through an unmodelled indirection described under Known Limits.
|
|
208
211
|
- **Prerequisite:** the acting agent must be allowed to call a research tool. An agent whose toolset denies `websearch`/`webfetch` and exposes no MCP docs server cannot satisfy the floor. Grant one, or the agent will (correctly) stall on the block. This is an opt-out-able default for that reason.
|
|
209
212
|
|
|
@@ -253,6 +256,7 @@ Besides enforcement hooks, the guard registers companion tools in OpenCode:
|
|
|
253
256
|
|
|
254
257
|
### Hook-Context Safety
|
|
255
258
|
- All spawned git commands run with a sanitized environment. Inherited git context variables (`GIT_INDEX_FILE`, `GIT_DIR`, `GIT_WORK_TREE`, and others) are stripped, so the tools resolve the repository from their working directory alone. This makes them safe to invoke from inside git hooks, which export those variables.
|
|
259
|
+
- **Abort propagation:** The two hosts name the per-call abort signal differently. OpenCode 2's promise-layer tool context supplies `signal`, and OpenCode 1's supplies `abort`. The long-running guard tools that spawn subprocesses (`guard_worktree_create`, `guard_worktree_cleanup`, `guard_review_rubric`, `guard_recovery_restore`) read either one before starting work, so a call whose session was interrupted before it started returns a `Cancelled` result instead of running to its own timeout. The check runs before the work rather than during it, because `spawnSync` cannot observe an abort mid-flight. Short git-backed reads (`guard_status`, `record_review`, `record_dogfood`, `project_memory_record`) are deliberately out of scope: their subprocesses are bounded by a five-second timeout and cannot strand a session.
|
|
256
260
|
|
|
257
261
|
### Inspection Tools
|
|
258
262
|
### `guard_status`
|
package/docs/testing.md
CHANGED
|
@@ -26,6 +26,8 @@ WORKFLOW_GUARD_LIVE_E2E=1 npm run test:install # also run model-driven policy pr
|
|
|
26
26
|
```
|
|
27
27
|
Package and loader checks remain deterministic. Live probes explicitly select the first entry in OpenCode's persisted recent-model state (`${XDG_STATE_HOME:-~/.local/state}/opencode/model.json`). They never silently inherit the configured default model. Set `WORKFLOW_GUARD_LIVE_MODEL=provider/model` to override that selection. Provider credentials still come from the normal OpenCode environment. A provider may reject a live prompt before guard behavior can run. That happens when credits, rate limits, capacity, overload, or an unresolvable model make the provider unavailable. Such a case is reported as unavailable rather than as a guard failure. The classifier matches the host's literal `Model unavailable:` error line rather than the bare phrase, so model prose cannot mask a real guard regression. Other live-runtime failures still fail the suite.
|
|
28
28
|
|
|
29
|
+
The suite needs a temp directory with room for a full `node_modules` copy. On a host whose `os.tmpdir()` is a small tmpfs, a nearly full one fails `npm pack` and `npm install` with `Unknown system error -122` (`EDQUOT`). Point `TMPDIR` at a filesystem-backed directory in that case, for example `TMPDIR=/var/tmp npm run test:install`. The harness stops every managed service it starts before removing its temporary project, so a run no longer leaves a detached server writing into the directory it is deleting.
|
|
30
|
+
|
|
29
31
|
### 4. Full Verification Suite
|
|
30
32
|
Runs typecheck, unit tests, and live runtime installation tests in sequence:
|
|
31
33
|
```bash
|
|
@@ -56,6 +58,7 @@ npm run test:all
|
|
|
56
58
|
| **V2 Permission Seat Abstention** | Verifies the simulated seat denies a real finding, abstains on a decision it cannot make instead of denying, never upgrades a configured `ask`, and journals the abstention as `deferred_to_execute_before` with the preserved decision. Covers both the remote-probe deferral (`remote_state_unchecked`) and the cwd-dependent deferral (`repository_unidentified`). |
|
|
57
59
|
| **Worktree-Aware Git Verdicts** | Verifies a cwd-dependent push or PR creation abstains with `repository_unidentified` instead of being judged against the session-bound checkout, that a non-checkout finding (`cat .env`) in the same compound command is still denied, that an explicit `-C` still runs the core, that a push to `main`/`master` is denied regardless of working directory while a push to a configured `protectedBranches` destination defers, that an explicitly named protected checkout is denied, that an explicitly named repository outside the workspace stays a boundary finding, and that a journaled deferral carries its own code. Also verifies that a `GIT_DIR=` value inside a commit message is not read as a repository claim while a real assignment, including through `env`/`sudo`/`timeout` wrappers, is, that an unresolvable repository selection (`git -C $OTHER_REPO`) stays a boundary block even inside a git workspace, and that a host session move rebinds only on a genuine move rather than on every `session.updated`. Also verifies that a relative shell mutation or git write in a `workdir` outside the workspace is blocked while a read-only command there, and a mutation in a linked worktree of the same repository, are allowed. Also verifies in-command `cd` tracking: `cd <foreign> && git commit`, `cd <foreign> && echo x > f` are blocked while a `cd` there followed by a read stays allowed, a newline-separated `cd <foreign>` moves the tree of the lines that follow for a removal, a git write, and a redirect, while its read-only form stays allowed, a heredoc shell body that cds into a foreign repository is blocked for a removal and a git write, including when the body is unterminated, read by `source`, or piped into a shell or an uncommon executor such as `ash`, `busybox sh`, `make -f -`, or `xargs sh -c`, while a body piped into a known filter such as `grep` stays prose, a body reaching a shell through a later pipeline stage (`| grep x | sh`, `| cat | bash`, `| tee /dev/null | sh`), a body delivered through `|&` to a shell (`|& sh`, `|& ash`) while `|&` into a filter and `||` stay prose, is blocked, a body consumed by a program that can run a command named in its own arguments (`sed 'e'`, `sed -n '1e echo hi'`, `awk '{system($0)}'`, `sort --compress-program`) is blocked, a data heredoc quoting a blocked command shape or a bare `rm` line stays writable and a second body on the same header line stays data, a quoted `"<<"` does not mask a later interpreter payload, a tilde repository selector (`git -C ~/repo`, `git -C~/repo`, `~root/path`) expands through the shell instead of naming a literal `~` directory inside the workspace, an assignment-prefixed `eval` moves the tree of later segments while a harmless one does not, an in-command `cd` into a workspace subdirectory is judged where it lands rather than as a foreign tree, an in-command `cd` into a linked worktree is allowed, an indeterminate `cd $VAR` before a write fails closed, `env -C <foreign> git commit` is blocked, a `cd` inside a grouping subshell does not move a later segment's tree, and nested payloads are judged by their own tree (`bash -c 'cd <foreign> && git commit'` blocked, `execSync(..., {cwd: '<foreign>'})` blocked, `process.chdir('<foreign>')` before a write blocked, an unrelated `{cwd: …}` object key not treated as a working directory, `regex.exec(str, {cwd})` not treated as a spawn, a non-literal `{cwd: process.env.X}` failing closed, a payload launched from an indeterminate `cd` failing closed while its read-only form stays allowed, a doubly nested launcher re-planned to its innermost tree, a payload `git -C` into a foreign repository blocked while a linked worktree stays allowed, a spawn `cwd` after a nested call still read as the working directory, a `pushd` inside a grouping subshell not leaking into a later outer `popd`, a `pushd +N`/`-n` rotation failing closed before a mutation while its read-only form stays allowed, a `cd` inside a `then`/`do`/`case`/brace-group body moving the tree of later segments, a `cd ~user` not read as a workspace-relative path, and a `--head` token inside a quoted PR body not read as the source branch, in-workspace and linked-worktree payloads allowed). |
|
|
58
60
|
| **V2 Todo Capability** | Verifies the `todowrite` registry probe (`available` / `unavailable` / `unknown`), that an empty history gates only when planning is possible, the once-per-session fail-open warning and audit record, and `todoCapability` in `guard_status`. |
|
|
61
|
+
| **V2 Delivered Event Handlers** | Verifies the deny contract the adapter provides (a rejected `execute.before` surfaces as a tool error carrying the reason), that a tool error recorded from `execute.after` accrues failure debt and raises the circuit-breaker path while a success clears it, that `session.execution.interrupted` with reason `user` suspends continuation while a host-lifecycle reason does not, that an idle `session.status` continues the session while `busy` does not, that the deprecated `session.idle` still continues it because the published idle type is not settled, that both idle types for one transition still yield a single continuation prompt, and that a delivered `mcp.status.changed` refreshes the guarded inventory with additive-only widening. A structural meta-test scans `src/lib/v2-plugin.ts` for every `event.type === "<literal>"` comparison and asserts each literal exists in `EventManifest.ServerDefinitions`, so a handler built on a type the host never delivers fails the suite instead of shipping dead. It also asserts the scan matched a nonzero number of literals, so a broken regex cannot pass vacuously. |
|
|
59
62
|
| **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. |
|
|
60
63
|
| **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. |
|
|
61
64
|
| **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. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-workflow-guard",
|
|
3
|
-
"version": "1.19.
|
|
3
|
+
"version": "1.19.3",
|
|
4
4
|
"description": "Deterministic workflow and safety policy enforcement for OpenCode",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -50,15 +50,15 @@
|
|
|
50
50
|
"prepublishOnly": "npm run typecheck"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@opencode-ai/plugin": "1.19.
|
|
54
|
-
"@opencode/ai": "2.2.
|
|
55
|
-
"@opencode/plugin": "2.2.
|
|
56
|
-
"@opentui/solid": "0.
|
|
53
|
+
"@opencode-ai/plugin": "1.19.5",
|
|
54
|
+
"@opencode/ai": "2.2.5",
|
|
55
|
+
"@opencode/plugin": "2.2.5",
|
|
56
|
+
"@opentui/solid": "0.8.1",
|
|
57
57
|
"jsonc-parser": "3.3.1"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@changesets/cli": "3.0.3",
|
|
61
|
-
"@types/node": "26.6.
|
|
61
|
+
"@types/node": "26.6.6",
|
|
62
62
|
"typescript": "7.0.2"
|
|
63
63
|
},
|
|
64
64
|
"overrides": {
|
package/src/lib/custom-tools.ts
CHANGED
|
@@ -132,6 +132,25 @@ export function buildWorkflowGuardSystemGuidance(options: {
|
|
|
132
132
|
return sections.join("\n");
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
/** Message a tool returns when its session was interrupted mid-call. */
|
|
136
|
+
const ABORTED_MESSAGE = "[workflow-guard] Cancelled: the session was interrupted before this tool finished.";
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Stop before starting cancellable work when the session is gone.
|
|
140
|
+
*
|
|
141
|
+
* The two hosts name the abort signal differently. OpenCode 2's promise-layer
|
|
142
|
+
* `ToolContext` adds `signal`, and OpenCode 1's `ToolContext` carries `abort`,
|
|
143
|
+
* so both are read and either one cancels the call. A subprocess spawned with
|
|
144
|
+
* `spawnSync` cannot observe an abort mid-flight, so the check is placed before
|
|
145
|
+
* the work rather than during it: a call that has not started yet is cancelled,
|
|
146
|
+
* and one already running finishes and reports normally.
|
|
147
|
+
*/
|
|
148
|
+
function abortedMessage(toolContext: unknown): string | undefined {
|
|
149
|
+
const signals = toolContext as { signal?: AbortSignal; abort?: AbortSignal } | undefined;
|
|
150
|
+
const aborted = signals?.signal?.aborted || signals?.abort?.aborted;
|
|
151
|
+
return aborted ? ABORTED_MESSAGE : undefined;
|
|
152
|
+
}
|
|
153
|
+
|
|
135
154
|
export function createCustomTools(options: {
|
|
136
155
|
effectiveRoot: string;
|
|
137
156
|
projectMemoryEnabled: boolean;
|
|
@@ -168,7 +187,7 @@ export function createCustomTools(options: {
|
|
|
168
187
|
// an instance-derived root must never re-anchor another session's tool
|
|
169
188
|
// execution.
|
|
170
189
|
const resolveCallWorkspace = async (
|
|
171
|
-
toolContext: { sessionID?: string; worktree?: string; directory?: string } | undefined,
|
|
190
|
+
toolContext: { sessionID?: string; worktree?: string; directory?: string; signal?: AbortSignal } | undefined,
|
|
172
191
|
explicitDirectory?: string,
|
|
173
192
|
): Promise<string> => {
|
|
174
193
|
if (explicitDirectory) {
|
|
@@ -187,6 +206,8 @@ export function createCustomTools(options: {
|
|
|
187
206
|
description: "Restore this root session's workspace to its pre-run recovery checkpoint. Refuses if the run has not gone idle or if the workspace changed after that boundary.",
|
|
188
207
|
args: { run: tool.schema.number() },
|
|
189
208
|
execute: async (args, toolContext) => {
|
|
209
|
+
const cancelled = abortedMessage(toolContext);
|
|
210
|
+
if (cancelled) return cancelled;
|
|
190
211
|
if (!Number.isInteger(args.run) || args.run < 1) return "[workflow-guard] Recovery rejected: run must be a positive integer.";
|
|
191
212
|
const parent = await fetchParentSession(toolContext.sessionID);
|
|
192
213
|
if (!parent.ok) return "[workflow-guard] Recovery rejected: could not confirm this is a root session.";
|
|
@@ -531,6 +552,8 @@ export function createCustomTools(options: {
|
|
|
531
552
|
directory: tool.schema.string().optional().describe("Target repository directory (defaults to active session directory or workspace root)"),
|
|
532
553
|
},
|
|
533
554
|
execute: async (args, toolContext) => {
|
|
555
|
+
const cancelled = abortedMessage(toolContext);
|
|
556
|
+
if (cancelled) return cancelled;
|
|
534
557
|
const sanitizedBase = typeof args.base === "string" && !args.base.startsWith("-") && !/[\s;'"\0]/.test(args.base) ? args.base : undefined;
|
|
535
558
|
const bases = sanitizedBase ? [sanitizedBase] : ["origin/main", "origin/master", "main", "master"];
|
|
536
559
|
const rubricWorkspace = await resolveCallWorkspace(toolContext, args?.directory);
|
|
@@ -545,6 +568,8 @@ export function createCustomTools(options: {
|
|
|
545
568
|
guard_worktree_create: tool({
|
|
546
569
|
description: "Create an isolated git worktree directory for concurrent subagent execution. Proactively call when launching parallel tasks/subagents to prevent file collision and maintain branch isolation.", args: { branch: tool.schema.string().describe("Branch name for the isolated worktree (e.g. 'feat/subagent-task')"), baseBranch: tool.schema.string().optional().describe("Base branch to branch off of (defaults to HEAD)") },
|
|
547
570
|
execute: async (args, toolContext) => {
|
|
571
|
+
const cancelled = abortedMessage(toolContext);
|
|
572
|
+
if (cancelled) return cancelled;
|
|
548
573
|
const todos = await effectiveTodos(toolContext.sessionID); if (todos !== undefined && !hasActiveTodo(todos)) return "[workflow-guard] Blocked: worktree creation with no active todo item. Break the request down with todowrite first, then create worktrees.";
|
|
549
574
|
const toolRoot = await resolveCallWorkspace(toolContext);
|
|
550
575
|
// Host first: it honors the operator's configured worktree directory
|
|
@@ -586,6 +611,8 @@ export function createCustomTools(options: {
|
|
|
586
611
|
guard_worktree_cleanup: tool({
|
|
587
612
|
description: "Commit a final snapshot and remove an isolated git worktree directory. Call to clean up worktrees created with guard_worktree_create after subagent tasks complete.", args: { worktreePath: tool.schema.string().describe("Path of the worktree directory to clean up") },
|
|
588
613
|
execute: async (args, toolContext) => {
|
|
614
|
+
const cancelled = abortedMessage(toolContext);
|
|
615
|
+
if (cancelled) return cancelled;
|
|
589
616
|
const todos = await effectiveTodos(toolContext.sessionID); if (todos !== undefined && !hasActiveTodo(todos)) return "[workflow-guard] Blocked: worktree cleanup with no active todo item. Break the request down with todowrite first, then clean up worktrees.";
|
|
590
617
|
const toolRoot = await resolveCallWorkspace(toolContext);
|
|
591
618
|
// Removal never delegates to the host: its `remove` takes a `force`
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared guard entry surface, host-agnostic.
|
|
3
|
+
*
|
|
4
|
+
* These three helpers used to live in `workflow-guard.ts`, the V1 entrypoint.
|
|
5
|
+
* `lib/v2-plugin.ts` imported them from there, which created an import cycle:
|
|
6
|
+
* `workflow-guard.ts` imports `WorkflowGuardV2` from `lib/v2-plugin.ts`, so the
|
|
7
|
+
* cycle dragged the whole V1 file, `@opencode-ai/plugin`, and its
|
|
8
|
+
* `@opencode-ai/sdk` subtree into a V2 host.
|
|
9
|
+
*
|
|
10
|
+
* They live here so both entrypoints import a leaf module instead. This is a
|
|
11
|
+
* pure move: behavior, audit fields, and return values are unchanged.
|
|
12
|
+
* `workflow-guard.ts` keeps re-exporting them, because the test harness imports
|
|
13
|
+
* that public surface.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { guardToolCallImpl } from "./guard-dispatcher.ts";
|
|
17
|
+
import { getSdkClient, runWithRuntimeState, lastMutationTimestamp, lastVerify } from "./state.ts";
|
|
18
|
+
import { logDecision } from "./audit.ts";
|
|
19
|
+
import { extractRecordTargetPath } from "./utils.ts";
|
|
20
|
+
import type { PolicyDecision } from "./types.ts";
|
|
21
|
+
import { EDIT_TOOL_NAMES } from "../policies/todo.ts";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Public guard entry point. Audits every decision (block or allow) to a
|
|
25
|
+
* durable JSONL file before returning.
|
|
26
|
+
*/
|
|
27
|
+
export async function guardToolDecision(
|
|
28
|
+
toolName: string,
|
|
29
|
+
input: unknown,
|
|
30
|
+
context?: { sessionID?: string; callID?: string; worktree?: string; directory?: string; agent?: string },
|
|
31
|
+
): Promise<PolicyDecision> {
|
|
32
|
+
const customRoot = context?.worktree || context?.directory;
|
|
33
|
+
const runImpl = () => guardToolCallImpl(toolName, input, context);
|
|
34
|
+
return customRoot
|
|
35
|
+
? await runWithRuntimeState(customRoot, getSdkClient(), runImpl)
|
|
36
|
+
: await runImpl();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Convenience wrapper: the block reason, or `undefined` when allowed. */
|
|
40
|
+
export async function guardToolCall(
|
|
41
|
+
toolName: string,
|
|
42
|
+
input: unknown,
|
|
43
|
+
context?: { sessionID?: string; callID?: string; worktree?: string; directory?: string; agent?: string },
|
|
44
|
+
): Promise<string | undefined> {
|
|
45
|
+
const decision = await guardToolDecision(toolName, input, context);
|
|
46
|
+
const allowLive = process.env.WORKFLOW_GUARD_ALLOW_LIVE === "1";
|
|
47
|
+
const isMutation = EDIT_TOOL_NAMES.has(toolName);
|
|
48
|
+
const targetPath = extractRecordTargetPath(input);
|
|
49
|
+
logDecision(toolName, input, context, decision, {
|
|
50
|
+
mutation: isMutation,
|
|
51
|
+
targetPath,
|
|
52
|
+
allowLive,
|
|
53
|
+
verification: lastVerify
|
|
54
|
+
? {
|
|
55
|
+
command: lastVerify.command,
|
|
56
|
+
passed: lastVerify.passed,
|
|
57
|
+
fresh: lastVerify.timestamp >= lastMutationTimestamp,
|
|
58
|
+
durationMs: lastVerify.durationMs,
|
|
59
|
+
}
|
|
60
|
+
: undefined,
|
|
61
|
+
});
|
|
62
|
+
return decision.status === "allowed" ? undefined : decision.message;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Build the bounded compaction context from the operational state plus the
|
|
67
|
+
* priority blocks, capping the total at `maxChars` (default 8,000).
|
|
68
|
+
*/
|
|
69
|
+
export function buildCompactionContext(operationalState: string, priorityBlocks: string[], maxChars = 8_000): string {
|
|
70
|
+
if (!Number.isFinite(maxChars) || maxChars < 0 || !Number.isInteger(maxChars)) {
|
|
71
|
+
throw new RangeError("maxChars must be a non-negative finite integer");
|
|
72
|
+
}
|
|
73
|
+
const truncate = (value: string, limit: number): string => {
|
|
74
|
+
let end = Math.min(value.length, limit);
|
|
75
|
+
if (end > 0 && end < value.length && /[\uD800-\uDBFF]/.test(value[end - 1])) end -= 1;
|
|
76
|
+
return value.slice(0, end);
|
|
77
|
+
};
|
|
78
|
+
let context = truncate(operationalState, maxChars);
|
|
79
|
+
for (const block of priorityBlocks) {
|
|
80
|
+
const remaining = maxChars - context.length - 2;
|
|
81
|
+
if (remaining <= 0) break;
|
|
82
|
+
context += `\n\n${truncate(block, remaining)}`;
|
|
83
|
+
}
|
|
84
|
+
return context;
|
|
85
|
+
}
|
|
@@ -205,8 +205,10 @@ export async function evaluatePermissionSeat(
|
|
|
205
205
|
|
|
206
206
|
// `<server>_<tool>` MCP actions: only the guarded live-system servers are
|
|
207
207
|
// mapped (GitHub/Azure DevOps), matching the execute.before MCP policy.
|
|
208
|
+
// Cache the host action's mutability to avoid recomputing it on every iteration.
|
|
209
|
+
const actionIsMutating = mcpMutationTool(event.action);
|
|
208
210
|
for (const resource of resources) {
|
|
209
|
-
if (!
|
|
211
|
+
if (!actionIsMutating && !mcpMutationTool(resource)) continue;
|
|
210
212
|
const decision = await decide(event.action, {});
|
|
211
213
|
return seatVerdict(decision, event.action) ?? { effect: "allow", mappedTool: event.action };
|
|
212
214
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single source of truth for the builtin tool-description suffixes.
|
|
3
|
+
*
|
|
4
|
+
* Both entrypoints append the same text: the V1 `tool.definition` hook in
|
|
5
|
+
* `workflow-guard.ts` and the V2 `ctx.tool.transform` enrichment in
|
|
6
|
+
* `lib/v2-plugin.ts`. Keeping one copy prevents the two hosts from drifting
|
|
7
|
+
* apart, which would make a model's expectations depend on which host it runs
|
|
8
|
+
* on.
|
|
9
|
+
*
|
|
10
|
+
* Each suffix carries a marker. The marker is the idempotence key: a
|
|
11
|
+
* description already containing it is left untouched, so a second plugin
|
|
12
|
+
* instance (or a re-applied transform) cannot append the text twice.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const TODOWRITE_MARKER = "verification evidence";
|
|
16
|
+
export const TODOWRITE_SUFFIX =
|
|
17
|
+
"\n\nWorkflow Guard lifecycle: use todowrite to plan before working - it is the only view of progress the operator has, and every file mutation is gated on it. Each call replaces the complete task list: preserve every pending/in_progress task in subsequent updates until you explicitly mark it completed or cancelled, and do not omit active tasks when adding new work. A task may be marked completed only after its own work is recorded: the guard blocks a completion that has no file mutation in that task's active window, and one mutation cannot vouch for several completions. If a task is genuinely read-only (review, investigation, reading), append the marker `[read-only]` to its text; every such use is journaled. Use `cancelled` for work that was deliberately dropped. Marking every task completed triggers the finalization gate - fresh verification evidence (test run) is required after the last mutation, and protected-branch/conflict checks apply. Proactively call guard_next_tasks when planning work to discover existing roadmap/TODOs, and guard_status to check outstanding requirements.";
|
|
18
|
+
|
|
19
|
+
export const EDIT_MARKER = "Workflow Guard requirement";
|
|
20
|
+
export const EDIT_SUFFIX =
|
|
21
|
+
"\n\nWorkflow Guard requirement: Modifications require an active task in todowrite (status pending or in_progress), a feature branch (edits on main/master are blocked), and a prior read of existing files in the current session.";
|
|
22
|
+
|
|
23
|
+
export const SUBAGENT_MARKER = "Workflow Guard subagent guidance";
|
|
24
|
+
export const SUBAGENT_SUFFIX =
|
|
25
|
+
"\n\nWorkflow Guard subagent guidance: When spawning parallel worker subagents, use guard_worktree_create to isolate file mutations in separate worktrees. When conducting code reviews before task completion or PR creation, fetch the rubric with guard_review_rubric and provide it to a reviewer subagent to evaluate and record via record_review.";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Append `suffix` unless the description already carries `marker`.
|
|
29
|
+
*
|
|
30
|
+
* Returns `undefined` when the suffix is already present, so a caller can tell
|
|
31
|
+
* "nothing to do" from "wrote an empty string".
|
|
32
|
+
*/
|
|
33
|
+
export function appendToolDescriptionSuffix(description: string, suffix: string, marker: string): string | undefined {
|
|
34
|
+
if (description.includes(marker)) return undefined;
|
|
35
|
+
return description + suffix;
|
|
36
|
+
}
|
package/src/lib/types.ts
CHANGED
|
@@ -19,8 +19,14 @@ export interface TodoSdkClient {
|
|
|
19
19
|
get?: (opts: { path: { id: string } }) => Promise<{ data?: { parentID?: unknown; title?: unknown; time?: { idle?: unknown } } }>;
|
|
20
20
|
promptAsync?: (opts: {
|
|
21
21
|
path: { id: string };
|
|
22
|
-
body: { messageID?: string; parts: Array<{ type: "text"; text: string; synthetic?: boolean }
|
|
22
|
+
body: { messageID?: string; parts: Array<{ type: "text"; text: string; synthetic?: boolean }>; delivery?: "steer" | "queue"; resume?: boolean };
|
|
23
23
|
}) => Promise<unknown>;
|
|
24
|
+
/**
|
|
25
|
+
* V2 only. The shim forwards a synthetic continuation through here, and
|
|
26
|
+
* the presence of this method is what marks a V2 client in
|
|
27
|
+
* `policies/continuation.ts` for `delivery`/`resume` support.
|
|
28
|
+
*/
|
|
29
|
+
synthetic?: (opts: { sessionID: string; text: string; delivery?: "steer" | "queue"; resume?: boolean }) => Promise<unknown>;
|
|
24
30
|
};
|
|
25
31
|
tui?: {
|
|
26
32
|
showToast?: (opts: { body: { title?: string; message: string; variant?: string } }) => Promise<unknown>;
|