ai-engineering-loop 2.11.0 → 2.12.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.
@@ -12,6 +12,7 @@
12
12
  Run these when the user asks how the loop is doing, before planning work, or when a gate points at them. All read local Run files; none starts a Run.
13
13
  - `stats [--last <n>] [--json]`: failure causes by harness layer (`task_spec`, `context`, `environment`, `verification`, `state`, `model`), false-victory rate per tier, iterations to PASS, revert rate of delivered Runs (from git) and the verification share of tokens. Fix the bottleneck layer first.
14
14
  - `learn promote ... --prove <commit>`: the check must fail on the commit that introduced the mistake. `measurement record --ac <id> --runs <n> --spread <pct> --effect <pct> --limiter <text>` for `measure: true` ACs (`docs verification-loop` 3e).
15
+ - `run --worktree "<task>"` starts a task in its own git worktree when another Run is unfinished; `worktree prune [--yes]` removes finished, clean worktrees and merged branches (`docs run-isolation`).
15
16
  - `recap [--days N] [--for me|lead|client] [--projects <p,...>|all]`: one HTML page of what shipped, with evidence (`docs recap`). Client recaps take one project.
16
17
  - `outcome record --run <id> --source mr-comment|revert|bug|incident --location <file[:line]> --summary <text> --by <name>`: a problem people found after delivery. Only record what the human reported; never invent one. Then `calibrate` lists DA misses and wrong dismissals per reviewer prompt version.
17
18
  - `debt [--file <path>]` lists trade-offs the Judge accepted and L3 waivers; `debt close <id> --by <name>` only on the human's word.
@@ -8,3 +8,4 @@
8
8
  - Long form: `node status --run <runId>`, `node approve delivery-approval --yes --by <name> --run <runId>` for each READY approval node, write `RUN_DIR/delivery.json`, then `gate delivery`. If the gate says a node is not READY, follow its prerequisite hint; never bypass approval.
9
9
  - Commit before `deliver` (its receipt binds `HEAD`; videos/screenshots: `--evidence AC-N=<https-url>`, required for `crossComponent` and rubric ACs). Paste `RUN_DIR/receipt.md` into the PR/MR Receipt section unchanged; ❌ stays ❌ (`docs pr-receipt`).
10
10
  - Only the delivery gate completes the run. It also mines lessons for the next Run.
11
+ - Worktree Run: after `deliver`, continue in `cleanup.mainCheckout` (Stage 9).
@@ -1,5 +1,6 @@
1
1
  # Stage 1: Goal Contract
2
2
 
3
+ - `run` said `RUN_CONFLICT`: the human picks an `option`.
3
4
  - If the user asks for ideas, list a short menu and wait; do not implement.
4
5
  - Ambiguous task the user can answer: grill first (`docs grill-policy`): design tree, recommended answers, never ask look-up facts. T2 adds `loop-risky`.
5
6
  - If the user prompt has no numbered AC, draft the contract (`docs goal-contract` if needed), list it, and wait. Chat agreement is not freeze.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,17 @@ All notable changes to this project are documented here. Versions follow [Semant
6
6
 
7
7
  _No changes yet._
8
8
 
9
+ ## 2.12.0 - 2026-11-21
10
+
11
+ Run isolation (cards C-37..C-40 in `docs/cards/run-isolation-2026-11-21.md`, issue #130; `docs run-isolation`).
12
+
13
+ - **Added:** `run "<task>"` with an unfinished Run on a different task returns `RUN_CONFLICT` (exit 3) with `live`, `idleMinutes`, `changedFiles`, a recommendation and exact commands to resume, start in a worktree, or abandon. A current Run with no task no longer resumes silently under a new task.
14
+ - **Added:** `run --worktree "<task>"` starts the task in a new git worktree (`ael/<slug>-<id>`) from HEAD and records it in `.ai-engineering-loop/worktrees.json`.
15
+ - **Added:** Stage 9 cleanup: after `deliver` in a worktree, run evidence is copied to the main checkout and a clean worktree is removed (branch kept until merged).
16
+ - **Added:** `worktree prune [--yes]` removes finished, clean worktrees and merged branches; `status` and `run` show a one-line hint. Uncommitted or unmerged work is never removed.
17
+ - **Changed:** `run --abandon` on a Run active in the last 15 minutes needs `--force-live`.
18
+ - **Changed:** task comparison for an unfinished Run ignores case and spacing.
19
+
9
20
  ## 2.11.0 - 2026-11-18
10
21
 
11
22
  From pstack (cards C-29..C-36 in `docs/cards/proof-not-prose-2026-11-18.md`): less human re-checking, because the CLI runs the proof instead of trusting prose.
@@ -14,7 +14,7 @@ const fs = require('fs');
14
14
  const os = require('os');
15
15
  const path = require('path');
16
16
  const { readJsonOptional, sha256: sha256Text } = require('../lib/fsutil.js');
17
- const { execSync, spawn } = require('child_process');
17
+ const { execSync, spawn, spawnSync } = require('child_process');
18
18
 
19
19
  // Command modules load on first use, so a hot path such as
20
20
  // `guard check --hook` (run before every tool call) loads only what it
@@ -929,6 +929,8 @@ function statusJson() {
929
929
  result.activeRun = { runId: activeRun.runId, state: activeRun.state, updatedAt: activeRun.updatedAt || null, stale: info.stale, idleDays: info.idleDays };
930
930
  if (info.stale) result.activeRun.hint = require('../lib/run-abandon.js').abandonCommand(activeRun.runId);
931
931
  }
932
+ const worktreeHint = require('../lib/run-isolation.js').pruneHint(CWD);
933
+ if (worktreeHint) result.worktreeHint = worktreeHint;
932
934
  }
933
935
  }
934
936
  return result;
@@ -976,6 +978,8 @@ function handleStatus() {
976
978
  const hint = staleRunHint(activeRun);
977
979
  if (hint) log.warn(` ${hint}`);
978
980
  }
981
+ const worktreeHint = require('../lib/run-isolation.js').pruneHint(CWD);
982
+ if (worktreeHint) log.warn(`- ${worktreeHint}`);
979
983
 
980
984
  const hosts = hostSkillStatus({ home: homeDir(), version: VERSION });
981
985
  if (hosts.stale) {
@@ -1298,6 +1302,65 @@ function workingTreePaths(rootDir) {
1298
1302
  // `run --abandon [--run <id>] --reason <text> --by <name> [--yes] [--json]`
1299
1303
  // (issue #46). ASSISTED asks for confirmation (or --yes); UNATTENDED runs are
1300
1304
  // refused unless a human passes --yes. Terminal runs exit 2.
1305
+ function startWorktreeRun(task, runArgs, runJson, realLog) {
1306
+ const isolation = require('../lib/run-isolation.js');
1307
+ try {
1308
+ const worktree = isolation.createWorktree(CWD, { task });
1309
+ const passthrough = [];
1310
+ for (const flag of ['--mode', '--recipe', '--tier', '--tier-reason']) {
1311
+ const value = argValue(flag);
1312
+ if (value != null) passthrough.push(flag, value);
1313
+ }
1314
+ const child = spawnSync(process.execPath, [process.argv[1], 'run', '--json', ...passthrough, task], { cwd: worktree.path, encoding: 'utf8', env: process.env });
1315
+ let started;
1316
+ try {
1317
+ started = JSON.parse(String(child.stdout || '').slice(String(child.stdout || '').indexOf('{')));
1318
+ } catch {
1319
+ started = { ok: false, error: (child.stderr || child.stdout || 'run did not start').trim() };
1320
+ }
1321
+ if (!started.ok) throw Object.assign(new Error(`Worktree created at ${worktree.path}, but the Run did not start: ${started.error}`), { code: started.code || 'RUN_FAILED' });
1322
+ isolation.registerWorktree(worktree.mainRoot, { runId: started.runId, path: worktree.path, branch: worktree.branch, base: worktree.base, task, state: 'active', createdAt: new Date().toISOString() });
1323
+ const result = { ...started, worktree: { path: worktree.path, branch: worktree.branch, mainCheckout: worktree.mainRoot }, next: `Work only in ${worktree.path} for this Run.` };
1324
+ if (runJson) realLog(JSON.stringify(result, null, 2));
1325
+ else {
1326
+ console.log = realLog;
1327
+ log.success(`✓ Run ${started.runId} started in a new worktree`);
1328
+ console.log(`- Path: ${worktree.path}`);
1329
+ console.log(`- Branch: ${worktree.branch} (from ${worktree.base.slice(0, 12)})`);
1330
+ console.log(`- Work only in that folder for this Run. After deliver, Stage 9 removes the worktree when it is clean.`);
1331
+ }
1332
+ } catch (err) {
1333
+ console.log = realLog;
1334
+ if (runJson) realLog(JSON.stringify({ ok: false, code: err.code || 'RUN_FAILED', error: err.message }));
1335
+ else log.error(err.message);
1336
+ process.exit(1);
1337
+ }
1338
+ }
1339
+
1340
+ function handleWorktree() {
1341
+ const json = process.argv.includes('--json');
1342
+ const isolation = require('../lib/run-isolation.js');
1343
+ try {
1344
+ if (args[1] !== 'prune') throw Object.assign(new Error('Use: worktree prune [--yes] [--json]'), { code: 'INVALID_USAGE' });
1345
+ if (!process.argv.includes('--yes')) {
1346
+ const { plan } = isolation.planPrune(CWD);
1347
+ if (json) console.log(JSON.stringify({ ok: true, applied: false, plan }, null, 2));
1348
+ else if (!plan.length) log.success('✓ No AEL worktree needs cleanup');
1349
+ 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)');
1352
+ }
1353
+ return;
1354
+ }
1355
+ const result = isolation.applyPrune(CWD);
1356
+ if (json) console.log(JSON.stringify({ ok: true, applied: true, ...result }, null, 2));
1357
+ else if (!result.done.length) log.success('✓ Nothing to clean up');
1358
+ else for (const item of result.done) console.log(`✓ ${item.action}: ${item.path}`);
1359
+ } catch (err) {
1360
+ stageJsonError(err, json, 'WORKTREE_FAILED');
1361
+ }
1362
+ }
1363
+
1301
1364
  function handleRunAbandon() {
1302
1365
  const json = process.argv.includes('--json');
1303
1366
  const yes = process.argv.includes('--yes');
@@ -1310,6 +1373,10 @@ function handleRunAbandon() {
1310
1373
  try {
1311
1374
  const plan = runAbandon.planAbandon(CWD, { runId: argValue('--run'), reason: argValue('--reason'), by: argValue('--by') });
1312
1375
  const { run } = plan;
1376
+ const activity = require('../lib/run-isolation.js').runActivity(CWD, run);
1377
+ if (activity.live && !process.argv.includes('--force-live')) {
1378
+ throw Object.assign(new Error(`Run ${run.runId} was active ${activity.idleMinutes} minute(s) ago; another session may still be working on it. Add --force-live only if you are sure, or start this task in a worktree: run --worktree "<task>".`), { code: 'RUN_LIVE' });
1379
+ }
1313
1380
  if (run.mode === 'UNATTENDED' && !yes) {
1314
1381
  throw Object.assign(new Error(`Run ${run.runId} is UNATTENDED. Agents must not abandon it; a human can re-run with --yes.`), { code: 'UNATTENDED_REQUIRES_HUMAN', exitCode: 2 });
1315
1382
  }
@@ -1381,7 +1448,7 @@ function handleRun() {
1381
1448
  const tierReasonArg = argValue('--tier-reason');
1382
1449
  const taskParts = [];
1383
1450
  for (let index = 0; index < runArgs.length; index++) {
1384
- if (runArgs[index] === '--new' || runArgs[index] === '--json') continue;
1451
+ if (['--new', '--json', '--worktree'].includes(runArgs[index])) continue;
1385
1452
  if (['--mode', '--recipe', '--tier', '--tier-reason'].includes(runArgs[index])) {
1386
1453
  index += 1;
1387
1454
  continue;
@@ -1389,9 +1456,16 @@ function handleRun() {
1389
1456
  taskParts.push(runArgs[index]);
1390
1457
  }
1391
1458
  const task = taskParts.join(' ').trim();
1459
+ if (runArgs.includes('--worktree')) return startWorktreeRun(task, runArgs, runJson, realLog);
1392
1460
  let runResult;
1393
1461
  try {
1394
1462
  const current = getCurrentRun(CWD);
1463
+ if (!forceNew) {
1464
+ const conflict = require('../lib/run-isolation.js').runConflict(CWD, current, task);
1465
+ if (conflict) {
1466
+ throw Object.assign(new Error(`Run ${conflict.runId} (${conflict.state}) is unfinished and works on a different task${conflict.live ? `; it was active ${conflict.idleMinutes} minute(s) ago` : ''}. Ask the human which option to take; do not pick one yourself.`), { code: 'RUN_CONFLICT', conflict });
1467
+ }
1468
+ }
1395
1469
  const policy = loadPolicy(CWD);
1396
1470
  const startsNewRun = forceNew || !current || TERMINAL_STATES.has(current.state);
1397
1471
  if (forceNew && current && !TERMINAL_STATES.has(current.state)) {
@@ -1454,10 +1528,14 @@ function handleRun() {
1454
1528
  } catch (err) {
1455
1529
  console.log = realLog;
1456
1530
  if (runJson) {
1457
- realLog(JSON.stringify({ ok: false, code: err.code || 'RUN_FAILED', error: err.message }));
1458
- process.exit(1);
1531
+ realLog(JSON.stringify({ ok: false, code: err.code || 'RUN_FAILED', error: err.message, ...(err.conflict ? { conflict: err.conflict } : {}) }));
1532
+ process.exit(err.code === 'RUN_CONFLICT' ? 3 : 1);
1459
1533
  }
1460
1534
  log.error(err.message);
1535
+ if (err.conflict) {
1536
+ for (const option of err.conflict.options) console.log(`- ${option.id === err.conflict.recommended ? '(recommended) ' : ''}${option.label}: ${option.command}`);
1537
+ process.exit(3);
1538
+ }
1461
1539
  process.exit(1);
1462
1540
  }
1463
1541
  if (runJson) {
@@ -1490,6 +1568,10 @@ function handleRun() {
1490
1568
  return { stale: h.stale, staleFiles: h.staleFiles, installedVersion: h.installedVersion, packageVersion: VERSION };
1491
1569
  })(),
1492
1570
  learnings: runLearnings(),
1571
+ ...(() => {
1572
+ const hint = require('../lib/run-isolation.js').pruneHint(CWD);
1573
+ return hint ? { worktreeHint: hint } : {};
1574
+ })(),
1493
1575
  ...specHintField(runResult),
1494
1576
  studioUrl: readStudioUrl(CWD)
1495
1577
  }, null, 2));
@@ -4145,6 +4227,14 @@ function handleDeliver() {
4145
4227
  humanApproved: delivery.humanApproved === true,
4146
4228
  receipt: receipt && { path: receipt.path, markdown: receipt.markdownPath, digest: receipt.receipt.digest, missingEvidence: receipt.missing }
4147
4229
  };
4230
+ if (next.state === 'DELIVERED') {
4231
+ try {
4232
+ const cleanup = require('../lib/run-isolation.js').cleanupAfterDeliver(CWD, runId);
4233
+ if (cleanup) result.cleanup = cleanup;
4234
+ } catch (cause) {
4235
+ result.cleanup = { error: cause.message };
4236
+ }
4237
+ }
4148
4238
  if (json) console.log(JSON.stringify(result));
4149
4239
  else {
4150
4240
  log.success('✓ delivery gate passed');
@@ -4152,6 +4242,9 @@ function handleDeliver() {
4152
4242
  if (approved.length) console.log(`- Approved: ${approved.join(', ')} by ${by}`);
4153
4243
  if (receipt) console.log(`- Receipt: ${receipt.path} (digest ${receipt.receipt.digest.slice(0, 12)}); paste ${receipt.markdownPath} into the PR/MR body`);
4154
4244
  if (receipt?.missing.length) console.log(`! Missing AC evidence (❌ in the receipt): ${receipt.missing.join(', ')}`);
4245
+ if (result.cleanup?.removed) console.log(`- Stage 9: worktree removed, evidence copied to ${result.cleanup.mainCheckout}; branch ${result.cleanup.branch} kept until merged. Continue in ${result.cleanup.mainCheckout}.`);
4246
+ else if (result.cleanup?.keptReason) console.log(`! Stage 9: worktree kept (${result.cleanup.keptReason}); evidence copied to ${result.cleanup.mainCheckout}.`);
4247
+ else if (result.cleanup?.error) console.log(`! Stage 9 cleanup failed: ${result.cleanup.error}`);
4155
4248
  }
4156
4249
  } catch (err) {
4157
4250
  stageJsonError(err, json, 'DELIVER_FAILED');
@@ -4407,11 +4500,12 @@ Commands:
4407
4500
  refresh Reconcile drifted context against repository non-destructively
4408
4501
  run [task] Start or resume a stateful engineering run and instruct the agent (never writes to home)
4409
4502
  --new start a new run even when another run is active
4503
+ --worktree start this task in a new git worktree (use when another run is unfinished)
4410
4504
  --mode report-only|assisted|unattended
4411
4505
  --recipe <id> bind an immutable compiled workflow plan
4412
4506
  --tier T0|T1|T2 --tier-reason <text> override the automatic tier (recorded)
4413
4507
  --json print runId, tier, tier reasons, subagent count, recipe, workflowSource, and studioUrl (tokenless; browser session comes from ael studio)
4414
- --abandon [--run <id>] --reason <text> --by <name> [--yes] [--json]
4508
+ --abandon [--run <id>] --reason <text> --by <name> [--yes] [--force-live] [--json]
4415
4509
  close a stale run as CANCELLED (kept on disk) and release current.json;
4416
4510
  ASSISTED asks to confirm, UNATTENDED needs --yes from a human
4417
4511
  state Inspect the current run ledger
@@ -4505,6 +4599,7 @@ Commands:
4505
4599
  calibrate Compare recorded outcomes with each Run's Finding Ledger: DA misses, wrong dismissals, per reviewer prompt
4506
4600
  debt Accepted trade-offs and L3 waivers recorded at delivery: list [--file <path>] | close <id> --by <name> [--note <text>]
4507
4601
  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)
4508
4603
  safety Record the one fact a change is safe because of [record --fact <text> --cmd <proof>] (T2 Judge PASS needs level 4+)
4509
4604
  measurement Record how a performance number was measured [record --ac <id> --runs <n> --spread <pct> --effect <pct> --limiter <text>]
4510
4605
  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]
@@ -4731,6 +4826,9 @@ switch (command) {
4731
4826
  case 'recap':
4732
4827
  handleRecap();
4733
4828
  break;
4829
+ case 'worktree':
4830
+ handleWorktree();
4831
+ break;
4734
4832
  case 'safety':
4735
4833
  handleSafety();
4736
4834
  break;
@@ -0,0 +1,55 @@
1
+ # Run isolation: one task, one checkout
2
+
3
+ Two agent sessions in one checkout corrupt each other: `gate maker --from-git` captures every uncommitted change, so a second task's diff would include the first task's work. AEL keeps one unfinished Run per checkout and moves other tasks into git worktrees (cards C-37 to C-40).
4
+
5
+ ## When another Run is unfinished (C-37)
6
+
7
+ `run "<task>"` with an unfinished current Run whose task differs (case and spacing ignored) does not start or resume anything. It exits 3 with `code: RUN_CONFLICT` and:
8
+
9
+ ```json
10
+ "conflict": {
11
+ "runId": "...", "state": "MAKER_COMPLETE", "task": "...",
12
+ "lastActivity": "2026-11-21T03:10:00.000Z", "idleMinutes": 4, "live": true,
13
+ "changedFiles": 9, "recommended": "worktree",
14
+ "options": [
15
+ { "id": "worktree", "command": "ai-engineering-loop run --worktree --json \"<task>\"" },
16
+ { "id": "resume", "command": "ai-engineering-loop run --json" },
17
+ { "id": "abandon", "command": "ai-engineering-loop run --abandon --run <id> --reason \"<why>\" --by <name> --force-live" }
18
+ ]
19
+ }
20
+ ```
21
+
22
+ - `live` means the Run changed state or logged a lifecycle event in the last 15 minutes, so another session is probably working on it.
23
+ - `recommended` is `worktree` when the Run is live or the checkout has uncommitted changes, otherwise `abandon`.
24
+ - The agent shows the options with the host's question UI and waits. It never picks one.
25
+ - The same task, or no task, still resumes the Run.
26
+ - `run --abandon` on a live Run needs `--force-live`.
27
+
28
+ ## `run --worktree "<task>"` (C-38)
29
+
30
+ Creates `<repo>.ael-worktrees/<slug>-<id>` next to the repository on branch `ael/<slug>-<id>`, from `HEAD` (uncommitted changes of the other Run stay behind), copies the AEL context files (not `runs/`, `recaps/`, `tasks/` or pointers), starts the Run there, and records it in `.ai-engineering-loop/worktrees.json` of the main checkout. `--mode`, `--recipe`, `--tier` and `--tier-reason` pass through. Work only in the printed path for that Run.
31
+
32
+ ## Stage 9: cleanup after deliver (C-39)
33
+
34
+ When `deliver` completes a Run inside a registered worktree:
35
+
36
+ 1. `runs/<id>/` is copied to the main checkout, so `stats`, `recap` and `calibrate` keep the history.
37
+ 2. If the worktree has no uncommitted or untracked changes (outside `.ai-engineering-loop/`), it is removed. Commits stay on the branch.
38
+ 3. The branch is kept until it is merged.
39
+ 4. The output's `cleanup.mainCheckout` is where the agent continues.
40
+
41
+ A dirty worktree is kept, with the reason in `cleanup.keptReason`.
42
+
43
+ ## `worktree prune` (C-40)
44
+
45
+ `ai-engineering-loop worktree prune` prints a plan; `--yes` applies it. Only worktrees in the registry are considered.
46
+
47
+ | Worktree | Action |
48
+ |---|---|
49
+ | Run delivered, cancelled or escalated, worktree clean | remove the worktree (evidence copied first) |
50
+ | Branch merged into the default branch (or a merged PR, when `gh` is available) and worktree gone | delete the branch |
51
+ | Uncommitted or untracked changes | kept, with a note |
52
+ | Run still active and idle for 7+ days | reported, so a human can abandon it there |
53
+ | Folder already deleted by hand | `git worktree prune`, entry closed |
54
+
55
+ Uncommitted or unmerged work is never removed. `status` and `run` print one line when something can be cleaned up.
package/lib/cli-args.js CHANGED
@@ -18,12 +18,13 @@ const WRITER_COMMANDS = Object.freeze({
18
18
  update: { flags: ['--json', '--yes', '--background', '--force', '--no-pin'], valued: ['--channel', '--pin'], positionals: ['check', 'plan', 'apply', 'auto', 'policy', 'rollback', ...['off', 'notify', 'patch', 'minor', 'all']] },
19
19
  projects: { flags: ['--json'], valued: ['--root', '--depth'], positionals: null },
20
20
  // `run --abandon` (issue #46) is a writer; plain `run` takes free text.
21
- 'run:abandon': { flags: ['--abandon', '--yes', '--json'], valued: ['--run', '--reason', '--by'], positionals: [] },
21
+ 'run:abandon': { flags: ['--abandon', '--yes', '--json', '--force-live'], valued: ['--run', '--reason', '--by'], positionals: [] },
22
22
  bench: {
23
23
  flags: ['--json', '--sandbox-home'],
24
24
  valued: ['--host', '--model', '--scenario', '--repeat', '--bin', '--mode', '--timeout', '--host-arg', '--without'],
25
25
  positionals: []
26
26
  },
27
+ worktree: { flags: ['--json', '--yes'], valued: [], positionals: ['prune'] },
27
28
  safety: { flags: ['--json', '--live'], valued: ['--run', '--fact', '--cmd', '--level'], positionals: ['record'] },
28
29
  measurement: { flags: ['--json'], valued: ['--run', '--ac', '--runs', '--spread', '--effect', '--limiter'], positionals: ['record'] },
29
30
  recap: { flags: ['--json', '--open'], valued: ['--days', '--for', '--projects', '--out', '--now', '--lang'], positionals: [] },
@@ -0,0 +1,293 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { execFileSync, spawnSync } = require('child_process');
6
+
7
+ const LIVE_MINUTES = 15;
8
+ const IDLE_DAYS = 7;
9
+ const REGISTRY = path.join('.ai-engineering-loop', 'worktrees.json');
10
+ const TERMINAL = new Set(['REPORTED', 'DELIVERED', 'ESCALATED', 'CANCELLED']);
11
+ const CONTEXT_SKIP = new Set(['runs', 'recaps', 'tasks', 'current.json', 'worktrees.json', 'bench-ablation.json']);
12
+
13
+ const fail = (message, code = 'INVALID_USAGE', extra = {}) => Object.assign(new Error(message), { code, ...extra });
14
+
15
+ function git(cwd, args, { allowFail = false } = {}) {
16
+ try {
17
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 }).trim();
18
+ } catch (error) {
19
+ if (allowFail) return null;
20
+ throw error;
21
+ }
22
+ }
23
+
24
+ function readJson(file) {
25
+ try {
26
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ function lastLifecycleAt(rootDir, runId) {
33
+ try {
34
+ const lines = fs.readFileSync(path.join(rootDir, '.ai-engineering-loop', 'runs', runId, 'lifecycle.jsonl'), 'utf8').trim().split('\n');
35
+ return Date.parse(JSON.parse(lines[lines.length - 1]).at) || 0;
36
+ } catch {
37
+ return 0;
38
+ }
39
+ }
40
+
41
+ function runActivity(rootDir, run, { now = new Date() } = {}) {
42
+ const last = Math.max(Date.parse(run.updatedAt || run.createdAt || 0) || 0, lastLifecycleAt(rootDir, run.runId));
43
+ const idleMinutes = last ? Math.max(0, Math.floor((now.getTime() - last) / 60000)) : null;
44
+ return { lastActivity: last ? new Date(last).toISOString() : null, idleMinutes, live: idleMinutes != null && idleMinutes < LIVE_MINUTES };
45
+ }
46
+
47
+ const normalizeTask = (text) => String(text || '').trim().replace(/\s+/g, ' ').toLowerCase();
48
+
49
+ function changedFileCount(rootDir) {
50
+ const out = git(rootDir, ['status', '--porcelain', '--', '.', ':(exclude).ai-engineering-loop'], { allowFail: true });
51
+ return out ? out.split('\n').filter(Boolean).length : 0;
52
+ }
53
+
54
+ function runConflict(rootDir, current, task, { now = new Date() } = {}) {
55
+ if (!current || TERMINAL.has(current.state)) return null;
56
+ const wanted = normalizeTask(task);
57
+ if (!wanted || wanted === normalizeTask(current.task)) return null;
58
+ const activity = runActivity(rootDir, current, { now });
59
+ const quoted = JSON.stringify(String(task).trim());
60
+ return {
61
+ runId: current.runId,
62
+ state: current.state,
63
+ task: current.task || null,
64
+ ...activity,
65
+ changedFiles: changedFileCount(rootDir),
66
+ recommended: activity.live || changedFileCount(rootDir) ? 'worktree' : 'abandon',
67
+ options: [
68
+ { id: 'worktree', label: 'New worktree for this task', command: `ai-engineering-loop run --worktree --json ${quoted}` },
69
+ { id: 'resume', label: `Resume ${current.runId} instead`, command: 'ai-engineering-loop run --json' },
70
+ { id: 'abandon', label: `Abandon ${current.runId}, then start this task`, command: `ai-engineering-loop run --abandon --run ${current.runId} --reason "<why>" --by <name>${activity.live ? ' --force-live' : ''}` }
71
+ ]
72
+ };
73
+ }
74
+
75
+ function mainCheckout(cwd) {
76
+ const common = git(cwd, ['rev-parse', '--git-common-dir'], { allowFail: true });
77
+ if (!common) return null;
78
+ return path.dirname(path.resolve(cwd, common));
79
+ }
80
+
81
+ const realpath = (p) => {
82
+ try {
83
+ return fs.realpathSync(p);
84
+ } catch {
85
+ return path.resolve(p);
86
+ }
87
+ };
88
+
89
+ function loadRegistry(mainRoot) {
90
+ return readJson(path.join(mainRoot, REGISTRY)) || { schemaVersion: 1, worktrees: [] };
91
+ }
92
+
93
+ function saveRegistry(mainRoot, registry) {
94
+ fs.mkdirSync(path.join(mainRoot, '.ai-engineering-loop'), { recursive: true });
95
+ fs.writeFileSync(path.join(mainRoot, REGISTRY), `${JSON.stringify(registry, null, 2)}\n`, { mode: 0o600 });
96
+ }
97
+
98
+ function slugOf(task) {
99
+ return normalizeTask(task).replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) || 'task';
100
+ }
101
+
102
+ function copyContext(fromRoot, toRoot) {
103
+ const from = path.join(fromRoot, '.ai-engineering-loop');
104
+ const to = path.join(toRoot, '.ai-engineering-loop');
105
+ if (!fs.existsSync(from)) return;
106
+ fs.mkdirSync(to, { recursive: true });
107
+ for (const name of fs.readdirSync(from)) {
108
+ if (CONTEXT_SKIP.has(name)) continue;
109
+ const target = path.join(to, name);
110
+ if (!fs.existsSync(target)) fs.cpSync(path.join(from, name), target, { recursive: true });
111
+ }
112
+ }
113
+
114
+ function createWorktree(rootDir, { task, now = new Date() }) {
115
+ if (!String(task || '').trim()) throw fail('run --worktree needs a task: run --worktree "<task>"');
116
+ const mainRoot = mainCheckout(rootDir);
117
+ if (!mainRoot) throw fail('run --worktree needs a git repository');
118
+ const id = now.toISOString().replace(/\D/g, '').slice(2, 12);
119
+ const slug = `${slugOf(task)}-${id}`;
120
+ const branch = `ael/${slug}`;
121
+ const worktreePath = path.join(path.dirname(mainRoot), `${path.basename(mainRoot)}.ael-worktrees`, slug);
122
+ const base = git(mainRoot, ['rev-parse', 'HEAD']);
123
+ fs.mkdirSync(path.dirname(worktreePath), { recursive: true });
124
+ git(mainRoot, ['worktree', 'add', '--quiet', '-b', branch, worktreePath, base]);
125
+ copyContext(mainRoot, worktreePath);
126
+ return { mainRoot, path: worktreePath, branch, base };
127
+ }
128
+
129
+ function registerWorktree(mainRoot, entry) {
130
+ const registry = loadRegistry(mainRoot);
131
+ registry.worktrees = registry.worktrees.filter((item) => realpath(item.path) !== realpath(entry.path)).concat(entry);
132
+ saveRegistry(mainRoot, registry);
133
+ }
134
+
135
+ function isDirty(worktreePath) {
136
+ const out = git(worktreePath, ['status', '--porcelain', '--', '.', ':(exclude).ai-engineering-loop'], { allowFail: true });
137
+ return out == null ? true : out.split('\n').filter(Boolean).length > 0;
138
+ }
139
+
140
+ function copyEvidence(worktreePath, mainRoot, runId) {
141
+ if (!runId) return false;
142
+ const from = path.join(worktreePath, '.ai-engineering-loop', 'runs', runId);
143
+ if (!fs.existsSync(from)) return false;
144
+ const to = path.join(mainRoot, '.ai-engineering-loop', 'runs', runId);
145
+ fs.mkdirSync(path.dirname(to), { recursive: true });
146
+ fs.cpSync(from, to, { recursive: true, force: true });
147
+ return true;
148
+ }
149
+
150
+ function removeWorktree(mainRoot, worktreePath) {
151
+ git(mainRoot, ['worktree', 'remove', '--force', worktreePath]);
152
+ }
153
+
154
+ function cleanupAfterDeliver(cwd, runId, { now = new Date() } = {}) {
155
+ const mainRoot = mainCheckout(cwd);
156
+ if (!mainRoot || realpath(mainRoot) === realpath(cwd)) return null;
157
+ const registry = loadRegistry(mainRoot);
158
+ const entry = registry.worktrees.find((item) => realpath(item.path) === realpath(cwd));
159
+ if (!entry) return null;
160
+ const evidenceCopied = copyEvidence(cwd, mainRoot, runId || entry.runId);
161
+ const result = { worktree: entry.path, branch: entry.branch, mainCheckout: mainRoot, evidenceCopied, removed: false };
162
+ if (isDirty(cwd)) {
163
+ result.keptReason = 'the worktree has uncommitted or untracked changes; commit or discard them, then run `worktree prune`';
164
+ entry.state = 'delivered';
165
+ } else {
166
+ removeWorktree(mainRoot, cwd);
167
+ result.removed = true;
168
+ entry.state = 'removed';
169
+ entry.removedAt = now.toISOString();
170
+ }
171
+ entry.deliveredAt = now.toISOString();
172
+ saveRegistry(mainRoot, registry);
173
+ return result;
174
+ }
175
+
176
+ function defaultBranch(mainRoot) {
177
+ const head = git(mainRoot, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], { allowFail: true });
178
+ if (head) return head.replace('refs/remotes/', '');
179
+ for (const name of ['main', 'master']) {
180
+ if (git(mainRoot, ['rev-parse', '--verify', '--quiet', name], { allowFail: true })) return name;
181
+ }
182
+ return null;
183
+ }
184
+
185
+ function isMerged(mainRoot, branch) {
186
+ if (!git(mainRoot, ['rev-parse', '--verify', '--quiet', branch], { allowFail: true })) return { merged: false, gone: true };
187
+ const target = defaultBranch(mainRoot);
188
+ if (target && spawnSync('git', ['merge-base', '--is-ancestor', branch, target], { cwd: mainRoot }).status === 0) return { merged: true };
189
+ const gh = spawnSync('gh', ['pr', 'list', '--head', branch.replace(/^origin\//, ''), '--state', 'merged', '--json', 'number'], { cwd: mainRoot, encoding: 'utf8', timeout: 15000 });
190
+ if (gh.status === 0) {
191
+ try {
192
+ if (JSON.parse(gh.stdout || '[]').length) return { merged: true };
193
+ } catch {
194
+ return { merged: false };
195
+ }
196
+ }
197
+ return { merged: false };
198
+ }
199
+
200
+ function runStateOf(entry, mainRoot) {
201
+ for (const root of [entry.path, mainRoot]) {
202
+ const state = readJson(path.join(root, '.ai-engineering-loop', 'runs', entry.runId || '-', 'state.json'));
203
+ if (state) return state;
204
+ }
205
+ return null;
206
+ }
207
+
208
+ function planPrune(rootDir, { now = new Date(), checkMerged = true } = {}) {
209
+ const mainRoot = mainCheckout(rootDir) || rootDir;
210
+ const registry = loadRegistry(mainRoot);
211
+ const plan = [];
212
+ for (const entry of registry.worktrees) {
213
+ if (entry.branchDeleted) continue;
214
+ const exists = fs.existsSync(entry.path);
215
+ const run = runStateOf(entry, mainRoot);
216
+ const state = run?.state || null;
217
+ const row = { path: entry.path, branch: entry.branch, runId: entry.runId || null, runState: state, actions: [], notes: [] };
218
+ if (!exists && entry.state !== 'removed') {
219
+ row.actions.push('forget-missing-folder');
220
+ } else if (exists) {
221
+ if (state === 'DELIVERED' || state === 'CANCELLED' || state === 'ESCALATED') {
222
+ if (isDirty(entry.path)) row.notes.push('kept: uncommitted or untracked changes');
223
+ else row.actions.push('remove-worktree');
224
+ } else if (run) {
225
+ const activity = runActivity(entry.path, run, { now });
226
+ if (activity.idleMinutes != null && activity.idleMinutes >= IDLE_DAYS * 1440) row.notes.push(`run ${run.runId} idle ${Math.floor(activity.idleMinutes / 1440)} days: abandon it there if it is dead`);
227
+ }
228
+ }
229
+ if (checkMerged && entry.branch && (state === 'DELIVERED' || entry.state === 'removed' || entry.state === 'delivered')) {
230
+ const merged = isMerged(mainRoot, entry.branch);
231
+ if (merged.merged) {
232
+ if (exists && !row.actions.includes('remove-worktree')) row.notes.push('branch merged but worktree kept until it is clean');
233
+ else row.actions.push('delete-branch');
234
+ }
235
+ }
236
+ if (row.actions.length || row.notes.length) plan.push(row);
237
+ }
238
+ return { mainRoot, plan };
239
+ }
240
+
241
+ function applyPrune(rootDir, { now = new Date() } = {}) {
242
+ const { mainRoot, plan } = planPrune(rootDir, { now });
243
+ const registry = loadRegistry(mainRoot);
244
+ const done = [];
245
+ for (const row of plan) {
246
+ const entry = registry.worktrees.find((item) => item.path === row.path);
247
+ for (const action of row.actions) {
248
+ if (action === 'remove-worktree') {
249
+ if (isDirty(row.path)) continue;
250
+ copyEvidence(row.path, mainRoot, row.runId);
251
+ removeWorktree(mainRoot, row.path);
252
+ entry.state = 'removed';
253
+ entry.removedAt = now.toISOString();
254
+ } else if (action === 'forget-missing-folder') {
255
+ git(mainRoot, ['worktree', 'prune'], { allowFail: true });
256
+ entry.state = 'removed';
257
+ entry.removedAt = now.toISOString();
258
+ } else if (action === 'delete-branch') {
259
+ if (fs.existsSync(row.path)) continue;
260
+ git(mainRoot, ['branch', '-D', row.branch], { allowFail: true });
261
+ entry.branchDeleted = true;
262
+ }
263
+ done.push({ path: row.path, action });
264
+ }
265
+ }
266
+ saveRegistry(mainRoot, registry);
267
+ return { mainRoot, done, plan };
268
+ }
269
+
270
+ function pruneHint(rootDir) {
271
+ try {
272
+ const { plan } = planPrune(rootDir, { checkMerged: false });
273
+ const ready = plan.filter((row) => row.actions.length).length;
274
+ return ready ? `${ready} AEL worktree(s) can be cleaned up: ai-engineering-loop worktree prune` : null;
275
+ } catch {
276
+ return null;
277
+ }
278
+ }
279
+
280
+ module.exports = {
281
+ IDLE_DAYS,
282
+ LIVE_MINUTES,
283
+ applyPrune,
284
+ cleanupAfterDeliver,
285
+ createWorktree,
286
+ loadRegistry,
287
+ mainCheckout,
288
+ planPrune,
289
+ pruneHint,
290
+ registerWorktree,
291
+ runActivity,
292
+ runConflict
293
+ };
package/lib/run-state.js CHANGED
@@ -303,7 +303,8 @@ function createOrResumeRun(
303
303
  const current = getCurrentRun(rootDir);
304
304
  const requestedTask = String(task || '').trim();
305
305
  if (current && !TERMINAL_STATES.has(current.state) && !forceNew) {
306
- if (requestedTask && current.task && requestedTask !== current.task) {
306
+ const same = (a, b) => String(a).trim().replace(/\s+/g, ' ').toLowerCase() === String(b).trim().replace(/\s+/g, ' ').toLowerCase();
307
+ if (requestedTask && current.task && !same(requestedTask, current.task)) {
307
308
  const err = new Error(
308
309
  `Run ${current.runId} is still ${current.state}. Resume it or pass --new to start another task.`
309
310
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-engineering-loop",
3
- "version": "2.11.0",
3
+ "version": "2.12.0",
4
4
  "description": "A visual workspace that helps AI coding agents plan, build, review, and ship reliable software.",
5
5
  "main": "bin/ai-engineering-loop.js",
6
6
  "bin": {