@pazmo/ai-workflow-kit 3.1.1 → 4.0.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.
@@ -0,0 +1,92 @@
1
+ import { createTaskGraph, dependencyIds } from './task-graph.mjs';
2
+ import { assertRunState, blockedNodeIds, createRunState, selectReadyNodes } from './scheduler.mjs';
3
+
4
+ export function normalizeEvaluation(result) {
5
+ if (typeof result === 'boolean') return { passed: result };
6
+ if (!result || typeof result !== 'object' || typeof result.passed !== 'boolean') {
7
+ throw new Error('evaluateNode must return an explicit boolean or { passed, ... }.');
8
+ }
9
+ if (result.action !== undefined && !['fix', 'replan', 'human'].includes(result.action)) {
10
+ throw new Error('Evaluation action must be fix, replan or human.');
11
+ }
12
+ return result;
13
+ }
14
+
15
+ function validateOutput(node, output) {
16
+ if (node.outputContract === 'task-graph') {
17
+ if (!output || typeof output !== 'object') throw new Error('Node must return a task graph.');
18
+ return createTaskGraph(output);
19
+ }
20
+ return output;
21
+ }
22
+
23
+ export async function executeTaskGraph({
24
+ graph, runNode, evaluateNode, context = {},
25
+ runState = createRunState(graph), maxConcurrency = 1,
26
+ } = {}) {
27
+ if (typeof runNode !== 'function') throw new Error('runNode must be a function.');
28
+ if (evaluateNode !== undefined && typeof evaluateNode !== 'function') throw new Error('evaluateNode must be a function.');
29
+ if (!(Number.isSafeInteger(maxConcurrency) && maxConcurrency >= 1) && maxConcurrency !== Infinity) {
30
+ throw new Error('maxConcurrency must be a positive integer or Infinity.');
31
+ }
32
+ assertRunState(graph, runState);
33
+ if (Object.values(runState.nodes).some(node => node.status === 'running')) {
34
+ throw new Error('Interrupted running nodes require an explicit reset before resuming.');
35
+ }
36
+ const state = structuredClone(runState);
37
+ const waves = [];
38
+ const inFlight = new Map();
39
+
40
+ const execute = async node => {
41
+ const current = state.nodes[node.id];
42
+ try {
43
+ const dependencies = structuredClone(Object.fromEntries(
44
+ dependencyIds(graph, node.id).map(id => [id, state.nodes[id].output]),
45
+ ));
46
+ const input = { context: structuredClone(context), dependencies };
47
+ let output;
48
+ let evaluation;
49
+ if (node.operation === 'validate-graph') {
50
+ const values = Object.values(dependencies);
51
+ if (values.length !== 1 || !values[0] || typeof values[0] !== 'object') {
52
+ throw new Error('Graph validation requires one task graph input.');
53
+ }
54
+ output = createTaskGraph(values[0]);
55
+ evaluation = { passed: true };
56
+ } else {
57
+ output = validateOutput(node, await runNode(node, input));
58
+ evaluation = normalizeEvaluation(evaluateNode ? await evaluateNode(node, output, input) : undefined);
59
+ }
60
+ current.output = structuredClone(output);
61
+ current.evaluation = structuredClone(evaluation);
62
+ current.status = evaluation.passed ? 'completed' : 'failed';
63
+ if (!evaluation.passed) current.error = evaluation.feedback || 'Node evaluation failed.';
64
+ else delete current.error;
65
+ } catch (error) {
66
+ current.status = 'failed';
67
+ current.error = (error instanceof Error ? error.message : String(error)) || 'Node execution failed.';
68
+ current.evaluation = { passed: false, action: 'fix', feedback: current.error };
69
+ }
70
+ };
71
+
72
+ while (true) {
73
+ const ready = selectReadyNodes(graph, state, maxConcurrency);
74
+ if (ready.length) waves.push(ready.map(node => node.id));
75
+ for (const node of ready) {
76
+ state.nodes[node.id].status = 'running';
77
+ state.nodes[node.id].attempts += 1;
78
+ // Register the entire selection before any node can complete.
79
+ const promise = Promise.resolve().then(() => execute(node)).finally(() => inFlight.delete(node.id));
80
+ inFlight.set(node.id, promise);
81
+ }
82
+ if (inFlight.size === 0) break;
83
+ await Promise.race(inFlight.values());
84
+ }
85
+
86
+ const idsWith = status => graph.nodes.filter(node => state.nodes[node.id].status === status).map(node => node.id);
87
+ const completed = idsWith('completed');
88
+ return {
89
+ status: completed.length === graph.nodes.length ? 'completed' : 'failed',
90
+ runState: state, waves, completed, failed: idsWith('failed'), blocked: blockedNodeIds(graph, state),
91
+ };
92
+ }
@@ -0,0 +1,17 @@
1
+ export {
2
+ GraphValidationError,
3
+ assertAcyclic,
4
+ createTaskGraph,
5
+ dependencyIds,
6
+ descendantIds,
7
+ nodeById,
8
+ } from './task-graph.mjs';
9
+ export {
10
+ assertRunState,
11
+ blockedNodeIds,
12
+ createRunState,
13
+ getReadyNodes,
14
+ resetAffectedSubgraph,
15
+ } from './scheduler.mjs';
16
+ export { executeTaskGraph } from './executor.mjs';
17
+ export { createPlanningGraph } from './planning-graph.mjs';
@@ -0,0 +1,16 @@
1
+ import { createTaskGraph } from './task-graph.mjs';
2
+
3
+ export function createPlanningGraph() {
4
+ return createTaskGraph({
5
+ id: 'planning-graph',
6
+ nodes: [
7
+ { id: 'planner', access: 'read', outputContract: 'task-graph', description: 'Research as needed; produce tasks, dependencies and verification linked to the Story.' },
8
+ { id: 'review', access: 'read', outputContract: 'task-graph', description: 'Check scope, dependencies and evidence; return the corrected graph.' },
9
+ { id: 'validate-graph', access: 'read', operation: 'validate-graph', description: 'Deterministically reject malformed or cyclic plans.' },
10
+ ],
11
+ edges: [
12
+ { from: 'planner', to: 'review' },
13
+ { from: 'review', to: 'validate-graph' },
14
+ ],
15
+ });
16
+ }
@@ -0,0 +1,99 @@
1
+ import { dependencyIds, descendantIds, graphFingerprint, nodeById } from './task-graph.mjs';
2
+
3
+ const TERMINAL = new Set(['completed', 'failed']);
4
+
5
+ export function createRunState(graph) {
6
+ return {
7
+ graphId: graph.id,
8
+ fingerprint: graphFingerprint(graph),
9
+ nodes: Object.fromEntries(graph.nodes.map((node) => [node.id, {
10
+ status: 'pending',
11
+ attempts: 0,
12
+ revision: 0,
13
+ }])),
14
+ };
15
+ }
16
+
17
+ export function assertRunState(graph, runState) {
18
+ if (!runState || runState.graphId !== graph.id || !runState.nodes) {
19
+ throw new Error(`runState does not belong to graph: ${graph.id}`);
20
+ }
21
+ if (runState.fingerprint !== graphFingerprint(graph)) {
22
+ throw new Error('Graph fingerprint changed or missing; create a new run for a changed plan.');
23
+ }
24
+ if (Object.keys(runState.nodes).length !== graph.nodes.length) throw new Error('runState node set differs from graph.');
25
+ for (const node of graph.nodes) {
26
+ if (!Object.hasOwn(runState.nodes, node.id)) throw new Error(`runState is missing node: ${node.id}`);
27
+ const current = runState.nodes[node.id];
28
+ if (!current || !['pending', 'running', 'completed', 'failed'].includes(current.status)) {
29
+ throw new Error(`Invalid status for node: ${node.id}`);
30
+ }
31
+ if (!Number.isSafeInteger(current.attempts) || current.attempts < 0) throw new Error(`Invalid attempts for node: ${node.id}`);
32
+ if (!Number.isSafeInteger(current.revision) || current.revision < 0) throw new Error(`Invalid revision for node: ${node.id}`);
33
+ if (current.status === 'completed' && current.evaluation?.passed !== true) {
34
+ throw new Error(`Completed node has no passed evaluation: ${node.id}`);
35
+ }
36
+ if (current.status === 'failed' && current.evaluation?.passed !== false) {
37
+ throw new Error(`Failed node has no failed evaluation: ${node.id}`);
38
+ }
39
+ if (current.evaluation?.action !== undefined && !['fix', 'replan', 'human'].includes(current.evaluation.action)) {
40
+ throw new Error(`Invalid evaluation action: ${node.id}`);
41
+ }
42
+ if (['running', 'completed'].includes(current.status)
43
+ && dependencyIds(graph, node.id).some(id => runState.nodes[id]?.status !== 'completed')) {
44
+ throw new Error(`Node has unfinished dependencies: ${node.id}`);
45
+ }
46
+ }
47
+ return runState;
48
+ }
49
+
50
+ export function getReadyNodes(graph, runState) {
51
+ assertRunState(graph, runState);
52
+ return graph.nodes.filter((node) => {
53
+ const current = runState.nodes[node.id];
54
+ if (current.status !== 'pending') return false;
55
+ const dependencies = dependencyIds(graph, node.id);
56
+ return dependencies.every((dependencyId) => runState.nodes[dependencyId].status === 'completed');
57
+ });
58
+ }
59
+
60
+ // Unknown access is conservative: only explicitly read-only nodes may overlap.
61
+ export function selectReadyNodes(graph, runState, limit = 1) {
62
+ const running = graph.nodes.filter(node => runState.nodes[node.id].status === 'running');
63
+ if (running.some(node => node.access !== 'read')) return [];
64
+ const ready = getReadyNodes(graph, runState);
65
+ const available = limit - running.length;
66
+ if (available <= 0 || ready.length === 0) return [];
67
+ if (running.length === 0 && ready[0].access !== 'read') return [ready[0]];
68
+ return ready.filter(node => node.access === 'read').slice(0, available);
69
+ }
70
+
71
+ export function blockedNodeIds(graph, runState) {
72
+ assertRunState(graph, runState);
73
+
74
+ const memo = new Map();
75
+ const hasFailedAncestor = (nodeId) => {
76
+ if (memo.has(nodeId)) return memo.get(nodeId);
77
+ const blocked = dependencyIds(graph, nodeId).some((dependencyId) => (
78
+ runState.nodes[dependencyId].status === 'failed' || hasFailedAncestor(dependencyId)
79
+ ));
80
+ memo.set(nodeId, blocked);
81
+ return blocked;
82
+ };
83
+
84
+ return graph.nodes.filter((node) => {
85
+ const current = runState.nodes[node.id];
86
+ return !TERMINAL.has(current.status) && hasFailedAncestor(node.id);
87
+ }).map((node) => node.id);
88
+ }
89
+
90
+ export function resetAffectedSubgraph(graph, runState, nodeIds) {
91
+ assertRunState(graph, runState);
92
+ const affected = descendantIds(graph, nodeIds);
93
+ const next = structuredClone(runState);
94
+ for (const nodeId of affected) {
95
+ nodeById(graph, nodeId);
96
+ next.nodes[nodeId] = { status: 'pending', attempts: runState.nodes[nodeId].attempts, revision: runState.nodes[nodeId].revision + 1 };
97
+ }
98
+ return next;
99
+ }
@@ -0,0 +1,76 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+
5
+ export const digest = value => createHash('sha256').update(value).digest('hex');
6
+
7
+ export async function projectFile(root, relative) {
8
+ if (typeof relative !== 'string' || !relative || path.isAbsolute(relative)) {
9
+ throw new Error('Use a project-relative file path.');
10
+ }
11
+ const file = path.resolve(root, relative);
12
+ const rel = path.relative(root, file);
13
+ if (!rel || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
14
+ throw new Error('Path escapes project root.');
15
+ }
16
+ let current = root;
17
+ for (const part of rel.split(path.sep)) {
18
+ current = path.join(current, part);
19
+ try {
20
+ const stat = await fs.lstat(current);
21
+ if (stat.isSymbolicLink()) throw new Error('Refusing symlink in graph path.');
22
+ } catch (error) {
23
+ if (error.code !== 'ENOENT') throw error;
24
+ }
25
+ }
26
+ return file;
27
+ }
28
+
29
+ export async function readProjectFile(root, relative) {
30
+ return fs.readFile(await projectFile(root, relative), 'utf8');
31
+ }
32
+
33
+ export async function readJson(root, relative) {
34
+ return JSON.parse(await readProjectFile(root, relative));
35
+ }
36
+
37
+ // One controller per run. A crashed writer leaves its lock for explicit inspection.
38
+ // No stale-lock guessing and no in-place JSON truncation.
39
+ export async function updateRun(root, relative, transform, { create = false } = {}) {
40
+ const file = await projectFile(root, relative);
41
+ const lock = await projectFile(root, `${relative}.lock`);
42
+ await fs.mkdir(path.dirname(file), { recursive: true });
43
+ let handle;
44
+ try { handle = await fs.open(lock, 'wx', 0o600); }
45
+ catch (error) {
46
+ if (error.code === 'EEXIST') throw new Error('Run is locked; inspect the writer before removing its .lock file.');
47
+ throw error;
48
+ }
49
+ const temporary = `${file}.${randomUUID()}.tmp`;
50
+ try {
51
+ await handle.writeFile(JSON.stringify({ pid: process.pid, started: new Date().toISOString() }));
52
+ let previous;
53
+ if (create) {
54
+ try { await fs.lstat(file); throw new Error('Run file already exists; choose a new run path.'); }
55
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
56
+ } else previous = await readJson(root, relative);
57
+ const next = await transform(previous);
58
+ await fs.writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
59
+ if (create) {
60
+ // Exclusive publication also protects a file created after the initial check.
61
+ await fs.link(temporary, file);
62
+ } else {
63
+ // Refuse external edits made during validation, even if they ignored our lock.
64
+ if (JSON.stringify(await readJson(root, relative)) !== JSON.stringify(previous)) {
65
+ throw new Error('Run changed during update; retry from fresh status.');
66
+ }
67
+ await projectFile(root, relative);
68
+ await fs.rename(temporary, file);
69
+ }
70
+ return next;
71
+ } finally {
72
+ await fs.rm(temporary, { force: true });
73
+ await handle.close();
74
+ await fs.unlink(lock);
75
+ }
76
+ }
@@ -0,0 +1,125 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export class GraphValidationError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'GraphValidationError';
7
+ }
8
+ }
9
+
10
+ function requireNonEmptyString(value, label) {
11
+ if (typeof value !== 'string' || value.trim() === '') {
12
+ throw new GraphValidationError(`${label} must be a non-empty string.`);
13
+ }
14
+ return value.trim();
15
+ }
16
+
17
+ export function createTaskGraph({ id = 'task-graph', nodes = [], edges = [] } = {}) {
18
+ const graphId = requireNonEmptyString(id, 'graph.id');
19
+ if (!Array.isArray(nodes) || nodes.length === 0) {
20
+ throw new GraphValidationError('graph.nodes must contain at least one node.');
21
+ }
22
+ if (!Array.isArray(edges)) {
23
+ throw new GraphValidationError('graph.edges must be an array.');
24
+ }
25
+
26
+ const nodeIds = new Set();
27
+ const normalizedNodes = nodes.map((node, index) => {
28
+ if (!node || typeof node !== 'object' || Array.isArray(node)) {
29
+ throw new GraphValidationError(`graph.nodes[${index}] must be an object.`);
30
+ }
31
+ const nodeId = requireNonEmptyString(node.id, `graph.nodes[${index}].id`);
32
+ if (['__proto__', 'constructor', 'prototype'].includes(nodeId)) {
33
+ throw new GraphValidationError(`reserved node id: ${nodeId}`);
34
+ }
35
+ if (node.access !== undefined && !['read', 'write'].includes(node.access)) {
36
+ throw new GraphValidationError(`invalid access for node: ${nodeId}`);
37
+ }
38
+ if (nodeIds.has(nodeId)) {
39
+ throw new GraphValidationError(`duplicate node id: ${nodeId}`);
40
+ }
41
+ nodeIds.add(nodeId);
42
+ return Object.freeze({ ...node, id: nodeId });
43
+ });
44
+
45
+ const edgeKeys = new Set();
46
+ const normalizedEdges = edges.map((edge, index) => {
47
+ if (!edge || typeof edge !== 'object' || Array.isArray(edge)) {
48
+ throw new GraphValidationError(`graph.edges[${index}] must be an object.`);
49
+ }
50
+ const from = requireNonEmptyString(edge.from, `graph.edges[${index}].from`);
51
+ const to = requireNonEmptyString(edge.to, `graph.edges[${index}].to`);
52
+ if (!nodeIds.has(from)) throw new GraphValidationError(`edge references missing node: ${from}`);
53
+ if (!nodeIds.has(to)) throw new GraphValidationError(`edge references missing node: ${to}`);
54
+ if (from === to) throw new GraphValidationError(`self edge is not allowed: ${from}`);
55
+ const key = JSON.stringify([from, to]);
56
+ if (edgeKeys.has(key)) throw new GraphValidationError(`duplicate edge: ${from} -> ${to}`);
57
+ edgeKeys.add(key);
58
+ return Object.freeze({ from, to });
59
+ });
60
+
61
+ const graph = Object.freeze({
62
+ id: graphId,
63
+ nodes: Object.freeze(normalizedNodes),
64
+ edges: Object.freeze(normalizedEdges),
65
+ });
66
+ assertAcyclic(graph);
67
+ return graph;
68
+ }
69
+
70
+ export function nodeById(graph, nodeId) {
71
+ const node = graph.nodes.find((candidate) => candidate.id === nodeId);
72
+ if (!node) throw new GraphValidationError(`unknown node: ${nodeId}`);
73
+ return node;
74
+ }
75
+
76
+ export function graphFingerprint(graph) {
77
+ return createHash('sha256').update(JSON.stringify(graph)).digest('hex');
78
+ }
79
+
80
+ export function dependencyIds(graph, nodeId) {
81
+ nodeById(graph, nodeId);
82
+ return graph.edges.filter((edge) => edge.to === nodeId).map((edge) => edge.from);
83
+ }
84
+
85
+ export function descendantIds(graph, nodeIds) {
86
+ const seeds = new Set(nodeIds);
87
+ for (const nodeId of seeds) nodeById(graph, nodeId);
88
+
89
+ const descendants = new Set(seeds);
90
+ const queue = [...seeds];
91
+ while (queue.length) {
92
+ const current = queue.shift();
93
+ for (const edge of graph.edges) {
94
+ if (edge.from !== current || descendants.has(edge.to)) continue;
95
+ descendants.add(edge.to);
96
+ queue.push(edge.to);
97
+ }
98
+ }
99
+ return descendants;
100
+ }
101
+
102
+ export function assertAcyclic(graph) {
103
+ const indegree = new Map(graph.nodes.map((node) => [node.id, 0]));
104
+ const outgoing = new Map(graph.nodes.map((node) => [node.id, []]));
105
+ for (const edge of graph.edges) {
106
+ indegree.set(edge.to, indegree.get(edge.to) + 1);
107
+ outgoing.get(edge.from).push(edge.to);
108
+ }
109
+
110
+ const queue = graph.nodes.filter((node) => indegree.get(node.id) === 0).map((node) => node.id);
111
+ let visited = 0;
112
+ while (queue.length) {
113
+ const current = queue.shift();
114
+ visited += 1;
115
+ for (const next of outgoing.get(current)) {
116
+ indegree.set(next, indegree.get(next) - 1);
117
+ if (indegree.get(next) === 0) queue.push(next);
118
+ }
119
+ }
120
+
121
+ if (visited !== graph.nodes.length) {
122
+ throw new GraphValidationError('graph must be a DAG; a dependency cycle was found.');
123
+ }
124
+ return graph;
125
+ }
@@ -0,0 +1,120 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createTaskGraph, dependencyIds, descendantIds, nodeById } from './task-graph.mjs';
3
+ import { assertRunState, blockedNodeIds, createRunState, selectReadyNodes } from './scheduler.mjs';
4
+ import { digest, readProjectFile } from './storage.mjs';
5
+
6
+ export const MAX_ATTEMPTS = 3;
7
+ const REVIEW = 'workflow-review';
8
+ const VERIFY = 'workflow-verify';
9
+
10
+ export function storyContract(text) {
11
+ // Progress metadata is mutable; requirements and human decisions are not.
12
+ const content = text.split(/\r?\n/).filter(line => !/^(?:Status:|Understanding gate \(G[134]\):|G4:)/i.test(line)).join('\n').trim();
13
+ const sectionIds = (heading, prefix) => {
14
+ const body = text.match(new RegExp(`^##\\s+${heading}\\s*$([\\s\\S]*?)(?=^##\\s|$(?![\\s\\S]))`, 'im'))?.[1] ?? '';
15
+ return [...body.matchAll(new RegExp(`^[-*]\\s+(${prefix}-?\\d+)\\b`, 'gim'))].map(match => match[1].toUpperCase());
16
+ };
17
+ return { fingerprint: digest(content), ids: [...sectionIds('MUST', 'M'), ...sectionIds('Verify', 'V')] };
18
+ }
19
+
20
+ export function createWorkflowGraph(plan, ids) {
21
+ const draft = plan ?? { id: 'delivery', nodes: [{ id: 'implement', description: 'Implement the approved Story, demonstrate RED/GREEN and simplify while green.', access: 'write', covers: ids, verify: 'Run related checks and record the changed files and evidence.' }], edges: [] };
22
+ const base = createTaskGraph(draft);
23
+ const covered = new Set();
24
+ for (const node of base.nodes) {
25
+ if ([REVIEW, VERIFY].includes(node.id)) throw new Error(`Reserved workflow node: ${node.id}`);
26
+ for (const field of ['description', 'verify']) {
27
+ if (typeof node[field] !== 'string' || !node[field].trim()) throw new Error(`Node ${node.id} needs ${field}.`);
28
+ }
29
+ if (!['read', 'write'].includes(node.access)) throw new Error(`Node ${node.id} needs read/write access.`);
30
+ if (!Array.isArray(node.covers) || !node.covers.length) throw new Error(`Node ${node.id} needs Story M/V references.`);
31
+ for (const id of node.covers) {
32
+ if (!ids.includes(id)) throw new Error(`Unknown Story reference: ${id}`);
33
+ covered.add(id);
34
+ }
35
+ }
36
+ for (const id of ids) if (!covered.has(id)) throw new Error(`Plan does not cover Story ${id}.`);
37
+ const sinks = base.nodes.filter(node => !base.edges.some(edge => edge.from === node.id));
38
+ return createTaskGraph({ id: base.id, nodes: [
39
+ ...base.nodes,
40
+ { id: REVIEW, access: 'read', covers: ids, description: 'Review the final diff against the Story, including failure paths.', verify: 'Record findings and evidence; fail with the corrective action if changes are needed.' },
41
+ { id: VERIFY, access: 'read', covers: ids, description: 'Run fresh verification after review fixes; prepare raw evidence for G4.', verify: 'Record actual commands, exit codes, changed-file scope and unproven boundaries.' },
42
+ ], edges: [...base.edges, ...sinks.map(node => ({ from: node.id, to: REVIEW })), { from: REVIEW, to: VERIFY }] });
43
+ }
44
+
45
+ export function newWorkflowRun(graph, story, contract) {
46
+ return { version: 1, runId: randomUUID(), graph, state: createRunState(graph), story: { path: story, fingerprint: contract.fingerprint }, history: [] };
47
+ }
48
+
49
+ export function assertWorkflowRun(run) {
50
+ if (run?.version !== 1 || typeof run.runId !== 'string' || !run.runId.trim()
51
+ || !run.graph || !run.story?.path || !Array.isArray(run.history)) throw new Error('Invalid workflow run.');
52
+ const graph = createTaskGraph(run.graph);
53
+ assertRunState(graph, run.state);
54
+ if (!graph.nodes.some(node => node.id === REVIEW) || !graph.nodes.some(node => node.id === VERIFY)) throw new Error('Workflow review/verification nodes are missing.');
55
+ if (!dependencyIds(graph, VERIFY).includes(REVIEW)
56
+ || graph.nodes.some(node => node.id !== VERIFY && !descendantIds(graph, [node.id]).has(VERIFY))) {
57
+ throw new Error('Every workflow node must precede final verification.');
58
+ }
59
+ return graph;
60
+ }
61
+
62
+ export function taskToken(run, nodeId) {
63
+ return digest(JSON.stringify([run.runId, run.state.fingerprint, run.story.fingerprint, nodeId,
64
+ run.state.nodes[nodeId].attempts, run.state.nodes[nodeId].revision,
65
+ dependencyIds(run.graph, nodeId).map(id => run.state.nodes[id]) ]));
66
+ }
67
+
68
+ export async function evidenceHashes(root, evidence) {
69
+ if (!Array.isArray(evidence) || evidence.length === 0) throw new Error('Node output requires evidence files.');
70
+ const hashes = {};
71
+ for (const file of evidence) {
72
+ const body = await readProjectFile(root, file);
73
+ if (!body.trim()) throw new Error(`Empty evidence file: ${file}`);
74
+ Object.defineProperty(hashes, file, { value: digest(body), enumerable: true, configurable: true });
75
+ }
76
+ return hashes;
77
+ }
78
+
79
+ export async function checkRunEvidence(root, run) {
80
+ for (const node of run.graph.nodes) {
81
+ const state = run.state.nodes[node.id];
82
+ if (!['completed', 'failed'].includes(state.status)) continue;
83
+ if (typeof state.output?.summary !== 'string' || !state.output.summary.trim()) throw new Error(`Missing output summary: ${node.id}`);
84
+ const actual = await evidenceHashes(root, state.output.evidence);
85
+ if (JSON.stringify(actual) !== JSON.stringify(state.evidenceHashes)) throw new Error(`Node evidence changed: ${node.id}; reset affected work.`);
86
+ }
87
+ }
88
+
89
+ export function workflowStatus(run) {
90
+ const graph = assertWorkflowRun(run);
91
+ const nodes = Object.entries(run.state.nodes);
92
+ const failed = nodes.filter(([, state]) => state.status === 'failed').map(([id, state]) => ({ id, action: state.evaluation?.action ?? 'fix', feedback: state.error }));
93
+ const running = nodes.filter(([, state]) => state.status === 'running').map(([id]) => id);
94
+ const exhausted = nodes.some(([, state]) => ['pending', 'failed'].includes(state.status) && state.attempts >= MAX_ATTEMPTS);
95
+ let action;
96
+ if (exhausted) action = 'stop';
97
+ else if (failed.some(node => node.action === 'human')) action = 'human';
98
+ else if (failed.some(node => node.action === 'replan')) action = 'replan';
99
+ else if (failed.length) action = 'fix';
100
+ else if (nodes.every(([, state]) => state.status === 'completed')) action = 'g4';
101
+ else action = 'execute';
102
+ const ready = ['execute', 'fix'].includes(action) ? selectReadyNodes(graph, run.state, 4).map(node => taskInput(run, node.id)) : [];
103
+ if (action === 'execute' && ready.length === 0 && running.length) action = 'wait';
104
+ return { runId: run.runId, action, ready, running, failed, blocked: blockedNodeIds(graph, run.state),
105
+ completed: nodes.filter(([, state]) => state.status === 'completed').map(([id]) => id),
106
+ gate: 'Graph evidence never approves G3/G4. G4 remains human-owned.', maxAttempts: MAX_ATTEMPTS };
107
+ }
108
+
109
+ export function taskInput(run, nodeId) {
110
+ return { ...nodeById(run.graph, nodeId), token: taskToken(run, nodeId), input: {
111
+ story: run.story.path,
112
+ dependencies: Object.fromEntries(dependencyIds(run.graph, nodeId).map(id => [id, run.state.nodes[id].output])),
113
+ } };
114
+ }
115
+
116
+ export function requireReady(run, nodeId, token) {
117
+ nodeById(run.graph, nodeId);
118
+ if (!workflowStatus(run).ready.some(node => node.id === nodeId)) throw new Error(`Node is not ready: ${nodeId}`);
119
+ if (token !== taskToken(run, nodeId)) throw new Error('Stale or missing task token; read fresh status.');
120
+ }
@@ -8,6 +8,7 @@ const PATHS = Object.freeze([
8
8
  'AGENTS.md', 'CLAUDE.md', '.agents/skills/workflow', '.claude/skills/workflow',
9
9
  'templates/ai-workflow/STORY.md', 'templates/ai-workflow/TASK.md',
10
10
  '.ai-workflow/bin/check.mjs', '.ai-workflow/config.json',
11
+ '.ai-workflow/bin/graph.mjs', '.ai-workflow/graph',
11
12
  ]);
12
13
  const JOURNAL = '.ai-workflow-install';
13
14
 
package/src/install.mjs CHANGED
@@ -17,9 +17,11 @@ import { installTransaction } from './install-transaction.mjs';
17
17
  const modulePackageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
18
18
  const CONFIG_PATH = '.ai-workflow/config.json';
19
19
  const CHECKER_PATH = '.ai-workflow/bin/check.mjs';
20
+ const GRAPH_PATH = '.ai-workflow/graph';
20
21
  const TEMPLATE_PATHS = Object.freeze([
21
22
  ['skills/workflow/assets/STORY.md', 'templates/ai-workflow/STORY.md'],
22
23
  ['skills/workflow/assets/TASK.md', 'templates/ai-workflow/TASK.md'],
24
+ ['assets/graph.mjs', '.ai-workflow/bin/graph.mjs'],
23
25
  ]);
24
26
 
25
27
  async function exists(file) {
@@ -181,6 +183,11 @@ async function installPrepared({
181
183
  }));
182
184
  }
183
185
 
186
+ const graphPlan = await inspectManagedTree({
187
+ source: path.join(packageRoot, 'src/graph'), target: projectPath(root, GRAPH_PATH),
188
+ previousHash: previous?.managedTrees?.[GRAPH_PATH], relative: GRAPH_PATH,
189
+ });
190
+
184
191
  const instructionPlans = new Map();
185
192
  for (const [host, hostConfig] of Object.entries(HOSTS)) {
186
193
  const file = projectPath(root, hostConfig.instructionFile);
@@ -212,6 +219,11 @@ async function installPrepared({
212
219
  }
213
220
 
214
221
  const managedTrees = {};
222
+ const graphResult = await applyManagedTree(graphPlan);
223
+ managedTrees[GRAPH_PATH] = graphResult.hash;
224
+ changed = graphResult.changed || changed;
225
+ if (graphResult.changed) installed.push(GRAPH_PATH);
226
+ if (graphResult.preserved) preserved.push(GRAPH_PATH);
215
227
  for (const host of selectedHosts) {
216
228
  const relative = HOSTS[host].skillDir;
217
229
  const result = await applyManagedTree(treePlans.get(host));
@@ -313,6 +325,10 @@ async function removePrepared({ root = process.cwd() } = {}) {
313
325
  if (removed) await removeEmptyParents(projectPath(root, relative), root);
314
326
  }
315
327
 
328
+ const graphRemoved = await removeTreeIfUnchanged(root, GRAPH_PATH, config?.managedTrees?.[GRAPH_PATH], preserved);
329
+ changed = graphRemoved || changed;
330
+ if (graphRemoved) await removeEmptyParents(projectPath(root, GRAPH_PATH), root);
331
+
316
332
  for (const [, targetRelative] of TEMPLATE_PATHS) {
317
333
  const expectedHash = config?.managedFiles?.[targetRelative]
318
334
  ?? config?.templateHashes?.[targetRelative];
@@ -8,7 +8,9 @@ export const MANAGED_BLOCK = `${START_MARKER}
8
8
  - Keep one concise canonical Story contract: Goal, Domain, MUST, SHOULD, OUT, Decisions, Verify.
9
9
  - Ask only blocking behavior questions; label safe defaults \`ASSUMED\` instead of silently inventing scope.
10
10
  - Keep Tasks at most 30 non-empty lines and reference Story M/V IDs; HOW belongs to the repository-grounded plan.
11
- - Use Compound Engineering when available: normal work \`ce-plan → ce-work → ce-simplify-code → ce-code-review\`; simplify after related tests pass, revalidate edits before G4. Follow the workflow execution reference for direct fallback; high-risk work adds a human plan gate.
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
+ - 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.
12
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.
13
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.
14
16
  ${END_MARKER}`;