opencode-workflow-guard 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,12 +8,19 @@
8
8
  * from ./lib/, and re-exports the public helper surface for tests.
9
9
  */
10
10
 
11
- import { tool, type Plugin, type PluginModule } from "@opencode-ai/plugin";
12
- import type { LearningEvidenceKind } from "./lib/types.ts";
13
- import { spawnSync } from "node:child_process";
11
+ import { type Plugin, type PluginModule } from "@opencode-ai/plugin";
14
12
  import { existsSync, readFileSync } from "node:fs";
15
13
  import { resolve } from "node:path";
16
14
  import { join } from "node:path";
15
+ import { editTargets, runPostEditValidators, snapshotFile } from "./policies/post-edit-validation.ts";
16
+ import { claimFiles, releaseFileClaims } from "./policies/file-claims.ts";
17
+ import { beginReadObservation, clearReadFingerprints, recordSuccessfulRead, staleWriteReason } from "./policies/stale-write.ts";
18
+ import { ToolInvocationLifecycle } from "./lib/tool-lifecycle.ts";
19
+ import { ToolOutcomeTracker, type ToolOutcomePart } from "./lib/tool-outcomes.ts";
20
+ import { guardToolCallImpl, isReadOnlyRole } from "./lib/guard-dispatcher.ts";
21
+ import { createCustomTools } from "./lib/custom-tools.ts";
22
+ export { isReadOnlyRole } from "./lib/guard-dispatcher.ts";
23
+ export { extractReviewFollowups } from "./lib/custom-tools.ts";
17
24
 
18
25
  // ── Types ────────────────────────────────────────────────────────────────────
19
26
  export type {
@@ -47,19 +54,19 @@ import {
47
54
  resetVerifyState,
48
55
  sessionMutationTimestamps,
49
56
  sessionVerifyResults,
50
- loadProjectConfig,
51
- reloadProjectConfig,
52
- stripJsonComments,
57
+ getProjectConfig,
53
58
  isReviewRequired,
54
59
  isDocumentationRequired,
55
60
  getSubagentMutationBudget,
56
61
  isLearningEnabled,
62
+ isProjectMemoryEnabled,
57
63
  getLearningInterventionBudget,
58
64
  recordReviewResult,
59
65
  getLastReviewResult,
60
66
  resetReviewState,
61
67
  sessionReviews,
62
68
  } from "./lib/state.ts";
69
+ import { loadProjectConfig, reloadProjectConfig, stripJsonComments } from "./lib/project-config.ts";
63
70
 
64
71
  export {
65
72
  setWorkspaceRoot,
@@ -86,25 +93,16 @@ export {
86
93
 
87
94
  // ── Shared shell/env utilities ───────────────────────────────────────────────
88
95
  import {
89
- asRecord,
90
- extractCommands,
91
- normalize,
92
- splitShellSegments,
96
+ extractRecordTargetPath,
93
97
  getCleanEnv,
94
98
  showBlockToast,
95
- SENSITIVE_ENV_KEYS,
96
- SENSITIVE_ENV_RE,
99
+ isSensitiveEnvKey,
97
100
  } from "./lib/utils.ts";
101
+ import { dynamicShellSyntaxIn } from "./lib/shell.ts";
98
102
 
99
- export { getCleanEnv };
103
+ export { getCleanEnv, dynamicShellSyntaxIn };
100
104
 
101
105
  // ── Adaptive learning engine ─────────────────────────────────────────────────
102
- import {
103
- loadLearnerProfile,
104
- recordLearningEvidence,
105
- selectLearningOpportunity,
106
- updateLearnerProfile,
107
- } from "./lib/learning.ts";
108
106
  export {
109
107
  createLearnerProfile,
110
108
  getLearnerProfilePath,
@@ -125,20 +123,13 @@ export {
125
123
  recordProjectMemory,
126
124
  searchProjectMemory,
127
125
  getRecentProjectMemory,
126
+ recordReviewFollowup,
127
+ listReviewFollowups,
128
+ resolveReviewFollowup,
128
129
  exportProjectKnowledge,
129
130
  importProjectKnowledge,
130
131
  } from "./lib/project-memory.ts";
131
- import {
132
- exportProjectKnowledge,
133
- ensureProjectMemoryExcluded,
134
- getProjectMemoryIdentity,
135
- getRecentProjectMemory,
136
- importProjectKnowledge,
137
- isProjectMemoryFresh,
138
- openProjectMemory,
139
- recordProjectMemory,
140
- searchProjectMemory,
141
- } from "./lib/project-memory.ts";
132
+ import { ensureProjectMemoryExcluded, getProjectMemoryIdentity, getRecentProjectMemory, importProjectKnowledge, isProjectMemoryFresh, listReviewFollowups, openProjectMemory } from "./lib/project-memory.ts";
142
133
 
143
134
  // ── Audit & durable verification cache ───────────────────────────────────────
144
135
  import {
@@ -146,13 +137,25 @@ import {
146
137
  getVerifyCacheFilePath,
147
138
  persistVerifyCache,
148
139
  loadVerifyCache,
149
- getRecentAuditEntries,
150
140
  audit,
151
141
  logDecision,
152
142
  summarizeInput,
153
143
  } from "./lib/audit.ts";
154
144
 
155
- export { getAuditFilePath, getVerifyCacheFilePath, persistVerifyCache, loadVerifyCache, getRecentAuditEntries };
145
+ export { getAuditFilePath, getVerifyCacheFilePath, getVerifyHistoryFilePath, persistVerifyCache, loadVerifyCache, getRecentAuditEntries, getRecentVerifyHistory } from "./lib/audit.ts";
146
+ export { summarizeInput };
147
+
148
+ export function managedConfigDiagnostic(platform = process.platform, env: NodeJS.ProcessEnv = process.env): string {
149
+ const directory = platform === "darwin"
150
+ ? "/Library/Application Support/opencode"
151
+ : platform === "win32"
152
+ ? env.ProgramData ? join(env.ProgramData, "opencode") : undefined
153
+ : platform === "linux" ? "/etc/opencode" : undefined;
154
+ const detected = directory !== undefined && ["opencode.json", "opencode.jsonc"].some((name) => existsSync(join(directory, name)));
155
+ return directory
156
+ ? `managed config ${detected ? "detected" : "not detected"} at ${directory}; plugin provenance is not verified by the OpenCode V1 API`
157
+ : "managed config location is unknown on this platform; plugin provenance is not verified by the OpenCode V1 API";
158
+ }
156
159
 
157
160
  // ── Verification engine ──────────────────────────────────────────────────────
158
161
  import {
@@ -200,28 +203,33 @@ import {
200
203
  validateTodoLifecycle,
201
204
  fetchSessionTodos,
202
205
  fetchParentSessionID,
206
+ fetchParentSession,
207
+ subagentMutationBudgetReason,
203
208
  effectiveTodos,
204
- effectiveTodoOwnerSessionID,
205
- hasActiveTodo,
206
209
  } from "./policies/todo.ts";
210
+ import {
211
+ clearContinuationState,
212
+ continueUnfinishedSession,
213
+ isGeneratedContinuationMessage,
214
+ recordUserMessage,
215
+ } from "./policies/continuation.ts";
216
+ import {
217
+ createRecoveryCheckpoint,
218
+ finalizeRecoveryCheckpoint,
219
+ nextRecoveryRun,
220
+ } from "./lib/checkpoint.ts";
221
+ import { discoverPlanningSources } from "./policies/planning.ts";
222
+ export { discoverPlanningSources };
207
223
 
208
224
  export { validateTodoLifecycle };
209
225
 
210
226
  import {
211
- PUSH_TO_MAIN_RE,
212
- GIT_WRITE_RE,
213
- GIT_BRANCH_CREATE_RE,
214
227
  currentGitBranch,
215
228
  onProtectedBranch,
216
229
  isProtectedBranchName,
217
- pushedProtectedBranchIn,
218
- branchGuardReason,
219
- parseGitInvocation,
220
- normalizeGitCommands,
221
230
  isBranchAlreadyMergedOrClosed,
222
231
  checkMergeConflicts,
223
232
  checkBranchBaseIsUpToDate,
224
- hasUnsafeGitAlias,
225
233
  } from "./policies/git.ts";
226
234
 
227
235
  export {
@@ -232,34 +240,18 @@ export {
232
240
  };
233
241
 
234
242
  import {
235
- hasPrCreateInvocation,
236
- branchHasChangelogChange,
237
- prBodyIncludesChangelog,
238
243
  checkLockfileSync,
239
244
  } from "./policies/changelog.ts";
240
245
 
241
246
  export { checkLockfileSync };
242
247
 
243
- import { liveMutationIn, extractEditContent } from "./policies/destructive.ts";
244
-
245
- import { mcpMutationTool } from "./policies/mcp.ts";
246
-
247
248
  import {
248
- PROTECTED_PATH_REASON,
249
249
  isProtectedPath,
250
- isSettingsTamper,
251
250
  } from "./policies/tamper.ts";
252
251
 
253
252
  export { isProtectedPath };
254
253
 
255
- import {
256
- isPathOutsideWorkspace,
257
- extractPatchPaths,
258
- guardShellMutation,
259
- detectShellMutation,
260
- } from "./policies/boundary.ts";
261
-
262
- import { isSecretPath, secretIn, secretFileReadIn, isEnvFilePath, generateMaskedEnvSchema } from "./policies/secrets.ts";
254
+ import { isSecretPath, secretIn, isEnvFilePath, generateMaskedEnvSchema } from "./policies/secrets.ts";
263
255
 
264
256
  export { isSecretPath, isEnvFilePath, generateMaskedEnvSchema };
265
257
 
@@ -267,7 +259,6 @@ import {
267
259
  extractInterpreterPayload,
268
260
  secretPathInPayload,
269
261
  outsideWritePathInPayload,
270
- writePathsInPayload,
271
262
  } from "./policies/interpreter.ts";
272
263
  export { extractInterpreterPayload, secretPathInPayload, outsideWritePathInPayload };
273
264
 
@@ -287,662 +278,14 @@ export { checkCompletionClaims };
287
278
 
288
279
  export { checkInteractiveTtyCommand, checkPackageHygiene, sendDesktopNotification, escapeAppleScriptString };
289
280
 
290
- const SHELL_TOOL_NAMES = new Set(["bash", "run_commands", "execute_command", "shell"]);
291
-
292
- function logBlock(message: string): void {
281
+ function logObservation(client: unknown, message: string): void {
293
282
  try {
294
- void (getSdkClient() as any)?.app?.log?.({
295
- body: {
296
- service: "workflow-guard",
297
- level: "warn",
298
- message,
299
- },
283
+ void (client as any)?.app?.log?.({
284
+ body: { service: "workflow-guard", level: "info", message },
300
285
  });
301
286
  } catch {}
302
287
  }
303
288
 
304
- const READ_ONLY_ROLES = new Set([
305
- "reviewer",
306
- "planner",
307
- "advisor",
308
- "critic",
309
- "explorer",
310
- "scout",
311
- "evaluator",
312
- ]);
313
-
314
- export function isReadOnlyRole(agent?: string): boolean {
315
- if (!agent) return false;
316
- const lower = agent.toLowerCase().trim();
317
- return READ_ONLY_ROLES.has(lower) || Array.from(READ_ONLY_ROLES).some((r) => lower.includes(r));
318
- }
319
-
320
- async function guardToolCallImpl(
321
- toolName: string,
322
- input: unknown,
323
- context?: { sessionID?: string; worktree?: string; directory?: string; agent?: string },
324
- ): Promise<string | undefined> {
325
- const currentRoot = getWorkspaceRoot();
326
-
327
- // ── Role confinement: subagents in read-only roles cannot mutate files ──
328
- if (context?.agent && isReadOnlyRole(context.agent)) {
329
- if (EDIT_TOOL_NAMES.has(toolName) || toolName.startsWith("guard_worktree_")) {
330
- const reason = `Blocked: subagent with read-only role '${context.agent}' cannot perform file mutations or lifecycle changes.`;
331
- logBlock(`[workflow-guard] ${reason}`);
332
- return reason;
333
- }
334
- }
335
-
336
- // ── Policy 17: secret file read block via read tool ──
337
- if (toolName === "read" || toolName === "read_file") {
338
- const record = asRecord(input);
339
- const target =
340
- typeof record?.filePath === "string"
341
- ? record.filePath
342
- : typeof record?.path === "string"
343
- ? record.path
344
- : typeof input === "string"
345
- ? input
346
- : "";
347
- if (target && isSecretPath(target)) {
348
- logBlock(`[workflow-guard] blocked read: secret file ${target}`);
349
- if (isEnvFilePath(target)) {
350
- let schemaHint = "";
351
- try {
352
- const resolvedTarget = resolve(currentRoot, target);
353
- if (existsSync(resolvedTarget)) {
354
- const raw = readFileSync(resolvedTarget, "utf8");
355
- const masked = generateMaskedEnvSchema(raw);
356
- schemaHint = `\n\nSafe variable schema mask:\n\`\`\`\n${masked.slice(0, 800)}\n\`\`\``;
357
- }
358
- } catch {}
359
- return (
360
- `Blocked: reading sensitive credential file '${target}' directly is not permitted. ` +
361
- `Use environment variables or reference safe templates.${schemaHint}`
362
- );
363
- }
364
- return (
365
- `Blocked: reading sensitive credential/secret file '${target}' is not permitted. ` +
366
- "Reference environment variables by name or inspect safe templates (e.g. .env.example) instead."
367
- );
368
- }
369
- return undefined;
370
- }
371
-
372
- // ── Policy 1: todowrite lifecycle validation & finalization gates ──
373
- if (toolName === "todowrite") {
374
- const record = asRecord(input);
375
- const rawTodos = record?.todos;
376
- if (Array.isArray(rawTodos)) {
377
- const newTodos = rawTodos as any[];
378
- const existingTodos = context?.sessionID
379
- ? await fetchSessionTodos(context.sessionID)
380
- : undefined;
381
- const err = validateTodoLifecycle(newTodos, existingTodos);
382
- if (err) {
383
- logBlock(`[workflow-guard] ${err}`);
384
- return err;
385
- }
386
-
387
- const allDone =
388
- newTodos.length > 0 &&
389
- newTodos.every((t) => {
390
- const s = String(t.status ?? "");
391
- return s === "completed" || s === "cancelled";
392
- });
393
- if (allDone) {
394
- // Policy 19: conflict-free mergeability gate before task completion/handoff
395
- const conflictCheck = checkMergeConflicts(currentRoot);
396
- if (conflictCheck.hasConflicts) {
397
- const reason = `Blocked todowrite: ${conflictCheck.reason}`;
398
- logBlock(`[workflow-guard] ${reason}`);
399
- return reason;
400
- }
401
-
402
- // Policy 10: evidence-based verification
403
- const command = detectVerifyCommand(currentRoot);
404
- if (command) {
405
- const sessionID = context?.sessionID;
406
- let verifyResult = sessionID
407
- ? sessionVerifyResults.get(sessionID)
408
- : lastVerify;
409
-
410
- // Recover durable evidence from disk when in-memory state is missing.
411
- // Durable evidence is bound to the workspace that produced it: without
412
- // this check a passing run from a different project (identical verify
413
- // command, non-git state) could satisfy finalization here.
414
- if (!verifyResult) {
415
- const diskCached = loadVerifyCache();
416
- if (
417
- diskCached &&
418
- diskCached.passed &&
419
- diskCached.command === command &&
420
- diskCached.workspaceRoot === resolve(currentRoot)
421
- ) {
422
- verifyResult = diskCached;
423
- }
424
- }
425
-
426
- const mutationTimestamp = sessionID
427
- ? (sessionMutationTimestamps.get(sessionID) ?? 0)
428
- : lastMutationTimestamp;
429
-
430
- const currentCommit = getCurrentGitCommitHash(currentRoot);
431
- const currentGitStatus = getGitStatusSummary(currentRoot);
432
-
433
- const gitStateMatches =
434
- !verifyResult?.commitHash ||
435
- (verifyResult.commitHash === currentCommit &&
436
- verifyResult.gitStatus === currentGitStatus);
437
-
438
- const isFresh =
439
- verifyResult !== undefined &&
440
- verifyResult.passed &&
441
- verifyResult.command === command &&
442
- verifyResult.timestamp >= mutationTimestamp &&
443
- gitStateMatches;
444
-
445
- if (!isFresh) {
446
- const result = await runVerify(command, currentRoot);
447
- recordVerifyResult(command, result, sessionID, currentRoot);
448
- if (!result.passed) {
449
- const tail = snipVerifyOutput(result.output, result.passed).slice(-500);
450
- const reason =
451
- `Blocked todowrite: all tasks marked done but verification is failing ` +
452
- `(${command}). Fix the failure before finishing; ` +
453
- `output tail: ${tail}`;
454
- logBlock(`[workflow-guard] ${reason}`);
455
- return reason;
456
- }
457
- }
458
- }
459
- }
460
- }
461
- return undefined;
462
- }
463
-
464
- // ── Policies 1, 6, 7, 8 & 9: edit/write/patch gates ──
465
- if (EDIT_TOOL_NAMES.has(toolName)) {
466
- const allowLive = process.env.WORKFLOW_GUARD_ALLOW_LIVE === "1";
467
- const record = asRecord(input);
468
- const target =
469
- typeof record?.filePath === "string"
470
- ? record.filePath
471
- : typeof record?.path === "string"
472
- ? record.path
473
- : typeof input === "string"
474
- ? input
475
- : "";
476
-
477
- if (target && isProtectedPath(target)) {
478
- logBlock(`[workflow-guard] blocked ${toolName}: protected path ${target}`);
479
- return PROTECTED_PATH_REASON;
480
- }
481
- if (target && isSecretPath(target)) {
482
- logBlock(`[workflow-guard] blocked ${toolName}: secret file path ${target}`);
483
- return (
484
- `Blocked: modifying secret file '${target}' directly is not permitted. ` +
485
- "Store credentials in environment variables or safe secret stores instead."
486
- );
487
- }
488
- if (toolName === "apply_patch") {
489
- const patchText =
490
- typeof record?.patchText === "string" ? record.patchText : "";
491
- for (const patchPath of extractPatchPaths(patchText)) {
492
- if (isProtectedPath(patchPath)) {
493
- logBlock(
494
- `[workflow-guard] blocked apply_patch: protected path ${patchPath}`,
495
- );
496
- return PROTECTED_PATH_REASON;
497
- }
498
- if (isSecretPath(patchPath)) {
499
- logBlock(
500
- `[workflow-guard] blocked apply_patch: secret file path ${patchPath}`,
501
- );
502
- return `Blocked: modifying secret file '${patchPath}' directly is not permitted.`;
503
- }
504
- if (isPathOutsideWorkspace(patchPath, currentRoot)) {
505
- logBlock(
506
- `[workflow-guard] blocked apply_patch: patch target escapes workspace: ${patchPath}`,
507
- );
508
- return `Blocked: patch targets file '${patchPath}' outside workspace root (${currentRoot}).`;
509
- }
510
- }
511
- }
512
-
513
- if (target && isPathOutsideWorkspace(target, currentRoot)) {
514
- logBlock(
515
- `[workflow-guard] blocked ${toolName}: path escapes workspace: ${target}`,
516
- );
517
- return `Blocked: file path '${target}' escapes workspace root (${currentRoot}). All changes must stay within the workspace.`;
518
- }
519
-
520
- for (const content of extractEditContent(input)) {
521
- const secret = secretIn(content);
522
- if (secret) {
523
- logBlock(
524
- `[workflow-guard] blocked ${toolName}: payload contains ${secret}`,
525
- );
526
- return (
527
- `Blocked: payload appears to contain a ${secret}. ` +
528
- "Secrets must not be committed to the repository. Store them " +
529
- "in a secret manager or environment file excluded from git, " +
530
- "and reference them by name instead."
531
- );
532
- }
533
- }
534
-
535
- if (!allowLive) {
536
- for (const content of extractEditContent(input)) {
537
- const lines = content.split("\n");
538
- for (const line of lines) {
539
- const trimmed = line.trim();
540
- if (trimmed.startsWith("#") || trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
541
- continue;
542
- }
543
- const normalizedContent = normalizeGitCommands(line);
544
- const what = liveMutationIn(normalizedContent);
545
- if (what) {
546
- logBlock(
547
- `[workflow-guard] blocked ${toolName}: payload contains ${what}`,
548
- );
549
- return (
550
- `Blocked: the file you are writing contains a ${what}. ` +
551
- "Script files are not a way to smuggle destructive commands " +
552
- "past the shell guard. Only the user can allow live mutations " +
553
- "(WORKFLOW_GUARD_ALLOW_LIVE=1)."
554
- );
555
- }
556
- }
557
- }
558
- }
559
- for (const content of extractEditContent(input)) {
560
- if (isSettingsTamper(content)) return PROTECTED_PATH_REASON;
561
- }
562
-
563
- if (onProtectedBranch(currentRoot)) {
564
- logBlock(
565
- `[workflow-guard] blocked ${toolName}: on protected branch ${currentGitBranch(currentRoot)}`,
566
- );
567
- return branchGuardReason();
568
- }
569
- const todos = await effectiveTodos(context?.sessionID);
570
- if (todos !== undefined && !hasActiveTodo(todos)) {
571
- logBlock(
572
- `[workflow-guard] blocked ${toolName}: no active todo item (session ${context?.sessionID ?? "?"})`,
573
- );
574
- return (
575
- "Blocked: no active todo item. First break the request down " +
576
- "with the todowrite tool (create items with status 'pending' " +
577
- "or 'in_progress'), then work them through, marking " +
578
- "each completed via todowrite as you finish it. When every " +
579
- "item is completed, create a fresh todo list before " +
580
- "starting new work."
581
- );
582
- }
583
- if (context?.sessionID) {
584
- const parentID = await fetchParentSessionID(context.sessionID);
585
- if (parentID) {
586
- const count = getMutationCount(context.sessionID);
587
- const budget = getSubagentMutationBudget(currentRoot);
588
- if (count >= budget) {
589
- const reason = `Blocked: subagent session '${context.sessionID}' has reached its mutation budget (${count}/${budget}). Hand work back to parent orchestrator.`;
590
- logBlock(`[workflow-guard] ${reason}`);
591
- return reason;
592
- }
593
- }
594
- }
595
- recordMutation(await effectiveTodoOwnerSessionID(context?.sessionID));
596
- return undefined;
597
- }
598
-
599
- const allowLive = process.env.WORKFLOW_GUARD_ALLOW_LIVE === "1";
600
-
601
- // ── Policy 5: MCP tools that mutate GitHub / Azure / DevOps ──
602
- if (!allowLive) {
603
- const mcpWhat = mcpMutationTool(toolName);
604
- if (mcpWhat) {
605
- logBlock(
606
- `[workflow-guard] blocked MCP tool ${toolName} (${mcpWhat} mutation)`,
607
- );
608
- return (
609
- `Blocked: ${toolName} mutates ${mcpWhat} - a live ` +
610
- "system. Changes must be made in code unless the user " +
611
- "explicitly allows live changes. Only the user can override " +
612
- "this, via the WORKFLOW_GUARD_ALLOW_LIVE=1 environment " +
613
- "variable set before launching the agent."
614
- );
615
- }
616
- }
617
-
618
- if (!SHELL_TOOL_NAMES.has(toolName)) {
619
- return undefined;
620
- }
621
-
622
- const commands = extractCommands(input);
623
- for (const raw of commands) {
624
- const command = normalize(raw);
625
-
626
- // ── Policy 22: non-interactive shell & TTY hang guard ──
627
- const ttyCheck = checkInteractiveTtyCommand(command);
628
- if (ttyCheck.isInteractive) {
629
- logBlock(`[workflow-guard] blocked interactive TTY command: ${command.slice(0, 100)}`);
630
- return (
631
- `Blocked: '${command.slice(0, 60)}' is an ${ttyCheck.name} and will hang non-interactive agent execution. ` +
632
- `${ttyCheck.advice}`
633
- );
634
- }
635
-
636
- // ── Policy 23: package supply-chain & dependency hygiene guard ──
637
- const packageCheck = checkPackageHygiene(command);
638
- if (packageCheck.isViolating && !allowLive) {
639
- logBlock(`[workflow-guard] blocked package supply-chain violation: ${command.slice(0, 100)}`);
640
- return (
641
- `Blocked: '${command.slice(0, 60)}' is a ${packageCheck.name}. ` +
642
- `${packageCheck.advice}`
643
- );
644
- }
645
-
646
- const normalizedCommand = normalizeGitCommands(command);
647
- if (hasUnsafeGitAlias(command)) {
648
- return "Blocked: per-invocation Git aliases cannot be used because they can hide guarded Git operations.";
649
- }
650
- const gitInvocations = splitShellSegments(command)
651
- .map((segment) => parseGitInvocation(segment.trim()))
652
- .filter((invocation): invocation is NonNullable<ReturnType<typeof parseGitInvocation>> => invocation !== undefined);
653
- const effectiveRoot = gitInvocations[0]?.repoDir ?? currentRoot;
654
-
655
- // Workspace boundary check for external git repo targets
656
- for (const invocation of gitInvocations) {
657
- const normalizedInvocation = `git ${invocation.rest}`;
658
- // The workspace boundary has no allow-live override (same invariant as
659
- // file redirects/mv): an external repository write is out of bounds even
660
- // with WORKFLOW_GUARD_ALLOW_LIVE=1.
661
- if (
662
- isPathOutsideWorkspace(invocation.repoDir, currentRoot) &&
663
- (GIT_WRITE_RE.test(normalizedInvocation) || /\bgit\s+push\b/.test(normalizedInvocation))
664
- ) {
665
- logBlock(`[workflow-guard] blocked git mutation on repository outside workspace: ${invocation.repoDir}`);
666
- return `Blocked: git command targets repository '${invocation.repoDir}' outside workspace root (${currentRoot}). All changes must stay within the workspace.`;
667
- }
668
- }
669
-
670
- // ── Policy 7: changes only on feature branches ──
671
- for (const invocation of gitInvocations) {
672
- if (GIT_WRITE_RE.test(`git ${invocation.rest}`) && onProtectedBranch(invocation.repoDir)) {
673
- logBlock(
674
- `[workflow-guard] blocked git write on protected branch: ${command.slice(0, 120)}`,
675
- );
676
- return branchGuardReason();
677
- }
678
- }
679
-
680
- // Policy 20: base freshness when creating a fresh branch
681
- if (GIT_BRANCH_CREATE_RE.test(normalizedCommand)) {
682
- const behindCheck = checkBranchBaseIsUpToDate(effectiveRoot);
683
- if (behindCheck.isBehind) {
684
- logBlock(
685
- `[workflow-guard] blocked branch creation: base is behind remote ${behindCheck.baseRef}`,
686
- );
687
- return `Blocked: ${behindCheck.reason}`;
688
- }
689
- }
690
-
691
- // ── Policy 6: block self-modification of approval gates ──
692
- if (isSettingsTamper(command)) {
693
- logBlock(
694
- `[workflow-guard] blocked settings tamper: ${command.slice(0, 120)}`,
695
- );
696
- return PROTECTED_PATH_REASON;
697
- }
698
-
699
- // ── Policy 17: secret file reads via shell ──
700
- for (const segment of command.split(/[\n|;&]+/)) {
701
- const secretFile = secretFileReadIn(segment.trim());
702
- if (secretFile) {
703
- logBlock(
704
- `[workflow-guard] blocked shell read of secret file: ${secretFile}`,
705
- );
706
- return (
707
- `Blocked: reading sensitive credential/secret file '${secretFile}' via shell is not permitted. ` +
708
- "Reference environment variables by name or inspect safe templates (e.g. .env.example) instead."
709
- );
710
- }
711
- }
712
-
713
- // ── Policy 18: interpreter inline evasion scanner ──
714
- for (const payload of extractInterpreterPayload(command)) {
715
- // Workspace boundary check inside inline interpreter payloads has no
716
- // allow-live override (same invariant as file redirects).
717
- const outsidePath = outsideWritePathInPayload(payload, currentRoot);
718
- if (outsidePath) {
719
- logBlock(
720
- `[workflow-guard] blocked interpreter payload writing outside workspace: ${outsidePath}`,
721
- );
722
- return `Blocked: inline interpreter script targets file '${outsidePath}' outside workspace root (${currentRoot}). All changes must stay within the workspace.`;
723
- }
724
- const writePaths = writePathsInPayload(payload);
725
- if (writePaths.length > 0) {
726
- if (context?.agent && isReadOnlyRole(context.agent)) {
727
- return `Blocked: subagent with read-only role '${context.agent}' cannot perform shell file mutations.`;
728
- }
729
- for (const path of writePaths) {
730
- if (isProtectedPath(path)) return PROTECTED_PATH_REASON;
731
- }
732
- if (onProtectedBranch(currentRoot)) return branchGuardReason();
733
- const todos = await effectiveTodos(context?.sessionID);
734
- if (todos !== undefined && !hasActiveTodo(todos)) {
735
- return "Blocked: inline interpreter file mutation with no active todo item.";
736
- }
737
- recordMutation(await effectiveTodoOwnerSessionID(context?.sessionID));
738
- }
739
-
740
- if (!allowLive) {
741
- const normPayload = normalizeGitCommands(normalize(payload));
742
- const liveCheck = liveMutationIn(normPayload);
743
- if (liveCheck) {
744
- logBlock(
745
- `[workflow-guard] blocked interpreter payload containing ${liveCheck}`,
746
- );
747
- return `Blocked: inline interpreter script contains a ${liveCheck}. Interpreter payloads cannot smuggle live destructive commands past the guard.`;
748
- }
749
- }
750
- if (isSettingsTamper(payload)) return PROTECTED_PATH_REASON;
751
- const secretPath = secretPathInPayload(payload);
752
- if (secretPath) return `Blocked: reading sensitive credential/secret file '${secretPath}' via inline interpreter script is not permitted.`;
753
- }
754
-
755
- // ── Policies 1, 7 & 8: shell file mutations get the same gates as edits ──
756
- const shellMutationReason = await guardShellMutation(
757
- command,
758
- context?.sessionID,
759
- );
760
- if (shellMutationReason) {
761
- logBlock(
762
- `[workflow-guard] blocked shell mutation: ${command.slice(0, 120)}`,
763
- );
764
- return shellMutationReason;
765
- }
766
-
767
- // ── Policy 4: live-system mutations (env var is the ONLY override) ──
768
- if (!allowLive) {
769
- const what = liveMutationIn(normalizedCommand) ?? liveMutationIn(command);
770
- if (what) {
771
- logBlock(
772
- `[workflow-guard] blocked ${what}: ${command.slice(0, 120)}`,
773
- );
774
- return (
775
- `Blocked: ${what} targets a live system. Changes must be ` +
776
- "made in code (IaC, migrations, source) unless the user " +
777
- "explicitly allows live changes. Only the user can override " +
778
- "this, via the WORKFLOW_GUARD_ALLOW_LIVE=1 environment " +
779
- "variable set before launching the agent."
780
- );
781
- }
782
- }
783
-
784
- // ── Policy 2: block git push to main/master ──
785
- if (PUSH_TO_MAIN_RE.test(normalizedCommand)) {
786
- logBlock(
787
- `[workflow-guard] blocked push to main/master: ${command}`,
788
- );
789
- return (
790
- "Blocked: direct pushes to main/master are not allowed. " +
791
- "Create a feature branch and open a PR instead."
792
- );
793
- }
794
- // Policy 2 (cont.): configured protected branches receive the same
795
- // destination-side push protection as main/master.
796
- for (const invocation of gitInvocations) {
797
- const pushText = `git ${invocation.rest}`;
798
- if (!/\bgit\s+push\b/.test(pushText)) continue;
799
- const pushedBranch = pushedProtectedBranchIn(pushText, invocation.repoDir);
800
- if (pushedBranch) {
801
- logBlock(
802
- `[workflow-guard] blocked push to protected branch '${pushedBranch}': ${command}`,
803
- );
804
- return (
805
- `Blocked: direct pushes to protected branch '${pushedBranch}' are not allowed. ` +
806
- "Create a feature branch and open a PR instead."
807
- );
808
- }
809
- }
810
-
811
- // ── Policy 20: block push from protected or already-merged branches ──
812
- for (const invocation of gitInvocations) {
813
- if (!/\bgit\s+push\b/.test(`git ${invocation.rest}`)) continue;
814
- if (onProtectedBranch(invocation.repoDir)) {
815
- logBlock(`[workflow-guard] blocked push from protected branch: ${command}`);
816
- return branchGuardReason();
817
- }
818
- const branch = currentGitBranch(invocation.repoDir);
819
- if (branch) {
820
- const mergedStatus = isBranchAlreadyMergedOrClosed(
821
- invocation.repoDir,
822
- branch,
823
- );
824
- if (mergedStatus.merged) {
825
- logBlock(
826
- `[workflow-guard] blocked push to merged/closed branch: ${branch}`,
827
- );
828
- return `Blocked: ${mergedStatus.reason}`;
829
- }
830
- }
831
- }
832
-
833
- // ── Policy 3: PRs must include a changelog (GitHub & Azure DevOps) ──
834
- if (hasPrCreateInvocation(raw)) {
835
- const isAz = /\baz\s+repos\s+pr\s+create\b/.test(normalizedCommand);
836
- const prTool = isAz ? "az repos pr create" : "gh pr create";
837
- const descFlag = isAz ? "--description" : "--body";
838
- const preflightFailures: string[] = [];
839
-
840
- // Policy 19: conflict-free mergeability gate before opening PR
841
- const conflictCheck = checkMergeConflicts(currentRoot);
842
- if (conflictCheck.hasConflicts) {
843
- preflightFailures.push(conflictCheck.reason ?? "Branch has merge conflicts with its base branch.");
844
- }
845
-
846
- // Policy 20: branch already merged/closed
847
- const branch = currentGitBranch(currentRoot);
848
- if (branch) {
849
- const mergedStatus = isBranchAlreadyMergedOrClosed(currentRoot, branch);
850
- if (mergedStatus.merged) {
851
- preflightFailures.push(mergedStatus.reason ?? "Branch is already merged or closed.");
852
- }
853
- }
854
-
855
- if (isReviewRequired(currentRoot)) {
856
- const review = context?.sessionID
857
- ? (sessionReviews.get(context.sessionID) ?? getLastReviewResult())
858
- : getLastReviewResult();
859
- const reviewMatchesContext =
860
- review?.passed === true &&
861
- review.workspace === resolve(currentRoot) &&
862
- (!review.targetSessionID || review.targetSessionID === context?.sessionID) &&
863
- review.commitHash === getCurrentGitCommitHash(currentRoot) &&
864
- review.gitStatus === getGitStatusSummary(currentRoot) &&
865
- review.worktreeFingerprint === getGitWorktreeFingerprint(currentRoot);
866
- if (!reviewMatchesContext) {
867
- preflightFailures.push("Passing secondary review approval is required; invoke a secondary review subagent and record approval with record_review.");
868
- }
869
- }
870
-
871
- // Policy 21: documentation review & update check
872
- if (isDocumentationRequired(currentRoot)) {
873
- const hasDocChange = branchHasDocumentationChange(currentRoot);
874
- if (!hasDocChange) {
875
- preflightFailures.push("Documentation update is required (Policy 21); update README.md or relevant documentation in docs/.");
876
- }
877
- }
878
-
879
- const branchChangelog = branchHasChangelogChange(currentRoot);
880
- const prSegments = splitShellSegments(raw)
881
- .filter((segment) => hasPrCreateInvocation(segment));
882
- const hasChangelog =
883
- branchChangelog ||
884
- prSegments.every((segment) => prBodyIncludesChangelog(segment));
885
- if (!hasChangelog) {
886
- preflightFailures.push(`Changelog is required; update a CHANGELOG file or include a 'Changelog:' section in the PR description (${descFlag}).`);
887
- }
888
-
889
- // Lockfile synchronization pre-flight gate
890
- const lockCheck = checkLockfileSync(currentRoot);
891
- if (lockCheck.isOutOfSync) {
892
- preflightFailures.push(lockCheck.reason ?? "Dependency lockfile is out of sync with its manifest.");
893
- }
894
-
895
- if (preflightFailures.length > 0) {
896
- const reason = `Blocked: PR preflight failed:\n${preflightFailures.map((failure) => `- ${failure}`).join("\n")}`;
897
- logBlock(`[workflow-guard] blocked ${prTool}: ${preflightFailures.length} preflight requirement(s) failed`);
898
- return reason;
899
- }
900
- }
901
-
902
- const hasGitMutation = gitInvocations.some((invocation) => {
903
- const normalizedInvocation = `git ${invocation.rest}`;
904
- return (
905
- GIT_WRITE_RE.test(normalizedInvocation) ||
906
- /\bgit\s+(?:switch|checkout)\b/.test(normalizedInvocation)
907
- );
908
- });
909
-
910
- if (context?.agent && isReadOnlyRole(context.agent)) {
911
- const mutation = detectShellMutation(command);
912
- if (mutation) {
913
- logBlock(`[workflow-guard] blocked shell mutation for read-only role ${context.agent}: ${mutation.what}`);
914
- return `Blocked: subagent with read-only role '${context.agent}' cannot perform shell file mutations (${mutation.what}).`;
915
- }
916
- if (hasGitMutation) {
917
- logBlock(`[workflow-guard] blocked git mutation for read-only role ${context.agent}`);
918
- return `Blocked: subagent with read-only role '${context.agent}' cannot mutate git history or state.`;
919
- }
920
- }
921
-
922
- const shellMut = detectShellMutation(command);
923
- if (hasGitMutation || shellMut) {
924
- if (context?.sessionID) {
925
- const parentID = await fetchParentSessionID(context.sessionID);
926
- if (parentID) {
927
- const count = getMutationCount(context.sessionID);
928
- const budget = getSubagentMutationBudget(currentRoot);
929
- if (count >= budget) {
930
- const reason = `Blocked: subagent session '${context.sessionID}' has reached its mutation budget (${count}/${budget}). Hand work back to parent orchestrator.`;
931
- logBlock(`[workflow-guard] ${reason}`);
932
- return reason;
933
- }
934
- }
935
- }
936
- }
937
-
938
- if (hasGitMutation) {
939
- recordMutation(await effectiveTodoOwnerSessionID(context?.sessionID));
940
- }
941
- }
942
-
943
- return undefined;
944
- }
945
-
946
289
  /**
947
290
  * Public guard entry point. Audits every decision (block or allow) to a
948
291
  * durable JSONL file before returning.
@@ -950,7 +293,7 @@ async function guardToolCallImpl(
950
293
  export async function guardToolCall(
951
294
  toolName: string,
952
295
  input: unknown,
953
- context?: { sessionID?: string; worktree?: string; directory?: string; agent?: string },
296
+ context?: { sessionID?: string; callID?: string; worktree?: string; directory?: string; agent?: string },
954
297
  ): Promise<string | undefined> {
955
298
  const customRoot = context?.worktree || context?.directory;
956
299
  const runImpl = () => guardToolCallImpl(toolName, input, context);
@@ -959,13 +302,7 @@ export async function guardToolCall(
959
302
  : await runImpl();
960
303
  const allowLive = process.env.WORKFLOW_GUARD_ALLOW_LIVE === "1";
961
304
  const isMutation = EDIT_TOOL_NAMES.has(toolName);
962
- const record = asRecord(input);
963
- const targetPath =
964
- typeof record?.filePath === "string"
965
- ? record.filePath
966
- : typeof record?.path === "string"
967
- ? record.path
968
- : undefined;
305
+ const targetPath = extractRecordTargetPath(input);
969
306
  logDecision(toolName, input, context, reason, {
970
307
  mutation: isMutation,
971
308
  targetPath,
@@ -991,16 +328,27 @@ async function emitBlockFeedback(message: string): Promise<void> {
991
328
 
992
329
  export const WorkflowGuard: Plugin = async (ctx) => {
993
330
  // Honor worktree if present (e.g. opencode worktrees or devcontainers)
994
- // so worktree plugins cannot punch through boundary gates.
995
- const effectiveRoot = ctx.worktree || ctx.directory || process.cwd();
331
+ // so worktree plugins cannot punch through boundary gates. When the host
332
+ // reports the filesystem root, use the SDK's actual project worktree instead.
333
+ const hostRoot = ctx.worktree || ctx.directory || process.cwd();
334
+ const hostIsFilesystemRoot = resolve(hostRoot) === resolve(hostRoot, "..");
335
+ const effectiveRoot = hostIsFilesystemRoot && ctx.project?.worktree
336
+ ? ctx.project.worktree
337
+ : hostRoot;
996
338
  setWorkspaceRoot(effectiveRoot);
997
339
  setSdkClient(ctx.client);
998
340
  reloadProjectConfig(effectiveRoot);
999
341
  const learningEnabled = isLearningEnabled(effectiveRoot);
342
+ const projectMemoryEnabled = isProjectMemoryEnabled(effectiveRoot);
1000
343
  const learningInterventions = new Map<string, number>();
1001
344
  const portableMemoryPath = join(effectiveRoot, ".opencode", "memory", "project-memory.jsonl");
345
+ let followupStore: ReturnType<typeof openProjectMemory> | undefined;
1002
346
  let projectMemory: ReturnType<typeof openProjectMemory> | undefined;
1003
347
  try {
348
+ followupStore = openProjectMemory(getProjectMemoryIdentity(effectiveRoot));
349
+ } catch {}
350
+ try {
351
+ if (!projectMemoryEnabled) throw new Error("Project memory disabled");
1004
352
  projectMemory = openProjectMemory(getProjectMemoryIdentity(effectiveRoot));
1005
353
  ensureProjectMemoryExcluded(effectiveRoot);
1006
354
  importProjectKnowledge(projectMemory, portableMemoryPath, (content) => secretIn(content) !== undefined);
@@ -1014,368 +362,16 @@ export const WorkflowGuard: Plugin = async (ctx) => {
1014
362
  body: {
1015
363
  service: "workflow-guard",
1016
364
  level: "info",
1017
- message: `Workflow Guard plugin initialized for ${effectiveRoot}`,
365
+ message: `Workflow Guard plugin initialized for ${effectiveRoot}; ${managedConfigDiagnostic()}`,
1018
366
  },
1019
367
  });
1020
368
  } catch {}
1021
369
 
370
+ const toolLifecycle = new ToolInvocationLifecycle();
371
+ const toolOutcomes = new ToolOutcomeTracker();
372
+
1022
373
  return {
1023
- tool: {
1024
- project_memory_search: tool({
1025
- description: "Search current durable knowledge for this project. Returns concise typed records with provenance; superseded records are excluded.",
1026
- args: { query: tool.schema.string() },
1027
- execute: async (args) => projectMemory ? JSON.stringify(args.query.length <= 500 ? searchProjectMemory(projectMemory, args.query, 8) : [], null, 2) : "[workflow-guard] Project memory unavailable; core guard enforcement remains active.",
1028
- }),
1029
- project_memory_record: tool({
1030
- description: "Record a durable project fact, decision, constraint, or lesson when it will matter in future sessions. Do not record transient tool output, secrets, or speculative hypotheses.",
1031
- args: {
1032
- kind: tool.schema.string().describe("fact, decision, constraint, or lesson"),
1033
- content: tool.schema.string(),
1034
- paths: tool.schema.array(tool.schema.string()),
1035
- supersedes: tool.schema.string().optional(),
1036
- },
1037
- execute: async (args, toolContext) => {
1038
- if (!projectMemory) return "[workflow-guard] Project memory unavailable; core guard enforcement remains active.";
1039
- if (!(["fact", "decision", "constraint", "lesson"] as string[]).includes(args.kind)) return "[workflow-guard] Project memory rejected: invalid kind.";
1040
- const detectedSecret = secretIn(args.content);
1041
- if (detectedSecret) return `[workflow-guard] Project memory rejected: possible secret detected (${detectedSecret}).`;
1042
- const record = recordProjectMemory(projectMemory, {
1043
- kind: args.kind as "fact" | "decision" | "constraint" | "lesson",
1044
- content: args.content,
1045
- source: "agent",
1046
- sessionID: toolContext.sessionID,
1047
- commit: getCurrentGitCommitHash(effectiveRoot),
1048
- paths: args.paths,
1049
- supersedes: args.supersedes || undefined,
1050
- });
1051
- return JSON.stringify(record);
1052
- },
1053
- }),
1054
- project_memory_export: tool({
1055
- description: "Explicitly promote selected durable project-memory records to the human-readable repo-local .opencode/memory/project-memory.jsonl file. Nothing is exported automatically.",
1056
- args: { ids: tool.schema.array(tool.schema.string()) },
1057
- execute: async (args) => {
1058
- if (!projectMemory) return "[workflow-guard] Project memory unavailable; core guard enforcement remains active.";
1059
- if (args.ids.length > 100 || args.ids.some((id) => id.length > 200)) return "[workflow-guard] Project memory export rejected: invalid record IDs.";
1060
- const count = exportProjectKnowledge(projectMemory, args.ids, portableMemoryPath, (content) => secretIn(content) !== undefined);
1061
- return `[workflow-guard] Exported ${count} project-memory record(s) to .opencode/memory/project-memory.jsonl.`;
1062
- },
1063
- }),
1064
- project_memory_import: tool({
1065
- description: "Import the fixed repo-local .opencode/memory/project-memory.jsonl file into this project's local working-memory index.",
1066
- args: {},
1067
- execute: async () => projectMemory ? `[workflow-guard] Imported ${importProjectKnowledge(projectMemory, portableMemoryPath, (content) => secretIn(content) !== undefined)} new project-memory record(s).` : "[workflow-guard] Project memory unavailable; core guard enforcement remains active.",
1068
- }),
1069
- ...(learningEnabled ? {
1070
- learning_profile: tool({
1071
- description: "Inspect the local evidence-based learner profile so teaching can build on demonstrated knowledge without assuming unobserved concepts are gaps.",
1072
- args: {},
1073
- execute: async () => JSON.stringify(loadLearnerProfile(), null, 2),
1074
- }),
1075
- learning_checkpoint: tool({
1076
- description: "At a high-value design decision, debugging moment, or important new concept, rank candidate Socratic learning opportunities. If one is selected, ask one concise question before continuing the work; do not turn routine syntax into a lesson.",
1077
- args: {
1078
- opportunities: tool.schema.array(tool.schema.object({
1079
- type: tool.schema.string().describe("design, debugging, or new-concept"),
1080
- concept: tool.schema.string().describe("Transferable engineering concept"),
1081
- relevance: tool.schema.number().describe("Current-task relevance from 0 to 1"),
1082
- consequence: tool.schema.number().describe("Decision consequence from 0 to 1"),
1083
- })),
1084
- },
1085
- execute: async (args, toolContext) => {
1086
- const valid = args.opportunities.slice(0, 20).filter((candidate): candidate is typeof candidate & { type: "design" | "debugging" | "new-concept" } =>
1087
- (candidate.type === "design" || candidate.type === "debugging" || candidate.type === "new-concept") &&
1088
- candidate.concept.length > 0 && candidate.concept.length <= 100 &&
1089
- candidate.relevance >= 0 && candidate.relevance <= 1 && candidate.consequence >= 0 && candidate.consequence <= 1,
1090
- );
1091
- const used = learningInterventions.get(toolContext.sessionID) ?? 0;
1092
- const selected = selectLearningOpportunity(loadLearnerProfile(), valid, {
1093
- interventionsThisSession: used,
1094
- maxInterventionsPerSession: getLearningInterventionBudget(effectiveRoot),
1095
- });
1096
- if (!selected) return JSON.stringify({ intervene: false, reason: "No opportunity selected or session learning budget reached." });
1097
- learningInterventions.set(toolContext.sessionID, used + 1);
1098
- return JSON.stringify({ intervene: true, opportunity: selected, guidance: "Ask one question, use the answer as task context, briefly reconcile if useful, then continue building." });
1099
- },
1100
- }),
1101
- learning_record: tool({
1102
- description: "Record concise evidence from a real Socratic interaction after observing the learner's reasoning. Record what was demonstrated, not a grade or an inferred deficit.",
1103
- args: {
1104
- concept: tool.schema.string(),
1105
- kind: tool.schema.string().describe("exposed, developing, demonstrated, independent, critique, or needs-reinforcement"),
1106
- summary: tool.schema.string().describe("Short factual description of observed reasoning"),
1107
- },
1108
- execute: async (args, toolContext) => {
1109
- const validKinds = new Set(["exposed", "developing", "demonstrated", "independent", "critique", "needs-reinforcement"]);
1110
- if (!validKinds.has(args.kind)) return "[workflow-guard] Learning evidence rejected: invalid evidence kind.";
1111
- if (args.concept.length < 1 || args.concept.length > 100 || args.summary.length < 1 || args.summary.length > 1000) {
1112
- return "[workflow-guard] Learning evidence rejected: concept must be 1-100 characters and summary 1-1000 characters.";
1113
- }
1114
- try {
1115
- updateLearnerProfile((profile) => {
1116
- if (!profile.concepts[args.concept] && Object.keys(profile.concepts).length >= 500) {
1117
- throw new Error("concept-limit");
1118
- }
1119
- recordLearningEvidence(profile, {
1120
- concept: args.concept,
1121
- kind: args.kind as LearningEvidenceKind,
1122
- summary: args.summary,
1123
- timestamp: Date.now(),
1124
- sessionID: toolContext.sessionID,
1125
- project: effectiveRoot,
1126
- });
1127
- });
1128
- } catch (error) {
1129
- if ((error as Error).message === "concept-limit") {
1130
- return "[workflow-guard] Learning evidence rejected: learner profile concept limit reached.";
1131
- }
1132
- throw error;
1133
- }
1134
- return `[workflow-guard] Learning evidence recorded for ${args.concept}.`;
1135
- },
1136
- }),
1137
- } : {}),
1138
- guard_status: tool({
1139
- description:
1140
- "Inspect active guardrails, current branch protection, and verification/review status.",
1141
- args: {},
1142
- execute: async () => {
1143
- const root = getWorkspaceRoot();
1144
- const branch = currentGitBranch(root) ?? "unknown";
1145
- const isProtected = onProtectedBranch(root);
1146
- const lastV = getLastVerifyResult();
1147
- const lastR = getLastReviewResult();
1148
- const lastMut = getLastMutationTimestamp();
1149
- const cfg = loadProjectConfig(root);
1150
- return JSON.stringify(
1151
- {
1152
- workspaceRoot: root,
1153
- branch,
1154
- onProtectedBranch: isProtected,
1155
- lastMutationTimestamp: lastMut,
1156
- mutationCount: getMutationCount(),
1157
- lastVerify: lastV
1158
- ? {
1159
- command: lastV.command,
1160
- passed: lastV.passed,
1161
- fresh: lastV.timestamp >= lastMut,
1162
- commitHash: lastV.commitHash,
1163
- }
1164
- : null,
1165
- lastReview: lastR
1166
- ? {
1167
- reviewer: lastR.reviewer,
1168
- passed: lastR.passed,
1169
- summary: lastR.summary,
1170
- }
1171
- : null,
1172
- projectConfig: {
1173
- protectedBranches: cfg.protectedBranches ?? ["main", "master"],
1174
- verifyCommand: detectVerifyCommand(root) ?? null,
1175
- requireReview: isReviewRequired(root),
1176
- requireDocumentation: isDocumentationRequired(root),
1177
- },
1178
- },
1179
- null,
1180
- 2,
1181
- );
1182
- },
1183
- }),
1184
- guard_audit: tool({
1185
- description:
1186
- "View recent audit entries recorded by opencode-workflow-guard.",
1187
- args: {
1188
- limit: tool.schema
1189
- .number()
1190
- .optional()
1191
- .describe("Maximum entries to return (default 10)"),
1192
- },
1193
- execute: async (args) => {
1194
- const limit =
1195
- typeof args?.limit === "number" ? Math.min(args.limit, 50) : 10;
1196
- return JSON.stringify(getRecentAuditEntries(limit), null, 2);
1197
- },
1198
- }),
1199
- guard_why: tool({
1200
- description:
1201
- "Simulate and explain whether a specific tool call or command would be blocked by guardrails.",
1202
- args: {
1203
- tool: tool.schema
1204
- .string()
1205
- .describe("Tool name (e.g. bash, edit, write, read, apply_patch)"),
1206
- input: tool.schema
1207
- .record(tool.schema.string(), tool.schema.any())
1208
- .optional()
1209
- .describe("Tool input arguments"),
1210
- },
1211
- execute: async (args) => {
1212
- const reason = await guardToolCallImpl(args.tool, args.input ?? {});
1213
- return reason
1214
- ? `BLOCKED: ${reason}`
1215
- : "ALLOWED: Satisfies all current guardrails.";
1216
- },
1217
- }),
1218
- record_review: tool({
1219
- description:
1220
- "Record a secondary reviewer agent's approval or critique of the current changes. The summary must reference the 5 core review axes from guard_review_rubric.",
1221
- args: {
1222
- reviewer: tool.schema
1223
- .string()
1224
- .describe("Identifier/name of the reviewer subagent"),
1225
- summary: tool.schema
1226
- .string()
1227
- .describe("Review findings summary across the 5 core review axes"),
1228
- passed: tool.schema
1229
- .boolean()
1230
- .describe("True if change is approved, false if changes requested"),
1231
- },
1232
- execute: async (args, toolContext) => {
1233
- const parentSessionID = await fetchParentSessionID(toolContext.sessionID);
1234
- if (!parentSessionID) {
1235
- return "[workflow-guard] Review rejected: record_review must be called from a secondary/subagent session.";
1236
- }
1237
- // The rubric is the contract: a recorded review must demonstrate it
1238
- // was evaluated against the 5 axes, not just assert a verdict.
1239
- const axesRefs = [
1240
- "test integrity",
1241
- "task completeness",
1242
- "cleanliness",
1243
- "security",
1244
- "platform",
1245
- ];
1246
- const summaryLower = args.summary.toLowerCase();
1247
- const referenced = axesRefs.filter((axis) => summaryLower.includes(axis));
1248
- if (referenced.length < 3) {
1249
- return (
1250
- `[workflow-guard] Review rejected: summary must reference the review axes ` +
1251
- `(found ${referenced.length}/5). Call guard_review_rubric to get the rubric, ` +
1252
- `evaluate each axis, and include findings per axis in the summary.`
1253
- );
1254
- }
1255
- if (args.passed) {
1256
- if (/(?:^|\s)(?:\[p[01]\]|p[01]\s*:\s*(?:blocker|defect|vulnerability|error|bug|issue)|p[01]\s+blocker)/i.test(args.summary)) {
1257
- return (
1258
- "[workflow-guard] Review rejected: cannot record approval when P0 or P1 blockers are flagged in findings. " +
1259
- "Resolve all P0/P1 issues before approving or record review with passed=false."
1260
- );
1261
- }
1262
- }
1263
- recordReviewResult(
1264
- args.reviewer,
1265
- args.summary,
1266
- args.passed,
1267
- parentSessionID,
1268
- toolContext.worktree || toolContext.directory,
1269
- );
1270
- return args.passed
1271
- ? `[workflow-guard] Review recorded as APPROVED by ${args.reviewer}.`
1272
- : `[workflow-guard] Review recorded as CHANGES REQUESTED by ${args.reviewer}.`;
1273
- },
1274
- }),
1275
- guard_review_rubric: tool({
1276
- description:
1277
- "Get the secondary-review rubric for the current branch diff. The orchestrator calls this, spawns a reviewer subagent with the rubric as the prompt, then the reviewer records its verdict via record_review.",
1278
- args: {
1279
- base: tool.schema
1280
- .string()
1281
- .optional()
1282
- .describe("Base ref to diff against (default: origin/main, origin/master, main)"),
1283
- },
1284
- execute: async (args) => {
1285
- const sanitizedBase =
1286
- typeof args.base === "string" &&
1287
- !args.base.startsWith("-") &&
1288
- !/[\s;'"\0]/.test(args.base)
1289
- ? args.base
1290
- : undefined;
1291
- const bases = sanitizedBase
1292
- ? [sanitizedBase]
1293
- : ["origin/main", "origin/master", "main", "master"];
1294
- let diffText = "";
1295
- for (const base of bases) {
1296
- const res = spawnSync(
1297
- "git",
1298
- ["diff", "--", `${base}...HEAD`],
1299
- { cwd: getWorkspaceRoot(), encoding: "utf8", timeout: 10_000 },
1300
- );
1301
- if (res.status === 0 && res.stdout.trim()) {
1302
- diffText = res.stdout;
1303
- break;
1304
- }
1305
- }
1306
- if (!diffText) {
1307
- const last = spawnSync("git", ["diff", "--", "HEAD~1"], {
1308
- cwd: getWorkspaceRoot(),
1309
- encoding: "utf8",
1310
- timeout: 10_000,
1311
- });
1312
- diffText = last.status === 0 ? last.stdout : "(no diff available)";
1313
- }
1314
- return buildReviewRubric(diffText);
1315
- },
1316
- }),
1317
- guard_worktree_create: tool({
1318
- description:
1319
- "Create an isolated git worktree directory for concurrent subagent execution.",
1320
- args: {
1321
- branch: tool.schema
1322
- .string()
1323
- .describe("Branch name for the isolated worktree (e.g. 'feat/subagent-task')"),
1324
- baseBranch: tool.schema
1325
- .string()
1326
- .optional()
1327
- .describe("Base branch to branch off of (defaults to HEAD)"),
1328
- },
1329
- execute: async (args, toolContext) => {
1330
- const todos = await effectiveTodos(toolContext.sessionID);
1331
- if (todos !== undefined && !hasActiveTodo(todos)) {
1332
- return (
1333
- "[workflow-guard] Blocked: worktree creation with no active todo item. " +
1334
- "Break the request down with todowrite first, then create worktrees."
1335
- );
1336
- }
1337
- const toolRoot = toolContext.worktree || toolContext.directory || effectiveRoot;
1338
- const res = createGitWorktree(args.branch, args.baseBranch ?? "HEAD", toolRoot);
1339
- if (!res.success) {
1340
- return `[workflow-guard] Failed to create worktree: ${res.error}`;
1341
- }
1342
- recordMutation(
1343
- (await effectiveTodoOwnerSessionID(toolContext.sessionID)) ?? toolContext.sessionID,
1344
- );
1345
- return (
1346
- `[workflow-guard] Worktree created successfully at: ${res.worktreePath}\n` +
1347
- `Run subagent tasks or pass worktree directory context to isolate file mutations.`
1348
- );
1349
- },
1350
- }),
1351
- guard_worktree_cleanup: tool({
1352
- description:
1353
- "Commit a final snapshot and remove an isolated git worktree directory.",
1354
- args: {
1355
- worktreePath: tool.schema
1356
- .string()
1357
- .describe("Path of the worktree directory to clean up"),
1358
- },
1359
- execute: async (args, toolContext) => {
1360
- const todos = await effectiveTodos(toolContext.sessionID);
1361
- if (todos !== undefined && !hasActiveTodo(todos)) {
1362
- return (
1363
- "[workflow-guard] Blocked: worktree cleanup with no active todo item. " +
1364
- "Break the request down with todowrite first, then clean up worktrees."
1365
- );
1366
- }
1367
- const toolRoot = toolContext.worktree || toolContext.directory || effectiveRoot;
1368
- const res = cleanupGitWorktree(args.worktreePath, toolRoot);
1369
- if (!res.success) {
1370
- return `[workflow-guard] Failed to clean up worktree: ${res.error}`;
1371
- }
1372
- recordMutation(
1373
- (await effectiveTodoOwnerSessionID(toolContext.sessionID)) ?? toolContext.sessionID,
1374
- );
1375
- return `[workflow-guard] Worktree at '${args.worktreePath}' cleaned up successfully.`;
1376
- },
1377
- }),
1378
- },
374
+ tool: createCustomTools({ effectiveRoot, projectMemoryEnabled, learningEnabled, projectMemory, followupStore, portableMemoryPath, learningInterventions }),
1379
375
 
1380
376
  "tool.execute.before": async (input, output) => {
1381
377
  const toolWorktree =
@@ -1393,6 +389,7 @@ export const WorkflowGuard: Plugin = async (ctx) => {
1393
389
  (input as { args?: unknown }).args;
1394
390
  const reason = await guardToolCall(input.tool, args, {
1395
391
  sessionID: input.sessionID,
392
+ callID: input.callID,
1396
393
  worktree: toolWorktree,
1397
394
  agent: toolAgent,
1398
395
  });
@@ -1400,6 +397,43 @@ export const WorkflowGuard: Plugin = async (ctx) => {
1400
397
  await emitBlockFeedback(reason);
1401
398
  throw new Error(`[workflow-guard] ${reason}`);
1402
399
  }
400
+ toolLifecycle.start(input.sessionID, input.callID);
401
+ if (input.tool === "read") {
402
+ const target = editTargets(args, toolWorktree)[0];
403
+ if (target) {
404
+ const observation = beginReadObservation(target);
405
+ if (observation) toolLifecycle.setReadObservation(input.sessionID, input.callID, observation);
406
+ }
407
+ }
408
+ if (EDIT_TOOL_NAMES.has(input.tool)) {
409
+ const snapshots = editTargets(args, toolWorktree).map(snapshotFile);
410
+ if (snapshots.length) toolLifecycle.setPostEditSnapshots(input.sessionID, input.callID, toolWorktree, snapshots);
411
+ }
412
+ });
413
+ },
414
+
415
+ "tool.execute.after": async (input, output) => {
416
+ const startedAt = toolLifecycle.finish(input.sessionID, input.callID);
417
+ audit({
418
+ ts: new Date().toISOString(),
419
+ sessionID: input.sessionID,
420
+ callID: input.callID,
421
+ tool: input.tool,
422
+ decision: "allow",
423
+ phase: "outcome",
424
+ durationMs: startedAt === undefined ? undefined : Date.now() - startedAt,
425
+ });
426
+ releaseFileClaims(input.sessionID, input.callID);
427
+ if (input.tool === "read") {
428
+ const observation = toolLifecycle.takeReadObservation(input.sessionID, input.callID);
429
+ if (observation) recordSuccessfulRead(observation, input.sessionID);
430
+ }
431
+ const pending = toolLifecycle.takePostEditSnapshots(input.sessionID, input.callID);
432
+ if (!pending) return;
433
+ await runWithRuntimeState(pending.root, ctx.client, async () => {
434
+ const reports = await Promise.all(pending.snapshots.map((before) => runPostEditValidators(pending.root, before)));
435
+ const report = reports.filter((value): value is string => Boolean(value)).join("\n\n");
436
+ if (report) output.output = `${output.output}\n\n${report}`;
1403
437
  });
1404
438
  },
1405
439
 
@@ -1454,6 +488,11 @@ export const WorkflowGuard: Plugin = async (ctx) => {
1454
488
  `- Secondary Review: ${lastR.passed ? "APPROVED" : "CHANGES REQUESTED"} by ${lastR.reviewer}`,
1455
489
  );
1456
490
  }
491
+ const openFollowups = followupStore ? listReviewFollowups(followupStore, "open", 8) : [];
492
+ if (openFollowups.length > 0) {
493
+ stateLines.push(`- Open Review Follow-ups: ${openFollowups.length} local P2/P3 item(s)`);
494
+ contextBlocks.push(`## Review Follow-ups\n${openFollowups.map((item) => `- [${item.severity}:${item.id.slice(0, 8)}] ${item.summary.slice(0, 300)}`).join("\n")}\nTreat these as durable technical debt: address relevant items when practical and resolve them explicitly after verification.`);
495
+ }
1457
496
  contextBlocks.push(stateLines.join("\n"));
1458
497
  const projectKnowledge = (projectMemory ? getRecentProjectMemory(projectMemory, 20) : [])
1459
498
  .filter((memory) => memory.source !== "portable" && isProjectMemoryFresh(memory, effectiveRoot))
@@ -1474,14 +513,8 @@ export const WorkflowGuard: Plugin = async (ctx) => {
1474
513
  const env = (output as { env?: Record<string, string> }).env;
1475
514
  if (env && typeof env === "object") {
1476
515
  const scrubbed: string[] = [];
1477
- for (const key of SENSITIVE_ENV_KEYS) {
1478
- if (key in env && env[key] !== "") {
1479
- env[key] = "";
1480
- scrubbed.push(key);
1481
- }
1482
- }
1483
516
  for (const key of Object.keys(env)) {
1484
- if (SENSITIVE_ENV_RE.test(key) && env[key] !== "") {
517
+ if (isSensitiveEnvKey(key) && env[key] !== "") {
1485
518
  env[key] = "";
1486
519
  scrubbed.push(key);
1487
520
  }
@@ -1526,7 +559,7 @@ export const WorkflowGuard: Plugin = async (ctx) => {
1526
559
  const text = typeof output.text === "string" ? output.text : "";
1527
560
  const check = checkCompletionClaims(text, { sessionID });
1528
561
  if (check.claimsCompletion && check.evidenceState && check.evidenceState !== "fresh-pass") {
1529
- logBlock(`[workflow-guard] completion claim mismatch: ${check.reason}`);
562
+ logObservation(ctx.client, `[workflow-guard] completion claim mismatch: ${check.reason}`);
1530
563
  audit({
1531
564
  ts: new Date().toISOString(),
1532
565
  sessionID,
@@ -1550,9 +583,82 @@ export const WorkflowGuard: Plugin = async (ctx) => {
1550
583
  "\n\nWorkflow Guard lifecycle: each todowrite call replaces the complete task list. Preserve every pending/in_progress task in subsequent updates until you explicitly mark it completed or cancelled; do not omit active tasks when adding new work. 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.";
1551
584
  },
1552
585
 
586
+ "chat.message": async (input) => {
587
+ if (getProjectConfig(effectiveRoot).recoveryCheckpoints !== true) return;
588
+ if (isGeneratedContinuationMessage(input.sessionID, input.messageID)) return;
589
+ const parent = await runWithRuntimeState(effectiveRoot, ctx.client, () => fetchParentSession(input.sessionID));
590
+ if (!parent.ok || parent.parentID) return;
591
+ const run = nextRecoveryRun(effectiveRoot, input.sessionID);
592
+ const checkpoint = createRecoveryCheckpoint(effectiveRoot, input.sessionID, run);
593
+ if (checkpoint) toolLifecycle.setRecoveryRun(input.sessionID, run);
594
+ },
595
+
1553
596
  event: async ({
1554
597
  event,
1555
598
  }: { event: { type?: string; properties?: unknown } }) => {
599
+ if (event?.type === "message.part.updated") {
600
+ const outcome = toolOutcomes.record((event.properties as { part?: ToolOutcomePart })?.part ?? {});
601
+ if (outcome) {
602
+ audit({
603
+ ts: new Date().toISOString(),
604
+ sessionID: outcome.sessionID,
605
+ callID: outcome.callID,
606
+ tool: outcome.tool,
607
+ decision: "allow",
608
+ phase: "outcome",
609
+ durationMs: outcome.durationMs,
610
+ reason: outcome.status,
611
+ });
612
+ if (outcome.status === "error" && outcome.repeatedFailureCount === 3) {
613
+ audit({
614
+ ts: new Date().toISOString(),
615
+ sessionID: outcome.sessionID,
616
+ callID: outcome.callID,
617
+ tool: outcome.tool,
618
+ decision: "allow",
619
+ phase: "event",
620
+ reason: "repeated-equivalent-failure:3",
621
+ });
622
+ logObservation(ctx.client, `[workflow-guard] ${outcome.tool} failed equivalently 3 times in this session; change approach or inspect the underlying failure before retrying.`);
623
+ }
624
+ }
625
+ }
626
+ if (event?.type === "session.deleted") {
627
+ const sessionID = (event.properties as { info?: { id?: unknown } })?.info?.id;
628
+ if (typeof sessionID === "string") toolOutcomes.clearSession(sessionID);
629
+ }
630
+ if (event?.type === "session.idle") {
631
+ const sessionID = (event.properties as { sessionID?: unknown })?.sessionID;
632
+ if (typeof sessionID === "string") {
633
+ toolOutcomes.clearSession(sessionID);
634
+ releaseFileClaims(sessionID);
635
+ clearReadFingerprints(sessionID);
636
+ toolLifecycle.clearSession(sessionID);
637
+ const recoveryRun = toolLifecycle.takeRecoveryRun(sessionID);
638
+ if (recoveryRun !== undefined) {
639
+ finalizeRecoveryCheckpoint(effectiveRoot, sessionID, recoveryRun);
640
+ }
641
+ await runWithRuntimeState(effectiveRoot, ctx.client, () => continueUnfinishedSession(sessionID));
642
+ }
643
+ }
644
+ if (event?.type === "message.updated") {
645
+ const info = (event.properties as { info?: { id?: unknown; role?: unknown; sessionID?: unknown } })?.info;
646
+ if (info?.role === "user" && typeof info.sessionID === "string") {
647
+ await runWithRuntimeState(effectiveRoot, ctx.client, () => {
648
+ recordUserMessage(info.sessionID as string, typeof info.id === "string" ? info.id : undefined);
649
+ });
650
+ }
651
+ }
652
+ if (event?.type === "session.deleted") {
653
+ const sessionID = (event.properties as { info?: { id?: unknown } })?.info?.id;
654
+ if (typeof sessionID === "string") {
655
+ releaseFileClaims(sessionID);
656
+ clearReadFingerprints(sessionID);
657
+ toolLifecycle.clearSession(sessionID);
658
+ toolLifecycle.takeRecoveryRun(sessionID);
659
+ await runWithRuntimeState(effectiveRoot, ctx.client, () => clearContinuationState(sessionID));
660
+ }
661
+ }
1556
662
  if (
1557
663
  event?.type === "command.executed" ||
1558
664
  event?.type === "permission.updated" ||