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.
@@ -19,20 +19,97 @@ type ContinuationState = {
19
19
  export type RalphOutcome = "running" | "completed" | "blocked" | "budget_exhausted" | "user_stopped";
20
20
  const states = new WeakMap<object, Map<string, ContinuationState>>();
21
21
 
22
+ /**
23
+ * Whether the active client is the V2 shim, which can carry `delivery` and
24
+ * `resume` on a synthetic continuation. `session.synthetic` is the
25
+ * discriminator: the V2 shim supplies it, and the V1 SDK client does not
26
+ * declare it. `session.todo` is required alongside it only because this module
27
+ * reads todos through the same surface, so a client missing it cannot be the
28
+ * V2 shim for our purposes.
29
+ */
30
+ function isV2Host(): boolean {
31
+ const session = getSdkClient()?.session as { synthetic?: unknown; todo?: unknown } | undefined;
32
+ return typeof session?.synthetic === "function" && typeof session?.todo === "function";
33
+ }
34
+
22
35
  export async function waitForSessionTitle(sessionID: string): Promise<void> {
23
36
  const session = getSdkClient()?.session;
24
37
  if (typeof session?.get !== "function") return;
25
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;
26
46
  try {
27
47
  const current = (await session.get({ path: { id: sessionID } }))?.data;
28
- 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);
29
49
  } catch {
50
+ wait.cancel();
51
+ return;
52
+ }
53
+ if (settled) {
54
+ wait.cancel();
55
+ return;
56
+ }
57
+ if (attempt + 1 >= TITLE_SETTLE_ATTEMPTS) {
58
+ wait.cancel();
30
59
  return;
31
60
  }
32
- if (attempt + 1 < TITLE_SETTLE_ATTEMPTS) await new Promise((resolve) => setTimeout(resolve, TITLE_SETTLE_MS));
61
+ await wait.promise;
33
62
  }
34
63
  }
35
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
+
36
113
  function getState(): ContinuationState | undefined {
37
114
  const client = getSdkClient();
38
115
  if (!client || (typeof client !== "object" && typeof client !== "function")) return undefined;
@@ -95,17 +172,34 @@ export async function continueUnfinishedSession(sessionID: string, settleTitle =
95
172
  : "";
96
173
 
97
174
  try {
98
- await session.promptAsync({
99
- path: { id: sessionID },
100
- body: {
101
- messageID,
102
- parts: [{
103
- type: "text",
104
- text: `Workflow Guard: unfinished todos remain. Continue working through them.${tasksSummary}\nIf you need user input, use the question tool instead of ending the run. Check guard_status for outstanding verification/review requirements, and guard_review_rubric before final completion.`,
105
- synthetic: true,
106
- }],
107
- },
108
- });
175
+ // Delivery and resume are stated explicitly so a V2 synthetic
176
+ // continuation does not depend on host defaults. `queue` keeps it in
177
+ // the session's inbox instead of steering an in-flight turn, and
178
+ // `resume: true` starts a run when the session is idle.
179
+ //
180
+ // The fields are V2-only. The V1 SDK body type declares neither
181
+ // (`SessionPromptAsyncData` in @opencode-ai/sdk), so adding them
182
+ // there would send unmodelled fields to a strict server. The V2
183
+ // client shim reads them off this same object, so the values travel
184
+ // without changing the V1 request shape.
185
+ const promptBody: {
186
+ messageID: string;
187
+ parts: Array<{ type: "text"; text: string; synthetic?: boolean }>;
188
+ delivery?: "steer" | "queue";
189
+ resume?: boolean;
190
+ } = {
191
+ messageID,
192
+ parts: [{
193
+ type: "text" as const,
194
+ text: `Workflow Guard: unfinished todos remain. Continue working through them.${tasksSummary}\nIf you need user input, use the question tool instead of ending the run. Check guard_status for outstanding verification/review requirements, and guard_review_rubric before final completion.`,
195
+ synthetic: true,
196
+ }],
197
+ };
198
+ if (isV2Host()) {
199
+ promptBody.delivery = "queue";
200
+ promptBody.resume = true;
201
+ }
202
+ await session.promptAsync({ path: { id: sessionID }, body: promptBody });
109
203
  return true;
110
204
  } catch {
111
205
  state.counts.set(sessionID, count);
@@ -22,10 +22,10 @@ import { expandShellTargetPath, isPathOutsideWorkspace, OPENCODE_SCRATCH_DIR, re
22
22
  import { beginReadObservation, clearReadFingerprints, recordMutationObservation, recordSuccessfulRead, staleWriteReason } from "./policies/stale-write.ts";
23
23
  import { ToolInvocationLifecycle } from "./lib/tool-lifecycle.ts";
24
24
  import { ToolOutcomeTracker, type ToolOutcomePart } from "./lib/tool-outcomes.ts";
25
- import { guardToolCallImpl, isMutatingSurfaceTool, isReadOnlyRole, SHELL_TOOL_NAMES } from "./lib/guard-dispatcher.ts";
25
+ import { isMutatingSurfaceTool, isReadOnlyRole, SHELL_TOOL_NAMES } from "./lib/guard-dispatcher.ts";
26
26
  import { createCustomTools, buildWorkflowGuardSystemGuidance } from "./lib/custom-tools.ts";
27
27
  import { evaluateDogfoodGate } from "./lib/dogfood.ts";
28
- import type { PolicyDecision, TodoSdkClient } from "./lib/types.ts";
28
+ import type { TodoSdkClient } from "./lib/types.ts";
29
29
  export { isReadOnlyRole } from "./lib/guard-dispatcher.ts";
30
30
  export { extractReviewFollowups, buildWorkflowGuardSystemGuidance } from "./lib/custom-tools.ts";
31
31
  export { evaluateDogfoodGate } from "./lib/dogfood.ts";
@@ -59,7 +59,6 @@ import {
59
59
  setSdkClient,
60
60
  getSdkClient,
61
61
  runWithRuntimeState,
62
- lastMutationTimestamp,
63
62
  getLastMutationTimestamp,
64
63
  getMutationCount,
65
64
  getSessionMutationCount,
@@ -163,7 +162,6 @@ export {
163
162
  // ── Shared shell/env utilities ───────────────────────────────────────────────
164
163
  import {
165
164
  asRecord,
166
- extractRecordTargetPath,
167
165
  getCleanEnv,
168
166
  showBlockToast,
169
167
  isSensitiveEnvKey,
@@ -212,13 +210,19 @@ import {
212
210
  persistReviewCache,
213
211
  loadReviewCache,
214
212
  audit,
215
- logDecision,
216
213
  summarizeInput,
217
214
  } from "./lib/audit.ts";
218
215
 
219
216
  export { getAuditFilePath, getVerifyCacheFilePath, getReviewCacheFilePath, getDogfoodCacheFilePath, getVerifyHistoryFilePath, persistVerifyCache, loadVerifyCache, persistReviewCache, loadReviewCache, persistDogfoodCache, loadDogfoodCache, getRecentAuditEntries, getRecentVerifyHistory } from "./lib/audit.ts";
220
217
  export { summarizeInput };
221
218
 
219
+ // The guard entry surface lives in a leaf module so the V2 entrypoint can
220
+ // import it without pulling in this V1 file (and its SDK subtree) through a
221
+ // cycle. Re-exported here because the test harness imports this public surface.
222
+ export { guardToolCall, guardToolDecision, buildCompactionContext } from "./lib/guard-api.ts";
223
+ import { guardToolCall, buildCompactionContext } from "./lib/guard-api.ts";
224
+ import { TODOWRITE_SUFFIX, TODOWRITE_MARKER, EDIT_SUFFIX, EDIT_MARKER, SUBAGENT_SUFFIX, SUBAGENT_MARKER, appendToolDescriptionSuffix } from "./lib/tool-descriptions.ts";
225
+
222
226
  export function managedConfigDiagnostic(platform = process.platform, env: NodeJS.ProcessEnv = process.env): string {
223
227
  const directory = platform === "darwin"
224
228
  ? "/Library/Application Support/opencode"
@@ -398,69 +402,10 @@ function logWarn(client: unknown, message: string): void {
398
402
  } catch {}
399
403
  }
400
404
 
401
- /**
402
- * Public guard entry point. Audits every decision (block or allow) to a
403
- * durable JSONL file before returning.
404
- */
405
- export async function guardToolDecision(
406
- toolName: string,
407
- input: unknown,
408
- context?: { sessionID?: string; callID?: string; worktree?: string; directory?: string; agent?: string },
409
- ): Promise<PolicyDecision> {
410
- const customRoot = context?.worktree || context?.directory;
411
- const runImpl = () => guardToolCallImpl(toolName, input, context);
412
- return customRoot
413
- ? await runWithRuntimeState(customRoot, getSdkClient(), runImpl)
414
- : await runImpl();
415
- }
416
-
417
- export async function guardToolCall(
418
- toolName: string,
419
- input: unknown,
420
- context?: { sessionID?: string; callID?: string; worktree?: string; directory?: string; agent?: string },
421
- ): Promise<string | undefined> {
422
- const decision = await guardToolDecision(toolName, input, context);
423
- const allowLive = process.env.WORKFLOW_GUARD_ALLOW_LIVE === "1";
424
- const isMutation = EDIT_TOOL_NAMES.has(toolName);
425
- const targetPath = extractRecordTargetPath(input);
426
- logDecision(toolName, input, context, decision, {
427
- mutation: isMutation,
428
- targetPath,
429
- allowLive,
430
- verification: lastVerify
431
- ? {
432
- command: lastVerify.command,
433
- passed: lastVerify.passed,
434
- fresh: lastVerify.timestamp >= lastMutationTimestamp,
435
- durationMs: lastVerify.durationMs,
436
- }
437
- : undefined,
438
- });
439
- return decision.status === "allowed" ? undefined : decision.message;
440
- }
441
-
442
405
  async function emitBlockFeedback(message: string): Promise<void> {
443
406
  await showBlockToast(message);
444
407
  }
445
408
 
446
- export function buildCompactionContext(operationalState: string, priorityBlocks: string[], maxChars = 8_000): string {
447
- if (!Number.isFinite(maxChars) || maxChars < 0 || !Number.isInteger(maxChars)) {
448
- throw new RangeError("maxChars must be a non-negative finite integer");
449
- }
450
- const truncate = (value: string, limit: number): string => {
451
- let end = Math.min(value.length, limit);
452
- if (end > 0 && end < value.length && /[\uD800-\uDBFF]/.test(value[end - 1])) end -= 1;
453
- return value.slice(0, end);
454
- };
455
- let context = truncate(operationalState, maxChars);
456
- for (const block of priorityBlocks) {
457
- const remaining = maxChars - context.length - 2;
458
- if (remaining <= 0) break;
459
- context += `\n\n${truncate(block, remaining)}`;
460
- }
461
- return context;
462
- }
463
-
464
409
  export const WorkflowGuard: V1Plugin = async (ctx: Parameters<V1Plugin>[0]) => {
465
410
  // Honor worktree if present (e.g. opencode worktrees or devcontainers)
466
411
  // so worktree plugins cannot punch through boundary gates. When the host
@@ -839,28 +784,21 @@ export const WorkflowGuard: V1Plugin = async (ctx: Parameters<V1Plugin>[0]) => {
839
784
  // Similarly, mutating tools reflect their active-todo, feature-branch, and prior-read requirements.
840
785
  // Subagent orchestration tools reflect worktree isolation and review expectations.
841
786
  "tool.definition": async (input, output) => {
842
- if (input.toolID === "todowrite") {
787
+ const append = (suffix: string, marker: string) => {
843
788
  const description = typeof output.description === "string" ? output.description : "";
844
- if (description.includes("verification evidence")) return;
845
- output.description =
846
- description +
847
- "\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.";
789
+ const next = appendToolDescriptionSuffix(description, suffix, marker);
790
+ if (next !== undefined) output.description = next;
791
+ };
792
+ if (input.toolID === "todowrite") {
793
+ append(TODOWRITE_SUFFIX, TODOWRITE_MARKER);
848
794
  return;
849
795
  }
850
796
  if (EDIT_TOOL_NAMES.has(input.toolID)) {
851
- const description = typeof output.description === "string" ? output.description : "";
852
- if (description.includes("Workflow Guard requirement")) return;
853
- output.description =
854
- description +
855
- "\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.";
797
+ append(EDIT_SUFFIX, EDIT_MARKER);
856
798
  return;
857
799
  }
858
800
  if (input.toolID === "task") {
859
- const description = typeof output.description === "string" ? output.description : "";
860
- if (description.includes("Workflow Guard subagent guidance")) return;
861
- output.description =
862
- description +
863
- "\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.";
801
+ append(SUBAGENT_SUFFIX, SUBAGENT_MARKER);
864
802
  return;
865
803
  }
866
804
  },
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);