opencode-workflow-guard 1.19.2 → 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 CHANGED
@@ -4,7 +4,7 @@
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 test suite enforces this structurally: a scan of `src/lib/v2-plugin.ts` asserts every compared literal is delivered.
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
8
 
9
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.
10
10
 
@@ -113,7 +113,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
113
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.
114
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.
115
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. Set `titleSettleWorkaround: false` to opt out. The bounded wait never rewrites titles or provider and model parameters.
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.
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.
@@ -256,6 +256,7 @@ Besides enforcement hooks, the guard registers companion tools in OpenCode:
256
256
 
257
257
  ### Hook-Context Safety
258
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.
259
260
 
260
261
  ### Inspection Tools
261
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-workflow-guard",
3
- "version": "1.19.2",
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.4",
54
- "@opencode/ai": "2.2.0",
55
- "@opencode/plugin": "2.2.0",
56
- "@opentui/solid": "0.7.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.5",
61
+ "@types/node": "26.6.6",
62
62
  "typescript": "7.0.2"
63
63
  },
64
64
  "overrides": {
@@ -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`
@@ -74,7 +74,7 @@ import { expandShellTargetPath, isPathOutsideWorkspace, OPENCODE_SCRATCH_DIR, re
74
74
  import { audit, summarizeInput } from "./audit.ts";
75
75
  import { asRecord, isSensitiveEnvKey } from "./utils.ts";
76
76
  import { loadedPluginVersion } from "./version.ts";
77
- import { clearContinuationState, continueUnfinishedSession, isGeneratedContinuationMessage, markInterrupted, recordUserMessage } from "../policies/continuation.ts";
77
+ import { clearContinuationState, continueUnfinishedSession, isGeneratedContinuationMessage, markInterrupted, notifySessionRenamed, recordUserMessage } from "../policies/continuation.ts";
78
78
  import { createRecoveryCheckpoint, finalizeRecoveryCheckpoint, nextRecoveryRun } from "./checkpoint.ts";
79
79
  import { buildCompactionContext, guardToolCall } from "./guard-api.ts";
80
80
  import { evaluateDogfoodGate } from "./dogfood.ts";
@@ -258,15 +258,20 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
258
258
  // definition.args is a V1 zod raw shape (plain object of zod fields);
259
259
  // wrap it so the V2 registry receives a real StandardSchemaV1.
260
260
  input: z.object(definition.args as unknown as z.ZodRawShape),
261
- execute: async (rawInput: unknown, toolContext: { sessionID: string; id: string }) => {
261
+ execute: async (rawInput: unknown, toolContext: { sessionID: string; id: string; signal?: AbortSignal }) => {
262
262
  // Only a session-bound workspace counts as the tool's own
263
263
  // context; an unbound entry is a plugin-instance bootstrap
264
264
  // and must not be presented to the tools as one.
265
265
  const boundWorktree = getSessionBoundWorkspace(toolContext.sessionID);
266
+ // `signal` aborts when the session is interrupted. Guard tools
267
+ // pass it to cancellable work so an interrupt stops them
268
+ // instead of waiting out their own timeouts. V1's tool
269
+ // context supplies no signal, so the checks there are no-ops.
266
270
  const result = await (definition.execute as (input: unknown, context: unknown) => Promise<unknown>)(rawInput, {
267
271
  sessionID: toolContext.sessionID,
268
272
  ...(boundWorktree ? { worktree: boundWorktree } : {}),
269
273
  directory: boundWorktree ?? effectiveRoot,
274
+ ...(toolContext.signal ? { signal: toolContext.signal } : {}),
270
275
  });
271
276
  const text = typeof result === "string" ? result : (result as { output?: string } | undefined)?.output;
272
277
  return {
@@ -710,10 +715,14 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
710
715
  } catch {}
711
716
 
712
717
  // ── Event stream ──
718
+ // `types` is a host-side filter, so unrelated events never cross the stream
719
+ // or reach the handler. It must list every literal `handleV2Event` acts on:
720
+ // the test suite asserts this set matches the handler's comparisons, because
721
+ // a missing type silently disables its feature instead of failing loudly.
713
722
  const controller = new AbortController();
714
723
  void (async () => {
715
724
  try {
716
- for await (const raw of ctx.event.subscribe({ signal: controller.signal })) {
725
+ for await (const raw of ctx.event.subscribe({ types: V2_EVENT_TYPES, signal: controller.signal })) {
717
726
  const event = raw as { type?: string; data?: unknown };
718
727
  try {
719
728
  await handleV2Event(event, {
@@ -831,6 +840,30 @@ function recordV2ToolOutcome(
831
840
 
832
841
  // ── Event handling ────────────────────────────────────────────────────────────
833
842
 
843
+ /**
844
+ * Every event type `handleV2Event` acts on.
845
+ *
846
+ * The subscription passes this as the host-side `types` filter. Each entry is a
847
+ * literal the handler compares against, so the two lists must stay identical: a
848
+ * type missing here is never delivered, and its feature becomes dead code that
849
+ * still type-checks. The suite asserts the match in both directions.
850
+ *
851
+ * Both idle triggers are listed because which one the host publishes is not
852
+ * settled, and `session.idle` is deprecated but still delivered.
853
+ */
854
+ export const V2_EVENT_TYPES = [
855
+ "mcp.status.changed",
856
+ "session.text.ended",
857
+ "session.moved",
858
+ "session.renamed",
859
+ "session.execution.interrupted",
860
+ "session.status",
861
+ "session.idle",
862
+ "session.deleted",
863
+ "permission.asked",
864
+ "permission.replied",
865
+ ] as const;
866
+
834
867
  export interface V2EventState {
835
868
  effectiveRoot: string;
836
869
  client: unknown;
@@ -892,6 +925,14 @@ export async function handleV2Event(
892
925
  return;
893
926
  }
894
927
 
928
+ if (event.type === "session.renamed") {
929
+ // The async title write landed. A pending continuation waits on this
930
+ // instead of polling for the full settle interval.
931
+ const data = event.data as { sessionID?: unknown } | undefined;
932
+ if (typeof data?.sessionID === "string") notifySessionRenamed(data.sessionID);
933
+ return;
934
+ }
935
+
895
936
  if (event.type === "session.moved") {
896
937
  // `session_move` relocates a session between checkouts, and the host
897
938
  // announces it. On the pinned 2.2.0 SDK the V2 union carries
@@ -36,16 +36,80 @@ export async function waitForSessionTitle(sessionID: string): Promise<void> {
36
36
  const session = getSdkClient()?.session;
37
37
  if (typeof session?.get !== "function") return;
38
38
  for (let attempt = 0; attempt < TITLE_SETTLE_ATTEMPTS; attempt++) {
39
+ // Register the wake-up BEFORE reading, then release it once the read is
40
+ // done. A rename that commits during the read is therefore still
41
+ // observed: registering afterwards would let it land in the gap between
42
+ // the read and the registration, which reads as "not yet renamed" and
43
+ // costs a whole extra interval even though the title already settled.
44
+ const wait = beginRenameWait(sessionID);
45
+ let settled = false;
39
46
  try {
40
47
  const current = (await session.get({ path: { id: sessionID } }))?.data;
41
- if (current?.parentID || typeof current?.title !== "string" || !DEFAULT_SESSION_TITLE.test(current.title)) return;
48
+ settled = Boolean(current?.parentID) || typeof current?.title !== "string" || !DEFAULT_SESSION_TITLE.test(current.title);
42
49
  } catch {
50
+ wait.cancel();
43
51
  return;
44
52
  }
45
- if (attempt + 1 < TITLE_SETTLE_ATTEMPTS) await new Promise((resolve) => setTimeout(resolve, TITLE_SETTLE_MS));
53
+ if (settled) {
54
+ wait.cancel();
55
+ return;
56
+ }
57
+ if (attempt + 1 >= TITLE_SETTLE_ATTEMPTS) {
58
+ wait.cancel();
59
+ return;
60
+ }
61
+ await wait.promise;
46
62
  }
47
63
  }
48
64
 
65
+ /**
66
+ * A pending wait for one session's title, resolved by `session.renamed` or by
67
+ * one poll interval elapsing.
68
+ *
69
+ * The poll exists because the host generates a title asynchronously and a
70
+ * continuation sent too early can be titled with the placeholder. `title` is a
71
+ * model-request hook, so it runs *before* the title is written and cannot
72
+ * report that the write happened. `session.renamed` is delivered when it does,
73
+ * so the normal case ends as soon as the title commits while the worst case
74
+ * stays the old interval. A host that never emits the event keeps the old
75
+ * timing exactly.
76
+ */
77
+ function beginRenameWait(sessionID: string): { promise: Promise<void>; cancel: () => void } {
78
+ const waiters = renaming.get(sessionID) ?? new Set<() => void>();
79
+ renaming.set(sessionID, waiters);
80
+ let finish!: () => void;
81
+ const promise = new Promise<void>((resolve) => {
82
+ finish = resolve;
83
+ });
84
+ let settled = false;
85
+ const done = (): void => {
86
+ if (settled) return;
87
+ settled = true;
88
+ waiters.delete(done);
89
+ if (waiters.size === 0) renaming.delete(sessionID);
90
+ clearTimeout(timer);
91
+ finish();
92
+ };
93
+ waiters.add(done);
94
+ // A plain timer, not `unref`: an unref'd timer lets the process exit while
95
+ // this promise is still pending, which would drop the wait.
96
+ const timer = setTimeout(done, TITLE_SETTLE_MS);
97
+ return { promise, cancel: done };
98
+ }
99
+
100
+ /** Named `renaming` rather than `sessions` to read as the event, not the store. */
101
+ const renaming = new Map<string, Set<() => void>>();
102
+
103
+ /**
104
+ * Wake any wait for this session's title. Called from the `session.renamed`
105
+ * subscription; a session with no waiter is a no-op.
106
+ */
107
+ export function notifySessionRenamed(sessionID: string): void {
108
+ const waiters = renaming.get(sessionID);
109
+ if (!waiters) return;
110
+ for (const waiter of [...waiters]) waiter();
111
+ }
112
+
49
113
  function getState(): ContinuationState | undefined {
50
114
  const client = getSdkClient();
51
115
  if (!client || (typeof client !== "object" && typeof client !== "function")) return undefined;
package/test/test-e2e.mts CHANGED
@@ -34,6 +34,20 @@ console.log("- OpenCode Plugin Installation & Runtime Load Test -");
34
34
  // checks run even when the optional live OpenCode binary is unavailable.
35
35
  const testDir = mkdtempSync(join(tmpdir(), "wg-install-test-"));
36
36
 
37
+ // Every isolated XDG root that a live probe may start a managed service under.
38
+ const liveServiceEnvs: NodeJS.ProcessEnv[] = [];
39
+ // `opencode debug config` auto-starts a detached `serve --service` under the
40
+ // probe's own XDG roots. Killing the probe child leaves that service running and
41
+ // writing into testDir, so a bare rmSync races it and fails with ENOTEMPTY.
42
+ // Stop each tracked service first, then retry the removal.
43
+ const cleanupTestDir = (): void => {
44
+ if (process.env.WG_E2E_KEEP) return;
45
+ for (const env of liveServiceEnvs) {
46
+ spawnSync("opencode", ["service", "stop"], { cwd: testDir, encoding: "utf8", env, timeout: 30_000 });
47
+ }
48
+ rmSync(testDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
49
+ };
50
+
37
51
  // Verify the publish artifact resolves its modular entrypoint, not only the
38
52
  // checkout/local-copy layout used by the live plugin test below.
39
53
  const packResult = spawnSync("npm", ["pack", "--pack-destination", testDir], {
@@ -143,7 +157,7 @@ check("server and TUI package specs resolve to different modules", installedPack
143
157
  const opencodeCheck = spawnSync("opencode", ["--version"], { encoding: "utf8" });
144
158
  if (opencodeCheck.status !== 0) {
145
159
  console.log("SKIP: opencode CLI is not available in PATH. Package checks passed; skipping live runtime load tests.");
146
- if (!process.env.WG_E2E_KEEP) rmSync(testDir, { recursive: true, force: true });
160
+ cleanupTestDir();
147
161
  console.log(`\n${pass} passed, ${fail} failed`);
148
162
  process.exit(fail > 0 ? 1 : 0);
149
163
  }
@@ -326,6 +340,7 @@ const runtimeEnv: NodeJS.ProcessEnv = {
326
340
  XDG_STATE_HOME: join(testDir, "runtime-state"),
327
341
  XDG_DATA_HOME: join(testDir, "runtime-data"),
328
342
  };
343
+ liveServiceEnvs.push(runtimeEnv);
329
344
  delete runtimeEnv.OPENCODE_PID;
330
345
  delete runtimeEnv.OPENCODE_PURE;
331
346
  delete runtimeEnv.OPENCODE;
@@ -482,6 +497,7 @@ if (isOpenCodeV2 && (opencodeMajor > 2 || (opencodeMajor === 2 && hostMinor >= 1
482
497
  XDG_STATE_HOME: join(testDir, "runtime-state-todo"),
483
498
  XDG_DATA_HOME: join(testDir, "runtime-data-todo"),
484
499
  };
500
+ liveServiceEnvs.push(todoEnv);
485
501
  const todoPort = 49400 + ((process.pid + 500) % 1000);
486
502
  spawnSync("opencode", ["service", "set", "port", String(todoPort)], { cwd: testDir, encoding: "utf8", env: todoEnv, timeout: 30_000 });
487
503
  try {
@@ -537,7 +553,7 @@ if (isOpenCodeV2 && (opencodeMajor > 2 || (opencodeMajor === 2 && hostMinor >= 1
537
553
 
538
554
  if (process.env.WORKFLOW_GUARD_LIVE_E2E !== "1") {
539
555
  console.log("SKIP: model-driven policy probes require WORKFLOW_GUARD_LIVE_E2E=1.");
540
- if (!process.env.WG_E2E_KEEP) rmSync(testDir, { recursive: true, force: true });
556
+ cleanupTestDir();
541
557
  console.log(`\n${pass} passed, ${fail} failed`);
542
558
  process.exit(fail > 0 ? 1 : 0);
543
559
  }
@@ -557,7 +573,7 @@ try {
557
573
  const liveModel = process.env.WORKFLOW_GUARD_LIVE_MODEL?.trim() || recentModel;
558
574
  if (!liveModel) {
559
575
  console.error(`FAIL: no recent OpenCode model found in ${recentModelPath}; select a model in OpenCode or set WORKFLOW_GUARD_LIVE_MODEL=provider/model.`);
560
- if (!process.env.WG_E2E_KEEP) rmSync(testDir, { recursive: true, force: true });
576
+ cleanupTestDir();
561
577
  process.exit(1);
562
578
  }
563
579
  console.log(` Using live model: ${liveModel}`);
@@ -608,7 +624,7 @@ if (!run3AccountedFor) {
608
624
  }
609
625
 
610
626
  // Clean up
611
- if (!process.env.WG_E2E_KEEP) rmSync(testDir, { recursive: true, force: true });
627
+ cleanupTestDir();
612
628
 
613
629
  console.log(`\n${pass} passed, ${fail} failed, ${unavailable} live unavailable`);
614
630
  process.exit(fail ? 1 : 0);
package/test/test.mts CHANGED
@@ -144,6 +144,7 @@ import { prBodyIncludesChangelog } from "../src/policies/changelog.ts";
144
144
  import { terminateProcessTree } from "../src/lib/verify.ts";
145
145
  import { audit } from "../src/lib/audit.ts";
146
146
  import { evaluatePermissionSeat } from "../src/lib/permission-seat.ts";
147
+ import { createCustomTools } from "../src/lib/custom-tools.ts";
147
148
  import { isProjectMemoryFreshAsync } from "../src/lib/project-memory.ts";
148
149
  import { ToolOutcomeTracker } from "../src/lib/tool-outcomes.ts";
149
150
  import { createRecoveryCheckpoint, finalizeRecoveryCheckpoint, listRecoveryCheckpoints, restoreRecoveryCheckpoint, setCheckpointGitForTesting } from "../src/lib/checkpoint.ts";
@@ -7908,5 +7909,138 @@ const serverEventTypes = new Set<string>([...EventManifest.ServerDefinitions].ma
7908
7909
  await runWithRuntimeState(root, bothClient, () => clearContinuationState(bothSession));
7909
7910
  }
7910
7911
 
7912
+ // E7: the subscription's `types` filter is a host-side narrowing, so a type
7913
+ // missing from the list is never delivered and its feature becomes dead code
7914
+ // that still compiles. Assert the list matches the handler's comparisons in
7915
+ // both directions, and that every entry is actually delivered.
7916
+ {
7917
+ const { V2_EVENT_TYPES } = v2EventModule;
7918
+ const pluginSource = readFileSync("src/lib/v2-plugin.ts", "utf8");
7919
+ const handled = new Set(
7920
+ [...pluginSource.matchAll(/event\??\.type\s*(?:===|!==)\s*"([^"]+)"/g)].map((match) => match[1]),
7921
+ );
7922
+ const subscribed = new Set<string>(V2_EVENT_TYPES);
7923
+ const missingFromFilter = [...handled].filter((type) => !subscribed.has(type));
7924
+ const unusedInHandler = [...subscribed].filter((type) => !handled.has(type));
7925
+ // The scan is a regex, so a refactor to `switch (event.type)` would match
7926
+ // nothing and leave both checks green while every feature went dead. Assert
7927
+ // it matched real comparisons, matching the E5 block's non-vacuity guard.
7928
+ check("the event-type scan matched real handler comparisons", handled.size >= 5);
7929
+ check("the event filter covers every type the handler acts on", missingFromFilter.length === 0);
7930
+ check("the event filter names no type the handler ignores", unusedInHandler.length === 0);
7931
+ if (missingFromFilter.length > 0) console.log(` not subscribed: ${missingFromFilter.join(", ")}`);
7932
+ if (unusedInHandler.length > 0) console.log(` subscribed but unhandled: ${unusedInHandler.join(", ")}`);
7933
+ const undeliveredFilter = [...subscribed].filter((type) => !serverEventTypes.has(type));
7934
+ check("every filtered event type is in EventManifest.ServerDefinitions", undeliveredFilter.length === 0);
7935
+ check("the event filter keeps both idle triggers", subscribed.has("session.status") && subscribed.has("session.idle"));
7936
+ }
7937
+
7938
+ // E8: an interrupted session cancels a guard tool that has not started yet.
7939
+ // The host supplies `signal` per call on V2; a tool that ignores it runs to its
7940
+ // own timeout after the user has already stopped the session.
7941
+ {
7942
+ const abortRoot = mkdtempSync(join(tmpdir(), "wg-tool-signal-"));
7943
+ mkdirSync(join(abortRoot, ".opencode"));
7944
+ const tools = createCustomTools({
7945
+ effectiveRoot: abortRoot,
7946
+ projectMemoryEnabled: false,
7947
+ learningEnabled: false,
7948
+ projectMemory: undefined,
7949
+ followupStore: undefined,
7950
+ portableMemoryPath: join(abortRoot, "memory.jsonl"),
7951
+ learningInterventions: new Map(),
7952
+ client: fakeClient,
7953
+ });
7954
+ const cancel = new AbortController();
7955
+ cancel.abort();
7956
+ const callTool = async (name: string, input: unknown, signal?: AbortSignal) => {
7957
+ const definition = (tools as Record<string, any>)[name];
7958
+ return await definition.execute(input, { sessionID: "s-abort", directory: abortRoot, ...(signal ? { signal } : {}) });
7959
+ };
7960
+ const aborted = await callTool("guard_worktree_create", { branch: "feat/never-created" }, cancel.signal);
7961
+ check("an aborted call cancels a worktree creation before it runs", String(aborted).includes("Cancelled"));
7962
+ const abortedCleanup = await callTool("guard_worktree_cleanup", { worktreePath: join(abortRoot, "nope") }, cancel.signal);
7963
+ check("an aborted call cancels a worktree cleanup before it runs", String(abortedCleanup).includes("Cancelled"));
7964
+ const abortedRubric = await callTool("guard_review_rubric", {}, cancel.signal);
7965
+ check("an aborted call cancels the diff-spawning rubric before it runs", String(abortedRubric).includes("Cancelled"));
7966
+ // A live signal must not change behavior: the guard's own gates still run.
7967
+ const live = new AbortController();
7968
+ const liveRubric = await callTool("guard_review_rubric", {}, live.signal);
7969
+ check("a live signal leaves the rubric path unchanged", !String(liveRubric).includes("Cancelled"));
7970
+ // OpenCode 1 names the same signal `abort`, so honoring only `signal` would
7971
+ // leave an interrupted V1 session running to its timeout.
7972
+ const abortedViaAbortKey = await (tools as Record<string, any>).guard_review_rubric.execute(
7973
+ {},
7974
+ { sessionID: "s-abort", directory: abortRoot, abort: cancel.signal },
7975
+ );
7976
+ check("an aborted call is cancelled through the V1 `abort` key", String(abortedViaAbortKey).includes("Cancelled"));
7977
+ // Recovery restore spawns git too, and it is only registered when the
7978
+ // project enables checkpoints, so cover it under its own config.
7979
+ writeFileSync(join(abortRoot, ".opencode", "workflow-guard.json"), JSON.stringify({ recoveryCheckpoints: true }));
7980
+ const recoveryTools = createCustomTools({
7981
+ effectiveRoot: abortRoot,
7982
+ projectMemoryEnabled: false,
7983
+ learningEnabled: false,
7984
+ projectMemory: undefined,
7985
+ followupStore: undefined,
7986
+ portableMemoryPath: join(abortRoot, "memory.jsonl"),
7987
+ learningInterventions: new Map(),
7988
+ client: fakeClient,
7989
+ });
7990
+ const abortedRecovery = await (recoveryTools as Record<string, any>).guard_recovery_restore.execute(
7991
+ { run: 1 },
7992
+ { sessionID: "s-abort", directory: abortRoot, signal: cancel.signal },
7993
+ );
7994
+ check("an aborted call cancels a recovery restore before it runs", String(abortedRecovery).includes("Cancelled"));
7995
+ rmSync(abortRoot, { recursive: true, force: true });
7996
+ }
7997
+
7998
+ // E9: the title settle wait ends as soon as the host renames the session,
7999
+ // instead of always sleeping the full poll interval. `session.renamed` is
8000
+ // delivered when the title commits; the model-request `title` hook runs before
8001
+ // the write, so it cannot report this.
8002
+ {
8003
+ const renameSession = "s-v2-rename-wake";
8004
+ todo(renameSession, item("unfinished work", "pending"));
8005
+ const racedPrompts: string[] = [];
8006
+ // The fake title reflects host state: it stays the placeholder until the
8007
+ // rename event lands, exactly as the real async title generation behaves.
8008
+ let titleSettled = false;
8009
+ let reads = 0;
8010
+ const racedClient = {
8011
+ session: {
8012
+ todo: async ({ path }: { path: { id: string } }) => ({ data: fakeTodos.get(path.id) ?? [] }),
8013
+ get: async ({ path }: { path: { id: string } }) => {
8014
+ reads++;
8015
+ const title = titleSettled ? "Native generated title" : "New session - 2026-08-27T12:00:00.000Z";
8016
+ return { data: { id: path.id, parentID: fakeParents.get(path.id), title } };
8017
+ },
8018
+ promptAsync: async ({ path }: { path: { id: string } }) => { racedPrompts.push(path.id); },
8019
+ },
8020
+ };
8021
+ const racedState = {
8022
+ effectiveRoot: root,
8023
+ client: racedClient,
8024
+ toolLifecycle: new ToolInvocationLifecycle(),
8025
+ toolOutcomes: new ToolOutcomeTracker(),
8026
+ };
8027
+ const started = Date.now();
8028
+ const continuation = handleV2Event(
8029
+ { type: "session.status", data: { sessionID: renameSession, status: { type: "idle" } } },
8030
+ racedState as any,
8031
+ );
8032
+ // The settle loop reads the session before it waits, so a read means the
8033
+ // waiter is registered. Firing the rename before that would test a gap the
8034
+ // real host cannot hit, because title generation is always slower.
8035
+ while (reads === 0) await new Promise((resolve) => setTimeout(resolve, 1));
8036
+ titleSettled = true;
8037
+ await handleV2Event({ type: "session.renamed", data: { sessionID: renameSession, title: "Native generated title" } }, racedState as any);
8038
+ await continuation;
8039
+ const elapsed = Date.now() - started;
8040
+ check("a session rename wakes the pending title settle", elapsed < 200);
8041
+ check("the woken continuation still delivers its prompt", racedPrompts.join(",") === renameSession);
8042
+ await runWithRuntimeState(root, racedClient, () => clearContinuationState(renameSession));
8043
+ }
8044
+
7911
8045
  console.log(`\n${pass} passed, ${fail} failed`);
7912
8046
  process.exitCode = fail ? 1 : 0;