@pazmo/ai-workflow-kit 4.1.0 → 5.0.1

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.
Files changed (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.ko.md +12 -0
  5. package/README.md +12 -0
  6. package/assets/check.mjs +4 -3
  7. package/bin/ai-workflow-kit.mjs +4 -1
  8. package/examples/host-routing/README.md +15 -0
  9. package/examples/verification/README.md +11 -0
  10. package/examples/verification/app.mjs +6 -0
  11. package/examples/verification/prove.mjs +12 -0
  12. package/examples/verification/verification.json +7 -0
  13. package/examples/verification/verify-cli/SKILL.md +34 -0
  14. package/examples/verification/verify-cli/features/README.md +7 -0
  15. package/examples/verification/verify-cli/features/addition.md +9 -0
  16. package/package.json +1 -1
  17. package/skills/workflow/EVALS.md +60 -2
  18. package/skills/workflow/SKILL.md +4 -2
  19. package/skills/workflow/references/execution.md +7 -7
  20. package/skills/workflow/references/graph-engineering.md +8 -4
  21. package/skills/workflow/references/intake.md +2 -0
  22. package/skills/workflow/references/model-selection.md +40 -0
  23. package/skills/workflow/references/pstack/LICENSE +21 -0
  24. package/skills/workflow/references/pstack/create-verification-skill.md +44 -0
  25. package/skills/workflow/references/pstack/principle-prove-it-works.md +22 -0
  26. package/skills/workflow/references/pstack/provenance.json +37 -0
  27. package/skills/workflow/references/pstack/references/feature-map-example/README.md +47 -0
  28. package/skills/workflow/references/pstack/references/feature-map-example/create-note.md +39 -0
  29. package/skills/workflow/references/pstack/references/feature-map-example/search.md +45 -0
  30. package/skills/workflow/references/role-graphs.md +7 -1
  31. package/skills/workflow/references/skill-integration.md +17 -2
  32. package/skills/workflow/references/understanding-gate.md +6 -3
  33. package/skills/workflow/references/verification.md +64 -0
  34. package/src/graph/approvals.mjs +19 -0
  35. package/src/graph/cli.mjs +100 -16
  36. package/src/graph/execution-metadata.mjs +22 -0
  37. package/src/graph/roles.mjs +1 -1
  38. package/src/graph/snapshot.mjs +76 -0
  39. package/src/graph/verification.mjs +151 -0
  40. package/src/graph/workflow.mjs +29 -13
  41. package/src/managed-block.mjs +3 -2
package/src/graph/cli.mjs CHANGED
@@ -5,9 +5,13 @@ import { descendantIds, nodeById } from './task-graph.mjs';
5
5
  import { resetAffectedSubgraph } from './scheduler.mjs';
6
6
  import { digest, readJson, readProjectFile, updateRun } from './storage.mjs';
7
7
  import { assertAssignment, assertRoleOutput, createRoleGraph } from './roles.mjs';
8
+ import { approvalPath, boundApproval } from './approvals.mjs';
9
+ import { createSnapshot } from './snapshot.mjs';
10
+ import { PROFILE, checkExecutions, needsExecution, runVerification, verificationProfile } from './verification.mjs';
11
+ import { normalizeExecutionMetadata } from './execution-metadata.mjs';
8
12
  import {
9
13
  MAX_ATTEMPTS, MAX_QUESTIONS, assertWorkflowRun, checkRunEvidence, createWorkflowGraph, evidenceHashes,
10
- newWorkflowRun, requireReady, revisionToken, storyContract, taskInput, taskToken, workflowStatus,
14
+ isRoleRun, newWorkflowRun, requireReady, revisionToken, storyContract, taskInput, taskToken, workflowStatus,
11
15
  } from './workflow.mjs';
12
16
 
13
17
  export const GRAPH_HELP = `Graph commands (run from project root):
@@ -16,6 +20,8 @@ export const GRAPH_HELP = `Graph commands (run from project root):
16
20
  graph.mjs status <run.json>
17
21
  graph.mjs start <run.json> <node-id> <ready-token>
18
22
  graph.mjs record <run.json> <node-id> <result.json>
23
+ graph.mjs verify <run.json> <node-id> <task-token> <check-id>
24
+ graph.mjs delivery <run.json>
19
25
  graph.mjs reset <run.json> <node-id> <reason>
20
26
  graph.mjs question <run.json> <node-id> <question.json>
21
27
  graph.mjs answer <run.json> <node-id> <answer.json>
@@ -26,7 +32,7 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
26
32
  root = await fs.realpath(root);
27
33
  const [command, ...values] = args;
28
34
  if (!command || command === '--help') return { help: GRAPH_HELP };
29
- const counts = { init: 3, 'init-role': 2, status: 1, start: 3, record: 3, reset: 3, question: 3, answer: 3, feedback: 3 };
35
+ const counts = { init: 3, 'init-role': 2, status: 1, delivery: 1, verify: 4, start: 3, record: 3, reset: 3, question: 3, answer: 3, feedback: 3 };
30
36
  if (!Object.hasOwn(counts, command) || values.length !== counts[command]) throw new Error(GRAPH_HELP);
31
37
 
32
38
  const loadStory = async file => {
@@ -48,17 +54,61 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
48
54
 
49
55
  const validate = async (run, { evidence = true } = {}) => {
50
56
  assertWorkflowRun(run);
51
- if (run.version === 2) {
57
+ if (run.version < 3) return run;
58
+ if (isRoleRun(run)) {
52
59
  const current = await readJson(root, run.assignment.file);
53
60
  if (digest(JSON.stringify(current)) !== run.assignment.fingerprint) throw new Error('Assignment changed; create a new run.');
54
61
  }
55
- const contract = run.version === 2 ? await loadSource(run.assignment.value) : await loadStory(run.story.path);
56
- if (run.version === 2) assertAssignment(run.assignment.value, contract.ids);
62
+ const contract = isRoleRun(run) ? await loadSource(run.assignment.value) : await loadStory(run.story.path);
63
+ if (isRoleRun(run)) assertAssignment(run.assignment.value, contract.ids);
57
64
  if (contract.fingerprint !== run.story.fingerprint) throw new Error('Story requirements changed; replan in a new run.');
58
- if (evidence) await checkRunEvidence(root, run);
65
+ await bindings(run, contract);
66
+ if (evidence) {
67
+ await checkRunEvidence(root, run);
68
+ for (const node of run.graph.nodes) await checkExecutions(root, run, node.id, {
69
+ requirePass: needsExecution(run, node.id) && run.state.nodes[node.id].status === 'completed',
70
+ });
71
+ }
59
72
  return run;
60
73
  };
61
74
 
75
+ const bindings = async (run, contract, initialize = false) => {
76
+ if (isRoleRun(run) && run.assignment.value.role === 'pm') return;
77
+ const g1 = await boundApproval({ root, story: run.story.path, gate: 'G1', expected: { storyHash: contract.fingerprint }, checkGate });
78
+ if (!initialize && JSON.stringify(run.approval) !== JSON.stringify(g1)) throw new Error('G1 approval changed; create a new run.');
79
+ run.approval = g1;
80
+ if (isRoleRun(run) && run.assignment.value.role === 'team-lead') return;
81
+ const profile = await verificationProfile(root, contract.ids);
82
+ if (!initialize && profile.fingerprint !== run.verification?.fingerprint) throw new Error('Verification profile changed; replan in a new run.');
83
+ run.verification = profile;
84
+ if (profile.value.requiresG3) {
85
+ const decisionHash = digest(await readProjectFile(root, profile.value.design));
86
+ const g3 = await boundApproval({ root, story: run.story.path, gate: 'G3', expected: { storyHash: contract.fingerprint, decisionHash }, checkGate });
87
+ if (!initialize && JSON.stringify(run.designApproval) !== JSON.stringify(g3)) throw new Error('G3 decision changed; replan in a new run.');
88
+ run.designApproval = g3;
89
+ }
90
+ };
91
+
92
+ const snapshot = async run => {
93
+ const text = await readProjectFile(root, run.story.path);
94
+ const extra = run.verification ? [PROFILE, ...(run.verification.recipe ? [run.verification.recipe.path] : []),
95
+ ...(run.verification.value.requiresG3 ? [run.verification.value.design] : [])] : [];
96
+ const runFile = command === 'init' || command === 'init-role' ? values[1] : values[0];
97
+ return createSnapshot({ root, inputs: run.verification?.value.inputs, additionalInputs: extra,
98
+ story: run.story.path, exclude: [runFile, `${runFile}.lock`, ...['G1', 'G3', 'G4'].map(gate => approvalPath(text, gate)).filter(Boolean)] });
99
+ };
100
+ const status = async run => {
101
+ const current = workflowStatus(run);
102
+ if (run.version < 3 || !run.verification) return current;
103
+ const code = await snapshot(run);
104
+ const stale = run.graph.nodes.filter(node => {
105
+ const state = run.state.nodes[node.id];
106
+ return state.snapshot && ['running', 'completed'].includes(state.status) && state.snapshot !== code.fingerprint;
107
+ }).map(node => node.id);
108
+ if (run.assignment?.targetSnapshot && code.fingerprint !== run.assignment.targetSnapshot && !stale.includes('review')) stale.push('review');
109
+ return { ...current, snapshot: code.fingerprint, ...(stale.length ? { action: 'stale', stale, ready: [] } : {}) };
110
+ };
111
+
62
112
  if (command === 'init-role') {
63
113
  const [file, runFile] = values;
64
114
  const value = await readJson(root, file);
@@ -66,11 +116,17 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
66
116
  const contract = await loadSource(value);
67
117
  assertAssignment(value, contract.ids);
68
118
  const graph = createRoleGraph(value);
69
- const run = await updateRun(root, runFile, async () => ({
70
- ...newWorkflowRun(graph, value.source, contract), version: 2,
71
- assignment: { file, fingerprint: digest(JSON.stringify(value)), value },
72
- }), { create: true });
73
- return workflowStatus(run);
119
+ const run = await updateRun(root, runFile, async () => {
120
+ const next = { ...newWorkflowRun(graph, value.source, contract), kind: 'role',
121
+ assignment: { file, fingerprint: digest(JSON.stringify(value)), value } };
122
+ await bindings(next, contract, true);
123
+ if (next.verification) {
124
+ const code = await snapshot(next);
125
+ if (value.role === 'reviewer') next.assignment.targetSnapshot = code.fingerprint;
126
+ }
127
+ return next;
128
+ }, { create: true });
129
+ return status(run);
74
130
  }
75
131
 
76
132
  if (command === 'init') {
@@ -78,21 +134,43 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
78
134
  const contract = await loadStory(story);
79
135
  const plan = planFile === '-' ? undefined : await readJson(root, planFile);
80
136
  const graph = createWorkflowGraph(plan, contract.ids);
81
- const run = await updateRun(root, runFile, async () => newWorkflowRun(graph, story, contract), { create: true });
82
- return workflowStatus(run);
137
+ const run = await updateRun(root, runFile, async () => {
138
+ const next = newWorkflowRun(graph, story, contract);
139
+ await bindings(next, contract, true);
140
+ await snapshot(next);
141
+ return next;
142
+ }, { create: true });
143
+ return status(run);
144
+ }
145
+ if (command === 'status' || command === 'delivery') {
146
+ const run = await validate(await readJson(root, values[0]));
147
+ const current = await status(run);
148
+ if (command === 'status') return current;
149
+ if (current.action !== 'g4' || run.kind !== 'delivery') throw new Error('Delivery requires fresh, completed v3 Graph verification.');
150
+ await boundApproval({ root, story: run.story.path, gate: 'G4', expected: {
151
+ storyHash: run.story.fingerprint, snapshot: current.snapshot, runId: run.runId,
152
+ }, checkGate });
153
+ return { ...current, action: 'delivered' };
154
+ }
155
+ if (command === 'verify') {
156
+ const [runFile, nodeId, token, checkId] = values;
157
+ const result = await runVerification({ root, runFile, nodeId, token, checkId, validate, snapshot });
158
+ return { ...await status(result.run), verification: result.verification };
83
159
  }
84
- if (command === 'status') return workflowStatus(await validate(await readJson(root, values[0])));
85
160
 
86
161
  const [runFile, nodeId, argument] = values;
87
162
  const run = await updateRun(root, runFile, async previous => {
88
163
  // Work on a copy so the optimistic edit check still compares original bytes/data.
89
164
  const next = structuredClone(previous);
90
165
  await validate(next, { evidence: command !== 'reset' });
166
+ if (next.version < 3) throw new Error('Legacy run is read-only; create a new v3 run and rerun review/verification.');
91
167
  nodeById(next.graph, nodeId);
92
168
  if (command === 'start') {
169
+ if ((await status(next)).action === 'stale') throw new Error('Code snapshot changed; reset stale review/verification first.');
93
170
  requireReady(next, nodeId, argument);
94
171
  next.state.nodes[nodeId].status = 'running';
95
172
  next.state.nodes[nodeId].attempts += 1;
173
+ if (next.verification && nodeById(next.graph, nodeId).access === 'read') next.state.nodes[nodeId].snapshot = (await snapshot(next)).fingerprint;
96
174
  next.history.push({ event: 'start', nodeId, at: new Date().toISOString() });
97
175
  } else if (command === 'record') {
98
176
  if (next.question?.nodeId === nodeId) throw new Error('Answer the pending question before recording this node.');
@@ -100,13 +178,18 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
100
178
  if (result.token !== taskToken(next, nodeId)) throw new Error('Stale or missing task token; read fresh status.');
101
179
  if (next.state.nodes[nodeId].status !== 'running') throw new Error(`Node must be started before recording: ${nodeId}`);
102
180
  if (typeof result.output?.summary !== 'string' || !result.output.summary.trim()) throw new Error('Node output needs a summary.');
181
+ result.output.execution = normalizeExecutionMetadata(result.output.execution);
103
182
  const evaluation = normalizeEvaluation(result.evaluation);
183
+ if (evaluation.passed && (await status(next)).action === 'stale') throw new Error('Code snapshot changed during review/verification; reset affected work.');
184
+ if (evaluation.passed && needsExecution(next, nodeId)) await checkExecutions(root, next, nodeId, { requirePass: true });
104
185
  if (evaluation.passed) assertRoleOutput(next, nodeId, result.output);
105
186
  if (!evaluation.passed && (typeof evaluation.feedback !== 'string' || !evaluation.feedback.trim())) throw new Error('Failed evaluation needs feedback.');
106
187
  const hashes = await evidenceHashes(root, result.output.evidence);
107
188
  const current = next.state.nodes[nodeId];
189
+ if (current.snapshot) result.output.snapshot = current.snapshot;
108
190
  next.state.nodes[nodeId] = {
109
- status: evaluation.passed ? 'completed' : 'failed', attempts: current.attempts, revision: current.revision,
191
+ ...current,
192
+ status: evaluation.passed ? 'completed' : 'failed',
110
193
  output: result.output, evaluation, evidenceHashes: hashes,
111
194
  ...(!evaluation.passed ? { error: evaluation.feedback } : {}),
112
195
  };
@@ -118,6 +201,7 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
118
201
  if (typeof request.text !== 'string' || !request.text.trim()) throw new Error('Question needs text.');
119
202
  if (next.history.filter(entry => entry.event === 'question' && entry.nodeId === nodeId).length >= MAX_QUESTIONS) throw new Error('Question limit reached; report the unresolved blocker with action human.');
120
203
  next.state.nodes[nodeId].revision += 1;
204
+ delete next.state.nodes[nodeId].executions;
121
205
  next.question = { id: randomUUID(), nodeId, text: request.text, token: taskToken(next, nodeId) };
122
206
  next.history.push({ event: 'question', nodeId, questionId: next.question.id, text: request.text, at: new Date().toISOString() });
123
207
  } else if (command === 'answer') {
@@ -152,6 +236,6 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
152
236
  }
153
237
  return next;
154
238
  });
155
- return { ...workflowStatus(run), ...(command === 'start' ? { started: taskInput(run, nodeId) } : {}),
239
+ return { ...await status(run), ...(command === 'start' ? { started: taskInput(run, nodeId) } : {}),
156
240
  ...(command === 'answer' ? { resumed: taskInput(run, nodeId) } : {}) };
157
241
  }
@@ -0,0 +1,22 @@
1
+ export function normalizeExecutionMetadata(value) {
2
+ if (value === undefined) return { selection: 'unknown', requestedModel: null, actualModel: null, confirmation: 'unknown',
3
+ effort: null, reason: 'Host did not supply model execution metadata.', usage: null };
4
+ if (!value || !['inline', 'delegated', 'pinned', 'unsupported', 'unknown'].includes(value.selection)
5
+ || !['confirmed', 'unknown', 'unsupported'].includes(value.confirmation)
6
+ || typeof value.reason !== 'string' || !value.reason.trim()) throw new Error('Invalid model execution metadata.');
7
+ for (const field of ['requestedModel', 'actualModel', 'effort']) {
8
+ if (value[field] !== null && (typeof value[field] !== 'string' || !value[field].trim())) throw new Error(`Execution metadata needs ${field} or null.`);
9
+ }
10
+ if (value.confirmation === 'confirmed' && (!value.actualModel || typeof value.metadataRef !== 'string' || !value.metadataRef.trim())) {
11
+ throw new Error('Confirmed model requires actualModel and host metadataRef.');
12
+ }
13
+ if (value.confirmation !== 'confirmed' && value.actualModel !== null) throw new Error('Unconfirmed actual model must stay null.');
14
+ if (value.usage !== null) {
15
+ if (!value.usage || typeof value.usage.source !== 'string' || !value.usage.source.trim()) throw new Error('Usage requires its host source.');
16
+ for (const field of ['inputTokens', 'outputTokens', 'cost']) {
17
+ const amount = value.usage[field];
18
+ if (amount !== null && (!Number.isFinite(amount) || amount < 0)) throw new Error('Unknown usage must be null; observed usage must be nonnegative.');
19
+ }
20
+ }
21
+ return structuredClone(value);
22
+ }
@@ -51,7 +51,7 @@ export function assertRoleRun(run) {
51
51
  }
52
52
 
53
53
  export function assertRoleOutput(run, nodeId, output) {
54
- if (run.version !== 2 || nodeId !== run.graph.nodes.at(-1).id) return;
54
+ if ((run.version !== 2 && run.kind !== 'role') || nodeId !== run.graph.nodes.at(-1).id) return;
55
55
  const assignment = run.assignment.value;
56
56
  if (assignment.role === 'developer' && (typeof output.producedRevision !== 'string' || !output.producedRevision.trim())) {
57
57
  throw new Error('Developer submission needs producedRevision covering actual changes.');
@@ -0,0 +1,76 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { digest, projectFile } from './storage.mjs';
6
+
7
+ const execute = promisify(execFile);
8
+ const outputPaths = ['.ai-workflow/runs', '.ai-workflow/evidence', '.ai-workflow/approvals'];
9
+ const inside = (parent, file) => file === parent || file.startsWith(`${parent}/`);
10
+
11
+ export function canonicalStory(text) {
12
+ return text.split(/\r?\n/).filter(line => !/^(?:Status:|Understanding gate \(G[134]\):|G4:)/i.test(line)).join('\n').trim();
13
+ }
14
+
15
+ function relativePath(value) {
16
+ if (typeof value !== 'string' || !value || value.includes('\\') || path.isAbsolute(value)
17
+ || value.split('/').includes('..') || path.posix.normalize(value) === '.') throw new Error('Snapshot inputs need project-relative paths without escapes.');
18
+ return path.posix.normalize(value).replace(/\/$/, '');
19
+ }
20
+
21
+ export async function createSnapshot({ root, inputs, additionalInputs = [], story, exclude = [] } = {}) {
22
+ root = await fs.realpath(root);
23
+ if (inputs !== undefined && (!Array.isArray(inputs) || inputs.some(file => typeof file !== 'string'))) throw new Error('Snapshot inputs must be a path array.');
24
+ const omitted = exclude.map(relativePath);
25
+ const ignored = file => outputPaths.some(dir => inside(dir, file)) || omitted.includes(file) || file === story;
26
+ const explicit = (inputs ?? []).map(relativePath);
27
+ const required = additionalInputs.map(relativePath);
28
+ if ([...explicit, ...required].some(file => ignored(file) || inside('.git', file))) throw new Error('Snapshot input overlaps an evidence/output or excluded path.');
29
+ const git = async args => (await execute('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })).stdout;
30
+ let repository = false;
31
+ try { repository = (await git(['rev-parse', '--is-inside-work-tree'])).trim() === 'true'; } catch { /* A non-Git project must declare its inputs. */ }
32
+ if (!repository && explicit.length === 0) throw new Error('Explicit snapshot inputs are required for a non-Git project.');
33
+ let head = null;
34
+ let index = [];
35
+ let files = [...explicit, ...required];
36
+ if (repository) {
37
+ const discovered = (await git(['ls-files', '-z', '--cached', '--others', '--exclude-standard'])).split('\0').filter(Boolean);
38
+ files = [...files, ...discovered];
39
+ index = (await git(['ls-files', '--stage', '-z'])).split('\0').filter(Boolean)
40
+ .filter(record => !ignored(record.slice(record.indexOf('\t') + 1))).sort();
41
+ try { head = (await git(['rev-parse', '--verify', 'HEAD'])).trim(); } catch { /* An unborn branch has no HEAD. */ }
42
+ }
43
+ const entries = new Map();
44
+ const collect = async relative => {
45
+ relative = relativePath(relative);
46
+ if (ignored(relative)) return;
47
+ if (inside('.git', relative)) throw new Error('Cannot snapshot Git internal paths.');
48
+ const file = path.join(root, relative);
49
+ let info;
50
+ try { info = await fs.lstat(file); }
51
+ catch (error) {
52
+ if (error.code !== 'ENOENT') throw error;
53
+ entries.set(relative, { path: relative, kind: 'missing' });
54
+ return;
55
+ }
56
+ if (info.isSymbolicLink()) {
57
+ const target = await fs.readlink(file);
58
+ const resolved = await fs.realpath(file);
59
+ const rel = path.relative(root, resolved);
60
+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) throw new Error('Snapshot symlink escapes project root.');
61
+ const targetInfo = await fs.stat(resolved);
62
+ if (!targetInfo.isFile()) throw new Error('Snapshot directory symlinks are unsupported; list their real inputs.');
63
+ entries.set(relative, { path: relative, kind: 'link', target, mode: targetInfo.mode & 0o777, hash: digest(await fs.readFile(resolved)) });
64
+ } else if (info.isDirectory()) {
65
+ for (const name of (await fs.readdir(file)).sort()) await collect(`${relative}/${name}`);
66
+ } else if (info.isFile()) {
67
+ // Reject symbolic ancestors even when the leaf itself is an ordinary file.
68
+ await projectFile(root, relative);
69
+ entries.set(relative, { path: relative, kind: 'file', mode: info.mode & 0o777, hash: digest(await fs.readFile(file)) });
70
+ } else throw new Error(`Unsupported snapshot input: ${relative}`);
71
+ };
72
+ for (const relative of [...new Set(files)].sort()) await collect(relative);
73
+ if (story) entries.set(story, { path: story, kind: 'story', hash: digest(canonicalStory(await fs.readFile(await projectFile(root, story), 'utf8'))) });
74
+ const manifest = { version: 1, head, index, files: [...entries.values()].sort((a, b) => a.path.localeCompare(b.path)) };
75
+ return { fingerprint: digest(JSON.stringify(manifest)), ...manifest };
76
+ }
@@ -0,0 +1,151 @@
1
+ import fs from 'node:fs/promises';
2
+ import { spawn } from 'node:child_process';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { digest, projectFile, readJson, updateRun } from './storage.mjs';
5
+ import { taskToken } from './workflow.mjs';
6
+
7
+ export const PROFILE = '.ai-workflow/verification.json';
8
+ export const needsExecution = (run, nodeId) => nodeId === 'workflow-verify'
9
+ || (run.kind === 'role' && run.assignment.value.role === 'developer' && nodeId === 'self-check');
10
+
11
+ export async function verificationProfile(root, ids) {
12
+ const value = await readJson(root, PROFILE);
13
+ if (value.version !== 1 || !Array.isArray(value.checks) || value.checks.length === 0
14
+ || (value.inputs !== undefined && (!Array.isArray(value.inputs) || value.inputs.length === 0))
15
+ || (value.requiresG3 !== undefined && typeof value.requiresG3 !== 'boolean')) throw new Error('Invalid verification profile.');
16
+ const seen = new Set();
17
+ for (const check of value.checks) {
18
+ if (typeof check.id !== 'string' || !/^[a-zA-Z0-9][\w-]*$/.test(check.id) || ['constructor', 'prototype'].includes(check.id) || seen.has(check.id)
19
+ || !Array.isArray(check.covers) || !check.covers.length || check.covers.some(id => !/^V-?\d+$/.test(id) || !ids.includes(id))
20
+ || !Array.isArray(check.argv) || !check.argv.length || check.argv.some(arg => typeof arg !== 'string' || arg.includes('\0')) || !check.argv[0]
21
+ || (check.timeoutMs !== undefined && (!Number.isInteger(check.timeoutMs) || check.timeoutMs < 1 || check.timeoutMs > 300000))) {
22
+ throw new Error('Invalid verification check: unique id, Story V references, argv and timeout (1..300000ms) are required.');
23
+ }
24
+ seen.add(check.id);
25
+ }
26
+ for (const id of ids.filter(id => /^V-?\d+$/.test(id))) {
27
+ if (!value.checks.some(check => check.covers.includes(id))) throw new Error(`Verification profile does not cover ${id}.`);
28
+ }
29
+ if (value.requiresG3 && (typeof value.design !== 'string' || !value.design.trim())) throw new Error('G3 requires a design artifact path.');
30
+ let recipe;
31
+ if (value.recipe !== undefined) {
32
+ const bytes = await fs.readFile(await projectFile(root, value.recipe));
33
+ if (!bytes.toString('utf8').trim()) throw new Error('Verification recipe must not be empty.');
34
+ recipe = { path: value.recipe, hash: digest(bytes) };
35
+ }
36
+ return { value, fingerprint: digest(JSON.stringify(value)), ...(recipe ? { recipe } : {}) };
37
+ }
38
+
39
+ async function execute(argv, root, timeoutMs) {
40
+ return new Promise(resolve => {
41
+ const stdout = [], stderr = [];
42
+ let bytes = 0, timedOut = false, truncated = false, spawnError, killer, settled = false;
43
+ const child = spawn(argv[0], argv.slice(1), { cwd: root, shell: false, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] });
44
+ const kill = signal => {
45
+ try { process.platform === 'win32' ? child.kill(signal) : process.kill(-child.pid, signal); }
46
+ catch (error) { if (error.code !== 'ESRCH') spawnError ??= error.message; }
47
+ };
48
+ const finish = (exitCode, signal, outputIncomplete = false) => {
49
+ if (settled) return;
50
+ settled = true;
51
+ clearTimeout(timer); clearTimeout(killer);
52
+ if (process.platform !== 'win32' && child.pid) kill('SIGKILL');
53
+ if (outputIncomplete) { child.stdout.destroy(); child.stderr.destroy(); child.unref(); }
54
+ resolve({ exitCode, signal, timedOut, truncated, outputIncomplete, ...(spawnError ? { spawnError } : {}), stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) });
55
+ };
56
+ const stop = () => {
57
+ if (settled) return;
58
+ kill('SIGTERM');
59
+ // An escaped descendant may keep the pipes open after our process group exits.
60
+ killer ??= setTimeout(() => {
61
+ kill('SIGKILL');
62
+ finish(child.exitCode, child.signalCode, true);
63
+ }, 500);
64
+ };
65
+ const capture = target => chunk => {
66
+ if (settled) return;
67
+ bytes += chunk.length;
68
+ if (bytes <= 10 * 1024 * 1024) target.push(chunk);
69
+ else { truncated = true; stop(); }
70
+ };
71
+ child.stdout.on('data', capture(stdout));
72
+ child.stderr.on('data', capture(stderr));
73
+ child.on('error', error => { spawnError = error.message; });
74
+ // Kill descendants belonging to this command when the parent exits, too.
75
+ child.on('exit', () => { if (process.platform !== 'win32') stop(); });
76
+ const timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs);
77
+ child.on('close', (exitCode, signal) => finish(exitCode, signal));
78
+ });
79
+ }
80
+
81
+ export async function checkExecutions(root, run, nodeId, { requirePass = false } = {}) {
82
+ const state = run.state.nodes[nodeId];
83
+ const receipts = [];
84
+ for (const binding of Object.values(state.executions ?? {})) {
85
+ if (binding.pending) { if (requirePass) throw new Error('Verification execution is still running.'); continue; }
86
+ const receipt = await readJson(root, binding.file);
87
+ if (digest(JSON.stringify(receipt)) !== binding.hash || receipt.token !== taskToken(run, nodeId)
88
+ || receipt.runId !== run.runId || receipt.storyHash !== run.story.fingerprint) throw new Error('Verification receipt changed or belongs to stale work.');
89
+ for (const stream of ['stdout', 'stderr']) {
90
+ const bytes = await fs.readFile(await projectFile(root, receipt[stream]));
91
+ if (digest(bytes) !== receipt[`${stream}Hash`]) throw new Error('Verification raw log changed.');
92
+ }
93
+ if (requirePass && (!receipt.passed || receipt.snapshotBefore !== state.snapshot || receipt.snapshotAfter !== state.snapshot)) {
94
+ throw new Error('Verification execution failed or its code snapshot changed.');
95
+ }
96
+ receipts.push(receipt);
97
+ }
98
+ if (requirePass) {
99
+ const ids = run.graph.nodes.find(node => node.id === nodeId).covers.filter(id => /^V-?\d+$/.test(id));
100
+ for (const id of ids) if (!receipts.some(receipt => receipt.covers.includes(id))) throw new Error(`Verification execution required for ${id}.`);
101
+ for (const check of run.verification.value.checks.filter(check => check.covers.some(id => ids.includes(id)))) {
102
+ if (!receipts.some(receipt => receipt.checkId === check.id)) throw new Error(`Verification execution required for configured check ${check.id}.`);
103
+ }
104
+ }
105
+ return receipts;
106
+ }
107
+
108
+ export async function runVerification({ root, runFile, nodeId, token, checkId, validate, snapshot }) {
109
+ const executionId = randomUUID();
110
+ const reserved = await updateRun(root, runFile, async previous => {
111
+ const run = structuredClone(previous);
112
+ await validate(run);
113
+ if (run.version !== 3 || !needsExecution(run, nodeId) || run.question
114
+ || run.state.nodes[nodeId]?.status !== 'running' || token !== taskToken(run, nodeId)) throw new Error('Verification requires the current running verification task token.');
115
+ const check = run.verification.value.checks.find(check => check.id === checkId);
116
+ if (!check) throw new Error('Unknown verification check.');
117
+ if (Object.hasOwn(run.state.nodes[nodeId].executions ?? {}, checkId)) throw new Error('Check already executed in this attempt; reset before retrying.');
118
+ const before = (await snapshot(run)).fingerprint;
119
+ if (before !== run.state.nodes[nodeId].snapshot) throw new Error('Verification snapshot is stale; reset affected work.');
120
+ run.state.nodes[nodeId].executions ??= {};
121
+ run.state.nodes[nodeId].executions[checkId] = { pending: executionId };
122
+ return run;
123
+ });
124
+ const check = reserved.verification.value.checks.find(check => check.id === checkId);
125
+ const directory = `.ai-workflow/evidence/${reserved.runId}/${executionId}`;
126
+ await fs.mkdir(await projectFile(root, directory), { recursive: true, mode: 0o700 });
127
+ const startedAt = new Date().toISOString();
128
+ const result = await execute(check.argv, root, check.timeoutMs ?? 30000);
129
+ const receipt = { version: 1, runId: reserved.runId, storyHash: reserved.story.fingerprint, nodeId, token, checkId, covers: check.covers,
130
+ ...(reserved.verification.recipe ? { recipe: reserved.verification.recipe } : {}),
131
+ argv: check.argv, cwd: '.', startedAt, finishedAt: new Date().toISOString(),
132
+ ...result, stdout: `${directory}/stdout.log`, stderr: `${directory}/stderr.log`,
133
+ stdoutHash: digest(result.stdout), stderrHash: digest(result.stderr),
134
+ snapshotBefore: reserved.state.nodes[nodeId].snapshot, snapshotAfter: null };
135
+ for (const stream of ['stdout', 'stderr']) await fs.writeFile(await projectFile(root, receipt[stream]), result[stream], { flag: 'wx', mode: 0o600 });
136
+ try { receipt.snapshotAfter = (await snapshot(reserved)).fingerprint; }
137
+ catch (error) { receipt.snapshotError = error.message; }
138
+ receipt.passed = receipt.exitCode === 0 && !receipt.signal && !receipt.timedOut && !receipt.truncated && !receipt.outputIncomplete && !receipt.spawnError
139
+ && !receipt.snapshotError && receipt.snapshotBefore === receipt.snapshotAfter;
140
+ const file = `${directory}/receipt.json`;
141
+ await fs.writeFile(await projectFile(root, file), `${JSON.stringify(receipt, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
142
+ const run = await updateRun(root, runFile, async previous => {
143
+ const next = structuredClone(previous);
144
+ await validate(next);
145
+ if (token !== taskToken(next, nodeId) || next.state.nodes[nodeId].status !== 'running'
146
+ || next.state.nodes[nodeId].executions?.[checkId]?.pending !== executionId) throw new Error('Late verification result rejected after reset/answer.');
147
+ next.state.nodes[nodeId].executions[checkId] = { file, hash: digest(JSON.stringify(receipt)) };
148
+ return next;
149
+ });
150
+ return { run, verification: { ...receipt, receipt: file } };
151
+ }
@@ -1,8 +1,12 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
2
3
  import { createTaskGraph, dependencyIds, descendantIds, nodeById } from './task-graph.mjs';
3
4
  import { assertRunState, blockedNodeIds, createRunState, selectReadyNodes } from './scheduler.mjs';
4
- import { digest, readProjectFile } from './storage.mjs';
5
+ import { digest, projectFile } from './storage.mjs';
5
6
  import { assertRoleOutput, assertRoleRun } from './roles.mjs';
7
+ import { canonicalStory } from './snapshot.mjs';
8
+
9
+ export const isRoleRun = run => run.version === 2 || run.kind === 'role';
6
10
 
7
11
  export const MAX_ATTEMPTS = 3;
8
12
  export const MAX_QUESTIONS = 3;
@@ -11,7 +15,7 @@ const VERIFY = 'workflow-verify';
11
15
 
12
16
  export function storyContract(text) {
13
17
  // Progress metadata is mutable; requirements and human decisions are not.
14
- const content = text.split(/\r?\n/).filter(line => !/^(?:Status:|Understanding gate \(G[134]\):|G4:)/i.test(line)).join('\n').trim();
18
+ const content = canonicalStory(text);
15
19
  const sectionIds = (heading, prefix) => {
16
20
  const body = text.match(new RegExp(`^##\\s+${heading}\\s*$([\\s\\S]*?)(?=^##\\s|$(?![\\s\\S]))`, 'im'))?.[1] ?? '';
17
21
  return [...body.matchAll(new RegExp(`^[-*]\\s+(${prefix}-?\\d+)\\b`, 'gim'))].map(match => match[1].toUpperCase());
@@ -45,11 +49,11 @@ export function createWorkflowGraph(plan, ids) {
45
49
  }
46
50
 
47
51
  export function newWorkflowRun(graph, story, contract) {
48
- return { version: 1, runId: randomUUID(), graph, state: createRunState(graph), story: { path: story, fingerprint: contract.fingerprint }, history: [] };
52
+ return { version: 3, kind: 'delivery', runId: randomUUID(), graph, state: createRunState(graph), story: { path: story, fingerprint: contract.fingerprint }, history: [] };
49
53
  }
50
54
 
51
55
  export function assertWorkflowRun(run) {
52
- if (![1, 2].includes(run?.version) || typeof run.runId !== 'string' || !run.runId.trim()
56
+ if (![1, 2, 3].includes(run?.version) || (run.version === 3 && !['delivery', 'role'].includes(run.kind)) || typeof run.runId !== 'string' || !run.runId.trim()
53
57
  || !run.graph || !run.story?.path || !Array.isArray(run.history)) throw new Error('Invalid workflow run.');
54
58
  const graph = createTaskGraph(run.graph);
55
59
  assertRunState(graph, run.state);
@@ -57,7 +61,7 @@ export function assertWorkflowRun(run) {
57
61
  || typeof run.question.id !== 'string' || !run.question.id
58
62
  || typeof run.question.text !== 'string' || !run.question.text.trim()
59
63
  || run.question.token !== taskToken(run, run.question.nodeId))) throw new Error('Invalid pending question.');
60
- if (run.version === 2) {
64
+ if (isRoleRun(run)) {
61
65
  assertRoleRun(run);
62
66
  return graph;
63
67
  }
@@ -73,7 +77,7 @@ export function taskToken(run, nodeId) {
73
77
  return digest(JSON.stringify([run.runId, run.state.fingerprint, run.story.fingerprint, nodeId,
74
78
  run.state.nodes[nodeId].attempts, run.state.nodes[nodeId].revision,
75
79
  dependencyIds(run.graph, nodeId).map(id => run.state.nodes[id]),
76
- ...(run.version === 2 ? [run.assignment.fingerprint] : []) ]));
80
+ ...(isRoleRun(run) ? [run.assignment.fingerprint] : []) ]));
77
81
  }
78
82
 
79
83
  export function revisionToken(run) {
@@ -84,8 +88,8 @@ export async function evidenceHashes(root, evidence) {
84
88
  if (!Array.isArray(evidence) || evidence.length === 0) throw new Error('Node output requires evidence files.');
85
89
  const hashes = {};
86
90
  for (const file of evidence) {
87
- const body = await readProjectFile(root, file);
88
- if (!body.trim()) throw new Error(`Empty evidence file: ${file}`);
91
+ const body = await fs.readFile(await projectFile(root, file));
92
+ if (!body.toString('utf8').trim()) throw new Error(`Empty evidence file: ${file}`);
89
93
  Object.defineProperty(hashes, file, { value: digest(body), enumerable: true, configurable: true });
90
94
  }
91
95
  return hashes;
@@ -113,17 +117,18 @@ export function workflowStatus(run) {
113
117
  const running = nodes.filter(([, state]) => state.status === 'running').map(([id]) => id);
114
118
  const exhausted = nodes.some(([, state]) => ['pending', 'failed'].includes(state.status) && state.attempts >= MAX_ATTEMPTS);
115
119
  let action;
116
- if (exhausted) action = 'stop';
120
+ if (run.version < 3) action = 'upgrade-required';
121
+ else if (exhausted) action = 'stop';
117
122
  else if (failed.some(node => node.action === 'human')) action = 'human';
118
123
  else if (failed.some(node => node.action === 'replan')) action = 'replan';
119
124
  else if (run.question) action = 'question';
120
125
  else if (failed.length) action = 'fix';
121
- else if (nodes.every(([, state]) => state.status === 'completed')) action = run.version === 2 ? 'role-complete' : 'g4';
126
+ else if (nodes.every(([, state]) => state.status === 'completed')) action = isRoleRun(run) ? 'role-complete' : 'g4';
122
127
  else action = 'execute';
123
128
  const ready = ['execute', 'fix'].includes(action) ? selectReadyNodes(graph, run.state, 4).map(node => taskInput(run, node.id)) : [];
124
129
  if (action === 'execute' && ready.length === 0 && running.length) action = 'wait';
125
130
  return { runId: run.runId, revisionToken: revisionToken(run), action, ready, running, failed, blocked: blockedNodeIds(graph, run.state),
126
- ...(run.version === 2 ? { assignment: run.assignment.value } : {}),
131
+ ...(isRoleRun(run) ? { assignment: run.assignment.value } : {}),
127
132
  ...(run.question ? { question: run.question } : {}),
128
133
  ...(action === 'role-complete' ? { submission: { nodeId: graph.nodes.at(-1).id, output: run.state.nodes[graph.nodes.at(-1).id].output } } : {}),
129
134
  completed: nodes.filter(([, state]) => state.status === 'completed').map(([id]) => id),
@@ -132,9 +137,20 @@ export function workflowStatus(run) {
132
137
 
133
138
  export function taskInput(run, nodeId) {
134
139
  const affected = descendantIds(run.graph, [nodeId]);
135
- return { ...nodeById(run.graph, nodeId), token: taskToken(run, nodeId), input: {
140
+ const node = nodeById(run.graph, nodeId);
141
+ return { ...node, token: taskToken(run, nodeId),
142
+ ...(run.state.nodes[nodeId].snapshot ? { snapshot: run.state.nodes[nodeId].snapshot } : {}), input: {
136
143
  story: run.story.path,
137
- ...(run.version === 2 ? { assignment: run.assignment.value } : {}),
144
+ ...(run.verification ? { verification: {
145
+ ...(run.verification.recipe ? { recipe: run.verification.recipe } : {}),
146
+ checks: run.verification.value.checks.filter(check => check.covers.some(id => node.covers.includes(id)))
147
+ .map(({ id, covers }) => ({ id, covers })),
148
+ } } : {}),
149
+ ...(nodeId === 'workflow-review' || (isRoleRun(run) && run.assignment.value.role === 'reviewer' && nodeId === 'review') ? {
150
+ reviewBudget: { defaultAgents: 3, smallChangeAgents: [0, 2], highRiskAgents: [4, 5], scope: 'whole-review-round',
151
+ nestedDelegation: false, dispatchOwner: 'host', aggregation: 'caller' },
152
+ } : {}),
153
+ ...(isRoleRun(run) ? { assignment: run.assignment.value } : {}),
138
154
  messages: run.history.flatMap(entry => {
139
155
  if (entry.event === 'record' && affected.has(entry.nodeId) && entry.result.evaluation?.passed === false) {
140
156
  return [{ event: 'failure', nodeId: entry.nodeId, feedback: entry.result.evaluation.feedback, output: entry.result.output }];
@@ -10,9 +10,10 @@ export const MANAGED_BLOCK = `${START_MARKER}
10
10
  - Keep Tasks at most 30 non-empty lines and reference Story M/V IDs; HOW belongs to the repository-grounded plan.
11
11
  - After G1, automatically initialize/resume the installed graph with \`node .ai-workflow/bin/graph.mjs\`. Follow the workflow graph reference; record node evidence, route failures and require graph readiness before G4. No separate npm dependency or Graph opt-in is needed.
12
12
  - Within an assigned kit graph node, apply only its role/task procedure and return evidence to that run. Office assigns roles and launches agents; the kit graph still controls readiness, joins and failure routing. Do not recursively start full delivery workflows.
13
- - Use compatible Superpowers focused TDD, diagnosis and fresh-verification skills with CE caller-owned planning, \`ce-simplify-code\`, report-only review and verified learning capture. Read the workflow skill-integration reference for exact modes, direct fallback and host limits. Do not nest end-to-end workflows or repeat approved plans. High-risk work retains G3.
13
+ - Use compatible Superpowers focused TDD, diagnosis and fresh-verification skills with CE caller-owned planning, bounded review and verified learning capture. Simplify inline by default; optional \`ce-simplify-code\` workers share the review allocation. Read skill-integration for exact modes, fallback and host limits. Do not nest end-to-end workflows or repeat approved plans. High-risk work retains G3.
14
14
  - Do not merge non-trivial changes until the workflow's G4 question gate records that a human understands behavior, an invariant/failure path, and the evidence boundary.
15
- - Gates are satisfied by evidence, not by assertion. Verify with \`node .ai-workflow/bin/check.mjs story <story-file>\` and report the exit code; exit 0 is the only pass.
15
+ - Configure the project verification profile using the workflow verification reference. Run required checks through Graph \`verify\`; inspect actual exit results/logs. Code changes make review/checks stale. Host model selection follows the workflow model policy; unknown actual model/cost stay unknown.
16
+ - \`node .ai-workflow/bin/check.mjs story <story-file>\` checks document shape/gate presence only. Report its exit code, and require \`node .ai-workflow/bin/graph.mjs delivery <run.json>\` after real G4 for bound execution/approval validation.
16
17
  ${END_MARKER}`;
17
18
 
18
19
  export function managedBlockFor(host) {