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