ai-engineering-loop 2.12.0 → 2.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 (46) hide show
  1. package/.agents/skills/ael/SKILL.md +3 -19
  2. package/.agents/skills/ael/references/loop-commands.md +5 -3
  3. package/.agents/skills/ael/references/loop-deliver.md +20 -0
  4. package/.agents/skills/ael/references/loop-goal.md +3 -2
  5. package/.agents/skills/ael/references/loop-hosts.md +10 -0
  6. package/.agents/skills/ael/references/loop-judge.md +9 -0
  7. package/.agents/skills/ael/references/loop-maker.md +1 -2
  8. package/.agents/skills/ael/references/loop-modes.md +6 -0
  9. package/.agents/skills/ael/references/loop-review.md +2 -6
  10. package/CHANGELOG.md +35 -0
  11. package/README.md +9 -1
  12. package/agents/instruction-only/AGENTS.md +1 -1
  13. package/bin/ai-engineering-loop.js +398 -41
  14. package/core/dig-first.md +46 -0
  15. package/core/goal-contract.md +40 -0
  16. package/core/run-isolation.md +24 -0
  17. package/core/verification-loop.md +27 -0
  18. package/lib/adapter-check.js +3 -2
  19. package/lib/agent-artifacts.js +28 -0
  20. package/lib/budget.js +1 -1
  21. package/lib/clean-state.js +20 -0
  22. package/lib/cli-args.js +5 -2
  23. package/lib/docs.js +2 -1
  24. package/lib/doctor.js +26 -0
  25. package/lib/driver-scaffold.js +289 -0
  26. package/lib/gates.js +3 -1
  27. package/lib/gh.js +27 -0
  28. package/lib/git-readiness.js +36 -0
  29. package/lib/harness-audit.js +11 -0
  30. package/lib/pr-status.js +83 -0
  31. package/lib/provenance.js +111 -0
  32. package/lib/quick.js +11 -0
  33. package/lib/recap-html.js +3 -2
  34. package/lib/recap.js +9 -0
  35. package/lib/receipt.js +3 -1
  36. package/lib/review-ingest.js +6 -1
  37. package/lib/rules.js +4 -2
  38. package/lib/run-isolation.js +117 -27
  39. package/lib/sources.js +166 -0
  40. package/lib/stats.js +9 -0
  41. package/lib/ste.js +69 -0
  42. package/lib/sync-hosts.js +2 -0
  43. package/lib/transcript-lessons.js +232 -0
  44. package/lib/workflow-runtime.js +8 -2
  45. package/package.json +2 -2
  46. package/schemas/goal-contract.schema.json +14 -0
@@ -369,13 +369,15 @@ function ignoreProjectContextOnFirstInit(rootDir) {
369
369
  /**
370
370
  * Colorized console helpers
371
371
  */
372
+ const COLOR = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
373
+ const paint = (code) => (msg) => (COLOR ? console.log(`\x1b[${code}m%s\x1b[0m`, msg) : console.log(msg));
372
374
  const log = {
373
- info: (msg) => console.log('\x1b[36m%s\x1b[0m', msg),
374
- success: (msg) => console.log('\x1b[32m%s\x1b[0m', msg),
375
- warn: (msg) => console.log('\x1b[33m%s\x1b[0m', msg),
376
- error: (msg) => console.log('\x1b[31m%s\x1b[0m', msg),
377
- bold: (msg) => console.log('\x1b[1m%s\x1b[0m', msg),
378
- dim: (msg) => console.log('\x1b[2m%s\x1b[0m', msg)
375
+ info: paint(36),
376
+ success: paint(32),
377
+ warn: paint(33),
378
+ error: paint(31),
379
+ bold: paint(1),
380
+ dim: paint(2)
379
381
  };
380
382
 
381
383
  /**
@@ -745,6 +747,11 @@ What becomes easier, harder, or forbidden.
745
747
  PRIVATE_RUNTIME_GITIGNORE,
746
748
  { overwrite: false }
747
749
  );
750
+ try {
751
+ require('../lib/sources.js').writeSourcesFile(rootDir);
752
+ } catch {
753
+ log.dim('sources.md was not written; run `ai-engineering-loop sources refresh` later.');
754
+ }
748
755
  }
749
756
 
750
757
  /**
@@ -880,12 +887,20 @@ function handleInit() {
880
887
  log.info('Analyzing repository topology and manifests...');
881
888
  const discovery = analyzeRepository(CWD);
882
889
 
883
- log.dim(`> Profile Bound: ${discovery.profile}`);
884
- log.dim(`> Languages: ${discovery.languages.join(', ') || 'Unspecified'}`);
885
- log.dim(`> Package Manager: ${discovery.packageManager}`);
886
- log.dim(`> Unit Test Command: ${discovery.scripts.testUnit}`);
890
+ if (!Object.keys(discovery.manifestChecksums || {}).length && !discovery.languages.length) {
891
+ log.warn('> No manifest found (package.json, go.mod, pyproject.toml, ...): profile unknown, no test command. Edit .ai-engineering-loop/verification.md once the project has one.');
892
+ } else {
893
+ log.dim(`> Profile Bound: ${discovery.profile}`);
894
+ log.dim(`> Languages: ${discovery.languages.join(', ') || 'Unspecified'}`);
895
+ log.dim(`> Package Manager: ${discovery.packageManager}`);
896
+ log.dim(`> Unit Test Command: ${discovery.scripts.testUnit}`);
897
+ }
898
+ const wantedNode = Number(String(require('../package.json').engines?.node || '>=18').match(/\d+/)?.[0] || 18);
899
+ if (Number(process.versions.node.split('.')[0]) < wantedNode) log.warn(`! Node ${process.versions.node} is older than the supported ${wantedNode}; some commands may fail. FIX: install Node ${wantedNode}+.`);
887
900
 
888
- if (firstInitialization) ignoreProjectContextOnFirstInit(CWD);
901
+ if (firstInitialization && ignoreProjectContextOnFirstInit(CWD)) {
902
+ log.dim('> .gitignore now ignores .ai-engineering-loop/. Commit it on its own so it stays out of your next change: git add .gitignore && git commit -m "Ignore AEL context"');
903
+ }
889
904
  generateContextFiles(CWD, discovery, trigger, impact, { overwriteCore });
890
905
 
891
906
  const validation = validateContext(CONTEXT_DIR);
@@ -893,6 +908,7 @@ function handleInit() {
893
908
  log.success('\n✓ Successfully initialized .ai-engineering-loop/ with:');
894
909
  REQUIRED_FILES.forEach((f) => console.log(` - .ai-engineering-loop/${f}`));
895
910
  log.dim('\nProject context is private by default. Remove .ai-engineering-loop/ from .gitignore if you want to share it.');
911
+ if (!agentSkillState().installed) log.warn(SETUP_HINT);
896
912
  } else {
897
913
  log.error(`\n✗ Initialization validation failed: ${validation.reason}`);
898
914
  process.exit(1);
@@ -936,6 +952,17 @@ function statusJson() {
936
952
  return result;
937
953
  }
938
954
 
955
+ function agentSkillState() {
956
+ try {
957
+ const hosts = hostSkillStatus({ home: homeDir(), version: VERSION });
958
+ return { hosts, installed: hosts.managedFiles > 0 || Boolean(hosts.installedVersion) };
959
+ } catch {
960
+ return { hosts: null, installed: true };
961
+ }
962
+ }
963
+
964
+ const SETUP_HINT = 'Next: `ael setup` installs the ael skill into the coding agents on this machine (Claude Code, Codex, Cursor, ...); then start a new agent session. No agent yet? See README "Bring your own AI agent".';
965
+
939
966
  function handleStatus() {
940
967
  if (command === 'status' && process.argv.includes('--json')) {
941
968
  const result = statusJson();
@@ -968,21 +995,36 @@ function handleStatus() {
968
995
  log.success('Status: READY & VALID');
969
996
  console.log(`- Project Name: ${path.basename(CWD)}`);
970
997
  console.log(`- Project Profile: ${metadata.projectProfile || 'unspecified'}`);
971
- console.log(`- Context Baseline Git: ${metadata.repositoryRevision ? metadata.repositoryRevision.slice(0, 8) : 'unknown'}`);
972
- console.log(`- Living Freshness: \x1b[32m${drift.status}\x1b[0m (${drift.reason})`);
998
+ const gitState = require('../lib/git-readiness.js').gitReadiness(CWD);
999
+ const baseline = metadata.repositoryRevision && /^[0-9a-f]{7,}$/.test(metadata.repositoryRevision) ? metadata.repositoryRevision.slice(0, 8) : 'none';
1000
+ console.log(`- Context Baseline Git: ${baseline}`);
1001
+ if (gitState.ok) console.log(`- Living Freshness: ${COLOR ? `\x1b[32m${drift.status}\x1b[0m` : drift.status} (${drift.reason})`);
1002
+ else {
1003
+ log.warn(`- Git: NOT READY (${gitState.message}); a Run cannot start.`);
1004
+ log.dim(` FIX: ${gitState.fix}`);
1005
+ }
1006
+ for (const warning of gitState.warnings || []) log.warn(`- Git: ${warning}`);
973
1007
  console.log(`- Context Files: ${REQUIRED_FILES.length}/${REQUIRED_FILES.length} verified (including metadata.json, glossary.md, adrs/)`);
974
1008
 
975
1009
  const activeRun = currentRunSafe(CWD);
976
1010
  if (activeRun && !TERMINAL_STATES.has(activeRun.state)) {
977
1011
  console.log(`- Active run: ${activeRun.runId} (${activeRun.state})`);
1012
+ const provenance = require('../lib/provenance.js').loadProvenance(CWD, activeRun.runId);
1013
+ if (provenance && provenance.unconfirmed.length) {
1014
+ log.warn(`- Unconfirmed: ${provenance.unconfirmed.length} assumption(s) in the Goal (not blocking)`);
1015
+ for (const text of provenance.unconfirmed.slice(0, 5)) log.dim(` - ${text}`);
1016
+ }
978
1017
  const hint = staleRunHint(activeRun);
979
1018
  if (hint) log.warn(` ${hint}`);
980
1019
  }
981
1020
  const worktreeHint = require('../lib/run-isolation.js').pruneHint(CWD);
982
1021
  if (worktreeHint) log.warn(`- ${worktreeHint}`);
983
1022
 
984
- const hosts = hostSkillStatus({ home: homeDir(), version: VERSION });
985
- if (hosts.stale) {
1023
+ const { hosts, installed } = agentSkillState();
1024
+ if (!installed) {
1025
+ log.warn('- Host skills: NOT INSTALLED (no agent on this machine has the ael skill yet)');
1026
+ log.dim(` ${SETUP_HINT}`);
1027
+ } else if (hosts.stale) {
986
1028
  log.warn(`- Host skills: STALE (${hosts.staleFiles} file(s) behind package v${VERSION}${hosts.installedVersion ? `, installed v${hosts.installedVersion}` : ''})`);
987
1029
  log.dim(' Run "npx ai-engineering-loop sync-hosts" (or "update apply --yes" after a package upgrade), then start a new session.');
988
1030
  } else {
@@ -1337,22 +1379,55 @@ function startWorktreeRun(task, runArgs, runJson, realLog) {
1337
1379
  }
1338
1380
  }
1339
1381
 
1382
+ function handlePr() {
1383
+ const json = process.argv.includes('--json');
1384
+ try {
1385
+ if (args[1] !== 'status') throw Object.assign(new Error('Use: pr status [--run <id> | --branch <name> | --pr <number>] [--json]'), { code: 'INVALID_USAGE' });
1386
+ const explicit = argValue('--pr') || argValue('--branch');
1387
+ const runId = argValue('--run') || (explicit ? null : getCurrentRun(CWD)?.runId) || null;
1388
+ const status = require('../lib/pr-status.js').prStatus(CWD, { runId, branch: argValue('--branch'), pr: argValue('--pr') });
1389
+ if (json) console.log(JSON.stringify({ ok: true, ...status }, null, 2));
1390
+ else {
1391
+ console.log(`PR #${status.pr} (${status.branch || 'branch unknown'}): ${status.verdict}`);
1392
+ for (const blocker of status.blockers) console.log(`- blocker: ${blocker}`);
1393
+ for (const item of status.waitingOn || []) console.log(`- waiting on: ${item}`);
1394
+ if (status.mergeRecorded) console.log(`- recorded runs/${status.runId}/merge.json`);
1395
+ console.log(`- ${status.url}`);
1396
+ }
1397
+ } catch (err) {
1398
+ if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'PR_STATUS_FAILED', error: err.message, ...(err.fix ? { fix: err.fix } : {}) }));
1399
+ else {
1400
+ log.error(err.message);
1401
+ if (err.fix) console.error(`FIX: ${err.fix}`);
1402
+ }
1403
+ process.exitCode = 1;
1404
+ }
1405
+ }
1406
+
1340
1407
  function handleWorktree() {
1341
1408
  const json = process.argv.includes('--json');
1342
1409
  const isolation = require('../lib/run-isolation.js');
1343
1410
  try {
1344
- if (args[1] !== 'prune') throw Object.assign(new Error('Use: worktree prune [--yes] [--json]'), { code: 'INVALID_USAGE' });
1411
+ if (args[1] !== 'prune') throw Object.assign(new Error('Use: worktree prune [--audit] [--include-scratch] [--yes] [--json]'), { code: 'INVALID_USAGE' });
1412
+ const includeScratch = process.argv.includes('--include-scratch');
1345
1413
  if (!process.argv.includes('--yes')) {
1346
- const { plan } = isolation.planPrune(CWD);
1414
+ const audit = process.argv.includes('--audit');
1415
+ const { plan } = isolation.planPrune(CWD, { includeScratch, audit, sizes: true });
1347
1416
  if (json) console.log(JSON.stringify({ ok: true, applied: false, plan }, null, 2));
1348
1417
  else if (!plan.length) log.success('✓ No AEL worktree needs cleanup');
1349
1418
  else {
1350
- for (const row of plan) console.log(`- ${row.path} [${row.runState || 'unknown'}]: ${[...row.actions, ...row.notes].join('; ')}`);
1351
- console.log('Apply with: ai-engineering-loop worktree prune --yes (uncommitted or unmerged work is never removed)');
1419
+ const mb = (bytes) => (bytes == null ? '?' : `${(bytes / 1048576).toFixed(1)} MB`);
1420
+ console.log('SIZE\tAGE\tBUCKET\tRUN\tWORKTREE');
1421
+ for (const row of plan) {
1422
+ console.log(`${mb(row.sizeBytes)}\t${row.ageDays == null ? '?' : `${row.ageDays}d`}\t${row.bucket}\t${row.runState || '-'}\t${row.path}`);
1423
+ const what = [...row.actions, ...row.notes];
1424
+ if (what.length) console.log(` ${what.join('; ')}`);
1425
+ }
1426
+ console.log('Apply with: ai-engineering-loop worktree prune --yes [--include-scratch] (changed tracked files, open PRs and foreign worktrees are never removed)');
1352
1427
  }
1353
1428
  return;
1354
1429
  }
1355
- const result = isolation.applyPrune(CWD);
1430
+ const result = isolation.applyPrune(CWD, { includeScratch });
1356
1431
  if (json) console.log(JSON.stringify({ ok: true, applied: true, ...result }, null, 2));
1357
1432
  else if (!result.done.length) log.success('✓ Nothing to clean up');
1358
1433
  else for (const item of result.done) console.log(`✓ ${item.action}: ${item.path}`);
@@ -1429,6 +1504,16 @@ function currentRunSafe(dir) {
1429
1504
  function handleRun() {
1430
1505
  if (process.argv.includes('--abandon')) return handleRunAbandon();
1431
1506
  const runJson = process.argv.includes('--json');
1507
+ const gitState = require('../lib/git-readiness.js').gitReadiness(CWD);
1508
+ if (!gitState.ok) {
1509
+ if (runJson) console.log(JSON.stringify({ ok: false, code: gitState.code, error: `Cannot start a Run: ${gitState.message}.`, why: gitState.why, fix: gitState.fix }));
1510
+ else {
1511
+ log.error(`Cannot start a Run: ${gitState.message}.`);
1512
+ console.error(`WHY: ${gitState.why}`);
1513
+ console.error(`FIX: ${gitState.fix}`);
1514
+ }
1515
+ process.exit(1);
1516
+ }
1432
1517
  const realLog = console.log;
1433
1518
  if (runJson) console.log = () => {};
1434
1519
  log.info('AI Engineering Loop — Task Execution Entrypoint (run)');
@@ -1460,6 +1545,9 @@ function handleRun() {
1460
1545
  let runResult;
1461
1546
  try {
1462
1547
  const current = getCurrentRun(CWD);
1548
+ if (!task && (forceNew || !current || TERMINAL_STATES.has(current.state))) {
1549
+ throw Object.assign(new Error('run needs a task when no Run is in progress'), { code: 'INVALID_USAGE', why: 'A Run is bound to one task; an empty task cannot be tiered, gated or delivered.', fix: 'ai-engineering-loop run "Add CSV export to the report page"' });
1550
+ }
1463
1551
  if (!forceNew) {
1464
1552
  const conflict = require('../lib/run-isolation.js').runConflict(CWD, current, task);
1465
1553
  if (conflict) {
@@ -1528,10 +1616,12 @@ function handleRun() {
1528
1616
  } catch (err) {
1529
1617
  console.log = realLog;
1530
1618
  if (runJson) {
1531
- realLog(JSON.stringify({ ok: false, code: err.code || 'RUN_FAILED', error: err.message, ...(err.conflict ? { conflict: err.conflict } : {}) }));
1619
+ realLog(JSON.stringify({ ok: false, code: err.code || 'RUN_FAILED', error: err.message, ...(err.why ? { why: err.why } : {}), ...(err.fix ? { fix: err.fix } : {}), ...(err.conflict ? { conflict: err.conflict } : {}) }));
1532
1620
  process.exit(err.code === 'RUN_CONFLICT' ? 3 : 1);
1533
1621
  }
1534
1622
  log.error(err.message);
1623
+ if (err.why) console.error(`WHY: ${err.why}`);
1624
+ if (err.fix) console.error(`FIX: ${err.fix}`);
1535
1625
  if (err.conflict) {
1536
1626
  for (const option of err.conflict.options) console.log(`- ${option.id === err.conflict.recommended ? '(recommended) ' : ''}${option.label}: ${option.command}`);
1537
1627
  process.exit(3);
@@ -1602,7 +1692,11 @@ function handleRun() {
1602
1692
  const grok = detectGrokHost();
1603
1693
 
1604
1694
  console.log('\n------------------------------------------------------------');
1605
- log.bold('AI Agent Ready:');
1695
+ if (!agentSkillState().installed) {
1696
+ log.warn('No agent has the ael skill yet, so nothing will pick up this Run on its own.');
1697
+ log.dim(SETUP_HINT);
1698
+ }
1699
+ log.bold('Agent checklist:');
1606
1700
  console.log('1. Grill if needed (docs grill-policy), then freeze a failure-table Goal Contract');
1607
1701
  if (runResult.run.mode === RUN_MODES.REPORT_ONLY) {
1608
1702
  console.log('2. Analyze evidence without changing repository files');
@@ -1917,6 +2011,16 @@ function handleArtifactTool(action) {
1917
2011
  try {
1918
2012
  if (action === 'scaffold') {
1919
2013
  const type = process.argv[3];
2014
+ if (type === 'goal') {
2015
+ const goal = require('../lib/agent-artifacts.js').scaffoldGoal(CWD, { runId: argValue('--run') });
2016
+ if (json) console.log(JSON.stringify({ ok: true, ...goal, templateOnly: true }));
2017
+ else {
2018
+ log.success('✓ Goal Contract template created');
2019
+ console.log(`- Path: ${goal.path}`);
2020
+ console.log(`- Next: fill in every <...>, delete _templateOnly, then \`${goal.nextCommand}\`.`);
2021
+ }
2022
+ return;
2023
+ }
1920
2024
  const result = scaffoldArtifact(CWD, { type, runId: argValue('--run') });
1921
2025
  if (json) console.log(JSON.stringify({ ok: true, ...result, templateOnly: true }));
1922
2026
  else {
@@ -1940,7 +2044,7 @@ function handleArtifactTool(action) {
1940
2044
  if (!result.valid) process.exitCode = 1;
1941
2045
  return;
1942
2046
  }
1943
- throw new Error('Use scaffold <verification|findings|delivery> or validate <file>');
2047
+ throw new Error('Use scaffold <goal|verification|findings|delivery> or validate <file>');
1944
2048
  } catch (err) {
1945
2049
  if (json) console.log(JSON.stringify({ ok: false, code: err.code || 'ARTIFACT_TOOL_FAILED', error: err.message }));
1946
2050
  else log.error(err.message);
@@ -2049,6 +2153,7 @@ function recordImpactDrift(runId) {
2049
2153
  // UNATTENDED diffs come from `sandbox capture`.
2050
2154
  function captureMakerDiff(run) {
2051
2155
  if (run.mode === 'UNATTENDED') throw new Error('--from-git is not allowed in UNATTENDED; use `sandbox capture`.');
2156
+ require('../lib/git-readiness.js').assertGitReady(CWD);
2052
2157
  const { execFileSync } = require('child_process');
2053
2158
  const exclude = ':(exclude).ai-engineering-loop';
2054
2159
  const git = (args, allowExit1 = false) => {
@@ -2060,7 +2165,8 @@ function captureMakerDiff(run) {
2060
2165
  }
2061
2166
  };
2062
2167
  let diff = git(['diff', '--binary', 'HEAD', '--', '.', exclude]);
2063
- const untracked = git(['ls-files', '--others', '--exclude-standard', '-z', '--', '.', exclude]).split('\0').filter(Boolean);
2168
+ const aelOnlyIgnore = (file) => file === '.gitignore' && (readFileSafe(path.join(CWD, file)) || '').trim().replace(/\/+$/, '') === '.ai-engineering-loop';
2169
+ const untracked = git(['ls-files', '--others', '--exclude-standard', '-z', '--', '.', exclude]).split('\0').filter(Boolean).filter((file) => !aelOnlyIgnore(file));
2064
2170
  for (const file of untracked) diff += git(['diff', '--binary', '--no-index', '--', '/dev/null', file], true);
2065
2171
  if (!diff.trim()) throw new Error('--from-git found no changes against HEAD.');
2066
2172
  const target = path.join(CWD, '.ai-engineering-loop', 'runs', run.runId, 'diff.patch');
@@ -2081,11 +2187,20 @@ function handleGate() {
2081
2187
  const gate = process.argv[3];
2082
2188
  const runId = argValue('--run');
2083
2189
  const json = process.argv.includes('--json');
2190
+ if (!gate || gate.startsWith('-')) {
2191
+ stageJsonError(Object.assign(new Error('gate needs a name: goal, maker, review, judge, delivery or report'), { code: 'INVALID_USAGE', why: 'Each gate checks one stage of the Run.', fix: '`ai-engineering-loop status` shows the current stage; then e.g. `ai-engineering-loop gate goal --run <id>`.' }), json, 'INVALID_USAGE');
2192
+ }
2084
2193
  let targetRunId = runId;
2085
2194
  try {
2086
2195
  const target = runId ? loadRun(CWD, runId) : getCurrentRun(CWD);
2087
2196
  if (!target) throw new Error('No current run. Start one with `ai-engineering-loop run`.');
2088
2197
  targetRunId = target.runId;
2198
+ if (gate === 'judge' && ['JUDGED_PASS', 'DELIVERED'].includes(target.state)) {
2199
+ const next = target.state === 'DELIVERED' ? 'nothing; the Run is delivered' : `deliver --run ${target.runId} --approve --by <name>`;
2200
+ if (json) console.log(JSON.stringify({ ok: true, runId: target.runId, state: target.state, gate, alreadyPassed: true, next }));
2201
+ else console.log(`✓ judge already PASS for ${target.runId}. Next: ${next}`);
2202
+ return;
2203
+ }
2089
2204
  if (process.argv.includes('--from-git')) {
2090
2205
  if (gate !== 'maker') throw new Error('--from-git only applies to `gate maker`.');
2091
2206
  captureMakerDiff(target);
@@ -2484,10 +2599,15 @@ function handleDoctor() {
2484
2599
  }
2485
2600
  return;
2486
2601
  }
2487
- const result = runDoctor(path.join(__dirname, '..'), { projectDir: CWD });
2488
- if (json) console.log(JSON.stringify(result));
2602
+ const packageScope = process.argv.includes('--package');
2603
+ const skill = agentSkillState();
2604
+ const result = packageScope
2605
+ ? runDoctor(path.join(__dirname, '..'), { projectDir: CWD })
2606
+ : require('../lib/doctor.js').machineChecks(path.join(__dirname, '..'), { projectDir: CWD, hostSkills: skill.hosts ? { installed: skill.installed, stale: skill.hosts.stale, staleFiles: skill.hosts.staleFiles } : null });
2607
+ if (json) console.log(JSON.stringify({ ...result, scope: packageScope ? 'package' : 'machine' }));
2489
2608
  else {
2490
- console.log(`AI Engineering Loop doctor: ${result.ok ? 'READY' : 'NOT READY'}`);
2609
+ const warned = result.checks.some((check) => !check.passed && check.level === 'warn');
2610
+ console.log(`AI Engineering Loop doctor${packageScope ? ' (package)' : ''}: ${result.ok ? (warned ? 'READY (warnings)' : 'READY') : 'NOT READY'}`);
2491
2611
  for (const check of result.checks) {
2492
2612
  console.log(`${check.passed ? '✓' : check.level === 'warn' ? '!' : '✗'} ${check.id}: ${check.detail}`);
2493
2613
  }
@@ -3171,6 +3291,8 @@ function readBoundedJsonInput(fileName) {
3171
3291
  if (!fileName) {
3172
3292
  const error = new Error('goal draft requires --file <json> or --from-design <doc.md>');
3173
3293
  error.code = 'INVALID_USAGE';
3294
+ error.why = 'The Goal Contract is a JSON file: objective, acceptance criteria with evidence and failure cases.';
3295
+ error.fix = '`ai-engineering-loop scaffold goal` writes a template to .ai-engineering-loop/drafts/goal.json; fill it in, then `goal draft --file .ai-engineering-loop/drafts/goal.json --revision 0`.';
3174
3296
  throw error;
3175
3297
  }
3176
3298
  const file = path.resolve(CWD, fileName);
@@ -3214,6 +3336,11 @@ function handleGoal() {
3214
3336
  const extra = {};
3215
3337
  if (action === 'show') {
3216
3338
  result = loadGoalDraft(CWD, runId);
3339
+ if (process.argv.includes('--human')) {
3340
+ if (!result) throw Object.assign(new Error('No Goal draft yet'), { code: 'GOAL_DRAFT_MISSING', fix: '`scaffold goal`, fill it in, then `goal draft --file .ai-engineering-loop/drafts/goal.json --revision 0`.' });
3341
+ process.stdout.write(require('../lib/ste.js').renderHumanGoal(result.contract, { runId, revision: result.metadata?.revision }));
3342
+ return;
3343
+ }
3217
3344
  if (result?.contract?.designRef) extra.design = require('../lib/design-ref.js').designStatus(CWD, result.contract.designRef);
3218
3345
  } else if (action === 'draft') {
3219
3346
  appendRunLifecycle(CWD, runId, {
@@ -3240,11 +3367,24 @@ function handleGoal() {
3240
3367
  } else {
3241
3368
  draftGoal = readBoundedJsonInput(argValue('--file'));
3242
3369
  }
3370
+ if (draftGoal && draftGoal._templateOnly === true) {
3371
+ throw Object.assign(new Error(`${argValue('--file')} is still the scaffold template`), { code: 'TEMPLATE_ONLY', why: 'A template with <...> placeholders would freeze a Goal nobody wrote.', fix: 'Replace every <...> with the real goal, delete `_templateOnly` and `_howTo`, then rerun `goal draft`.' });
3372
+ }
3373
+ const draftFile = argValue('--file');
3374
+ if (draftFile && !path.resolve(CWD, draftFile).startsWith(path.join(CWD, '.ai-engineering-loop') + path.sep)) {
3375
+ extra.warning = `Goal draft file ${draftFile} is outside .ai-engineering-loop/, so it will show up in the Maker diff. Keep drafts in .ai-engineering-loop/drafts/.`;
3376
+ console.error(`! ${extra.warning}`);
3377
+ }
3243
3378
  result = saveGoalDraft(CWD, runId, draftGoal, {
3244
3379
  actor: argValue('--by') || 'agent',
3245
3380
  expectedRevision: requiredIntegerArg('--revision')
3246
3381
  });
3247
3382
  extra.impactPreview = impactPreview(runId, draftGoal);
3383
+ const ste = require('../lib/ste.js');
3384
+ const humanPath = path.join(runsDir(CWD), runId, 'goal.md');
3385
+ fs.writeFileSync(humanPath, ste.renderHumanGoal(draftGoal, { runId, revision: result.metadata?.revision }), { mode: 0o600 });
3386
+ extra.human = { path: path.relative(CWD, humanPath).split(path.sep).join('/'), show: `goal show --run ${runId} --human` };
3387
+ extra.readability = ste.goalReadability(draftGoal);
3248
3388
  if (draftGoal && draftGoal.flow != null) {
3249
3389
  const flowLib = require('../lib/flow.js');
3250
3390
  extra.flow = { table: flowLib.renderFlow(draftGoal.flow), mermaid: flowLib.renderMermaid(draftGoal.flow), problems: flowLib.flowProblems(draftGoal.flow), warnings: flowLib.flowWarnings(draftGoal.flow), ...flowLib.flowCounts(draftGoal) };
@@ -3331,10 +3471,29 @@ function handleGoal() {
3331
3471
  error.code = 'INVALID_USAGE';
3332
3472
  throw error;
3333
3473
  }
3474
+ if (!process.argv.includes('--json') && ['draft', 'freeze'].includes(action)) {
3475
+ const meta = result?.metadata || {};
3476
+ log.success(`✓ goal ${action}: Run ${runId}${meta.revision != null ? `, revision ${meta.revision}` : ''}${meta.contentHash ? ` (${String(meta.contentHash).slice(0, 12)})` : ''}`);
3477
+ if (action === 'draft' && extra.human) {
3478
+ console.log('');
3479
+ process.stdout.write(fs.readFileSync(path.join(CWD, extra.human.path), 'utf8'));
3480
+ console.log('');
3481
+ }
3482
+ if (extra.impactPreview) console.log(`- Impact preview: ${JSON.stringify(extra.impactPreview).slice(0, 200)}`);
3483
+ if (extra.warning) console.log(`! ${extra.warning}`);
3484
+ console.log(action === 'draft' ? `- Next: the human reads this and says freeze; then \`goal freeze --latest --run ${runId} --by <name>\`. Agents: add --json.` : '- Next: Maker (implement), then `gate maker --from-git`. Agents: add --json.');
3485
+ return;
3486
+ }
3334
3487
  console.log(JSON.stringify({ ok: true, runId, [action === 'show' ? 'draft' : 'result']: result, ...extra }, null, 2));
3335
3488
  } catch (error) {
3336
- log.error(`${error.code || 'GOAL_FAILED'}: ${error.message}`);
3337
3489
  process.exitCode = 1;
3490
+ if (process.argv.includes('--json')) {
3491
+ console.log(JSON.stringify({ ok: false, code: error.code || 'GOAL_FAILED', error: error.message, ...(error.why ? { why: error.why } : {}), ...(error.fix ? { fix: error.fix } : {}) }));
3492
+ return;
3493
+ }
3494
+ log.error(`${error.code || 'GOAL_FAILED'}: ${error.message}`);
3495
+ if (error.why) console.error(`WHY: ${error.why}`);
3496
+ if (error.fix) console.error(`FIX: ${error.fix}`);
3338
3497
  }
3339
3498
  }
3340
3499
 
@@ -3539,14 +3698,15 @@ function splitCommand(text, shell) {
3539
3698
 
3540
3699
  function stageJsonError(err, json, code) {
3541
3700
  if (json) {
3542
- console.log(JSON.stringify({ ok: false, code: err.code || code, error: err.message, ...(err.why ? { why: err.why } : {}), ...(err.fix ? { fix: err.fix } : {}), details: err.details || [] }));
3701
+ console.log(JSON.stringify({ ok: false, code: err.code || code, error: err.message, ...(err.why ? { why: err.why } : {}), ...(err.fix ? { fix: err.fix } : {}), details: err.details || [], ...(err.conflict ? { conflict: err.conflict } : {}) }));
3543
3702
  } else {
3544
3703
  log.error(err.message);
3545
3704
  if (err.why) console.error(`WHY: ${err.why}`);
3546
- if (err.fix) console.error(`FIX: ${err.fix}`);
3705
+ if (err.fix && !err.conflict) console.error(`FIX: ${err.fix}`);
3706
+ for (const option of err.conflict ? err.conflict.options : []) console.error(`- ${option.id === err.conflict.recommended ? '(recommended) ' : ''}${option.label}: ${option.command}`);
3547
3707
  for (const detail of err.details || []) console.error(`- ${detail}`);
3548
3708
  }
3549
- process.exit(1);
3709
+ process.exit(err.code === 'RUN_CONFLICT' ? 3 : 1);
3550
3710
  }
3551
3711
 
3552
3712
  function repeatedArg(name) {
@@ -4101,6 +4261,8 @@ function handleReviewPack() {
4101
4261
  const featureMap = require('../lib/feature-map.js');
4102
4262
  touchedFeatures = featureMap.featuresForFiles(CWD, changed);
4103
4263
  if (touchedFeatures.length && pack.path) fs.appendFileSync(path.join(CWD, pack.path), `${featureMap.renderForPack(touchedFeatures)}\n`);
4264
+ const unconfirmed = require('../lib/provenance.js').renderUnconfirmed(require('../lib/provenance.js').loadProvenance(CWD, runId), '## Unconfirmed assumptions in the Goal (raise a finding if the code relies on one)');
4265
+ if (unconfirmed.length && pack.path) fs.appendFileSync(path.join(CWD, pack.path), `\n${unconfirmed.join('\n')}\n`);
4104
4266
  } catch {
4105
4267
  openDebt = [];
4106
4268
  }
@@ -4155,7 +4317,11 @@ function handleDeliver() {
4155
4317
  throw Object.assign(new Error('REPORT_ONLY runs finish with gate report, not deliver.'), { code: 'INVALID_USAGE' });
4156
4318
  }
4157
4319
  if (mode === RUN_MODES.ASSISTED && !approve) {
4158
- console.error('ASSISTED delivery needs the human\'s explicit approval: deliver --approve --by <name>. Nothing was written.');
4320
+ if (!['JUDGED_PASS', 'DELIVERED'].includes(run.state)) {
4321
+ console.error(`Run ${run.runId} is ${run.state}; deliver comes after the Judge passes. Next: \`ai-engineering-loop status\` shows the stage to finish. Nothing was written.`);
4322
+ } else {
4323
+ console.error('ASSISTED delivery needs the human\'s explicit approval: deliver --approve --by <name>. Nothing was written.');
4324
+ }
4159
4325
  process.exit(2);
4160
4326
  }
4161
4327
  if (approve && !by) {
@@ -4412,6 +4578,99 @@ function handleQuick() {
4412
4578
  }
4413
4579
  }
4414
4580
 
4581
+ function handleSources() {
4582
+ const json = process.argv.includes('--json');
4583
+ const action = args[1] || 'show';
4584
+ const sources = require('../lib/sources.js');
4585
+ try {
4586
+ if (action === 'refresh' || action === 'show') {
4587
+ const result = action === 'refresh' ? sources.writeSourcesFile(CWD) : { path: sources.SOURCES_FILE, sources: sources.detectSources(CWD) };
4588
+ if (json) {
4589
+ console.log(JSON.stringify({ ok: true, ...result }, null, 2));
4590
+ return;
4591
+ }
4592
+ for (const item of result.sources) console.log(`${item.available ? '✓' : '-'} ${item.id}: ${item.detail}`);
4593
+ if (action === 'refresh') console.log(`Wrote ${result.path}; edit its Scope section to limit channels and labels.`);
4594
+ return;
4595
+ }
4596
+ const runId = action === 'record' ? requiredRunId('sources record') : (argValue('--run') || currentRunSafe(CWD)?.runId);
4597
+ const run = runId ? loadRun(CWD, runId) : null;
4598
+ if (action === 'hint') {
4599
+ const result = sources.gatherHints(CWD, run);
4600
+ if (json) {
4601
+ console.log(JSON.stringify({ ok: true, ...result }, null, 2));
4602
+ return;
4603
+ }
4604
+ console.log(`Gather budget ${result.tier}: ${result.used}/${result.budget} used. Stop once every Goal statement has a source.`);
4605
+ for (const item of result.hints) console.log(`- ${item.source}: ${item.try}`);
4606
+ return;
4607
+ }
4608
+ if (action === 'record') {
4609
+ const result = sources.recordGather(CWD, run, { source: argValue('--source'), ref: argValue('--ref'), line: argValue('--line') });
4610
+ if (json) console.log(JSON.stringify({ ok: true, ...result }, null, 2));
4611
+ else console.log(`✓ ${result.entry.id} recorded (${result.used}/${result.budget}). Cite it as source "${result.entry.id}" on a Goal fact.`);
4612
+ return;
4613
+ }
4614
+ throw Object.assign(new Error('Use: sources [show|refresh|hint|record] [--run <id>] [--source <id> --ref <ref> --line <text>] [--json]'), { code: 'INVALID_USAGE' });
4615
+ } catch (err) {
4616
+ stageJsonError(err, json, 'SOURCES_FAILED');
4617
+ }
4618
+ }
4619
+
4620
+ function handleDriver() {
4621
+ const json = process.argv.includes('--json');
4622
+ try {
4623
+ if (args[1] !== 'scaffold') throw Object.assign(new Error('Use: driver scaffold [--feature <id>] [--surface web|api|cli|launch] [--json]'), { code: 'INVALID_USAGE' });
4624
+ const results = require('../lib/driver-scaffold.js').scaffoldDriver(CWD, { feature: argValue('--feature'), surface: argValue('--surface') });
4625
+ if (json) {
4626
+ console.log(JSON.stringify({ ok: true, drivers: results }, null, 2));
4627
+ return;
4628
+ }
4629
+ if (!results.length) log.success('✓ Every feature in the feature map already has a driver');
4630
+ for (const item of results) {
4631
+ if (item.written && item.written.endsWith('.ael-new')) console.log(`! ${item.feature}: ${item.file} was edited; new template saved as ${item.written}`);
4632
+ else if (item.written) console.log(`✓ ${item.feature} (${item.surface}): ${item.written}${item.featureMapUpdated ? ' (feature map Driver set)' : ''}`);
4633
+ else console.log(`- ${item.feature}: ${item.file} unchanged`);
4634
+ if (item.gaps.length) console.log(` missing: ${item.gaps.join(', ')} (see the .md next to the driver)`);
4635
+ }
4636
+ console.log('Fill in EXPECT and the user steps, then run the driver; it exits 0 only when the result matches.');
4637
+ } catch (err) {
4638
+ stageJsonError(err, json, 'DRIVER_FAILED');
4639
+ }
4640
+ }
4641
+
4642
+ function learnFromTranscripts(json) {
4643
+ try {
4644
+ const lessons = require('../lib/transcript-lessons.js');
4645
+ const sinceArg = String(argValue('--since') || '30d');
4646
+ if (!/^\d+d?$/.test(sinceArg)) throw Object.assign(new Error('--since must be a number of days, such as 30 or 30d'), { code: 'INVALID_USAGE' });
4647
+ const since = Number(sinceArg.replace(/d$/, ''));
4648
+ const hostArg = argValue('--host') || 'all';
4649
+ const hosts = hostArg === 'all' ? lessons.HOSTS : hostArg.split(',').map((item) => item.trim());
4650
+ const minArg = argValue('--min-sessions');
4651
+ const minSessions = minArg == null ? 2 : parsePositiveIntegerArg('--min-sessions', minArg);
4652
+ const result = lessons.mineTranscripts(CWD, { hosts, since, minSessions });
4653
+ const dryRun = process.argv.includes('--dry-run');
4654
+ const written = dryRun ? null : lessons.writeTranscriptLessons(CWD, result, { since });
4655
+ if (json) {
4656
+ console.log(JSON.stringify({ ok: true, written, ...result }, null, 2));
4657
+ return;
4658
+ }
4659
+ log.info(`Transcripts scanned (last ${since} days): ${Object.entries(result.scanned).map(([host, n]) => `${host} ${n}`).join(', ')}; ${result.corrections} correction(s) found`);
4660
+ if (!result.entries.length) {
4661
+ log.success(`✓ No correction repeated across ${minSessions}+ sessions`);
4662
+ return;
4663
+ }
4664
+ for (const entry of result.entries) {
4665
+ console.log(`- ${entry.id} ×${entry.sessions} sessions (${entry.hosts.join(', ')}): ${entry.lesson}`);
4666
+ console.log(` fix level: ${entry.suggestedFix.level} (${entry.suggestedFix.why})${entry.suggestedFix.command ? `\n try: ${entry.suggestedFix.command}` : ''}`);
4667
+ }
4668
+ console.log(written ? `Saved to ${written} (redacted examples only). Promote one with \`learn promote <id> ...\`.` : 'Dry run: nothing saved.');
4669
+ } catch (err) {
4670
+ stageJsonError(err, json, 'LEARN_TRANSCRIPTS_FAILED');
4671
+ }
4672
+ }
4673
+
4415
4674
  function handleLearn() {
4416
4675
  const json = process.argv.includes('--json');
4417
4676
  if (args[1] === 'promote') {
@@ -4435,6 +4694,7 @@ function handleLearn() {
4435
4694
  }
4436
4695
  return;
4437
4696
  }
4697
+ if (process.argv.includes('--transcripts')) return learnFromTranscripts(json);
4438
4698
  try {
4439
4699
  const maxAge = argValue('--max-age-runs');
4440
4700
  const result = learn(CWD, {
@@ -4520,6 +4780,7 @@ Commands:
4520
4780
  draft --file <json> --revision <n> [--run <id>] [--by <agent>]
4521
4781
  draft --from-design <doc.md> [--file <json>] --revision <n> prefill from a design doc, record designRef
4522
4782
  freeze --revision <n> --hash <sha256> [--run <id>] [--by <name>]
4783
+ show --human [--run <id>] the Goal as plain Markdown for people (STE style: short active sentences)
4523
4784
  freeze --latest [--run <id>] --by <name> freeze the newest draft (CLI resolves revision/hash)
4524
4785
  diagram --view state|storyboard|lanes [--run <id>] [--revision <n>] [--lang <tag>] [--open] draw the Goal flow as HTML
4525
4786
  verification Summarize verification.json for compact Judge context
@@ -4528,7 +4789,7 @@ Commands:
4528
4789
  Captures bounded, redacted output; updates verification.json and its summary
4529
4790
  --shell opts into a shell; pass one quoted command string, e.g. -- "npm test"
4530
4791
  scaffold Create a private, deliberately incomplete stage-artifact template
4531
- verification | findings | delivery [--run <id>] [--json]
4792
+ goal | verification | findings | delivery [--run <id>] [--json]
4532
4793
  validate Check a verification, findings, or delivery JSON file without advancing a gate
4533
4794
  <repository-relative-file> [--type verification|findings|delivery] [--json]
4534
4795
  activity Publish safe Run lifecycle summaries for Studio
@@ -4599,7 +4860,10 @@ Commands:
4599
4860
  calibrate Compare recorded outcomes with each Run's Finding Ledger: DA misses, wrong dismissals, per reviewer prompt
4600
4861
  debt Accepted trade-offs and L3 waivers recorded at delivery: list [--file <path>] | close <id> --by <name> [--note <text>]
4601
4862
  next Next unblocked feature from .ai-engineering-loop/features.json, VCR (verified/activated), evidence audit [--json]
4602
- worktree Clean up AEL worktrees: prune [--yes] [--json] (never removes uncommitted or unmerged work)
4863
+ worktree Clean up AEL worktrees: prune [--audit] [--include-scratch] [--yes] [--json] (never removes changed tracked files, open PRs or foreign worktrees)
4864
+ pr One read-only PR snapshot via gh: status [--run <id> | --branch <name> | --pr <n>] [--json]; records merge.json when merged
4865
+ sources Where the agent digs before asking (read-only): show | refresh | hint | record --source <id> --ref <ref> --line <text>
4866
+ driver Scaffold a reusable verification driver per feature-map row: scaffold [--feature <id>] [--surface web|api|cli|launch]
4603
4867
  safety Record the one fact a change is safe because of [record --fact <text> --cmd <proof>] (T2 Judge PASS needs level 4+)
4604
4868
  measurement Record how a performance number was measured [record --ac <id> --runs <n> --spread <pct> --effect <pct> --limiter <text>]
4605
4869
  recap Evidence-backed recap of the last N days as one HTML page [--days 7] [--for me|lead|client] [--projects <p,...>|all] [--out <file>] [--lang <tag>] [--open] [--json]
@@ -4653,10 +4917,13 @@ Commands:
4653
4917
  [--dry-run] [--prune] [--max-age-runs <n>] [--json]
4654
4918
  deterministic and deduped with runId provenance; --prune drops lessons whose files are gone
4655
4919
  or not seen in the last <n> Runs (default 20); maker / devil-advocate packs get the top entries
4920
+ --transcripts [--since 30d] [--host claude|cursor|codex|all] [--min-sessions 2] [--dry-run]: corrections you
4921
+ repeated in local agent chats become candidate lessons (redacted, read-only, never sent anywhere)
4656
4922
  docs Print a packaged spec without needing the package source tree
4657
4923
  list [--json]
4658
4924
  <name> [--section <heading>] [--json] e.g. docs grill-policy --section "When to grill"
4659
- doctor Check runtime, schemas, host assets, package contents, and eval catalog
4925
+ doctor Check this machine: Node, git, git identity, agent skill, adapter CLI and login (every problem names its FIX)
4926
+ --package release checks instead: schemas, host assets, package contents, eval catalog (npm run doctor)
4660
4927
  --harness audit harness debt instead: entry-file size/structure, stale learnings, rule provenance, skill budget
4661
4928
  --json print machine-readable diagnostics
4662
4929
  update Check or apply the package update workflow
@@ -4725,9 +4992,88 @@ function printHelp() {
4725
4992
  console.log(helpText());
4726
4993
  }
4727
4994
 
4995
+ function commandNames() {
4996
+ return [...new Set(helpText().split('\n').map((line) => (line.match(/^ ([a-z][\w-]*)(?: \[task\])?\s+(?=[A-Z])/) || [])[1]).filter(Boolean))];
4997
+ }
4998
+
4999
+ function shortHelp() {
5000
+ return `AI Engineering Loop v${VERSION}: a gated engineering loop for your coding agent.
5001
+
5002
+ Start here:
5003
+ npm i -g ai-engineering-loop Node 18+ and git required
5004
+ ael setup install the ael skill into your coding agents
5005
+ ael init write .ai-engineering-loop/ for this project
5006
+ Then tell your agent: "Use AI Engineering Loop to build <your feature>"
5007
+
5008
+ Everyday:
5009
+ ael status is this project ready, and what is running?
5010
+ ael run "<task>" start or resume a Run; the agent drives the rest
5011
+ ael quick start "<task>" a tiny change in two calls (T0)
5012
+ ael studio watch the Run in your browser
5013
+ ael doctor check this machine (git, agent skill, gh/glab)
5014
+
5015
+ Help:
5016
+ ael help <command> usage for one command
5017
+ ael help --all every command and flag
5018
+ ael docs list specs and policies
5019
+
5020
+ All commands: ${commandNames().join(', ')}`;
5021
+ }
5022
+
5023
+ function editDistance(a, b) {
5024
+ const row = Array.from({ length: b.length + 1 }, (_, index) => index);
5025
+ for (let i = 1; i <= a.length; i += 1) {
5026
+ let previous = row[0];
5027
+ row[0] = i;
5028
+ for (let j = 1; j <= b.length; j += 1) {
5029
+ const saved = row[j];
5030
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
5031
+ previous = saved;
5032
+ }
5033
+ }
5034
+ return row[b.length];
5035
+ }
5036
+
5037
+ function startMenu() {
5038
+ return `AI Engineering Loop v${VERSION}
5039
+ No .ai-engineering-loop/ in this folder yet. Pick one:
5040
+ 1. Build my workflow ael init (then \`ael setup\` if your agent does not have the skill yet)
5041
+ 2. Start a task ael run "<task>"
5042
+ 3. Check this project ael status
5043
+ Help: ael help. Nothing was written.`;
5044
+ }
5045
+
4728
5046
  // CLI Router
4729
5047
  const args = process.argv.slice(2);
4730
- const command = args[0] || 'init';
5048
+ const printNow = (text) => {
5049
+ const buffer = Buffer.from(`${text}\n`);
5050
+ let offset = 0;
5051
+ while (offset < buffer.length) {
5052
+ try {
5053
+ offset += fs.writeSync(1, buffer, offset);
5054
+ } catch (err) {
5055
+ if (err.code !== 'EAGAIN') throw err;
5056
+ }
5057
+ }
5058
+ };
5059
+ if (!args.length && !fs.existsSync(CONTEXT_DIR)) {
5060
+ printNow(startMenu());
5061
+ process.exit(0);
5062
+ }
5063
+ const command = args[0] || 'status';
5064
+ if (command === 'help' || ((command === '-h' || command === '--help') && args.length === 1) || ((command === '-h' || command === '--help') && args[1] === '--all')) {
5065
+ const topic = command === 'help' ? args[1] : null;
5066
+ if (topic === '--all' || args.includes('--all')) printNow(helpText());
5067
+ else if (topic) {
5068
+ const block = commandHelp(helpText(), topic);
5069
+ if (!block) {
5070
+ log.error(`No help for "${topic}". Commands: ${commandNames().join(', ')}`);
5071
+ process.exit(2);
5072
+ }
5073
+ printNow(`Usage: npx ai-engineering-loop ${block.trim()}`);
5074
+ } else printNow(shortHelp());
5075
+ process.exit(0);
5076
+ }
4731
5077
 
4732
5078
  // Side-effect guard (issue #25): help never executes a command, and writer
4733
5079
  // commands reject unknown flags before touching any file.
@@ -4826,6 +5172,15 @@ switch (command) {
4826
5172
  case 'recap':
4827
5173
  handleRecap();
4828
5174
  break;
5175
+ case 'sources':
5176
+ handleSources();
5177
+ break;
5178
+ case 'pr':
5179
+ handlePr();
5180
+ break;
5181
+ case 'driver':
5182
+ handleDriver();
5183
+ break;
4829
5184
  case 'worktree':
4830
5185
  handleWorktree();
4831
5186
  break;
@@ -4928,10 +5283,12 @@ switch (command) {
4928
5283
  break;
4929
5284
  case '-h':
4930
5285
  case '--help':
4931
- default:
4932
- if (command && command !== '-h' && command !== '--help') {
4933
- log.error(`Unknown command: ${command}`);
4934
- }
4935
- printHelp();
5286
+ console.log(shortHelp());
4936
5287
  break;
5288
+ default: {
5289
+ const best = commandNames().map((name) => ({ name, distance: editDistance(command, name) })).sort((a, b) => a.distance - b.distance)[0];
5290
+ log.error(`Unknown command: ${command}.${best && best.distance <= 2 ? ` Did you mean \`${best.name}\`?` : ''}`);
5291
+ console.error('Run `ael help` for the common commands, or `ael help --all`.');
5292
+ process.exit(2);
5293
+ }
4937
5294
  }