mandrel 2.114.0 → 2.116.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 (44) hide show
  1. package/.agents/docs/agentrc-reference.json +1 -0
  2. package/.agents/docs/configuration.md +18 -4
  3. package/.agents/docs/workflows.md +2 -1
  4. package/.agents/schemas/agentrc.schema.json +54 -1
  5. package/.agents/scripts/acceptance-eval.js +2 -2
  6. package/.agents/scripts/ceremony-derive.js +15 -2
  7. package/.agents/scripts/closeout-audit.js +132 -0
  8. package/.agents/scripts/lib/baselines/crap-preview-scan.js +15 -8
  9. package/.agents/scripts/lib/baselines/crap-preview-touched.js +140 -0
  10. package/.agents/scripts/lib/baselines/crap-prune.js +86 -0
  11. package/.agents/scripts/lib/baselines/kinds/crap.js +12 -4
  12. package/.agents/scripts/lib/baselines/seat-missing.js +1 -1
  13. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  14. package/.agents/scripts/lib/config/gates/crap.schema.js +7 -0
  15. package/.agents/scripts/lib/config/quality.js +3 -0
  16. package/.agents/scripts/lib/config/temp-paths.js +12 -0
  17. package/.agents/scripts/lib/config-settings-schema-delivery.js +34 -0
  18. package/.agents/scripts/lib/coverage-capture-delta.js +26 -3
  19. package/.agents/scripts/lib/coverage-capture-own-fix.js +35 -19
  20. package/.agents/scripts/lib/coverage-capture.js +62 -14
  21. package/.agents/scripts/lib/crap-engine.js +3 -5
  22. package/.agents/scripts/lib/crap-utils.js +12 -2
  23. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  24. package/.agents/scripts/lib/git-branch-lifecycle.js +2 -1
  25. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  26. package/.agents/scripts/lib/orchestrate/classify.js +238 -0
  27. package/.agents/scripts/lib/orchestrate/conflicts.js +119 -0
  28. package/.agents/scripts/lib/orchestrate/inherited-failure.js +66 -0
  29. package/.agents/scripts/lib/orchestrate/inventory.js +388 -0
  30. package/.agents/scripts/lib/orchestrate/ledger.js +223 -0
  31. package/.agents/scripts/lib/orchestration/closeout-audit.js +511 -0
  32. package/.agents/scripts/lib/orchestration/handoff-gates.js +25 -8
  33. package/.agents/scripts/lib/orchestration/merge-queue.js +1 -1
  34. package/.agents/scripts/lib/orchestration/required-checks.js +12 -2
  35. package/.agents/scripts/lib/orchestration/story-handoff.js +131 -41
  36. package/.agents/scripts/orchestrate-inventory.js +70 -0
  37. package/.agents/scripts/orchestrate-ledger.js +141 -0
  38. package/.agents/scripts/single-story-init.js +43 -5
  39. package/.agents/scripts/story-handoff.js +6 -2
  40. package/.agents/workflows/helpers/deliver-digest.md +3 -3
  41. package/.agents/workflows/helpers/deliver-reference.md +31 -4
  42. package/.agents/workflows/mandrel-orchestrate.md +140 -0
  43. package/docs/CHANGELOG.md +21 -0
  44. package/package.json +1 -1
@@ -22,7 +22,8 @@
22
22
  import fs from 'node:fs';
23
23
  import path from 'node:path';
24
24
  import { fileURLToPath } from 'node:url';
25
-
25
+ import { pruneStaleCrapRows } from '../baselines/crap-prune.js';
26
+ import { isCaptureFresh, SeatRefusal } from '../baselines/seat-missing.js';
26
27
  import { spawnStreamAsync } from '../child-exec.js';
27
28
  import {
28
29
  createLockEventChannel,
@@ -30,12 +31,14 @@ import {
30
31
  } from '../close-lock-events.js';
31
32
  import { resolveTestGateArgv } from '../close-validation/commands.js';
32
33
  import {
34
+ BASELINES_GATE_NAMES,
33
35
  isCrapGateEnabled,
34
36
  resolveCreditedDepositor,
35
37
  } from '../close-validation/gates.js';
36
38
  import { isBiomeNoFilesProcessed } from '../close-validation/process.js';
37
39
  import { applyChangedFileScope } from '../close-validation/runner.js';
38
40
  import { skipBranchDeposit } from '../close-validation/skip-branch-test.js';
41
+ import { getBaselines } from '../config/baselines.js';
39
42
  import { getPostSeatChecks } from '../config/handoff.js';
40
43
  import { getQuality } from '../config/quality.js';
41
44
  import {
@@ -72,6 +75,7 @@ import { defaultSleep } from '../util/sleep.js';
72
75
  import { hashCommandConfig } from '../validation-evidence.js';
73
76
  import { runStreamed } from './evidence-stream.js';
74
77
  import {
78
+ baselineComparePreflight,
75
79
  carryCoverageDeferral,
76
80
  carryCredit,
77
81
  carryPreflightCredits,
@@ -346,8 +350,8 @@ function describeSuiteFailure(status) {
346
350
  }
347
351
 
348
352
  /**
349
- * Typecheck, lint and format (deposited), quality-preview, then each ratchet whose
350
- * baseline is committed.
353
+ * Typecheck, lint and format (deposited), quality-preview, each ratchet whose
354
+ * baseline is committed, then close's artifact-free baseline compare.
351
355
  *
352
356
  * @param {object} ctx
353
357
  * @returns {Array<{ key: string, cmd: string, args: string[], gated?: boolean, deposit?: object }>}
@@ -375,6 +379,7 @@ function preflightChecks(ctx) {
375
379
  ],
376
380
  },
377
381
  ...ratchets,
382
+ ...baselineComparePreflight(ctx),
378
383
  ];
379
384
  }
380
385
 
@@ -400,7 +405,7 @@ function preflightFinding(check, run) {
400
405
  .slice(0, MAX_OFFENDING_LINES)
401
406
  : extractFailureRows(run.output, { max: MAX_OFFENDING_LINES });
402
407
  const rows = offending.length > 0 ? `: ${offending.join('; ')}` : '';
403
- return `${check.key}${check.gated ? ' ratchet' : ''} finding${rows} — fix and commit, then re-run`;
408
+ return `${check.label ?? check.key}${check.gated ? ' ratchet' : ''} finding${rows} — fix and commit, then re-run`;
404
409
  }
405
410
 
406
411
  /**
@@ -463,7 +468,10 @@ async function stepPreflight(ctx) {
463
468
 
464
469
  /** A baselined ratchet's finding is a `ratchet`; any other check is its own key. */
465
470
  function preflightCause(key) {
466
- return STANDALONE_RATCHETS.some((r) => r.key === key) ? 'ratchet' : key;
471
+ return key === BASELINES_GATE_NAMES.independent ||
472
+ STANDALONE_RATCHETS.some((r) => r.key === key)
473
+ ? 'ratchet'
474
+ : key;
467
475
  }
468
476
 
469
477
  /**
@@ -487,7 +495,7 @@ async function runPreflightCheck(ctx, check, pass, env) {
487
495
  `preflight-${check.key}`,
488
496
  check.cmd,
489
497
  check.args,
490
- env,
498
+ check.env ? { ...(env ?? ctx.env), ...check.env } : env,
491
499
  );
492
500
  const finding = preflightFinding(check, run);
493
501
  if (check.key === 'lint') pass.lint = finding ? 'failed' : 'passed';
@@ -495,7 +503,10 @@ async function runPreflightCheck(ctx, check, pass, env) {
495
503
  creditCheck(ctx, check);
496
504
  return null;
497
505
  }
498
- const detail = finding + seatHint(ctx, check);
506
+ const detail =
507
+ finding +
508
+ raisedDuplicationSuffix(ctx, check, MAX_OFFENDING_LINES) +
509
+ seatHint(ctx, check);
499
510
  return { check: check.key, detail, evidencePath: run.evidencePath };
500
511
  }
501
512
 
@@ -943,6 +954,30 @@ function seatsCoverage(ctx) {
943
954
  );
944
955
  }
945
956
 
957
+ /**
958
+ * Drop the stale CRAP rows of change-set files; a refusal stops the step.
959
+ *
960
+ * @returns {Promise<StepResult|{ total: number }>}
961
+ */
962
+ async function pruneCrapRows(ctx, name) {
963
+ if (!isCrapGateEnabled(ctx.config)) return { total: 0 };
964
+ try {
965
+ const { pruned } = await ctx.pruneStaleCrap({
966
+ writePath: path.resolve(ctx.cwd, getBaselines(ctx.config).crap.path),
967
+ baseRef: `origin/${ctx.baseBranch}`,
968
+ cwd: ctx.cwd,
969
+ });
970
+ ctx.progress(name, `pruned ${pruned} stale CRAP row(s)`);
971
+ return { total: pruned };
972
+ } catch (err) {
973
+ if (!(err instanceof SeatRefusal)) throw err;
974
+ return fixRequired(name, err.message, {
975
+ evidencePath: ctx.writeEvidence('seat-prune', err.message),
976
+ cause: 'seat-refused',
977
+ });
978
+ }
979
+ }
980
+
946
981
  /** Static MI needs no capture, so its seat runs before preflight. */
947
982
  function staticSeatKinds(config) {
948
983
  const mi = config?.delivery?.quality?.gates?.maintainability?.enabled;
@@ -954,8 +989,11 @@ async function seatAndCommit(ctx, kinds, step) {
954
989
  if (ctx.state[step.headKey] === ctx.head) {
955
990
  return creditSkip(step.name, `nothing to seat at ${ctx.head.slice(0, 12)}`);
956
991
  }
957
- const seated = await runSeats(ctx, step.name, kinds);
958
- if (seated.stop) return seated;
992
+ const seats = await runSeats(ctx, step.name, kinds);
993
+ if (seats.stop) return seats;
994
+ const pruned = step.prune ? await step.prune(ctx, step.name) : { total: 0 };
995
+ if (pruned.stop) return pruned;
996
+ const seated = { ...seats, total: seats.total + pruned.total };
959
997
  if (seated.total === 0) {
960
998
  ctx.state[step.headKey] = ctx.head;
961
999
  return skipped(step.name, 'seated: 0 — nothing to seat', {
@@ -970,6 +1008,7 @@ function stepSeatStatic(ctx) {
970
1008
  return seatAndCommit(ctx, staticSeatKinds(ctx.config), {
971
1009
  name: 'seat-static',
972
1010
  headKey: 'staticSeatHead',
1011
+ prune: pruneCrapRows,
973
1012
  });
974
1013
  }
975
1014
 
@@ -1331,40 +1370,48 @@ async function stepPostCapture(ctx) {
1331
1370
  if (postCaptureHead === ctx.head && postCaptureSettled(ctx)) {
1332
1371
  return creditSkip(name, `already clean at ${ctx.head.slice(0, 12)}`);
1333
1372
  }
1334
- const { gates, failed } = await scorePostCapture(ctx, (...a) =>
1335
- runLogged(ctx, ...a),
1336
- );
1337
- if (failed) {
1338
- const rows = raisedDuplicationSuffix(ctx, failed, MAX_OFFENDING_LINES);
1339
- return fixRequired(name, `${failed.finding}${rows}`, {
1340
- evidencePath: failed.evidencePath,
1341
- gate: failed.gate,
1342
- cause: 'post-capture',
1343
- });
1373
+ if (ctx.reportAll && !hasFreshArtifact(ctx)) {
1374
+ return skipped(name, 'no fresh coverage artifact to score');
1344
1375
  }
1345
- const post = await runPostSeatChecks(ctx, (...a) => runLogged(ctx, ...a));
1346
- if (post.failed) return postSeatFixRequired(name, post.failed);
1376
+ const run = (...a) => runLogged(ctx, ...a);
1377
+ const { gates, failures } = await scorePostCapture(ctx, run);
1378
+ const post = await runPostSeatChecks(ctx, run);
1379
+ const findings = [...failures, ...post.failures];
1380
+ if (findings.length > 0) return postCaptureFixRequired(ctx, name, findings);
1347
1381
  ctx.state.postCaptureHead = ctx.head;
1348
1382
  return settledPostCapture(name, gates, post);
1349
1383
  }
1350
1384
 
1385
+ /** Whether any capture stamp vouches for the CRAP artifact at this tree. */
1386
+ function hasFreshArtifact(ctx) {
1387
+ const { coveragePath, targetDirs } = getQuality(ctx.config).crap;
1388
+ return ctx.isCaptureFresh({ coveragePath, targetDirs }, { cwd: ctx.cwd });
1389
+ }
1390
+
1391
+ /** Why the post-seat checks do not run; a `--report-all` run seats nothing. */
1392
+ function postSeatSkipReason(ctx) {
1393
+ if (ctx.reportAll) return 'report-all seats nothing';
1394
+ return isCoverageDeferred(ctx) ? 'coverage deferred' : null;
1395
+ }
1396
+
1351
1397
  /**
1352
- * Run each `delivery.handoff.postSeatChecks` entry through `run`; the first
1353
- * non-zero exit is the finding. Skipped under a coverage deferral.
1398
+ * Run every `delivery.handoff.postSeatChecks` entry through `run`; each
1399
+ * non-zero exit is a finding, and a clean set releases the held lint.
1354
1400
  *
1355
- * @returns {Promise<{ checks: object[], skipped?: boolean, failed: object|null }>}
1401
+ * @returns {Promise<{ checks: object[], skipped?: string, failures: object[] }>}
1356
1402
  */
1357
1403
  async function runPostSeatChecks(ctx, run) {
1358
1404
  const checks = getPostSeatChecks(ctx.config);
1359
- if (checks.length === 0) return { checks, failed: null };
1360
- if (isCoverageDeferred(ctx)) return { checks, skipped: true, failed: null };
1405
+ if (checks.length === 0) return { checks, failures: [] };
1406
+ const skipReason = postSeatSkipReason(ctx);
1407
+ if (skipReason) return { checks, skipped: skipReason, failures: [] };
1408
+ const failures = [];
1361
1409
  for (const [i, check] of checks.entries()) {
1362
1410
  const res = await run(`post-seat-${i + 1}`, check.cmd, check.args);
1363
- if (res.status !== 0)
1364
- return { checks, failed: postSeatFailure(check, res) };
1411
+ if (res.status !== 0) failures.push(postSeatFailure(check, res));
1365
1412
  }
1366
- releaseHeldLint(ctx);
1367
- return { checks, failed: null };
1413
+ if (failures.length === 0) releaseHeldLint(ctx);
1414
+ return { checks, failures };
1368
1415
  }
1369
1416
 
1370
1417
  /** A failed post-seat check as the handoff's finding. */
@@ -1377,11 +1424,17 @@ function postSeatFailure(check, res) {
1377
1424
  };
1378
1425
  }
1379
1426
 
1380
- /** @param {string} name @param {{ finding: string, evidencePath: string, gate: string }} failed */
1381
- function postSeatFixRequired(name, failed) {
1382
- return fixRequired(name, failed.finding, {
1383
- evidencePath: failed.evidencePath,
1384
- gate: failed.gate,
1427
+ /** One `fix-required` listing every post-capture finding, in run order. */
1428
+ function postCaptureFixRequired(ctx, name, failed) {
1429
+ const findings = failed.map((f) => ({
1430
+ check: f.gate,
1431
+ detail: `${f.finding}${raisedDuplicationSuffix(ctx, f, MAX_OFFENDING_LINES)}`,
1432
+ evidencePath: f.evidencePath,
1433
+ }));
1434
+ return fixRequired(name, findings.map((f) => f.detail).join('\n'), {
1435
+ evidencePath: findings[0].evidencePath,
1436
+ gate: findings[0].check,
1437
+ findings,
1385
1438
  cause: 'post-capture',
1386
1439
  });
1387
1440
  }
@@ -1392,7 +1445,7 @@ function settledPostCapture(name, gates, post) {
1392
1445
  if (post.checks.length > 0) {
1393
1446
  names.push(
1394
1447
  post.skipped
1395
- ? 'post-seat checks skipped (coverage deferred)'
1448
+ ? `post-seat checks skipped (${post.skipped})`
1396
1449
  : `${post.checks.length} post-seat check(s)`,
1397
1450
  );
1398
1451
  }
@@ -1441,6 +1494,9 @@ function stepOrder(depositor) {
1441
1494
  ];
1442
1495
  }
1443
1496
 
1497
+ /** `--report-all`: the steps that spawn no suite and write nothing. */
1498
+ const REPORT_ALL_STEPS = Object.freeze([stepPreflight, stepPostCapture]);
1499
+
1444
1500
  /** `run`'s results, each carrying the call's wall time as `durationMs`. */
1445
1501
  async function timed(ctx, run) {
1446
1502
  const startedAt = ctx.now();
@@ -1459,11 +1515,15 @@ function envelopeStep(ctx, { stop: _stop, ...rest }) {
1459
1515
 
1460
1516
  /**
1461
1517
  * Run the steps in order into `steps`; a step may settle several results.
1518
+ * A `--report-all` run continues past every finding and always ends
1519
+ * `fix-required`: nothing it did makes the branch ready to hand off.
1462
1520
  *
1463
1521
  * @returns {Promise<StepResult|null>} the result that stopped the run.
1464
1522
  */
1465
1523
  async function runSteps(ctx, steps) {
1466
- for (const step of stepOrder(ctx.depositor)) {
1524
+ const order = ctx.reportAll ? REPORT_ALL_STEPS : stepOrder(ctx.depositor);
1525
+ let first = null;
1526
+ for (const step of order) {
1467
1527
  ctx.stepName = handoffStepName(step);
1468
1528
  ctx.storyProgress.phase(ctx.stepName);
1469
1529
  const results = await timed(ctx, async () => [await step(ctx)].flat());
@@ -1472,9 +1532,29 @@ async function runSteps(ctx, steps) {
1472
1532
  ctx.progress(result.name, `${result.outcome} — ${result.detail}`);
1473
1533
  }
1474
1534
  const stop = results.find((r) => r.stop);
1475
- if (stop) return stop;
1535
+ if (stop && !ctx.reportAll) return stop;
1536
+ first ??= stop ?? null;
1476
1537
  }
1477
- return null;
1538
+ if (!ctx.reportAll || first) return first;
1539
+ const none = fixRequired(
1540
+ 'report-all',
1541
+ 'no findings in the non-suite steps; nothing was credited, seated or pushed, so run without --report-all to hand off',
1542
+ { cause: 'other' },
1543
+ );
1544
+ steps.push(none);
1545
+ return none;
1546
+ }
1547
+
1548
+ /** Every finding the steps settled; a step without a list is one finding. */
1549
+ function reportAllFindings(steps) {
1550
+ return steps
1551
+ .filter((s) => s.stop)
1552
+ .flatMap(
1553
+ (s) =>
1554
+ s.findings ?? [
1555
+ { check: s.name, detail: s.detail, evidencePath: s.evidencePath },
1556
+ ],
1557
+ );
1478
1558
  }
1479
1559
 
1480
1560
  const PRECHECK = Object.freeze({ cause: 'precheck' });
@@ -1574,7 +1654,7 @@ async function defaultBlock({
1574
1654
  }
1575
1655
 
1576
1656
  /**
1577
- * @param {{ storyId: number, cwd: string, config: object }} input
1657
+ * @param {{ storyId: number, cwd: string, config: object, reportAll?: boolean }} input
1578
1658
  * @param {{
1579
1659
  * git?: typeof gitSpawn,
1580
1660
  * runCommand?: (cmd: string, args: string[], opts: { cwd: string }) => Promise<{ status: number, stdout: string, stderr: string, timedOut?: boolean }>,
@@ -1611,7 +1691,10 @@ async function defaultBlock({
1611
1691
  * still gets its whole output written at settle.
1612
1692
  * @returns {Promise<{ envelope: object, exitCode: number }>}
1613
1693
  */
1614
- export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1694
+ export async function runStoryHandoff(
1695
+ { storyId, cwd, config, reportAll = false },
1696
+ deps,
1697
+ ) {
1615
1698
  const {
1616
1699
  git = gitSpawn,
1617
1700
  runCommand = spawnStreamAsync,
@@ -1639,6 +1722,8 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1639
1722
  runDuplicationRescore = runDuplicationCloseRescore,
1640
1723
  emitFriction = emitRuntimeFriction,
1641
1724
  admitSuite = withSuiteAdmission,
1725
+ pruneStaleCrap = pruneStaleCrapRows,
1726
+ isCaptureFreshFn = isCaptureFresh,
1642
1727
  writeSignal,
1643
1728
  readSignals,
1644
1729
  } = deps;
@@ -1685,6 +1770,9 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1685
1770
  runDuplicationRescore,
1686
1771
  emitFriction,
1687
1772
  admitSuite,
1773
+ pruneStaleCrap,
1774
+ isCaptureFresh: isCaptureFreshFn,
1775
+ reportAll,
1688
1776
  state: readState(statePath, progress),
1689
1777
  review: null,
1690
1778
  reviewPending: null,
@@ -1777,7 +1865,9 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1777
1865
  }
1778
1866
  : {}),
1779
1867
  attempt: await nextHandoffAttempt({ storyId, config, readFn: readSignals }),
1868
+ ...(reportAll ? { reportAll, findings: reportAllFindings(steps) } : {}),
1780
1869
  };
1870
+ if (reportAll) return { envelope, exitCode: EXIT_CODES[status] };
1781
1871
  writeFileAtomic(
1782
1872
  statePath,
1783
1873
  `${JSON.stringify({ state: ctx.state, envelope }, null, 2)}\n`,
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * orchestrate-inventory.js — read-only: every open PR in exactly one state,
5
+ * plus overlaps, inherited failures, landed Stories and runner backlog.
6
+ * With `--run-id` it appends the sweep to the run ledger and fills `changes[]`.
7
+ */
8
+
9
+ import path from 'node:path';
10
+ import { parseArgs } from 'node:util';
11
+
12
+ import { runAsCli } from './lib/cli-utils.js';
13
+ import { PROJECT_ROOT, resolveConfig } from './lib/config-resolver.js';
14
+ import { renderInventory, runInventory } from './lib/orchestrate/inventory.js';
15
+ import { ledgerPath } from './lib/orchestrate/ledger.js';
16
+
17
+ const USAGE = {
18
+ invocation:
19
+ 'node .agents/scripts/orchestrate-inventory.js [--run-id <id>] [--json] [--cwd <main-repo>]',
20
+ summary:
21
+ 'Classify every open PR for /mandrel-orchestrate. Reads GitHub and git only; never a job log.',
22
+ flags: [
23
+ [
24
+ '--run-id <id>',
25
+ 'Append this sweep to the run ledger and report the PRs whose state changed.',
26
+ ],
27
+ ['--json', 'Print the orchestrate-inventory envelope as JSON.'],
28
+ ['--cwd <path>', 'Main-repo checkout (default: project root).'],
29
+ ],
30
+ notes: [
31
+ 'Over repo-scoped REST the merge queue is unreadable: `merge-queue` is listed in degraded[].',
32
+ ],
33
+ };
34
+
35
+ export function parseInventoryArgv(argv) {
36
+ const { values } = parseArgs({
37
+ args: argv,
38
+ options: {
39
+ 'run-id': { type: 'string' },
40
+ json: { type: 'boolean', default: false },
41
+ cwd: { type: 'string' },
42
+ },
43
+ strict: true,
44
+ });
45
+ return {
46
+ runId: values['run-id'] ?? null,
47
+ json: values.json,
48
+ cwd: path.resolve(values.cwd ?? PROJECT_ROOT),
49
+ };
50
+ }
51
+
52
+ /* node:coverage ignore next -- CLI wiring over the tested lib */
53
+ async function main() {
54
+ const args = parseInventoryArgv(process.argv.slice(2));
55
+ const config = resolveConfig({ cwd: args.cwd });
56
+ const envelope = await runInventory({
57
+ config,
58
+ cwd: args.cwd,
59
+ runId: args.runId,
60
+ ledgerFile: args.runId ? ledgerPath(args.runId, config) : null,
61
+ });
62
+ process.stdout.write(
63
+ args.json ? `${JSON.stringify(envelope)}\n` : renderInventory(envelope),
64
+ );
65
+ }
66
+
67
+ runAsCli(import.meta.url, main, {
68
+ source: 'orchestrate-inventory',
69
+ usage: USAGE,
70
+ });
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * orchestrate-ledger.js — the `/mandrel-orchestrate` run ledger: record the
5
+ * operator's authority once, record each action before it is taken (refusing
6
+ * an ungranted one), and print the hand-back summary.
7
+ *
8
+ * Exit codes: 0 recorded / printed, 2 refused (nothing written), 1 usage.
9
+ */
10
+
11
+ import path from 'node:path';
12
+ import { parseArgs } from 'node:util';
13
+
14
+ import { runAsCli } from './lib/cli-utils.js';
15
+ import { PROJECT_ROOT, resolveConfig } from './lib/config-resolver.js';
16
+ import {
17
+ ACTION_DEFAULTS,
18
+ ledgerPath,
19
+ readLedger,
20
+ recordAction,
21
+ recordAuthority,
22
+ renderSummary,
23
+ summarize,
24
+ } from './lib/orchestrate/ledger.js';
25
+
26
+ const USAGE = {
27
+ invocation:
28
+ 'node .agents/scripts/orchestrate-ledger.js <authority|record|summary> --run-id <id> [options]',
29
+ summary:
30
+ 'Authority, action records and the hand-back summary for one /mandrel-orchestrate run.',
31
+ flags: [
32
+ ['--run-id <id>', 'The orchestrate run (required).'],
33
+ [
34
+ '--grant <a[,b…]>',
35
+ `authority: the actions granted (${Object.keys(ACTION_DEFAULTS).join(', ')}).`,
36
+ ],
37
+ [
38
+ '--action <name>',
39
+ 'record: a granted action, or raise / follow-up (always allowed).',
40
+ ],
41
+ ['--pr <n>', 'record: the PR the action concerns.'],
42
+ ['--story <id>', 'record: the Story the action concerns.'],
43
+ ['--text <line>', 'record: one line saying what is being done.'],
44
+ ['--json', 'summary: print JSON.'],
45
+ ['--cwd <path>', 'Main-repo checkout (default: project root).'],
46
+ ],
47
+ notes: [
48
+ 'Exit 0 recorded, 2 refused (not-granted, already-raised, no-authority) with nothing written, 1 usage error.',
49
+ ],
50
+ };
51
+
52
+ const intOrNull = (v, flag) => {
53
+ if (v === undefined) return null;
54
+ const n = Number(v);
55
+ if (!Number.isInteger(n) || n <= 0)
56
+ throw new Error(`${flag} must be a positive integer (got "${v}")`);
57
+ return n;
58
+ };
59
+
60
+ export function parseLedgerArgv(argv) {
61
+ const { values, positionals } = parseArgs({
62
+ args: argv,
63
+ allowPositionals: true,
64
+ options: {
65
+ 'run-id': { type: 'string' },
66
+ grant: { type: 'string' },
67
+ action: { type: 'string' },
68
+ pr: { type: 'string' },
69
+ story: { type: 'string' },
70
+ text: { type: 'string' },
71
+ json: { type: 'boolean', default: false },
72
+ cwd: { type: 'string' },
73
+ },
74
+ strict: true,
75
+ });
76
+ const [command] = positionals;
77
+ if (!['authority', 'record', 'summary'].includes(command)) {
78
+ throw new Error('first argument must be authority, record or summary');
79
+ }
80
+ if (!values['run-id']) throw new Error('--run-id is required');
81
+ if (command === 'record' && !values.action)
82
+ throw new Error('record needs --action');
83
+ return {
84
+ command,
85
+ runId: values['run-id'],
86
+ grants: (values.grant ?? '')
87
+ .split(',')
88
+ .map((g) => g.trim())
89
+ .filter(Boolean),
90
+ action: values.action ?? null,
91
+ pr: intOrNull(values.pr, '--pr'),
92
+ story: intOrNull(values.story, '--story'),
93
+ text: values.text ?? '',
94
+ json: values.json,
95
+ cwd: path.resolve(values.cwd ?? PROJECT_ROOT),
96
+ };
97
+ }
98
+
99
+ /** @returns {number} the exit code */
100
+ export function runLedgerCommand(
101
+ args,
102
+ { file, now = Date.now(), out = process.stdout, err = process.stderr },
103
+ ) {
104
+ if (args.command === 'summary') {
105
+ const summary = summarize(readLedger(file));
106
+ out.write(
107
+ args.json ? `${JSON.stringify(summary)}\n` : renderSummary(summary),
108
+ );
109
+ return 0;
110
+ }
111
+ const result =
112
+ args.command === 'authority'
113
+ ? recordAuthority({ file, grants: args.grants, now })
114
+ : recordAction({
115
+ file,
116
+ action: args.action,
117
+ pr: args.pr,
118
+ story: args.story,
119
+ text: args.text,
120
+ now,
121
+ });
122
+ if (!result.ok) {
123
+ err.write(`[orchestrate-ledger] refused: ${result.reason}\n`);
124
+ return 2;
125
+ }
126
+ out.write(`${JSON.stringify(result.record)}\n`);
127
+ return 0;
128
+ }
129
+
130
+ /* node:coverage ignore next -- CLI wiring over the tested lib */
131
+ async function main() {
132
+ const args = parseLedgerArgv(process.argv.slice(2));
133
+ const config = resolveConfig({ cwd: args.cwd });
134
+ return runLedgerCommand(args, { file: ledgerPath(args.runId, config) });
135
+ }
136
+
137
+ runAsCli(import.meta.url, main, {
138
+ source: 'orchestrate-ledger',
139
+ propagateExitCode: true,
140
+ usage: USAGE,
141
+ });
@@ -42,6 +42,7 @@ import {
42
42
  planFastForward,
43
43
  } from './lib/orchestration/git-cleanup/phases/fast-forward.js';
44
44
  import { verifyRemote } from './lib/orchestration/remote-verifier.js';
45
+ import { resolveSharedBaseRef } from './lib/orchestration/review-base-ref.js';
45
46
  import {
46
47
  acquireStoryLease,
47
48
  releaseStoryLease,
@@ -448,6 +449,7 @@ export async function materializeBaseBranch({
448
449
  `Fetch completed after ${fetchResult.attempts} attempt(s) — packed-refs contention.`,
449
450
  );
450
451
  }
452
+ deepenShallowClone({ cwd, baseBranch, progress });
451
453
 
452
454
  const { worktreeSweep } = await reapMergedStoryBranches({
453
455
  cwd,
@@ -469,12 +471,47 @@ export async function materializeBaseBranch({
469
471
  return { worktreeSweep };
470
472
  }
471
473
 
472
- fastForwardBase({ cwd, baseBranch, progress });
474
+ reconcileLocalBase({ cwd, baseBranch, progress });
473
475
  return { worktreeSweep };
474
476
  }
475
477
 
478
+ /**
479
+ * Merge-base probes are meaningless against a truncated history.
480
+ *
481
+ * @param {{ cwd: string, baseBranch: string, progress: Function }} opts
482
+ */
483
+ function deepenShallowClone({ cwd, baseBranch, progress }) {
484
+ const probe = gitSpawn(cwd, 'rev-parse', '--is-shallow-repository');
485
+ if (String(probe.stdout ?? '').trim() !== 'true') return;
486
+ progress('GIT', `Shallow clone — deepening from origin/${baseBranch}.`);
487
+ const r = gitSpawn(cwd, 'fetch', '--unshallow', 'origin', baseBranch);
488
+ if (r.status !== 0) {
489
+ throw new Error(
490
+ `\`git fetch --unshallow origin ${baseBranch}\` failed: ${r.stderr || '(no stderr)'}`,
491
+ );
492
+ }
493
+ }
494
+
495
+ /**
496
+ * A base with no history in common cannot fast-forward: warn once and move on.
497
+ *
498
+ * @param {{ cwd: string, baseBranch: string, progress: Function }} opts
499
+ */
500
+ function reconcileLocalBase({ cwd, baseBranch, progress }) {
501
+ const probe = gitSpawn(cwd, 'merge-base', baseBranch, `origin/${baseBranch}`);
502
+ if (probe.status === 1) {
503
+ progress(
504
+ 'GIT',
505
+ `⚠️ local ${baseBranch} shares no history with origin/${baseBranch}; leaving it as is.`,
506
+ );
507
+ return;
508
+ }
509
+ fastForwardBase({ cwd, baseBranch, progress });
510
+ }
511
+
476
512
  /**
477
513
  * `git fetch` leaves local base at the old tip until fast-forwarded.
514
+ * Best-effort: the Story branch seeds from the remote base regardless.
478
515
  *
479
516
  * @param {{ cwd: string, baseBranch: string, progress: Function }} opts
480
517
  */
@@ -497,7 +534,7 @@ function fastForwardBase({ cwd, baseBranch, progress }) {
497
534
  } else if (ff.reason === 'not-fast-forward') {
498
535
  progress(
499
536
  'GIT',
500
- `⚠️ local ${baseBranch} is not a fast-forward behind origin/${baseBranch}; seeding from local tip.`,
537
+ `⚠️ local ${baseBranch} is not a fast-forward behind origin/${baseBranch}; leaving it as is.`,
501
538
  );
502
539
  } else if (ff.reason === 'dirty-tree') {
503
540
  progress(
@@ -508,8 +545,9 @@ function fastForwardBase({ cwd, baseBranch, progress }) {
508
545
  }
509
546
 
510
547
  /**
511
- * Idempotent seed. Assumes `materializeBaseBranch` already fetched, so
512
- * tracking refs are authoritative (no `ls-remote`).
548
+ * Idempotent seed from `origin/<base>`, or the local base when no remote ref
549
+ * resolves. Assumes `materializeBaseBranch` already fetched, so tracking refs
550
+ * are authoritative (no `ls-remote`).
513
551
  *
514
552
  * @param {object} opts
515
553
  * @param {string} opts.cwd
@@ -521,7 +559,7 @@ export function seedStoryBranch({ cwd, storyBranch, baseBranch, progress }) {
521
559
  // No concurrent creator to race here, so create failures are fatal.
522
560
  seedStoryBranchRef({
523
561
  storyBranch,
524
- baseRef: baseBranch,
562
+ baseRef: resolveSharedBaseRef({ baseBranch, cwd }).ref ?? baseBranch,
525
563
  swallowCreateRace: false,
526
564
  spawn: (args) => gitSpawn(cwd, ...args),
527
565
  existsLocally: (b) => branchExistsLocally(b, cwd),
@@ -24,12 +24,16 @@ import { computeStoryReviewDeposit } from './story-review-compute.js';
24
24
 
25
25
  const USAGE = {
26
26
  invocation:
27
- 'node .agents/scripts/story-handoff.js --story <id> [--cwd <workCwd>]',
27
+ 'node .agents/scripts/story-handoff.js --story <id> [--cwd <workCwd>] [--report-all]',
28
28
  summary:
29
29
  "Run the story-worker's post-implementation tail — base merge, duplication re-score, preflight, the one credited run, baseline seating, push and held review — and print one envelope: ready (exit 0), fix-required (exit 2) or blocked (exit 1).",
30
30
  flags: [
31
31
  ['--story <id>', 'Story issue number; the branch is story-<id>.'],
32
32
  ['--cwd <path>', "The Story's worktree (default: the current directory)."],
33
+ [
34
+ '--report-all',
35
+ 'List every finding from preflight and post-capture in one fix-required envelope: spawns no suite, records no credit, seats, commits and pushes nothing, and runs no review.',
36
+ ],
33
37
  ],
34
38
  notes: [
35
39
  'Exit codes:\n 0 ready — hand off\n 2 fix-required — fix, commit, re-run (labels untouched)\n 1 blocked — agent::blocked + friction comment, or a usage error',
@@ -67,7 +71,7 @@ export async function runStoryHandoffCli(
67
71
  const workCwd = cwd ?? defaultCwd;
68
72
  const config = resolveConfigImpl({ cwd: workCwd });
69
73
  const outcome = await runHandoffImpl(
70
- { storyId, cwd: workCwd, config },
74
+ { storyId, cwd: workCwd, config, reportAll: argv.includes('--report-all') },
71
75
  {
72
76
  computeReview: computeStoryReviewDeposit,
73
77
  createProviderFn: createProvider,