@pazmo/ai-workflow-kit 5.2.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 (39) 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 +34 -30
  5. package/README.md +34 -30
  6. package/assets/check.mjs +127 -4
  7. package/assets/graph.mjs +2 -1
  8. package/bin/ai-workflow-kit.mjs +63 -4
  9. package/package.json +1 -1
  10. package/skills/workflow/EVALS.md +36 -11
  11. package/skills/workflow/SKILL.md +7 -5
  12. package/skills/workflow/assets/STORY.md +30 -15
  13. package/skills/workflow/references/execution.md +26 -15
  14. package/skills/workflow/references/fast-path.md +23 -0
  15. package/skills/workflow/references/graph-advanced.md +126 -0
  16. package/skills/workflow/references/graph-engineering.md +1 -122
  17. package/skills/workflow/references/graph-minimal.md +52 -0
  18. package/skills/workflow/references/intake.md +25 -9
  19. package/skills/workflow/references/jira.md +3 -3
  20. package/skills/workflow/references/light-lane.md +31 -0
  21. package/skills/workflow/references/model-selection.md +14 -0
  22. package/skills/workflow/references/role-graphs.md +2 -2
  23. package/skills/workflow/references/skill-integration.md +4 -4
  24. package/skills/workflow/references/understanding-gate.md +49 -9
  25. package/skills/workflow/references/verification.md +3 -3
  26. package/src/graph/advance.mjs +180 -0
  27. package/src/graph/approvals.mjs +29 -1
  28. package/src/graph/approve.mjs +105 -0
  29. package/src/graph/cli.mjs +126 -8
  30. package/src/graph/copies.mjs +85 -0
  31. package/src/graph/light.mjs +182 -0
  32. package/src/graph/profile.mjs +129 -0
  33. package/src/graph/snapshot.mjs +2 -1
  34. package/src/graph/verification.mjs +92 -28
  35. package/src/graph/workflow.mjs +1 -1
  36. package/src/install.mjs +53 -14
  37. package/src/jira.mjs +14 -13
  38. package/src/managed-block.mjs +3 -3
  39. package/src/version.mjs +28 -0
@@ -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) {
@@ -5,6 +5,14 @@ import { digest, projectFile, readJson, updateRun } from './storage.mjs';
5
5
  import { taskToken } from './workflow.mjs';
6
6
 
7
7
  export const PROFILE = '.ai-workflow/verification.json';
8
+ /** A profile check as this run executes it: its argv with the run's scope resolved. */
9
+ export const runCheck = (run, check) => ({ ...check, argv: run.checkArgv?.[check.id]
10
+ ?? check.argv.filter(arg => !['{scope}', '{gradle-tests}'].includes(arg)).map(arg => (arg === '{gradle-test}' ? 'test' : arg)) });
11
+
12
+ /** Reuse key: the same check (id, argv, timeout) on the same code snapshot. */
13
+ export const receiptKey = (check, snapshot) =>
14
+ `${check.id}:${digest(JSON.stringify({ argv: check.argv, timeoutMs: check.timeoutMs ?? null }))}:${snapshot}`;
15
+
8
16
  export const needsExecution = (run, nodeId) => nodeId === 'workflow-verify'
9
17
  || (run.kind === 'role' && run.assignment.value.role === 'developer' && nodeId === 'self-check');
10
18
 
@@ -36,14 +44,19 @@ export async function verificationProfile(root, ids) {
36
44
  return { value, fingerprint: digest(JSON.stringify(value)), ...(recipe ? { recipe } : {}) };
37
45
  }
38
46
 
39
- async function execute(argv, root, timeoutMs) {
47
+ const killGroupOf = child => signal => (process.platform === 'win32' ? child.kill(signal) : process.kill(-child.pid, signal));
48
+
49
+ // A kill that fails while cleaning up after the command (a sandbox can refuse to signal a
50
+ // forked build daemon) is recorded as cleanupError; it never fails a command that exited 0.
51
+ export async function execute(argv, root, timeoutMs, { killGroup } = {}) {
40
52
  return new Promise(resolve => {
41
53
  const stdout = [], stderr = [];
42
- let bytes = 0, timedOut = false, truncated = false, spawnError, killer, settled = false;
54
+ let bytes = 0, timedOut = false, truncated = false, spawnError, cleanupError, killer, settled = false;
43
55
  const child = spawn(argv[0], argv.slice(1), { cwd: root, shell: false, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] });
56
+ const signalGroup = killGroup ?? killGroupOf(child);
44
57
  const kill = signal => {
45
- try { process.platform === 'win32' ? child.kill(signal) : process.kill(-child.pid, signal); }
46
- catch (error) { if (error.code !== 'ESRCH') spawnError ??= error.message; }
58
+ try { signalGroup(signal); }
59
+ catch (error) { if (error.code !== 'ESRCH') cleanupError ??= error.message; }
47
60
  };
48
61
  const finish = (exitCode, signal, outputIncomplete = false) => {
49
62
  if (settled) return;
@@ -51,7 +64,7 @@ async function execute(argv, root, timeoutMs) {
51
64
  clearTimeout(timer); clearTimeout(killer);
52
65
  if (process.platform !== 'win32' && child.pid) kill('SIGKILL');
53
66
  if (outputIncomplete) { child.stdout.destroy(); child.stderr.destroy(); child.unref(); }
54
- resolve({ exitCode, signal, timedOut, truncated, outputIncomplete, ...(spawnError ? { spawnError } : {}), stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) });
67
+ resolve({ exitCode, signal, timedOut, truncated, outputIncomplete, ...(spawnError ? { spawnError } : {}), ...(cleanupError ? { cleanupError } : {}), stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) });
55
68
  };
56
69
  const stop = () => {
57
70
  if (settled) return;
@@ -81,10 +94,15 @@ async function execute(argv, root, timeoutMs) {
81
94
  export async function checkExecutions(root, run, nodeId, { requirePass = false } = {}) {
82
95
  const state = run.state.nodes[nodeId];
83
96
  const receipts = [];
84
- for (const binding of Object.values(state.executions ?? {})) {
97
+ for (const [checkId, binding] of Object.entries(state.executions ?? {})) {
85
98
  if (binding.pending) { if (requirePass) throw new Error('Verification execution is still running.'); continue; }
86
99
  const receipt = await readJson(root, binding.file);
87
- if (digest(JSON.stringify(receipt)) !== binding.hash || receipt.token !== taskToken(run, nodeId)
100
+ // A reused receipt was produced earlier in this run for the same check and snapshot.
101
+ const owned = binding.reused
102
+ ? run.receipts?.[binding.reused]?.file === binding.file && run.receipts[binding.reused].hash === binding.hash
103
+ && receipt.checkId === checkId && receipt.passed === true
104
+ : receipt.token === taskToken(run, nodeId);
105
+ if (digest(JSON.stringify(receipt)) !== binding.hash || !owned
88
106
  || receipt.runId !== run.runId || receipt.storyHash !== run.story.fingerprint) throw new Error('Verification receipt changed or belongs to stale work.');
89
107
  for (const stream of ['stdout', 'stderr']) {
90
108
  const bytes = await fs.readFile(await projectFile(root, receipt[stream]));
@@ -105,46 +123,92 @@ export async function checkExecutions(root, run, nodeId, { requirePass = false }
105
123
  return receipts;
106
124
  }
107
125
 
108
- export async function runVerification({ root, runFile, nodeId, token, checkId, validate, snapshot }) {
109
- const executionId = randomUUID();
110
- const reserved = await updateRun(root, runFile, async previous => {
111
- const run = structuredClone(previous);
112
- await validate(run);
113
- if (run.version !== 3 || !needsExecution(run, nodeId) || run.question
114
- || run.state.nodes[nodeId]?.status !== 'running' || token !== taskToken(run, nodeId)) throw new Error('Verification requires the current running verification task token.');
115
- const check = run.verification.value.checks.find(check => check.id === checkId);
116
- if (!check) throw new Error('Unknown verification check.');
117
- if (Object.hasOwn(run.state.nodes[nodeId].executions ?? {}, checkId)) throw new Error('Check already executed in this attempt; reset before retrying.');
118
- const before = (await snapshot(run)).fingerprint;
119
- if (before !== run.state.nodes[nodeId].snapshot) throw new Error('Verification snapshot is stale; reset affected work.');
120
- run.state.nodes[nodeId].executions ??= {};
121
- run.state.nodes[nodeId].executions[checkId] = { pending: executionId };
122
- return run;
126
+ /** A passing receipt from this run for the same check and snapshot, if its file is intact. */
127
+ export async function findReusableReceipt(root, run, check, snapshot) {
128
+ const indexed = run.receipts?.[receiptKey(check, snapshot)];
129
+ if (!indexed) return null;
130
+ const receipt = await readJson(root, indexed.file);
131
+ if (digest(JSON.stringify(receipt)) !== indexed.hash || !receipt.passed || receipt.runId !== run.runId
132
+ || receipt.snapshotBefore !== snapshot || receipt.snapshotAfter !== snapshot) return null;
133
+ return { receipt, file: indexed.file, hash: indexed.hash };
134
+ }
135
+
136
+ /** Index a passing receipt so later nodes on the same snapshot reuse it. */
137
+ export async function indexReceipt(root, runFile, check, receipt, file) {
138
+ if (!receipt.passed) return;
139
+ await updateRun(root, runFile, async previous => {
140
+ if (previous.runId !== receipt.runId) throw new Error('Receipt belongs to another run.');
141
+ return { ...structuredClone(previous), receipts: { ...previous.receipts,
142
+ [receiptKey(check, receipt.snapshotBefore)]: { file, hash: digest(JSON.stringify(receipt)) } } };
123
143
  });
124
- const check = reserved.verification.value.checks.find(check => check.id === checkId);
125
- const directory = `.ai-workflow/evidence/${reserved.runId}/${executionId}`;
144
+ }
145
+
146
+ /** Run one profile check against the current code and write its receipt and raw logs. */
147
+ export async function executeCheck({ root, run, nodeId, token, check, snapshotBefore, snapshot, executionId = randomUUID() }) {
148
+ const directory = `.ai-workflow/evidence/${run.runId}/${executionId}`;
126
149
  await fs.mkdir(await projectFile(root, directory), { recursive: true, mode: 0o700 });
127
150
  const startedAt = new Date().toISOString();
128
151
  const result = await execute(check.argv, root, check.timeoutMs ?? 30000);
129
- const receipt = { version: 1, runId: reserved.runId, storyHash: reserved.story.fingerprint, nodeId, token, checkId, covers: check.covers,
130
- ...(reserved.verification.recipe ? { recipe: reserved.verification.recipe } : {}),
152
+ const receipt = { version: 1, runId: run.runId, storyHash: run.story.fingerprint, nodeId, token, checkId: check.id, covers: check.covers,
153
+ ...(run.verification.recipe ? { recipe: run.verification.recipe } : {}),
131
154
  argv: check.argv, cwd: '.', startedAt, finishedAt: new Date().toISOString(),
132
155
  ...result, stdout: `${directory}/stdout.log`, stderr: `${directory}/stderr.log`,
133
156
  stdoutHash: digest(result.stdout), stderrHash: digest(result.stderr),
134
- snapshotBefore: reserved.state.nodes[nodeId].snapshot, snapshotAfter: null };
157
+ snapshotBefore, snapshotAfter: null };
135
158
  for (const stream of ['stdout', 'stderr']) await fs.writeFile(await projectFile(root, receipt[stream]), result[stream], { flag: 'wx', mode: 0o600 });
136
- try { receipt.snapshotAfter = (await snapshot(reserved)).fingerprint; }
159
+ try { receipt.snapshotAfter = (await snapshot(run)).fingerprint; }
137
160
  catch (error) { receipt.snapshotError = error.message; }
138
161
  receipt.passed = receipt.exitCode === 0 && !receipt.signal && !receipt.timedOut && !receipt.truncated && !receipt.outputIncomplete && !receipt.spawnError
139
162
  && !receipt.snapshotError && receipt.snapshotBefore === receipt.snapshotAfter;
140
163
  const file = `${directory}/receipt.json`;
141
164
  await fs.writeFile(await projectFile(root, file), `${JSON.stringify(receipt, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
165
+ return { receipt, file, hash: digest(JSON.stringify(receipt)) };
166
+ }
167
+
168
+ /** The last lines of a failed check's output, for feedback that fits in a compact result. */
169
+ export async function receiptTail(root, receipt, lines = 20) {
170
+ // Both streams: Gradle and others print the failure to stdout and only JVM notices to stderr.
171
+ const read = async stream => (await fs.readFile(await projectFile(root, receipt[stream]))).toString('utf8');
172
+ const noise = /^Picked up (?:JAVA_TOOL_OPTIONS|_JAVA_OPTIONS|JDK_JAVA_OPTIONS)/;
173
+ const kept = [...(await read('stdout')).split(/\r?\n/), ...(await read('stderr')).split(/\r?\n/)]
174
+ .filter(line => line.trim() && !noise.test(line.trim()));
175
+ const text = kept.length ? kept.slice(-lines).join('\n')
176
+ : (receipt.timedOut ? 'timed out' : receipt.spawnError ?? `exit ${receipt.exitCode}`);
177
+ return text.slice(-1500);
178
+ }
179
+
180
+ export async function runVerification({ root, runFile, nodeId, token, checkId, validate, snapshot }) {
181
+ const executionId = randomUUID();
182
+ let reused;
183
+ const reserved = await updateRun(root, runFile, async previous => {
184
+ const run = structuredClone(previous);
185
+ await validate(run);
186
+ if (run.version !== 3 || !needsExecution(run, nodeId) || run.question
187
+ || run.state.nodes[nodeId]?.status !== 'running' || token !== taskToken(run, nodeId)) throw new Error('Verification requires the current running verification task token.');
188
+ const found = run.verification.value.checks.find(check => check.id === checkId);
189
+ if (!found) throw new Error('Unknown verification check.');
190
+ const check = runCheck(run, found);
191
+ if (Object.hasOwn(run.state.nodes[nodeId].executions ?? {}, checkId)) throw new Error('Check already executed in this attempt; reset before retrying.');
192
+ const before = (await snapshot(run)).fingerprint;
193
+ if (before !== run.state.nodes[nodeId].snapshot) throw new Error('Verification snapshot is stale; reset affected work.');
194
+ run.state.nodes[nodeId].executions ??= {};
195
+ reused = await findReusableReceipt(root, run, check, before);
196
+ run.state.nodes[nodeId].executions[checkId] = reused
197
+ ? { file: reused.file, hash: reused.hash, reused: receiptKey(check, before) }
198
+ : { pending: executionId };
199
+ return run;
200
+ });
201
+ if (reused) return { run: reserved, verification: { ...reused.receipt, receipt: reused.file, reused: true } };
202
+ const check = runCheck(reserved, reserved.verification.value.checks.find(check => check.id === checkId));
203
+ const { receipt, file } = await executeCheck({ root, run: reserved, nodeId, token, check, executionId,
204
+ snapshotBefore: reserved.state.nodes[nodeId].snapshot, snapshot });
142
205
  const run = await updateRun(root, runFile, async previous => {
143
206
  const next = structuredClone(previous);
144
207
  await validate(next);
145
208
  if (token !== taskToken(next, nodeId) || next.state.nodes[nodeId].status !== 'running'
146
209
  || next.state.nodes[nodeId].executions?.[checkId]?.pending !== executionId) throw new Error('Late verification result rejected after reset/answer.');
147
210
  next.state.nodes[nodeId].executions[checkId] = { file, hash: digest(JSON.stringify(receipt)) };
211
+ if (receipt.passed) next.receipts = { ...next.receipts, [receiptKey(check, receipt.snapshotBefore)]: next.state.nodes[nodeId].executions[checkId] };
148
212
  return next;
149
213
  });
150
214
  return { run, verification: { ...receipt, receipt: file } };
@@ -147,7 +147,7 @@ export function taskInput(run, nodeId) {
147
147
  .map(({ id, covers }) => ({ id, covers })),
148
148
  } } : {}),
149
149
  ...(nodeId === 'workflow-review' || (isRoleRun(run) && run.assignment.value.role === 'reviewer' && nodeId === 'review') ? {
150
- reviewBudget: { defaultAgents: 3, smallChangeAgents: [0, 2], highRiskAgents: [4, 5], scope: 'whole-review-round',
150
+ reviewBudget: { defaultAgents: 1, smallChangeAgents: [1, 1], highRiskAgents: [2, 2], scope: 'whole-review-round',
151
151
  nestedDelegation: false, dispatchOwner: 'host', aggregation: 'caller' },
152
152
  } : {}),
153
153
  ...(isRoleRun(run) ? { assignment: run.assignment.value } : {}),
package/src/install.mjs CHANGED
@@ -13,6 +13,7 @@ import { fileURLToPath } from 'node:url';
13
13
  import { HOSTS, normalizeHosts, projectPath } from './paths.mjs';
14
14
  import { managedBlockFor, removeManagedBlock, upsertManagedBlock } from './managed-block.mjs';
15
15
  import { installTransaction } from './install-transaction.mjs';
16
+ import { readPackageVersion } from './version.mjs';
16
17
 
17
18
  const modulePackageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
18
19
  const CONFIG_PATH = '.ai-workflow/config.json';
@@ -50,9 +51,9 @@ async function fileHash(file) {
50
51
  return sha256(await readFile(file));
51
52
  }
52
53
 
53
- async function treeHash(directory) {
54
- if (!await exists(directory)) return null;
55
- const entries = [];
54
+ // Relative path -> content hash, in the walk order treeHash has always used.
55
+ async function treeFiles(directory) {
56
+ const files = new Map();
56
57
 
57
58
  async function walk(current, prefix = '') {
58
59
  const children = await readdir(current, { withFileTypes: true });
@@ -61,11 +62,18 @@ async function treeHash(directory) {
61
62
  const relative = path.posix.join(prefix, child.name);
62
63
  const full = path.join(current, child.name);
63
64
  if (child.isDirectory()) await walk(full, relative);
64
- else entries.push(`${relative}:${await fileHash(full)}`);
65
+ else files.set(relative, await fileHash(full));
65
66
  }
66
67
  }
67
68
 
68
69
  await walk(directory);
70
+ return files;
71
+ }
72
+
73
+ // Recorded in .ai-workflow/config.json: the entry format must stay byte-identical.
74
+ async function treeHash(directory) {
75
+ if (!await exists(directory)) return null;
76
+ const entries = [...await treeFiles(directory)].map(([relative, hash]) => `${relative}:${hash}`);
69
77
  return sha256(entries.join('\n'));
70
78
  }
71
79
 
@@ -77,14 +85,6 @@ async function writeIfChanged(file, content) {
77
85
  return true;
78
86
  }
79
87
 
80
- async function packageVersion(packageRoot) {
81
- try {
82
- return JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8')).version;
83
- } catch {
84
- return '3.0.0';
85
- }
86
- }
87
-
88
88
  async function readConfig(root) {
89
89
  try {
90
90
  return JSON.parse(await readFile(projectPath(root, CONFIG_PATH), 'utf8'));
@@ -259,16 +259,24 @@ async function installPrepared({
259
259
  if (checkerResult.changed) installed.push(CHECKER_PATH);
260
260
  if (checkerResult.preserved) preserved.push(CHECKER_PATH);
261
261
 
262
+ const version = await readPackageVersion(packageRoot);
262
263
  const config = `${JSON.stringify({
263
264
  schemaVersion: 2,
264
- packageVersion: await packageVersion(packageRoot),
265
+ packageVersion: version,
265
266
  hosts: selectedHosts,
266
267
  managedFiles,
267
268
  managedTrees,
268
269
  }, null, 2)}\n`;
269
270
  changed = await writeIfChanged(projectPath(root, CONFIG_PATH), config) || changed;
270
271
 
271
- return { changed, installed, preserved, hosts: selectedHosts };
272
+ return {
273
+ changed,
274
+ installed,
275
+ preserved,
276
+ hosts: selectedHosts,
277
+ previousVersion: previous?.packageVersion ?? null,
278
+ version,
279
+ };
272
280
  }
273
281
 
274
282
  export async function installWorkflow(options = {}) {
@@ -276,6 +284,37 @@ export async function installWorkflow(options = {}) {
276
284
  return installTransaction(root, (stage) => installPrepared({ ...options, root: stage }));
277
285
  }
278
286
 
287
+ // Managed paths whose bytes differ from this package's source: files an install
288
+ // preserved (local edits, formatter passes, older copies) next to newer ones.
289
+ // Trees list the differing files inside them; deleting the tree is the fix.
290
+ export async function managedDrift({ root = process.cwd(), packageRoot = modulePackageRoot, hosts = [] } = {}) {
291
+ root = path.resolve(root);
292
+ packageRoot = path.resolve(packageRoot);
293
+ const drift = [];
294
+ const trees = [
295
+ ...normalizeHosts(hosts).map((host) => ['skills/workflow', HOSTS[host].skillDir]),
296
+ ['src/graph', GRAPH_PATH],
297
+ ];
298
+ for (const [sourceRelative, relative] of trees) {
299
+ const target = projectPath(root, relative);
300
+ if (!await exists(target)) continue;
301
+ const expected = await treeFiles(path.join(packageRoot, sourceRelative));
302
+ const actual = await treeFiles(target);
303
+ const files = [...new Set([...expected.keys(), ...actual.keys()])]
304
+ .filter((file) => expected.get(file) !== actual.get(file))
305
+ .sort();
306
+ if (files.length) drift.push({ relative, files });
307
+ }
308
+ for (const [sourceRelative, relative] of [...TEMPLATE_PATHS, ['assets/check.mjs', CHECKER_PATH]]) {
309
+ const target = projectPath(root, relative);
310
+ if (!await exists(target)) continue;
311
+ if (await fileHash(target) !== await fileHash(path.join(packageRoot, sourceRelative))) {
312
+ drift.push({ relative, files: [] });
313
+ }
314
+ }
315
+ return drift;
316
+ }
317
+
279
318
  async function removeEmptyParents(file, stopAt) {
280
319
  let current = path.dirname(file);
281
320
  while (current.startsWith(stopAt) && current !== stopAt) {
package/src/jira.mjs CHANGED
@@ -2,10 +2,9 @@ import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
- import { checkArtifact, checkGate, isGateMetadataLine } from '../assets/check.mjs';
5
+ import { STORY_LAYOUTS, checkArtifact, checkGate, isGateMetadataLine, storyRecordZones } from '../assets/check.mjs';
6
6
  import { safePath } from './install-transaction.mjs';
7
7
 
8
- const HEADINGS = ['Goal', 'Domain', 'MUST', 'SHOULD', 'OUT', 'Decisions', 'Verify'];
9
8
  const hash = (value) => createHash('sha256').update(value).digest('hex');
10
9
  const textNode = (text) => ({ type: 'text', text });
11
10
  const paragraph = (text) => ({ type: 'paragraph', content: [textNode(text)] });
@@ -16,21 +15,21 @@ export function formatStory(text) {
16
15
  if (!summary || summary.length > 255) throw new Error('Story title is missing or exceeds 255 characters.');
17
16
  const sections = [];
18
17
  let fenced = false;
19
- let trailingGates = false;
20
- for (const line of text.replace(/\r\n/g, '\n').split('\n')) {
18
+ // Only the trailing record block after Verify (optionally opened by "---") is
19
+ // metadata; the checker reads the same zones. Similarly named prose stays content.
20
+ const normalized = text.replace(/\r\n/g, '\n');
21
+ const { footerStart } = storyRecordZones(normalized);
22
+ for (const line of normalized.split('\n').slice(0, footerStart)) {
21
23
  if (/^\s*(?:`{3,}|~{3,})/.test(line)) fenced = !fenced;
22
- // Only a trailing gate block after Verify is metadata, not similarly named prose.
23
- const gateLine = isGateMetadataLine(line);
24
- if (!fenced && sections.at(-1)?.heading === 'Verify' && gateLine) trailingGates = true;
25
- if (trailingGates) {
26
- if (gateLine || !line.trim()) continue;
24
+ if (!fenced && sections.at(-1)?.heading === 'Verify' && isGateMetadataLine(line)) {
27
25
  throw new Error('Gate metadata must follow all Verify content or move to the Story preamble.');
28
26
  }
29
27
  const heading = !fenced && line.match(/^##\s+(.+?)\s*$/);
30
28
  if (heading) sections.push({ heading: heading[1], lines: [] });
31
29
  else if (sections.length) sections.at(-1).lines.push(line);
32
30
  }
33
- if (!isDeepStrictEqual(sections.map((section) => section.heading), HEADINGS) || fenced) {
31
+ const headings = sections.map((section) => section.heading);
32
+ if (!Object.values(STORY_LAYOUTS).some((layout) => isDeepStrictEqual(headings, [...layout])) || fenced) {
34
33
  throw new Error('Story needs exactly the seven canonical sections in order and closed code fences.');
35
34
  }
36
35
  const content = [];
@@ -108,15 +107,17 @@ export async function publishStory({ root = process.cwd(), file, target, adapter
108
107
  if (!shape.ok) throw new Error('Story validation failed (shape or G1/G4 evidence). Run the local checker privately to inspect the details.');
109
108
  const preview = { status: 'preview', ...formatted };
110
109
  if (publish !== true || !adapter || !target?.project || !target?.siteUrl) return preview;
111
- const metadata = original.slice(0, /^##[\t ]+/m.exec(original)?.index ?? 0);
112
- if (!metadata.split(/\r?\n/).every((line) => /^(?:\s*|# Story: .+|Status: .+|Owner: .+|Understanding gate \(G[134]\): .+|G4: .+)$/.test(line))) {
110
+ // Records live in the preamble (v1) or the trailing footer after Verify (v2), outside fences.
111
+ const zones = storyRecordZones(original);
112
+ if (!zones.preamble.every((line) => /^(?:\s*|# Story: .+|Status: .+|Owner: .+|Lane: .+|Understanding gate \(G[134]\): .+|G4: .+)$/.test(line))) {
113
113
  throw new Error('Jira publication requires plain Story metadata; comments, fences and other blocks are not allowed in the preamble.');
114
114
  }
115
+ const metadata = [...zones.preamble, ...zones.footer].join('\n');
115
116
  const statuses = [...metadata.matchAll(/^Status:[\t ]*(.+)$/gmi)];
116
117
  const approvals = [...original.matchAll(/^Understanding gate \(G1\):.*$/gmi)];
117
118
  if (statuses.length !== 1 || !/^Status:[\t ]*(Approved|Delivered)[\t ]*\r?$/mi.test(metadata)
118
119
  || approvals.length !== 1 || !metadata.includes(approvals[0][0])) {
119
- throw new Error('Jira publication requires one Approved Status and one G1 record in the Story metadata.');
120
+ throw new Error('Jira publication requires one Approved Status and one G1 record in the Story metadata (preamble or record footer).');
120
121
  }
121
122
  const gate = await checkGate({ root, file: storyFile, gate: 'G1' });
122
123
  if (!gate.ok) throw new Error('Jira publication requires valid G1 evidence. Run the local checker privately.');
@@ -5,13 +5,13 @@ export const MANAGED_BLOCK = `${START_MARKER}
5
5
  ## AI workflow
6
6
 
7
7
  - Start product or engineering work with the \`workflow\` skill before implementation.
8
- - Keep one concise canonical Story contract: Goal, Domain, MUST, SHOULD, OUT, Decisions, Verify.
8
+ - Keep one concise canonical Story contract: Goal, Domain, Decisions, MUST, SHOULD, OUT, Verify, then a record footer.
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
- - 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.
11
+ - After G1, automatically run the installed graph with \`node .ai-workflow/bin/graph.mjs\`: \`light\` for a \`Lane: light\` Story, otherwise \`go\` and \`complete\` per node; record G1/G4 with \`approve\` after the human's reply. Follow the workflow graph reference; record node evidence, route failures and require graph readiness before G4. No separate npm dependency or Graph opt-in is needed.
12
12
  - Within an assigned kit graph node, apply only its role/task procedure and return evidence to that run. Office assigns roles and launches agents; the kit graph still controls readiness, joins and failure routing. Do not recursively start full delivery workflows.
13
13
  - Use compatible Superpowers focused caller-owned planning, TDD, diagnosis, bounded review and fresh-verification skills with CE verified learning capture; CE planning and review are explicit alternatives. Simplify inline by default; optional \`ce-simplify-code\` workers share the review allocation. Read skill-integration for exact modes, fallback and host limits. Do not nest end-to-end workflows or repeat approved plans. High-risk work retains G3.
14
- - 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.
14
+ - Do not merge non-trivial changes until the workflow's G4 gate records the human's own decision on behavior, an invariant/failure path, and the evidence boundary: explicit approval of the AI summary, or restatement for G3 work.
15
15
  - Configure the project verification profile using the workflow verification reference. Run required checks through Graph \`verify\`; inspect actual exit results/logs. Code changes make review/checks stale. Host model selection follows the workflow model policy; unknown actual model/cost stay unknown.
16
16
  - \`node .ai-workflow/bin/check.mjs story <story-file>\` checks document shape/gate presence only. Report its exit code, and require \`node .ai-workflow/bin/graph.mjs delivery <run.json>\` after real G4 for bound execution/approval validation.
17
17
  ${END_MARKER}`;
@@ -0,0 +1,28 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ export async function readPackageVersion(packageRoot) {
5
+ try {
6
+ return JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8')).version;
7
+ } catch {
8
+ return '3.0.0';
9
+ }
10
+ }
11
+
12
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
13
+
14
+ // Negative when left < right, positive when left > right, 0 when equal, null when
15
+ // either side is not a version (a hand-edited or missing packageVersion).
16
+ export function compareVersions(left, right) {
17
+ const a = SEMVER.exec(String(left ?? ''));
18
+ const b = SEMVER.exec(String(right ?? ''));
19
+ if (!a || !b) return null;
20
+ for (let index = 1; index <= 3; index += 1) {
21
+ const difference = Number(a[index]) - Number(b[index]);
22
+ if (difference) return Math.sign(difference);
23
+ }
24
+ if (a[4] === b[4]) return 0;
25
+ if (!a[4]) return 1;
26
+ if (!b[4]) return -1;
27
+ return a[4] < b[4] ? -1 : 1;
28
+ }