@pazmo/ai-workflow-kit 5.3.0 → 5.4.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.
Files changed (36) 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 +32 -42
  5. package/README.md +32 -42
  6. package/assets/check.mjs +127 -4
  7. package/assets/graph.mjs +2 -1
  8. package/package.json +1 -1
  9. package/skills/workflow/EVALS.md +16 -11
  10. package/skills/workflow/SKILL.md +7 -5
  11. package/skills/workflow/assets/STORY.md +30 -15
  12. package/skills/workflow/references/execution.md +26 -15
  13. package/skills/workflow/references/fast-path.md +23 -0
  14. package/skills/workflow/references/graph-advanced.md +126 -0
  15. package/skills/workflow/references/graph-engineering.md +1 -122
  16. package/skills/workflow/references/graph-minimal.md +52 -0
  17. package/skills/workflow/references/intake.md +25 -9
  18. package/skills/workflow/references/jira.md +3 -3
  19. package/skills/workflow/references/light-lane.md +31 -0
  20. package/skills/workflow/references/model-selection.md +14 -0
  21. package/skills/workflow/references/role-graphs.md +2 -2
  22. package/skills/workflow/references/skill-integration.md +4 -4
  23. package/skills/workflow/references/understanding-gate.md +49 -9
  24. package/skills/workflow/references/verification.md +3 -3
  25. package/src/graph/advance.mjs +180 -0
  26. package/src/graph/approvals.mjs +29 -1
  27. package/src/graph/approve.mjs +105 -0
  28. package/src/graph/cli.mjs +126 -8
  29. package/src/graph/copies.mjs +85 -0
  30. package/src/graph/light.mjs +182 -0
  31. package/src/graph/profile.mjs +129 -0
  32. package/src/graph/snapshot.mjs +2 -1
  33. package/src/graph/verification.mjs +92 -28
  34. package/src/graph/workflow.mjs +1 -1
  35. package/src/jira.mjs +14 -13
  36. package/src/managed-block.mjs +3 -3
package/src/graph/cli.mjs CHANGED
@@ -1,13 +1,19 @@
1
1
  import fs from 'node:fs/promises';
2
+ import path from 'node:path';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import { normalizeEvaluation } from './executor.mjs';
4
5
  import { descendantIds, nodeById } from './task-graph.mjs';
5
6
  import { resetAffectedSubgraph } from './scheduler.mjs';
6
- import { digest, readJson, readProjectFile, updateRun } from './storage.mjs';
7
+ import { digest, projectFile, readJson, readProjectFile, updateRun } from './storage.mjs';
7
8
  import { assertAssignment, assertRoleOutput, createRoleGraph } from './roles.mjs';
8
- import { approvalPath, boundApproval } from './approvals.mjs';
9
+ import { approvalPath, boundApproval, checkG4Record, storyG4Mode } from './approvals.mjs';
9
10
  import { createSnapshot } from './snapshot.mjs';
10
- import { PROFILE, checkExecutions, needsExecution, runVerification, verificationProfile } from './verification.mjs';
11
+ import { begin, complete } from './advance.mjs';
12
+ import { BASELINE_NARROW, resolveChecks, writeProfile } from './profile.mjs';
13
+ import { lightCommands, storyLane } from './light.mjs';
14
+ import { findCopies } from './copies.mjs';
15
+ import { approveG1, approveG4 } from './approve.mjs';
16
+ import { PROFILE, checkExecutions, executeCheck, findReusableReceipt, indexReceipt, needsExecution, receiptTail, runCheck, runVerification, verificationProfile } from './verification.mjs';
11
17
  import { normalizeExecutionMetadata } from './execution-metadata.mjs';
12
18
  import {
13
19
  MAX_ATTEMPTS, MAX_QUESTIONS, assertWorkflowRun, checkRunEvidence, createWorkflowGraph, evidenceHashes,
@@ -18,6 +24,17 @@ export const GRAPH_HELP = `Graph commands (run from project root):
18
24
  graph.mjs init <plan.json|-> <run.json> <story.md>
19
25
  graph.mjs init-role <assignment.json> <run.json>
20
26
  graph.mjs status <run.json>
27
+ graph.mjs copies <file-or-folder>... (parallel copies in sibling folders, before the Story)
28
+ graph.mjs approve G1 <story.md> --response <reply-file>
29
+ graph.mjs go <story.md> <run.json> [--scope <module-or-path>...]
30
+ graph.mjs approve G4 <run.json> --summary <four-lines-file> --response <reply-file> [--mode ai-summary|human-restatement]
31
+ graph.mjs profile <story.md> [--scope <module-or-path>]
32
+ graph.mjs baseline <run.json> (optional: repositories with known failures)
33
+ graph.mjs begin <run.json> <node-id>
34
+ graph.mjs complete <run.json> <node-id> [--verdict pass|fix|human|replan] [--notes <file>] [--tests <test>...]
35
+ graph.mjs light <story.md> <run.json> (light lane: Lane: light in the Story)
36
+ graph.mjs check <run.json> [--tests <test>...] (light lane)
37
+ graph.mjs review <run.json> --verdict pass|fix [--notes <file>] (light lane)
21
38
  graph.mjs start <run.json> <node-id> <ready-token>
22
39
  graph.mjs record <run.json> <node-id> <result.json>
23
40
  graph.mjs verify <run.json> <node-id> <task-token> <check-id>
@@ -26,13 +43,37 @@ export const GRAPH_HELP = `Graph commands (run from project root):
26
43
  graph.mjs question <run.json> <node-id> <question.json>
27
44
  graph.mjs answer <run.json> <node-id> <answer.json>
28
45
  graph.mjs feedback <run.json> <node-id> <feedback.json>
29
- Use - for a minimal plan. The host executes work; this tool validates state/evidence and routes the next action.`;
46
+ Use - for a minimal plan. begin/complete run a node in two calls; start/verify/record remain for advanced use.
47
+ The host executes work; this tool validates state/evidence and routes the next action.`;
48
+
49
+ // Only these commands take flags; every other argument stays positional.
50
+ function splitFlags(command, raw) {
51
+ const allowed = { complete: ['verdict', 'notes', 'tests'], review: ['verdict', 'notes'], approve: ['response', 'summary', 'mode'],
52
+ go: ['scope'], init: ['scope'], light: ['scope'], check: ['tests'] }[command] ?? [];
53
+ const flags = {};
54
+ const values = [];
55
+ for (let index = 0; index < raw.length; index += 1) {
56
+ const name = raw[index].startsWith('--') ? raw[index].slice(2) : null;
57
+ if (name && allowed.includes(name)) {
58
+ if (index + 1 >= raw.length) throw new Error(`--${name} needs a value.`);
59
+ // --scope and --tests take every value up to the next flag, and may repeat.
60
+ if (name === 'scope' || name === 'tests') {
61
+ const list = (flags[name] ??= []);
62
+ do list.push(raw[++index]); while (index + 1 < raw.length && !raw[index + 1].startsWith('--'));
63
+ } else flags[name] = raw[++index];
64
+ } else values.push(raw[index]);
65
+ }
66
+ return { flags, values };
67
+ }
30
68
 
31
69
  export async function runGraphCommand(args, { root = process.cwd(), checkArtifact, checkGate } = {}) {
32
70
  root = await fs.realpath(root);
33
- const [command, ...values] = args;
71
+ const [command, ...raw] = args;
34
72
  if (!command || command === '--help') return { help: GRAPH_HELP };
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 };
73
+ const { flags, values } = splitFlags(command, raw);
74
+ if (command === 'copies') return findCopies(root, values);
75
+ 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,
76
+ begin: 2, complete: 2, profile: 1, baseline: 1, light: 2, check: 1, review: 1, approve: 2, go: 2 };
36
77
  if (!Object.hasOwn(counts, command) || values.length !== counts[command]) throw new Error(GRAPH_HELP);
37
78
 
38
79
  const loadStory = async file => {
@@ -93,7 +134,7 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
93
134
  const text = await readProjectFile(root, run.story.path);
94
135
  const extra = run.verification ? [PROFILE, ...(run.verification.recipe ? [run.verification.recipe.path] : []),
95
136
  ...(run.verification.value.requiresG3 ? [run.verification.value.design] : [])] : [];
96
- const runFile = command === 'init' || command === 'init-role' ? values[1] : values[0];
137
+ const runFile = ['init', 'init-role', 'light'].includes(command) ? values[1] : values[0];
97
138
  return createSnapshot({ root, inputs: run.verification?.value.inputs, additionalInputs: extra,
98
139
  story: run.story.path, exclude: [runFile, `${runFile}.lock`, ...['G1', 'G3', 'G4'].map(gate => approvalPath(text, gate)).filter(Boolean)] });
99
140
  };
@@ -137,19 +178,33 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
137
178
  const run = await updateRun(root, runFile, async () => {
138
179
  const next = newWorkflowRun(graph, story, contract);
139
180
  await bindings(next, contract, true);
181
+ if (next.verification) {
182
+ if (flags.scope) next.scope = flags.scope;
183
+ next.checkArgv = await resolveChecks(root, next.verification.value.checks, flags.scope);
184
+ }
140
185
  await snapshot(next);
141
186
  return next;
142
187
  }, { create: true });
143
188
  return status(run);
144
189
  }
190
+ const lane = lightCommands({ root, loadStory, checkGate, snapshot });
191
+ if (command === 'light') return lane.create(values[0], values[1], flags.scope);
192
+ if (command === 'check') {
193
+ if (flags.tests) await updateRun(root, values[0], async previous => ({ ...structuredClone(previous), tests: flags.tests,
194
+ checkArgv: await resolveChecks(root, previous.verification?.value.checks ?? [], previous.scope, flags.tests) }));
195
+ return lane.check(values[0]);
196
+ }
197
+ if (command === 'review') return lane.review(values[0], flags);
198
+ if ((command === 'status' || command === 'delivery') && (await readJson(root, values[0]))?.kind === 'light') return lane[command](values[0]);
145
199
  if (command === 'status' || command === 'delivery') {
146
200
  const run = await validate(await readJson(root, values[0]));
147
201
  const current = await status(run);
148
202
  if (command === 'status') return current;
149
203
  if (current.action !== 'g4' || run.kind !== 'delivery') throw new Error('Delivery requires fresh, completed v3 Graph verification.');
204
+ const mode = storyG4Mode(await readProjectFile(root, run.story.path));
150
205
  await boundApproval({ root, story: run.story.path, gate: 'G4', expected: {
151
206
  storyHash: run.story.fingerprint, snapshot: current.snapshot, runId: run.runId,
152
- }, checkGate });
207
+ }, checkGate, validate: value => checkG4Record(value, { mode, requiresG3: Boolean(run.verification?.value.requiresG3) }) });
153
208
  return { ...current, action: 'delivered' };
154
209
  }
155
210
  if (command === 'verify') {
@@ -157,6 +212,69 @@ export async function runGraphCommand(args, { root = process.cwd(), checkArtifac
157
212
  const result = await runVerification({ root, runFile, nodeId, token, checkId, validate, snapshot });
158
213
  return { ...await status(result.run), verification: result.verification };
159
214
  }
215
+ const call = argv => runGraphCommand(argv, { root, checkArtifact, checkGate });
216
+ if (command === 'profile') return writeProfile({ root, ids: (await loadStory(values[0])).ids });
217
+ if (command === 'approve') {
218
+ if (values[0] === 'G1') return approveG1({ root, story: values[1], response: flags.response, checkArtifact, checkGate });
219
+ if (values[0] === 'G4') return approveG4({ root, runFile: values[1], summary: flags.summary, response: flags.response, mode: flags.mode, call });
220
+ throw new Error('approve takes G1 <story.md> or G4 <run.json>.');
221
+ }
222
+ if (command === 'go') {
223
+ // One call from an approved Story to the first node's brief, or back to the node in progress.
224
+ const story = path.posix.normalize(values[0]);
225
+ const runFile = values[1];
226
+ const scope = (flags.scope ?? []).flatMap(entry => ['--scope', entry]);
227
+ const exists = await fs.access(await projectFile(root, runFile)).then(() => true, () => false);
228
+ if (exists) {
229
+ const owner = (await readJson(root, runFile)).story?.path;
230
+ if (path.posix.normalize(owner ?? '') !== story) throw new Error(`${runFile} belongs to another Story (${owner}); use a run file for ${story}.`);
231
+ } else await call(['profile', story]);
232
+ if (storyLane(await readProjectFile(root, story)) === 'light') return exists ? call(['status', runFile]) : call(['light', story, runFile, ...scope]);
233
+ if (!exists) await call(['init', '-', runFile, story, ...scope]);
234
+ const state = await call(['status', runFile]);
235
+ const nodeId = state.running[0] ?? state.ready[0]?.id;
236
+ return nodeId ? { run: runFile, ...await begin({ root, runFile, nodeId, call }) } : state;
237
+ }
238
+ if (command === 'baseline') {
239
+ // One run of every check on the code before the change; implementation waits for it.
240
+ const [runFile] = values;
241
+ const run = await validate(await readJson(root, runFile));
242
+ if (run.kind !== 'delivery' || !run.verification) throw new Error('Baseline needs a delivery run with a verification profile.');
243
+ if (storyLane(await readProjectFile(root, run.story.path)) === 'moved-up') {
244
+ throw new Error('This Story moved up from light: its code already changed, so there is no baseline to take. begin implement directly.');
245
+ }
246
+ const code = (await snapshot(run)).fingerprint;
247
+ const receipts = {};
248
+ const failing = [];
249
+ for (const check of run.verification.value.checks.map(entry => runCheck(run, entry))) {
250
+ let found = await findReusableReceipt(root, run, check, code);
251
+ if (!found) {
252
+ found = await executeCheck({ root, run, nodeId: 'baseline', token: null, check, snapshotBefore: code, snapshot });
253
+ await indexReceipt(root, runFile, check, found.receipt, found.file);
254
+ }
255
+ receipts[check.id] = { file: found.file, hash: found.hash };
256
+ if (!found.receipt.passed) failing.push(`${check.id}:\n${await receiptTail(root, found.receipt)}`);
257
+ }
258
+ if (failing.length) throw new Error(`Baseline failed before any change.\n${failing.join('\n')}\n${BASELINE_NARROW}`);
259
+ await updateRun(root, runFile, async previous => ({ ...structuredClone(previous),
260
+ baseline: { profile: run.verification.fingerprint, snapshot: code, receipts } }));
261
+ return { baseline: 'passed', checks: Object.keys(receipts), next: (await call(['status', runFile])).ready[0]?.id ?? null };
262
+ }
263
+ if (command === 'begin') {
264
+ // The baseline no longer gates implementation (RC 2): it sat on the critical path.
265
+ return begin({ root, runFile: values[0], nodeId: values[1], call });
266
+ }
267
+ if (command === 'complete') {
268
+ if (flags.tests) {
269
+ // Narrow the checks to the named tests for this run; later nodes reuse the same argv and receipts.
270
+ await updateRun(root, values[0], async previous => ({ ...structuredClone(previous), tests: flags.tests,
271
+ checkArgv: await resolveChecks(root, previous.verification?.value.checks ?? [], previous.scope, flags.tests) }));
272
+ }
273
+ return complete({ root, runFile: values[0], nodeId: values[1], verdict: flags.verdict, notesFile: flags.notes, call, snapshot,
274
+ loadRun: async () => validate(await readJson(root, values[0])),
275
+ indexReceipt: (check, receipt, file) => indexReceipt(root, values[0], check, receipt, file),
276
+ reuseReceipt: (run, check, code) => findReusableReceipt(root, run, check, code) });
277
+ }
160
278
 
161
279
  const [runFile, nodeId, argument] = values;
162
280
  const run = await updateRun(root, runFile, async previous => {
@@ -0,0 +1,85 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ const SKIP = new Set(['node_modules', 'build', 'dist', 'out', 'target', 'coverage']);
5
+ const LIMIT = 20;
6
+
7
+ export const COPIES_RULE = 'Each listed copy that has the behavior the request changes is in To-be, unless the request names a copy '
8
+ + 'with a word the code uses for it (cite file:line); a copy without that behavior is not. Otherwise ask OPEN BLOCKING. '
9
+ + 'Write the list and the decision as the first Decisions line.';
10
+
11
+ /** Every project file as a posix path, skipping dot folders and build or dependency output. */
12
+ export async function listFiles(root) {
13
+ const files = [];
14
+ const walk = async dir => {
15
+ const entries = await fs.readdir(path.join(root, dir), { withFileTypes: true }).catch(() => []);
16
+ for (const entry of entries) {
17
+ const rel = dir ? `${dir}/${entry.name}` : entry.name;
18
+ if (entry.isDirectory()) {
19
+ if (!entry.name.startsWith('.') && !SKIP.has(entry.name)) await walk(rel);
20
+ } else if (entry.isFile()) files.push(rel);
21
+ }
22
+ };
23
+ await walk('');
24
+ return files;
25
+ }
26
+
27
+ const clean = target => path.posix.normalize(target).replace(/^(?:\.\/)+/, '').replace(/\/+$/, '');
28
+
29
+ /** How many trailing path segments two paths share, ignoring case. */
30
+ const sharedTail = (a, b) => {
31
+ const left = a.toLowerCase().split('/');
32
+ const right = b.toLowerCase().split('/');
33
+ let count = 0;
34
+ while (count < left.length && count < right.length && left[left.length - 1 - count] === right[right.length - 1 - count]) count += 1;
35
+ return count;
36
+ };
37
+
38
+ /**
39
+ * Folders elsewhere that hold the same files as `target`: the same paths inside, ignoring case.
40
+ * Their own names may differ (brand-a and brand-b/ko). At least two shared files, unless the
41
+ * target holds one, and at least 30% of the smaller folder.
42
+ */
43
+ function folderCopies(files, target) {
44
+ const prefix = `${target}/`;
45
+ const inside = new Set(files.filter(file => file.startsWith(prefix)).map(file => file.slice(prefix.length).toLowerCase()));
46
+ const shared = new Map();
47
+ const sizes = new Map();
48
+ for (const file of files) {
49
+ const parts = file.split('/');
50
+ for (let cut = 1; cut < parts.length; cut += 1) {
51
+ const folder = parts.slice(0, cut).join('/');
52
+ sizes.set(folder, (sizes.get(folder) ?? 0) + 1);
53
+ if (file.startsWith(prefix) || folder === target || target.startsWith(`${folder}/`) || folder.startsWith(prefix)) continue;
54
+ if (inside.has(parts.slice(cut).join('/').toLowerCase())) shared.set(folder, (shared.get(folder) ?? 0) + 1);
55
+ }
56
+ }
57
+ return [...shared]
58
+ .filter(([folder, count]) => count >= Math.min(2, inside.size) && count / Math.min(inside.size, sizes.get(folder)) >= 0.3)
59
+ .sort(([a, x], [b, y]) => y - x || sharedTail(b, target) - sharedTail(a, target) || a.localeCompare(b))
60
+ .map(([folder]) => folder);
61
+ }
62
+
63
+ /**
64
+ * Parallel copies of each target. A file's copies have the same name and parent folder, ignoring
65
+ * case (a shared file name alone, index.tsx, is not a copy); a folder's copies hold the same files.
66
+ * Closest first.
67
+ */
68
+ export async function findCopies(root, targets) {
69
+ if (!targets.length) throw new Error('copies needs at least one file or folder.');
70
+ const files = await listFiles(root);
71
+ const copies = [];
72
+ for (const raw of targets) {
73
+ const target = clean(raw);
74
+ const stat = await fs.stat(path.join(root, target)).catch(() => null);
75
+ if (!stat) throw new Error(`Not found: ${raw}`);
76
+ const found = stat.isDirectory() ? folderCopies(files, target) : files
77
+ .filter(candidate => candidate !== target)
78
+ .map(candidate => ({ candidate, shared: sharedTail(candidate, target) }))
79
+ .filter(({ shared }) => shared >= 2)
80
+ .sort((a, b) => b.shared - a.shared || a.candidate.localeCompare(b.candidate))
81
+ .map(({ candidate }) => candidate);
82
+ copies.push({ path: target, copies: found.slice(0, LIMIT), ...(found.length > LIMIT ? { more: found.length - LIMIT } : {}) });
83
+ }
84
+ return { copies, rule: COPIES_RULE };
85
+ }
@@ -0,0 +1,182 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { digest, projectFile, readJson, readProjectFile, updateRun } from './storage.mjs';
5
+ import { executeCheck, findReusableReceipt, indexReceipt, receiptTail, runCheck, verificationProfile } from './verification.mjs';
6
+ import { boundApproval, checkG4Record, storyG4Mode } from './approvals.mjs';
7
+ import { assertNotesPath } from './advance.mjs';
8
+ import { resolveChecks } from './profile.mjs';
9
+
10
+ // The light lane: no Graph. One check run, one review and G4, each bound to the code snapshot.
11
+ // Requirements, G1 binding and the profile are re-validated on every command.
12
+
13
+ const RECORD = /^(?:Status|Owner|Lane|Understanding gate \(G[134]\)|G4):/i;
14
+ const FENCE = /^\s*(?:`{3,}|~{3,})/;
15
+
16
+ /** Indexes of the Story's record lines zone: the preamble before the first "##" and the trailing footer, outside fences. */
17
+ export function recordZoneIndexes(text) {
18
+ const lines = text.split(/\r?\n/);
19
+ const fencedAt = [];
20
+ let fenced = false;
21
+ let firstSection = lines.length;
22
+ lines.forEach((line, index) => {
23
+ const marker = FENCE.test(line);
24
+ if (marker) fenced = !fenced;
25
+ fencedAt[index] = fenced || marker;
26
+ if (!fencedAt[index] && firstSection === lines.length && /^##\s+/.test(line)) firstSection = index;
27
+ });
28
+ let start = lines.length;
29
+ const record = index => !fencedAt[index] && (RECORD.test(lines[index].trim()) || !lines[index].trim() || /^---\s*$/.test(lines[index]));
30
+ while (start > firstSection && record(start - 1)) start -= 1;
31
+ return [...Array(firstSection).keys(), ...Array.from({ length: lines.length - start }, (_, i) => start + i)];
32
+ }
33
+
34
+ /**
35
+ * The Story's lane from its preamble or record footer, outside fences: 'light', 'standard',
36
+ * 'moved-up' (standard, from light) or null. A Lane line inside a section is content.
37
+ */
38
+ export function storyLane(text) {
39
+ const lines = text.split(/\r?\n/);
40
+ const lane = recordZoneIndexes(text).map(index => lines[index].trim()).filter(line => /^Lane:/i.test(line)).at(-1);
41
+ const value = lane?.replace(/^Lane:[\t ]*/i, '');
42
+ if (/^light$/i.test(value ?? '')) return 'light';
43
+ if (/^standard[\t ]*\(from light:/i.test(value ?? '')) return 'moved-up';
44
+ if (/^standard$/i.test(value ?? '')) return 'standard';
45
+ return null;
46
+ }
47
+
48
+ /** Replace the record line matching pattern in the record zone, or add it after the last record line. */
49
+ export function setRecordLine(text, pattern, line) {
50
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
51
+ const lines = text.split(/\r?\n/);
52
+ const zone = recordZoneIndexes(text);
53
+ const existing = zone.find(index => pattern.test(lines[index].trim()));
54
+ if (existing !== undefined) lines[existing] = line;
55
+ else {
56
+ const after = zone.filter(index => RECORD.test(lines[index].trim())).at(-1);
57
+ const title = lines.findIndex(entry => /^#\s+Story:/.test(entry));
58
+ lines.splice((after ?? title) + 1, 0, line);
59
+ }
60
+ return lines.join(eol);
61
+ }
62
+
63
+ export function lightCommands({ root, loadStory, checkGate, snapshot }) {
64
+ // Lane stays out of the Story hash, so the G1 record itself says the human approved the light lane.
65
+ const bindG1 = (story, contract) => boundApproval({ root, story, gate: 'G1', expected: { storyHash: contract.fingerprint }, checkGate,
66
+ validate: value => {
67
+ if (value.lane !== 'light') throw new Error('The light lane needs a G1 that approved Lane: light (lane: "light" in the G1 record); moving down from standard needs a new G1.');
68
+ } });
69
+
70
+ const load = async runFile => {
71
+ const run = await readJson(root, runFile);
72
+ if (run?.version !== 3 || run.kind !== 'light' || typeof run.runId !== 'string' || !run.story?.path) throw new Error('Invalid light run.');
73
+ const text = await readProjectFile(root, run.story.path);
74
+ if (storyLane(text) !== 'light') throw new Error('The Story is no longer on the light lane; continue in the standard Graph with init.');
75
+ const contract = await loadStory(run.story.path);
76
+ if (contract.fingerprint !== run.story.fingerprint) throw new Error('Story requirements changed; start a new light run after G1.');
77
+ if (JSON.stringify(await bindG1(run.story.path, contract)) !== JSON.stringify(run.approval)) throw new Error('G1 approval changed; create a new run.');
78
+ const profile = await verificationProfile(root, contract.ids);
79
+ if (profile.fingerprint !== run.verification.fingerprint) throw new Error('Verification profile changed; start a new light run.');
80
+ run.verification = profile;
81
+ return run;
82
+ };
83
+
84
+ // A stored result counts only for the code it was made on.
85
+ const progress = (run, code) => {
86
+ const checked = run.checks?.passed === true && run.checks.snapshot === code;
87
+ const reviewed = run.review?.verdict === 'pass' && run.review.snapshot === code;
88
+ return { checked, reviewed, action: !checked ? 'check' : !reviewed ? 'review' : 'g4' };
89
+ };
90
+
91
+ return {
92
+ async create(story, runFile, scope) {
93
+ story = path.posix.normalize(story);
94
+ const text = await readProjectFile(root, story);
95
+ if (storyLane(text) !== 'light') throw new Error('The light lane needs "Lane: light" in the Story footer.');
96
+ const contract = await loadStory(story);
97
+ const own = await projectFile(root, runFile);
98
+ const directories = new Set([path.dirname(own), await projectFile(root, '.ai-workflow/runs')]);
99
+ for (const directory of directories) {
100
+ for (const name of await fs.readdir(directory).catch(() => [])) {
101
+ if (!name.endsWith('.json') || path.join(directory, name) === own) continue;
102
+ const other = await fs.readFile(path.join(directory, name), 'utf8').then(JSON.parse, () => null);
103
+ if (other?.kind === 'delivery' && path.posix.normalize(other.story?.path ?? '') === story) {
104
+ throw new Error(`A standard run already exists for this Story (${path.relative(root, path.join(directory, name))}); moving down to light needs a new G1.`);
105
+ }
106
+ }
107
+ }
108
+ const profile = await verificationProfile(root, contract.ids);
109
+ if (profile.value.requiresG3) throw new Error('Work that needs G3 cannot use the light lane.');
110
+ const approval = await bindG1(story, contract);
111
+ const run = await updateRun(root, runFile, async () => ({ version: 3, kind: 'light', runId: randomUUID(),
112
+ story: { path: story, fingerprint: contract.fingerprint }, approval, verification: profile, receipts: {}, history: [],
113
+ ...(scope ? { scope } : {}), checkArgv: await resolveChecks(root, profile.value.checks, scope) }), { create: true });
114
+ return { runId: run.runId, lane: 'light', checks: profile.value.checks.map(check => check.id), next: 'check' };
115
+ },
116
+
117
+ async check(runFile) {
118
+ const run = await load(runFile);
119
+ const code = (await snapshot(run)).fingerprint;
120
+ const receipts = {};
121
+ let failing;
122
+ for (const check of run.verification.value.checks.map(entry => runCheck(run, entry))) {
123
+ let found = await findReusableReceipt(root, run, check, code);
124
+ if (!found) {
125
+ found = await executeCheck({ root, run, nodeId: 'check', token: null, check, snapshotBefore: code, snapshot });
126
+ await indexReceipt(root, runFile, check, found.receipt, found.file);
127
+ }
128
+ receipts[check.id] = { file: found.file, hash: found.hash };
129
+ if (!found.receipt.passed) { failing = { check: check.id, tail: await receiptTail(root, found.receipt) }; break; }
130
+ }
131
+ await updateRun(root, runFile, async previous => ({ ...structuredClone(previous),
132
+ checks: { snapshot: code, passed: !failing, receipts },
133
+ history: [...previous.history, { event: 'check', passed: !failing, snapshot: code, at: new Date().toISOString() }] }));
134
+ return { passed: !failing, snapshot: code, ...(failing ? { failing } : {}), next: failing ? 'fix, then check' : progress({ ...run, checks: { passed: true, snapshot: code } }, code).action };
135
+ },
136
+
137
+ async review(runFile, { verdict, notes }) {
138
+ if (!['pass', 'fix'].includes(verdict)) throw new Error('review needs --verdict pass|fix, and --notes <file> with the findings.');
139
+ assertNotesPath(notes);
140
+ const current = await readJson(root, runFile);
141
+ if (verdict === 'fix' && current.history?.some(entry => entry.event === 'review' && entry.verdict === 'fix')) {
142
+ throw new Error('One review round per run: record --verdict pass and list the remaining findings in --notes (they go to the G4 summary as unverified).');
143
+ }
144
+ const text = notes ? (await readProjectFile(root, notes)).trim() : '';
145
+ if (verdict === 'fix' && !text) throw new Error('A fix verdict needs feedback: pass --notes <file> with the findings.');
146
+ const run = await load(runFile);
147
+ const code = (await snapshot(run)).fingerprint;
148
+ const review = { verdict, snapshot: code, ...(notes ? { notes, notesHash: digest(text) } : {}), at: new Date().toISOString() };
149
+ const next = await updateRun(root, runFile, async previous => {
150
+ const value = { ...structuredClone(previous), review, history: [...previous.history, { event: 'review', ...review }] };
151
+ if (verdict === 'fix') delete value.checks; // the fix changes the code; its checks must run again
152
+ return value;
153
+ });
154
+ return { verdict, snapshot: code, next: progress(next, code).action };
155
+ },
156
+
157
+ async status(runFile) {
158
+ const run = await load(runFile);
159
+ const code = (await snapshot(run)).fingerprint;
160
+ return { runId: run.runId, lane: 'light', snapshot: code, ...progress(run, code),
161
+ gate: 'Checks and review never approve G4. G4 remains human-owned.' };
162
+ },
163
+
164
+ async delivery(runFile) {
165
+ const run = await load(runFile);
166
+ const code = (await snapshot(run)).fingerprint;
167
+ const state = progress(run, code);
168
+ if (!state.reviewed) throw new Error('Light delivery needs a passing review of the current code; run review again after the last change.');
169
+ if (!state.checked) throw new Error('Light delivery needs passing checks on the current code; run check.');
170
+ for (const check of run.verification.value.checks) {
171
+ const binding = run.checks.receipts[check.id];
172
+ const receipt = binding && await readJson(root, binding.file);
173
+ if (!receipt || digest(JSON.stringify(receipt)) !== binding.hash || !receipt.passed || receipt.runId !== run.runId
174
+ || receipt.snapshotBefore !== code || receipt.snapshotAfter !== code) throw new Error(`Check receipt missing or changed: ${check.id}; run check.`);
175
+ }
176
+ const mode = storyG4Mode(await readProjectFile(root, run.story.path));
177
+ await boundApproval({ root, story: run.story.path, gate: 'G4', expected: { storyHash: run.story.fingerprint, snapshot: code, runId: run.runId },
178
+ checkGate, validate: value => checkG4Record(value, { mode, requiresG3: false }) });
179
+ return { runId: run.runId, lane: 'light', snapshot: code, action: 'delivered' };
180
+ },
181
+ };
182
+ }
@@ -0,0 +1,129 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { projectFile, readJson } from './storage.mjs';
4
+ import { PROFILE } from './verification.mjs';
5
+ import { listFiles } from './copies.mjs';
6
+
7
+ const TIMEOUT = 300000;
8
+ // Placeholders in detected checks; each run resolves them from its own --scope, so one shared
9
+ // profile never carries another Story's scope.
10
+ export const SCOPE = '{scope}';
11
+ export const GRADLE_TEST = '{gradle-test}';
12
+ export const GRADLE_TESTS = '{gradle-tests}';
13
+
14
+ const cleanScope = scope => (scope ? path.posix.normalize(scope).replace(/^(?:\.\/)+/, '').replace(/^:+/, '').replace(/\/+$/, '') : '');
15
+ const scopeList = scopes => [].concat(scopes ?? []).map(cleanScope).filter(scope => scope && scope !== '.');
16
+
17
+ /** The Gradle task for a scope: the deepest module directory with a build file, else the root test task. */
18
+ async function gradleTask(root, scope) {
19
+ for (let dir = scope; dir && dir !== '.'; dir = path.posix.dirname(dir)) {
20
+ for (const file of ['build.gradle', 'build.gradle.kts']) {
21
+ if (await present(root, `${dir}/${file}`)) return `:${dir.split('/').join(':')}:test`;
22
+ }
23
+ }
24
+ return 'test';
25
+ }
26
+
27
+ /** Test source files under any src/test, keyed by class name (file name without extension). */
28
+ async function testFiles(root) {
29
+ const index = new Map();
30
+ for (const file of await listFiles(root)) {
31
+ if (!/(?:^|\/)src\/test\//.test(file) || !/\.(?:java|kt|groovy|scala)$/.test(file)) continue;
32
+ const name = path.posix.basename(file).replace(/\.[^.]+$/, '');
33
+ index.set(name, [...(index.get(name) ?? []), file]);
34
+ }
35
+ return index;
36
+ }
37
+
38
+ /** The class a --tests value names: `*FooTest`, `com.x.FooTest`, `FooTest.method`, `Outer$Inner`. */
39
+ const className = test => {
40
+ const segment = test.replace(/^[*.]+/, '').split('.').find(part => /^[A-Z]/.test(part)) ?? '';
41
+ const name = segment.split('$')[0].replace(/\*+$/, '');
42
+ return /^[A-Za-z_][\w]*$/.test(name) ? name : '';
43
+ };
44
+
45
+ /**
46
+ * Gradle task arguments for named tests. Gradle applies --tests to the task just before it, so
47
+ * each test follows the task of the module holding its file; a test with no file found stays
48
+ * with the scope's tasks.
49
+ */
50
+ async function gradleTestArgs(root, scopeTasks, tests) {
51
+ const groups = new Map();
52
+ const add = (task, test) => groups.set(task, [...(groups.get(task) ?? []), test]);
53
+ const index = await testFiles(root);
54
+ const unknown = [];
55
+ for (const test of tests) {
56
+ const files = test.includes('/') ? [test] : index.get(className(test)) ?? [];
57
+ const tasks = [...new Set(await Promise.all(files.map(file => gradleTask(root, path.posix.dirname(file)))))];
58
+ if (tasks.length) for (const task of tasks) add(task, test);
59
+ else unknown.push(test);
60
+ }
61
+ for (const test of unknown) for (const task of scopeTasks) add(task, test);
62
+ return [...groups].flatMap(([task, list]) => [task, ...list.flatMap(test => ['--tests', test])]);
63
+ }
64
+
65
+ /** A check's argv with its placeholders resolved for one run's scopes (a module or path each). */
66
+ export async function resolveArgv(root, argv, scopes, tests = []) {
67
+ const list = scopeList(scopes);
68
+ const out = [];
69
+ for (const arg of argv) {
70
+ // Named tests (complete --tests) replace the scope paths: the check runs only what the change touched.
71
+ if (arg === SCOPE) out.push(...(tests.length ? tests : list));
72
+ else if (arg === GRADLE_TESTS) { if (!argv.includes(GRADLE_TEST)) out.push(...tests.flatMap(test => ['--tests', test])); }
73
+ else if (arg === GRADLE_TEST) {
74
+ const found = [...new Set(await Promise.all(list.map(scope => gradleTask(root, scope))))];
75
+ // The root task already covers every module; an unscoped run uses it too.
76
+ const tasks = !found.length || found.includes('test') ? ['test'] : found;
77
+ out.push(...(tests.length ? await gradleTestArgs(root, tasks, tests) : tasks));
78
+ } else out.push(arg);
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** Resolved argv for every check of a profile, keyed by check id. */
84
+ export async function resolveChecks(root, checks, scope, tests) {
85
+ return Object.fromEntries(await Promise.all(checks.map(async check => [check.id, await resolveArgv(root, check.argv, scope, tests)])));
86
+ }
87
+ const present = async (root, file) => fs.access(await projectFile(root, file)).then(() => true, () => false);
88
+
89
+ /** A check profile from the repository type, covering every Story V ID. */
90
+ export async function detectProfile({ root, ids }) {
91
+ const covers = ids.filter(id => /^V-?\d+$/.test(id));
92
+ if (!covers.length) throw new Error('The Story has no V# items to cover.');
93
+ const checks = [];
94
+ if (await present(root, 'package.json')) {
95
+ const pkg = await readJson(root, 'package.json');
96
+ const dependencies = { ...pkg.dependencies, ...pkg.devDependencies };
97
+ const test = pkg.scripts?.test;
98
+ if (typeof test === 'string' && test.trim() && !/no test specified/i.test(test)) {
99
+ const argv = dependencies['react-scripts'] ? ['npm', 'test', '--', '--watchAll=false'] : ['npm', 'test'];
100
+ // Only runners that take a path filter get the per-run {scope}; node --test and others would fail on it.
101
+ const filters = /\b(?:react-scripts|jest|vitest|mocha)\b/.test(test);
102
+ checks.push({ id: 'test', argv: filters ? [...argv, ...(argv.includes('--') ? [] : ['--']), SCOPE] : argv });
103
+ }
104
+ if (typeof pkg.scripts?.typecheck === 'string') checks.push({ id: 'typecheck', argv: ['npm', 'run', 'typecheck'] });
105
+ else if (await present(root, 'tsconfig.json')) checks.push({ id: 'typecheck', argv: ['npx', 'tsc', '--noEmit'] });
106
+ }
107
+ if (await present(root, 'gradlew')) checks.push({ id: 'gradle-test', argv: ['./gradlew', GRADLE_TEST, GRADLE_TESTS] });
108
+ if (!checks.length) {
109
+ throw new Error('No test command detected (package.json scripts.test, typecheck/tsconfig.json, or gradlew); '
110
+ + 'write .ai-workflow/verification.json by hand, as references/verification.md describes.');
111
+ }
112
+ return { version: 1, checks: checks.map(check => ({ ...check, covers, timeoutMs: TIMEOUT })) };
113
+ }
114
+
115
+ /** Write the detected profile unless one exists; return what applies now. */
116
+ export async function writeProfile({ root, ids }) {
117
+ const file = await projectFile(root, PROFILE);
118
+ if (await present(root, PROFILE)) {
119
+ const existing = await readJson(root, PROFILE);
120
+ return { profile: PROFILE, written: false, checks: (existing.checks ?? []).map(({ id, argv }) => ({ id, argv })) };
121
+ }
122
+ const value = await detectProfile({ root, ids });
123
+ await fs.mkdir(path.dirname(file), { recursive: true });
124
+ await fs.writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { flag: 'wx' });
125
+ return { profile: PROFILE, written: true, checks: value.checks.map(({ id, argv }) => ({ id, argv })) };
126
+ }
127
+
128
+ export const BASELINE_NARROW = 'Narrow each failing check in .ai-workflow/verification.json so it excludes failures that existed before this change '
129
+ + '(for example a test path or filter), init a new run file, and run baseline again.';
@@ -9,7 +9,8 @@ const outputPaths = ['.ai-workflow/runs', '.ai-workflow/evidence', '.ai-workflow
9
9
  const inside = (parent, file) => file === parent || file.startsWith(`${parent}/`);
10
10
 
11
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();
12
+ // Lane moves with the work (light → standard) without a new G1, like Status.
13
+ return text.split(/\r?\n/).filter(line => !/^(?:Status:|Lane:|Understanding gate \(G[134]\):|G4:)/i.test(line)).join('\n').trim();
13
14
  }
14
15
 
15
16
  function relativePath(value) {