@pazmo/ai-workflow-kit 3.1.1 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.ko.md +206 -0
- package/README.md +130 -223
- package/assets/graph.mjs +10 -0
- package/assets/readme/workflow-en.png +0 -0
- package/assets/readme/workflow-en.svg +41 -0
- package/assets/readme/workflow-ko.png +0 -0
- package/assets/readme/workflow-ko.svg +41 -0
- package/bin/ai-workflow-kit.mjs +38 -2
- package/package.json +9 -3
- package/skills/workflow/EVALS.md +45 -0
- package/skills/workflow/SKILL.md +5 -5
- package/skills/workflow/references/execution.md +31 -5
- package/skills/workflow/references/graph-engineering.md +120 -0
- package/skills/workflow/references/intake.md +6 -2
- package/skills/workflow/references/role-graphs.md +136 -0
- package/skills/workflow/references/skill-integration.md +55 -0
- package/skills/workflow/references/understanding-gate.md +2 -0
- package/src/git-visibility.mjs +19 -12
- package/src/graph/cli.mjs +157 -0
- package/src/graph/executor.mjs +92 -0
- package/src/graph/index.mjs +17 -0
- package/src/graph/planning-graph.mjs +16 -0
- package/src/graph/roles.mjs +62 -0
- package/src/graph/scheduler.mjs +99 -0
- package/src/graph/storage.mjs +76 -0
- package/src/graph/task-graph.mjs +125 -0
- package/src/graph/workflow.mjs +153 -0
- package/src/install-transaction.mjs +1 -0
- package/src/install.mjs +16 -0
- package/src/managed-block.mjs +3 -1
|
@@ -4,6 +4,8 @@ This gate checks ownership of the actual implementation. It is not a generated s
|
|
|
4
4
|
|
|
5
5
|
## Predict before reveal
|
|
6
6
|
|
|
7
|
+
Before presenting G4, run `node .ai-workflow/bin/graph.mjs status <run.json>` and require `action: g4`. Graph readiness only establishes recorded workflow evidence; it never supplies the human answer or approves this gate. For work completed before graph installation, initialize a run and record freshly checked implementation/review/verification evidence before continuing.
|
|
8
|
+
|
|
7
9
|
1. Gather the approved Story, test results, review findings, and the **raw diff** or mechanical diff/stat. Show only that evidence; do not explain the solution yet.
|
|
8
10
|
2. Ask in the user's language: “이 변경 뒤에 사용자가 겪는 일이 어떻게 달라질까요? 꼭 지켜야 할 규칙과 실패했을 때의 동작은 무엇인가요? 어떤 테스트가 그걸 확인했고, 아직 확인하지 못한 것은 무엇인가요?” **END THE TURN.**
|
|
9
11
|
3. Only after the human answers, **compare** the answer with the Story, diff, runtime flow, and tests.
|
package/src/git-visibility.mjs
CHANGED
|
@@ -34,19 +34,26 @@ function git(args, cwd) {
|
|
|
34
34
|
* { status: 'ignored', source } source is "<file>:<line>:<pattern>"
|
|
35
35
|
* { status: 'no-git' } no git, or not a work tree — nothing to say
|
|
36
36
|
*/
|
|
37
|
-
export async function checkerVisibility(root) {
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const tracked = await git(['ls-files', '--error-unmatch', '--', CHECKER_PATH], root);
|
|
42
|
-
if (tracked.code === 0) return { status: 'tracked' };
|
|
43
|
-
|
|
44
|
-
const ignored = await git(['check-ignore', '-v', '--', CHECKER_PATH], root);
|
|
45
|
-
if (ignored.code !== 0) return { status: 'visible' };
|
|
37
|
+
export async function checkerVisibility(root, relative = CHECKER_PATH) {
|
|
38
|
+
const { file, ...visibility } = (await fileVisibilities(root, [relative]))[0];
|
|
39
|
+
return visibility;
|
|
40
|
+
}
|
|
46
41
|
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
42
|
+
export async function fileVisibilities(root, files) {
|
|
43
|
+
const inside = await git(['rev-parse', '--is-inside-work-tree'], root);
|
|
44
|
+
if (inside.code !== 0 || inside.stdout.trim() !== 'true') return files.map(file => ({ file, status: 'no-git' }));
|
|
45
|
+
const [tracked, ignored] = await Promise.all([
|
|
46
|
+
git(['ls-files', '--', ...files], root), git(['check-ignore', '-v', '--', ...files], root),
|
|
47
|
+
]);
|
|
48
|
+
const trackedFiles = new Set(tracked.stdout.trim().split('\n'));
|
|
49
|
+
const sources = new Map();
|
|
50
|
+
for (const line of ignored.stdout.trim().split('\n')) {
|
|
51
|
+
const [source, file] = line.split('\t');
|
|
52
|
+
if (file && !source.split(':').slice(2).join(':').startsWith('!')) sources.set(file, source);
|
|
53
|
+
}
|
|
54
|
+
return files.map(file => trackedFiles.has(file) ? { file, status: 'tracked' }
|
|
55
|
+
: sources.has(file) ? { file, status: 'ignored', source: sources.get(file) }
|
|
56
|
+
: { file, status: 'visible' });
|
|
50
57
|
}
|
|
51
58
|
|
|
52
59
|
export function ignoredCheckerAdvice({ source }) {
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { normalizeEvaluation } from './executor.mjs';
|
|
4
|
+
import { descendantIds, nodeById } from './task-graph.mjs';
|
|
5
|
+
import { resetAffectedSubgraph } from './scheduler.mjs';
|
|
6
|
+
import { digest, readJson, readProjectFile, updateRun } from './storage.mjs';
|
|
7
|
+
import { assertAssignment, assertRoleOutput, createRoleGraph } from './roles.mjs';
|
|
8
|
+
import {
|
|
9
|
+
MAX_ATTEMPTS, MAX_QUESTIONS, assertWorkflowRun, checkRunEvidence, createWorkflowGraph, evidenceHashes,
|
|
10
|
+
newWorkflowRun, requireReady, revisionToken, storyContract, taskInput, taskToken, workflowStatus,
|
|
11
|
+
} from './workflow.mjs';
|
|
12
|
+
|
|
13
|
+
export const GRAPH_HELP = `Graph commands (run from project root):
|
|
14
|
+
graph.mjs init <plan.json|-> <run.json> <story.md>
|
|
15
|
+
graph.mjs init-role <assignment.json> <run.json>
|
|
16
|
+
graph.mjs status <run.json>
|
|
17
|
+
graph.mjs start <run.json> <node-id> <ready-token>
|
|
18
|
+
graph.mjs record <run.json> <node-id> <result.json>
|
|
19
|
+
graph.mjs reset <run.json> <node-id> <reason>
|
|
20
|
+
graph.mjs question <run.json> <node-id> <question.json>
|
|
21
|
+
graph.mjs answer <run.json> <node-id> <answer.json>
|
|
22
|
+
graph.mjs feedback <run.json> <node-id> <feedback.json>
|
|
23
|
+
Use - for a minimal plan. The host executes work; this tool validates state/evidence and routes the next action.`;
|
|
24
|
+
|
|
25
|
+
export async function runGraphCommand(args, { root = process.cwd(), checkArtifact, checkGate } = {}) {
|
|
26
|
+
root = await fs.realpath(root);
|
|
27
|
+
const [command, ...values] = args;
|
|
28
|
+
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 };
|
|
30
|
+
if (!Object.hasOwn(counts, command) || values.length !== counts[command]) throw new Error(GRAPH_HELP);
|
|
31
|
+
|
|
32
|
+
const loadStory = async file => {
|
|
33
|
+
const text = await readProjectFile(root, file);
|
|
34
|
+
if (!/^Status:\s*(Approved|Delivered)\s*$/im.test(text)) throw new Error('Story must be Approved with accepted G1.');
|
|
35
|
+
if (typeof checkArtifact !== 'function' || typeof checkGate !== 'function') throw new Error('Story checker is required.');
|
|
36
|
+
for (const result of [await checkArtifact({ root, file, kind: 'story' }), await checkGate({ root, file, gate: 'G1' })]) {
|
|
37
|
+
if (!result.ok) throw new Error(result.errors.join('\n'));
|
|
38
|
+
}
|
|
39
|
+
return storyContract(text);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const loadSource = async assignment => {
|
|
43
|
+
if (assignment.role !== 'pm') return loadStory(assignment.source);
|
|
44
|
+
const text = await readProjectFile(root, assignment.source);
|
|
45
|
+
if (!text.trim()) throw new Error('PM source request must not be empty.');
|
|
46
|
+
return { fingerprint: digest(text), ids: [] };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const validate = async (run, { evidence = true } = {}) => {
|
|
50
|
+
assertWorkflowRun(run);
|
|
51
|
+
if (run.version === 2) {
|
|
52
|
+
const current = await readJson(root, run.assignment.file);
|
|
53
|
+
if (digest(JSON.stringify(current)) !== run.assignment.fingerprint) throw new Error('Assignment changed; create a new run.');
|
|
54
|
+
}
|
|
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);
|
|
57
|
+
if (contract.fingerprint !== run.story.fingerprint) throw new Error('Story requirements changed; replan in a new run.');
|
|
58
|
+
if (evidence) await checkRunEvidence(root, run);
|
|
59
|
+
return run;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
if (command === 'init-role') {
|
|
63
|
+
const [file, runFile] = values;
|
|
64
|
+
const value = await readJson(root, file);
|
|
65
|
+
assertAssignment(value);
|
|
66
|
+
const contract = await loadSource(value);
|
|
67
|
+
assertAssignment(value, contract.ids);
|
|
68
|
+
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);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (command === 'init') {
|
|
77
|
+
const [planFile, runFile, story] = values;
|
|
78
|
+
const contract = await loadStory(story);
|
|
79
|
+
const plan = planFile === '-' ? undefined : await readJson(root, planFile);
|
|
80
|
+
const graph = createWorkflowGraph(plan, contract.ids);
|
|
81
|
+
const run = await updateRun(root, runFile, async () => newWorkflowRun(graph, story, contract), { create: true });
|
|
82
|
+
return workflowStatus(run);
|
|
83
|
+
}
|
|
84
|
+
if (command === 'status') return workflowStatus(await validate(await readJson(root, values[0])));
|
|
85
|
+
|
|
86
|
+
const [runFile, nodeId, argument] = values;
|
|
87
|
+
const run = await updateRun(root, runFile, async previous => {
|
|
88
|
+
// Work on a copy so the optimistic edit check still compares original bytes/data.
|
|
89
|
+
const next = structuredClone(previous);
|
|
90
|
+
await validate(next, { evidence: command !== 'reset' });
|
|
91
|
+
nodeById(next.graph, nodeId);
|
|
92
|
+
if (command === 'start') {
|
|
93
|
+
requireReady(next, nodeId, argument);
|
|
94
|
+
next.state.nodes[nodeId].status = 'running';
|
|
95
|
+
next.state.nodes[nodeId].attempts += 1;
|
|
96
|
+
next.history.push({ event: 'start', nodeId, at: new Date().toISOString() });
|
|
97
|
+
} else if (command === 'record') {
|
|
98
|
+
if (next.question?.nodeId === nodeId) throw new Error('Answer the pending question before recording this node.');
|
|
99
|
+
const result = await readJson(root, argument);
|
|
100
|
+
if (result.token !== taskToken(next, nodeId)) throw new Error('Stale or missing task token; read fresh status.');
|
|
101
|
+
if (next.state.nodes[nodeId].status !== 'running') throw new Error(`Node must be started before recording: ${nodeId}`);
|
|
102
|
+
if (typeof result.output?.summary !== 'string' || !result.output.summary.trim()) throw new Error('Node output needs a summary.');
|
|
103
|
+
const evaluation = normalizeEvaluation(result.evaluation);
|
|
104
|
+
if (evaluation.passed) assertRoleOutput(next, nodeId, result.output);
|
|
105
|
+
if (!evaluation.passed && (typeof evaluation.feedback !== 'string' || !evaluation.feedback.trim())) throw new Error('Failed evaluation needs feedback.');
|
|
106
|
+
const hashes = await evidenceHashes(root, result.output.evidence);
|
|
107
|
+
const current = next.state.nodes[nodeId];
|
|
108
|
+
next.state.nodes[nodeId] = {
|
|
109
|
+
status: evaluation.passed ? 'completed' : 'failed', attempts: current.attempts, revision: current.revision,
|
|
110
|
+
output: result.output, evaluation, evidenceHashes: hashes,
|
|
111
|
+
...(!evaluation.passed ? { error: evaluation.feedback } : {}),
|
|
112
|
+
};
|
|
113
|
+
next.history.push({ event: 'record', nodeId, at: new Date().toISOString(), result: next.state.nodes[nodeId] });
|
|
114
|
+
} else if (command === 'question') {
|
|
115
|
+
if (next.question || ['human', 'replan', 'stop'].includes(workflowStatus(next).action)) throw new Error('Resolve the pending question or blocking decision first.');
|
|
116
|
+
const request = await readJson(root, argument);
|
|
117
|
+
if (next.state.nodes[nodeId].status !== 'running' || request.token !== taskToken(next, nodeId)) throw new Error('Question requires the current running task token.');
|
|
118
|
+
if (typeof request.text !== 'string' || !request.text.trim()) throw new Error('Question needs text.');
|
|
119
|
+
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
|
+
next.state.nodes[nodeId].revision += 1;
|
|
121
|
+
next.question = { id: randomUUID(), nodeId, text: request.text, token: taskToken(next, nodeId) };
|
|
122
|
+
next.history.push({ event: 'question', nodeId, questionId: next.question.id, text: request.text, at: new Date().toISOString() });
|
|
123
|
+
} else if (command === 'answer') {
|
|
124
|
+
const reply = await readJson(root, argument);
|
|
125
|
+
const question = next.question;
|
|
126
|
+
if (!question || question.nodeId !== nodeId || reply.questionId !== question.id || reply.token !== question.token) throw new Error('Stale or mismatched question answer.');
|
|
127
|
+
if (workflowStatus(next).action !== 'question') throw new Error('Resolve the blocking decision before resuming this task.');
|
|
128
|
+
if (typeof reply.text !== 'string' || !reply.text.trim()) throw new Error('Answer needs text.');
|
|
129
|
+
const hashes = await evidenceHashes(root, reply.evidence);
|
|
130
|
+
next.history.push({ event: 'answer', nodeId, questionId: question.id, text: reply.text, evidence: reply.evidence, evidenceHashes: hashes, at: new Date().toISOString() });
|
|
131
|
+
delete next.question;
|
|
132
|
+
next.state.nodes[nodeId].revision += 1;
|
|
133
|
+
} else {
|
|
134
|
+
if (!argument.trim()) throw new Error('Reset requires a reason.');
|
|
135
|
+
if (next.question) throw new Error('Answer the pending question before resetting work.');
|
|
136
|
+
const status = workflowStatus(next);
|
|
137
|
+
if (['human', 'replan', 'stop'].includes(status.action)) throw new Error(`Cannot blindly retry ${status.action}; resolve the decision and create a new run.`);
|
|
138
|
+
const affected = [...descendantIds(next.graph, [nodeId])];
|
|
139
|
+
if (affected.some(id => id !== nodeId && next.state.nodes[id].status === 'running')) throw new Error('Stop running descendants before resetting their inputs.');
|
|
140
|
+
if (affected.some(id => next.state.nodes[id].attempts >= MAX_ATTEMPTS)) throw new Error('Attempt limit reached; stop and inspect the evidence.');
|
|
141
|
+
let feedback;
|
|
142
|
+
if (command === 'feedback') {
|
|
143
|
+
feedback = await readJson(root, argument);
|
|
144
|
+
if (feedback.token !== revisionToken(next)) throw new Error('Stale feedback token; read fresh status.');
|
|
145
|
+
if (!['completed', 'failed'].includes(next.state.nodes[nodeId].status)) throw new Error('Feedback requires completed or failed work; stop running work first.');
|
|
146
|
+
if (typeof feedback.summary !== 'string' || !feedback.summary.trim()) throw new Error('Feedback needs a summary.');
|
|
147
|
+
feedback = { summary: feedback.summary, evidence: feedback.evidence, evidenceHashes: await evidenceHashes(root, feedback.evidence) };
|
|
148
|
+
}
|
|
149
|
+
next.state = resetAffectedSubgraph(next.graph, next.state, [nodeId]);
|
|
150
|
+
next.history.push({ event: command, nodeId, affected, ...(feedback ?? { reason: argument }), at: new Date().toISOString() });
|
|
151
|
+
await checkRunEvidence(root, next);
|
|
152
|
+
}
|
|
153
|
+
return next;
|
|
154
|
+
});
|
|
155
|
+
return { ...workflowStatus(run), ...(command === 'start' ? { started: taskInput(run, nodeId) } : {}),
|
|
156
|
+
...(command === 'answer' ? { resumed: taskInput(run, nodeId) } : {}) };
|
|
157
|
+
}
|
|
@@ -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,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 || 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,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
|
+
}
|