ai-engineering-loop 1.13.0 → 1.15.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 (117) hide show
  1. package/.agents/skills/ai-engineering-loop/SKILL.md +62 -0
  2. package/.agents/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  3. package/.agents/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  4. package/.agents/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  5. package/.agents/skills/ai-engineering-loop/references/loop-hosts.md +44 -0
  6. package/.agents/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  7. package/.agents/skills/ai-engineering-loop/references/loop-review.md +18 -0
  8. package/.agents/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  9. package/.agents/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  10. package/.claude/skills/ai-engineering-loop/SKILL.md +28 -47
  11. package/.claude/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  12. package/.claude/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  13. package/.claude/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  14. package/.claude/skills/ai-engineering-loop/references/loop-hosts.md +44 -0
  15. package/.claude/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  16. package/.claude/skills/ai-engineering-loop/references/loop-review.md +18 -0
  17. package/.claude/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  18. package/.claude/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  19. package/CHANGELOG.md +116 -0
  20. package/README.md +90 -5
  21. package/README.npm.md +6 -2
  22. package/THIRD_PARTY_NOTICES.md +29 -0
  23. package/adapters/dot/README.md +1 -1
  24. package/adapters/dot/skills/dot-dev-skill-router/SKILL.md +24 -16
  25. package/adapters/project-onboarding/SKILL.md +27 -0
  26. package/adapters/project-onboarding/references/output.md +29 -0
  27. package/adapters/quality/skills/ael-code-simplifier/SKILL.md +43 -0
  28. package/adapters/quality/skills/ael-receiving-code-review/SKILL.md +37 -0
  29. package/bin/ai-engineering-loop.js +1270 -75
  30. package/core/grill-policy.md +1 -1
  31. package/core/root-cause-analysis.md +6 -0
  32. package/core/runtime-safety.md +31 -3
  33. package/evals/cases/21-tier-t0-docs.json +34 -0
  34. package/evals/cases/22-tier-t1-small-pass.json +30 -0
  35. package/evals/cases/23-tier-t1-blocker.json +26 -0
  36. package/evals/cases/24-tier-t1-auth-escalates.json +30 -0
  37. package/lib/auto-update.js +488 -0
  38. package/lib/budget.js +31 -1
  39. package/lib/cli-args.js +95 -0
  40. package/lib/docs.js +91 -0
  41. package/lib/doctor.js +9 -14
  42. package/lib/gates.js +114 -1
  43. package/lib/host-skill-build.js +121 -0
  44. package/lib/hosts/agent-formats.js +135 -0
  45. package/lib/hosts/commands.js +126 -0
  46. package/lib/hosts/detect.js +56 -0
  47. package/lib/hosts/doctor.js +76 -0
  48. package/lib/hosts/redetect.js +60 -0
  49. package/lib/hosts/registry.js +271 -0
  50. package/lib/hosts/table.js +35 -0
  51. package/lib/migrations.js +84 -0
  52. package/lib/project-registry.js +148 -0
  53. package/lib/run-abandon.js +116 -0
  54. package/lib/run-state.js +6 -3
  55. package/lib/sync-hosts.js +456 -130
  56. package/lib/tier.js +134 -0
  57. package/lib/update-manager.js +17 -1
  58. package/lib/update-notice.js +192 -0
  59. package/lib/user-state.js +80 -0
  60. package/lib/verification-recorder.js +44 -0
  61. package/migrations/README.md +21 -0
  62. package/package.json +8 -4
  63. package/.agents/devil-advocate.md +0 -79
  64. package/.agents/judge.md +0 -58
  65. package/.agents/workflows/ai-engineering-loop.md +0 -24
  66. package/.claude/commands/ai-engineering-loop.md +0 -11
  67. package/.gemini/skills/ai-engineering-loop/SKILL.md +0 -74
  68. package/.gemini/skills/animate/RECIPES.md +0 -324
  69. package/.gemini/skills/animate/SKILL.md +0 -207
  70. package/.gemini/skills/animate-expo/RECIPES.md +0 -385
  71. package/.gemini/skills/animate-expo/SKILL.md +0 -263
  72. package/.gemini/skills/animation-vocabulary/SKILL.md +0 -181
  73. package/.gemini/skills/apple-design/SKILL.md +0 -290
  74. package/.gemini/skills/ask-sonner/API.md +0 -64
  75. package/.gemini/skills/ask-sonner/SKILL.md +0 -88
  76. package/.gemini/skills/backend-development/SKILL.md +0 -272
  77. package/.gemini/skills/backend-development/references/api-design-guidelines.md +0 -95
  78. package/.gemini/skills/backend-development/references/query-and-database-best-practices.md +0 -53
  79. package/.gemini/skills/backend-development/references/security-checklist.md +0 -60
  80. package/.gemini/skills/emil-design-eng/SKILL.md +0 -674
  81. package/.gemini/skills/find-animation-opportunities/SKILL.md +0 -140
  82. package/.gemini/skills/improve-animations/AUDIT.md +0 -115
  83. package/.gemini/skills/improve-animations/PLAN-TEMPLATE.md +0 -73
  84. package/.gemini/skills/improve-animations/SKILL.md +0 -109
  85. package/.gemini/skills/mobile-native/SKILL.md +0 -311
  86. package/.gemini/skills/pick-ui-library/SKILL.md +0 -85
  87. package/.gemini/skills/prototype/PICKER.md +0 -197
  88. package/.gemini/skills/prototype/SKILL.md +0 -98
  89. package/.gemini/skills/review-animations/SKILL.md +0 -120
  90. package/.gemini/skills/review-animations/STANDARDS.md +0 -187
  91. package/.gemini/skills/write-swift/SKILL.md +0 -396
  92. package/.grok/commands/ai-engineering-loop.md +0 -11
  93. package/.grok/skills/ai-engineering-loop/SKILL.md +0 -94
  94. package/.grok/skills/animate/RECIPES.md +0 -324
  95. package/.grok/skills/animate/SKILL.md +0 -207
  96. package/.grok/skills/animate-expo/RECIPES.md +0 -385
  97. package/.grok/skills/animate-expo/SKILL.md +0 -263
  98. package/.grok/skills/animation-vocabulary/SKILL.md +0 -181
  99. package/.grok/skills/apple-design/SKILL.md +0 -290
  100. package/.grok/skills/ask-sonner/API.md +0 -64
  101. package/.grok/skills/ask-sonner/SKILL.md +0 -88
  102. package/.grok/skills/backend-development/SKILL.md +0 -272
  103. package/.grok/skills/backend-development/references/api-design-guidelines.md +0 -95
  104. package/.grok/skills/backend-development/references/query-and-database-best-practices.md +0 -53
  105. package/.grok/skills/backend-development/references/security-checklist.md +0 -60
  106. package/.grok/skills/emil-design-eng/SKILL.md +0 -674
  107. package/.grok/skills/find-animation-opportunities/SKILL.md +0 -140
  108. package/.grok/skills/improve-animations/AUDIT.md +0 -115
  109. package/.grok/skills/improve-animations/PLAN-TEMPLATE.md +0 -73
  110. package/.grok/skills/improve-animations/SKILL.md +0 -109
  111. package/.grok/skills/mobile-native/SKILL.md +0 -311
  112. package/.grok/skills/pick-ui-library/SKILL.md +0 -85
  113. package/.grok/skills/prototype/PICKER.md +0 -197
  114. package/.grok/skills/prototype/SKILL.md +0 -98
  115. package/.grok/skills/review-animations/SKILL.md +0 -120
  116. package/.grok/skills/review-animations/STANDARDS.md +0 -187
  117. package/.grok/skills/write-swift/SKILL.md +0 -396
@@ -17,9 +17,19 @@ const { execSync, spawn } = require('child_process');
17
17
  const {
18
18
  homeDir,
19
19
  applyHostSync,
20
+ hostSkillStatus,
21
+ resolveHostSelection,
20
22
  planHostSync,
21
23
  formatHostSyncReport
22
24
  } = require('../lib/sync-hosts.js');
25
+ const hostCommands = require('../lib/hosts/commands.js');
26
+ const { listDocs, readDoc } = require('../lib/docs.js');
27
+ const {
28
+ wantsCommandHelp,
29
+ unknownWriterArgs,
30
+ effectiveCommand,
31
+ commandHelp
32
+ } = require('../lib/cli-args.js');
23
33
  const {
24
34
  detectAdapterHints,
25
35
  writeShippedAdapter,
@@ -51,8 +61,10 @@ const {
51
61
  updatePolicy
52
62
  } = require('../lib/runtime-policy.js');
53
63
  const {
54
- applyGate
64
+ applyGate,
65
+ judgeRequirement
55
66
  } = require('../lib/gates.js');
67
+ const { initialTierState } = require('../lib/tier.js');
56
68
  const {
57
69
  createContextPack,
58
70
  contextPackSummary
@@ -82,6 +94,7 @@ const {
82
94
  writeVerificationSummary
83
95
  } = require('../lib/verification-summary.js');
84
96
  const {
97
+ recordVerificationCommands,
85
98
  recordVerificationCommand
86
99
  } = require('../lib/verification-recorder.js');
87
100
  const {
@@ -96,12 +109,16 @@ const {
96
109
  } = require('../lib/doctor.js');
97
110
  const {
98
111
  checkForUpdate,
112
+ detectInstallScope,
99
113
  executeUpdatePlan
100
114
  } = require('../lib/update-manager.js');
115
+ const autoUpdate = require('../lib/auto-update.js');
116
+ const projectRegistry = require('../lib/project-registry.js');
101
117
  const {
102
118
  assertBudgetAvailable,
103
119
  budgetStatus,
104
120
  recordTokenUsage,
121
+ recordUsageUnavailable,
105
122
  setKillSwitch
106
123
  } = require('../lib/budget.js');
107
124
  const {
@@ -179,15 +196,150 @@ const REQUIRED_FILES = [
179
196
  'adrs/README.md'
180
197
  ];
181
198
 
199
+ // Non-destructive mode (issue #37, `refresh --non-destructive`): a context file
200
+ // is overwritten only if it still matches what AEL last generated (hash in
201
+ // .ael-generated.json) or is package-owned; otherwise the new template goes to
202
+ // `<file>.ael-new` and the user's file is left alone.
203
+ // Legacy projects (no .ael-generated.json yet, decision 5 on #37): the first
204
+ // such refresh overwrites AEL-managed files directly and deletes obsolete
205
+ // AEL-managed files, after copying the old content into a snapshot under
206
+ // .ai-engineering-loop/.ael-backup/<timestamp>/. Hashes are recorded so later
207
+ // refreshes use the normal flow. Only paths this writer generates (or lists in
208
+ // OBSOLETE_CONTEXT_FILES) are touched; files written with overwrite:false
209
+ // (lessons, glossary, ...) and every other user file are left alone.
210
+ let CONTEXT_WRITE_SAFE = false;
211
+ let CONTEXT_WRITE_LEGACY = null; // { root, snapshotDir } during a legacy refresh
212
+ const CONTEXT_WRITE_REPORT = { updated: [], aelNew: [], kept: [], seen: new Set(), snapshot: [], removed: [], obsoleteKept: [] };
213
+ const PACKAGE_OWNED_CONTEXT = new Set(['metadata.json']);
214
+ // Context files older AEL versions generated and this one no longer does
215
+ // (relative to .ai-engineering-loop/). Deleted on the first legacy refresh.
216
+ const OBSOLETE_CONTEXT_FILES = Object.freeze([]);
217
+ const GENERATED_HASHES_FILE = '.ael-generated.json';
218
+
219
+ function generatedHashesPath(filePath) {
220
+ return path.join(path.dirname(filePath), GENERATED_HASHES_FILE);
221
+ }
222
+
223
+ function readGeneratedHashes(filePath) {
224
+ try {
225
+ return JSON.parse(fs.readFileSync(generatedHashesPath(filePath), 'utf8'));
226
+ } catch {
227
+ return {};
228
+ }
229
+ }
230
+
231
+ function writeGeneratedHashes(filePath, hashes) {
232
+ try {
233
+ fs.writeFileSync(generatedHashesPath(filePath), `${JSON.stringify(hashes, null, 2)}\n`);
234
+ } catch {
235
+ // Best effort.
236
+ }
237
+ }
238
+
239
+ function recordGeneratedHash(filePath, content) {
240
+ const hashes = readGeneratedHashes(filePath);
241
+ hashes[path.basename(filePath)] = require('crypto').createHash('sha256').update(content).digest('hex');
242
+ writeGeneratedHashes(filePath, hashes);
243
+ }
244
+
245
+ function sha256Text(content) {
246
+ return require('crypto').createHash('sha256').update(content).digest('hex');
247
+ }
248
+
249
+ function snapshotContextFile(filePath) {
250
+ if (!CONTEXT_WRITE_LEGACY || !fs.existsSync(filePath)) return;
251
+ const rel = path.relative(CONTEXT_WRITE_LEGACY.root, filePath);
252
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return;
253
+ const dest = path.join(CONTEXT_WRITE_LEGACY.snapshotDir, rel);
254
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
255
+ fs.copyFileSync(filePath, dest);
256
+ CONTEXT_WRITE_REPORT.snapshot.push(rel.split(path.sep).join('/'));
257
+ }
258
+
182
259
  function writeContextFile(filePath, content, { overwrite = true } = {}) {
260
+ CONTEXT_WRITE_REPORT.seen.add(path.resolve(filePath));
183
261
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
184
262
  if (!overwrite && fs.existsSync(filePath) && fs.statSync(filePath).size > 0) {
185
263
  return false;
186
264
  }
265
+ const name = path.basename(filePath);
266
+ if (CONTEXT_WRITE_SAFE && fs.existsSync(filePath) && !PACKAGE_OWNED_CONTEXT.has(name)) {
267
+ const current = fs.readFileSync(filePath, 'utf8');
268
+ if (current === content) {
269
+ CONTEXT_WRITE_REPORT.kept.push(name);
270
+ recordGeneratedHash(filePath, content);
271
+ return false;
272
+ }
273
+ if (CONTEXT_WRITE_LEGACY) {
274
+ snapshotContextFile(filePath);
275
+ } else if (readGeneratedHashes(filePath)[name] !== sha256Text(current)) {
276
+ fs.writeFileSync(`${filePath}.ael-new`, content);
277
+ CONTEXT_WRITE_REPORT.aelNew.push(`${name}.ael-new`);
278
+ return false;
279
+ }
280
+ }
187
281
  fs.writeFileSync(filePath, content);
282
+ recordGeneratedHash(filePath, content);
283
+ if (CONTEXT_WRITE_SAFE) CONTEXT_WRITE_REPORT.updated.push(name);
188
284
  return true;
189
285
  }
190
286
 
287
+ // After a non-destructive refresh: remove AEL-managed files this version no
288
+ // longer generates. Normal flow: only files whose recorded hash still matches
289
+ // (edited ones are reported and kept). Legacy flow: OBSOLETE_CONTEXT_FILES,
290
+ // snapshotted first.
291
+ function removeObsoleteContextFiles(contextDir) {
292
+ const root = path.resolve(contextDir);
293
+ const candidates = new Map();
294
+ const hashDirs = [root];
295
+ try {
296
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
297
+ if (entry.isDirectory() && !entry.name.startsWith('.') && fs.existsSync(path.join(root, entry.name, GENERATED_HASHES_FILE))) {
298
+ hashDirs.push(path.join(root, entry.name));
299
+ }
300
+ }
301
+ } catch {
302
+ return;
303
+ }
304
+ for (const dir of hashDirs) {
305
+ const hashes = readGeneratedHashes(path.join(dir, 'x'));
306
+ for (const [name, hash] of Object.entries(hashes)) {
307
+ if (!/^[\w.-]+$/.test(name) || name.startsWith('.')) continue;
308
+ candidates.set(path.join(dir, name), { hash, dir, name });
309
+ }
310
+ }
311
+ if (CONTEXT_WRITE_LEGACY) {
312
+ for (const rel of OBSOLETE_CONTEXT_FILES) {
313
+ const abs = path.resolve(root, rel);
314
+ if (abs.startsWith(root + path.sep)) candidates.set(abs, { hash: null, dir: path.dirname(abs), name: path.basename(abs), legacy: true });
315
+ }
316
+ }
317
+ for (const [abs, info] of candidates) {
318
+ if (CONTEXT_WRITE_REPORT.seen.has(abs)) continue;
319
+ const rel = path.relative(root, abs).split(path.sep).join('/');
320
+ let stat;
321
+ try {
322
+ stat = fs.lstatSync(abs);
323
+ } catch {
324
+ stat = null;
325
+ }
326
+ if (stat && stat.isFile()) {
327
+ if (!info.legacy && sha256Text(fs.readFileSync(abs)) !== info.hash) {
328
+ CONTEXT_WRITE_REPORT.obsoleteKept.push(rel);
329
+ continue;
330
+ }
331
+ snapshotContextFile(abs);
332
+ fs.unlinkSync(abs);
333
+ CONTEXT_WRITE_REPORT.removed.push(rel);
334
+ }
335
+ const hashes = readGeneratedHashes(path.join(info.dir, 'x'));
336
+ if (Object.hasOwn(hashes, info.name)) {
337
+ delete hashes[info.name];
338
+ writeGeneratedHashes(path.join(info.dir, 'x'), hashes);
339
+ }
340
+ }
341
+ }
342
+
191
343
  function ignoreProjectContextOnFirstInit(rootDir) {
192
344
  const filePath = path.join(rootDir, '.gitignore');
193
345
  if (fs.existsSync(filePath) && fs.lstatSync(filePath).isSymbolicLink()) {
@@ -514,6 +666,7 @@ ${discovery.topLevelDirs.map((d) => `- \`${d}/\``).join('\n') || '- Flat directo
514
666
  ${discovery.scripts.e2e ? `- **e2e**: \`${discovery.scripts.e2e}\`` : ''}
515
667
 
516
668
  ## Verification Protocol
669
+ - Default order, cheapest first, stop at the first failure: build -> typecheck -> lint -> test_unit -> security scan (for example \`npm audit --omit=dev\`) -> e2e (optional).
517
670
  - 100% deterministic checks must pass before Devil's Advocate review.
518
671
  - Unit tests must cover boundary cases, null safety, and error paths.
519
672
  `;
@@ -738,7 +891,46 @@ function handleInit() {
738
891
  }
739
892
 
740
893
  // Command: status
894
+ function statusJson() {
895
+ const result = {
896
+ ok: false,
897
+ status: 'NOT_INITIALIZED',
898
+ packageVersion: VERSION,
899
+ project: path.basename(CWD),
900
+ hostSkills: hostSkillStatus({ home: homeDir(), version: VERSION })
901
+ };
902
+ if (fs.existsSync(CONTEXT_DIR)) {
903
+ const validation = validateContext(CONTEXT_DIR);
904
+ if (!validation.valid) {
905
+ result.status = 'INCOMPLETE';
906
+ result.reason = validation.reason;
907
+ } else {
908
+ let metadata = {};
909
+ try { metadata = JSON.parse(readFileSafe(path.join(CONTEXT_DIR, 'metadata.json')) || '{}'); } catch (e) {}
910
+ const drift = evaluateDrift(CWD, CONTEXT_DIR);
911
+ result.ok = true;
912
+ result.status = 'READY';
913
+ result.contextVersion = metadata.contextVersion || null;
914
+ result.projectProfile = metadata.projectProfile || null;
915
+ result.freshness = { status: drift.status, reason: drift.reason, level: drift.level || null };
916
+ const activeRun = currentRunSafe(CWD);
917
+ if (activeRun && !TERMINAL_STATES.has(activeRun.state)) {
918
+ const info = require('../lib/run-abandon.js').staleRunInfo(activeRun);
919
+ result.activeRun = { runId: activeRun.runId, state: activeRun.state, updatedAt: activeRun.updatedAt || null, stale: info.stale, idleDays: info.idleDays };
920
+ if (info.stale) result.activeRun.hint = require('../lib/run-abandon.js').abandonCommand(activeRun.runId);
921
+ }
922
+ }
923
+ }
924
+ return result;
925
+ }
926
+
741
927
  function handleStatus() {
928
+ if (command === 'status' && process.argv.includes('--json')) {
929
+ const result = statusJson();
930
+ console.log(JSON.stringify(result, null, 2));
931
+ if (!result.ok) process.exitCode = 1;
932
+ return;
933
+ }
742
934
  log.info('AI Engineering Loop — Project Context Status (status)');
743
935
  log.dim(`Target directory: ${CWD}`);
744
936
 
@@ -768,19 +960,28 @@ function handleStatus() {
768
960
  console.log(`- Living Freshness: \x1b[32m${drift.status}\x1b[0m (${drift.reason})`);
769
961
  console.log(`- Context Files: ${REQUIRED_FILES.length}/${REQUIRED_FILES.length} verified (including metadata.json, glossary.md, adrs/)`);
770
962
 
771
- const hostPlan = planHostSync({ home: homeDir() });
772
- const hostCopy = hostPlan.filter((item) => item.action === 'copy').length;
773
- if (hostCopy > 0) {
774
- log.warn(`- Host skills: STALE (${hostCopy} file(s) behind package v${VERSION})`);
775
- log.dim(' Run "npx ai-engineering-loop sync-hosts" then start a new session.');
963
+ const activeRun = currentRunSafe(CWD);
964
+ if (activeRun && !TERMINAL_STATES.has(activeRun.state)) {
965
+ console.log(`- Active run: ${activeRun.runId} (${activeRun.state})`);
966
+ const hint = staleRunHint(activeRun);
967
+ if (hint) log.warn(` ${hint}`);
968
+ }
969
+
970
+ const hosts = hostSkillStatus({ home: homeDir(), version: VERSION });
971
+ if (hosts.stale) {
972
+ log.warn(`- Host skills: STALE (${hosts.staleFiles} file(s) behind package v${VERSION}${hosts.installedVersion ? `, installed v${hosts.installedVersion}` : ''})`);
973
+ log.dim(' Run "npx ai-engineering-loop sync-hosts" (or "update apply --yes" after a package upgrade), then start a new session.');
776
974
  } else {
777
- const hostCurrent = hostPlan.filter((item) => item.action === 'current').length;
778
- console.log(`- Host skills: CURRENT (${hostCurrent} managed file(s) match v${VERSION})`);
975
+ console.log(`- Host skills: CURRENT (${hosts.managedFiles} managed file(s) match v${VERSION}; packs: ${hosts.packs.join(', ')})`);
779
976
  }
780
977
  }
781
978
 
782
979
  // Command: refresh
783
980
  function handleRefresh() {
981
+ if (process.argv.includes('--non-destructive')) {
982
+ handleSafeRefresh();
983
+ return;
984
+ }
784
985
  log.info('AI Engineering Loop — Context Drift Refresh (refresh)');
785
986
  log.dim(`Target directory: ${CWD}`);
786
987
 
@@ -813,20 +1014,201 @@ function handleRefresh() {
813
1014
  handleStatus();
814
1015
  }
815
1016
 
816
- function syncHostsQuiet() {
817
- const results = applyHostSync({ home: homeDir(), dryRun: false });
818
- const copied = results.filter((item) => item.action === 'copy').length;
819
- if (copied === 0) return;
820
- console.log(formatHostSyncReport(results, { version: VERSION }));
821
- }
822
-
823
1017
  function handleSyncHosts() {
824
1018
  const dryRun = process.argv.includes('--dry-run');
1019
+ const prune = process.argv.includes('--prune');
1020
+ const json = process.argv.includes('--json');
1021
+ const packArg = argValue('--pack');
1022
+ let results;
1023
+ try {
1024
+ results = applyHostSync({
1025
+ home: homeDir(),
1026
+ dryRun,
1027
+ prune,
1028
+ packs: packArg == null ? null : packArg,
1029
+ version: VERSION
1030
+ });
1031
+ } catch (err) {
1032
+ log.error(`${err.code || 'SYNC_FAILED'}: ${err.message}`);
1033
+ process.exit(2);
1034
+ }
1035
+ if (json) {
1036
+ console.log(JSON.stringify({
1037
+ ok: true,
1038
+ version: VERSION,
1039
+ dryRun,
1040
+ packs: results.packs,
1041
+ packSource: results.packSource,
1042
+ files: results.map(({ content, ...item }) => item)
1043
+ }, null, 2));
1044
+ return;
1045
+ }
825
1046
  log.info(`AI Engineering Loop — Sync host skills (sync-hosts)${dryRun ? ' [dry-run]' : ''}`);
826
- const results = applyHostSync({ home: homeDir(), dryRun });
827
1047
  console.log(formatHostSyncReport(results, { version: VERSION, dryRun }));
828
1048
  }
829
1049
 
1050
+ function hostSyncOrExit(selection, { dryRun = false } = {}) {
1051
+ try {
1052
+ return applyHostSync({ home: homeDir(), hosts: selection, dryRun, version: VERSION });
1053
+ } catch (err) {
1054
+ log.error(`${err.code || 'SYNC_FAILED'}: ${err.message}`);
1055
+ process.exit(2);
1056
+ }
1057
+ }
1058
+
1059
+ function readTtyLine(question, fallback) {
1060
+ process.stdout.write(question);
1061
+ try {
1062
+ const buffer = Buffer.alloc(64);
1063
+ const bytes = fs.readSync(0, buffer, 0, buffer.length, null);
1064
+ return buffer.toString('utf8', 0, bytes).trim().toLowerCase() || fallback;
1065
+ } catch {
1066
+ return fallback;
1067
+ }
1068
+ }
1069
+
1070
+ // `hosts list|doctor|enable|disable` (issues #49, #52).
1071
+ function handleHosts() {
1072
+ const rest = process.argv.slice(3).filter((arg) => !arg.startsWith('-'));
1073
+ const sub = rest[0] || 'list';
1074
+ const json = process.argv.includes('--json');
1075
+ const home = homeDir();
1076
+ const selection = resolveHostSelection(home);
1077
+ if (sub === 'list') {
1078
+ const rows = hostCommands.listHosts({ home, selection });
1079
+ if (json) {
1080
+ console.log(JSON.stringify({ ok: true, source: selection.source, mode: selection.mode, hosts: rows }, null, 2));
1081
+ return;
1082
+ }
1083
+ console.log(hostCommands.formatHostsList(rows, selection));
1084
+ if (selection.source !== 'config') console.log('Run "ai-engineering-loop setup" to choose hosts explicitly.');
1085
+ return;
1086
+ }
1087
+ if (sub === 'doctor') {
1088
+ const { hostsDoctor, formatHostsDoctor } = require('../lib/hosts/doctor.js');
1089
+ const report = hostsDoctor({ home, selection, plan: planHostSync({ home, hosts: selection }) });
1090
+ console.log(json ? JSON.stringify(report, null, 2) : formatHostsDoctor(report));
1091
+ if (!report.ok) process.exitCode = 1;
1092
+ return;
1093
+ }
1094
+ if (sub !== 'enable' && sub !== 'disable') {
1095
+ log.error(`Unknown hosts subcommand "${sub}". Use: list, doctor, enable <id...>, disable <id...>. Nothing was written.`);
1096
+ process.exit(2);
1097
+ }
1098
+ let ids;
1099
+ try {
1100
+ ids = hostCommands.parseHostIds(rest.slice(1));
1101
+ } catch (err) {
1102
+ log.error(`${err.code}: ${err.message}. Nothing was written.`);
1103
+ process.exit(2);
1104
+ }
1105
+ if (!ids.length) {
1106
+ log.error(`hosts ${sub} needs at least one host id. Nothing was written.`);
1107
+ process.exit(2);
1108
+ }
1109
+ const next = hostCommands.changeHosts({ home, selection, [sub]: ids });
1110
+ const results = hostSyncOrExit(next);
1111
+ if (json) {
1112
+ console.log(JSON.stringify({ ok: true, [sub === 'enable' ? 'enabled' : 'disabled']: ids, hosts: [...next.enabled], files: results.map(({ content, ...item }) => item) }, null, 2));
1113
+ return;
1114
+ }
1115
+ log.info(`AI Engineering Loop — hosts ${sub} ${ids.join(', ')}`);
1116
+ console.log(formatHostSyncReport(results, { version: VERSION }));
1117
+ }
1118
+
1119
+ // `setup` (issue #49): the one-time, explicit replacement for a postinstall
1120
+ // hook. Detects agents (config folder or PATH binary, never executed), asks,
1121
+ // then syncs. Without a TTY it only prints the plan unless --yes is given.
1122
+ function handleSetup() {
1123
+ const home = homeDir();
1124
+ const json = process.argv.includes('--json');
1125
+ const yes = process.argv.includes('--yes');
1126
+ const hostsArg = argValue('--hosts');
1127
+ const modeArg = argValue('--mode');
1128
+ if (modeArg && !['auto', 'manual'].includes(modeArg)) {
1129
+ log.error('--mode must be auto or manual. Nothing was written.');
1130
+ process.exit(2);
1131
+ }
1132
+ const selection = resolveHostSelection(home);
1133
+ const rows = hostCommands.listHosts({ home, selection });
1134
+ let ids;
1135
+ try {
1136
+ ids = hostsArg ? hostCommands.parseHostIds(hostsArg) : rows.filter((row) => row.detected).map((row) => row.id);
1137
+ } catch (err) {
1138
+ log.error(`${err.code}: ${err.message}. Nothing was written.`);
1139
+ process.exit(2);
1140
+ }
1141
+ const interactive = process.stdin.isTTY && process.stdout.isTTY && !json && autoUpdate.autoUpdateAllowedHere();
1142
+ if (!yes && !interactive) {
1143
+ const plan = { ok: true, wrote: false, detected: rows.filter((row) => row.detected).map((row) => row.id), wouldEnable: ids };
1144
+ if (json) console.log(JSON.stringify(plan, null, 2));
1145
+ else {
1146
+ console.log(hostCommands.formatHostsList(rows, selection));
1147
+ console.log(`Would enable: ${ids.join(', ') || '(none detected)'}`);
1148
+ console.log('Nothing was written. Run "ai-engineering-loop setup --yes" (optionally --hosts a,b --mode auto|manual) to install.');
1149
+ }
1150
+ return;
1151
+ }
1152
+ let mode = hostCommands.setupMode({ modeArg, interactive: false });
1153
+ if (!yes) {
1154
+ console.log(hostCommands.formatHostsList(rows, selection));
1155
+ if (!ids.length) {
1156
+ console.log('No AI agent detected. Install one, or pick hosts with "setup --hosts <id,...>".');
1157
+ return;
1158
+ }
1159
+ const ok = readTtyLine(`Install the loop for ${ids.join(', ')}? [Y/n] `, 'y');
1160
+ if (!['y', 'yes'].includes(ok)) {
1161
+ console.log('Nothing was written.');
1162
+ return;
1163
+ }
1164
+ if (!modeArg) {
1165
+ mode = hostCommands.setupMode({ interactive: true, answer: readTtyLine(hostCommands.SETUP_MODE_QUESTION, '') });
1166
+ }
1167
+ }
1168
+ const next = hostCommands.applySetup({ home, ids, mode });
1169
+ const results = hostSyncOrExit(next);
1170
+ if (json) {
1171
+ console.log(JSON.stringify({ ok: true, wrote: true, enabled: [...next.enabled], mode: next.mode, files: results.map(({ content, ...item }) => item) }, null, 2));
1172
+ return;
1173
+ }
1174
+ log.info(`AI Engineering Loop — setup (${next.enabled.size} host${next.enabled.size === 1 ? '' : 's'}, mode ${next.mode})`);
1175
+ console.log(formatHostSyncReport(results, { version: VERSION }));
1176
+ }
1177
+
1178
+ // First-run hint (issue #49): no postinstall writes to HOME, so the first
1179
+ // interactive CLI use suggests `setup` once a day until hosts are chosen.
1180
+ function maybeSetupHint() {
1181
+ try {
1182
+ if (process.env.AEL_NO_SETUP_HINT === '1' || process.argv.includes('--json')) return;
1183
+ if (!process.stderr.isTTY || !autoUpdate.autoUpdateAllowedHere()) return;
1184
+ const home = homeDir();
1185
+ if (hostCommands.savedHosts(home)) return;
1186
+ const userState = require('../lib/user-state.js');
1187
+ const stampFile = userState.userStatePath('setup-hint.json', home);
1188
+ const last = userState.readJsonFile(stampFile, {});
1189
+ if (last.at && Date.now() - Date.parse(last.at) < 24 * 60 * 60 * 1000) return;
1190
+ const rows = hostCommands.listHosts({ home, selection: resolveHostSelection(home) });
1191
+ const detected = rows.filter((row) => row.detected).map((row) => row.id);
1192
+ if (!detected.length) return;
1193
+ userState.writeJsonFile(stampFile, { at: new Date().toISOString() });
1194
+ process.stderr.write(`ai-engineering-loop: detected ${detected.join(', ')}. Run "ai-engineering-loop setup" once to install the loop for them (silence: AEL_NO_SETUP_HINT=1).\n`);
1195
+ } catch {
1196
+ // A hint never breaks a command.
1197
+ }
1198
+ }
1199
+
1200
+ // New agents after setup (issue #52): `status` prints a short, rate-limited
1201
+ // notice in manual mode; auto mode is handled by the background `update auto`.
1202
+ function maybeNewHostsNotice() {
1203
+ try {
1204
+ if (process.argv.includes('--json') || !process.stderr.isTTY || !autoUpdate.autoUpdateAllowedHere()) return;
1205
+ const message = require('../lib/hosts/redetect.js').newHostsNotice({ home: homeDir() });
1206
+ if (message) process.stderr.write(`${message}\n`);
1207
+ } catch {
1208
+ // A notice never breaks a command.
1209
+ }
1210
+ }
1211
+
830
1212
  function handleGenerateAdapter() {
831
1213
  log.info('AI Engineering Loop — Generate delivery adapter (generate-adapter)');
832
1214
  const hints = detectAdapterHints(CWD);
@@ -869,8 +1251,88 @@ function detectGrokHost() {
869
1251
  }
870
1252
  }
871
1253
 
1254
+ function workingTreePaths(rootDir) {
1255
+ try {
1256
+ return execSync('git status --porcelain --untracked-files=all', { cwd: rootDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
1257
+ .split('\n')
1258
+ .map((line) => line.slice(3).trim())
1259
+ .filter((line) => line && !line.startsWith('.ai-engineering-loop/'))
1260
+ .map((line) => line.includes(' -> ') ? line.split(' -> ').pop() : line);
1261
+ } catch (e) {
1262
+ return [];
1263
+ }
1264
+ }
1265
+
872
1266
  // Command: run
1267
+ // `run --abandon [--run <id>] --reason <text> --by <name> [--yes] [--json]`
1268
+ // (issue #46). ASSISTED asks for confirmation (or --yes); UNATTENDED runs are
1269
+ // refused unless a human passes --yes. Terminal runs exit 2.
1270
+ function handleRunAbandon() {
1271
+ const json = process.argv.includes('--json');
1272
+ const yes = process.argv.includes('--yes');
1273
+ const runAbandon = require('../lib/run-abandon.js');
1274
+ const fail = (err) => {
1275
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'ABANDON_FAILED', error: err.message }));
1276
+ else log.error(err.message);
1277
+ process.exit(err.exitCode || 1);
1278
+ };
1279
+ try {
1280
+ const plan = runAbandon.planAbandon(CWD, { runId: argValue('--run'), reason: argValue('--reason'), by: argValue('--by') });
1281
+ const { run } = plan;
1282
+ if (run.mode === 'UNATTENDED' && !yes) {
1283
+ throw Object.assign(new Error(`Run ${run.runId} is UNATTENDED. Agents must not abandon it; a human can re-run with --yes.`), { code: 'UNATTENDED_REQUIRES_HUMAN', exitCode: 2 });
1284
+ }
1285
+ if (!yes) {
1286
+ if (json || !process.stdin.isTTY || !process.stdout.isTTY) {
1287
+ throw Object.assign(new Error(`Confirm abandoning run ${run.runId} (${run.state}) by re-running with --yes.`), { code: 'CONFIRMATION_REQUIRED' });
1288
+ }
1289
+ process.stdout.write(`Abandon run ${run.runId} (${run.state}, ${run.task ? `"${String(run.task).slice(0, 60)}"` : 'no task'})? Run data is kept. [y/N] `);
1290
+ const buffer = Buffer.alloc(16);
1291
+ let answer = '';
1292
+ try {
1293
+ answer = buffer.toString('utf8', 0, fs.readSync(0, buffer, 0, buffer.length, null)).trim().toLowerCase();
1294
+ } catch {
1295
+ answer = '';
1296
+ }
1297
+ if (!['y', 'yes'].includes(answer)) {
1298
+ console.log('Not abandoned.');
1299
+ process.exit(1);
1300
+ }
1301
+ }
1302
+ const result = runAbandon.abandonRun(CWD, { runId: run.runId, reason: plan.reason, by: plan.actor });
1303
+ if (json) console.log(JSON.stringify({ ok: true, ...result }));
1304
+ else {
1305
+ log.success(`✓ Run ${result.runId} abandoned (${result.from} -> CANCELLED) by ${result.by}: ${result.reason}`);
1306
+ console.log(result.released
1307
+ ? '- current.json released; refresh and auto-update will process this project again.'
1308
+ : `- current run unchanged${result.current ? ` (${result.current})` : ''}.`);
1309
+ }
1310
+ } catch (err) {
1311
+ fail(err);
1312
+ }
1313
+ }
1314
+
1315
+ // One-line hint for an active run that has not moved for STALE_RUN_DAYS.
1316
+ function staleRunHint(run) {
1317
+ const runAbandon = require('../lib/run-abandon.js');
1318
+ const info = runAbandon.staleRunInfo(run);
1319
+ if (!info.stale) return null;
1320
+ return `Run ${run.runId} has been ${run.state} for ${info.idleDays} day(s). If it is abandoned: ${runAbandon.abandonCommand(run.runId)}`;
1321
+ }
1322
+
1323
+ function currentRunSafe(dir) {
1324
+ try {
1325
+ return getCurrentRun(dir);
1326
+ } catch {
1327
+ return null;
1328
+ }
1329
+ }
1330
+
873
1331
  function handleRun() {
1332
+ if (process.argv.includes('--abandon')) return handleRunAbandon();
1333
+ const runJson = process.argv.includes('--json');
1334
+ const realLog = console.log;
1335
+ if (runJson) console.log = () => {};
874
1336
  log.info('AI Engineering Loop — Task Execution Entrypoint (run)');
875
1337
 
876
1338
  if (!fs.existsSync(CONTEXT_DIR)) {
@@ -880,20 +1342,16 @@ function handleRun() {
880
1342
  handleStatus();
881
1343
  }
882
1344
 
883
- syncHostsQuiet();
884
-
885
1345
  const runArgs = process.argv.slice(3);
886
1346
  const forceNew = runArgs.includes('--new');
887
1347
  const modeArg = argValue('--mode');
888
1348
  const recipeArg = argValue('--recipe');
1349
+ const tierArg = argValue('--tier');
1350
+ const tierReasonArg = argValue('--tier-reason');
889
1351
  const taskParts = [];
890
1352
  for (let index = 0; index < runArgs.length; index++) {
891
- if (runArgs[index] === '--new') continue;
892
- if (runArgs[index] === '--mode') {
893
- index += 1;
894
- continue;
895
- }
896
- if (runArgs[index] === '--recipe') {
1353
+ if (runArgs[index] === '--new' || runArgs[index] === '--json') continue;
1354
+ if (['--mode', '--recipe', '--tier', '--tier-reason'].includes(runArgs[index])) {
897
1355
  index += 1;
898
1356
  continue;
899
1357
  }
@@ -939,19 +1397,63 @@ function handleRun() {
939
1397
  }
940
1398
  }
941
1399
  if (mode) assertModeAllowed(CWD, mode);
1400
+ const tier = startsNewRun
1401
+ ? initialTierState({ task, changedPaths: workingTreePaths(CWD), override: tierArg, overrideReason: tierReasonArg })
1402
+ : null;
1403
+ if (!startsNewRun && tierArg) throw new Error('--tier applies only when a new run starts (use --new).');
942
1404
  runResult = createOrResumeRun(CWD, {
943
1405
  task,
944
1406
  forceNew,
945
1407
  mode,
946
1408
  workflow,
1409
+ tier,
947
1410
  ...(requestedRunId ? { runId: requestedRunId } : {})
948
1411
  });
949
1412
  assertBudgetAvailable(CWD, { runId: runResult.run.runId });
950
1413
  } catch (err) {
1414
+ console.log = realLog;
1415
+ if (runJson) {
1416
+ realLog(JSON.stringify({ ok: false, code: err.code || 'RUN_FAILED', error: err.message }));
1417
+ process.exit(1);
1418
+ }
951
1419
  log.error(err.message);
952
1420
  process.exit(1);
953
1421
  }
1422
+ if (runJson) {
1423
+ console.log = realLog;
1424
+ const run = runResult.run;
1425
+ console.log(JSON.stringify({
1426
+ ok: true,
1427
+ runId: run.runId,
1428
+ resumed: runResult.resumed,
1429
+ state: run.state,
1430
+ iteration: run.iteration,
1431
+ mode: run.mode || RUN_MODES.ASSISTED,
1432
+ tier: run.tier ? run.tier.current : null,
1433
+ tierSource: run.tier ? run.tier.source : null,
1434
+ tierReasons: run.tier ? run.tier.reasons : [],
1435
+ subagents: run.tier ? { T0: 0, T1: 1, T2: 2 }[run.tier.current] : 2,
1436
+ recipe: run.workflow ? run.workflow.recipeId : null,
1437
+ budget: (() => {
1438
+ try {
1439
+ const b = budgetStatus(CWD, { runId: run.runId });
1440
+ return { allowed: b.allowed, spentThisRun: b.spentThisRun, warnings: b.warnings || [] };
1441
+ } catch (e) {
1442
+ return { allowed: false, error: e.message };
1443
+ }
1444
+ })(),
1445
+ hostSkills: (() => {
1446
+ const h = hostSkillStatus({ home: homeDir(), version: VERSION });
1447
+ return { stale: h.stale, staleFiles: h.staleFiles, installedVersion: h.installedVersion, packageVersion: VERSION };
1448
+ })()
1449
+ }, null, 2));
1450
+ return;
1451
+ }
954
1452
  console.log(`- Run: ${runResult.run.runId} (${runResult.resumed ? 'resumed' : 'created'})`);
1453
+ if (runResult.run.tier) {
1454
+ const t = runResult.run.tier;
1455
+ console.log(`- Tier: ${t.current} (${t.source}; ${t.reasons.map((r) => r.code).join(', ')})`);
1456
+ }
955
1457
  console.log(`- State: ${runResult.run.state}, iteration ${runResult.run.iteration}`);
956
1458
  console.log(`- Mode: ${runResult.run.mode || RUN_MODES.ASSISTED}`);
957
1459
  if (runResult.run.workflow) {
@@ -967,16 +1469,25 @@ function handleRun() {
967
1469
 
968
1470
  console.log('\n------------------------------------------------------------');
969
1471
  log.bold('AI Agent Ready:');
970
- console.log('1. Grill if needed, then freeze Goal Contract (core/grill-policy.md, core/goal-contract.md)');
1472
+ console.log('1. Grill if needed (docs grill-policy), then freeze a failure-table Goal Contract');
971
1473
  if (runResult.run.mode === RUN_MODES.REPORT_ONLY) {
972
1474
  console.log('2. Analyze evidence without changing repository files');
973
1475
  console.log('3. Write report.json and finish with `ai-engineering-loop gate report`');
974
1476
  } else {
975
- console.log('2. Root Cause Analysis (core/root-cause-analysis.md) & Plan');
976
- console.log('3. Maker TDD at named seams (policies/tdd-policy.md)');
1477
+ console.log('2. Root Cause Analysis (docs root-cause-analysis) & Plan');
1478
+ console.log('3. Maker TDD at named seams (docs tdd-policy)');
977
1479
  console.log('4. Run Deterministic Verification');
978
- console.log('5. Execute Devil\'s Advocate Adversarial Review');
979
- console.log('6. Judge Agent evaluates DoD and issues PASS verdict');
1480
+ const tierNow = runResult.run.tier ? runResult.run.tier.current : null;
1481
+ if (tierNow === 'T0') {
1482
+ console.log('5. T0: no Devil\'s Advocate. Fill claimed-vs-reality, then `gate review` (CLI writes the empty ledger)');
1483
+ console.log('6. T0: `gate judge` writes the deterministic verdict (no Judge subagent)');
1484
+ } else if (tierNow === 'T1') {
1485
+ console.log('5. Execute lean Devil\'s Advocate review, then `gate review --json`');
1486
+ console.log('6. Judge subagent only if `gate review` says judgeRequired; otherwise `gate judge` is deterministic');
1487
+ } else {
1488
+ console.log('5. Execute Devil\'s Advocate Adversarial Review');
1489
+ console.log(`6. Judge Agent evaluates DoD and issues PASS verdict${tierNow === 'T2' ? ' (STRONG_MODEL required)' : ''}`);
1490
+ }
980
1491
  console.log('7. Context Impact Assessment (NONE / TARGETED / MAJOR)');
981
1492
  console.log('8. Delivery Adapter creates MR/PR');
982
1493
  if (runResult.run.mode === RUN_MODES.ASSISTED) {
@@ -997,7 +1508,7 @@ function handleRun() {
997
1508
  } else {
998
1509
  console.log(`- Fallback: CONTEXT_ISOLATION_ONLY (${grok.reason})`);
999
1510
  }
1000
- console.log('- Skill: .grok/skills/ai-engineering-loop/SKILL.md');
1511
+ console.log('- Skill: .agents/skills/ai-engineering-loop/SKILL.md (spawn rules: references/loop-hosts.md, Grok CLI section)');
1001
1512
  }
1002
1513
 
1003
1514
  const claudeSkill = path.join(CWD, '.claude', 'skills', 'ai-engineering-loop', 'SKILL.md');
@@ -1012,14 +1523,14 @@ function handleRun() {
1012
1523
  console.log('- Skill: .claude/skills/ai-engineering-loop/SKILL.md');
1013
1524
  }
1014
1525
 
1015
- const agAgent = path.join(CWD, '.agents', 'judge.md');
1016
- if (fs.existsSync(agAgent)) {
1526
+ const sharedSkill = path.join(CWD, '.agents', 'skills', 'ai-engineering-loop', 'SKILL.md');
1527
+ if (fs.existsSync(sharedSkill)) {
1017
1528
  console.log('------------------------------------------------------------');
1018
- log.bold('Antigravity host:');
1019
- console.log('- Subagent: invoke_subagent or Task; wait; never browser_subagent');
1529
+ log.bold('Shared .agents/skills hosts (Codex, Gemini CLI, Antigravity, Cursor, Copilot, ...):');
1530
+ console.log('- Same skill on every host; spawn rules per host: references/loop-hosts.md');
1020
1531
  console.log('- Devil\'s Advocate: 8 tool calls, diff file, skip css');
1021
1532
  console.log('- Judge: 4 tool calls, ledger + contract only');
1022
- console.log('- Workflow: .agents/workflows/ai-engineering-loop.md');
1533
+ console.log('- Skill: .agents/skills/ai-engineering-loop/SKILL.md');
1023
1534
  }
1024
1535
  console.log('------------------------------------------------------------\n');
1025
1536
  }
@@ -1126,6 +1637,8 @@ function handleBudget() {
1126
1637
  ? 0
1127
1638
  : parseNonNegativeIntegerArg('--estimate', argValue('--estimate'))
1128
1639
  });
1640
+ } else if (action === 'record' && process.argv.includes('--unavailable')) {
1641
+ result = recordUsageUnavailable(CWD, { runId, nodeId });
1129
1642
  } else if (action === 'record') {
1130
1643
  result = recordTokenUsage(CWD, {
1131
1644
  runId,
@@ -1299,6 +1812,69 @@ function handleArtifactTool(action) {
1299
1812
  }
1300
1813
  }
1301
1814
 
1815
+ // Shared by `gate` and the combined stage commands (issue #34) so both paths
1816
+ // publish identical workflow-node and Studio lifecycle events.
1817
+ function executeGate(gate, runId) {
1818
+ const target = runId ? loadRun(CWD, runId) : getCurrentRun(CWD);
1819
+ if (!target) throw new Error('No current run. Start one with `ai-engineering-loop run`.');
1820
+ listRunLifecycle(CWD, target.runId);
1821
+ let lifecycleNode = null;
1822
+ if (target.workflow) {
1823
+ const workflow = workflowStatus(CWD, { runId: target.runId });
1824
+ lifecycleNode = workflow.plan.nodes.find((node) => node.legacyGate === gate) || null;
1825
+ if (lifecycleNode && workflow.state.nodes[lifecycleNode.id].status === 'READY') {
1826
+ startWorkflowNode(CWD, lifecycleNode.id, { runId: target.runId });
1827
+ appendRunLifecycle(CWD, target.runId, {
1828
+ type: 'NODE_STARTED',
1829
+ nodeId: lifecycleNode.id,
1830
+ phase: gate,
1831
+ actor: 'agent',
1832
+ message: `${lifecycleNode.displayName || lifecycleNode.id} started`
1833
+ });
1834
+ }
1835
+ }
1836
+ const run = target.workflow
1837
+ ? applyWorkflowGate(CWD, gate, { runId: target.runId }).run
1838
+ : applyGate(CWD, gate, { runId: target.runId });
1839
+ const runCompleted = run.state === 'DELIVERED' || run.state === 'REPORTED';
1840
+ appendRunLifecycle(CWD, target.runId, {
1841
+ type: runCompleted
1842
+ ? 'RUN_COMPLETED'
1843
+ : (lifecycleNode ? 'NODE_COMPLETED' : 'PHASE_COMPLETED'),
1844
+ ...(!runCompleted && lifecycleNode ? { nodeId: lifecycleNode.id } : {}),
1845
+ phase: gate,
1846
+ actor: 'agent',
1847
+ status: 'PASSED',
1848
+ message: `${lifecycleNode?.displayName || gate} completed`
1849
+ });
1850
+ return run;
1851
+ }
1852
+
1853
+ // `gate maker --from-git` (issue #35): write the working-tree diff (tracked and
1854
+ // untracked files, excluding .ai-engineering-loop/) to RUN_DIR/diff.patch so the
1855
+ // agent does not need a separate write step. ASSISTED/REPORT_ONLY only;
1856
+ // UNATTENDED diffs come from `sandbox capture`.
1857
+ function captureMakerDiff(run) {
1858
+ if (run.mode === 'UNATTENDED') throw new Error('--from-git is not allowed in UNATTENDED; use `sandbox capture`.');
1859
+ const { execFileSync } = require('child_process');
1860
+ const exclude = ':(exclude).ai-engineering-loop';
1861
+ const git = (args, allowExit1 = false) => {
1862
+ try {
1863
+ return execFileSync('git', args, { cwd: CWD, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
1864
+ } catch (e) {
1865
+ if (allowExit1 && e.status === 1) return e.stdout;
1866
+ throw e;
1867
+ }
1868
+ };
1869
+ let diff = git(['diff', '--binary', 'HEAD', '--', '.', exclude]);
1870
+ const untracked = git(['ls-files', '--others', '--exclude-standard', '-z', '--', '.', exclude]).split('\0').filter(Boolean);
1871
+ for (const file of untracked) diff += git(['diff', '--binary', '--no-index', '--', '/dev/null', file], true);
1872
+ if (!diff.trim()) throw new Error('--from-git found no changes against HEAD.');
1873
+ const target = path.join(CWD, '.ai-engineering-loop', 'runs', run.runId, 'diff.patch');
1874
+ fs.writeFileSync(target, diff);
1875
+ return { path: path.relative(CWD, target).split(path.sep).join('/'), files: untracked.length };
1876
+ }
1877
+
1302
1878
  function handleGate() {
1303
1879
  const gate = process.argv[3];
1304
1880
  const runId = argValue('--run');
@@ -1308,48 +1884,32 @@ function handleGate() {
1308
1884
  const target = runId ? loadRun(CWD, runId) : getCurrentRun(CWD);
1309
1885
  if (!target) throw new Error('No current run. Start one with `ai-engineering-loop run`.');
1310
1886
  targetRunId = target.runId;
1311
- listRunLifecycle(CWD, target.runId);
1312
- let lifecycleNode = null;
1313
- if (target.workflow) {
1314
- const workflow = workflowStatus(CWD, { runId: target.runId });
1315
- lifecycleNode = workflow.plan.nodes.find((node) => node.legacyGate === gate) || null;
1316
- if (lifecycleNode && workflow.state.nodes[lifecycleNode.id].status === 'READY') {
1317
- startWorkflowNode(CWD, lifecycleNode.id, { runId: target.runId });
1318
- appendRunLifecycle(CWD, target.runId, {
1319
- type: 'NODE_STARTED',
1320
- nodeId: lifecycleNode.id,
1321
- phase: gate,
1322
- actor: 'agent',
1323
- message: `${lifecycleNode.displayName || lifecycleNode.id} started`
1324
- });
1325
- }
1887
+ if (process.argv.includes('--from-git')) {
1888
+ if (gate !== 'maker') throw new Error('--from-git only applies to `gate maker`.');
1889
+ captureMakerDiff(target);
1326
1890
  }
1327
- const run = target.workflow
1328
- ? applyWorkflowGate(CWD, gate, { runId: target.runId }).run
1329
- : applyGate(CWD, gate, { runId: target.runId });
1330
- const runCompleted = run.state === 'DELIVERED' || run.state === 'REPORTED';
1331
- appendRunLifecycle(CWD, target.runId, {
1332
- type: runCompleted
1333
- ? 'RUN_COMPLETED'
1334
- : (lifecycleNode ? 'NODE_COMPLETED' : 'PHASE_COMPLETED'),
1335
- ...(!runCompleted && lifecycleNode ? { nodeId: lifecycleNode.id } : {}),
1336
- phase: gate,
1337
- actor: 'agent',
1338
- status: 'PASSED',
1339
- message: `${lifecycleNode?.displayName || gate} completed`
1340
- });
1891
+ const run = executeGate(gate, target.runId);
1892
+ const judge = gate === 'review' && run.tier ? judgeRequirement(CWD, run) : null;
1341
1893
  if (json) {
1342
1894
  console.log(JSON.stringify({
1343
1895
  ok: true,
1344
1896
  runId: run.runId,
1345
1897
  state: run.state,
1346
1898
  iteration: run.iteration,
1347
- gate
1899
+ gate,
1900
+ ...(run.tier ? { tier: run.tier.current } : {}),
1901
+ ...(judge ? { judgeRequired: judge.required, judgeReasons: judge.reasons } : {})
1348
1902
  }));
1349
1903
  } else {
1350
1904
  log.success(`✓ ${gate} gate passed`);
1351
1905
  console.log(`- Run: ${run.runId}`);
1352
1906
  console.log(`- State: ${run.state}, iteration ${run.iteration}`);
1907
+ if (run.tier) console.log(`- Tier: ${run.tier.current}`);
1908
+ if (judge) {
1909
+ console.log(judge.required
1910
+ ? `- Judge: REQUIRED (${judge.reasons.join('; ')}). Spawn the Judge subagent, write verdict.json, then gate judge.`
1911
+ : '- Judge: not required. Run "gate judge" now; the CLI writes the deterministic verdict.');
1912
+ }
1353
1913
  }
1354
1914
  } catch (err) {
1355
1915
  const retryHint = targetRunId && gate && err.code === 'GATE_FAILED'
@@ -1685,6 +2245,8 @@ function handleState() {
1685
2245
  console.log(`State: ${run.state}`);
1686
2246
  console.log(`Iteration: ${run.iteration}`);
1687
2247
  console.log(`Artifacts: ${Object.keys(run.artifacts).join(', ') || 'none'}`);
2248
+ const hint = staleRunHint(run);
2249
+ if (hint) log.warn(hint);
1688
2250
  }
1689
2251
  } catch (err) {
1690
2252
  if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'STATE_FAILED', error: err.message }));
@@ -1718,8 +2280,280 @@ function printUpdatePlan(plan) {
1718
2280
  for (const item of plan.commands) console.log(item.display);
1719
2281
  }
1720
2282
 
2283
+ // Used by auto-update for every registered project: regenerate context with
2284
+ // user-edited files preserved (new templates land in *.ael-new).
2285
+ function handleSafeRefresh() {
2286
+ if (!fs.existsSync(CONTEXT_DIR)) {
2287
+ log.error('No .ai-engineering-loop/ here; run init first.');
2288
+ process.exit(1);
2289
+ }
2290
+ const current = getCurrentRun(CWD);
2291
+ if (current && !TERMINAL_STATES.has(current.state)) {
2292
+ log.warn(`Run ${current.runId} is active (${current.state}); skipping refresh until it finishes.`);
2293
+ log.dim(`If that run is abandoned, close it first: ${require('../lib/run-abandon.js').abandonCommand(current.runId)}`);
2294
+ process.exit(3);
2295
+ }
2296
+ const legacy = !fs.existsSync(path.join(CONTEXT_DIR, GENERATED_HASHES_FILE));
2297
+ if (legacy) {
2298
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
2299
+ CONTEXT_WRITE_LEGACY = { root: path.resolve(CONTEXT_DIR), snapshotDir: path.join(CONTEXT_DIR, '.ael-backup', stamp) };
2300
+ }
2301
+ CONTEXT_WRITE_SAFE = true;
2302
+ const discovery = analyzeRepository(CWD);
2303
+ generateContextFiles(CWD, discovery, 'refresh', 'PACKAGE_UPDATE', { overwriteCore: true });
2304
+ removeObsoleteContextFiles(CONTEXT_DIR);
2305
+ CONTEXT_WRITE_SAFE = false;
2306
+ let snapshot = null;
2307
+ if (CONTEXT_WRITE_LEGACY && CONTEXT_WRITE_REPORT.snapshot.length) {
2308
+ snapshot = path.relative(CWD, CONTEXT_WRITE_LEGACY.snapshotDir).split(path.sep).join('/');
2309
+ fs.writeFileSync(path.join(CONTEXT_WRITE_LEGACY.snapshotDir, 'snapshot.json'), `${JSON.stringify({
2310
+ schemaVersion: 1,
2311
+ reason: 'LEGACY_FIRST_UPDATE',
2312
+ version: VERSION,
2313
+ at: new Date().toISOString(),
2314
+ files: CONTEXT_WRITE_REPORT.snapshot,
2315
+ removed: CONTEXT_WRITE_REPORT.removed
2316
+ }, null, 2)}\n`);
2317
+ }
2318
+ CONTEXT_WRITE_LEGACY = null;
2319
+ const report = {
2320
+ ok: true,
2321
+ mode: legacy ? 'legacy-first-update' : 'hash-checked',
2322
+ updated: CONTEXT_WRITE_REPORT.updated,
2323
+ aelNew: CONTEXT_WRITE_REPORT.aelNew,
2324
+ unchanged: CONTEXT_WRITE_REPORT.kept,
2325
+ removed: CONTEXT_WRITE_REPORT.removed,
2326
+ obsoleteKept: CONTEXT_WRITE_REPORT.obsoleteKept,
2327
+ snapshot
2328
+ };
2329
+ if (process.argv.includes('--json')) console.log(JSON.stringify(report));
2330
+ else {
2331
+ log.success('✓ Context refreshed non-destructively.');
2332
+ if (legacy) console.log(`- First update of a legacy project: AEL-managed files overwritten${snapshot ? `; previous copies in ${snapshot}` : ''}.`);
2333
+ if (report.removed.length) console.log(`- Removed obsolete AEL files: ${report.removed.join(', ')}`);
2334
+ if (report.aelNew.length) console.log(`- Kept your edits; review new templates: ${report.aelNew.join(', ')}`);
2335
+ if (report.obsoleteKept.length) console.log(`- Obsolete but edited (kept): ${report.obsoleteKept.join(', ')}`);
2336
+ }
2337
+ }
2338
+
2339
+ function readCurrentRunFor(dir) {
2340
+ const run = getCurrentRun(dir);
2341
+ return run ? { ...run, terminal: TERMINAL_STATES.has(run.state) } : null;
2342
+ }
2343
+
2344
+ function expectedRepository() {
2345
+ const repo = require('../package.json').repository;
2346
+ return repo && typeof repo === 'object' ? repo.url : repo || null;
2347
+ }
2348
+
2349
+ // Decision 1 on #37: a short, useful notice, at most once a day per project,
2350
+ // interactive stderr only (never CI or --json).
2351
+ function showUpdateNotice(cache, decision, policy) {
2352
+ const notice = require('../lib/update-notice.js');
2353
+ if (!notice.noticeAllowed()) return;
2354
+ const projectKey = path.resolve(process.cwd());
2355
+ if (!notice.noticeDue(cache, projectKey)) return;
2356
+ const packageRoot = path.join(__dirname, '..');
2357
+ const scope = cache.scope || detectInstallScope(packageRoot);
2358
+ const manager = scope === 'global' ? notice.detectGlobalPackageManager(packageRoot) : notice.detectPackageManager(projectKey);
2359
+ const cached = cache.highlights;
2360
+ const highlights = cached && cached.target === decision.target && cached.from === VERSION ? cached.items || [] : [];
2361
+ process.stderr.write(`${notice.formatNotice({
2362
+ packageName: require('../package.json').name,
2363
+ current: VERSION,
2364
+ target: decision.target,
2365
+ bump: decision.bump,
2366
+ scope,
2367
+ manager,
2368
+ highlights,
2369
+ policy: policy.policy,
2370
+ reason: decision.reason
2371
+ })}\n`);
2372
+ const userState = require('../lib/user-state.js');
2373
+ userState.writeJsonFile(userState.userStatePath('update-check.json'), notice.markNoticeShown(cache, projectKey, decision.target));
2374
+ }
2375
+
2376
+ // Background only: cache 2-4 CHANGELOG highlights for current -> target.
2377
+ async function cacheUpdateHighlights(cache, decision, packageName) {
2378
+ if (!decision.target || decision.action === 'none') return;
2379
+ if (cache.highlights && cache.highlights.target === decision.target && cache.highlights.from === VERSION) return;
2380
+ const notice = require('../lib/update-notice.js');
2381
+ const slug = (String(expectedRepository() || '').match(/github\.com[/:]([^/]+\/[^/.]+)/) || [])[1] || null;
2382
+ const text = await notice.fetchChangelog({ packageName, target: decision.target, repositorySlug: slug });
2383
+ if (!text) return;
2384
+ const items = notice.changelogHighlights(text, { current: VERSION, target: decision.target });
2385
+ const userState = require('../lib/user-state.js');
2386
+ const latest = autoUpdate.readCache() || cache;
2387
+ userState.writeJsonFile(userState.userStatePath('update-check.json'), { ...latest, highlights: { from: VERSION, target: decision.target, items } });
2388
+ }
2389
+
2390
+ // Foreground hook for run/status/init/refresh. Never blocks and never throws:
2391
+ // prints a pending summary or notice to stderr and, when the cache is stale or
2392
+ // an update is due, starts `update auto --background` detached.
2393
+ function maybeAutoUpdate() {
2394
+ try {
2395
+ if (!autoUpdate.autoUpdateAllowedHere()) return;
2396
+ const summary = autoUpdate.consumeSummary();
2397
+ if (summary) process.stderr.write(`${summary}\n`);
2398
+ const policy = autoUpdate.resolvePolicy();
2399
+ if (policy.policy === 'off') return;
2400
+ const cache = autoUpdate.readCache();
2401
+ if (autoUpdate.cacheStale(cache)) {
2402
+ autoUpdate.spawnBackgroundCheck({ cliPath: __filename });
2403
+ return;
2404
+ }
2405
+ const state = autoUpdate.readState();
2406
+ const decision = autoUpdate.decideUpdate({ current: VERSION, distTags: cache.distTags, ...policy });
2407
+ const applyInBackground = decision.action === 'apply' && cache.scope === 'global';
2408
+ if (applyInBackground || (state.pendingProjects || []).length) {
2409
+ autoUpdate.spawnBackgroundCheck({ cliPath: __filename });
2410
+ }
2411
+ if (!applyInBackground && decision.action !== 'none') showUpdateNotice(cache, decision, policy);
2412
+ } catch {
2413
+ // Auto-update must never break a command.
2414
+ }
2415
+ }
2416
+
2417
+ // `update auto [--background] [--force] [--json]`: check (cached 24 h), decide,
2418
+ // and apply under the user's policy; also retries projects left pending.
2419
+ function handleUpdateAuto() {
2420
+ const json = process.argv.includes('--json');
2421
+ const background = process.argv.includes('--background');
2422
+ const packageName = require('../package.json').name;
2423
+ const policy = autoUpdate.resolvePolicy();
2424
+ const out = (value) => {
2425
+ if (!background) console.log(json ? JSON.stringify(value) : JSON.stringify(value, null, 2));
2426
+ };
2427
+ if (policy.policy === 'off' && !process.argv.includes('--force')) {
2428
+ out({ ok: true, action: 'none', reason: `POLICY_OFF (${policy.source})` });
2429
+ return;
2430
+ }
2431
+ let cache = autoUpdate.readCache();
2432
+ if (autoUpdate.cacheStale(cache) || process.argv.includes('--force')) cache = autoUpdate.refreshCache({ packageName });
2433
+ const scope = detectInstallScope(path.join(__dirname, '..'));
2434
+ try {
2435
+ require('../lib/user-state.js').writeJsonFile(require('../lib/user-state.js').userStatePath('update-check.json'), { ...cache, scope });
2436
+ } catch {
2437
+ // Best effort.
2438
+ }
2439
+ const decision = autoUpdate.decideUpdate({ current: VERSION, distTags: cache.distTags, ...policy });
2440
+ // Agents installed after setup (#52): auto mode enables and syncs them here.
2441
+ let hostsResult = { added: [] };
2442
+ try {
2443
+ hostsResult = require('../lib/hosts/redetect.js').autoEnableNewHosts({ home: homeDir(), scope });
2444
+ if (hostsResult.added.length && decision.action !== 'apply') {
2445
+ const synced = applyHostSync({ home: homeDir(), hosts: resolveHostSelection(homeDir()), version: VERSION });
2446
+ hostsResult = { ...hostsResult, synced: synced.filter((item) => item.action === 'copy').length };
2447
+ }
2448
+ } catch (err) {
2449
+ hostsResult = { added: [], error: err.message };
2450
+ }
2451
+ const projects = projectRegistry.listProjects().projects;
2452
+ let result = null;
2453
+ if (decision.action === 'apply') {
2454
+ result = autoUpdate.applyUpdate({
2455
+ packageName,
2456
+ current: VERSION,
2457
+ target: decision.target,
2458
+ scope,
2459
+ projects,
2460
+ readCurrentRun: readCurrentRunFor,
2461
+ expectedRepository: expectedRepository()
2462
+ });
2463
+ } else {
2464
+ result = autoUpdate.processPending({ projects, readCurrentRun: readCurrentRunFor });
2465
+ }
2466
+ const held = result && Array.isArray(result.pending) && result.pending.length
2467
+ ? { pendingHint: `Projects skipped because a run is active. If a run is abandoned, run in that project: ${require('../lib/run-abandon.js').abandonCommand()}` }
2468
+ : {};
2469
+ out({ ok: true, policy: policy.policy, policySource: policy.source, scope, offline: cache.error || null, decision, result, hosts: hostsResult, ...held });
2470
+ cacheUpdateHighlights({ ...cache, scope }, decision, packageName).catch(() => {});
2471
+ }
2472
+
2473
+ function handleUpdatePolicy() {
2474
+ const json = process.argv.includes('--json');
2475
+ const value = process.argv[4] && !process.argv[4].startsWith('-') ? process.argv[4] : undefined;
2476
+ const channel = argValue('--channel') || undefined;
2477
+ const pin = process.argv.includes('--no-pin') ? null : (argValue('--pin') || undefined);
2478
+ try {
2479
+ if (value !== undefined || channel !== undefined || pin !== undefined) autoUpdate.setPolicy({ policy: value, channel, pin });
2480
+ const resolved = autoUpdate.resolvePolicy();
2481
+ if (json) console.log(JSON.stringify({ ok: true, ...resolved }));
2482
+ else console.log(`Auto-update policy: ${resolved.policy} (${resolved.source}); channel ${resolved.channel}${resolved.pin ? `; pin ${resolved.pin}` : ''}. Majors are always notice-only.`);
2483
+ } catch (err) {
2484
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code, error: err.message }));
2485
+ else log.error(err.message);
2486
+ process.exit(1);
2487
+ }
2488
+ }
2489
+
2490
+ function handleUpdateRollback() {
2491
+ const json = process.argv.includes('--json');
2492
+ try {
2493
+ if (!process.argv.includes('--yes')) throw Object.assign(new Error('update rollback requires --yes'), { code: 'CONFIRMATION_REQUIRED' });
2494
+ const record = autoUpdate.rollback({ packageName: require('../package.json').name, projects: projectRegistry.listProjects().projects });
2495
+ if (json) console.log(JSON.stringify({ ok: true, ...record }));
2496
+ else log.success(`✓ Rolled back to ${record.to} and re-synced host skills${record.restored && record.restored.length ? `; restored ${record.restored.length} legacy project snapshot(s)` : ""}.`);
2497
+ } catch (err) {
2498
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'ROLLBACK_FAILED', error: err.message }));
2499
+ else log.error(err.message);
2500
+ process.exit(1);
2501
+ }
2502
+ }
2503
+
2504
+ function handleProjects() {
2505
+ const action = process.argv[3] || 'list';
2506
+ const json = process.argv.includes('--json');
2507
+ try {
2508
+ let result;
2509
+ if (action === 'list') result = projectRegistry.listProjects();
2510
+ else if (action === 'add') result = { added: projectRegistry.addProject(process.argv[4] && !process.argv[4].startsWith('-') ? process.argv[4] : CWD) };
2511
+ else if (action === 'remove') result = { removed: projectRegistry.removeProject(process.argv[4] && !process.argv[4].startsWith('-') ? process.argv[4] : CWD) };
2512
+ else if (action === 'scan') {
2513
+ const root = argValue('--root');
2514
+ if (!root) throw Object.assign(new Error('projects scan requires --root <dir>'), { code: 'ROOT_REQUIRED' });
2515
+ const depth = Number(argValue('--depth') || 4);
2516
+ if (!Number.isInteger(depth) || depth < 0 || depth > 8) throw Object.assign(new Error('--depth must be 0-8'), { code: 'INVALID_DEPTH' });
2517
+ result = projectRegistry.scanProjects(root, { maxDepth: depth });
2518
+ } else throw Object.assign(new Error(`Unknown projects action: ${action}`), { code: 'UNKNOWN_ACTION' });
2519
+ if (json) console.log(JSON.stringify({ ok: true, action, ...result }));
2520
+ else if (action === 'list') {
2521
+ if (!result.projects.length) console.log('No registered projects. They are added by init/run/status/refresh, or `projects add|scan`.');
2522
+ for (const p of result.projects) {
2523
+ const held = currentRunSafe(p.path);
2524
+ const info = held ? require('../lib/run-abandon.js').staleRunInfo(held) : { stale: false };
2525
+ const tag = info.stale ? `; held by stale run ${held.runId} (${held.state}, ${info.idleDays}d): run --abandon there` : '';
2526
+ console.log(`- ${p.path} (context ${p.contextVersion || '?'}, seen ${p.lastSeen}${tag})`);
2527
+ }
2528
+ } else console.log(JSON.stringify(result, null, 2));
2529
+ } catch (err) {
2530
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'PROJECTS_FAILED', error: err.message }));
2531
+ else log.error(err.message);
2532
+ process.exit(1);
2533
+ }
2534
+ }
2535
+
2536
+ // First-run question (TTY only, once). Non-interactive sessions stay on
2537
+ // `notify` until the user picks a policy with `update policy`.
2538
+ function askAutoUpdatePolicyOnce() {
2539
+ try {
2540
+ if (!process.stdin.isTTY || !process.stdout.isTTY || !autoUpdate.autoUpdateAllowedHere()) return;
2541
+ if (autoUpdate.resolvePolicy().source !== 'unset') return;
2542
+ process.stdout.write(`Auto-update ai-engineering-loop? [off/notify/patch/minor/all] (default ${autoUpdate.DEFAULT_POLICY}; majors are always notice-only): `);
2543
+ const buffer = Buffer.alloc(64);
2544
+ const bytes = fs.readSync(0, buffer, 0, buffer.length, null);
2545
+ const answer = buffer.toString('utf8', 0, bytes).trim().toLowerCase() || autoUpdate.DEFAULT_POLICY;
2546
+ autoUpdate.setPolicy({ policy: autoUpdate.POLICIES.includes(answer) ? answer : autoUpdate.DEFAULT_POLICY });
2547
+ } catch {
2548
+ // Never block init on the prompt.
2549
+ }
2550
+ }
2551
+
1721
2552
  function handleUpdate() {
1722
2553
  const action = process.argv[3] || 'check';
2554
+ if (action === 'auto') return handleUpdateAuto();
2555
+ if (action === 'policy') return handleUpdatePolicy();
2556
+ if (action === 'rollback') return handleUpdateRollback();
1723
2557
  const json = process.argv.includes('--json');
1724
2558
  const yes = process.argv.includes('--yes');
1725
2559
  try {
@@ -1759,6 +2593,28 @@ function handleUpdate() {
1759
2593
  }
1760
2594
  }
1761
2595
 
2596
+ // `migrate --from <old>`: idempotent major migrations for home and every
2597
+ // registered project (plus this one when it has .ai-engineering-loop/).
2598
+ function handleMigrate() {
2599
+ const json = process.argv.includes('--json');
2600
+ try {
2601
+ const from = argValue('--from');
2602
+ if (!from) throw Object.assign(new Error('migrate requires --from <old-version>'), { code: 'FROM_REQUIRED' });
2603
+ const migrations = require('../lib/migrations.js');
2604
+ const projects = projectRegistry.listProjects().projects.map((p) => p.path);
2605
+ const here = path.resolve(CWD);
2606
+ if (fs.existsSync(path.join(here, '.ai-engineering-loop')) && !projects.includes(here)) projects.push(here);
2607
+ const report = migrations.runMigrations({ from, to: VERSION, projects, dryRun: process.argv.includes('--dry-run') });
2608
+ if (json) console.log(JSON.stringify({ ok: true, ...report }));
2609
+ else if (!report.migrations.length) console.log(`No migrations between ${from} and ${VERSION}.`);
2610
+ else for (const step of report.migrations) console.log(`- v${step.major}: ${step.description} (home ${step.home}, ${step.projects.length} project(s))`);
2611
+ } catch (err) {
2612
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'MIGRATE_FAILED', error: err.message }));
2613
+ else log.error(err.message);
2614
+ process.exit(1);
2615
+ }
2616
+ }
2617
+
1762
2618
  function handleRecipe() {
1763
2619
  const action = process.argv[3] || 'list';
1764
2620
  const id = process.argv[4];
@@ -2034,9 +2890,14 @@ function handleGoal() {
2034
2890
  message: `Goal draft revision ${result.metadata.revision} is ready for review`
2035
2891
  });
2036
2892
  } else if (action === 'freeze') {
2037
- const expectedHash = argValue('--hash');
2893
+ const latest = process.argv.includes('--latest');
2894
+ const latestDraft = latest ? loadGoalDraft(CWD, runId) : null;
2895
+ if (latest && !latestDraft) {
2896
+ throw Object.assign(new Error('No Goal draft to freeze'), { code: 'GOAL_DRAFT_MISSING' });
2897
+ }
2898
+ const expectedHash = latest ? latestDraft.metadata.contentHash : argValue('--hash');
2038
2899
  if (!expectedHash) {
2039
- const error = new Error('--hash is required');
2900
+ const error = new Error('--hash is required (or --latest)');
2040
2901
  error.code = 'INVALID_USAGE';
2041
2902
  throw error;
2042
2903
  }
@@ -2058,7 +2919,7 @@ function handleGoal() {
2058
2919
  }
2059
2920
  result = freezeGoal(CWD, runId, {
2060
2921
  actor: argValue('--by') || 'human',
2061
- expectedRevision: requiredIntegerArg('--revision'),
2922
+ expectedRevision: latest ? latestDraft.metadata.revision : requiredIntegerArg('--revision'),
2062
2923
  expectedHash
2063
2924
  });
2064
2925
  appendRunLifecycle(CWD, runId, {
@@ -2193,9 +3054,247 @@ function handleInteraction() {
2193
3054
  }
2194
3055
  }
2195
3056
 
3057
+
3058
+ // ---------------------------------------------------------------------------
3059
+ // Combined stage commands (issue #34). Each replaces several agent turns with
3060
+ // one CLI call and goes through the same gates, so results are identical to
3061
+ // the long form (`verification record`... `gate verification`, etc.).
3062
+
3063
+ function autoHeartbeat(runId, phase, message) {
3064
+ try {
3065
+ appendRunLifecycle(CWD, runId, { type: 'AGENT_HEARTBEAT', phase, actor: 'agent', message });
3066
+ } catch (e) {
3067
+ // Heartbeats are best-effort Studio telemetry; never fail a stage on them.
3068
+ }
3069
+ }
3070
+
3071
+ function defaultVerificationCommand() {
3072
+ const text = readFileSafe(path.join(CONTEXT_DIR, 'verification.md')) || '';
3073
+ const match = text.match(/\*\*test_unit\*\*:\s*`([^`]+)`/);
3074
+ return match ? match[1].trim() : null;
3075
+ }
3076
+
3077
+ function splitCommand(text, shell) {
3078
+ const value = String(text || '').trim();
3079
+ if (!value) throw Object.assign(new Error('Empty verification command'), { code: 'INVALID_COMMAND' });
3080
+ if (shell) return { command: value, args: [], shell: true };
3081
+ if (/[|&;<>()$`"'\\*?]/.test(value)) {
3082
+ throw Object.assign(new Error(`"${value}" needs shell syntax; pass --shell or split it into separate --cmd values.`), { code: 'INVALID_COMMAND' });
3083
+ }
3084
+ const [command, ...rest] = value.split(/\s+/);
3085
+ return { command, args: rest, shell: false };
3086
+ }
3087
+
3088
+ function stageJsonError(err, json, code) {
3089
+ if (json) {
3090
+ console.log(JSON.stringify({ ok: false, code: err.code || code, error: err.message, details: err.details || [] }));
3091
+ } else {
3092
+ log.error(err.message);
3093
+ for (const detail of err.details || []) console.error(`- ${detail}`);
3094
+ }
3095
+ process.exit(1);
3096
+ }
3097
+
3098
+ function repeatedArg(name) {
3099
+ const values = [];
3100
+ const separator = process.argv.indexOf('--');
3101
+ const scoped = separator === -1 ? process.argv : process.argv.slice(0, separator);
3102
+ for (let index = 0; index < scoped.length; index += 1) {
3103
+ if (scoped[index] === name && scoped[index + 1] != null) values.push(scoped[index + 1]);
3104
+ }
3105
+ return values;
3106
+ }
3107
+
3108
+ async function handleVerify() {
3109
+ const json = process.argv.includes('--json');
3110
+ try {
3111
+ const runId = requiredRunId('verify');
3112
+ const shell = process.argv.includes('--shell');
3113
+ let texts = repeatedArg('--cmd');
3114
+ if (texts.length === 0) {
3115
+ const fallback = defaultVerificationCommand();
3116
+ if (!fallback) throw Object.assign(new Error('No --cmd given and no test_unit command in .ai-engineering-loop/verification.md'), { code: 'INVALID_COMMAND' });
3117
+ texts = [fallback];
3118
+ }
3119
+ const timeoutValue = argValue('--timeout-ms');
3120
+ const recorded = await recordVerificationCommands(CWD, {
3121
+ runId,
3122
+ commands: texts.map((text) => splitCommand(text, shell)),
3123
+ serial: process.argv.includes('--serial'),
3124
+ ...(timeoutValue == null ? {} : { timeoutMs: parsePositiveIntegerArg('--timeout-ms', timeoutValue) })
3125
+ });
3126
+ const commands = recorded.commands.map((c) => ({ command: c.command, exitCode: c.exitCode, timeoutStatus: c.timeoutStatus }));
3127
+ if (!recorded.passed) {
3128
+ autoHeartbeat(runId, 'verification', 'Verification failed; Maker must fix before review');
3129
+ const result = { ok: false, code: 'VERIFICATION_FAILED', runId, commands, gate: null };
3130
+ if (json) console.log(JSON.stringify(result));
3131
+ else {
3132
+ log.error('Verification failed; the gate was not attempted.');
3133
+ for (const c of commands) console.log(`- ${c.command}: exit ${c.exitCode} (${c.timeoutStatus})`);
3134
+ }
3135
+ process.exitCode = 1;
3136
+ return;
3137
+ }
3138
+ const run = executeGate('verification', runId);
3139
+ const compact = compactRun(CWD, { runId });
3140
+ let claimed = { path: '.ai-engineering-loop/tasks/claimed-vs-reality.md', created: false };
3141
+ try {
3142
+ claimed = { ...createClaimedVsRealityTemplate(CWD, { runId }), created: true };
3143
+ } catch (err) {
3144
+ if (err.code !== 'OUTPUT_EXISTS') throw err;
3145
+ }
3146
+ const result = {
3147
+ ok: true,
3148
+ runId,
3149
+ state: run.state,
3150
+ tier: run.tier ? run.tier.current : null,
3151
+ commands,
3152
+ testCounts: recorded.summary.testCounts,
3153
+ compact: compact.paths,
3154
+ claimedVsReality: claimed,
3155
+ next: run.tier && run.tier.current === 'T0'
3156
+ ? 'Fill claimed-vs-reality, then gate review and gate judge'
3157
+ : 'Fill claimed-vs-reality, then review-pack and spawn the Devil\'s Advocate'
3158
+ };
3159
+ if (json) console.log(JSON.stringify(result));
3160
+ else {
3161
+ log.success('✓ verification recorded and gated');
3162
+ for (const c of commands) console.log(`- ${c.command}: exit ${c.exitCode}`);
3163
+ console.log(`- State: ${run.state}`);
3164
+ console.log(`- Claimed-vs-reality: ${claimed.path}${claimed.created ? ' (scaffolded; fill it from the command output)' : ''}`);
3165
+ console.log(`- Next: ${result.next}`);
3166
+ }
3167
+ } catch (err) {
3168
+ stageJsonError(err, json, 'VERIFY_FAILED');
3169
+ }
3170
+ }
3171
+
3172
+ function handleReviewPack() {
3173
+ const json = process.argv.includes('--json');
3174
+ try {
3175
+ const runId = requiredRunId('review-pack');
3176
+ const run = loadRun(CWD, runId);
3177
+ if (!run.artifacts?.verification) {
3178
+ throw Object.assign(new Error('review-pack needs a passed verification gate (run verify first).'), { code: 'GATE_FAILED' });
3179
+ }
3180
+ const base = argValue('--base') || 'HEAD';
3181
+ const fastPath = assessSmallTaskFastPath(CWD, { base });
3182
+ const pack = smartContextSummary(createDiffHunkPack(CWD, { runId, base, profile: argValue('--profile') }));
3183
+ const escalation = assessRunEscalation(CWD, { runId });
3184
+ const tier = run.tier ? run.tier.current : null;
3185
+ autoHeartbeat(runId, 'review', 'Review pack built');
3186
+ const result = {
3187
+ ok: true,
3188
+ runId,
3189
+ tier,
3190
+ devilAdvocateRequired: tier !== 'T0',
3191
+ packPath: pack.path,
3192
+ diffPath: path.relative(CWD, path.join(runsDir(CWD), runId, 'diff.patch')).split(path.sep).join('/'),
3193
+ reviewProfile: pack.reviewProfile,
3194
+ estimatedTokens: pack.estimatedTokens,
3195
+ truncated: pack.truncated,
3196
+ unresolvedFindings: pack.unresolvedFindings,
3197
+ fastPath: { eligible: fastPath.eligible, reasons: fastPath.reasons },
3198
+ escalation: { requiredTier: escalation.requiredTier, reasons: escalation.reasons.map((r) => r.code) }
3199
+ };
3200
+ if (json) console.log(JSON.stringify(result));
3201
+ else {
3202
+ log.success('✓ review pack ready');
3203
+ console.log(`- Pack: ${result.packPath} (${result.reviewProfile}, ~${result.estimatedTokens} tokens)`);
3204
+ console.log(`- Tier: ${tier || 'none'}; Devil's Advocate ${result.devilAdvocateRequired ? 'required' : 'not used (T0)'}`);
3205
+ console.log(`- Judge tier floor: ${result.escalation.requiredTier}${result.escalation.reasons.length ? ` (${result.escalation.reasons.join(', ')})` : ''}`);
3206
+ }
3207
+ } catch (err) {
3208
+ stageJsonError(err, json, 'REVIEW_PACK_FAILED');
3209
+ }
3210
+ }
3211
+
3212
+ function handleDeliver() {
3213
+ const json = process.argv.includes('--json');
3214
+ try {
3215
+ const runId = requiredRunId('deliver');
3216
+ const run = loadRun(CWD, runId);
3217
+ const mode = run.mode || RUN_MODES.ASSISTED;
3218
+ const approve = process.argv.includes('--approve');
3219
+ const by = argValue('--by');
3220
+ if (mode === RUN_MODES.REPORT_ONLY) {
3221
+ throw Object.assign(new Error('REPORT_ONLY runs finish with gate report, not deliver.'), { code: 'INVALID_USAGE' });
3222
+ }
3223
+ if (mode === RUN_MODES.ASSISTED && !approve) {
3224
+ console.error('ASSISTED delivery needs the human\'s explicit approval: deliver --approve --by <name>. Nothing was written.');
3225
+ process.exit(2);
3226
+ }
3227
+ if (approve && !by) {
3228
+ throw Object.assign(new Error('--approve requires --by <name> (the approving human).'), { code: 'INVALID_USAGE' });
3229
+ }
3230
+ const approved = [];
3231
+ if (approve && run.workflow) {
3232
+ const workflow = workflowStatus(CWD, { runId });
3233
+ for (const node of workflow.plan.nodes) {
3234
+ if (node.type !== 'approval' || workflow.state.nodes[node.id].status !== 'READY') continue;
3235
+ approveWorkflowNode(CWD, node.id, { runId, approvedBy: by });
3236
+ appendRunLifecycle(CWD, runId, { type: 'NODE_COMPLETED', nodeId: node.id, phase: node.id, actor: by, message: `Node ${node.id} approved` });
3237
+ approved.push(node.id);
3238
+ }
3239
+ }
3240
+ const deliveryPath = path.join(runsDir(CWD), runId, 'delivery.json');
3241
+ let delivery = null;
3242
+ if (fs.existsSync(deliveryPath)) {
3243
+ try { delivery = JSON.parse(fs.readFileSync(deliveryPath, 'utf8')); } catch (e) { delivery = null; }
3244
+ }
3245
+ const destination = argValue('--destination');
3246
+ const summary = argValue('--summary');
3247
+ if (!delivery && !(destination && summary)) {
3248
+ throw Object.assign(new Error('Pass --destination <where> and --summary <text>, or write delivery.json first.'), { code: 'INVALID_USAGE' });
3249
+ }
3250
+ delivery = {
3251
+ ...(delivery || {}),
3252
+ schemaVersion: 1,
3253
+ runId,
3254
+ ...(destination ? { destination } : {}),
3255
+ ...(summary ? { summary } : {}),
3256
+ ...(approve ? { humanApproved: true, approvedBy: by } : {})
3257
+ };
3258
+ fs.writeFileSync(deliveryPath, `${JSON.stringify(delivery, null, 2)}\n`, { mode: 0o600 });
3259
+ const next = executeGate('delivery', runId);
3260
+ const result = { ok: true, runId, state: next.state, approvedNodes: approved, humanApproved: delivery.humanApproved === true };
3261
+ if (json) console.log(JSON.stringify(result));
3262
+ else {
3263
+ log.success('✓ delivery gate passed');
3264
+ console.log(`- State: ${next.state}`);
3265
+ if (approved.length) console.log(`- Approved: ${approved.join(', ')} by ${by}`);
3266
+ }
3267
+ } catch (err) {
3268
+ stageJsonError(err, json, 'DELIVER_FAILED');
3269
+ }
3270
+ }
3271
+
3272
+ // Command: docs (read-only packaged specs)
3273
+ function handleDocs() {
3274
+ const json = process.argv.includes('--json');
3275
+ const target = process.argv[3] && !process.argv[3].startsWith('--') ? process.argv[3] : 'list';
3276
+ if (target === 'list') {
3277
+ const docs = listDocs();
3278
+ if (json) {
3279
+ console.log(JSON.stringify({ ok: true, docs }, null, 2));
3280
+ return;
3281
+ }
3282
+ for (const doc of docs) console.log(`${doc.name.padEnd(44)} ${String(doc.bytes).padStart(6)} B ${doc.rel}`);
3283
+ return;
3284
+ }
3285
+ try {
3286
+ const doc = readDoc(target, { section: argValue('--section') });
3287
+ if (json) console.log(JSON.stringify({ ok: true, ...doc }, null, 2));
3288
+ else process.stdout.write(`${doc.text}\n`);
3289
+ } catch (err) {
3290
+ log.error(`${err.code || 'DOCS_FAILED'}: ${err.message}`);
3291
+ process.exitCode = 1;
3292
+ }
3293
+ }
3294
+
2196
3295
  // Help Menu
2197
- function printHelp() {
2198
- console.log(`
3296
+ function helpText() {
3297
+ return (`
2199
3298
  AI Engineering Loop CLI (v${VERSION})
2200
3299
  A reusable, framework-agnostic AI Engineering Operating System.
2201
3300
 
@@ -2205,15 +3304,21 @@ Usage:
2205
3304
  Commands:
2206
3305
  init Bootstrap .ai-engineering-loop/ context from repository discovery
2207
3306
  status Check the validity, readiness, and baseline freshness of context
3307
+ --json print context and host-skill freshness as JSON (no writes)
2208
3308
  refresh Reconcile drifted context against repository non-destructively
2209
- run [task] Start or resume a stateful engineering run, sync hosts, and instruct the agent
3309
+ run [task] Start or resume a stateful engineering run and instruct the agent (never writes to home)
2210
3310
  --new start a new run even when another run is active
2211
3311
  --mode report-only|assisted|unattended
2212
3312
  --recipe <id> bind an immutable compiled workflow plan
3313
+ --tier T0|T1|T2 --tier-reason <text> override the automatic tier (recorded)
3314
+ --json print runId, tier, tier reasons, and subagent count only
3315
+ --abandon [--run <id>] --reason <text> --by <name> [--yes] [--json]
3316
+ close a stale run as CANCELLED (kept on disk) and release current.json;
3317
+ ASSISTED asks to confirm, UNATTENDED needs --yes from a human
2213
3318
  state Inspect the current run ledger
2214
3319
  --run <id> target a non-current run
2215
3320
  --json print the complete machine-readable ledger
2216
- gate <name> Validate an artifact and advance the current run
3321
+ gate <name> Validate an artifact and advance the current run (maker: --from-git writes diff.patch first)
2217
3322
  goal | report | maker | verification | review | judge | delivery
2218
3323
  --run <id> target a non-current run
2219
3324
  --json print machine-readable gate output
@@ -2221,6 +3326,7 @@ Commands:
2221
3326
  show [--run <id>]
2222
3327
  draft --file <json> --revision <n> [--run <id>] [--by <agent>]
2223
3328
  freeze --revision <n> --hash <sha256> [--run <id>] [--by <name>]
3329
+ freeze --latest [--run <id>] --by <name> freeze the newest draft (CLI resolves revision/hash)
2224
3330
  verification Summarize verification.json for compact Judge context
2225
3331
  summarize [--run <id>] [--json]
2226
3332
  record [--run <id>] [--timeout-ms <n>] [--shell] [--json] -- <executable> [args...]
@@ -2255,6 +3361,8 @@ Commands:
2255
3361
  budget Enforce actual provider-reported token usage and emergency pause
2256
3362
  status [--run <id>] [--node <id>] [--estimate <n>] [--json]
2257
3363
  record --input <n> --output <n> --model <id> [--run <id>] [--node <id>]
3364
+ record --unavailable [--run <id>] [--node <id>]
3365
+ host exposed no usage: ASSISTED notes it and continues; UNATTENDED fails
2258
3366
  pause | resume
2259
3367
  sandbox Isolate Maker changes in a locked disposable Git worktree
2260
3368
  create | capture | abort | status [--run <id>] [--json]
@@ -2275,18 +3383,37 @@ Commands:
2275
3383
  --limit <n> bound query/related result count
2276
3384
  --include-ignored include CSS, generated, lockfile, and .aelcontextignore paths
2277
3385
  --json print only pack metadata; never print packed content
2278
- eval Validate the 20-case production evaluation catalog
3386
+ eval Validate the 24-case production evaluation catalog
2279
3387
  --results <dir> score host-generated JSON results
2280
3388
  --cases <dir> use another compatible fixture catalog
2281
3389
  --json print machine-readable metrics
2282
3390
  escalation Compute the minimum Judge model tier from deterministic risk signals
2283
3391
  --run <id> target a non-current run
2284
3392
  --json print machine-readable reasons
3393
+ verify Record verification commands, gate them, compact, and scaffold claimed-vs-reality
3394
+ [--run <id>] [--cmd "<command>"]... [--shell] [--serial] [--timeout-ms <n>] [--json]
3395
+ default command: test_unit from .ai-engineering-loop/verification.md; commands run in parallel
3396
+ review-pack Build the Devil's Advocate pack: fast-path, diff hunks, escalation floor, tier
3397
+ [--run <id>] [--base <git-ref>] [--profile lean|standard|thorough] [--json]
3398
+ deliver Approve READY approval nodes, write delivery.json, and pass the delivery gate
3399
+ [--run <id>] [--destination <where> --summary <text>] [--approve --by <name>] [--json]
3400
+ ASSISTED requires --approve --by <name>, given only after explicit human approval
3401
+ docs Print a packaged spec without needing the package source tree
3402
+ list [--json]
3403
+ <name> [--section <heading>] [--json] e.g. docs grill-policy --section "When to grill"
2285
3404
  doctor Check runtime, schemas, host assets, package contents, and eval catalog
2286
3405
  --json print machine-readable diagnostics
2287
3406
  update Check or apply the package update workflow
2288
3407
  check|plan [--json]
2289
3408
  apply --yes
3409
+ policy [off|notify|patch|minor|all] [--channel latest|next] [--pin 1.13.x|--no-pin]
3410
+ auto [--force] [--json] check (cached 24 h) and apply per policy; majors notice-only
3411
+ rollback --yes reinstall the previous version, re-sync hosts, restore legacy snapshots
3412
+ migrate Run major-version migrations (migrations/<major>.js); update apply calls it across a major
3413
+ --from <old-version> [--dry-run] [--json]
3414
+ projects Registry of local projects with .ai-engineering-loop/ (~/.ai-engineering-loop/projects.json)
3415
+ list|add [dir]|remove [dir] [--json]
3416
+ scan --root <dir> [--depth 4]
2290
3417
  recipe Inspect and compile declarative workflow recipes (does not execute nodes)
2291
3418
  list [--json]
2292
3419
  catalog [--json]
@@ -2304,9 +3431,19 @@ Commands:
2304
3431
  create [--run <id>] [--audience developer|agent|auditor]
2305
3432
  [--output <repository-relative-file>|-] [--json]
2306
3433
  inspect | brief <repository-relative-file> [--json]
2307
- sync-hosts Copy package skills/agents/commands into ~/.claude ~/.grok ~/.gemini ~/.agents
3434
+ setup One-time: detect AI agents (config folder or PATH binary, never run) and install for them
3435
+ --yes skip the prompt --hosts <id,...> pick hosts --json
3436
+ --mode auto|manual (prompt suggests auto; --yes / no TTY default to manual)
3437
+ Without a TTY and without --yes it only prints the plan
3438
+ hosts Show or change which AI agent hosts get the loop
3439
+ list [--json] | doctor [--json] | enable <id...> | disable <id...> (removes unedited AEL files)
3440
+ sync-hosts Install the loop skill and reviewer agents into every detected AI agent host
2308
3441
  (only hosts that already exist; DOT skills only if already installed)
2309
- --dry-run print the plan without writing
3442
+ --dry-run print the plan without writing
3443
+ --pack <list> core (always), backend, design, quality; saved for later syncs
3444
+ --prune remove unmodified files of packs that are not selected
3445
+ --json print machine-readable results
3446
+ User-edited host files are backed up to <file>.ael-backup before overwrite
2310
3447
  generate-adapter Print detected forge and grill protocol for Stage 8
2311
3448
  --type standard|github|gitlab|dot write .ai-engineering-loop/adapter.md (skip grill)
2312
3449
  generate-workflow Print grill protocol for a loop overlay (hooks + intern + lessons.md)
@@ -2321,14 +3458,51 @@ Documentation:
2321
3458
  `);
2322
3459
  }
2323
3460
 
3461
+ function printHelp() {
3462
+ console.log(helpText());
3463
+ }
3464
+
2324
3465
  // CLI Router
2325
3466
  const args = process.argv.slice(2);
2326
3467
  const command = args[0] || 'init';
2327
3468
 
3469
+ // Side-effect guard (issue #25): help never executes a command, and writer
3470
+ // commands reject unknown flags before touching any file.
3471
+ if (!['-h', '--help', '-v', '--version'].includes(command)) {
3472
+ const checked = effectiveCommand(command, args.slice(1));
3473
+ if (wantsCommandHelp(checked, args.slice(1))) {
3474
+ const block = commandHelp(helpText(), command);
3475
+ console.log(block
3476
+ ? `Usage: npx ai-engineering-loop ${block.trim()}`
3477
+ : helpText());
3478
+ process.exit(0);
3479
+ }
3480
+ const unknown = unknownWriterArgs(checked, args.slice(1));
3481
+ if (unknown.length > 0) {
3482
+ log.error(`Unknown argument(s) for "${command}": ${unknown.join(' ')}. Nothing was written.`);
3483
+ console.log(`Run "npx ai-engineering-loop ${command} --help" for usage.`);
3484
+ process.exit(2);
3485
+ }
3486
+ }
3487
+
3488
+ // Registry + auto-update hooks (issue #37). Registration runs at exit so a
3489
+ // fresh `init` is recorded too.
3490
+ if (['init', 'run', 'status', 'refresh'].includes(command)) {
3491
+ process.once('exit', () => projectRegistry.registerProject(CWD));
3492
+ if (command === 'init') askAutoUpdatePolicyOnce();
3493
+ maybeAutoUpdate();
3494
+ }
3495
+
3496
+ if (!['setup', 'hosts', 'sync-hosts', '-h', '--help', '-v', '--version'].includes(command)) maybeSetupHint();
3497
+ if (command === 'status') maybeNewHostsNotice();
3498
+
2328
3499
  switch (command) {
2329
3500
  case 'init':
2330
3501
  handleInit();
2331
3502
  break;
3503
+ case 'projects':
3504
+ handleProjects();
3505
+ break;
2332
3506
  case 'status':
2333
3507
  handleStatus();
2334
3508
  break;
@@ -2383,12 +3557,27 @@ switch (command) {
2383
3557
  case 'escalation':
2384
3558
  handleEscalation();
2385
3559
  break;
3560
+ case 'docs':
3561
+ handleDocs();
3562
+ break;
3563
+ case 'verify':
3564
+ handleVerify();
3565
+ break;
3566
+ case 'review-pack':
3567
+ handleReviewPack();
3568
+ break;
3569
+ case 'deliver':
3570
+ handleDeliver();
3571
+ break;
2386
3572
  case 'doctor':
2387
3573
  handleDoctor();
2388
3574
  break;
2389
3575
  case 'update':
2390
3576
  handleUpdate();
2391
3577
  break;
3578
+ case 'migrate':
3579
+ handleMigrate();
3580
+ break;
2392
3581
  case 'recipe':
2393
3582
  handleRecipe();
2394
3583
  break;
@@ -2401,6 +3590,12 @@ switch (command) {
2401
3590
  case 'sync-hosts':
2402
3591
  handleSyncHosts();
2403
3592
  break;
3593
+ case 'hosts':
3594
+ handleHosts();
3595
+ break;
3596
+ case 'setup':
3597
+ handleSetup();
3598
+ break;
2404
3599
  case 'generate-adapter':
2405
3600
  handleGenerateAdapter();
2406
3601
  break;