dorfl 0.13.2 → 0.13.4

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 (56) hide show
  1. package/dist/claim-cas.d.ts.map +1 -1
  2. package/dist/claim-cas.js +39 -0
  3. package/dist/claim-cas.js.map +1 -1
  4. package/dist/cli.d.ts.map +1 -1
  5. package/dist/cli.js +10 -1
  6. package/dist/cli.js.map +1 -1
  7. package/dist/complete.d.ts.map +1 -1
  8. package/dist/complete.js +9 -2
  9. package/dist/complete.js.map +1 -1
  10. package/dist/cwd-section.d.ts +40 -0
  11. package/dist/cwd-section.d.ts.map +1 -1
  12. package/dist/cwd-section.js +111 -5
  13. package/dist/cwd-section.js.map +1 -1
  14. package/dist/format.d.ts.map +1 -1
  15. package/dist/format.js +56 -0
  16. package/dist/format.js.map +1 -1
  17. package/dist/frontmatter.d.ts.map +1 -1
  18. package/dist/frontmatter.js +16 -4
  19. package/dist/frontmatter.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/item-lock.d.ts +167 -0
  25. package/dist/item-lock.d.ts.map +1 -1
  26. package/dist/item-lock.js +255 -1
  27. package/dist/item-lock.js.map +1 -1
  28. package/dist/needs-attention.d.ts +216 -1
  29. package/dist/needs-attention.d.ts.map +1 -1
  30. package/dist/needs-attention.js +595 -2
  31. package/dist/needs-attention.js.map +1 -1
  32. package/dist/reconcile-terminal.d.ts +97 -0
  33. package/dist/reconcile-terminal.d.ts.map +1 -0
  34. package/dist/reconcile-terminal.js +88 -0
  35. package/dist/reconcile-terminal.js.map +1 -0
  36. package/dist/scan.d.ts +17 -0
  37. package/dist/scan.d.ts.map +1 -1
  38. package/dist/scan.js +51 -2
  39. package/dist/scan.js.map +1 -1
  40. package/dist/status.d.ts +28 -0
  41. package/dist/status.d.ts.map +1 -1
  42. package/dist/status.js +79 -2
  43. package/dist/status.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/claim-cas.ts +40 -0
  46. package/src/cli.ts +18 -1
  47. package/src/complete.ts +9 -2
  48. package/src/cwd-section.ts +157 -4
  49. package/src/format.ts +72 -0
  50. package/src/frontmatter.ts +16 -4
  51. package/src/index.ts +2 -0
  52. package/src/item-lock.ts +369 -1
  53. package/src/needs-attention.ts +783 -0
  54. package/src/reconcile-terminal.ts +180 -0
  55. package/src/scan.ts +82 -5
  56. package/src/status.ts +131 -6
@@ -4,11 +4,11 @@ import { join } from 'node:path';
4
4
  import { workFolderPrefix, workFolderRel, workItemRel, isWorkItemFile, } from './work-layout.js';
5
5
  import { run, runAsync } from './git.js';
6
6
  import { branchAheadOf, rebaseContinuedBranchOntoMain, } from './continue-branch.js';
7
- import { acquireItemLock, releaseItemLock, readItemLock, itemLockRef, lockEntryFor, parseLockEntry, } from './item-lock.js';
7
+ import { acquireItemLock, releaseItemLock, readItemLock, itemLockRef, lockEntryFor, refreshMainRef, parseLockEntry, } from './item-lock.js';
8
8
  import { ledgerWrite } from './ledger-write.js';
9
9
  import { workBranchRef } from './slug-namespace.js';
10
10
  import { refreshArbiterRefs, resolveArbiterBranch } from './arbiter-refs.js';
11
- import { appendQuestions, isEntryAnswered, newSidecar, parseSidecar, resolveSidecarIdentity, serialiseSidecar, sidecarPathFor, } from './sidecar.js';
11
+ import { appendQuestions, isEntryAnswered, newSidecar, parseSidecar, resolveSidecarIdentity, serialiseSidecar, sidecarPathFor, sidecarPathCandidates, } from './sidecar.js';
12
12
  import { parseFrontmatter, setNeedsAnswersMarker } from './frontmatter.js';
13
13
  import { retryWithBackoff, realSleep, } from './retry-backoff.js';
14
14
  /**
@@ -1306,6 +1306,599 @@ export function prepareTreelessSurfaceCommit(params) {
1306
1306
  rmSync(scratchIndex, { force: true });
1307
1307
  }
1308
1308
  }
1309
+ /**
1310
+ * The terminal `work/` paths for an item, tagged by {@link TerminalKind}, so a
1311
+ * reader can tell "the work happened" from "the item was abandoned".
1312
+ *
1313
+ * Same SHAPE as `terminalMainPaths` in `item-lock.ts`, but deliberately NOT the
1314
+ * same folder set, and the difference must not be "tidied" away: locks treat
1315
+ * `specs/tasked/` as terminal (correctly, a tasked spec must release its lock),
1316
+ * whereas QUESTION state there is still live. This map is keyed to "is the
1317
+ * question loop CLOSED at this resting place?", not "has the item stopped
1318
+ * moving?". See the `case 'spec'` comment below.
1319
+ */
1320
+ export function terminalMainPathsByKind(type, slug) {
1321
+ const file = `${slug}.md`;
1322
+ switch (type) {
1323
+ case 'task':
1324
+ return [
1325
+ { path: workItemRel('done', file), kind: 'completed' },
1326
+ { path: workItemRel('cancelled', file), kind: 'wont-proceed' },
1327
+ ];
1328
+ case 'spec':
1329
+ // `specs/tasked/` is deliberately NOT listed. WORK-CONTRACT ("A SPEC that
1330
+ // has drifted AFTER it was TASKED") makes a bare `needsAnswers:true` on a
1331
+ // tasked spec LEGAL and load-bearing: it means "tasked, but the spec has
1332
+ // drifted, do not RE-task or rely on it until reconciled", and the
1333
+ // contract says to set it *while the spec stays in `specs/tasked/`*
1334
+ // (moving it back would falsely un-record a tasking that really happened
1335
+ // and orphan the tasks it already emitted).
1336
+ //
1337
+ // So the reasoning that makes a task's question state moot at its terminal
1338
+ // does NOT transfer: a tasked spec is still IN the question loop.
1339
+ // `lifecycle-gather.ts` enumerates tasked resting specs UNCONDITIONALLY,
1340
+ // routing a bare flag to the SURFACE rung and an answered sidecar to the
1341
+ // APPLY rung, so BOTH halves are live inputs to a rung that WILL run.
1342
+ // Draining either would disarm a live drift gate and let a stale spec be
1343
+ // re-tasked. That is precisely the "clearing a live needsAnswers hands gated work
1344
+ // to agents" harm this pass exists to avoid.
1345
+ //
1346
+ // `specs/dropped/` needs no such carve-out: a dropped spec is abandoned,
1347
+ // and no rung enumerates it.
1348
+ return [{ path: workItemRel('specs-dropped', file), kind: 'wont-proceed' }];
1349
+ case 'observation':
1350
+ // A note has no durable terminal folder: it leaves by DELETION, so there
1351
+ // is no resting record to reconcile against.
1352
+ return [];
1353
+ }
1354
+ }
1355
+ /** Every SUCCESS-terminal folder that can hold a stranded `needsAnswers` flag,
1356
+ * paired with the item type that rests there. Derived from
1357
+ * {@link terminalMainPathsByKind} with a sentinel slug so the folder set stays
1358
+ * SINGLE-SOURCED: adding a regime there adds it here, and the `wont-proceed`
1359
+ * terminals are excluded by the SAME `kind` split the drain already branches on
1360
+ * (a cancelled item's flag is accurate history, not residue). `observation`
1361
+ * contributes nothing, having no durable terminal. */
1362
+ function successTerminalFolders() {
1363
+ const out = [];
1364
+ for (const type of ['task', 'spec', 'observation']) {
1365
+ for (const candidate of terminalMainPathsByKind(type, '__slug__')) {
1366
+ if (candidate.kind !== 'completed') {
1367
+ continue;
1368
+ }
1369
+ out.push({
1370
+ folder: candidate.path.slice(0, candidate.path.lastIndexOf('/')),
1371
+ type,
1372
+ });
1373
+ }
1374
+ }
1375
+ return out;
1376
+ }
1377
+ /**
1378
+ * Classify the arbiter's STRANDED QUESTION STATE, read-only (observation
1379
+ * `a-rebuilt-task-leaves-its-bounce-question-asking-to-cancel-a-merged-task`).
1380
+ *
1381
+ * THE BUG THIS EXISTS FOR. When a build bounces, the surface path atomically
1382
+ * writes BOTH halves of the question state in ONE commit: the sidecar
1383
+ * `work/questions/<type>-<slug>.md` AND `needsAnswers: true` on the item body.
1384
+ * That is correct, and the atomicity is what makes this reconciliation decidable
1385
+ * at all. But if the human DISAGREES with the bounce and simply re-dispatches,
1386
+ * and the rebuild SUCCEEDS (PR opened, gate green, merged, body done-moved),
1387
+ * NEITHER half is ever cleared. The item comes to rest in `tasks/done/` still
1388
+ * carrying a question asking whether to CANCEL it, with a destructive default.
1389
+ *
1390
+ * The flag is the harmful half. A stranded sidecar is a stale question in a
1391
+ * folder a human scans; a stranded `needsAnswers` is a GATE LEFT ARMED, and it
1392
+ * makes `status` report shipped (sometimes released) work under "open questions
1393
+ * block autonomous work".
1394
+ *
1395
+ * Dorfl ALREADY knows this state is illegal: `advance-classify.ts` refuses it as
1396
+ * `invariant-violation` / `sidecar-without-needsAnswers`. The defect is purely
1397
+ * that the detector lives in the `advance` tick's classifier, and a human driving
1398
+ * `do` and merging a PR never enters that loop. So this is the same shape as the
1399
+ * propose-path lock leak, settled by the same reconcile pass at the same moment
1400
+ * (the done-move), rather than by a second mechanism.
1401
+ *
1402
+ * THE TRAP, and why the TERMINAL POSITION is the discriminator rather than the
1403
+ * flag/sidecar disagreement: the MIRROR state (`needsAnswers:true` with NO
1404
+ * sidecar) is LEGAL and COMMON. An item authored with open questions carries the
1405
+ * flag and has no sidecar until `surface` runs, and that flagged-but-unsurfaced
1406
+ * item is precisely the `surface` rung's INPUT. Clearing the flag there would
1407
+ * silently disarm every un-surfaced item in the repo and hand gated work to
1408
+ * agents. So this only ever considers items whose body has reached a TERMINAL
1409
+ * folder on `main`; an item resting in a pool or staging folder keeps whatever
1410
+ * state it has, untouched.
1411
+ *
1412
+ * TWO ENUMERATIONS, because the two halves can be separated in either order and
1413
+ * a sweep anchored on one is blind to the other:
1414
+ * 1. the SIDECAR SET (`work/questions/` on `main`), small and cheap to list,
1415
+ * which finds a stale sidecar and the flag paired with it; and
1416
+ * 2. the SUCCESS-TERMINAL BODIES that are flagged with NO sidecar beside them
1417
+ * ({@link collectStrandedTerminalFlags}), which finds the armed gate ALONE.
1418
+ *
1419
+ * (2) is not optional tidiness. It is the half that actually gates work, and a
1420
+ * sweep anchored only on (1) reports success while any gate it cannot see stays
1421
+ * armed. The sidecar is the
1422
+ * half a human deletes by hand (it is the visible one, in a folder they scan),
1423
+ * and deleting it REMOVES the only handle (1) has, stranding the flag for good.
1424
+ * The discriminator that keeps (2) safe is POSITION, exactly as for (1): a bare
1425
+ * flag is LEGAL on a pool/staging item (the `surface` rung's input) and residue
1426
+ * only once the item has shipped, where `surface` can never run again.
1427
+ *
1428
+ * Best-effort and never throws.
1429
+ */
1430
+ export async function classifyTerminalQuestionResidue(params) {
1431
+ const { cwd, mainRef, env } = params;
1432
+ // REFRESH `mainRef` FIRST, with an explicit refspec that writes exactly the ref
1433
+ // we are about to read. Without this the pass reads a STALE view: the caller
1434
+ // may not have fetched, and the lock sub-pass of the combined reconciliation
1435
+ // early-returns (so does not refresh) when no locks are held. A failed refresh
1436
+ // is NOT fatal, but it does mean the view may be stale in EITHER direction (an
1437
+ // item may have left a terminal folder, or acquired an answer, since we last
1438
+ // looked), which is exactly why the WRITE path re-derives this same
1439
+ // classification against its own freshly-resolved base rather than trusting
1440
+ // this snapshot.
1441
+ await refreshMainRef(mainRef, params.arbiter, cwd, env);
1442
+ return deriveTerminalQuestionResidue(mainRef, cwd, env);
1443
+ }
1444
+ /**
1445
+ * The SYNC, PURE-of-network derivation of the question residue AT ONE COMMIT.
1446
+ *
1447
+ * Split out of {@link classifyTerminalQuestionResidue} so the WRITE path can
1448
+ * re-derive the SAME classification against the base it is actually about to
1449
+ * commit on, per contention attempt. That matters for correctness, not tidiness:
1450
+ * a classification taken before a contention retry can be stale in two ways that
1451
+ * both break a documented guarantee. An item may have LEFT its terminal folder
1452
+ * (re-opened), in which case its sidecar is live again and must not be deleted;
1453
+ * and a human may have written an ANSWER into a sidecar in the window, which must
1454
+ * never be auto-deleted. Re-deriving against `base` closes both, because the
1455
+ * commit is built on exactly that base.
1456
+ */
1457
+ function deriveTerminalQuestionResidue(base, cwd, env) {
1458
+ const mainRef = base;
1459
+ const out = {
1460
+ drainable: [],
1461
+ answeredHeld: [],
1462
+ staleFlags: [],
1463
+ errors: [],
1464
+ };
1465
+ // The SECOND half of the residue, enumerated from the OTHER side. The sidecar
1466
+ // sweep below can only ever see items that still HAVE a sidecar; this one finds
1467
+ // the SUCCESS-terminal bodies whose gate is armed with no sidecar left to point
1468
+ // at them. Both must run: they are the same defect observed through the two
1469
+ // halves the surface path writes atomically, and either half can outlive the
1470
+ // other.
1471
+ collectStrandedTerminalFlags(mainRef, cwd, env, out);
1472
+ const questionsDir = workFolderRel('questions');
1473
+ const ls = run('git', ['ls-tree', '--name-only', `${mainRef}:${questionsDir}`], cwd, { env });
1474
+ if (ls.status !== 0) {
1475
+ // No `work/questions/` on main at all: nothing surfaced, nothing to drain.
1476
+ return out;
1477
+ }
1478
+ for (const name of ls.stdout.split('\n').map((l) => l.trim())) {
1479
+ if (name === '' || !isWorkItemFile(name)) {
1480
+ continue;
1481
+ }
1482
+ const sidecarPath = `${questionsDir}/${name}`;
1483
+ try {
1484
+ // `<type>-<slug>.md` → `<type>:<slug>`. Only the CURRENT namespaces are
1485
+ // addressable; a legacy `prd-` file has no current item-form and is left
1486
+ // for the migration command.
1487
+ const stem = name.replace(/\.md$/, '');
1488
+ const dash = stem.indexOf('-');
1489
+ const type = stem.slice(0, dash);
1490
+ const slug = stem.slice(dash + 1);
1491
+ if (!['task', 'spec', 'observation'].includes(type) || slug === '') {
1492
+ continue;
1493
+ }
1494
+ const item = `${type}:${slug}`;
1495
+ // Is the body at rest in a terminal folder on `main`?
1496
+ const terminalHit = terminalMainPathsByKind(type, slug).find((c) => pathInCommit(mainRef, c.path, cwd, env));
1497
+ if (terminalHit === undefined) {
1498
+ // NOT terminal: a live item. Its question state is its own business
1499
+ // a pending sidecar is a human's outstanding decision, and clearing a
1500
+ // flag here is the trap above. Untouched.
1501
+ continue;
1502
+ }
1503
+ // N5 GUARD: a mid-migration spec can have BOTH `spec-<slug>.md` and the
1504
+ // legacy `prd-<slug>.md` on main (`sidecarPathCandidates` still resolves
1505
+ // the legacy name for readers). Draining only the canonical one while
1506
+ // clearing the flag would leave the legacy sidecar live against
1507
+ // `needsAnswers:false`, which is precisely the
1508
+ // `sidecar-without-needsAnswers` invariant violation this change exists
1509
+ // to remove. If any OTHER candidate for this item still exists, leave the
1510
+ // whole item to `dorfl prd-to-spec`, which renames the DATA.
1511
+ const hasLegacyAlias = sidecarPathCandidates(item).some((c) => c !== sidecarPath && pathInCommit(mainRef, c, cwd, env));
1512
+ if (hasLegacyAlias) {
1513
+ continue;
1514
+ }
1515
+ const model = parseSidecar(catBlob(`${mainRef}:${sidecarPath}`, cwd, env));
1516
+ const answered = model.entries.some((e) => isEntryAnswered(e));
1517
+ const body = catBlob(`${mainRef}:${terminalHit.path}`, cwd, env);
1518
+ const flagged = parseFrontmatter(body).needsAnswers === true;
1519
+ const residue = {
1520
+ item,
1521
+ sidecarPath,
1522
+ itemPath: terminalHit.path,
1523
+ terminal: terminalHit.kind,
1524
+ flagged,
1525
+ answered,
1526
+ };
1527
+ if (answered) {
1528
+ // A human WROTE an answer here and the apply rung never consumed it.
1529
+ // Deleting it would discard prose the tool did not author, so this is
1530
+ // surfaced for a human instead. (That the drain never runs on the
1531
+ // human-answer path either is a SEPARATE defect; this pass must not
1532
+ // paper over it by destroying the evidence.)
1533
+ out.answeredHeld.push(residue);
1534
+ }
1535
+ else {
1536
+ out.drainable.push(residue);
1537
+ }
1538
+ }
1539
+ catch (err) {
1540
+ out.errors.push({
1541
+ item: sidecarPath,
1542
+ message: err instanceof Error ? err.message : String(err),
1543
+ });
1544
+ }
1545
+ }
1546
+ return out;
1547
+ }
1548
+ /**
1549
+ * Find every SUCCESS-terminal body on `base` carrying `needsAnswers:true` with NO
1550
+ * sidecar beside it, appending them to `out.staleFlags`.
1551
+ *
1552
+ * ENUMERATION COST is why this is a `git grep` and not a walk. The terminal
1553
+ * folders are the repo's largest and most monotonically growing (this repo holds
1554
+ * 404 done tasks), and this runs on the CLAIM path, so reading every terminal
1555
+ * body per claim would be a real tax on a hot path. One `git grep -l` returns
1556
+ * only the candidates, and the frontmatter parse runs over that short list.
1557
+ *
1558
+ * The pattern is ANCHORED to match the PARSER rather than the word.
1559
+ * `parseFrontmatter` reads keys with `/^([A-Za-z0-9_.]+)\s*:\s*(.*)$/`, so a key
1560
+ * it will honour is always at column 0; an unanchored needle instead matches
1561
+ * every body that merely DISCUSSES the flag, which in `work/tasks/done/` here is
1562
+ * 77 files against 18 anchored, and the truthy form narrows it to 1.
1563
+ *
1564
+ * The value part is matched LOOSELY on purpose (optional quote, any case),
1565
+ * because `toBoolean` unquotes and lower-cases before comparing, so
1566
+ * `needsAnswers: 'True'` is a real armed gate. A needle of `:\s*true` would read
1567
+ * tighter and be WRONG: it would silently skip those bodies for ever, which is
1568
+ * the blind-spot class this function exists to remove. A superset is the safe
1569
+ * direction for a shortlist; a subset is not.
1570
+ *
1571
+ * The grep is still only a CANDIDATE FILTER, never the decision: prose can sit
1572
+ * at column 0 too (`needsAnswers: true?` appears in this repo's own bodies), so
1573
+ * every hit is confirmed by actually PARSING the frontmatter.
1574
+ *
1575
+ * Two git-isms are pinned rather than left to the environment:
1576
+ * - `core.quotePath=false`, or git C-quotes any non-ASCII path
1577
+ * (`"work/.../caf\303\251.md"`). A quoted line still starts with the
1578
+ * `<base>:` prefix but then fails the folder-prefix test, so such a body
1579
+ * would be SILENTLY skipped for ever, a permanent blind spot of exactly the
1580
+ * class this function exists to remove.
1581
+ * - `--full-name` + `:(top,literal)` pathspecs, because `git grep`'s pathspecs
1582
+ * are CWD-RELATIVE (unlike the `ls-tree`/`cat-file` probes elsewhere here,
1583
+ * which are tree-relative) and are globs. Without these, running any dorfl
1584
+ * command from a SUBDIRECTORY makes this half a silent no-op while the
1585
+ * sidecar half keeps working.
1586
+ *
1587
+ * Never throws; a failed grep yields no candidates, which leaves state alone.
1588
+ */
1589
+ function collectStrandedTerminalFlags(base, cwd, env, out) {
1590
+ const folders = successTerminalFolders();
1591
+ if (folders.length === 0) {
1592
+ return;
1593
+ }
1594
+ // `-l` names files only, `-I` skips binaries. Exit 1 means NO MATCH, which
1595
+ // ALSO covers "the folder does not exist on this base yet" (verified: an
1596
+ // absent pathspec folder exits 1 with no stderr), and an absent lifecycle
1597
+ // folder is legal per WORK-CONTRACT rule 3. Any OTHER non-zero is a genuine
1598
+ // fault and is REPORTED rather than swallowed: degrading silently to "no
1599
+ // candidates" would leave this half a no-op while the sidecar half keeps
1600
+ // reporting success, which is the very "reports success while the gate stays
1601
+ // armed" shape this change exists to correct.
1602
+ const grep = run('git', [
1603
+ '-c',
1604
+ 'core.quotePath=false',
1605
+ 'grep',
1606
+ '-l',
1607
+ '-I',
1608
+ '--full-name',
1609
+ '-E',
1610
+ '^needsAnswers:[[:space:]]*[\'"]?[Tt][Rr][Uu][Ee]',
1611
+ base,
1612
+ '--',
1613
+ ...folders.map((f) => `:(top,literal)${f.folder}`),
1614
+ ], cwd, { env });
1615
+ if (grep.status !== 0) {
1616
+ if (grep.status !== 1) {
1617
+ out.errors.push({
1618
+ item: '(stranded-flag scan)',
1619
+ message: `git grep over the terminal folders failed (exit ${grep.status}): ` +
1620
+ `${grep.stderr.trim() || 'no stderr'}; stranded gates were NOT scanned.`,
1621
+ });
1622
+ }
1623
+ return;
1624
+ }
1625
+ const prefix = `${base}:`;
1626
+ for (const line of grep.stdout.split('\n')) {
1627
+ const raw = line.trim();
1628
+ if (raw === '' || !raw.startsWith(prefix)) {
1629
+ continue;
1630
+ }
1631
+ const path = raw.slice(prefix.length);
1632
+ try {
1633
+ const home = folders.find((f) => path.startsWith(`${f.folder}/`));
1634
+ if (home === undefined) {
1635
+ continue;
1636
+ }
1637
+ const name = path.slice(home.folder.length + 1);
1638
+ // Direct children only: a nested path is not an item body.
1639
+ if (name.includes('/') || !isWorkItemFile(name)) {
1640
+ continue;
1641
+ }
1642
+ // Case-INSENSITIVE to match `isWorkItemFile` above: a `Foo.MD` body must
1643
+ // yield the slug `Foo`, or the sidecar-existence guard below would probe
1644
+ // the wrong path and could clear a gate whose sidecar holds an answer.
1645
+ const slug = name.replace(/\.md$/i, '');
1646
+ if (slug === '') {
1647
+ continue;
1648
+ }
1649
+ const item = `${home.type}:${slug}`;
1650
+ // A sidecar STILL EXISTS for this item (canonical or legacy alias) ⇒ this
1651
+ // is the sidecar-anchored sweep's business, not ours. Skipping keeps the
1652
+ // two enumerations DISJOINT, so an item is never planned twice in one
1653
+ // commit and the answered-sidecar carve-out cannot be bypassed through
1654
+ // this path (an item held for an unapplied human answer keeps its flag).
1655
+ if (sidecarPathCandidates(item).some((c) => pathInCommit(base, c, cwd, env))) {
1656
+ continue;
1657
+ }
1658
+ // CONFIRM against the parsed frontmatter: the grep only shortlisted.
1659
+ const body = catBlob(`${base}:${path}`, cwd, env);
1660
+ if (parseFrontmatter(body).needsAnswers !== true) {
1661
+ continue;
1662
+ }
1663
+ out.staleFlags.push({ item, itemPath: path });
1664
+ }
1665
+ catch (err) {
1666
+ out.errors.push({
1667
+ item: path,
1668
+ message: err instanceof Error ? err.message : String(err),
1669
+ });
1670
+ }
1671
+ }
1672
+ }
1673
+ /**
1674
+ * Drain the stranded question state {@link classifyTerminalQuestionResidue}
1675
+ * finds, in ONE tree-less commit CAS-published to the arbiter's `main` through
1676
+ * the SAME {@link runTreelessLedgerMove} core the surface path uses (same
1677
+ * contention-retry, same lease, same write seam; there is no second mechanism).
1678
+ *
1679
+ * WHAT IT CLEARS, and the deliberate asymmetry between the two terminals. Note
1680
+ * the terminal SET first: `specs/tasked/` is deliberately NOT in this map at all
1681
+ * (see {@link terminalMainPathsByKind}), so nothing below applies to a tasked
1682
+ * spec, whose question state stays untouched in both halves.
1683
+ * - the SIDECAR is deleted for EITHER terminal in the map. A question asking
1684
+ * whether to cancel an item that has already come to rest is stale in both
1685
+ * cases, and it sits in a folder a human scans carrying a destructive
1686
+ * default.
1687
+ * - the `needsAnswers` FLAG is cleared ONLY for a `completed` terminal
1688
+ * (`tasks/done/`). On a `wont-proceed` terminal
1689
+ * (`tasks/cancelled/`, `specs/dropped/`) the flag is KEPT, because an item
1690
+ * can be cancelled precisely BECAUSE its questions were never answered: there
1691
+ * the flag is accurate history, not residue, and the body may carry a real
1692
+ * `## Open questions` section saying so. Keeping it is harmless, a terminal
1693
+ * item is in no pool, so the flag gates nothing.
1694
+ * - a SUCCESS-terminal item whose gate is armed with NO sidecar left beside it
1695
+ * has that FLAG cleared and nothing deleted (there is nothing to delete).
1696
+ * Restricted to the `completed` terminal by the same asymmetry above.
1697
+ *
1698
+ * A sidecar with ANY answered entry is never touched (see the classifier), and
1699
+ * an item still holding such a sidecar is excluded from the flag-only half too,
1700
+ * so the carve-out cannot be bypassed by clearing its gate.
1701
+ *
1702
+ * Best-effort: it never throws, and any fault leaves the state exactly as it was.
1703
+ */
1704
+ export async function reconcileTerminalQuestionResidue(params) {
1705
+ const { cwd, arbiter, mainRef, env } = params;
1706
+ const note = params.note ?? (() => { });
1707
+ const result = {
1708
+ drained: [],
1709
+ unflagged: [],
1710
+ answeredHeld: [],
1711
+ errors: [],
1712
+ };
1713
+ let report;
1714
+ try {
1715
+ report = await classifyTerminalQuestionResidue({
1716
+ cwd,
1717
+ arbiter,
1718
+ mainRef,
1719
+ env,
1720
+ mainAlreadyFresh: params.mainAlreadyFresh,
1721
+ });
1722
+ }
1723
+ catch (err) {
1724
+ result.errors.push({
1725
+ item: '(classify)',
1726
+ message: err instanceof Error ? err.message : String(err),
1727
+ });
1728
+ return result;
1729
+ }
1730
+ result.answeredHeld = report.answeredHeld.map((r) => r.item);
1731
+ result.errors.push(...report.errors);
1732
+ if (report.drainable.length === 0 && report.staleFlags.length === 0) {
1733
+ return result;
1734
+ }
1735
+ // What the LANDED commit ACTUALLY did, filled in by the plan against the base
1736
+ // it committed on. The pre-plan `report` above is only a fast "is there
1737
+ // anything to do?" probe; reporting from it would claim a gate was disarmed
1738
+ // when a contention retry re-derived the residue and skipped the item.
1739
+ let applied = [];
1740
+ // Filled by the PLAN with what it actually STAGED (not what it intended), so a
1741
+ // body the marker writer cannot annotate is never reported as unflagged.
1742
+ const clearedSidecarFlags = [];
1743
+ const clearedStaleFlags = [];
1744
+ // NEVER THROW. `runTreelessLedgerMove` and the git plumbing inside the plan
1745
+ // both throw on any non-zero git, and this pass runs from the CLAIM path as
1746
+ // OPPORTUNISTIC HYGIENE on unrelated items. A fault here (a stale scratch ref,
1747
+ // a protected `main`, a permission refusal) must degrade to "left it alone",
1748
+ // never fail the caller's actual work.
1749
+ let landed = false;
1750
+ try {
1751
+ landed = await runTreelessLedgerMove({
1752
+ cwd,
1753
+ // The ref name only has to be unique for the scratch ref; this pass is
1754
+ // batch (many items, one commit), so it is not keyed to a single slug.
1755
+ slug: 'terminal-question-drain',
1756
+ arbiter,
1757
+ kind: 'needs-attention',
1758
+ onContended: 'drain stranded questions',
1759
+ explicitMainRefspec: true,
1760
+ env,
1761
+ note,
1762
+ // RE-PLANNED per attempt against the freshly-fetched base: the residue is
1763
+ // RE-DERIVED from that base, never reused from the probe above, so an item
1764
+ // re-opened out of its terminal folder, or a sidecar a human answered, in the
1765
+ // contention window is correctly left alone.
1766
+ plan: (base) => {
1767
+ const fresh = deriveTerminalQuestionResidue(base, cwd, env);
1768
+ applied = fresh.drainable;
1769
+ result.answeredHeld = fresh.answeredHeld.map((r) => r.item);
1770
+ return prepareTerminalQuestionDrainCommit({
1771
+ cwd,
1772
+ base,
1773
+ residue: fresh.drainable,
1774
+ staleFlags: fresh.staleFlags,
1775
+ clearedSidecarFlags,
1776
+ clearedStaleFlags,
1777
+ env,
1778
+ });
1779
+ },
1780
+ });
1781
+ }
1782
+ catch (err) {
1783
+ result.errors.push({
1784
+ item: '(publish)',
1785
+ message: err instanceof Error ? err.message : String(err),
1786
+ });
1787
+ return result;
1788
+ }
1789
+ if (!landed) {
1790
+ result.errors.push({
1791
+ item: '(publish)',
1792
+ message: 'the stranded-question drain did not land on the arbiter’s main ' +
1793
+ '(contention exhausted, or nothing to do); state left untouched.',
1794
+ });
1795
+ return result;
1796
+ }
1797
+ for (const r of applied) {
1798
+ result.drained.push(r.item);
1799
+ }
1800
+ // `unflagged` reports what the commit ACTUALLY staged, from both halves. The
1801
+ // flag-only half never appears in `drained`: it deletes nothing.
1802
+ for (const r of [...clearedSidecarFlags, ...clearedStaleFlags]) {
1803
+ result.unflagged.push(r.item);
1804
+ }
1805
+ return result;
1806
+ }
1807
+ /**
1808
+ * Stage `itemPath` with `needsAnswers` cleared, into the scratch index the drain
1809
+ * commit is being built in. Shared by BOTH halves of the residue (the
1810
+ * sidecar-paired flag and the stranded flag-only one) so they can never disagree
1811
+ * about what clearing a gate means.
1812
+ *
1813
+ * Defense-in-depth, mirroring the surface path's guard in the opposite
1814
+ * direction: if the marker does not parse back as `false`, the body is left
1815
+ * ALONE rather than written as something we cannot vouch for. Every uncertainty
1816
+ * resolves to LEAVING STATE ALONE.
1817
+ *
1818
+ * RETURNS whether the gate was actually STAGED, so callers report EFFECT rather
1819
+ * than INTENT. That distinction is load-bearing here: a body this cannot
1820
+ * annotate (e.g. duplicate `needsAnswers` keys, where the writer replaces the
1821
+ * FIRST and the parser reads the LAST) would otherwise be reported as unflagged
1822
+ * on every claim for ever while its gate stayed armed, the precise
1823
+ * "reports success while the defect remains" failure this whole change exists to
1824
+ * correct.
1825
+ */
1826
+ function clearNeedsAnswersInIndex(itemPath, base, cwd, env, withIndex) {
1827
+ if (!pathInCommit(base, itemPath, cwd, env)) {
1828
+ return false;
1829
+ }
1830
+ const body = catBlob(`${base}:${itemPath}`, cwd, env);
1831
+ const cleared = setNeedsAnswersMarker(body, false);
1832
+ if (parseFrontmatter(cleared).needsAnswers !== false) {
1833
+ return false;
1834
+ }
1835
+ const blob = hashObject(cleared, cwd, env);
1836
+ gitHard(['update-index', '--add', '--cacheinfo', `100644,${blob},${itemPath}`], cwd, withIndex);
1837
+ return true;
1838
+ }
1839
+ /**
1840
+ * Build the ONE tree-less commit that removes every drainable sidecar and clears
1841
+ * the `needsAnswers` flag on every `completed`-terminal body, using PLUMBING on a
1842
+ * SCRATCH INDEX (the caller's index/HEAD/working tree are never touched)
1843
+ * exactly as {@link prepareTreelessSurfaceCommit} does in the opposite direction.
1844
+ *
1845
+ * Batched into a single commit on purpose: the residue is a SET, one commit is
1846
+ * one CAS against `main` instead of N, and the whole drain then lands or does not
1847
+ * land atomically.
1848
+ */
1849
+ function prepareTerminalQuestionDrainCommit(params) {
1850
+ const { cwd, base, residue, env, clearedSidecarFlags, clearedStaleFlags } = params;
1851
+ clearedSidecarFlags.length = 0;
1852
+ clearedStaleFlags.length = 0;
1853
+ // RE-DERIVE against THIS base: anything already gone is not our business.
1854
+ const live = residue.filter((r) => pathInCommit(base, r.sidecarPath, cwd, env));
1855
+ const liveFlags = params.staleFlags.filter((r) => pathInCommit(base, r.itemPath, cwd, env));
1856
+ if (live.length === 0 && liveFlags.length === 0) {
1857
+ return 'already-done';
1858
+ }
1859
+ const scratchIndex = join(tmpdir(), `dorfl-question-drain-${process.pid}-${Date.now()}.index`);
1860
+ const withIndex = {
1861
+ ...(env ?? process.env),
1862
+ GIT_INDEX_FILE: scratchIndex,
1863
+ };
1864
+ try {
1865
+ gitHard(['read-tree', base], cwd, withIndex);
1866
+ for (const r of live) {
1867
+ // Remove the stale sidecar.
1868
+ gitHard(['update-index', '--force-remove', r.sidecarPath], cwd, withIndex);
1869
+ // Clear the flag ONLY on a `completed` terminal (see the doc above).
1870
+ if (r.terminal !== 'completed' || !r.flagged) {
1871
+ continue;
1872
+ }
1873
+ if (clearNeedsAnswersInIndex(r.itemPath, base, cwd, env, withIndex)) {
1874
+ clearedSidecarFlags.push(r);
1875
+ }
1876
+ }
1877
+ // The FLAG-ONLY half: a SUCCESS terminal whose sidecar is already gone. No
1878
+ // `--force-remove` here, because there is nothing to delete; the armed gate IS the
1879
+ // whole residue.
1880
+ // Record what was actually STAGED: a body we could not annotate is dropped
1881
+ // from the report rather than claimed as cleared.
1882
+ for (const r of liveFlags) {
1883
+ if (clearNeedsAnswersInIndex(r.itemPath, base, cwd, env, withIndex)) {
1884
+ clearedStaleFlags.push(r);
1885
+ }
1886
+ }
1887
+ const tree = runHard(['write-tree'], cwd, withIndex).stdout.trim();
1888
+ const touched = live.length + liveFlags.length;
1889
+ const only = live[0]?.item ?? liveFlags[0]?.item;
1890
+ const subject = touched === 1
1891
+ ? `drain stranded question state for ${only} (terminal on main)`
1892
+ : `drain stranded question state for ${touched} terminal items`;
1893
+ const commit = runHard(['commit-tree', tree, '-p', base, '-m', subject], cwd, env).stdout.trim();
1894
+ const ref = 'refs/dorfl/question-drain/batch';
1895
+ gitHard(['update-ref', ref, commit], cwd, env);
1896
+ return { ref, commit };
1897
+ }
1898
+ finally {
1899
+ rmSync(scratchIndex, { force: true });
1900
+ }
1901
+ }
1309
1902
  /**
1310
1903
  * The PR-1 thin HARNESS around {@link prepareTreelessSurfaceCommit}: run it
1311
1904
  * through the EXISTING {@link runTreelessLedgerMove} CAS loop, then release the