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/test/test.mts CHANGED
@@ -7,6 +7,8 @@ import { DatabaseSync } from "node:sqlite";
7
7
  import type { PluginModule } from "@opencode-ai/plugin";
8
8
  import { getRalphMaxIterations, runWithRuntimeState } from "../src/lib/state.ts";
9
9
  import { isGeneratedContinuationMessage } from "../src/policies/continuation.ts";
10
+ import { clearContinuationState, continueUnfinishedSession, recordUserMessage } from "../src/policies/continuation.ts";
11
+ import { ToolInvocationLifecycle } from "../src/lib/tool-lifecycle.ts";
10
12
  import {
11
13
  guardToolCall,
12
14
  guardToolDecision,
@@ -142,6 +144,7 @@ import { prBodyIncludesChangelog } from "../src/policies/changelog.ts";
142
144
  import { terminateProcessTree } from "../src/lib/verify.ts";
143
145
  import { audit } from "../src/lib/audit.ts";
144
146
  import { evaluatePermissionSeat } from "../src/lib/permission-seat.ts";
147
+ import { createCustomTools } from "../src/lib/custom-tools.ts";
145
148
  import { isProjectMemoryFreshAsync } from "../src/lib/project-memory.ts";
146
149
  import { ToolOutcomeTracker } from "../src/lib/tool-outcomes.ts";
147
150
  import { createRecoveryCheckpoint, finalizeRecoveryCheckpoint, listRecoveryCheckpoints, restoreRecoveryCheckpoint, setCheckpointGitForTesting } from "../src/lib/checkpoint.ts";
@@ -7646,5 +7649,398 @@ rmSync(liveBase, { recursive: true, force: true });
7646
7649
 
7647
7650
  rmSync(root, { recursive: true, force: true });
7648
7651
  if (prevLive !== undefined) process.env.WORKFLOW_GUARD_ALLOW_LIVE = prevLive;
7652
+
7653
+ // ── V2 delivered event handlers ──────────────────────────────────────────────
7654
+ // `ctx.event.subscribe()` is served from EventManifest.ServerDefinitions. A type
7655
+ // present in `Definitions` but absent from that manifest is never delivered,
7656
+ // even when a plugin handles it. Three handlers were built on such types, so
7657
+ // tool-outcome telemetry, the Policy 25 research floor, the MCP inventory
7658
+ // refresh, and the command audit were all silently dead on V2. These tests pin
7659
+ // the repaired paths and add a structural guard against the recurrence.
7660
+ console.log("- V2 delivered event handlers -");
7661
+
7662
+ const v2EventModule = await import("../src/lib/v2-plugin.ts");
7663
+ const { handleV2Event } = v2EventModule;
7664
+ const { EventManifest } = await import("@opencode/schema/event-manifest");
7665
+ const serverEventTypes = new Set<string>([...EventManifest.ServerDefinitions].map((entry) => entry.type as string));
7666
+
7667
+ // E5 (structural, highest value): every literal the plugin compares against
7668
+ // `event.type` must be a type the host actually delivers. This is what would
7669
+ // have caught the three dead handlers before they shipped.
7670
+ {
7671
+ const pluginSource = readFileSync("src/lib/v2-plugin.ts", "utf8");
7672
+ const literals = [...pluginSource.matchAll(/event\??\.type\s*(?:===|!==)\s*"([^"]+)"/g)].map((match) => match[1]);
7673
+ const unique = [...new Set(literals)];
7674
+ const undelivered = unique.filter((type) => !serverEventTypes.has(type));
7675
+ check("V2 event-liveness scan finds the plugin's event comparisons", unique.length >= 5);
7676
+ check("every event.type literal in v2-plugin.ts is in EventManifest.ServerDefinitions", undelivered.length === 0);
7677
+ if (undelivered.length > 0) console.log(` undelivered literal(s): ${undelivered.join(", ")}`);
7678
+ // The three types that made A1/A3/A4 dead must not come back as literals.
7679
+ check("the replay-only tool-content type is no longer handled", !unique.includes("session.message.content.updated"));
7680
+ check("the ephemeral mcp.tools.changed type is no longer handled", !unique.includes("mcp.tools.changed"));
7681
+ check("the replay-only command.executed type is no longer handled", !unique.includes("command.executed"));
7682
+ }
7683
+
7684
+ // E1: the deny contract. `execute.before` may reject, and that rejection is what
7685
+ // fails the call with the guard's reason. Source-only fact: the adapter wraps
7686
+ // only that hook in `Effect.tryPromise`. A real V2 instance is driven so the
7687
+ // assertion covers the shipped registration, not a re-creation of it.
7688
+ {
7689
+ resetPluginInstancesForTesting();
7690
+ resetToolCallClaimsForTesting();
7691
+ const denyRoot = mkdtempSync(join(tmpdir(), "wg-v2-deny-"));
7692
+ const v2Deny = makeV2Context(denyRoot);
7693
+ await (defaultExport.setup as any)(v2Deny.ctx);
7694
+ const beforeHook = v2Deny.state.beforeHooks[0];
7695
+ check("V2 registers exactly one execute.before hook", v2Deny.state.beforeHooks.length === 1);
7696
+ let rejected: unknown;
7697
+ let allowedReason: unknown = "sentinel";
7698
+ try {
7699
+ await beforeHook({ tool: "write", sessionID: "s-v2-deny", id: "call-deny", agent: "build", messageID: "m1", input: { filePath: join(denyRoot, "..", "escape.txt"), content: "x" } });
7700
+ } catch (error) {
7701
+ rejected = error;
7702
+ }
7703
+ check("a blocked execute.before rejects the call", rejected instanceof Error);
7704
+ check("the rejection carries the workflow-guard reason prefix", rejected instanceof Error && rejected.message.includes("[workflow-guard]"));
7705
+ check("the rejection carries an actionable policy reason", rejected instanceof Error && rejected.message.length > "[workflow-guard] ".length + 10);
7706
+ // A permitted call must stay silent: the hook resolves without throwing.
7707
+ try {
7708
+ allowedReason = await beforeHook({ tool: "read", sessionID: "s-v2-deny", id: "call-allow", agent: "build", messageID: "m2", input: { filePath: join(denyRoot, "ok.txt") } });
7709
+ } catch (error) {
7710
+ allowedReason = error;
7711
+ }
7712
+ check("a permitted execute.before resolves without throwing", !(allowedReason instanceof Error));
7713
+ rmSync(denyRoot, { recursive: true, force: true });
7714
+ }
7715
+
7716
+ // E2: tool-outcome telemetry (A1). The old subscription keyed on a replay-only
7717
+ // event, so nothing ever reached the tracker and the circuit breaker could not
7718
+ // fire. Recording now happens in `execute.after`, which does fire for a failed
7719
+ // call, so an error accrues failure debt and a success clears it.
7720
+ {
7721
+ resetPluginInstancesForTesting();
7722
+ resetToolCallClaimsForTesting();
7723
+ const outcomeRoot = mkdtempSync(join(tmpdir(), "wg-v2-outcome-"));
7724
+ const v2Outcome = makeV2Context(outcomeRoot);
7725
+ await (defaultExport.setup as any)(v2Outcome.ctx);
7726
+ const beforeHook = v2Outcome.state.beforeHooks[0];
7727
+ const afterHook = v2Outcome.state.afterHooks[0];
7728
+ const breaker = (error: unknown) => error instanceof Error && error.message.includes("[Workflow Guard Circuit Breaker");
7729
+ // One error is not enough: the suffix starts at a count of 2.
7730
+ await afterHook({ tool: "write", sessionID: "s-v2-outcome", id: "call-a", agent: "build", messageID: "m1", input: {}, status: "error", error: new Error("boom") });
7731
+ let firstError: unknown;
7732
+ try {
7733
+ await beforeHook({ tool: "write", sessionID: "s-v2-outcome", id: "call-b", agent: "build", messageID: "m2", input: { filePath: join(outcomeRoot, "..", "escape.txt"), content: "x" } });
7734
+ } catch (error) {
7735
+ firstError = error;
7736
+ }
7737
+ check("one failure stays below the circuit-breaker threshold", !breaker(firstError));
7738
+ // A second equivalent error crosses the threshold.
7739
+ await afterHook({ tool: "write", sessionID: "s-v2-outcome", id: "call-c", agent: "build", messageID: "m3", input: {}, status: "error", error: new Error("boom") });
7740
+ let secondError: unknown;
7741
+ try {
7742
+ await beforeHook({ tool: "write", sessionID: "s-v2-outcome", id: "call-d", agent: "build", messageID: "m4", input: { filePath: join(outcomeRoot, "..", "escape.txt"), content: "x" } });
7743
+ } catch (error) {
7744
+ secondError = error;
7745
+ }
7746
+ check("two equivalent tool errors raise the circuit-breaker path", breaker(secondError));
7747
+ // A completed call clears the debt, so the suffix disappears again.
7748
+ await afterHook({ tool: "write", sessionID: "s-v2-outcome", id: "call-e", agent: "build", messageID: "m5", input: {}, status: "completed", result: { content: "ok" } });
7749
+ let clearedError: unknown;
7750
+ try {
7751
+ await beforeHook({ tool: "write", sessionID: "s-v2-outcome", id: "call-f", agent: "build", messageID: "m6", input: { filePath: join(outcomeRoot, "..", "escape.txt"), content: "x" } });
7752
+ } catch (error) {
7753
+ clearedError = error;
7754
+ }
7755
+ check("the circuit-breaker suffix is gone after a success", !breaker(clearedError));
7756
+ check("the failure outcome is journaled for diagnosis", getRecentAuditEntries(50).some((entry) => entry.sessionID === "s-v2-outcome" && entry.phase === "outcome" && entry.reason === "error"));
7757
+ // Read the counter directly, so the debt assertions cannot pass on a call
7758
+ // that throws for an unrelated reason. Two errors accrued, one completion
7759
+ // cleared them; the audit rows are the durable witness for the same state.
7760
+ const outcomeAudit = getRecentAuditEntries(50).filter((entry) => entry.sessionID === "s-v2-outcome" && entry.phase === "outcome");
7761
+ check("two failures and one completion are each journaled", outcomeAudit.filter((entry) => entry.reason === "error").length === 2 && outcomeAudit.some((entry) => entry.reason === "completed"));
7762
+ // A partial event with no terminal status takes the fallback path. That path
7763
+ // must still journal its outcome row, which is the coverage the move onto
7764
+ // `execute.after` nearly dropped.
7765
+ await afterHook({ tool: "write", sessionID: "s-v2-outcome", id: "call-g", agent: "build", messageID: "m7", input: {}, result: { content: "ok" } });
7766
+ check("a status-less after event still journals an outcome row", getRecentAuditEntries(50).some((entry) => entry.sessionID === "s-v2-outcome" && entry.callID === "call-g" && entry.phase === "outcome"));
7767
+ rmSync(outcomeRoot, { recursive: true, force: true });
7768
+ }
7769
+
7770
+ // E3: a user interrupt suspends continuation on V2 (A2). Only reason `user` is
7771
+ // user intent; the other three are host-lifecycle events and must not stop the
7772
+ // session's own unfinished work from continuing.
7773
+ {
7774
+ const makeState = (root: string, client: unknown) => ({
7775
+ effectiveRoot: root,
7776
+ client,
7777
+ toolLifecycle: new ToolInvocationLifecycle(),
7778
+ toolOutcomes: new ToolOutcomeTracker(),
7779
+ });
7780
+ const interrupts = [
7781
+ { reason: "user", suspends: true },
7782
+ { reason: "shutdown", suspends: false },
7783
+ { reason: "superseded", suspends: false },
7784
+ { reason: "inactivity", suspends: false },
7785
+ ];
7786
+ for (const { reason, suspends } of interrupts) {
7787
+ const sessionID = `s-v2-int-${reason}`;
7788
+ todo(sessionID, item("unfinished work", "pending"));
7789
+ // A continuation can only be observed if the client can actually prompt,
7790
+ // and continuation state is keyed on the client object, so each case
7791
+ // gets its own client and asserts on the delivered prompt rather than on
7792
+ // a false-negative return value.
7793
+ const prompted: string[] = [];
7794
+ const continuationClient = {
7795
+ session: {
7796
+ todo: async ({ path }: { path: { id: string } }) => ({ data: fakeTodos.get(path.id) ?? [] }),
7797
+ get: async ({ path }: { path: { id: string } }) => ({ data: { id: path.id, parentID: fakeParents.get(path.id) } }),
7798
+ promptAsync: async ({ path }: { path: { id: string } }) => { prompted.push(path.id); },
7799
+ },
7800
+ };
7801
+ await handleV2Event({ type: "session.execution.interrupted", data: { sessionID, reason } }, makeState(root, continuationClient) as any);
7802
+ const continued = await runWithRuntimeState(root, continuationClient, () => continueUnfinishedSession(sessionID));
7803
+ check(`session.execution.interrupted reason "${reason}" ${suspends ? "suspends" : "does not suspend"} continuation`, continued === !suspends && prompted.length === (suspends ? 0 : 1));
7804
+ await runWithRuntimeState(root, continuationClient, () => clearContinuationState(sessionID));
7805
+ }
7806
+ // A genuine user message re-enables a suspended session, proven by an
7807
+ // actual continuation prompt: suspension must block it, user input must not.
7808
+ const resumedSession = "s-v2-int-resume";
7809
+ todo(resumedSession, item("unfinished work", "pending"));
7810
+ const resumedPrompts: string[] = [];
7811
+ const resumeClient = {
7812
+ session: {
7813
+ todo: async ({ path }: { path: { id: string } }) => ({ data: fakeTodos.get(path.id) ?? [] }),
7814
+ get: async ({ path }: { path: { id: string } }) => ({ data: { id: path.id, parentID: fakeParents.get(path.id) } }),
7815
+ promptAsync: async ({ path }: { path: { id: string } }) => { resumedPrompts.push(path.id); },
7816
+ },
7817
+ };
7818
+ await handleV2Event({ type: "session.execution.interrupted", data: { sessionID: resumedSession, reason: "user" } }, makeState(root, resumeClient) as any);
7819
+ const suspendedResult = await runWithRuntimeState(root, resumeClient, () => continueUnfinishedSession(resumedSession));
7820
+ check("a suspended session sends no continuation prompt", suspendedResult === false && resumedPrompts.length === 0);
7821
+ // Continuation state is keyed on the client object, so the user-message
7822
+ // record must run against the same client the session was suspended under.
7823
+ await runWithRuntimeState(root, resumeClient, () => recordUserMessage(resumedSession));
7824
+ const afterUserInput = await runWithRuntimeState(root, resumeClient, () => continueUnfinishedSession(resumedSession));
7825
+ check("genuine user input re-enables a suspended continuation", afterUserInput === true && resumedPrompts.length === 1);
7826
+ await runWithRuntimeState(root, resumeClient, () => clearContinuationState(resumedSession));
7827
+ }
7828
+
7829
+ // E4: the MCP inventory refresh keys on a delivered event (A3), and widening is
7830
+ // additive only. A guarded server that connects mid-session must be guarded
7831
+ // without waiting for the next session, and a quieter roster must never unguard
7832
+ // a token that a static rule already covers.
7833
+ {
7834
+ const refreshCalls: string[] = [];
7835
+ const state = {
7836
+ effectiveRoot: root,
7837
+ client: fakeClient,
7838
+ toolLifecycle: new ToolInvocationLifecycle(),
7839
+ toolOutcomes: new ToolOutcomeTracker(),
7840
+ refreshMcpInventory: async () => { refreshCalls.push("refresh"); },
7841
+ };
7842
+ await handleV2Event({ type: "mcp.status.changed", data: { server: "github-enterprise" } }, state as any);
7843
+ check("a delivered mcp.status.changed triggers the inventory refresh", refreshCalls.length === 1);
7844
+ await handleV2Event({ type: "mcp.tools.changed", data: { server: "github-enterprise" } }, state as any);
7845
+ check("the undelivered mcp.tools.changed no longer triggers anything", refreshCalls.length === 1);
7846
+ // Widening is additive: a later roster without the server cannot remove it.
7847
+ resetGuardedMcpTokensForTesting();
7848
+ const added = recordHostMcpServers(["github-enterprise"]);
7849
+ const widened = [...guardedMcpServers()];
7850
+ check("a host-declared guarded server widens the token set", added.length > 0 && widened.some((token) => added.includes(token)));
7851
+ recordHostMcpServers([]);
7852
+ check("an emptied roster never narrows the guarded token set", [...guardedMcpServers()].length >= widened.length);
7853
+ resetGuardedMcpTokensForTesting();
7854
+ }
7855
+
7856
+ // E6: the idle trigger. The host keeps two event types for it and neither is
7857
+ // established as the one the server publishes: `session.status` with
7858
+ // `status.type === "idle"`, and the deprecated `session.idle`. Handling only
7859
+ // one silently disables automatic continuation if the other is what arrives.
7860
+ // The assertions are delivered continuation prompts, not return values.
7861
+ {
7862
+ const makeIdleState = (client: unknown) => ({
7863
+ effectiveRoot: root,
7864
+ client,
7865
+ toolLifecycle: new ToolInvocationLifecycle(),
7866
+ toolOutcomes: new ToolOutcomeTracker(),
7867
+ });
7868
+ const idleSession = "s-v2-idle-status";
7869
+ todo(idleSession, item("unfinished work", "pending"));
7870
+ const idlePrompts: string[] = [];
7871
+ const idleClient = {
7872
+ session: {
7873
+ todo: async ({ path }: { path: { id: string } }) => ({ data: fakeTodos.get(path.id) ?? [] }),
7874
+ get: async ({ path }: { path: { id: string } }) => ({ data: { id: path.id, parentID: fakeParents.get(path.id) } }),
7875
+ promptAsync: async ({ path }: { path: { id: string } }) => { idlePrompts.push(path.id); },
7876
+ },
7877
+ };
7878
+ await handleV2Event({ type: "session.status", data: { sessionID: idleSession, status: { type: "busy" } } }, makeIdleState(idleClient) as any);
7879
+ check("a busy session.status does not continue the session", idlePrompts.length === 0);
7880
+ await handleV2Event({ type: "session.status", data: { sessionID: idleSession, status: { type: "idle" } } }, makeIdleState(idleClient) as any);
7881
+ check("an idle session.status continues the session", idlePrompts.length === 1);
7882
+ // The deprecated trigger must still work: a host that emits only this one
7883
+ // would otherwise lose auto-continuation entirely.
7884
+ await handleV2Event({ type: "session.idle", data: { sessionID: idleSession } }, makeIdleState(idleClient) as any);
7885
+ check("the deprecated session.idle still continues the session", idlePrompts.length === 2);
7886
+ await runWithRuntimeState(root, idleClient, () => clearContinuationState(idleSession));
7887
+
7888
+ // A host that emits both types for one transition must produce one prompt.
7889
+ // Each event is handled on its own call, so this pins the in-flight lock
7890
+ // rather than any per-call dedupe.
7891
+ const bothSession = "s-v2-idle-both";
7892
+ todo(bothSession, item("unfinished work", "pending"));
7893
+ let bothPrompts = 0;
7894
+ let releaseBoth!: () => void;
7895
+ const bothGate = new Promise<void>((resolve) => { releaseBoth = resolve; });
7896
+ const bothClient = {
7897
+ session: {
7898
+ todo: async ({ path }: { path: { id: string } }) => ({ data: fakeTodos.get(path.id) ?? [] }),
7899
+ get: async ({ path }: { path: { id: string } }) => ({ data: { id: path.id, parentID: fakeParents.get(path.id) } }),
7900
+ promptAsync: async () => { bothPrompts++; await bothGate; },
7901
+ },
7902
+ };
7903
+ const firstTrigger = handleV2Event({ type: "session.status", data: { sessionID: bothSession, status: { type: "idle" } } }, makeIdleState(bothClient) as any);
7904
+ const secondTrigger = handleV2Event({ type: "session.idle", data: { sessionID: bothSession } }, makeIdleState(bothClient) as any);
7905
+ await new Promise((resolve) => setTimeout(resolve, 0));
7906
+ releaseBoth();
7907
+ await Promise.all([firstTrigger, secondTrigger]);
7908
+ check("both idle event types for one transition yield a single continuation prompt", bothPrompts === 1);
7909
+ await runWithRuntimeState(root, bothClient, () => clearContinuationState(bothSession));
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
+
7649
8045
  console.log(`\n${pass} passed, ${fail} failed`);
7650
8046
  process.exitCode = fail ? 1 : 0;