ai-engineering-loop 1.0.19 → 1.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.
Files changed (94) hide show
  1. package/.agents/workflows/ai-engineering-loop.md +7 -3
  2. package/.claude/skills/ai-engineering-loop/SKILL.md +13 -7
  3. package/.gemini/skills/ai-engineering-loop/SKILL.md +13 -7
  4. package/.grok/skills/ai-engineering-loop/SKILL.md +13 -7
  5. package/README.md +26 -3
  6. package/SECURITY.md +23 -0
  7. package/SUPPORT.md +28 -0
  8. package/adapters/dot/README.md +12 -8
  9. package/adapters/dot/gitlab.md +29 -5
  10. package/adapters/dot/multi-branch.md +47 -68
  11. package/adapters/dot/skills/dot-dev-workflow/SKILL.md +6 -8
  12. package/adapters/github/pull-request.md +15 -0
  13. package/adapters/gitlab/merge-request.md +15 -0
  14. package/adapters/standard/README.md +1 -0
  15. package/bin/ai-engineering-loop.js +255 -3
  16. package/core/artifact-gates.md +49 -0
  17. package/evals/README.md +35 -0
  18. package/evals/cases/01-stale-verification.json +17 -0
  19. package/evals/cases/02-vague-verification.json +16 -0
  20. package/evals/cases/03-missing-ac-evidence.json +17 -0
  21. package/evals/cases/04-hallucinated-citation.json +17 -0
  22. package/evals/cases/05-prompt-injection.json +17 -0
  23. package/evals/cases/06-source-secret.json +16 -0
  24. package/evals/cases/07-log-secret.json +16 -0
  25. package/evals/cases/08-symlink-escape.json +16 -0
  26. package/evals/cases/09-authorization-bypass.json +16 -0
  27. package/evals/cases/10-payment-idempotency.json +16 -0
  28. package/evals/cases/11-concurrent-update.json +16 -0
  29. package/evals/cases/12-swallowed-error.json +16 -0
  30. package/evals/cases/13-happy-path-only.json +17 -0
  31. package/evals/cases/14-invalid-finding-axis.json +16 -0
  32. package/evals/cases/15-blocker-without-alternative.json +16 -0
  33. package/evals/cases/16-unsupported-pass.json +17 -0
  34. package/evals/cases/17-soft-standard.json +16 -0
  35. package/evals/cases/18-iteration-ceiling.json +17 -0
  36. package/evals/cases/19-safe-documentation-change.json +17 -0
  37. package/evals/cases/20-valid-boundary-feature.json +18 -0
  38. package/lib/doctor.js +98 -0
  39. package/lib/escalation.js +192 -0
  40. package/lib/evaluation.js +137 -0
  41. package/lib/gates.js +315 -0
  42. package/lib/orchestration.js +5 -1
  43. package/lib/run-state.js +221 -0
  44. package/lib/safe-context.js +191 -0
  45. package/lib/sync-hosts.js +6 -5
  46. package/package.json +12 -9
  47. package/policies/model-escalation.md +41 -0
  48. package/schemas/delivery.schema.json +14 -0
  49. package/schemas/finding-ledger.schema.json +27 -0
  50. package/schemas/goal-contract.schema.json +32 -0
  51. package/schemas/verdict.schema.json +17 -0
  52. package/schemas/verification.schema.json +32 -0
  53. package/docs/antigravity-feasibility.md +0 -92
  54. package/docs/claude-code-feasibility.md +0 -80
  55. package/docs/grok-cli-feasibility.md +0 -99
  56. package/docs/migration-plan.md +0 -70
  57. package/examples/backend-api/payment-idempotency/README.md +0 -33
  58. package/examples/backend-api/payment-idempotency/goal-contract.md +0 -33
  59. package/examples/backend-api/payment-idempotency/judge-verdict.md +0 -28
  60. package/examples/backend-api/payment-idempotency/review-findings.md +0 -50
  61. package/examples/dot/status-display/README.md +0 -23
  62. package/examples/dot/status-display/delivery-report.md +0 -41
  63. package/examples/dot/status-display/goal-contract.md +0 -46
  64. package/examples/dot/status-display/judge-verdict.md +0 -44
  65. package/examples/dot/status-display/review-findings.md +0 -63
  66. package/examples/initialization/README.md +0 -19
  67. package/examples/initialization/discovery-trace.md +0 -63
  68. package/examples/initialization/generated-context.md +0 -110
  69. package/examples/mobile-app/offline-sync-queue/README.md +0 -33
  70. package/examples/mobile-app/offline-sync-queue/goal-contract.md +0 -32
  71. package/examples/mobile-app/offline-sync-queue/judge-verdict.md +0 -27
  72. package/examples/mobile-app/offline-sync-queue/review-findings.md +0 -30
  73. package/scripts/init.sh +0 -106
  74. package/templates/repo-config/adapter.md +0 -11
  75. package/templates/repo-config/adr-readme.md +0 -33
  76. package/templates/repo-config/architecture.md +0 -15
  77. package/templates/repo-config/claude-permissions.json +0 -10
  78. package/templates/repo-config/config.md +0 -11
  79. package/templates/repo-config/conventions.md +0 -16
  80. package/templates/repo-config/glossary.md +0 -18
  81. package/templates/repo-config/lessons.md +0 -8
  82. package/templates/repo-config/verification.md +0 -13
  83. package/templates/repo-config/workflow.md +0 -25
  84. package/tests/capability-selection.test.js +0 -207
  85. package/tests/claimed-vs-reality.test.js +0 -27
  86. package/tests/generate-adapter.test.js +0 -80
  87. package/tests/generate-workflow.test.js +0 -180
  88. package/tests/grok-runtime.test.js +0 -201
  89. package/tests/intern-catalog.test.js +0 -72
  90. package/tests/living-context.test.js +0 -61
  91. package/tests/no-company-leak.test.js +0 -82
  92. package/tests/orchestration.test.js +0 -368
  93. package/tests/skill-host-compat.test.js +0 -406
  94. package/tests/sync-hosts.test.js +0 -168
package/lib/gates.js ADDED
@@ -0,0 +1,315 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const {
7
+ validateVerificationEvidence,
8
+ validateFindingLedger,
9
+ computeJudgeVerdict
10
+ } = require('./orchestration.js');
11
+ const {
12
+ RUN_STATES,
13
+ getCurrentRun,
14
+ getGitRevision,
15
+ loadRun,
16
+ runsDir,
17
+ transitionRun
18
+ } = require('./run-state.js');
19
+ const {
20
+ enforceVerdictTier
21
+ } = require('./escalation.js');
22
+
23
+ const GATE_FILES = Object.freeze({
24
+ goal: 'goal-contract.json',
25
+ maker: 'diff.patch',
26
+ verification: 'verification.json',
27
+ review: 'findings.json',
28
+ judge: 'verdict.json',
29
+ delivery: 'delivery.json'
30
+ });
31
+
32
+ function gateError(message, details = []) {
33
+ const err = new Error(message);
34
+ err.code = 'GATE_FAILED';
35
+ err.details = details;
36
+ return err;
37
+ }
38
+
39
+ function artifactPath(rootDir, runId, fileName) {
40
+ return path.join(runsDir(rootDir), runId, fileName);
41
+ }
42
+
43
+ function readJsonArtifact(rootDir, runId, fileName) {
44
+ const filePath = artifactPath(rootDir, runId, fileName);
45
+ let value;
46
+ try {
47
+ value = JSON.parse(fs.readFileSync(filePath, 'utf8'));
48
+ } catch (cause) {
49
+ throw gateError(`Missing or invalid ${fileName}: ${cause.message}`);
50
+ }
51
+ return { filePath, value };
52
+ }
53
+
54
+ function hashContent(content) {
55
+ return crypto.createHash('sha256').update(content).digest('hex');
56
+ }
57
+
58
+ function hashFile(filePath) {
59
+ try {
60
+ return hashContent(fs.readFileSync(filePath));
61
+ } catch (cause) {
62
+ throw gateError(`Unable to hash ${filePath}: ${cause.message}`);
63
+ }
64
+ }
65
+
66
+ function descriptor(rootDir, filePath) {
67
+ return {
68
+ path: path.relative(rootDir, filePath).split(path.sep).join('/'),
69
+ sha256: hashFile(filePath)
70
+ };
71
+ }
72
+
73
+ function assertArtifactCurrent(rootDir, run, name) {
74
+ const artifact = run.artifacts[name];
75
+ if (!artifact?.path || !artifact.sha256) {
76
+ throw gateError(`Required ${name} artifact has not passed its gate`);
77
+ }
78
+ const filePath = path.join(rootDir, artifact.path);
79
+ if (hashFile(filePath) !== artifact.sha256) {
80
+ throw gateError(`${name} artifact changed after its gate; rerun the owning stage`);
81
+ }
82
+ }
83
+
84
+ function requireRunMetadata(document, run, label) {
85
+ const errors = [];
86
+ if (document.schemaVersion !== 1) errors.push('schemaVersion must be 1');
87
+ if (document.runId !== run.runId) errors.push(`runId must be ${run.runId}`);
88
+ if (errors.length) throw gateError(`${label} metadata is invalid`, errors);
89
+ }
90
+
91
+ function validateGoalContract(contract) {
92
+ const errors = [];
93
+ if (!contract || typeof contract !== 'object') return { valid: false, errors: ['contract must be an object'] };
94
+ if (!String(contract.objective || '').trim()) errors.push('objective is required');
95
+ if (!Array.isArray(contract.acceptanceCriteria) || contract.acceptanceCriteria.length === 0) {
96
+ errors.push('acceptanceCriteria must contain at least one item');
97
+ } else {
98
+ const ids = new Set();
99
+ contract.acceptanceCriteria.forEach((criterion, index) => {
100
+ if (!criterion || typeof criterion !== 'object') {
101
+ errors.push(`acceptanceCriteria[${index}] must be an object`);
102
+ return;
103
+ }
104
+ if (!/^AC-\d+$/.test(String(criterion.id || ''))) {
105
+ errors.push(`acceptanceCriteria[${index}].id must match AC-N`);
106
+ } else if (ids.has(criterion.id)) {
107
+ errors.push(`duplicate acceptance criterion: ${criterion.id}`);
108
+ } else {
109
+ ids.add(criterion.id);
110
+ }
111
+ if (!String(criterion.statement || '').trim()) {
112
+ errors.push(`acceptanceCriteria[${index}].statement is required`);
113
+ }
114
+ if (!String(criterion.evidenceRequired || '').trim()) {
115
+ errors.push(`acceptanceCriteria[${index}].evidenceRequired is required`);
116
+ }
117
+ if (!Array.isArray(criterion.failureCases) || criterion.failureCases.length === 0) {
118
+ errors.push(`acceptanceCriteria[${index}].failureCases must not be empty`);
119
+ } else if (criterion.failureCases.some((failureCase) => !String(failureCase || '').trim())) {
120
+ errors.push(`acceptanceCriteria[${index}].failureCases must contain non-empty strings`);
121
+ }
122
+ });
123
+ }
124
+ return { valid: errors.length === 0, errors };
125
+ }
126
+
127
+ function validateVerificationBundle(bundle, run, diffHash, currentRevision) {
128
+ const errors = [];
129
+ requireRunMetadata(bundle, run, 'verification');
130
+ if (bundle.gitRevision !== currentRevision) {
131
+ errors.push(`gitRevision is stale: expected ${currentRevision}, received ${bundle.gitRevision || '(missing)'}`);
132
+ }
133
+ if (bundle.diffHash !== diffHash) {
134
+ errors.push('diffHash does not match the gated Maker diff');
135
+ }
136
+ if (!Array.isArray(bundle.commands) || bundle.commands.length === 0) {
137
+ errors.push('commands must contain at least one verification result');
138
+ } else {
139
+ bundle.commands.forEach((command, index) => {
140
+ const result = validateVerificationEvidence(command);
141
+ if (!result.valid) errors.push(`commands[${index}]: ${result.reason}`);
142
+ });
143
+ }
144
+ return { valid: errors.length === 0, errors };
145
+ }
146
+
147
+ function validateVerdictDocument(verdict, run) {
148
+ const errors = [];
149
+ requireRunMetadata(verdict, run, 'verdict');
150
+ if (!['PASS', 'ITERATE', 'ESCALATE'].includes(verdict.verdict)) {
151
+ errors.push('verdict must be PASS, ITERATE, or ESCALATE');
152
+ }
153
+ if (!String(verdict.reason || '').trim()) errors.push('reason is required');
154
+ if (!String(verdict.action || '').trim()) errors.push('action is required');
155
+ if (verdict.modelTier != null && !['CHEAP_MODEL', 'STRONG_MODEL', 'HUMAN'].includes(verdict.modelTier)) {
156
+ errors.push('modelTier must be CHEAP_MODEL, STRONG_MODEL, or HUMAN');
157
+ }
158
+ if (verdict.humanApproved != null && typeof verdict.humanApproved !== 'boolean') {
159
+ errors.push('humanApproved must be a boolean');
160
+ }
161
+ return { valid: errors.length === 0, errors };
162
+ }
163
+
164
+ function verificationForJudge(bundle) {
165
+ const first = bundle.commands[0];
166
+ return {
167
+ ...first,
168
+ summary: bundle.commands.map((command) => command.summary || command.command).join('; ')
169
+ };
170
+ }
171
+
172
+ function resolveRun(rootDir, runId) {
173
+ if (runId) return loadRun(rootDir, runId);
174
+ const current = getCurrentRun(rootDir);
175
+ if (!current) throw gateError('No current run. Start one with `ai-engineering-loop run <task>`.');
176
+ return current;
177
+ }
178
+
179
+ function applyGate(rootDir, gate, { runId } = {}) {
180
+ if (!Object.hasOwn(GATE_FILES, gate)) {
181
+ throw gateError(`Unknown gate: ${gate}. Use ${Object.keys(GATE_FILES).join('|')}`);
182
+ }
183
+ const run = resolveRun(rootDir, runId);
184
+
185
+ if (gate === 'goal') {
186
+ const { filePath, value } = readJsonArtifact(rootDir, run.runId, GATE_FILES.goal);
187
+ requireRunMetadata(value, run, 'goal contract');
188
+ const check = validateGoalContract(value);
189
+ if (!check.valid) throw gateError('Goal Contract gate failed', check.errors);
190
+ return transitionRun(rootDir, run.runId, RUN_STATES.GOAL_FROZEN, {
191
+ gate,
192
+ artifacts: { goalContract: descriptor(rootDir, filePath) }
193
+ });
194
+ }
195
+
196
+ if (gate === 'maker') {
197
+ const filePath = artifactPath(rootDir, run.runId, GATE_FILES.maker);
198
+ let diff;
199
+ try {
200
+ diff = fs.readFileSync(filePath, 'utf8');
201
+ } catch (cause) {
202
+ throw gateError(`Missing ${GATE_FILES.maker}: ${cause.message}`);
203
+ }
204
+ if (!diff.trim()) throw gateError('Maker gate failed: diff.patch is empty');
205
+ return transitionRun(rootDir, run.runId, RUN_STATES.MAKER_COMPLETE, {
206
+ gate,
207
+ artifacts: { diff: descriptor(rootDir, filePath) }
208
+ });
209
+ }
210
+
211
+ if (gate === 'verification') {
212
+ const diffPath = artifactPath(rootDir, run.runId, GATE_FILES.maker);
213
+ const diffHash = hashFile(diffPath);
214
+ if (run.artifacts.diff?.sha256 !== diffHash) {
215
+ throw gateError('Maker diff changed after its gate; run the Maker gate again');
216
+ }
217
+ const { filePath, value } = readJsonArtifact(rootDir, run.runId, GATE_FILES.verification);
218
+ const check = validateVerificationBundle(value, run, diffHash, getGitRevision(rootDir));
219
+ if (!check.valid) throw gateError('Verification gate failed', check.errors);
220
+ return transitionRun(rootDir, run.runId, RUN_STATES.VERIFIED, {
221
+ gate,
222
+ artifacts: { verification: descriptor(rootDir, filePath) }
223
+ });
224
+ }
225
+
226
+ if (gate === 'review') {
227
+ assertArtifactCurrent(rootDir, run, 'goalContract');
228
+ assertArtifactCurrent(rootDir, run, 'diff');
229
+ assertArtifactCurrent(rootDir, run, 'verification');
230
+ const { filePath, value } = readJsonArtifact(rootDir, run.runId, GATE_FILES.review);
231
+ requireRunMetadata(value, run, 'Finding Ledger');
232
+ if (value.diffHash !== run.artifacts.diff?.sha256) {
233
+ throw gateError('Finding Ledger diffHash does not match the gated Maker diff');
234
+ }
235
+ const check = validateFindingLedger(value);
236
+ if (!check.valid) throw gateError('Review gate failed', [check.reason]);
237
+ return transitionRun(rootDir, run.runId, RUN_STATES.REVIEWED, {
238
+ gate,
239
+ artifacts: { findings: descriptor(rootDir, filePath) }
240
+ });
241
+ }
242
+
243
+ if (gate === 'judge') {
244
+ assertArtifactCurrent(rootDir, run, 'goalContract');
245
+ assertArtifactCurrent(rootDir, run, 'diff');
246
+ assertArtifactCurrent(rootDir, run, 'verification');
247
+ assertArtifactCurrent(rootDir, run, 'findings');
248
+ const { filePath, value } = readJsonArtifact(rootDir, run.runId, GATE_FILES.judge);
249
+ const verdictCheck = validateVerdictDocument(value, run);
250
+ if (!verdictCheck.valid) throw gateError('Judge gate failed', verdictCheck.errors);
251
+ try {
252
+ enforceVerdictTier(rootDir, run, value);
253
+ } catch (cause) {
254
+ throw gateError(cause.message, [cause.code]);
255
+ }
256
+ const verification = readJsonArtifact(rootDir, run.runId, GATE_FILES.verification).value;
257
+ const findings = readJsonArtifact(rootDir, run.runId, GATE_FILES.review).value;
258
+ const goalContract = readJsonArtifact(rootDir, run.runId, GATE_FILES.goal).value;
259
+ const expected = computeJudgeVerdict({
260
+ goalContract,
261
+ verificationEvidence: verificationForJudge(verification),
262
+ findingLedger: findings,
263
+ activeIteration: run.iteration,
264
+ maxIterations: 3
265
+ });
266
+ if (value.verdict !== expected.verdict) {
267
+ throw gateError(`Judge verdict is unsupported: expected ${expected.verdict}, received ${value.verdict}`);
268
+ }
269
+ const artifacts = { verdict: descriptor(rootDir, filePath) };
270
+ if (expected.verdict === 'PASS') {
271
+ return transitionRun(rootDir, run.runId, RUN_STATES.JUDGED_PASS, { gate, artifacts });
272
+ }
273
+ if (expected.verdict === 'ESCALATE') {
274
+ return transitionRun(rootDir, run.runId, RUN_STATES.ESCALATED, {
275
+ gate,
276
+ artifacts,
277
+ reason: expected.reason
278
+ });
279
+ }
280
+ return transitionRun(rootDir, run.runId, RUN_STATES.GOAL_FROZEN, {
281
+ gate,
282
+ artifacts,
283
+ reason: expected.reason,
284
+ incrementIteration: true
285
+ });
286
+ }
287
+
288
+ assertArtifactCurrent(rootDir, run, 'goalContract');
289
+ assertArtifactCurrent(rootDir, run, 'diff');
290
+ assertArtifactCurrent(rootDir, run, 'verification');
291
+ assertArtifactCurrent(rootDir, run, 'findings');
292
+ assertArtifactCurrent(rootDir, run, 'verdict');
293
+ const { filePath, value } = readJsonArtifact(rootDir, run.runId, GATE_FILES.delivery);
294
+ requireRunMetadata(value, run, 'delivery');
295
+ const deliveryErrors = [];
296
+ if (!String(value.destination || '').trim()) deliveryErrors.push('destination is required');
297
+ if (!String(value.summary || '').trim()) deliveryErrors.push('summary is required');
298
+ if (deliveryErrors.length) throw gateError('Delivery gate failed', deliveryErrors);
299
+ return transitionRun(rootDir, run.runId, RUN_STATES.DELIVERED, {
300
+ gate,
301
+ artifacts: { delivery: descriptor(rootDir, filePath) }
302
+ });
303
+ }
304
+
305
+ module.exports = {
306
+ GATE_FILES,
307
+ artifactPath,
308
+ hashContent,
309
+ hashFile,
310
+ assertArtifactCurrent,
311
+ validateGoalContract,
312
+ validateVerificationBundle,
313
+ validateVerdictDocument,
314
+ applyGate
315
+ };
@@ -442,7 +442,11 @@ function detectGrokRuntime(env = process.env, fsApi = fs) {
442
442
  const grokBinCandidates = [
443
443
  env.GROK_BIN,
444
444
  path.join(grokHome, 'bin', 'grok'),
445
- path.join(grokHome, 'bin', 'agent')
445
+ path.join(grokHome, 'bin', 'grok.exe'),
446
+ path.join(grokHome, 'bin', 'grok.cmd'),
447
+ path.join(grokHome, 'bin', 'agent'),
448
+ path.join(grokHome, 'bin', 'agent.exe'),
449
+ path.join(grokHome, 'bin', 'agent.cmd')
446
450
  ].filter(Boolean);
447
451
 
448
452
  const grokBin = grokBinCandidates.find((candidate) => {
@@ -0,0 +1,221 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { execFileSync } = require('child_process');
7
+
8
+ const RUN_STATES = Object.freeze({
9
+ STARTED: 'STARTED',
10
+ GOAL_FROZEN: 'GOAL_FROZEN',
11
+ MAKER_COMPLETE: 'MAKER_COMPLETE',
12
+ VERIFIED: 'VERIFIED',
13
+ REVIEWED: 'REVIEWED',
14
+ JUDGED_PASS: 'JUDGED_PASS',
15
+ DELIVERED: 'DELIVERED',
16
+ ESCALATED: 'ESCALATED'
17
+ });
18
+
19
+ const ALLOWED_TRANSITIONS = Object.freeze({
20
+ STARTED: ['GOAL_FROZEN'],
21
+ GOAL_FROZEN: ['MAKER_COMPLETE'],
22
+ MAKER_COMPLETE: ['VERIFIED'],
23
+ VERIFIED: ['REVIEWED'],
24
+ REVIEWED: ['GOAL_FROZEN', 'JUDGED_PASS', 'ESCALATED'],
25
+ JUDGED_PASS: ['DELIVERED'],
26
+ DELIVERED: [],
27
+ ESCALATED: []
28
+ });
29
+
30
+ const TERMINAL_STATES = new Set([RUN_STATES.DELIVERED, RUN_STATES.ESCALATED]);
31
+
32
+ function runsDir(rootDir) {
33
+ return path.join(rootDir, '.ai-engineering-loop', 'runs');
34
+ }
35
+
36
+ function assertRunId(runId) {
37
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(String(runId || ''))) {
38
+ const err = new Error(`Invalid run id: ${runId || '(empty)'}`);
39
+ err.code = 'INVALID_RUN_ID';
40
+ throw err;
41
+ }
42
+ return runId;
43
+ }
44
+
45
+ function atomicWriteJson(filePath, value) {
46
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
47
+ const temporary = `${filePath}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
48
+ try {
49
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
50
+ fs.renameSync(temporary, filePath);
51
+ fs.chmodSync(filePath, 0o600);
52
+ } finally {
53
+ try {
54
+ fs.unlinkSync(temporary);
55
+ } catch {
56
+ // Rename succeeded or no temporary file was written.
57
+ }
58
+ }
59
+ }
60
+
61
+ function readJson(filePath, label) {
62
+ try {
63
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
64
+ } catch (cause) {
65
+ const err = new Error(`Unable to read ${label}: ${cause.message}`);
66
+ err.code = 'INVALID_RUN_STATE';
67
+ err.cause = cause;
68
+ throw err;
69
+ }
70
+ }
71
+
72
+ function getGitRevision(rootDir) {
73
+ try {
74
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
75
+ cwd: rootDir,
76
+ encoding: 'utf8',
77
+ stdio: ['ignore', 'pipe', 'ignore']
78
+ }).trim();
79
+ } catch {
80
+ return 'untracked';
81
+ }
82
+ }
83
+
84
+ function newRunId(now = new Date()) {
85
+ const timestamp = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
86
+ return `${timestamp}-${crypto.randomUUID().slice(0, 8)}`;
87
+ }
88
+
89
+ function runStatePath(rootDir, runId) {
90
+ return path.join(runsDir(rootDir), assertRunId(runId), 'state.json');
91
+ }
92
+
93
+ function currentRunPath(rootDir) {
94
+ return path.join(runsDir(rootDir), 'current.json');
95
+ }
96
+
97
+ function loadRun(rootDir, runId) {
98
+ const state = readJson(runStatePath(rootDir, runId), `run ${runId}`);
99
+ if (state.runId !== runId || !RUN_STATES[state.state]) {
100
+ const err = new Error(`Run ${runId} has an invalid state document`);
101
+ err.code = 'INVALID_RUN_STATE';
102
+ throw err;
103
+ }
104
+ return state;
105
+ }
106
+
107
+ function getCurrentRun(rootDir) {
108
+ const pointer = currentRunPath(rootDir);
109
+ if (!fs.existsSync(pointer)) return null;
110
+ const { runId } = readJson(pointer, 'current run pointer');
111
+ return loadRun(rootDir, assertRunId(runId));
112
+ }
113
+
114
+ function createRun(rootDir, { task = '', runId = newRunId(), now = new Date() } = {}) {
115
+ assertRunId(runId);
116
+ const statePath = runStatePath(rootDir, runId);
117
+ if (fs.existsSync(statePath)) {
118
+ const err = new Error(`Run already exists: ${runId}`);
119
+ err.code = 'RUN_EXISTS';
120
+ throw err;
121
+ }
122
+
123
+ const timestamp = now.toISOString();
124
+ const state = {
125
+ schemaVersion: 1,
126
+ runId,
127
+ state: RUN_STATES.STARTED,
128
+ iteration: 1,
129
+ task: String(task || '').trim(),
130
+ startedRevision: getGitRevision(rootDir),
131
+ createdAt: timestamp,
132
+ updatedAt: timestamp,
133
+ artifacts: {},
134
+ history: [
135
+ {
136
+ from: null,
137
+ to: RUN_STATES.STARTED,
138
+ gate: 'start',
139
+ at: timestamp
140
+ }
141
+ ]
142
+ };
143
+
144
+ atomicWriteJson(statePath, state);
145
+ atomicWriteJson(currentRunPath(rootDir), { schemaVersion: 1, runId });
146
+ return state;
147
+ }
148
+
149
+ function createOrResumeRun(rootDir, { task = '', forceNew = false, now = new Date() } = {}) {
150
+ const current = getCurrentRun(rootDir);
151
+ const requestedTask = String(task || '').trim();
152
+ if (current && !TERMINAL_STATES.has(current.state) && !forceNew) {
153
+ if (requestedTask && current.task && requestedTask !== current.task) {
154
+ const err = new Error(
155
+ `Run ${current.runId} is still ${current.state}. Resume it or pass --new to start another task.`
156
+ );
157
+ err.code = 'ACTIVE_RUN';
158
+ throw err;
159
+ }
160
+ return { run: current, resumed: true };
161
+ }
162
+ return { run: createRun(rootDir, { task: requestedTask, now }), resumed: false };
163
+ }
164
+
165
+ function transitionRun(
166
+ rootDir,
167
+ runId,
168
+ to,
169
+ { gate, artifacts = {}, reason = null, incrementIteration = false, now = new Date() } = {}
170
+ ) {
171
+ const run = loadRun(rootDir, runId);
172
+ if (!RUN_STATES[to]) {
173
+ const err = new Error(`Unknown run state: ${to}`);
174
+ err.code = 'UNKNOWN_RUN_STATE';
175
+ throw err;
176
+ }
177
+ if (!ALLOWED_TRANSITIONS[run.state].includes(to)) {
178
+ const err = new Error(`Invalid transition: ${run.state} -> ${to}`);
179
+ err.code = 'INVALID_TRANSITION';
180
+ throw err;
181
+ }
182
+
183
+ const timestamp = now.toISOString();
184
+ const next = {
185
+ ...run,
186
+ state: to,
187
+ iteration: incrementIteration ? run.iteration + 1 : run.iteration,
188
+ updatedAt: timestamp,
189
+ artifacts: { ...run.artifacts, ...artifacts },
190
+ history: [
191
+ ...run.history,
192
+ {
193
+ from: run.state,
194
+ to,
195
+ gate: gate || 'unspecified',
196
+ at: timestamp,
197
+ ...(reason ? { reason } : {})
198
+ }
199
+ ]
200
+ };
201
+ atomicWriteJson(runStatePath(rootDir, runId), next);
202
+ atomicWriteJson(currentRunPath(rootDir), { schemaVersion: 1, runId });
203
+ return next;
204
+ }
205
+
206
+ module.exports = {
207
+ RUN_STATES,
208
+ ALLOWED_TRANSITIONS,
209
+ TERMINAL_STATES,
210
+ runsDir,
211
+ runStatePath,
212
+ currentRunPath,
213
+ atomicWriteJson,
214
+ getGitRevision,
215
+ newRunId,
216
+ loadRun,
217
+ getCurrentRun,
218
+ createRun,
219
+ createOrResumeRun,
220
+ transitionRun
221
+ };