ai-engineering-loop 2.2.0 → 2.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 (133) hide show
  1. package/.agents/skills/ai-engineering-loop/SKILL.md +4 -4
  2. package/.agents/skills/ai-engineering-loop/references/loop-deliver.md +2 -2
  3. package/.agents/skills/ai-engineering-loop/references/loop-goal.md +3 -3
  4. package/.agents/skills/ai-engineering-loop/references/loop-maker.md +1 -0
  5. package/.agents/skills/ai-engineering-loop/references/loop-review.md +3 -4
  6. package/.agents/skills/ai-engineering-loop/references/loop-risky.md +1 -0
  7. package/.agents/skills/ai-engineering-loop/references/loop-verify.md +3 -3
  8. package/.claude/agents/judge.md +5 -2
  9. package/.grok/agents/judge.md +5 -2
  10. package/CHANGELOG.md +60 -0
  11. package/README.md +1 -0
  12. package/THIRD_PARTY_NOTICES.md +11 -0
  13. package/adapters/spec/LICENSE +202 -0
  14. package/adapters/spec/NOTICE-AEL.md +26 -0
  15. package/adapters/spec/agents/ael-spec-codebase-details.md +71 -0
  16. package/adapters/spec/agents/ael-spec-comprehension.md +71 -0
  17. package/adapters/spec/agents/ael-spec-design.md +65 -0
  18. package/adapters/spec/agents/ael-spec-implementation-readiness.md +64 -0
  19. package/adapters/spec/agents/ael-spec-structural.md +67 -0
  20. package/adapters/spec/agents/ael-spec-style.md +68 -0
  21. package/adapters/spec/agents/ael-spec-synthesizer.md +73 -0
  22. package/adapters/spec/agents/ael-spec-zoom-out.md +76 -0
  23. package/adapters/spec/skills/ael-spec-brainstorm/SKILL.md +265 -0
  24. package/adapters/spec/skills/ael-spec-draft/SKILL.md +315 -0
  25. package/adapters/spec/skills/ael-spec-draft/references/design_doc.md +179 -0
  26. package/adapters/spec/skills/ael-spec-drift/SKILL.md +68 -0
  27. package/adapters/spec/skills/ael-spec-resolve/SKILL.md +188 -0
  28. package/adapters/spec/skills/ael-spec-review/SKILL.md +403 -0
  29. package/adapters/spec/skills/ael-spec-review-loop/SKILL.md +191 -0
  30. package/adapters/spec/standards/ael-spec-execution-instructions.md +36 -0
  31. package/adapters/spec/standards/ael-spec-feature-spec-standard.md +38 -0
  32. package/adapters/spec/standards/ael-spec-heilmeier-standard.md +32 -0
  33. package/adapters/spec/standards/ael-spec-implementation-readiness-standard.md +36 -0
  34. package/adapters/spec/standards/ael-spec-re-implementation-standard.md +39 -0
  35. package/adapters/spec/standards/ael-spec-zoom-out-standard.md +62 -0
  36. package/agents/maker.md +1 -1
  37. package/agents/shared/judge.body.md +5 -2
  38. package/bin/ai-engineering-loop.js +344 -78
  39. package/core/definition-of-done.md +2 -2
  40. package/core/escalation-policy.md +1 -1
  41. package/core/goal-contract.md +1 -1
  42. package/core/iteration-policy.md +2 -1
  43. package/core/judge-policy.md +10 -4
  44. package/core/orchestration-model.md +8 -7
  45. package/core/repo-config-schema.md +2 -2
  46. package/core/runtime-safety.md +3 -3
  47. package/core/spec-pack.md +47 -0
  48. package/lib/auto-update.js +8 -14
  49. package/lib/claimed-vs-reality.js +2 -2
  50. package/lib/cli-args.js +3 -1
  51. package/lib/design-ref.js +178 -0
  52. package/lib/docs.js +1 -1
  53. package/lib/doctor.js +0 -6
  54. package/lib/escalation.js +1 -1
  55. package/lib/fsutil.js +88 -0
  56. package/lib/gates.js +70 -27
  57. package/lib/generate-workflow.js +0 -29
  58. package/lib/goal-runtime.js +8 -2
  59. package/lib/guard-hooks.js +26 -7
  60. package/lib/guard.js +100 -10
  61. package/lib/hosts/doctor.js +17 -7
  62. package/lib/impact-map.js +31 -8
  63. package/lib/jsonl-ledger.js +104 -0
  64. package/lib/learn.js +4 -9
  65. package/lib/loop-groups.js +0 -25
  66. package/lib/migrations.js +1 -5
  67. package/lib/no-progress.js +119 -0
  68. package/lib/node-evidence.js +1 -5
  69. package/lib/orchestration.js +5 -361
  70. package/lib/personal-workflow.js +1 -1
  71. package/lib/quick.js +152 -0
  72. package/lib/receipt.js +13 -6
  73. package/lib/recipe-builder.js +3 -35
  74. package/lib/recipe-graph.js +2 -63
  75. package/lib/recipe.js +2 -4
  76. package/lib/review-ingest.js +116 -0
  77. package/lib/run-abandon.js +2 -1
  78. package/lib/run-compaction.js +4 -12
  79. package/lib/run-interactions.js +16 -71
  80. package/lib/run-lifecycle.js +25 -77
  81. package/lib/run-state.js +68 -17
  82. package/lib/run-watcher.js +11 -14
  83. package/lib/runtime-files.js +45 -1
  84. package/lib/safe-context.js +17 -6
  85. package/lib/sandbox.js +2 -1
  86. package/lib/smart-context.js +13 -14
  87. package/lib/spawn-command.js +94 -0
  88. package/lib/studio-layout.js +2 -8
  89. package/lib/studio-runtime.js +2 -1
  90. package/lib/studio-server.js +25 -5
  91. package/lib/sync-hosts.js +25 -2
  92. package/lib/tier.js +36 -10
  93. package/lib/user-state.js +2 -17
  94. package/lib/verification-lanes.js +115 -0
  95. package/lib/verification-recorder.js +110 -22
  96. package/lib/workflow-runtime.js +7 -4
  97. package/package.json +1 -2
  98. package/policies/review-budget.md +1 -1
  99. package/schemas/goal-contract.schema.json +87 -11
  100. package/.claude/skills/ai-engineering-loop/SKILL.md +0 -62
  101. package/.claude/skills/ai-engineering-loop/references/loop-commands.md +0 -24
  102. package/.claude/skills/ai-engineering-loop/references/loop-deliver.md +0 -10
  103. package/.claude/skills/ai-engineering-loop/references/loop-goal.md +0 -11
  104. package/.claude/skills/ai-engineering-loop/references/loop-hosts.md +0 -48
  105. package/.claude/skills/ai-engineering-loop/references/loop-maker.md +0 -14
  106. package/.claude/skills/ai-engineering-loop/references/loop-review.md +0 -20
  107. package/.claude/skills/ai-engineering-loop/references/loop-risky.md +0 -9
  108. package/.claude/skills/ai-engineering-loop/references/loop-verify.md +0 -20
  109. package/.claude/skills/animate/RECIPES.md +0 -324
  110. package/.claude/skills/animate/SKILL.md +0 -207
  111. package/.claude/skills/animate-expo/RECIPES.md +0 -385
  112. package/.claude/skills/animate-expo/SKILL.md +0 -263
  113. package/.claude/skills/animation-vocabulary/SKILL.md +0 -181
  114. package/.claude/skills/apple-design/SKILL.md +0 -290
  115. package/.claude/skills/ask-sonner/API.md +0 -64
  116. package/.claude/skills/ask-sonner/SKILL.md +0 -88
  117. package/.claude/skills/backend-development/SKILL.md +0 -272
  118. package/.claude/skills/backend-development/references/api-design-guidelines.md +0 -95
  119. package/.claude/skills/backend-development/references/query-and-database-best-practices.md +0 -53
  120. package/.claude/skills/backend-development/references/security-checklist.md +0 -60
  121. package/.claude/skills/emil-design-eng/SKILL.md +0 -674
  122. package/.claude/skills/find-animation-opportunities/SKILL.md +0 -140
  123. package/.claude/skills/improve-animations/AUDIT.md +0 -115
  124. package/.claude/skills/improve-animations/PLAN-TEMPLATE.md +0 -73
  125. package/.claude/skills/improve-animations/SKILL.md +0 -109
  126. package/.claude/skills/mobile-native/SKILL.md +0 -311
  127. package/.claude/skills/pick-ui-library/SKILL.md +0 -85
  128. package/.claude/skills/prototype/PICKER.md +0 -197
  129. package/.claude/skills/prototype/SKILL.md +0 -98
  130. package/.claude/skills/review-animations/SKILL.md +0 -120
  131. package/.claude/skills/review-animations/STANDARDS.md +0 -187
  132. package/.claude/skills/write-swift/SKILL.md +0 -396
  133. package/lib/intern-catalog.js +0 -53
package/lib/gates.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const crypto = require('crypto');
4
3
  const fs = require('fs');
5
4
  const path = require('path');
5
+ const { sha256: hashContent } = require('./fsutil.js');
6
6
  const {
7
7
  validateVerificationEvidence,
8
8
  validateFindingLedger,
@@ -52,6 +52,9 @@ const {
52
52
  } = require('./escalation.js');
53
53
  const { raiseTierFromDiff } = require('./tier.js');
54
54
  const { readyForDa } = require('./claimed-vs-reality.js');
55
+ const { runMaxIterations, detectNoProgress, recordIteration } = require('./no-progress.js');
56
+ const { finalVerificationStatus } = require('./verification-lanes.js');
57
+ const { checkLedgerBinding } = require('./review-ingest.js');
55
58
 
56
59
  const CLAIMED_VS_REALITY_PATH = '.ai-engineering-loop/tasks/claimed-vs-reality.md';
57
60
 
@@ -87,10 +90,6 @@ function readJsonArtifact(rootDir, runId, fileName) {
87
90
  return { filePath, value };
88
91
  }
89
92
 
90
- function hashContent(content) {
91
- return crypto.createHash('sha256').update(content).digest('hex');
92
- }
93
-
94
93
  function hashFile(filePath) {
95
94
  try {
96
95
  return hashContent(fs.readFileSync(filePath));
@@ -158,6 +157,7 @@ function validateGoalContract(contract) {
158
157
  });
159
158
  }
160
159
  errors.push(...validateGoalScope(contract.scope));
160
+ errors.push(...require('./design-ref.js').validateDesignRef(contract.designRef));
161
161
  return { valid: errors.length === 0, errors };
162
162
  }
163
163
 
@@ -284,7 +284,7 @@ function judgeRequirement(rootDir, run) {
284
284
  }
285
285
  const serious = findings.filter((f) => f && (f.severity === 'BLOCKER' || f.severity === 'HIGH'));
286
286
  if (serious.length) reasons.push(`BLOCKER_OR_HIGH_FINDINGS: ${serious.map((f) => f.id).join(', ')}`);
287
- if (run.iteration >= 3) reasons.push('ITERATION_CEILING');
287
+ if (run.iteration >= runMaxIterations(rootDir, run)) reasons.push('ITERATION_CEILING');
288
288
  let escalation = null;
289
289
  try {
290
290
  escalation = assessRunEscalation(rootDir, { runId: run.runId });
@@ -298,6 +298,49 @@ function judgeRequirement(rootDir, run) {
298
298
  return { required: reasons.length > 0, tier, reasons };
299
299
  }
300
300
 
301
+ // The verdict the evidence supports. The Judge may add evidence-backed
302
+ // blocking findings (judgeFindings) that the Maker's ledger lacks; it can
303
+ // never PASS what the deterministic rules block. An ITERATE that repeats the
304
+ // previous iteration (same diff or same blocking findings) escalates.
305
+ function expectedJudgeVerdict(rootDir, run, { judgeFindings = [] } = {}) {
306
+ const verification = readJsonArtifact(rootDir, run.runId, GATE_FILES.verification).value;
307
+ const findings = readJsonArtifact(rootDir, run.runId, GATE_FILES.review).value;
308
+ const goalContract = readJsonArtifact(rootDir, run.runId, GATE_FILES.goal).value;
309
+ const ledger = judgeFindings.length
310
+ ? { ...findings, findings: [...(findings.findings || []), ...judgeFindings] }
311
+ : findings;
312
+ const expected = computeJudgeVerdict({
313
+ goalContract,
314
+ verificationEvidence: verificationForJudge(verification),
315
+ findingLedger: ledger,
316
+ activeIteration: run.iteration,
317
+ maxIterations: runMaxIterations(rootDir, run)
318
+ });
319
+ if (expected.verdict === 'ITERATE') {
320
+ const noProgress = detectNoProgress(rootDir, run, {
321
+ diffHash: run.artifacts?.diff?.sha256,
322
+ blockingFindings: expected.blockingFindings || []
323
+ });
324
+ if (noProgress) {
325
+ return {
326
+ ...expected,
327
+ verdict: 'ESCALATE',
328
+ reason: noProgress,
329
+ action: 'Human escalation: the loop stopped making progress.'
330
+ };
331
+ }
332
+ }
333
+ return expected;
334
+ }
335
+
336
+ function validateJudgeFindings(value) {
337
+ if (value == null) return [];
338
+ if (!Array.isArray(value)) throw gateError('Judge gate failed', ['judgeFindings must be an array']);
339
+ const check = validateFindingLedger({ findings: value });
340
+ if (!check.valid) throw gateError('Judge gate failed', [`judgeFindings: ${check.reason}`]);
341
+ return value.map((finding) => ({ ...finding, source: 'judge' }));
342
+ }
343
+
301
344
  function writeDeterministicVerdictIfEligible(rootDir, run) {
302
345
  const filePath = artifactPath(rootDir, run.runId, GATE_FILES.judge);
303
346
  if (fs.existsSync(filePath)) return false;
@@ -307,16 +350,7 @@ function writeDeterministicVerdictIfEligible(rootDir, run) {
307
350
  if (requirement.required) {
308
351
  throw gateError(`Judge subagent required for tier ${tier}; write ${GATE_FILES.judge} from its verdict`, requirement.reasons);
309
352
  }
310
- const verification = readJsonArtifact(rootDir, run.runId, GATE_FILES.verification).value;
311
- const findings = readJsonArtifact(rootDir, run.runId, GATE_FILES.review).value;
312
- const goalContract = readJsonArtifact(rootDir, run.runId, GATE_FILES.goal).value;
313
- const expected = computeJudgeVerdict({
314
- goalContract,
315
- verificationEvidence: verificationForJudge(verification),
316
- findingLedger: findings,
317
- activeIteration: run.iteration,
318
- maxIterations: 3
319
- });
353
+ const expected = expectedJudgeVerdict(rootDir, run);
320
354
  fs.writeFileSync(filePath, `${JSON.stringify({
321
355
  schemaVersion: 1,
322
356
  runId: run.runId,
@@ -458,6 +492,15 @@ function applyGate(rootDir, gate, { runId, transitionOptions = {} } = {}) {
458
492
  }
459
493
  const check = validateFindingLedger(value);
460
494
  if (!check.valid) throw gateError('Review gate failed', [check.reason]);
495
+ const binding = checkLedgerBinding(rootDir, run, value);
496
+ if (binding.errors.length) {
497
+ throw gateError('Finding Ledger does not match the reviewer output (LEDGER_TAMPERED)', binding.errors);
498
+ }
499
+ if (binding.binding === 'UNBOUND' && mode === RUN_MODES.UNATTENDED) {
500
+ throw gateError('UNATTENDED review needs a ledger bound to the reviewer output', [
501
+ 'Run `review ingest --run <id> --child-id <id> --file <child-output>` instead of writing findings.json'
502
+ ]);
503
+ }
461
504
  return transitionRun(rootDir, run.runId, RUN_STATES.REVIEWED, {
462
505
  gate,
463
506
  artifacts: { findings: descriptor(rootDir, filePath) }
@@ -482,19 +525,16 @@ function applyGate(rootDir, gate, { runId, transitionOptions = {} } = {}) {
482
525
  } catch (cause) {
483
526
  throw gateError(cause.message, [cause.code]);
484
527
  }
485
- const verification = readJsonArtifact(rootDir, run.runId, GATE_FILES.verification).value;
486
- const findings = readJsonArtifact(rootDir, run.runId, GATE_FILES.review).value;
487
- const goalContract = readJsonArtifact(rootDir, run.runId, GATE_FILES.goal).value;
488
- const expected = computeJudgeVerdict({
489
- goalContract,
490
- verificationEvidence: verificationForJudge(verification),
491
- findingLedger: findings,
492
- activeIteration: run.iteration,
493
- maxIterations: 3
494
- });
528
+ const judgeFindings = validateJudgeFindings(value.judgeFindings);
529
+ const expected = expectedJudgeVerdict(rootDir, run, { judgeFindings });
495
530
  if (value.verdict !== expected.verdict) {
496
- throw gateError(`Judge verdict is unsupported: expected ${expected.verdict}, received ${value.verdict}`);
531
+ throw gateError(`Judge verdict is unsupported: expected ${expected.verdict}, received ${value.verdict}`, [expected.reason]);
497
532
  }
533
+ recordIteration(rootDir, run, {
534
+ verdict: expected.verdict,
535
+ diffHash: run.artifacts?.diff?.sha256,
536
+ blockingFindings: expected.blockingFindings || []
537
+ });
498
538
  const artifacts = { verdict: descriptor(rootDir, filePath) };
499
539
  if (expected.verdict === 'PASS') {
500
540
  return transitionRun(rootDir, run.runId, RUN_STATES.JUDGED_PASS, { gate, artifacts });
@@ -527,6 +567,8 @@ function applyGate(rootDir, gate, { runId, transitionOptions = {} } = {}) {
527
567
  if (mode === RUN_MODES.ASSISTED && value.humanApproved !== true) {
528
568
  deliveryErrors.push('humanApproved must be true for ASSISTED delivery');
529
569
  }
570
+ const finalCheck = finalVerificationStatus(rootDir, run);
571
+ if (!finalCheck.satisfied) deliveryErrors.push(`Full verification required before delivery: ${finalCheck.reason}`);
530
572
  if (deliveryErrors.length) throw gateError('Delivery gate failed', deliveryErrors);
531
573
  return transitionRun(rootDir, run.runId, RUN_STATES.DELIVERED, {
532
574
  gate,
@@ -545,5 +587,6 @@ module.exports = {
545
587
  validateVerificationBundle,
546
588
  validateVerdictDocument,
547
589
  judgeRequirement,
590
+ expectedJudgeVerdict,
548
591
  applyGate
549
592
  };
@@ -41,17 +41,6 @@ function assertNoRequiredSkip(skips) {
41
41
  }
42
42
  }
43
43
 
44
- function routeDurableNote(kind) {
45
- const map = {
46
- term: 'glossary.md',
47
- process: 'lessons.md',
48
- lesson: 'lessons.md',
49
- convention: 'conventions.md',
50
- adr: 'adrs/'
51
- };
52
- return map[kind] || 'lessons.md';
53
- }
54
-
55
44
  function normalizeMakerIntern(raw) {
56
45
  const s = String(raw || '').trim();
57
46
  if (!s || /^none$/i.test(s)) return DEFAULT_MAKER_INTERN;
@@ -143,22 +132,6 @@ function parseWorkflowMarkdown(text) {
143
132
  };
144
133
  }
145
134
 
146
- function parseWorkflowFile(rootDir) {
147
- const dest = path.join(rootDir, '.ai-engineering-loop', 'workflow.md');
148
- try {
149
- const text = fs.readFileSync(dest, 'utf8');
150
- return parseWorkflowMarkdown(text);
151
- } catch {
152
- return {
153
- missing: true,
154
- required: REQUIRED_STAGES.slice(),
155
- hooks: { ...DEFAULT_HOOKS },
156
- makerIntern: DEFAULT_MAKER_INTERN,
157
- optionalSkips: []
158
- };
159
- }
160
- }
161
-
162
135
  function lessonsAreFilled(text) {
163
136
  if (!text || !text.trim()) return false;
164
137
  return /\| 20\d{2}-/.test(text);
@@ -223,11 +196,9 @@ module.exports = {
223
196
  DEFAULT_MAKER_INTERN,
224
197
  assertNoRequiredSkip,
225
198
  normalizeMakerIntern,
226
- routeDurableNote,
227
199
  workflowMarkdown,
228
200
  lessonsMarkdown,
229
201
  parseWorkflowMarkdown,
230
- parseWorkflowFile,
231
202
  writeWorkflowOverlay,
232
203
  formatGenerateWorkflowReport,
233
204
  parseWriteArg
@@ -2,8 +2,10 @@
2
2
 
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
+ const { ACTOR_ID } = require('./fsutil.js');
5
6
  const { validateGoalContract, hashFile } = require('./gates.js');
6
7
  const { sha256 } = require('./recipe.js');
8
+ const { placeholderRows } = require('./design-ref.js');
7
9
  const {
8
10
  RUN_STATES,
9
11
  atomicWritePrivateFile,
@@ -22,7 +24,7 @@ function goalError(message, code, details = []) {
22
24
 
23
25
  function actorId(actor) {
24
26
  const value = String(actor || '').trim();
25
- if (!/^[A-Za-z0-9@._-]{1,64}$/.test(value)) {
27
+ if (!ACTOR_ID.test(value)) {
26
28
  throw goalError('Goal actor must be a short account identifier', 'INVALID_GOAL_ACTOR');
27
29
  }
28
30
  return value;
@@ -59,7 +61,7 @@ function normalizeDraft(value, runId) {
59
61
  contract.runId !== runId ||
60
62
  !Number.isSafeInteger(revision) ||
61
63
  revision < 1 ||
62
- !/^[A-Za-z0-9@._-]{1,64}$/.test(String(metadata.actor || '')) ||
64
+ !ACTOR_ID.test(String(metadata.actor || '')) ||
63
65
  !metadata.updatedAt ||
64
66
  !Number.isFinite(Date.parse(metadata.updatedAt)) ||
65
67
  metadata.contentHash !== contentHash
@@ -181,6 +183,10 @@ function freezeGoal(
181
183
  }
182
184
  const validation = validateGoalContract(contract);
183
185
  if (!validation.valid) throw goalError('Goal Contract gate failed', 'GATE_FAILED', validation.errors);
186
+ const unfilled = placeholderRows(contract);
187
+ if (unfilled.length) {
188
+ throw goalError(`Fill the <fill: ...> placeholders before freezing: ${unfilled.join(', ')}`, 'GOAL_PLACEHOLDERS', unfilled);
189
+ }
184
190
  const human = actorId(actor);
185
191
  if (fs.existsSync(paths.version)) {
186
192
  throw goalError(`Goal version ${version} already exists`, 'GOAL_VERSION_EXISTS');
@@ -7,10 +7,16 @@
7
7
  const fs = require('fs');
8
8
  const path = require('path');
9
9
  const { HOSTS, getHost, guardrailSupport } = require('./hosts/registry.js');
10
+ const { atomicWrite, jsonText } = require('./fsutil.js');
10
11
 
11
12
  const HOOK_MARKER = 'ai-engineering-loop guard check';
13
+ // Matches pinned (ai-engineering-loop@x.y.z) and older unpinned commands.
14
+ const HOOK_PATTERN = /ai-engineering-loop(?:@\S+)? guard check/;
12
15
  const CLAUDE_MATCHER = 'Edit|Write|MultiEdit|NotebookEdit|Bash';
13
- const CLAUDE_COMMAND = 'npx --yes ai-engineering-loop guard check --hook claude';
16
+ const { version: PACKAGE_VERSION } = require('../package.json');
17
+
18
+ // Pinned so a hook never resolves whatever version the registry serves today.
19
+ const CLAUDE_COMMAND = `npx --yes ai-engineering-loop@${PACKAGE_VERSION} guard check --hook claude`;
14
20
 
15
21
  function hooksError(message, code = 'INVALID_USAGE') {
16
22
  const error = new Error(message);
@@ -46,14 +52,11 @@ function readSettings(filePath) {
46
52
  }
47
53
 
48
54
  function writeSettings(filePath, value) {
49
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
50
- const temporary = `${filePath}.${process.pid}.tmp`;
51
- fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`);
52
- fs.renameSync(temporary, filePath);
55
+ atomicWrite(filePath, jsonText(value));
53
56
  }
54
57
 
55
58
  function isOurHook(hook) {
56
- return typeof hook?.command === 'string' && hook.command.includes(HOOK_MARKER);
59
+ return typeof hook?.command === 'string' && HOOK_PATTERN.test(hook.command);
57
60
  }
58
61
 
59
62
  function ourEntries(settings) {
@@ -76,7 +79,23 @@ function installHooks(rootDir, { host: hostId = 'claude' } = {}) {
76
79
  const host = hookHost(hostId);
77
80
  const filePath = settingsPath(rootDir, host);
78
81
  const settings = readSettings(filePath);
79
- if (ourEntries(settings).length) return { ...hooksStatus(rootDir, { host: host.id }), changed: false };
82
+ const existing = ourEntries(settings);
83
+ if (existing.length) {
84
+ const current = existing.every((entry) => entry.hooks.every((hook) => !isOurHook(hook) || hook.command === CLAUDE_COMMAND));
85
+ if (current) return { ...hooksStatus(rootDir, { host: host.id }), changed: false };
86
+ // Re-pin hooks written by an older install (unpinned or another version).
87
+ writeSettings(filePath, {
88
+ ...settings,
89
+ hooks: {
90
+ ...settings.hooks,
91
+ PreToolUse: settings.hooks.PreToolUse.map((entry) => ({
92
+ ...entry,
93
+ hooks: (entry.hooks || []).map((hook) => (isOurHook(hook) ? { ...hook, command: CLAUDE_COMMAND } : hook))
94
+ }))
95
+ }
96
+ });
97
+ return { ...hooksStatus(rootDir, { host: host.id }), changed: true };
98
+ }
80
99
  const hooks = settings.hooks && typeof settings.hooks === 'object' ? settings.hooks : {};
81
100
  const preToolUse = Array.isArray(hooks.PreToolUse) ? hooks.PreToolUse : [];
82
101
  writeSettings(filePath, {
package/lib/guard.js CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  const fs = require('fs');
10
10
  const path = require('path');
11
+ const { readJsonOptional } = require('./fsutil.js');
11
12
  const { RUN_MODES, TERMINAL_STATES, atomicWriteJson, getCurrentRun, loadRun, runsDir } = require('./run-state.js');
12
13
  const { loadPolicy } = require('./runtime-policy.js');
13
14
  const { redactHomePaths, redactSecrets } = require('./safe-context.js');
@@ -48,12 +49,14 @@ function parseGuardInput(input, tool) {
48
49
  };
49
50
  }
50
51
 
51
- // Shell segments split on ; && || | and newlines; quotes are kept simple on
52
+ // Shell segments split on ; && || | & and newlines; quotes are kept simple on
52
53
  // purpose: a quoted "rm -rf" still warns, which errs on the safe side.
53
54
  function segments(command) {
54
55
  return String(command || '')
55
- .split(/\n|;|&&|\|\||\|/)
56
- .map((part) => part.trim().split(/\s+/).filter(Boolean).map((token) => token.replace(/^['"]|['"]$/g, '')))
56
+ .split(/\n|;|&&|\|\||\||&/)
57
+ .map((part) => part.trim().split(/\s+/).filter(Boolean)
58
+ // `\rm` and `"rm"` bypass aliases but run the same binary.
59
+ .map((token) => token.replace(/^['"]|['"]$/g, '').replace(/^\\+/, '')))
57
60
  .filter((tokens) => tokens.length);
58
61
  }
59
62
 
@@ -113,6 +116,50 @@ const DESTRUCTIVE_RULES = Object.freeze([
113
116
  return git?.name === 'reset' && git.args.includes('--hard');
114
117
  }
115
118
  },
119
+ {
120
+ id: 'find-delete',
121
+ reason: 'find -delete removes every matching file without confirmation',
122
+ test: (tokens) => {
123
+ const start = commandIndex(tokens, 'find');
124
+ if (start === -1) return false;
125
+ const args = tokens.slice(start + 1);
126
+ const exec = args.findIndex((arg) => arg === '-exec' || arg === '-execdir' || arg === '-ok');
127
+ return args.includes('-delete') || (exec !== -1 && commandIndex(args.slice(exec + 1), 'rm') === 0);
128
+ }
129
+ },
130
+ {
131
+ id: 'git-checkout-discard',
132
+ reason: 'git checkout -- <paths> (or --force) discards uncommitted work',
133
+ test: (tokens) => {
134
+ const git = gitSubcommand(tokens);
135
+ if (git?.name !== 'checkout') return false;
136
+ return git.args.includes('--') || git.args.includes('.') || git.args.includes('--force') ||
137
+ /f/.test(shortFlags(git.args));
138
+ }
139
+ },
140
+ {
141
+ id: 'git-restore',
142
+ reason: 'git restore discards uncommitted work in the working tree',
143
+ test: (tokens) => {
144
+ const git = gitSubcommand(tokens);
145
+ if (git?.name !== 'restore') return false;
146
+ const stagedOnly = (git.args.includes('--staged') || /S/.test(shortFlags(git.args))) &&
147
+ !git.args.includes('--worktree') && !/W/.test(shortFlags(git.args));
148
+ return !stagedOnly;
149
+ }
150
+ },
151
+ {
152
+ id: 'git-branch-force-delete',
153
+ reason: 'git branch -D deletes a branch even when it is not merged',
154
+ test: (tokens) => {
155
+ const git = gitSubcommand(tokens);
156
+ if (git?.name !== 'branch') return false;
157
+ const flags = shortFlags(git.args);
158
+ const remove = /d/i.test(flags) || git.args.includes('--delete');
159
+ const force = flags.includes('D') || flags.includes('f') || git.args.includes('--force');
160
+ return remove && force;
161
+ }
162
+ },
116
163
  {
117
164
  id: 'git-clean-force',
118
165
  reason: 'git clean -fd deletes untracked files and directories',
@@ -153,12 +200,7 @@ function activeRun(rootDir, runId) {
153
200
 
154
201
  function readFrozenGoal(rootDir, run) {
155
202
  const filePath = path.join(runsDir(rootDir), run.runId, 'goal-contract.json');
156
- if (!fs.existsSync(filePath)) return null;
157
- try {
158
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
159
- } catch {
160
- return null;
161
- }
203
+ return readJsonOptional(filePath);
162
204
  }
163
205
 
164
206
  // Allowed = the frozen Goal's scope.allowedPaths plus the confirmed impact
@@ -212,10 +254,45 @@ function repoRelative(rootDir, filePath) {
212
254
  return null;
213
255
  }
214
256
 
257
+ // CLI-owned Run ledgers and evidence. Agents produce their artifacts through
258
+ // gates and the recorder; a direct edit here could forge verification or
259
+ // replay state, so it is never exempt like the rest of .ai-engineering-loop/.
260
+ const RUN_EVIDENCE_FILES = new Set([
261
+ 'state.json',
262
+ 'plan.json',
263
+ 'workflow-state.json',
264
+ 'events.jsonl',
265
+ 'lifecycle.jsonl',
266
+ 'interactions.jsonl',
267
+ 'verification.json',
268
+ 'verification-summary.json',
269
+ 'sandbox-evidence.json',
270
+ 'impact-map.json',
271
+ 'impact-drift.json',
272
+ 'guard-events.json',
273
+ 'receipt.json',
274
+ 'receipt.md',
275
+ 'CANCELLED'
276
+ ]);
277
+
278
+ function runEvidenceFinding(relative) {
279
+ const parts = relative.split('/');
280
+ if (parts[0] !== '.ai-engineering-loop' || parts[1] !== 'runs') return null;
281
+ const protectedFile = (parts.length === 3 && parts[2] === 'current.json') ||
282
+ (parts.length === 4 && RUN_EVIDENCE_FILES.has(parts[3])) ||
283
+ (parts.length >= 4 && parts[3].toLowerCase().startsWith('verification'));
284
+ return protectedFile
285
+ ? { id: 'run-evidence', reason: `${relative} is CLI-owned Run evidence; use the CLI instead of editing it` }
286
+ : null;
287
+ }
288
+
215
289
  function scopeFindings(rootDir, filePath, scope) {
216
290
  if (!filePath) return [];
217
291
  const relative = repoRelative(rootDir, filePath);
218
- if (relative != null && (relative === '.ai-engineering-loop' || relative.startsWith('.ai-engineering-loop/'))) return [];
292
+ if (relative != null && (relative === '.ai-engineering-loop' || relative.startsWith('.ai-engineering-loop/'))) {
293
+ const evidence = runEvidenceFinding(relative);
294
+ return evidence ? [evidence] : [];
295
+ }
219
296
  if (relative == null) {
220
297
  return scope.allowedPaths ? [{ id: 'outside-repository', reason: 'edit target is outside the repository and the Run scope' }] : [];
221
298
  }
@@ -289,6 +366,18 @@ function checkGuard(rootDir, { tool, input, runId, now = new Date() } = {}) {
289
366
  return result;
290
367
  }
291
368
 
369
+ // When guard check itself fails inside a hook, fail closed unless the Run is
370
+ // ASSISTED (a human is approving each call anyway).
371
+ function hookFailureExitCode(rootDir, runId) {
372
+ let mode = null;
373
+ try {
374
+ mode = activeRun(rootDir, runId)?.mode || loadPolicy(rootDir).defaultMode;
375
+ } catch {
376
+ mode = null;
377
+ }
378
+ return mode === RUN_MODES.ASSISTED ? 1 : 2;
379
+ }
380
+
292
381
  function loadGuardEvents(rootDir, runId) {
293
382
  const filePath = path.join(runsDir(rootDir), runId, GUARD_EVENTS_FILE);
294
383
  if (!fs.existsSync(filePath)) return [];
@@ -330,6 +419,7 @@ module.exports = {
330
419
  destructiveFindings,
331
420
  runScope,
332
421
  checkGuard,
422
+ hookFailureExitCode,
333
423
  loadGuardEvents,
334
424
  guardSummary,
335
425
  claudeHookOutput
@@ -4,18 +4,14 @@
4
4
  // skill it can see across the folders it scans, whether they are identical,
5
5
  // and which AEL files a sync would still write. Read-only.
6
6
 
7
- const crypto = require('crypto');
8
7
  const fs = require('fs');
9
8
  const path = require('path');
9
+ const { sha256 } = require('../fsutil.js');
10
10
  const { HOSTS, guardrailSupport, usesSharedSkills } = require('./registry.js');
11
11
  const { certificationLabel } = require('./table.js');
12
12
 
13
13
  const CORE_SKILL = 'ai-engineering-loop';
14
14
 
15
- function sha256(buf) {
16
- return crypto.createHash('sha256').update(buf).digest('hex');
17
- }
18
-
19
15
  function realOrSelf(file) {
20
16
  try {
21
17
  return fs.realpathSync(file);
@@ -40,6 +36,18 @@ function visibleCopies(host, home, skill = CORE_SKILL) {
40
36
  return [...seen.values()];
41
37
  }
42
38
 
39
+ // Spec pack (#99): installed when the host can see `ael-spec-review`.
40
+ // Instruction-only hosts have no subagent tool, so the pack's reviews run
41
+ // in-session as CONTEXT_ISOLATION_ONLY. Informational; never fails doctor.
42
+ const SPEC_PROBE = 'ael-spec-review';
43
+
44
+ function specStatus(host, home) {
45
+ return {
46
+ installed: visibleCopies(host, home, SPEC_PROBE).length > 0,
47
+ reviewMode: host.certification === 'instruction-only' ? 'CONTEXT_ISOLATION_ONLY' : 'FRESH_SUBAGENT'
48
+ };
49
+ }
50
+
43
51
  // `plan` is planHostSync(...) output; groups are host ids plus 'shared'.
44
52
  function hostsDoctor({ home, selection, plan }) {
45
53
  const rows = [];
@@ -55,7 +63,7 @@ function hostsDoctor({ home, selection, plan }) {
55
63
  if (!copies.length) problems.push('core skill not installed');
56
64
  if (hashes.size > 1) problems.push(`${copies.length} copies with different content`);
57
65
  if (resync.length) problems.push(`${resync.length} file(s) need sync`);
58
- rows.push({ id: host.id, name: host.name, certification: host.certification, certifiedBy: host.certifiedBy || null, guardrails: guardrailSupport(host), copies, identical: hashes.size <= 1, resync, ok: problems.length === 0, problems });
66
+ rows.push({ id: host.id, name: host.name, certification: host.certification, certifiedBy: host.certifiedBy || null, guardrails: guardrailSupport(host), copies, identical: hashes.size <= 1, resync, ok: problems.length === 0, problems, spec: specStatus(host, home) });
59
67
  }
60
68
  return { ok: rows.every((row) => row.ok), hosts: rows };
61
69
  }
@@ -66,12 +74,14 @@ function formatHostsDoctor(report) {
66
74
  for (const row of report.hosts) {
67
75
  const where = row.copies.map((c) => c.path).join(', ') || '-';
68
76
  lines.push(` ${row.ok ? '✓' : '✗'} ${row.id.padEnd(16)} [${certificationLabel(row)}, guardrails ${row.guardrails}] ${row.copies.length} cop${row.copies.length === 1 ? 'y' : 'ies'}${row.copies.length > 1 ? (row.identical ? ' (identical)' : ' (DIFFERENT)') : ''}: ${where}`);
77
+ if (row.spec?.installed) lines.push(` spec pack: installed (${row.spec.reviewMode === 'FRESH_SUBAGENT' ? 'reviews in fresh subagents' : 'no subagents: reviews run in-session, CONTEXT_ISOLATION_ONLY'})`);
69
78
  for (const problem of row.problems) lines.push(` ${problem}`);
70
79
  for (const file of row.resync.slice(0, 5)) lines.push(` needs sync: ${file}`);
71
80
  if (row.resync.length > 5) lines.push(` ... and ${row.resync.length - 5} more`);
72
81
  }
73
82
  if (!report.ok) lines.push('Fix: "ai-engineering-loop sync-hosts" (edited files are kept; remove an old copy by hand if it differs).');
83
+ if (!report.hosts.some((row) => row.spec?.installed)) lines.push('Optional: "ai-engineering-loop sync-hosts --pack spec" adds the ael-spec-* design review skills (used at T2).');
74
84
  return lines.join('\n');
75
85
  }
76
86
 
77
- module.exports = { CORE_SKILL, visibleCopies, hostsDoctor, formatHostsDoctor };
87
+ module.exports = { CORE_SKILL, visibleCopies, specStatus, hostsDoctor, formatHostsDoctor };
package/lib/impact-map.js CHANGED
@@ -5,9 +5,9 @@
5
5
  // Stage 3 (Maker). A human confirms or edits it; the confirmed paths become
6
6
  // the Run's allowed scope (#59), and verify reports drift outside it.
7
7
 
8
- const crypto = require('crypto');
9
8
  const fs = require('fs');
10
9
  const path = require('path');
10
+ const { ACTOR_ID, readJsonOptional, sha256: hashBytes } = require('./fsutil.js');
11
11
  const { atomicWriteJson, getCurrentRun, loadRun, runsDir } = require('./run-state.js');
12
12
  const { sha256 } = require('./recipe.js');
13
13
 
@@ -329,7 +329,7 @@ function writeMap(rootDir, run, map) {
329
329
 
330
330
  function actorId(actor) {
331
331
  const value = String(actor || '').trim();
332
- if (!/^[A-Za-z0-9@._-]{1,64}$/.test(value)) {
332
+ if (!ACTOR_ID.test(value)) {
333
333
  throw impactError('--by <name> must be a short account identifier', 'INVALID_USAGE');
334
334
  }
335
335
  return value;
@@ -431,29 +431,52 @@ function detectImpactDrift(rootDir, { runId, now = new Date() } = {}) {
431
431
  else if (map?.status === 'DRAFT') allowed = mappedPaths(map);
432
432
  const compared = map && map.status !== 'SKIPPED';
433
433
  const outOfMap = compared ? changedFiles.filter((file) => !matchesAnyGlob(file, allowed)) : [];
434
+ const design = designDrift(rootDir, run, changedFiles);
434
435
  const drift = {
435
436
  schemaVersion: 1,
436
437
  runId: run.runId,
437
- diffHash: crypto.createHash('sha256').update(raw).digest('hex'),
438
+ diffHash: hashBytes(raw),
438
439
  mapStatus: map ? map.status : 'MISSING',
439
440
  ...(map?.status === 'SKIPPED' ? { skipReason: map.skipReason } : {}),
440
441
  checkedAt: now.toISOString(),
441
442
  changedFiles,
442
- outOfMap
443
+ outOfMap,
444
+ ...(design ? { design } : {})
443
445
  };
444
446
  const filePath = driftPath(rootDir, run.runId);
445
447
  atomicWriteJson(filePath, drift);
446
448
  return { drift, path: relative(rootDir, filePath) };
447
449
  }
448
450
 
449
- function loadImpactDrift(rootDir, runId) {
450
- const filePath = driftPath(rootDir, runId);
451
- if (!fs.existsSync(filePath)) return null;
451
+ // Design-scope drift (#98): when the frozen Goal has a designRef, compare the
452
+ // design's planned files with the Maker diff. Informational only; it never
453
+ // adds a ledger finding or fails a gate. Run evidence under the context dir
454
+ // is not "unplanned".
455
+ function designDrift(rootDir, run, changedFiles) {
456
+ let goal;
452
457
  try {
453
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
458
+ goal = readGoal(rootDir, run);
454
459
  } catch {
455
460
  return null;
456
461
  }
462
+ const ref = goal?.designRef;
463
+ if (!ref || typeof ref.path !== 'string') return null;
464
+ const { designStatus } = require('./design-ref.js');
465
+ const status = designStatus(rootDir, ref);
466
+ const planned = Array.isArray(ref.targetFiles) ? ref.targetFiles : [];
467
+ const code = changedFiles.filter((file) => !file.startsWith('.ai-engineering-loop/'));
468
+ return {
469
+ path: ref.path,
470
+ docChanged: status.designChanged,
471
+ planned: planned.length,
472
+ unplanned: planned.length ? code.filter((file) => !matchesAnyGlob(file, planned)) : [],
473
+ untouched: planned.filter((pattern) => !code.some((file) => matchesGlob(file, pattern)))
474
+ };
475
+ }
476
+
477
+ function loadImpactDrift(rootDir, runId) {
478
+ const filePath = driftPath(rootDir, runId);
479
+ return readJsonOptional(filePath);
457
480
  }
458
481
 
459
482
  function driftFindings(drift) {