@pazmo/ai-workflow-kit 4.0.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 +22 -4
  5. package/README.md +23 -4
  6. package/assets/check.mjs +4 -3
  7. package/bin/ai-workflow-kit.mjs +6 -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 +8 -3
  17. package/skills/workflow/EVALS.md +60 -2
  18. package/skills/workflow/SKILL.md +5 -3
  19. package/skills/workflow/references/execution.md +7 -7
  20. package/skills/workflow/references/graph-engineering.md +27 -5
  21. package/skills/workflow/references/intake.md +6 -2
  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 +142 -0
  31. package/skills/workflow/references/skill-integration.md +18 -3
  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 +159 -12
  36. package/src/graph/execution-metadata.mjs +22 -0
  37. package/src/graph/roles.mjs +62 -0
  38. package/src/graph/snapshot.mjs +76 -0
  39. package/src/graph/verification.mjs +151 -0
  40. package/src/graph/workflow.mjs +61 -12
  41. package/src/managed-block.mjs +3 -2
@@ -0,0 +1,64 @@
1
+ # Prove the current Story against the running product
2
+
3
+ Read this at project setup and final verification, not at every node. The pinned Pstack [principle](pstack/principle-prove-it-works.md) and [recipe guide](pstack/create-verification-skill.md) supply evidence standards. Pstack creates project-specific `verify-<app>` skills; it does not expose one universal `verify` skill. This integration uses that project procedure inside SP's fresh-verification stage; Graph owns state and receipts.
4
+
5
+ ## Discover and exercise the project procedure
6
+
7
+ 1. Inspect the project's skill catalog, E2E scripts and verification guides. Reuse an adequate existing procedure. Record its project-relative path as profile `recipe`; read it before running relevant checks. If no guide is needed for a simple existing assertion, a recipe-free profile remains valid.
8
+ 2. If the user journey has no runnable procedure, use the pinned creation guide to write a minimal project-local `verify-<app>/SKILL.md` or an existing-style verification guide. Include Launch (start/configure), Doctor (diagnose prerequisites), Drive (user actions and assertions), Evidence (preserved observations), Cleanup (owned resources) and only necessary Helpers. A short-lived CLI can state that no server is required. Reuse the current harness and record external stand-ins and limits.
9
+ 3. For multiple journeys, keep a small feature index beside the recipe linking each covered V to its actions, expected result, failure path and checker. Read only relevant entries. List helper/feature-map directories in profile `inputs`; Markdown links alone do not bind those files.
10
+ 4. Before accepting a new or changed procedure, actually follow it once: diagnose the environment, launch/drive the real product, inspect assertions/logs and clean up. Check that evidence survives cleanup. A changed feature or failed Doctor triggers repair of the affected procedure, not a second full workflow or one worker per feature.
11
+
12
+ For a runnable example see [verify-cli](../../../examples/verification/verify-cli/SKILL.md) in the package source; installed projects copy `examples/verification` from the package as described in its README. Do not install full Pstack setup/poteto-mode or register a second workflow to obtain this procedure.
13
+
14
+ For each Story V ID, describe the real user entry point, preconditions, action, expected state/side effect and failure path. Reuse a suitable existing test. Otherwise write a small executable checker that starts/drives the actual CLI/server/browser and asserts those observations. A server's successful startup alone does not prove its feature. No mocks beyond existing external boundaries. Missing prerequisites, unavailable environments and manual-only checks remain unverified and block executable delivery; never replace them with a convenient no-op.
15
+
16
+ ## Project profile
17
+
18
+ Create `.ai-workflow/verification.json` (review it like executable code):
19
+
20
+ ```json
21
+ {
22
+ "version": 1,
23
+ "recipe": "verify-app/SKILL.md",
24
+ "inputs": ["src", "scripts/prove-feature.mjs", "verify-app", "package.json"],
25
+ "checks": [
26
+ {"id":"feature", "covers":["V1"], "argv":["node","scripts/prove-feature.mjs"], "timeoutMs":30000}
27
+ ],
28
+ "requiresG3": false
29
+ }
30
+ ```
31
+
32
+ Use actual project paths and Story IDs. Optional `recipe` must name a readable, nonempty file inside the project without symlinks. Task inputs include its path/byte hash and relevant check IDs; receipts retain that recipe identity. The file is not executed as code. A hash binds content, not proof that an agent read/invoked the skill or that its assertions are adequate.
33
+
34
+ Commands run from the project root with `shell: false`, inherited host environment/permissions, closed stdin and a 30-second default timeout (maximum 300 seconds). Combined output over 10 MiB fails the check and retains truncated logs. Cleanup targets the command's process group on POSIX and its direct child on Windows; checkers must stop services they detach. If output pipes remain open beyond the 500ms termination grace, the runner closes its streams and records `outputIncomplete`, which fails verification. Shell operators are literal argv; put pipelines/server lifecycle in a reviewed checker script that asserts behavior and exits nonzero on failure. This runner is not a security sandbox. Use an existing worktree/container for risky prototypes according to host policy.
35
+
36
+ Git snapshots include HEAD, index state, tracked bytes/deletions, executable modes and nonignored untracked files, plus explicit inputs. Profile, selected recipe and required G3 design are always additional snapshot inputs, including when Git-ignored. Other ignored helpers/features require explicit inputs. Recipe edits make previous review/verification stale; profile edits require a new run. Non-Git projects must still list behavioral inputs explicitly, including dependencies/configuration/checkers. Commit/stage before final verification, or rerun affected checks after those Git changes. External services, environment variables, installed dependencies and data are not fully captured; record versions/seed conditions and remaining boundaries in the recipe.
37
+
38
+ Keep generated run/result/log/approval files under `.ai-workflow/runs/`, `.ai-workflow/evidence/`, `.ai-workflow/approvals/`. These outputs are excluded; never put product source there. Keep checker-generated caches/builds Git-ignored, or make them declared stable inputs. Logs may contain secrets: keep them local, inspect/redact before intentionally sharing, never automatically upload/commit them.
39
+
40
+ ## Bind human decisions
41
+
42
+ Compute the canonical Story hash with installed `storyContract` from `.ai-workflow/graph/workflow.mjs`; it excludes Status and G1/G3/G4 metadata lines. Add the existing gate line pointing to an approval JSON. Populate only after the real human decision:
43
+
44
+ ```json
45
+ {"gate":"G1", "storyHash":"<canonical hash>", "responseRef":"<actual response reference>"}
46
+ ```
47
+
48
+ For a design requiring G3, set `requiresG3: true` and `design: "docs/design.md"` in the profile; the G3 JSON additionally has `decisionHash` (SHA-256 of design bytes). Obtain the decision before initialization/implementation. Small changes need no G3. Risk declaration belongs to the approved scope and reviewed profile, not a keyword classifier.
49
+
50
+ G4 JSON additionally has the current Graph `snapshot` and `runId`; preserve prediction-before-reveal in `understanding-gate.md`. These bindings prevent accidental reuse; a host controlling repository files can forge records. They are not human identity authentication.
51
+
52
+ ## Run and inspect
53
+
54
+ Start the final verification node, then execute every configured check intersecting its V scope. If several checks cover the same V, all are required; one convenient passing journey cannot replace another:
55
+
56
+ ```bash
57
+ node .ai-workflow/bin/graph.mjs verify <run.json> workflow-verify <started-token> feature
58
+ ```
59
+
60
+ Under `superpowers:verification-before-completion`, read `verification.passed`, exit code/signal/timeout/incomplete-output, actual stdout/stderr, snapshot before/after and asserted boundaries from this same execution. No second run is needed merely because Pstack and SP both apply. CLI exit 0 reports successful collection, including a failing check. Empty logs are valid; the structured receipt captures execution. Raw log hashes and receipts are rechecked. A failed execution cannot be overridden by result `passed: true`; reset affected work and re-execute after correction. Repeating a check in one attempt is rejected. Reset preserves attempt counts and fences late results; it does not cancel a running process, which remains timeout-bound. Inspect host-owned workers before recovery.
61
+
62
+ Record the existing result JSON afterward. Review and final checks must reference the current code snapshot. `status` returns `stale` without rewriting saved state when code changed. Reset the earliest stale node, rerun descendants, and obtain G4 for the fresh snapshot. After real G4 run `graph.mjs delivery <run.json>`; document shape checks alone cannot establish delivery.
63
+
64
+ Legacy v1/v2 runs remain readable with `upgrade-required`. Stop old workers, retain artifacts/attempt history, and rerun checks/review in a new v3 run. Never import old `passed` flags as proof or reset budgets by renaming runs. Package 5.0 introduces this breaking persisted-format change; run format v3 is independent of the package version.
@@ -0,0 +1,19 @@
1
+ import { digest, readJson, readProjectFile } from './storage.mjs';
2
+
3
+ export function approvalPath(text, gate) {
4
+ return text.match(new RegExp(`^Understanding gate \\(${gate}\\):\\s*([^·|\\n]+)[·|]`, 'im'))?.[1].trim();
5
+ }
6
+
7
+ // Binding prevents accidental reuse. It does not authenticate the host or the human.
8
+ export async function boundApproval({ root, story, gate, expected, checkGate }) {
9
+ const checked = await checkGate({ root, file: story, gate });
10
+ if (!checked.ok) throw new Error(checked.errors.join('\n'));
11
+ const file = approvalPath(await readProjectFile(root, story), gate);
12
+ if (!file) throw new Error(`${gate} requires a bound approval JSON artifact.`);
13
+ const value = await readJson(root, file);
14
+ if (value.gate !== gate || typeof value.responseRef !== 'string' || !value.responseRef.trim()
15
+ || Object.entries(expected).some(([key, expectedValue]) => value[key] !== expectedValue)) {
16
+ throw new Error(`${gate} approval binding changed or missing; obtain a fresh human decision for this Story/revision.`);
17
+ }
18
+ return { file, hash: digest(JSON.stringify(value)) };
19
+ }
package/src/graph/cli.mjs CHANGED
@@ -1,26 +1,38 @@
1
1
  import fs from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { normalizeEvaluation } from './executor.mjs';
3
4
  import { descendantIds, nodeById } from './task-graph.mjs';
4
5
  import { resetAffectedSubgraph } from './scheduler.mjs';
5
- import { readJson, readProjectFile, updateRun } from './storage.mjs';
6
+ import { digest, readJson, readProjectFile, updateRun } from './storage.mjs';
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';
6
12
  import {
7
- MAX_ATTEMPTS, assertWorkflowRun, checkRunEvidence, createWorkflowGraph, evidenceHashes,
8
- newWorkflowRun, requireReady, storyContract, taskInput, taskToken, workflowStatus,
13
+ MAX_ATTEMPTS, MAX_QUESTIONS, assertWorkflowRun, checkRunEvidence, createWorkflowGraph, evidenceHashes,
14
+ isRoleRun, newWorkflowRun, requireReady, revisionToken, storyContract, taskInput, taskToken, workflowStatus,
9
15
  } from './workflow.mjs';
10
16
 
11
17
  export const GRAPH_HELP = `Graph commands (run from project root):
12
18
  graph.mjs init <plan.json|-> <run.json> <story.md>
19
+ graph.mjs init-role <assignment.json> <run.json>
13
20
  graph.mjs status <run.json>
14
21
  graph.mjs start <run.json> <node-id> <ready-token>
15
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>
16
25
  graph.mjs reset <run.json> <node-id> <reason>
26
+ graph.mjs question <run.json> <node-id> <question.json>
27
+ graph.mjs answer <run.json> <node-id> <answer.json>
28
+ graph.mjs feedback <run.json> <node-id> <feedback.json>
17
29
  Use - for a minimal plan. The host executes work; this tool validates state/evidence and routes the next action.`;
18
30
 
19
31
  export async function runGraphCommand(args, { root = process.cwd(), checkArtifact, checkGate } = {}) {
20
32
  root = await fs.realpath(root);
21
33
  const [command, ...values] = args;
22
34
  if (!command || command === '--help') return { help: GRAPH_HELP };
23
- const counts = { init: 3, status: 1, start: 3, record: 3, reset: 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 };
24
36
  if (!Object.hasOwn(counts, command) || values.length !== counts[command]) throw new Error(GRAPH_HELP);
25
37
 
26
38
  const loadStory = async file => {
@@ -33,62 +45,197 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
33
45
  return storyContract(text);
34
46
  };
35
47
 
48
+ const loadSource = async assignment => {
49
+ if (assignment.role !== 'pm') return loadStory(assignment.source);
50
+ const text = await readProjectFile(root, assignment.source);
51
+ if (!text.trim()) throw new Error('PM source request must not be empty.');
52
+ return { fingerprint: digest(text), ids: [] };
53
+ };
54
+
36
55
  const validate = async (run, { evidence = true } = {}) => {
37
56
  assertWorkflowRun(run);
38
- const contract = await loadStory(run.story.path);
57
+ if (run.version < 3) return run;
58
+ if (isRoleRun(run)) {
59
+ const current = await readJson(root, run.assignment.file);
60
+ if (digest(JSON.stringify(current)) !== run.assignment.fingerprint) throw new Error('Assignment changed; create a new run.');
61
+ }
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);
39
64
  if (contract.fingerprint !== run.story.fingerprint) throw new Error('Story requirements changed; replan in a new run.');
40
- 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
+ }
41
72
  return run;
42
73
  };
43
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
+
112
+ if (command === 'init-role') {
113
+ const [file, runFile] = values;
114
+ const value = await readJson(root, file);
115
+ assertAssignment(value);
116
+ const contract = await loadSource(value);
117
+ assertAssignment(value, contract.ids);
118
+ const graph = createRoleGraph(value);
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);
130
+ }
131
+
44
132
  if (command === 'init') {
45
133
  const [planFile, runFile, story] = values;
46
134
  const contract = await loadStory(story);
47
135
  const plan = planFile === '-' ? undefined : await readJson(root, planFile);
48
136
  const graph = createWorkflowGraph(plan, contract.ids);
49
- const run = await updateRun(root, runFile, async () => newWorkflowRun(graph, story, contract), { create: true });
50
- 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 };
51
159
  }
52
- if (command === 'status') return workflowStatus(await validate(await readJson(root, values[0])));
53
160
 
54
161
  const [runFile, nodeId, argument] = values;
55
162
  const run = await updateRun(root, runFile, async previous => {
56
163
  // Work on a copy so the optimistic edit check still compares original bytes/data.
57
164
  const next = structuredClone(previous);
58
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.');
59
167
  nodeById(next.graph, nodeId);
60
168
  if (command === 'start') {
169
+ if ((await status(next)).action === 'stale') throw new Error('Code snapshot changed; reset stale review/verification first.');
61
170
  requireReady(next, nodeId, argument);
62
171
  next.state.nodes[nodeId].status = 'running';
63
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;
64
174
  next.history.push({ event: 'start', nodeId, at: new Date().toISOString() });
65
175
  } else if (command === 'record') {
176
+ if (next.question?.nodeId === nodeId) throw new Error('Answer the pending question before recording this node.');
66
177
  const result = await readJson(root, argument);
67
178
  if (result.token !== taskToken(next, nodeId)) throw new Error('Stale or missing task token; read fresh status.');
68
179
  if (next.state.nodes[nodeId].status !== 'running') throw new Error(`Node must be started before recording: ${nodeId}`);
69
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);
70
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 });
185
+ if (evaluation.passed) assertRoleOutput(next, nodeId, result.output);
71
186
  if (!evaluation.passed && (typeof evaluation.feedback !== 'string' || !evaluation.feedback.trim())) throw new Error('Failed evaluation needs feedback.');
72
187
  const hashes = await evidenceHashes(root, result.output.evidence);
73
188
  const current = next.state.nodes[nodeId];
189
+ if (current.snapshot) result.output.snapshot = current.snapshot;
74
190
  next.state.nodes[nodeId] = {
75
- status: evaluation.passed ? 'completed' : 'failed', attempts: current.attempts, revision: current.revision,
191
+ ...current,
192
+ status: evaluation.passed ? 'completed' : 'failed',
76
193
  output: result.output, evaluation, evidenceHashes: hashes,
77
194
  ...(!evaluation.passed ? { error: evaluation.feedback } : {}),
78
195
  };
79
196
  next.history.push({ event: 'record', nodeId, at: new Date().toISOString(), result: next.state.nodes[nodeId] });
197
+ } else if (command === 'question') {
198
+ if (next.question || ['human', 'replan', 'stop'].includes(workflowStatus(next).action)) throw new Error('Resolve the pending question or blocking decision first.');
199
+ const request = await readJson(root, argument);
200
+ if (next.state.nodes[nodeId].status !== 'running' || request.token !== taskToken(next, nodeId)) throw new Error('Question requires the current running task token.');
201
+ if (typeof request.text !== 'string' || !request.text.trim()) throw new Error('Question needs text.');
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.');
203
+ next.state.nodes[nodeId].revision += 1;
204
+ delete next.state.nodes[nodeId].executions;
205
+ next.question = { id: randomUUID(), nodeId, text: request.text, token: taskToken(next, nodeId) };
206
+ next.history.push({ event: 'question', nodeId, questionId: next.question.id, text: request.text, at: new Date().toISOString() });
207
+ } else if (command === 'answer') {
208
+ const reply = await readJson(root, argument);
209
+ const question = next.question;
210
+ if (!question || question.nodeId !== nodeId || reply.questionId !== question.id || reply.token !== question.token) throw new Error('Stale or mismatched question answer.');
211
+ if (workflowStatus(next).action !== 'question') throw new Error('Resolve the blocking decision before resuming this task.');
212
+ if (typeof reply.text !== 'string' || !reply.text.trim()) throw new Error('Answer needs text.');
213
+ const hashes = await evidenceHashes(root, reply.evidence);
214
+ next.history.push({ event: 'answer', nodeId, questionId: question.id, text: reply.text, evidence: reply.evidence, evidenceHashes: hashes, at: new Date().toISOString() });
215
+ delete next.question;
216
+ next.state.nodes[nodeId].revision += 1;
80
217
  } else {
81
218
  if (!argument.trim()) throw new Error('Reset requires a reason.');
219
+ if (next.question) throw new Error('Answer the pending question before resetting work.');
82
220
  const status = workflowStatus(next);
83
221
  if (['human', 'replan', 'stop'].includes(status.action)) throw new Error(`Cannot blindly retry ${status.action}; resolve the decision and create a new run.`);
84
222
  const affected = [...descendantIds(next.graph, [nodeId])];
85
223
  if (affected.some(id => id !== nodeId && next.state.nodes[id].status === 'running')) throw new Error('Stop running descendants before resetting their inputs.');
86
224
  if (affected.some(id => next.state.nodes[id].attempts >= MAX_ATTEMPTS)) throw new Error('Attempt limit reached; stop and inspect the evidence.');
225
+ let feedback;
226
+ if (command === 'feedback') {
227
+ feedback = await readJson(root, argument);
228
+ if (feedback.token !== revisionToken(next)) throw new Error('Stale feedback token; read fresh status.');
229
+ if (!['completed', 'failed'].includes(next.state.nodes[nodeId].status)) throw new Error('Feedback requires completed or failed work; stop running work first.');
230
+ if (typeof feedback.summary !== 'string' || !feedback.summary.trim()) throw new Error('Feedback needs a summary.');
231
+ feedback = { summary: feedback.summary, evidence: feedback.evidence, evidenceHashes: await evidenceHashes(root, feedback.evidence) };
232
+ }
87
233
  next.state = resetAffectedSubgraph(next.graph, next.state, [nodeId]);
88
- next.history.push({ event: 'reset', nodeId, affected, reason: argument, at: new Date().toISOString() });
234
+ next.history.push({ event: command, nodeId, affected, ...(feedback ?? { reason: argument }), at: new Date().toISOString() });
89
235
  await checkRunEvidence(root, next);
90
236
  }
91
237
  return next;
92
238
  });
93
- return { ...workflowStatus(run), ...(command === 'start' ? { started: taskInput(run, nodeId) } : {}) };
239
+ return { ...await status(run), ...(command === 'start' ? { started: taskInput(run, nodeId) } : {}),
240
+ ...(command === 'answer' ? { resumed: taskInput(run, nodeId) } : {}) };
94
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
+ }
@@ -0,0 +1,62 @@
1
+ import { createTaskGraph, graphFingerprint } from './task-graph.mjs';
2
+ import { digest } from './storage.mjs';
3
+
4
+ const flows = {
5
+ pm: [
6
+ ['clarify', 'read', 'Read the request, related knowledge and open questions.', 'Identify missing decisions; ask only necessary questions.'],
7
+ ['propose', 'write', 'Propose the canonical Story within the assigned scope.', 'Check clarity and verifiability. Return the proposal without issuing G1.'],
8
+ ],
9
+ 'team-lead': [
10
+ ['investigate', 'read', 'Inspect the repository, dependencies and related lessons.', 'Ground the plan in source and approved requirements.'],
11
+ ['plan', 'write', 'Plan the assigned scope and propose ownership and dependencies.', 'Use caller-owned CE planning; return the plan without dispatching another full workflow.'],
12
+ ],
13
+ developer: [
14
+ ['implement', 'write', 'Implement the assigned scope using focused TDD and diagnosis.', 'Record applicable RED/GREEN evidence; simplify while green.'],
15
+ ['self-check', 'read', 'Verify the produced revision against assigned requirements.', 'Record fresh checks, producedRevision and limitations; independent review remains separate.'],
16
+ ],
17
+ reviewer: [
18
+ ['review', 'read', 'Review the assigned revision using CE review in agent mode.', 'Return pass or needs_changes, reviewedRevision and evidence; do not edit product code.'],
19
+ ],
20
+ };
21
+
22
+ export function assertAssignment(value, ids) {
23
+ if (value?.version !== 1 || !Object.hasOwn(flows, value.role)) throw new Error('Invalid role assignment version or role.');
24
+ for (const key of ['taskId', 'source', 'targetRevision']) {
25
+ if (typeof value[key] !== 'string' || !value[key].trim()) throw new Error(`Assignment needs ${key}.`);
26
+ }
27
+ if (!Array.isArray(value.scope) || value.scope.some(id => typeof id !== 'string')
28
+ || new Set(value.scope).size !== value.scope.length) throw new Error('Assignment needs unique scope references.');
29
+ if (value.role === 'pm') {
30
+ if (value.scope.length) throw new Error('PM request scope must be empty; propose Story references in its output.');
31
+ } else {
32
+ if (!value.scope.some(id => /^M-?\d+$/.test(id)) || !value.scope.some(id => /^V-?\d+$/.test(id))) throw new Error('Assignment scope needs Story M/V references.');
33
+ if (ids && value.scope.some(id => !ids.includes(id))) throw new Error('Assignment contains unknown Story references.');
34
+ }
35
+ }
36
+
37
+ export function createRoleGraph(assignment) {
38
+ assertAssignment(assignment);
39
+ const nodes = flows[assignment.role].map(([id, access, description, verify]) => ({ id, access, description, verify, covers: assignment.scope }));
40
+ return createTaskGraph({ id: `role-${assignment.role}`, nodes,
41
+ edges: nodes.slice(1).map((node, index) => ({ from: nodes[index].id, to: node.id })) });
42
+ }
43
+
44
+ export function assertRoleRun(run) {
45
+ const binding = run.assignment;
46
+ assertAssignment(binding?.value);
47
+ if (typeof binding.file !== 'string' || !binding.file.trim()
48
+ || digest(JSON.stringify(binding.value)) !== binding.fingerprint
49
+ || binding.value.source !== run.story.path
50
+ || graphFingerprint(createRoleGraph(binding.value)) !== graphFingerprint(run.graph)) throw new Error('Role assignment or graph changed.');
51
+ }
52
+
53
+ export function assertRoleOutput(run, nodeId, output) {
54
+ if ((run.version !== 2 && run.kind !== 'role') || nodeId !== run.graph.nodes.at(-1).id) return;
55
+ const assignment = run.assignment.value;
56
+ if (assignment.role === 'developer' && (typeof output.producedRevision !== 'string' || !output.producedRevision.trim())) {
57
+ throw new Error('Developer submission needs producedRevision covering actual changes.');
58
+ }
59
+ if (assignment.role === 'reviewer' && (!['pass', 'needs_changes'].includes(output.verdict) || output.reviewedRevision !== assignment.targetRevision)) {
60
+ throw new Error('Reviewer submission needs verdict and the assigned reviewedRevision.');
61
+ }
62
+ }
@@ -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
+ }