ai-engineering-loop 1.13.0 → 1.14.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 (60) hide show
  1. package/.agents/workflows/ai-engineering-loop.md +47 -11
  2. package/.claude/commands/ai-engineering-loop.md +1 -1
  3. package/.claude/skills/ai-engineering-loop/SKILL.md +26 -44
  4. package/.claude/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  5. package/.claude/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  6. package/.claude/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  7. package/.claude/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  8. package/.claude/skills/ai-engineering-loop/references/loop-review.md +18 -0
  9. package/.claude/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  10. package/.claude/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  11. package/.gemini/skills/ai-engineering-loop/SKILL.md +24 -37
  12. package/.gemini/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  13. package/.gemini/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  14. package/.gemini/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  15. package/.gemini/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  16. package/.gemini/skills/ai-engineering-loop/references/loop-review.md +18 -0
  17. package/.gemini/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  18. package/.gemini/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  19. package/.grok/skills/ai-engineering-loop/SKILL.md +29 -61
  20. package/.grok/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  21. package/.grok/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  22. package/.grok/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  23. package/.grok/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  24. package/.grok/skills/ai-engineering-loop/references/loop-review.md +18 -0
  25. package/.grok/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  26. package/.grok/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  27. package/CHANGELOG.md +69 -0
  28. package/README.md +40 -1
  29. package/README.npm.md +6 -2
  30. package/THIRD_PARTY_NOTICES.md +29 -0
  31. package/adapters/dot/skills/dot-dev-skill-router/SKILL.md +24 -16
  32. package/adapters/project-onboarding/SKILL.md +27 -0
  33. package/adapters/project-onboarding/references/output.md +29 -0
  34. package/adapters/quality/skills/ael-code-simplifier/SKILL.md +43 -0
  35. package/adapters/quality/skills/ael-receiving-code-review/SKILL.md +37 -0
  36. package/bin/ai-engineering-loop.js +979 -69
  37. package/core/root-cause-analysis.md +6 -0
  38. package/core/runtime-safety.md +30 -3
  39. package/evals/cases/21-tier-t0-docs.json +34 -0
  40. package/evals/cases/22-tier-t1-small-pass.json +30 -0
  41. package/evals/cases/23-tier-t1-blocker.json +26 -0
  42. package/evals/cases/24-tier-t1-auth-escalates.json +30 -0
  43. package/lib/auto-update.js +486 -0
  44. package/lib/budget.js +31 -1
  45. package/lib/cli-args.js +84 -0
  46. package/lib/docs.js +91 -0
  47. package/lib/doctor.js +7 -1
  48. package/lib/gates.js +114 -1
  49. package/lib/host-skill-build.js +121 -0
  50. package/lib/migrations.js +84 -0
  51. package/lib/project-registry.js +148 -0
  52. package/lib/run-state.js +6 -3
  53. package/lib/sync-hosts.js +325 -42
  54. package/lib/tier.js +134 -0
  55. package/lib/update-manager.js +17 -1
  56. package/lib/update-notice.js +192 -0
  57. package/lib/user-state.js +80 -0
  58. package/lib/verification-recorder.js +44 -0
  59. package/migrations/README.md +21 -0
  60. package/package.json +7 -2
@@ -17,9 +17,15 @@ const { execSync, spawn } = require('child_process');
17
17
  const {
18
18
  homeDir,
19
19
  applyHostSync,
20
- planHostSync,
20
+ hostSkillStatus,
21
21
  formatHostSyncReport
22
22
  } = require('../lib/sync-hosts.js');
23
+ const { listDocs, readDoc } = require('../lib/docs.js');
24
+ const {
25
+ wantsCommandHelp,
26
+ unknownWriterArgs,
27
+ commandHelp
28
+ } = require('../lib/cli-args.js');
23
29
  const {
24
30
  detectAdapterHints,
25
31
  writeShippedAdapter,
@@ -51,8 +57,10 @@ const {
51
57
  updatePolicy
52
58
  } = require('../lib/runtime-policy.js');
53
59
  const {
54
- applyGate
60
+ applyGate,
61
+ judgeRequirement
55
62
  } = require('../lib/gates.js');
63
+ const { initialTierState } = require('../lib/tier.js');
56
64
  const {
57
65
  createContextPack,
58
66
  contextPackSummary
@@ -82,6 +90,7 @@ const {
82
90
  writeVerificationSummary
83
91
  } = require('../lib/verification-summary.js');
84
92
  const {
93
+ recordVerificationCommands,
85
94
  recordVerificationCommand
86
95
  } = require('../lib/verification-recorder.js');
87
96
  const {
@@ -96,12 +105,16 @@ const {
96
105
  } = require('../lib/doctor.js');
97
106
  const {
98
107
  checkForUpdate,
108
+ detectInstallScope,
99
109
  executeUpdatePlan
100
110
  } = require('../lib/update-manager.js');
111
+ const autoUpdate = require('../lib/auto-update.js');
112
+ const projectRegistry = require('../lib/project-registry.js');
101
113
  const {
102
114
  assertBudgetAvailable,
103
115
  budgetStatus,
104
116
  recordTokenUsage,
117
+ recordUsageUnavailable,
105
118
  setKillSwitch
106
119
  } = require('../lib/budget.js');
107
120
  const {
@@ -179,15 +192,150 @@ const REQUIRED_FILES = [
179
192
  'adrs/README.md'
180
193
  ];
181
194
 
195
+ // Non-destructive mode (issue #37, `refresh --non-destructive`): a context file
196
+ // is overwritten only if it still matches what AEL last generated (hash in
197
+ // .ael-generated.json) or is package-owned; otherwise the new template goes to
198
+ // `<file>.ael-new` and the user's file is left alone.
199
+ // Legacy projects (no .ael-generated.json yet, decision 5 on #37): the first
200
+ // such refresh overwrites AEL-managed files directly and deletes obsolete
201
+ // AEL-managed files, after copying the old content into a snapshot under
202
+ // .ai-engineering-loop/.ael-backup/<timestamp>/. Hashes are recorded so later
203
+ // refreshes use the normal flow. Only paths this writer generates (or lists in
204
+ // OBSOLETE_CONTEXT_FILES) are touched; files written with overwrite:false
205
+ // (lessons, glossary, ...) and every other user file are left alone.
206
+ let CONTEXT_WRITE_SAFE = false;
207
+ let CONTEXT_WRITE_LEGACY = null; // { root, snapshotDir } during a legacy refresh
208
+ const CONTEXT_WRITE_REPORT = { updated: [], aelNew: [], kept: [], seen: new Set(), snapshot: [], removed: [], obsoleteKept: [] };
209
+ const PACKAGE_OWNED_CONTEXT = new Set(['metadata.json']);
210
+ // Context files older AEL versions generated and this one no longer does
211
+ // (relative to .ai-engineering-loop/). Deleted on the first legacy refresh.
212
+ const OBSOLETE_CONTEXT_FILES = Object.freeze([]);
213
+ const GENERATED_HASHES_FILE = '.ael-generated.json';
214
+
215
+ function generatedHashesPath(filePath) {
216
+ return path.join(path.dirname(filePath), GENERATED_HASHES_FILE);
217
+ }
218
+
219
+ function readGeneratedHashes(filePath) {
220
+ try {
221
+ return JSON.parse(fs.readFileSync(generatedHashesPath(filePath), 'utf8'));
222
+ } catch {
223
+ return {};
224
+ }
225
+ }
226
+
227
+ function writeGeneratedHashes(filePath, hashes) {
228
+ try {
229
+ fs.writeFileSync(generatedHashesPath(filePath), `${JSON.stringify(hashes, null, 2)}\n`);
230
+ } catch {
231
+ // Best effort.
232
+ }
233
+ }
234
+
235
+ function recordGeneratedHash(filePath, content) {
236
+ const hashes = readGeneratedHashes(filePath);
237
+ hashes[path.basename(filePath)] = require('crypto').createHash('sha256').update(content).digest('hex');
238
+ writeGeneratedHashes(filePath, hashes);
239
+ }
240
+
241
+ function sha256Text(content) {
242
+ return require('crypto').createHash('sha256').update(content).digest('hex');
243
+ }
244
+
245
+ function snapshotContextFile(filePath) {
246
+ if (!CONTEXT_WRITE_LEGACY || !fs.existsSync(filePath)) return;
247
+ const rel = path.relative(CONTEXT_WRITE_LEGACY.root, filePath);
248
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return;
249
+ const dest = path.join(CONTEXT_WRITE_LEGACY.snapshotDir, rel);
250
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
251
+ fs.copyFileSync(filePath, dest);
252
+ CONTEXT_WRITE_REPORT.snapshot.push(rel.split(path.sep).join('/'));
253
+ }
254
+
182
255
  function writeContextFile(filePath, content, { overwrite = true } = {}) {
256
+ CONTEXT_WRITE_REPORT.seen.add(path.resolve(filePath));
183
257
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
184
258
  if (!overwrite && fs.existsSync(filePath) && fs.statSync(filePath).size > 0) {
185
259
  return false;
186
260
  }
261
+ const name = path.basename(filePath);
262
+ if (CONTEXT_WRITE_SAFE && fs.existsSync(filePath) && !PACKAGE_OWNED_CONTEXT.has(name)) {
263
+ const current = fs.readFileSync(filePath, 'utf8');
264
+ if (current === content) {
265
+ CONTEXT_WRITE_REPORT.kept.push(name);
266
+ recordGeneratedHash(filePath, content);
267
+ return false;
268
+ }
269
+ if (CONTEXT_WRITE_LEGACY) {
270
+ snapshotContextFile(filePath);
271
+ } else if (readGeneratedHashes(filePath)[name] !== sha256Text(current)) {
272
+ fs.writeFileSync(`${filePath}.ael-new`, content);
273
+ CONTEXT_WRITE_REPORT.aelNew.push(`${name}.ael-new`);
274
+ return false;
275
+ }
276
+ }
187
277
  fs.writeFileSync(filePath, content);
278
+ recordGeneratedHash(filePath, content);
279
+ if (CONTEXT_WRITE_SAFE) CONTEXT_WRITE_REPORT.updated.push(name);
188
280
  return true;
189
281
  }
190
282
 
283
+ // After a non-destructive refresh: remove AEL-managed files this version no
284
+ // longer generates. Normal flow: only files whose recorded hash still matches
285
+ // (edited ones are reported and kept). Legacy flow: OBSOLETE_CONTEXT_FILES,
286
+ // snapshotted first.
287
+ function removeObsoleteContextFiles(contextDir) {
288
+ const root = path.resolve(contextDir);
289
+ const candidates = new Map();
290
+ const hashDirs = [root];
291
+ try {
292
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
293
+ if (entry.isDirectory() && !entry.name.startsWith('.') && fs.existsSync(path.join(root, entry.name, GENERATED_HASHES_FILE))) {
294
+ hashDirs.push(path.join(root, entry.name));
295
+ }
296
+ }
297
+ } catch {
298
+ return;
299
+ }
300
+ for (const dir of hashDirs) {
301
+ const hashes = readGeneratedHashes(path.join(dir, 'x'));
302
+ for (const [name, hash] of Object.entries(hashes)) {
303
+ if (!/^[\w.-]+$/.test(name) || name.startsWith('.')) continue;
304
+ candidates.set(path.join(dir, name), { hash, dir, name });
305
+ }
306
+ }
307
+ if (CONTEXT_WRITE_LEGACY) {
308
+ for (const rel of OBSOLETE_CONTEXT_FILES) {
309
+ const abs = path.resolve(root, rel);
310
+ if (abs.startsWith(root + path.sep)) candidates.set(abs, { hash: null, dir: path.dirname(abs), name: path.basename(abs), legacy: true });
311
+ }
312
+ }
313
+ for (const [abs, info] of candidates) {
314
+ if (CONTEXT_WRITE_REPORT.seen.has(abs)) continue;
315
+ const rel = path.relative(root, abs).split(path.sep).join('/');
316
+ let stat;
317
+ try {
318
+ stat = fs.lstatSync(abs);
319
+ } catch {
320
+ stat = null;
321
+ }
322
+ if (stat && stat.isFile()) {
323
+ if (!info.legacy && sha256Text(fs.readFileSync(abs)) !== info.hash) {
324
+ CONTEXT_WRITE_REPORT.obsoleteKept.push(rel);
325
+ continue;
326
+ }
327
+ snapshotContextFile(abs);
328
+ fs.unlinkSync(abs);
329
+ CONTEXT_WRITE_REPORT.removed.push(rel);
330
+ }
331
+ const hashes = readGeneratedHashes(path.join(info.dir, 'x'));
332
+ if (Object.hasOwn(hashes, info.name)) {
333
+ delete hashes[info.name];
334
+ writeGeneratedHashes(path.join(info.dir, 'x'), hashes);
335
+ }
336
+ }
337
+ }
338
+
191
339
  function ignoreProjectContextOnFirstInit(rootDir) {
192
340
  const filePath = path.join(rootDir, '.gitignore');
193
341
  if (fs.existsSync(filePath) && fs.lstatSync(filePath).isSymbolicLink()) {
@@ -514,6 +662,7 @@ ${discovery.topLevelDirs.map((d) => `- \`${d}/\``).join('\n') || '- Flat directo
514
662
  ${discovery.scripts.e2e ? `- **e2e**: \`${discovery.scripts.e2e}\`` : ''}
515
663
 
516
664
  ## Verification Protocol
665
+ - 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
666
  - 100% deterministic checks must pass before Devil's Advocate review.
518
667
  - Unit tests must cover boundary cases, null safety, and error paths.
519
668
  `;
@@ -738,7 +887,40 @@ function handleInit() {
738
887
  }
739
888
 
740
889
  // Command: status
890
+ function statusJson() {
891
+ const result = {
892
+ ok: false,
893
+ status: 'NOT_INITIALIZED',
894
+ packageVersion: VERSION,
895
+ project: path.basename(CWD),
896
+ hostSkills: hostSkillStatus({ home: homeDir(), version: VERSION })
897
+ };
898
+ if (fs.existsSync(CONTEXT_DIR)) {
899
+ const validation = validateContext(CONTEXT_DIR);
900
+ if (!validation.valid) {
901
+ result.status = 'INCOMPLETE';
902
+ result.reason = validation.reason;
903
+ } else {
904
+ let metadata = {};
905
+ try { metadata = JSON.parse(readFileSafe(path.join(CONTEXT_DIR, 'metadata.json')) || '{}'); } catch (e) {}
906
+ const drift = evaluateDrift(CWD, CONTEXT_DIR);
907
+ result.ok = true;
908
+ result.status = 'READY';
909
+ result.contextVersion = metadata.contextVersion || null;
910
+ result.projectProfile = metadata.projectProfile || null;
911
+ result.freshness = { status: drift.status, reason: drift.reason, level: drift.level || null };
912
+ }
913
+ }
914
+ return result;
915
+ }
916
+
741
917
  function handleStatus() {
918
+ if (command === 'status' && process.argv.includes('--json')) {
919
+ const result = statusJson();
920
+ console.log(JSON.stringify(result, null, 2));
921
+ if (!result.ok) process.exitCode = 1;
922
+ return;
923
+ }
742
924
  log.info('AI Engineering Loop — Project Context Status (status)');
743
925
  log.dim(`Target directory: ${CWD}`);
744
926
 
@@ -768,19 +950,21 @@ function handleStatus() {
768
950
  console.log(`- Living Freshness: \x1b[32m${drift.status}\x1b[0m (${drift.reason})`);
769
951
  console.log(`- Context Files: ${REQUIRED_FILES.length}/${REQUIRED_FILES.length} verified (including metadata.json, glossary.md, adrs/)`);
770
952
 
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.');
953
+ const hosts = hostSkillStatus({ home: homeDir(), version: VERSION });
954
+ if (hosts.stale) {
955
+ log.warn(`- Host skills: STALE (${hosts.staleFiles} file(s) behind package v${VERSION}${hosts.installedVersion ? `, installed v${hosts.installedVersion}` : ''})`);
956
+ log.dim(' Run "npx ai-engineering-loop sync-hosts" (or "update apply --yes" after a package upgrade), then start a new session.');
776
957
  } else {
777
- const hostCurrent = hostPlan.filter((item) => item.action === 'current').length;
778
- console.log(`- Host skills: CURRENT (${hostCurrent} managed file(s) match v${VERSION})`);
958
+ console.log(`- Host skills: CURRENT (${hosts.managedFiles} managed file(s) match v${VERSION}; packs: ${hosts.packs.join(', ')})`);
779
959
  }
780
960
  }
781
961
 
782
962
  // Command: refresh
783
963
  function handleRefresh() {
964
+ if (process.argv.includes('--non-destructive')) {
965
+ handleSafeRefresh();
966
+ return;
967
+ }
784
968
  log.info('AI Engineering Loop — Context Drift Refresh (refresh)');
785
969
  log.dim(`Target directory: ${CWD}`);
786
970
 
@@ -813,17 +997,36 @@ function handleRefresh() {
813
997
  handleStatus();
814
998
  }
815
999
 
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
1000
  function handleSyncHosts() {
824
1001
  const dryRun = process.argv.includes('--dry-run');
1002
+ const prune = process.argv.includes('--prune');
1003
+ const json = process.argv.includes('--json');
1004
+ const packArg = argValue('--pack');
1005
+ let results;
1006
+ try {
1007
+ results = applyHostSync({
1008
+ home: homeDir(),
1009
+ dryRun,
1010
+ prune,
1011
+ packs: packArg == null ? null : packArg,
1012
+ version: VERSION
1013
+ });
1014
+ } catch (err) {
1015
+ log.error(`${err.code || 'SYNC_FAILED'}: ${err.message}`);
1016
+ process.exit(2);
1017
+ }
1018
+ if (json) {
1019
+ console.log(JSON.stringify({
1020
+ ok: true,
1021
+ version: VERSION,
1022
+ dryRun,
1023
+ packs: results.packs,
1024
+ packSource: results.packSource,
1025
+ files: results.map(({ content, ...item }) => item)
1026
+ }, null, 2));
1027
+ return;
1028
+ }
825
1029
  log.info(`AI Engineering Loop — Sync host skills (sync-hosts)${dryRun ? ' [dry-run]' : ''}`);
826
- const results = applyHostSync({ home: homeDir(), dryRun });
827
1030
  console.log(formatHostSyncReport(results, { version: VERSION, dryRun }));
828
1031
  }
829
1032
 
@@ -869,8 +1072,23 @@ function detectGrokHost() {
869
1072
  }
870
1073
  }
871
1074
 
1075
+ function workingTreePaths(rootDir) {
1076
+ try {
1077
+ return execSync('git status --porcelain --untracked-files=all', { cwd: rootDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
1078
+ .split('\n')
1079
+ .map((line) => line.slice(3).trim())
1080
+ .filter((line) => line && !line.startsWith('.ai-engineering-loop/'))
1081
+ .map((line) => line.includes(' -> ') ? line.split(' -> ').pop() : line);
1082
+ } catch (e) {
1083
+ return [];
1084
+ }
1085
+ }
1086
+
872
1087
  // Command: run
873
1088
  function handleRun() {
1089
+ const runJson = process.argv.includes('--json');
1090
+ const realLog = console.log;
1091
+ if (runJson) console.log = () => {};
874
1092
  log.info('AI Engineering Loop — Task Execution Entrypoint (run)');
875
1093
 
876
1094
  if (!fs.existsSync(CONTEXT_DIR)) {
@@ -880,20 +1098,16 @@ function handleRun() {
880
1098
  handleStatus();
881
1099
  }
882
1100
 
883
- syncHostsQuiet();
884
-
885
1101
  const runArgs = process.argv.slice(3);
886
1102
  const forceNew = runArgs.includes('--new');
887
1103
  const modeArg = argValue('--mode');
888
1104
  const recipeArg = argValue('--recipe');
1105
+ const tierArg = argValue('--tier');
1106
+ const tierReasonArg = argValue('--tier-reason');
889
1107
  const taskParts = [];
890
1108
  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') {
1109
+ if (runArgs[index] === '--new' || runArgs[index] === '--json') continue;
1110
+ if (['--mode', '--recipe', '--tier', '--tier-reason'].includes(runArgs[index])) {
897
1111
  index += 1;
898
1112
  continue;
899
1113
  }
@@ -939,19 +1153,63 @@ function handleRun() {
939
1153
  }
940
1154
  }
941
1155
  if (mode) assertModeAllowed(CWD, mode);
1156
+ const tier = startsNewRun
1157
+ ? initialTierState({ task, changedPaths: workingTreePaths(CWD), override: tierArg, overrideReason: tierReasonArg })
1158
+ : null;
1159
+ if (!startsNewRun && tierArg) throw new Error('--tier applies only when a new run starts (use --new).');
942
1160
  runResult = createOrResumeRun(CWD, {
943
1161
  task,
944
1162
  forceNew,
945
1163
  mode,
946
1164
  workflow,
1165
+ tier,
947
1166
  ...(requestedRunId ? { runId: requestedRunId } : {})
948
1167
  });
949
1168
  assertBudgetAvailable(CWD, { runId: runResult.run.runId });
950
1169
  } catch (err) {
1170
+ console.log = realLog;
1171
+ if (runJson) {
1172
+ realLog(JSON.stringify({ ok: false, code: err.code || 'RUN_FAILED', error: err.message }));
1173
+ process.exit(1);
1174
+ }
951
1175
  log.error(err.message);
952
1176
  process.exit(1);
953
1177
  }
1178
+ if (runJson) {
1179
+ console.log = realLog;
1180
+ const run = runResult.run;
1181
+ console.log(JSON.stringify({
1182
+ ok: true,
1183
+ runId: run.runId,
1184
+ resumed: runResult.resumed,
1185
+ state: run.state,
1186
+ iteration: run.iteration,
1187
+ mode: run.mode || RUN_MODES.ASSISTED,
1188
+ tier: run.tier ? run.tier.current : null,
1189
+ tierSource: run.tier ? run.tier.source : null,
1190
+ tierReasons: run.tier ? run.tier.reasons : [],
1191
+ subagents: run.tier ? { T0: 0, T1: 1, T2: 2 }[run.tier.current] : 2,
1192
+ recipe: run.workflow ? run.workflow.recipeId : null,
1193
+ budget: (() => {
1194
+ try {
1195
+ const b = budgetStatus(CWD, { runId: run.runId });
1196
+ return { allowed: b.allowed, spentThisRun: b.spentThisRun, warnings: b.warnings || [] };
1197
+ } catch (e) {
1198
+ return { allowed: false, error: e.message };
1199
+ }
1200
+ })(),
1201
+ hostSkills: (() => {
1202
+ const h = hostSkillStatus({ home: homeDir(), version: VERSION });
1203
+ return { stale: h.stale, staleFiles: h.staleFiles, installedVersion: h.installedVersion, packageVersion: VERSION };
1204
+ })()
1205
+ }, null, 2));
1206
+ return;
1207
+ }
954
1208
  console.log(`- Run: ${runResult.run.runId} (${runResult.resumed ? 'resumed' : 'created'})`);
1209
+ if (runResult.run.tier) {
1210
+ const t = runResult.run.tier;
1211
+ console.log(`- Tier: ${t.current} (${t.source}; ${t.reasons.map((r) => r.code).join(', ')})`);
1212
+ }
955
1213
  console.log(`- State: ${runResult.run.state}, iteration ${runResult.run.iteration}`);
956
1214
  console.log(`- Mode: ${runResult.run.mode || RUN_MODES.ASSISTED}`);
957
1215
  if (runResult.run.workflow) {
@@ -967,16 +1225,25 @@ function handleRun() {
967
1225
 
968
1226
  console.log('\n------------------------------------------------------------');
969
1227
  log.bold('AI Agent Ready:');
970
- console.log('1. Grill if needed, then freeze Goal Contract (core/grill-policy.md, core/goal-contract.md)');
1228
+ console.log('1. Grill if needed (docs grill-policy), then freeze a failure-table Goal Contract');
971
1229
  if (runResult.run.mode === RUN_MODES.REPORT_ONLY) {
972
1230
  console.log('2. Analyze evidence without changing repository files');
973
1231
  console.log('3. Write report.json and finish with `ai-engineering-loop gate report`');
974
1232
  } 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)');
1233
+ console.log('2. Root Cause Analysis (docs root-cause-analysis) & Plan');
1234
+ console.log('3. Maker TDD at named seams (docs tdd-policy)');
977
1235
  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');
1236
+ const tierNow = runResult.run.tier ? runResult.run.tier.current : null;
1237
+ if (tierNow === 'T0') {
1238
+ console.log('5. T0: no Devil\'s Advocate. Fill claimed-vs-reality, then `gate review` (CLI writes the empty ledger)');
1239
+ console.log('6. T0: `gate judge` writes the deterministic verdict (no Judge subagent)');
1240
+ } else if (tierNow === 'T1') {
1241
+ console.log('5. Execute lean Devil\'s Advocate review, then `gate review --json`');
1242
+ console.log('6. Judge subagent only if `gate review` says judgeRequired; otherwise `gate judge` is deterministic');
1243
+ } else {
1244
+ console.log('5. Execute Devil\'s Advocate Adversarial Review');
1245
+ console.log(`6. Judge Agent evaluates DoD and issues PASS verdict${tierNow === 'T2' ? ' (STRONG_MODEL required)' : ''}`);
1246
+ }
980
1247
  console.log('7. Context Impact Assessment (NONE / TARGETED / MAJOR)');
981
1248
  console.log('8. Delivery Adapter creates MR/PR');
982
1249
  if (runResult.run.mode === RUN_MODES.ASSISTED) {
@@ -1126,6 +1393,8 @@ function handleBudget() {
1126
1393
  ? 0
1127
1394
  : parseNonNegativeIntegerArg('--estimate', argValue('--estimate'))
1128
1395
  });
1396
+ } else if (action === 'record' && process.argv.includes('--unavailable')) {
1397
+ result = recordUsageUnavailable(CWD, { runId, nodeId });
1129
1398
  } else if (action === 'record') {
1130
1399
  result = recordTokenUsage(CWD, {
1131
1400
  runId,
@@ -1299,6 +1568,69 @@ function handleArtifactTool(action) {
1299
1568
  }
1300
1569
  }
1301
1570
 
1571
+ // Shared by `gate` and the combined stage commands (issue #34) so both paths
1572
+ // publish identical workflow-node and Studio lifecycle events.
1573
+ function executeGate(gate, runId) {
1574
+ const target = runId ? loadRun(CWD, runId) : getCurrentRun(CWD);
1575
+ if (!target) throw new Error('No current run. Start one with `ai-engineering-loop run`.');
1576
+ listRunLifecycle(CWD, target.runId);
1577
+ let lifecycleNode = null;
1578
+ if (target.workflow) {
1579
+ const workflow = workflowStatus(CWD, { runId: target.runId });
1580
+ lifecycleNode = workflow.plan.nodes.find((node) => node.legacyGate === gate) || null;
1581
+ if (lifecycleNode && workflow.state.nodes[lifecycleNode.id].status === 'READY') {
1582
+ startWorkflowNode(CWD, lifecycleNode.id, { runId: target.runId });
1583
+ appendRunLifecycle(CWD, target.runId, {
1584
+ type: 'NODE_STARTED',
1585
+ nodeId: lifecycleNode.id,
1586
+ phase: gate,
1587
+ actor: 'agent',
1588
+ message: `${lifecycleNode.displayName || lifecycleNode.id} started`
1589
+ });
1590
+ }
1591
+ }
1592
+ const run = target.workflow
1593
+ ? applyWorkflowGate(CWD, gate, { runId: target.runId }).run
1594
+ : applyGate(CWD, gate, { runId: target.runId });
1595
+ const runCompleted = run.state === 'DELIVERED' || run.state === 'REPORTED';
1596
+ appendRunLifecycle(CWD, target.runId, {
1597
+ type: runCompleted
1598
+ ? 'RUN_COMPLETED'
1599
+ : (lifecycleNode ? 'NODE_COMPLETED' : 'PHASE_COMPLETED'),
1600
+ ...(!runCompleted && lifecycleNode ? { nodeId: lifecycleNode.id } : {}),
1601
+ phase: gate,
1602
+ actor: 'agent',
1603
+ status: 'PASSED',
1604
+ message: `${lifecycleNode?.displayName || gate} completed`
1605
+ });
1606
+ return run;
1607
+ }
1608
+
1609
+ // `gate maker --from-git` (issue #35): write the working-tree diff (tracked and
1610
+ // untracked files, excluding .ai-engineering-loop/) to RUN_DIR/diff.patch so the
1611
+ // agent does not need a separate write step. ASSISTED/REPORT_ONLY only;
1612
+ // UNATTENDED diffs come from `sandbox capture`.
1613
+ function captureMakerDiff(run) {
1614
+ if (run.mode === 'UNATTENDED') throw new Error('--from-git is not allowed in UNATTENDED; use `sandbox capture`.');
1615
+ const { execFileSync } = require('child_process');
1616
+ const exclude = ':(exclude).ai-engineering-loop';
1617
+ const git = (args, allowExit1 = false) => {
1618
+ try {
1619
+ return execFileSync('git', args, { cwd: CWD, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
1620
+ } catch (e) {
1621
+ if (allowExit1 && e.status === 1) return e.stdout;
1622
+ throw e;
1623
+ }
1624
+ };
1625
+ let diff = git(['diff', '--binary', 'HEAD', '--', '.', exclude]);
1626
+ const untracked = git(['ls-files', '--others', '--exclude-standard', '-z', '--', '.', exclude]).split('\0').filter(Boolean);
1627
+ for (const file of untracked) diff += git(['diff', '--binary', '--no-index', '--', '/dev/null', file], true);
1628
+ if (!diff.trim()) throw new Error('--from-git found no changes against HEAD.');
1629
+ const target = path.join(CWD, '.ai-engineering-loop', 'runs', run.runId, 'diff.patch');
1630
+ fs.writeFileSync(target, diff);
1631
+ return { path: path.relative(CWD, target).split(path.sep).join('/'), files: untracked.length };
1632
+ }
1633
+
1302
1634
  function handleGate() {
1303
1635
  const gate = process.argv[3];
1304
1636
  const runId = argValue('--run');
@@ -1308,48 +1640,32 @@ function handleGate() {
1308
1640
  const target = runId ? loadRun(CWD, runId) : getCurrentRun(CWD);
1309
1641
  if (!target) throw new Error('No current run. Start one with `ai-engineering-loop run`.');
1310
1642
  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
- }
1643
+ if (process.argv.includes('--from-git')) {
1644
+ if (gate !== 'maker') throw new Error('--from-git only applies to `gate maker`.');
1645
+ captureMakerDiff(target);
1326
1646
  }
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
- });
1647
+ const run = executeGate(gate, target.runId);
1648
+ const judge = gate === 'review' && run.tier ? judgeRequirement(CWD, run) : null;
1341
1649
  if (json) {
1342
1650
  console.log(JSON.stringify({
1343
1651
  ok: true,
1344
1652
  runId: run.runId,
1345
1653
  state: run.state,
1346
1654
  iteration: run.iteration,
1347
- gate
1655
+ gate,
1656
+ ...(run.tier ? { tier: run.tier.current } : {}),
1657
+ ...(judge ? { judgeRequired: judge.required, judgeReasons: judge.reasons } : {})
1348
1658
  }));
1349
1659
  } else {
1350
1660
  log.success(`✓ ${gate} gate passed`);
1351
1661
  console.log(`- Run: ${run.runId}`);
1352
1662
  console.log(`- State: ${run.state}, iteration ${run.iteration}`);
1663
+ if (run.tier) console.log(`- Tier: ${run.tier.current}`);
1664
+ if (judge) {
1665
+ console.log(judge.required
1666
+ ? `- Judge: REQUIRED (${judge.reasons.join('; ')}). Spawn the Judge subagent, write verdict.json, then gate judge.`
1667
+ : '- Judge: not required. Run "gate judge" now; the CLI writes the deterministic verdict.');
1668
+ }
1353
1669
  }
1354
1670
  } catch (err) {
1355
1671
  const retryHint = targetRunId && gate && err.code === 'GATE_FAILED'
@@ -1718,8 +2034,260 @@ function printUpdatePlan(plan) {
1718
2034
  for (const item of plan.commands) console.log(item.display);
1719
2035
  }
1720
2036
 
2037
+ // Used by auto-update for every registered project: regenerate context with
2038
+ // user-edited files preserved (new templates land in *.ael-new).
2039
+ function handleSafeRefresh() {
2040
+ if (!fs.existsSync(CONTEXT_DIR)) {
2041
+ log.error('No .ai-engineering-loop/ here; run init first.');
2042
+ process.exit(1);
2043
+ }
2044
+ const current = getCurrentRun(CWD);
2045
+ if (current && !TERMINAL_STATES.has(current.state)) {
2046
+ log.warn(`Run ${current.runId} is active (${current.state}); skipping refresh until it finishes.`);
2047
+ process.exit(3);
2048
+ }
2049
+ const legacy = !fs.existsSync(path.join(CONTEXT_DIR, GENERATED_HASHES_FILE));
2050
+ if (legacy) {
2051
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
2052
+ CONTEXT_WRITE_LEGACY = { root: path.resolve(CONTEXT_DIR), snapshotDir: path.join(CONTEXT_DIR, '.ael-backup', stamp) };
2053
+ }
2054
+ CONTEXT_WRITE_SAFE = true;
2055
+ const discovery = analyzeRepository(CWD);
2056
+ generateContextFiles(CWD, discovery, 'refresh', 'PACKAGE_UPDATE', { overwriteCore: true });
2057
+ removeObsoleteContextFiles(CONTEXT_DIR);
2058
+ CONTEXT_WRITE_SAFE = false;
2059
+ let snapshot = null;
2060
+ if (CONTEXT_WRITE_LEGACY && CONTEXT_WRITE_REPORT.snapshot.length) {
2061
+ snapshot = path.relative(CWD, CONTEXT_WRITE_LEGACY.snapshotDir).split(path.sep).join('/');
2062
+ fs.writeFileSync(path.join(CONTEXT_WRITE_LEGACY.snapshotDir, 'snapshot.json'), `${JSON.stringify({
2063
+ schemaVersion: 1,
2064
+ reason: 'LEGACY_FIRST_UPDATE',
2065
+ version: VERSION,
2066
+ at: new Date().toISOString(),
2067
+ files: CONTEXT_WRITE_REPORT.snapshot,
2068
+ removed: CONTEXT_WRITE_REPORT.removed
2069
+ }, null, 2)}\n`);
2070
+ }
2071
+ CONTEXT_WRITE_LEGACY = null;
2072
+ const report = {
2073
+ ok: true,
2074
+ mode: legacy ? 'legacy-first-update' : 'hash-checked',
2075
+ updated: CONTEXT_WRITE_REPORT.updated,
2076
+ aelNew: CONTEXT_WRITE_REPORT.aelNew,
2077
+ unchanged: CONTEXT_WRITE_REPORT.kept,
2078
+ removed: CONTEXT_WRITE_REPORT.removed,
2079
+ obsoleteKept: CONTEXT_WRITE_REPORT.obsoleteKept,
2080
+ snapshot
2081
+ };
2082
+ if (process.argv.includes('--json')) console.log(JSON.stringify(report));
2083
+ else {
2084
+ log.success('✓ Context refreshed non-destructively.');
2085
+ if (legacy) console.log(`- First update of a legacy project: AEL-managed files overwritten${snapshot ? `; previous copies in ${snapshot}` : ''}.`);
2086
+ if (report.removed.length) console.log(`- Removed obsolete AEL files: ${report.removed.join(', ')}`);
2087
+ if (report.aelNew.length) console.log(`- Kept your edits; review new templates: ${report.aelNew.join(', ')}`);
2088
+ if (report.obsoleteKept.length) console.log(`- Obsolete but edited (kept): ${report.obsoleteKept.join(', ')}`);
2089
+ }
2090
+ }
2091
+
2092
+ function readCurrentRunFor(dir) {
2093
+ const run = getCurrentRun(dir);
2094
+ return run ? { ...run, terminal: TERMINAL_STATES.has(run.state) } : null;
2095
+ }
2096
+
2097
+ function expectedRepository() {
2098
+ const repo = require('../package.json').repository;
2099
+ return repo && typeof repo === 'object' ? repo.url : repo || null;
2100
+ }
2101
+
2102
+ // Decision 1 on #37: a short, useful notice, at most once a day per project,
2103
+ // interactive stderr only (never CI or --json).
2104
+ function showUpdateNotice(cache, decision, policy) {
2105
+ const notice = require('../lib/update-notice.js');
2106
+ if (!notice.noticeAllowed()) return;
2107
+ const projectKey = path.resolve(process.cwd());
2108
+ if (!notice.noticeDue(cache, projectKey)) return;
2109
+ const packageRoot = path.join(__dirname, '..');
2110
+ const scope = cache.scope || detectInstallScope(packageRoot);
2111
+ const manager = scope === 'global' ? notice.detectGlobalPackageManager(packageRoot) : notice.detectPackageManager(projectKey);
2112
+ const cached = cache.highlights;
2113
+ const highlights = cached && cached.target === decision.target && cached.from === VERSION ? cached.items || [] : [];
2114
+ process.stderr.write(`${notice.formatNotice({
2115
+ packageName: require('../package.json').name,
2116
+ current: VERSION,
2117
+ target: decision.target,
2118
+ bump: decision.bump,
2119
+ scope,
2120
+ manager,
2121
+ highlights,
2122
+ policy: policy.policy,
2123
+ reason: decision.reason
2124
+ })}\n`);
2125
+ const userState = require('../lib/user-state.js');
2126
+ userState.writeJsonFile(userState.userStatePath('update-check.json'), notice.markNoticeShown(cache, projectKey, decision.target));
2127
+ }
2128
+
2129
+ // Background only: cache 2-4 CHANGELOG highlights for current -> target.
2130
+ async function cacheUpdateHighlights(cache, decision, packageName) {
2131
+ if (!decision.target || decision.action === 'none') return;
2132
+ if (cache.highlights && cache.highlights.target === decision.target && cache.highlights.from === VERSION) return;
2133
+ const notice = require('../lib/update-notice.js');
2134
+ const slug = (String(expectedRepository() || '').match(/github\.com[/:]([^/]+\/[^/.]+)/) || [])[1] || null;
2135
+ const text = await notice.fetchChangelog({ packageName, target: decision.target, repositorySlug: slug });
2136
+ if (!text) return;
2137
+ const items = notice.changelogHighlights(text, { current: VERSION, target: decision.target });
2138
+ const userState = require('../lib/user-state.js');
2139
+ const latest = autoUpdate.readCache() || cache;
2140
+ userState.writeJsonFile(userState.userStatePath('update-check.json'), { ...latest, highlights: { from: VERSION, target: decision.target, items } });
2141
+ }
2142
+
2143
+ // Foreground hook for run/status/init/refresh. Never blocks and never throws:
2144
+ // prints a pending summary or notice to stderr and, when the cache is stale or
2145
+ // an update is due, starts `update auto --background` detached.
2146
+ function maybeAutoUpdate() {
2147
+ try {
2148
+ if (!autoUpdate.autoUpdateAllowedHere()) return;
2149
+ const summary = autoUpdate.consumeSummary();
2150
+ if (summary) process.stderr.write(`${summary}\n`);
2151
+ const policy = autoUpdate.resolvePolicy();
2152
+ if (policy.policy === 'off') return;
2153
+ const cache = autoUpdate.readCache();
2154
+ if (autoUpdate.cacheStale(cache)) {
2155
+ autoUpdate.spawnBackgroundCheck({ cliPath: __filename });
2156
+ return;
2157
+ }
2158
+ const state = autoUpdate.readState();
2159
+ const decision = autoUpdate.decideUpdate({ current: VERSION, distTags: cache.distTags, ...policy });
2160
+ const applyInBackground = decision.action === 'apply' && cache.scope === 'global';
2161
+ if (applyInBackground || (state.pendingProjects || []).length) {
2162
+ autoUpdate.spawnBackgroundCheck({ cliPath: __filename });
2163
+ }
2164
+ if (!applyInBackground && decision.action !== 'none') showUpdateNotice(cache, decision, policy);
2165
+ } catch {
2166
+ // Auto-update must never break a command.
2167
+ }
2168
+ }
2169
+
2170
+ // `update auto [--background] [--force] [--json]`: check (cached 24 h), decide,
2171
+ // and apply under the user's policy; also retries projects left pending.
2172
+ function handleUpdateAuto() {
2173
+ const json = process.argv.includes('--json');
2174
+ const background = process.argv.includes('--background');
2175
+ const packageName = require('../package.json').name;
2176
+ const policy = autoUpdate.resolvePolicy();
2177
+ const out = (value) => {
2178
+ if (!background) console.log(json ? JSON.stringify(value) : JSON.stringify(value, null, 2));
2179
+ };
2180
+ if (policy.policy === 'off' && !process.argv.includes('--force')) {
2181
+ out({ ok: true, action: 'none', reason: `POLICY_OFF (${policy.source})` });
2182
+ return;
2183
+ }
2184
+ let cache = autoUpdate.readCache();
2185
+ if (autoUpdate.cacheStale(cache) || process.argv.includes('--force')) cache = autoUpdate.refreshCache({ packageName });
2186
+ const scope = detectInstallScope(path.join(__dirname, '..'));
2187
+ try {
2188
+ require('../lib/user-state.js').writeJsonFile(require('../lib/user-state.js').userStatePath('update-check.json'), { ...cache, scope });
2189
+ } catch {
2190
+ // Best effort.
2191
+ }
2192
+ const decision = autoUpdate.decideUpdate({ current: VERSION, distTags: cache.distTags, ...policy });
2193
+ const projects = projectRegistry.listProjects().projects;
2194
+ let result = null;
2195
+ if (decision.action === 'apply') {
2196
+ result = autoUpdate.applyUpdate({
2197
+ packageName,
2198
+ current: VERSION,
2199
+ target: decision.target,
2200
+ scope,
2201
+ projects,
2202
+ readCurrentRun: readCurrentRunFor,
2203
+ expectedRepository: expectedRepository()
2204
+ });
2205
+ } else {
2206
+ result = autoUpdate.processPending({ projects, readCurrentRun: readCurrentRunFor });
2207
+ }
2208
+ out({ ok: true, policy: policy.policy, policySource: policy.source, scope, offline: cache.error || null, decision, result });
2209
+ cacheUpdateHighlights({ ...cache, scope }, decision, packageName).catch(() => {});
2210
+ }
2211
+
2212
+ function handleUpdatePolicy() {
2213
+ const json = process.argv.includes('--json');
2214
+ const value = process.argv[4] && !process.argv[4].startsWith('-') ? process.argv[4] : undefined;
2215
+ const channel = argValue('--channel') || undefined;
2216
+ const pin = process.argv.includes('--no-pin') ? null : (argValue('--pin') || undefined);
2217
+ try {
2218
+ if (value !== undefined || channel !== undefined || pin !== undefined) autoUpdate.setPolicy({ policy: value, channel, pin });
2219
+ const resolved = autoUpdate.resolvePolicy();
2220
+ if (json) console.log(JSON.stringify({ ok: true, ...resolved }));
2221
+ else console.log(`Auto-update policy: ${resolved.policy} (${resolved.source}); channel ${resolved.channel}${resolved.pin ? `; pin ${resolved.pin}` : ''}. Majors are always notice-only.`);
2222
+ } catch (err) {
2223
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code, error: err.message }));
2224
+ else log.error(err.message);
2225
+ process.exit(1);
2226
+ }
2227
+ }
2228
+
2229
+ function handleUpdateRollback() {
2230
+ const json = process.argv.includes('--json');
2231
+ try {
2232
+ if (!process.argv.includes('--yes')) throw Object.assign(new Error('update rollback requires --yes'), { code: 'CONFIRMATION_REQUIRED' });
2233
+ const record = autoUpdate.rollback({ packageName: require('../package.json').name, projects: projectRegistry.listProjects().projects });
2234
+ if (json) console.log(JSON.stringify({ ok: true, ...record }));
2235
+ 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)` : ""}.`);
2236
+ } catch (err) {
2237
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'ROLLBACK_FAILED', error: err.message }));
2238
+ else log.error(err.message);
2239
+ process.exit(1);
2240
+ }
2241
+ }
2242
+
2243
+ function handleProjects() {
2244
+ const action = process.argv[3] || 'list';
2245
+ const json = process.argv.includes('--json');
2246
+ try {
2247
+ let result;
2248
+ if (action === 'list') result = projectRegistry.listProjects();
2249
+ else if (action === 'add') result = { added: projectRegistry.addProject(process.argv[4] && !process.argv[4].startsWith('-') ? process.argv[4] : CWD) };
2250
+ else if (action === 'remove') result = { removed: projectRegistry.removeProject(process.argv[4] && !process.argv[4].startsWith('-') ? process.argv[4] : CWD) };
2251
+ else if (action === 'scan') {
2252
+ const root = argValue('--root');
2253
+ if (!root) throw Object.assign(new Error('projects scan requires --root <dir>'), { code: 'ROOT_REQUIRED' });
2254
+ const depth = Number(argValue('--depth') || 4);
2255
+ if (!Number.isInteger(depth) || depth < 0 || depth > 8) throw Object.assign(new Error('--depth must be 0-8'), { code: 'INVALID_DEPTH' });
2256
+ result = projectRegistry.scanProjects(root, { maxDepth: depth });
2257
+ } else throw Object.assign(new Error(`Unknown projects action: ${action}`), { code: 'UNKNOWN_ACTION' });
2258
+ if (json) console.log(JSON.stringify({ ok: true, action, ...result }));
2259
+ else if (action === 'list') {
2260
+ if (!result.projects.length) console.log('No registered projects. They are added by init/run/status/refresh, or `projects add|scan`.');
2261
+ for (const p of result.projects) console.log(`- ${p.path} (context ${p.contextVersion || '?'}, seen ${p.lastSeen})`);
2262
+ } else console.log(JSON.stringify(result, null, 2));
2263
+ } catch (err) {
2264
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'PROJECTS_FAILED', error: err.message }));
2265
+ else log.error(err.message);
2266
+ process.exit(1);
2267
+ }
2268
+ }
2269
+
2270
+ // First-run question (TTY only, once). Non-interactive sessions stay on
2271
+ // `notify` until the user picks a policy with `update policy`.
2272
+ function askAutoUpdatePolicyOnce() {
2273
+ try {
2274
+ if (!process.stdin.isTTY || !process.stdout.isTTY || !autoUpdate.autoUpdateAllowedHere()) return;
2275
+ if (autoUpdate.resolvePolicy().source !== 'unset') return;
2276
+ process.stdout.write(`Auto-update ai-engineering-loop? [off/notify/patch/minor/all] (default ${autoUpdate.DEFAULT_POLICY}; majors are always notice-only): `);
2277
+ const buffer = Buffer.alloc(64);
2278
+ const bytes = fs.readSync(0, buffer, 0, buffer.length, null);
2279
+ const answer = buffer.toString('utf8', 0, bytes).trim().toLowerCase() || autoUpdate.DEFAULT_POLICY;
2280
+ autoUpdate.setPolicy({ policy: autoUpdate.POLICIES.includes(answer) ? answer : autoUpdate.DEFAULT_POLICY });
2281
+ } catch {
2282
+ // Never block init on the prompt.
2283
+ }
2284
+ }
2285
+
1721
2286
  function handleUpdate() {
1722
2287
  const action = process.argv[3] || 'check';
2288
+ if (action === 'auto') return handleUpdateAuto();
2289
+ if (action === 'policy') return handleUpdatePolicy();
2290
+ if (action === 'rollback') return handleUpdateRollback();
1723
2291
  const json = process.argv.includes('--json');
1724
2292
  const yes = process.argv.includes('--yes');
1725
2293
  try {
@@ -1759,6 +2327,28 @@ function handleUpdate() {
1759
2327
  }
1760
2328
  }
1761
2329
 
2330
+ // `migrate --from <old>`: idempotent major migrations for home and every
2331
+ // registered project (plus this one when it has .ai-engineering-loop/).
2332
+ function handleMigrate() {
2333
+ const json = process.argv.includes('--json');
2334
+ try {
2335
+ const from = argValue('--from');
2336
+ if (!from) throw Object.assign(new Error('migrate requires --from <old-version>'), { code: 'FROM_REQUIRED' });
2337
+ const migrations = require('../lib/migrations.js');
2338
+ const projects = projectRegistry.listProjects().projects.map((p) => p.path);
2339
+ const here = path.resolve(CWD);
2340
+ if (fs.existsSync(path.join(here, '.ai-engineering-loop')) && !projects.includes(here)) projects.push(here);
2341
+ const report = migrations.runMigrations({ from, to: VERSION, projects, dryRun: process.argv.includes('--dry-run') });
2342
+ if (json) console.log(JSON.stringify({ ok: true, ...report }));
2343
+ else if (!report.migrations.length) console.log(`No migrations between ${from} and ${VERSION}.`);
2344
+ else for (const step of report.migrations) console.log(`- v${step.major}: ${step.description} (home ${step.home}, ${step.projects.length} project(s))`);
2345
+ } catch (err) {
2346
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'MIGRATE_FAILED', error: err.message }));
2347
+ else log.error(err.message);
2348
+ process.exit(1);
2349
+ }
2350
+ }
2351
+
1762
2352
  function handleRecipe() {
1763
2353
  const action = process.argv[3] || 'list';
1764
2354
  const id = process.argv[4];
@@ -2034,9 +2624,14 @@ function handleGoal() {
2034
2624
  message: `Goal draft revision ${result.metadata.revision} is ready for review`
2035
2625
  });
2036
2626
  } else if (action === 'freeze') {
2037
- const expectedHash = argValue('--hash');
2627
+ const latest = process.argv.includes('--latest');
2628
+ const latestDraft = latest ? loadGoalDraft(CWD, runId) : null;
2629
+ if (latest && !latestDraft) {
2630
+ throw Object.assign(new Error('No Goal draft to freeze'), { code: 'GOAL_DRAFT_MISSING' });
2631
+ }
2632
+ const expectedHash = latest ? latestDraft.metadata.contentHash : argValue('--hash');
2038
2633
  if (!expectedHash) {
2039
- const error = new Error('--hash is required');
2634
+ const error = new Error('--hash is required (or --latest)');
2040
2635
  error.code = 'INVALID_USAGE';
2041
2636
  throw error;
2042
2637
  }
@@ -2058,7 +2653,7 @@ function handleGoal() {
2058
2653
  }
2059
2654
  result = freezeGoal(CWD, runId, {
2060
2655
  actor: argValue('--by') || 'human',
2061
- expectedRevision: requiredIntegerArg('--revision'),
2656
+ expectedRevision: latest ? latestDraft.metadata.revision : requiredIntegerArg('--revision'),
2062
2657
  expectedHash
2063
2658
  });
2064
2659
  appendRunLifecycle(CWD, runId, {
@@ -2193,9 +2788,247 @@ function handleInteraction() {
2193
2788
  }
2194
2789
  }
2195
2790
 
2791
+
2792
+ // ---------------------------------------------------------------------------
2793
+ // Combined stage commands (issue #34). Each replaces several agent turns with
2794
+ // one CLI call and goes through the same gates, so results are identical to
2795
+ // the long form (`verification record`... `gate verification`, etc.).
2796
+
2797
+ function autoHeartbeat(runId, phase, message) {
2798
+ try {
2799
+ appendRunLifecycle(CWD, runId, { type: 'AGENT_HEARTBEAT', phase, actor: 'agent', message });
2800
+ } catch (e) {
2801
+ // Heartbeats are best-effort Studio telemetry; never fail a stage on them.
2802
+ }
2803
+ }
2804
+
2805
+ function defaultVerificationCommand() {
2806
+ const text = readFileSafe(path.join(CONTEXT_DIR, 'verification.md')) || '';
2807
+ const match = text.match(/\*\*test_unit\*\*:\s*`([^`]+)`/);
2808
+ return match ? match[1].trim() : null;
2809
+ }
2810
+
2811
+ function splitCommand(text, shell) {
2812
+ const value = String(text || '').trim();
2813
+ if (!value) throw Object.assign(new Error('Empty verification command'), { code: 'INVALID_COMMAND' });
2814
+ if (shell) return { command: value, args: [], shell: true };
2815
+ if (/[|&;<>()$`"'\\*?]/.test(value)) {
2816
+ throw Object.assign(new Error(`"${value}" needs shell syntax; pass --shell or split it into separate --cmd values.`), { code: 'INVALID_COMMAND' });
2817
+ }
2818
+ const [command, ...rest] = value.split(/\s+/);
2819
+ return { command, args: rest, shell: false };
2820
+ }
2821
+
2822
+ function stageJsonError(err, json, code) {
2823
+ if (json) {
2824
+ console.log(JSON.stringify({ ok: false, code: err.code || code, error: err.message, details: err.details || [] }));
2825
+ } else {
2826
+ log.error(err.message);
2827
+ for (const detail of err.details || []) console.error(`- ${detail}`);
2828
+ }
2829
+ process.exit(1);
2830
+ }
2831
+
2832
+ function repeatedArg(name) {
2833
+ const values = [];
2834
+ const separator = process.argv.indexOf('--');
2835
+ const scoped = separator === -1 ? process.argv : process.argv.slice(0, separator);
2836
+ for (let index = 0; index < scoped.length; index += 1) {
2837
+ if (scoped[index] === name && scoped[index + 1] != null) values.push(scoped[index + 1]);
2838
+ }
2839
+ return values;
2840
+ }
2841
+
2842
+ async function handleVerify() {
2843
+ const json = process.argv.includes('--json');
2844
+ try {
2845
+ const runId = requiredRunId('verify');
2846
+ const shell = process.argv.includes('--shell');
2847
+ let texts = repeatedArg('--cmd');
2848
+ if (texts.length === 0) {
2849
+ const fallback = defaultVerificationCommand();
2850
+ if (!fallback) throw Object.assign(new Error('No --cmd given and no test_unit command in .ai-engineering-loop/verification.md'), { code: 'INVALID_COMMAND' });
2851
+ texts = [fallback];
2852
+ }
2853
+ const timeoutValue = argValue('--timeout-ms');
2854
+ const recorded = await recordVerificationCommands(CWD, {
2855
+ runId,
2856
+ commands: texts.map((text) => splitCommand(text, shell)),
2857
+ serial: process.argv.includes('--serial'),
2858
+ ...(timeoutValue == null ? {} : { timeoutMs: parsePositiveIntegerArg('--timeout-ms', timeoutValue) })
2859
+ });
2860
+ const commands = recorded.commands.map((c) => ({ command: c.command, exitCode: c.exitCode, timeoutStatus: c.timeoutStatus }));
2861
+ if (!recorded.passed) {
2862
+ autoHeartbeat(runId, 'verification', 'Verification failed; Maker must fix before review');
2863
+ const result = { ok: false, code: 'VERIFICATION_FAILED', runId, commands, gate: null };
2864
+ if (json) console.log(JSON.stringify(result));
2865
+ else {
2866
+ log.error('Verification failed; the gate was not attempted.');
2867
+ for (const c of commands) console.log(`- ${c.command}: exit ${c.exitCode} (${c.timeoutStatus})`);
2868
+ }
2869
+ process.exitCode = 1;
2870
+ return;
2871
+ }
2872
+ const run = executeGate('verification', runId);
2873
+ const compact = compactRun(CWD, { runId });
2874
+ let claimed = { path: '.ai-engineering-loop/tasks/claimed-vs-reality.md', created: false };
2875
+ try {
2876
+ claimed = { ...createClaimedVsRealityTemplate(CWD, { runId }), created: true };
2877
+ } catch (err) {
2878
+ if (err.code !== 'OUTPUT_EXISTS') throw err;
2879
+ }
2880
+ const result = {
2881
+ ok: true,
2882
+ runId,
2883
+ state: run.state,
2884
+ tier: run.tier ? run.tier.current : null,
2885
+ commands,
2886
+ testCounts: recorded.summary.testCounts,
2887
+ compact: compact.paths,
2888
+ claimedVsReality: claimed,
2889
+ next: run.tier && run.tier.current === 'T0'
2890
+ ? 'Fill claimed-vs-reality, then gate review and gate judge'
2891
+ : 'Fill claimed-vs-reality, then review-pack and spawn the Devil\'s Advocate'
2892
+ };
2893
+ if (json) console.log(JSON.stringify(result));
2894
+ else {
2895
+ log.success('✓ verification recorded and gated');
2896
+ for (const c of commands) console.log(`- ${c.command}: exit ${c.exitCode}`);
2897
+ console.log(`- State: ${run.state}`);
2898
+ console.log(`- Claimed-vs-reality: ${claimed.path}${claimed.created ? ' (scaffolded; fill it from the command output)' : ''}`);
2899
+ console.log(`- Next: ${result.next}`);
2900
+ }
2901
+ } catch (err) {
2902
+ stageJsonError(err, json, 'VERIFY_FAILED');
2903
+ }
2904
+ }
2905
+
2906
+ function handleReviewPack() {
2907
+ const json = process.argv.includes('--json');
2908
+ try {
2909
+ const runId = requiredRunId('review-pack');
2910
+ const run = loadRun(CWD, runId);
2911
+ if (!run.artifacts?.verification) {
2912
+ throw Object.assign(new Error('review-pack needs a passed verification gate (run verify first).'), { code: 'GATE_FAILED' });
2913
+ }
2914
+ const base = argValue('--base') || 'HEAD';
2915
+ const fastPath = assessSmallTaskFastPath(CWD, { base });
2916
+ const pack = smartContextSummary(createDiffHunkPack(CWD, { runId, base, profile: argValue('--profile') }));
2917
+ const escalation = assessRunEscalation(CWD, { runId });
2918
+ const tier = run.tier ? run.tier.current : null;
2919
+ autoHeartbeat(runId, 'review', 'Review pack built');
2920
+ const result = {
2921
+ ok: true,
2922
+ runId,
2923
+ tier,
2924
+ devilAdvocateRequired: tier !== 'T0',
2925
+ packPath: pack.path,
2926
+ diffPath: path.relative(CWD, path.join(runsDir(CWD), runId, 'diff.patch')).split(path.sep).join('/'),
2927
+ reviewProfile: pack.reviewProfile,
2928
+ estimatedTokens: pack.estimatedTokens,
2929
+ truncated: pack.truncated,
2930
+ unresolvedFindings: pack.unresolvedFindings,
2931
+ fastPath: { eligible: fastPath.eligible, reasons: fastPath.reasons },
2932
+ escalation: { requiredTier: escalation.requiredTier, reasons: escalation.reasons.map((r) => r.code) }
2933
+ };
2934
+ if (json) console.log(JSON.stringify(result));
2935
+ else {
2936
+ log.success('✓ review pack ready');
2937
+ console.log(`- Pack: ${result.packPath} (${result.reviewProfile}, ~${result.estimatedTokens} tokens)`);
2938
+ console.log(`- Tier: ${tier || 'none'}; Devil's Advocate ${result.devilAdvocateRequired ? 'required' : 'not used (T0)'}`);
2939
+ console.log(`- Judge tier floor: ${result.escalation.requiredTier}${result.escalation.reasons.length ? ` (${result.escalation.reasons.join(', ')})` : ''}`);
2940
+ }
2941
+ } catch (err) {
2942
+ stageJsonError(err, json, 'REVIEW_PACK_FAILED');
2943
+ }
2944
+ }
2945
+
2946
+ function handleDeliver() {
2947
+ const json = process.argv.includes('--json');
2948
+ try {
2949
+ const runId = requiredRunId('deliver');
2950
+ const run = loadRun(CWD, runId);
2951
+ const mode = run.mode || RUN_MODES.ASSISTED;
2952
+ const approve = process.argv.includes('--approve');
2953
+ const by = argValue('--by');
2954
+ if (mode === RUN_MODES.REPORT_ONLY) {
2955
+ throw Object.assign(new Error('REPORT_ONLY runs finish with gate report, not deliver.'), { code: 'INVALID_USAGE' });
2956
+ }
2957
+ if (mode === RUN_MODES.ASSISTED && !approve) {
2958
+ console.error('ASSISTED delivery needs the human\'s explicit approval: deliver --approve --by <name>. Nothing was written.');
2959
+ process.exit(2);
2960
+ }
2961
+ if (approve && !by) {
2962
+ throw Object.assign(new Error('--approve requires --by <name> (the approving human).'), { code: 'INVALID_USAGE' });
2963
+ }
2964
+ const approved = [];
2965
+ if (approve && run.workflow) {
2966
+ const workflow = workflowStatus(CWD, { runId });
2967
+ for (const node of workflow.plan.nodes) {
2968
+ if (node.type !== 'approval' || workflow.state.nodes[node.id].status !== 'READY') continue;
2969
+ approveWorkflowNode(CWD, node.id, { runId, approvedBy: by });
2970
+ appendRunLifecycle(CWD, runId, { type: 'NODE_COMPLETED', nodeId: node.id, phase: node.id, actor: by, message: `Node ${node.id} approved` });
2971
+ approved.push(node.id);
2972
+ }
2973
+ }
2974
+ const deliveryPath = path.join(runsDir(CWD), runId, 'delivery.json');
2975
+ let delivery = null;
2976
+ if (fs.existsSync(deliveryPath)) {
2977
+ try { delivery = JSON.parse(fs.readFileSync(deliveryPath, 'utf8')); } catch (e) { delivery = null; }
2978
+ }
2979
+ const destination = argValue('--destination');
2980
+ const summary = argValue('--summary');
2981
+ if (!delivery && !(destination && summary)) {
2982
+ throw Object.assign(new Error('Pass --destination <where> and --summary <text>, or write delivery.json first.'), { code: 'INVALID_USAGE' });
2983
+ }
2984
+ delivery = {
2985
+ ...(delivery || {}),
2986
+ schemaVersion: 1,
2987
+ runId,
2988
+ ...(destination ? { destination } : {}),
2989
+ ...(summary ? { summary } : {}),
2990
+ ...(approve ? { humanApproved: true, approvedBy: by } : {})
2991
+ };
2992
+ fs.writeFileSync(deliveryPath, `${JSON.stringify(delivery, null, 2)}\n`, { mode: 0o600 });
2993
+ const next = executeGate('delivery', runId);
2994
+ const result = { ok: true, runId, state: next.state, approvedNodes: approved, humanApproved: delivery.humanApproved === true };
2995
+ if (json) console.log(JSON.stringify(result));
2996
+ else {
2997
+ log.success('✓ delivery gate passed');
2998
+ console.log(`- State: ${next.state}`);
2999
+ if (approved.length) console.log(`- Approved: ${approved.join(', ')} by ${by}`);
3000
+ }
3001
+ } catch (err) {
3002
+ stageJsonError(err, json, 'DELIVER_FAILED');
3003
+ }
3004
+ }
3005
+
3006
+ // Command: docs (read-only packaged specs)
3007
+ function handleDocs() {
3008
+ const json = process.argv.includes('--json');
3009
+ const target = process.argv[3] && !process.argv[3].startsWith('--') ? process.argv[3] : 'list';
3010
+ if (target === 'list') {
3011
+ const docs = listDocs();
3012
+ if (json) {
3013
+ console.log(JSON.stringify({ ok: true, docs }, null, 2));
3014
+ return;
3015
+ }
3016
+ for (const doc of docs) console.log(`${doc.name.padEnd(44)} ${String(doc.bytes).padStart(6)} B ${doc.rel}`);
3017
+ return;
3018
+ }
3019
+ try {
3020
+ const doc = readDoc(target, { section: argValue('--section') });
3021
+ if (json) console.log(JSON.stringify({ ok: true, ...doc }, null, 2));
3022
+ else process.stdout.write(`${doc.text}\n`);
3023
+ } catch (err) {
3024
+ log.error(`${err.code || 'DOCS_FAILED'}: ${err.message}`);
3025
+ process.exitCode = 1;
3026
+ }
3027
+ }
3028
+
2196
3029
  // Help Menu
2197
- function printHelp() {
2198
- console.log(`
3030
+ function helpText() {
3031
+ return (`
2199
3032
  AI Engineering Loop CLI (v${VERSION})
2200
3033
  A reusable, framework-agnostic AI Engineering Operating System.
2201
3034
 
@@ -2205,15 +3038,18 @@ Usage:
2205
3038
  Commands:
2206
3039
  init Bootstrap .ai-engineering-loop/ context from repository discovery
2207
3040
  status Check the validity, readiness, and baseline freshness of context
3041
+ --json print context and host-skill freshness as JSON (no writes)
2208
3042
  refresh Reconcile drifted context against repository non-destructively
2209
- run [task] Start or resume a stateful engineering run, sync hosts, and instruct the agent
3043
+ run [task] Start or resume a stateful engineering run and instruct the agent (never writes to home)
2210
3044
  --new start a new run even when another run is active
2211
3045
  --mode report-only|assisted|unattended
2212
3046
  --recipe <id> bind an immutable compiled workflow plan
3047
+ --tier T0|T1|T2 --tier-reason <text> override the automatic tier (recorded)
3048
+ --json print runId, tier, tier reasons, and subagent count only
2213
3049
  state Inspect the current run ledger
2214
3050
  --run <id> target a non-current run
2215
3051
  --json print the complete machine-readable ledger
2216
- gate <name> Validate an artifact and advance the current run
3052
+ gate <name> Validate an artifact and advance the current run (maker: --from-git writes diff.patch first)
2217
3053
  goal | report | maker | verification | review | judge | delivery
2218
3054
  --run <id> target a non-current run
2219
3055
  --json print machine-readable gate output
@@ -2221,6 +3057,7 @@ Commands:
2221
3057
  show [--run <id>]
2222
3058
  draft --file <json> --revision <n> [--run <id>] [--by <agent>]
2223
3059
  freeze --revision <n> --hash <sha256> [--run <id>] [--by <name>]
3060
+ freeze --latest [--run <id>] --by <name> freeze the newest draft (CLI resolves revision/hash)
2224
3061
  verification Summarize verification.json for compact Judge context
2225
3062
  summarize [--run <id>] [--json]
2226
3063
  record [--run <id>] [--timeout-ms <n>] [--shell] [--json] -- <executable> [args...]
@@ -2255,6 +3092,8 @@ Commands:
2255
3092
  budget Enforce actual provider-reported token usage and emergency pause
2256
3093
  status [--run <id>] [--node <id>] [--estimate <n>] [--json]
2257
3094
  record --input <n> --output <n> --model <id> [--run <id>] [--node <id>]
3095
+ record --unavailable [--run <id>] [--node <id>]
3096
+ host exposed no usage: ASSISTED notes it and continues; UNATTENDED fails
2258
3097
  pause | resume
2259
3098
  sandbox Isolate Maker changes in a locked disposable Git worktree
2260
3099
  create | capture | abort | status [--run <id>] [--json]
@@ -2275,18 +3114,37 @@ Commands:
2275
3114
  --limit <n> bound query/related result count
2276
3115
  --include-ignored include CSS, generated, lockfile, and .aelcontextignore paths
2277
3116
  --json print only pack metadata; never print packed content
2278
- eval Validate the 20-case production evaluation catalog
3117
+ eval Validate the 24-case production evaluation catalog
2279
3118
  --results <dir> score host-generated JSON results
2280
3119
  --cases <dir> use another compatible fixture catalog
2281
3120
  --json print machine-readable metrics
2282
3121
  escalation Compute the minimum Judge model tier from deterministic risk signals
2283
3122
  --run <id> target a non-current run
2284
3123
  --json print machine-readable reasons
3124
+ verify Record verification commands, gate them, compact, and scaffold claimed-vs-reality
3125
+ [--run <id>] [--cmd "<command>"]... [--shell] [--serial] [--timeout-ms <n>] [--json]
3126
+ default command: test_unit from .ai-engineering-loop/verification.md; commands run in parallel
3127
+ review-pack Build the Devil's Advocate pack: fast-path, diff hunks, escalation floor, tier
3128
+ [--run <id>] [--base <git-ref>] [--profile lean|standard|thorough] [--json]
3129
+ deliver Approve READY approval nodes, write delivery.json, and pass the delivery gate
3130
+ [--run <id>] [--destination <where> --summary <text>] [--approve --by <name>] [--json]
3131
+ ASSISTED requires --approve --by <name>, given only after explicit human approval
3132
+ docs Print a packaged spec without needing the package source tree
3133
+ list [--json]
3134
+ <name> [--section <heading>] [--json] e.g. docs grill-policy --section "When to grill"
2285
3135
  doctor Check runtime, schemas, host assets, package contents, and eval catalog
2286
3136
  --json print machine-readable diagnostics
2287
3137
  update Check or apply the package update workflow
2288
3138
  check|plan [--json]
2289
3139
  apply --yes
3140
+ policy [off|notify|patch|minor|all] [--channel latest|next] [--pin 1.13.x|--no-pin]
3141
+ auto [--force] [--json] check (cached 24 h) and apply per policy; majors notice-only
3142
+ rollback --yes reinstall the previous version, re-sync hosts, restore legacy snapshots
3143
+ migrate Run major-version migrations (migrations/<major>.js); update apply calls it across a major
3144
+ --from <old-version> [--dry-run] [--json]
3145
+ projects Registry of local projects with .ai-engineering-loop/ (~/.ai-engineering-loop/projects.json)
3146
+ list|add [dir]|remove [dir] [--json]
3147
+ scan --root <dir> [--depth 4]
2290
3148
  recipe Inspect and compile declarative workflow recipes (does not execute nodes)
2291
3149
  list [--json]
2292
3150
  catalog [--json]
@@ -2306,7 +3164,11 @@ Commands:
2306
3164
  inspect | brief <repository-relative-file> [--json]
2307
3165
  sync-hosts Copy package skills/agents/commands into ~/.claude ~/.grok ~/.gemini ~/.agents
2308
3166
  (only hosts that already exist; DOT skills only if already installed)
2309
- --dry-run print the plan without writing
3167
+ --dry-run print the plan without writing
3168
+ --pack <list> core (always), backend, design, quality; saved for later syncs
3169
+ --prune remove unmodified files of packs that are not selected
3170
+ --json print machine-readable results
3171
+ User-edited host files are backed up to <file>.ael-backup before overwrite
2310
3172
  generate-adapter Print detected forge and grill protocol for Stage 8
2311
3173
  --type standard|github|gitlab|dot write .ai-engineering-loop/adapter.md (skip grill)
2312
3174
  generate-workflow Print grill protocol for a loop overlay (hooks + intern + lessons.md)
@@ -2321,14 +3183,47 @@ Documentation:
2321
3183
  `);
2322
3184
  }
2323
3185
 
3186
+ function printHelp() {
3187
+ console.log(helpText());
3188
+ }
3189
+
2324
3190
  // CLI Router
2325
3191
  const args = process.argv.slice(2);
2326
3192
  const command = args[0] || 'init';
2327
3193
 
3194
+ // Side-effect guard (issue #25): help never executes a command, and writer
3195
+ // commands reject unknown flags before touching any file.
3196
+ if (!['-h', '--help', '-v', '--version'].includes(command)) {
3197
+ if (wantsCommandHelp(command, args.slice(1))) {
3198
+ const block = commandHelp(helpText(), command);
3199
+ console.log(block
3200
+ ? `Usage: npx ai-engineering-loop ${block.trim()}`
3201
+ : helpText());
3202
+ process.exit(0);
3203
+ }
3204
+ const unknown = unknownWriterArgs(command, args.slice(1));
3205
+ if (unknown.length > 0) {
3206
+ log.error(`Unknown argument(s) for "${command}": ${unknown.join(' ')}. Nothing was written.`);
3207
+ console.log(`Run "npx ai-engineering-loop ${command} --help" for usage.`);
3208
+ process.exit(2);
3209
+ }
3210
+ }
3211
+
3212
+ // Registry + auto-update hooks (issue #37). Registration runs at exit so a
3213
+ // fresh `init` is recorded too.
3214
+ if (['init', 'run', 'status', 'refresh'].includes(command)) {
3215
+ process.once('exit', () => projectRegistry.registerProject(CWD));
3216
+ if (command === 'init') askAutoUpdatePolicyOnce();
3217
+ maybeAutoUpdate();
3218
+ }
3219
+
2328
3220
  switch (command) {
2329
3221
  case 'init':
2330
3222
  handleInit();
2331
3223
  break;
3224
+ case 'projects':
3225
+ handleProjects();
3226
+ break;
2332
3227
  case 'status':
2333
3228
  handleStatus();
2334
3229
  break;
@@ -2383,12 +3278,27 @@ switch (command) {
2383
3278
  case 'escalation':
2384
3279
  handleEscalation();
2385
3280
  break;
3281
+ case 'docs':
3282
+ handleDocs();
3283
+ break;
3284
+ case 'verify':
3285
+ handleVerify();
3286
+ break;
3287
+ case 'review-pack':
3288
+ handleReviewPack();
3289
+ break;
3290
+ case 'deliver':
3291
+ handleDeliver();
3292
+ break;
2386
3293
  case 'doctor':
2387
3294
  handleDoctor();
2388
3295
  break;
2389
3296
  case 'update':
2390
3297
  handleUpdate();
2391
3298
  break;
3299
+ case 'migrate':
3300
+ handleMigrate();
3301
+ break;
2392
3302
  case 'recipe':
2393
3303
  handleRecipe();
2394
3304
  break;