mandrel 2.70.0 → 2.72.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 (79) hide show
  1. package/.agents/README.md +8 -9
  2. package/.agents/agents/acceptance-critic.md +1 -0
  3. package/.agents/agents/auditor.md +1 -0
  4. package/.agents/agents/plan-critic.md +1 -0
  5. package/.agents/agents/story-worker.md +63 -64
  6. package/.agents/docs/agentrc-reference.json +2 -1
  7. package/.agents/docs/configuration.md +7 -8
  8. package/.agents/rules/git-conventions-reference.md +2 -2
  9. package/.agents/schemas/agentrc.schema.json +19 -2
  10. package/.agents/schemas/story-deliver-terminal.schema.json +10 -1
  11. package/.agents/scripts/acceptance-eval.js +194 -15
  12. package/.agents/scripts/deliver-run.js +92 -43
  13. package/.agents/scripts/lib/audit-suite/index.js +1 -1
  14. package/.agents/scripts/lib/audit-suite/story-checklist.js +65 -0
  15. package/.agents/scripts/lib/audit-to-stories/audit-label-taxonomy.js +2 -2
  16. package/.agents/scripts/lib/bootstrap/issue-forms-template.js +1 -1
  17. package/.agents/scripts/lib/cli-args.js +22 -0
  18. package/.agents/scripts/lib/close-validation/gates.js +17 -3
  19. package/.agents/scripts/lib/config/agent-models.js +117 -0
  20. package/.agents/scripts/lib/config-settings-schema-delivery.js +13 -1
  21. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  22. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  23. package/.agents/scripts/lib/git/sync-from-base.js +89 -17
  24. package/.agents/scripts/lib/label-taxonomy.js +13 -3
  25. package/.agents/scripts/lib/notifications/notifier.js +11 -15
  26. package/.agents/scripts/lib/observability/close-telemetry.js +19 -3
  27. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  28. package/.agents/scripts/lib/orchestration/cancelled-run-discount.js +129 -0
  29. package/.agents/scripts/lib/orchestration/code-review.js +2 -2
  30. package/.agents/scripts/lib/orchestration/deliver-recover.js +166 -34
  31. package/.agents/scripts/lib/orchestration/file-assumptions.js +45 -11
  32. package/.agents/scripts/lib/orchestration/plan-context.js +17 -10
  33. package/.agents/scripts/lib/orchestration/plan-persist/changes-repair.js +130 -24
  34. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +19 -16
  35. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +1 -0
  36. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +4 -3
  37. package/.agents/scripts/lib/orchestration/pr-watch.js +14 -3
  38. package/.agents/scripts/lib/orchestration/resolve-stories.js +10 -2
  39. package/.agents/scripts/lib/orchestration/review-providers/native.js +5 -165
  40. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +14 -2
  41. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +45 -0
  42. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +162 -58
  43. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +58 -6
  44. package/.agents/scripts/lib/orchestration/single-story-close/phases/merge-wait-recovery.js +296 -0
  45. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +20 -4
  46. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +52 -6
  47. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +2 -2
  48. package/.agents/scripts/lib/orchestration/single-story-close/phases/story-branch-catch-up.js +50 -0
  49. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-reap.js +64 -52
  50. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-restore.js +133 -0
  51. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +187 -74
  52. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +46 -6
  53. package/.agents/scripts/lib/orchestration/story-handoff.js +849 -0
  54. package/.agents/scripts/lib/orchestration/story-init-result.js +83 -0
  55. package/.agents/scripts/lib/orchestration/task-body-validator.js +35 -5
  56. package/.agents/scripts/lib/orchestration/ticket-validator-sizing.js +1 -1
  57. package/.agents/scripts/lib/orchestration/ticket-validator.js +20 -2
  58. package/.agents/scripts/lib/single-story/confirm-merge.js +44 -7
  59. package/.agents/scripts/lib/story-body/story-body.js +40 -5
  60. package/.agents/scripts/lib/templates/decomposer-prompts.js +33 -36
  61. package/.agents/scripts/pr-watch-with-update.js +5 -0
  62. package/.agents/scripts/single-story-close.js +8 -0
  63. package/.agents/scripts/single-story-confirm-merge.js +34 -3
  64. package/.agents/scripts/single-story-init.js +17 -32
  65. package/.agents/scripts/story-handoff.js +112 -0
  66. package/.agents/scripts/sync-claude-agents.js +58 -27
  67. package/.agents/workflows/helpers/acceptance-self-eval.md +24 -18
  68. package/.agents/workflows/helpers/code-review.md +3 -3
  69. package/.agents/workflows/helpers/deliver-digest.md +79 -80
  70. package/.agents/workflows/helpers/deliver-light.md +9 -7
  71. package/.agents/workflows/helpers/deliver-reference.md +38 -22
  72. package/.agents/workflows/helpers/deliver-story-reference.md +39 -18
  73. package/.agents/workflows/helpers/deliver-story.md +30 -23
  74. package/.agents/workflows/helpers/plan-reference.md +24 -9
  75. package/.agents/workflows/helpers/worktree-lifecycle.md +5 -5
  76. package/docs/CHANGELOG.md +31 -0
  77. package/lib/cli/registry.js +7 -0
  78. package/package.json +4 -3
  79. package/.agents/scripts/lib/orchestration/review-providers/scoped-lint.js +0 -272
@@ -18,6 +18,11 @@ import {
18
18
  deriveChecksStatus,
19
19
  isPrMerged,
20
20
  } from './merge-poll.js';
21
+ import { readMergeQueueState as defaultReadMergeQueueState } from './merge-queue.js';
22
+ import {
23
+ closeArmedPr,
24
+ manualArmCommand,
25
+ } from './single-story-close/phases/auto-merge.js';
21
26
  import { NEXT_COMMANDS } from './story-deliver-terminal.js';
22
27
  import { STATE_LABELS } from './ticketing.js';
23
28
 
@@ -87,25 +92,82 @@ export function probeBranch({ cwd, storyBranch, config, gitSpawnFn }) {
87
92
  };
88
93
  }
89
94
 
95
+ /**
96
+ * Whether the row carries an auto-merge request; `undefined` when the field
97
+ * was not returned, so an unread field never reads as a disarm.
98
+ *
99
+ * @param {object|null|undefined} row
100
+ * @returns {boolean|undefined}
101
+ */
102
+ function readAutoMergeArmed(row) {
103
+ if (!row || !Object.hasOwn(row, 'autoMergeRequest')) return undefined;
104
+ return row.autoMergeRequest != null;
105
+ }
106
+
107
+ /**
108
+ * Merge-queue facts for an open, un-armed PR only: GitHub clears the
109
+ * auto-merge request on enqueue, so a queued PR looks un-armed. A read.
110
+ *
111
+ * @returns {Promise<{ inMergeQueue?: boolean|null, queueRequired?: boolean|null }>}
112
+ */
113
+ async function probePrQueue({ pr, nodeId, gh, readMergeQueueStateFn }) {
114
+ if (pr.state !== 'OPEN' || pr.autoMergeArmed !== false) return {};
115
+ const queue = await readMergeQueueStateFn({
116
+ prNumber: pr.number,
117
+ prNodeId: typeof nodeId === 'string' && nodeId ? nodeId : undefined,
118
+ gh,
119
+ });
120
+ return {
121
+ inMergeQueue: queue?.inQueue ?? null,
122
+ queueRequired: queue?.queueRequired ?? null,
123
+ };
124
+ }
125
+
90
126
  /**
91
127
  * `--state all`: the merged-but-label-stale strand needs the merged PR.
92
128
  *
93
129
  * @returns {Promise<object|null>}
94
130
  */
95
- export async function probePr({ storyBranch, gh = defaultGh }) {
131
+ export async function probePr({
132
+ storyBranch,
133
+ gh = defaultGh,
134
+ readMergeQueueStateFn = defaultReadMergeQueueState,
135
+ }) {
96
136
  try {
97
137
  const rows = await gh.pr.list(
98
138
  ['--head', storyBranch, '--state', 'all'],
99
- ['number', 'url', 'state', 'mergedAt', 'statusCheckRollup'],
139
+ [
140
+ 'number',
141
+ 'url',
142
+ 'state',
143
+ 'mergedAt',
144
+ 'statusCheckRollup',
145
+ 'mergeStateStatus',
146
+ 'autoMergeRequest',
147
+ 'headRefOid',
148
+ 'id',
149
+ ],
100
150
  );
101
151
  if (!Array.isArray(rows) || rows.length === 0) return null;
102
152
  const row = rows[0];
103
- return {
153
+ const pr = {
104
154
  number: Number(row?.number) || null,
105
155
  url: row?.url ?? null,
106
156
  state: row?.state ?? null,
107
157
  mergedAt: row?.mergedAt ?? null,
108
158
  checksStatus: deriveChecksStatus(row?.statusCheckRollup),
159
+ mergeStateStatus: row?.mergeStateStatus ?? null,
160
+ autoMergeArmed: readAutoMergeArmed(row),
161
+ headSha: row?.headRefOid ?? null,
162
+ };
163
+ return {
164
+ ...pr,
165
+ ...(await probePrQueue({
166
+ pr,
167
+ nodeId: row?.id,
168
+ gh,
169
+ readMergeQueueStateFn,
170
+ })),
109
171
  };
110
172
  } catch (err) {
111
173
  return { error: String(err?.message ?? err) };
@@ -380,6 +442,8 @@ export function decideRecovery({
380
442
  `issue=${ticket?.issueState ?? 'unknown'}`,
381
443
  `pr=${pr?.number ? `#${pr.number} ${pr.state ?? '?'}` : 'none'}`,
382
444
  `checks=${pr?.checksStatus ?? 'n/a'}`,
445
+ `mergeState=${pr?.mergeStateStatus ?? 'n/a'}`,
446
+ `autoMerge=${pr?.autoMergeArmed === undefined ? 'n/a' : pr.autoMergeArmed ? 'armed' : 'unarmed'}`,
383
447
  `branch.local=${branch?.local ?? false}`,
384
448
  `branch.remote=${branch?.remote ?? false}`,
385
449
  `worktree=${branch?.worktreePath ?? 'none'}`,
@@ -427,37 +491,7 @@ export function decideRecovery({
427
491
  }
428
492
 
429
493
  if (label === STATE_LABELS.CLOSING) {
430
- if (pr?.checksStatus === 'failure') {
431
- return {
432
- shape: 'closing-pr-red',
433
- nextCommand: NEXT_COMMANDS.watchCi(storyId, pr.number),
434
- detail:
435
- `PR #${pr.number} has a red required check. Waiting cannot help — fix the ` +
436
- `failure and push a new commit on \`story-${storyId}\`; the red disarmed ` +
437
- `auto-merge, and only a green on a new head SHA re-arms it.`,
438
- evidence,
439
- };
440
- }
441
- if (pr?.number) {
442
- return {
443
- shape: 'closing-pr-pending',
444
- nextCommand: NEXT_COMMANDS.resumeLand(storyId),
445
- detail:
446
- `PR #${pr.number} is open and healthy. This is the normal resumable shape after ` +
447
- `a bounded merge wait returned \`pending\`. The confirm CLI polls it to a ` +
448
- `confirmed merge and runs the land tail.`,
449
- evidence,
450
- };
451
- }
452
- return {
453
- shape: 'closing-no-pr',
454
- nextCommand: NEXT_COMMANDS.close(storyId),
455
- detail:
456
- `Story is at \`agent::closing\` but no PR exists for \`story-${storyId}\`. The ` +
457
- `close did not reach the pull-request phase; re-run it (close is idempotent and ` +
458
- `reuses an existing PR when one is found).`,
459
- evidence,
460
- };
494
+ return decideClosing({ storyId, branch, pr, closeArtifacts, evidence });
461
495
  }
462
496
 
463
497
  if (label === STATE_LABELS.EXECUTING) {
@@ -474,6 +508,104 @@ export function decideRecovery({
474
508
  };
475
509
  }
476
510
 
511
+ /**
512
+ * `main` moved under the PR and it no longer merges cleanly. Close re-syncs
513
+ * in the Story worktree (recreating it when missing).
514
+ */
515
+ function conflictedVerdict({ storyId, branch, pr, evidence }) {
516
+ const worktree = branch?.worktreePath ?? `.worktrees/story-${storyId}`;
517
+ return {
518
+ shape: 'closing-pr-conflicted',
519
+ nextCommand: NEXT_COMMANDS.close(storyId),
520
+ detail:
521
+ `PR #${pr.number} is DIRTY: its base moved and it no longer merges cleanly, so ` +
522
+ `waiting cannot land it. Re-run close: it merges origin/<base> into \`story-${storyId}\` ` +
523
+ `in the Story worktree (\`${worktree}\`), recreating that worktree when it is missing, ` +
524
+ `and pushes a clean merge. If close reports conflicted files, resolve exactly those in ` +
525
+ `the worktree, commit, and re-run close.`,
526
+ evidence,
527
+ };
528
+ }
529
+
530
+ /** A new head disarmed auto-merge; the resumed wait re-arms it. */
531
+ function unarmedVerdict({ storyId, pr, evidence }) {
532
+ const command = `\`${manualArmCommand({ prNumber: pr.number, queueRequired: pr.queueRequired === true })}\``;
533
+ const manual =
534
+ pr.queueRequired === true
535
+ ? `${command} (the base requires a merge queue, so the queue rule picks the strategy)`
536
+ : command;
537
+ return {
538
+ shape: 'closing-pr-unarmed',
539
+ nextCommand: NEXT_COMMANDS.resumeLand(storyId),
540
+ detail:
541
+ `PR #${pr.number} is open with no red check, but it has NO auto-merge request — a new ` +
542
+ `head disarmed it, so nothing will ever merge it. The resumed merge wait re-arms it ` +
543
+ `(once per head SHA, unless a CI red was recorded against this same head). The manual ` +
544
+ `equivalent is ${manual}.`,
545
+ evidence,
546
+ };
547
+ }
548
+
549
+ /**
550
+ * Un-armed by a new head — only when the last close's envelope proves close
551
+ * armed it; an operator-owned PR (`--no-auto-merge`, `strict`) is never one.
552
+ */
553
+ function isUnarmed(pr, closeArtifacts) {
554
+ const envelope = closeArtifacts?.envelope;
555
+ return (
556
+ closeArmedPr(envelope?.pr) &&
557
+ pr?.state === 'OPEN' &&
558
+ pr.autoMergeArmed === false &&
559
+ pr.inMergeQueue !== true &&
560
+ pr.checksStatus !== 'failure'
561
+ );
562
+ }
563
+
564
+ /**
565
+ * The `agent::closing` rows; conflicted and un-armed come before red.
566
+ *
567
+ * @returns {{ shape: string, nextCommand: string, detail: string, evidence: string[] }}
568
+ */
569
+ function decideClosing({ storyId, branch, pr, closeArtifacts, evidence }) {
570
+ if (pr?.number && pr.mergeStateStatus === 'DIRTY') {
571
+ return conflictedVerdict({ storyId, branch, pr, evidence });
572
+ }
573
+ if (pr?.number && isUnarmed(pr, closeArtifacts)) {
574
+ return unarmedVerdict({ storyId, pr, evidence });
575
+ }
576
+ if (pr?.checksStatus === 'failure') {
577
+ return {
578
+ shape: 'closing-pr-red',
579
+ nextCommand: NEXT_COMMANDS.watchCi(storyId, pr.number),
580
+ detail:
581
+ `PR #${pr.number} has a red required check. Waiting cannot help — fix the ` +
582
+ `failure and push a new commit on \`story-${storyId}\`; the red disarmed ` +
583
+ `auto-merge, and only a green on a new head SHA re-arms it.`,
584
+ evidence,
585
+ };
586
+ }
587
+ if (pr?.number) {
588
+ return {
589
+ shape: 'closing-pr-pending',
590
+ nextCommand: NEXT_COMMANDS.resumeLand(storyId),
591
+ detail:
592
+ `PR #${pr.number} is open and healthy. This is the normal resumable shape after ` +
593
+ `a bounded merge wait returned \`pending\`. The confirm CLI polls it to a ` +
594
+ `confirmed merge and runs the land tail.`,
595
+ evidence,
596
+ };
597
+ }
598
+ return {
599
+ shape: 'closing-no-pr',
600
+ nextCommand: NEXT_COMMANDS.close(storyId),
601
+ detail:
602
+ `Story is at \`agent::closing\` but no PR exists for \`story-${storyId}\`. The ` +
603
+ `close did not reach the pull-request phase; re-run it (close is idempotent and ` +
604
+ `reuses an existing PR when one is found).`,
605
+ evidence,
606
+ };
607
+ }
608
+
477
609
  /**
478
610
  * Shapes a live delivery may be mutating (e.g. a PR about to open), so they
479
611
  * earn a stability re-probe; the other shapes are settled.
@@ -12,7 +12,7 @@ import { gitSpawn } from '../git-utils.js';
12
12
  import { parse as parseStoryBody } from '../story-body/story-body.js';
13
13
  import { FILE_ASSUMPTION_VALUES } from './file-assumption-enum.js';
14
14
  import { computeStoryReachability } from './story-reachability.js';
15
- import { isObjectPathEntry } from './task-body-validator.js';
15
+ import { bareReferencePath, isObjectPathEntry } from './task-body-validator.js';
16
16
 
17
17
  /**
18
18
  * Existence probe at `baseBranchRef`; same semantics as
@@ -82,8 +82,11 @@ function defaultHistoryRunner({ baseBranchRef, path, cwd }) {
82
82
  }
83
83
 
84
84
  /**
85
+ * A bare `references[]` entry is a read, so it is derived as `exists` and
86
+ * flagged `derived` — the probe then warns, never refuses, when it is absent.
87
+ *
85
88
  * @param {object} story
86
- * @returns {Array<{ path: string, assumption: string, source: 'changes' | 'references' }>}
89
+ * @returns {Array<{ path: string, assumption: string, source: 'changes' | 'references', derived?: true }>}
87
90
  */
88
91
  export function collectStoryAssumptionEntries(story) {
89
92
  const out = [];
@@ -116,18 +119,30 @@ export function collectStoryAssumptionEntries(story) {
116
119
  }
117
120
  if (Array.isArray(structuredBody.references)) {
118
121
  for (const entry of structuredBody.references) {
119
- if (isObjectPathEntry(entry)) {
120
- out.push({
121
- path: entry.path,
122
- assumption: entry.assumption,
123
- source: 'references',
124
- });
125
- }
122
+ const read = referenceAssumptionEntry(entry);
123
+ if (read !== null) out.push(read);
126
124
  }
127
125
  }
128
126
  return out;
129
127
  }
130
128
 
129
+ /**
130
+ * @param {unknown} entry
131
+ * @returns {{ path: string, assumption: string, source: 'references', derived?: true }|null}
132
+ */
133
+ function referenceAssumptionEntry(entry) {
134
+ if (isObjectPathEntry(entry)) {
135
+ return {
136
+ path: entry.path,
137
+ assumption: entry.assumption,
138
+ source: 'references',
139
+ };
140
+ }
141
+ const path = bareReferencePath(entry);
142
+ if (path === null) return null;
143
+ return { path, assumption: 'exists', source: 'references', derived: true };
144
+ }
145
+
131
146
  /**
132
147
  * @param {object} story
133
148
  * @returns {boolean}
@@ -326,7 +341,7 @@ export function validateStoryFileAssumptions(opts) {
326
341
 
327
342
  const predecessors = reach.get(slug) ?? new Set();
328
343
 
329
- for (const { path, assumption, source } of entries) {
344
+ for (const { path, assumption, source, derived } of entries) {
330
345
  let baseExists = probeCache.get(path);
331
346
  if (baseExists === undefined) {
332
347
  baseExists = Boolean(gitRunner({ baseBranchRef, path, cwd }));
@@ -356,6 +371,7 @@ export function validateStoryFileAssumptions(opts) {
356
371
  predecessorCreator,
357
372
  });
358
373
  if (mismatch !== null) {
374
+ mismatch.derived = derived === true;
359
375
  const { kind, finding } = classifyMismatch(mismatch, probeHistory);
360
376
  if (kind === 'normalization') {
361
377
  normalizations.push(finding);
@@ -403,7 +419,25 @@ export function validateStoryFileAssumptions(opts) {
403
419
  */
404
420
  function routeMismatch(finding, { errors, warnings }) {
405
421
  const channel = finding.assumption === 'deletes' ? errors : warnings;
406
- channel.push(renderMismatch(finding));
422
+ channel.push(renderFinding(finding));
423
+ }
424
+
425
+ /**
426
+ * @param {object} finding
427
+ * @returns {string}
428
+ */
429
+ function renderFinding(finding) {
430
+ return finding.derived ? renderAbsentRead(finding) : renderMismatch(finding);
431
+ }
432
+
433
+ /**
434
+ * A bare reference is derived as `exists`, so its only mismatch is absence.
435
+ *
436
+ * @param {{ slug: string, source: string, path: string }} finding
437
+ * @returns {string}
438
+ */
439
+ function renderAbsentRead({ slug, source, path }) {
440
+ return `"${slug}" → body.${source} names ${path} as a read-first file but the path is absent at the base branch — fix the path or drop the entry.`;
407
441
  }
408
442
 
409
443
  /**
@@ -219,20 +219,27 @@ export function renderStoriesTemplate({ complexitySignals = null } = {}) {
219
219
  body: {
220
220
  goal: 'Fill: one sentence stating why this Story exists.',
221
221
  // A filled example: each line is a commit-boundary stage of the
222
- // work, never a restated acceptance item.
222
+ // work, never a restated acceptance item, ending in the command that
223
+ // proves the stage before the next one starts.
223
224
  slicing:
224
- '1. Re-anchor the shared constant and its consumers.\n' +
225
- '2. Move the gate ahead of the first write and arm the refusal.\n' +
226
- '3. Delete the superseded module, its test and its flag.\n' +
227
- '4. Regenerate the affected baselines; run the full gate chain.',
225
+ '1. Re-anchor the shared constant and its consumers — verify: node --test tests/constants.test.js\n' +
226
+ '2. Move the gate ahead of the first write and arm the refusal — verify: node --test tests/gate.test.js\n' +
227
+ '3. Delete the superseded module, its test and its flag — verify: npm run lint\n' +
228
+ '4. Regenerate the affected baselines; run the full gate chain — verify: npm test',
228
229
  spec:
229
- 'Optional — contract and invariants only: interfaces, status ' +
230
- 'codes, security invariants, and load-bearing constraints with ' +
231
- 'their why. Implementation choices belong to the deliverer unless ' +
232
- 'load-bearing. No per-file behavior paragraphs, no current-state ' +
233
- 'narration. As long as the work needs. ' +
230
+ 'Optional — the decided approach: choose every load-bearing ' +
231
+ 'mechanism and state it with its why; leave a choice open only ' +
232
+ 'when it is genuinely not load-bearing. Contract and invariants ' +
233
+ 'only — interfaces, status codes, security invariants — no ' +
234
+ 'per-file behavior paragraphs. As long as the work needs. ' +
234
235
  'Delete this field when acceptance[] carries the whole contract.',
236
+ context:
237
+ 'Optional — the facts you verified while planning, tersely: entry ' +
238
+ 'points (`path/to/file.ext` + symbol), the existing pattern to ' +
239
+ 'mirror, the test file or harness to extend, known traps, the ' +
240
+ 'scoped test command. Never a walkthrough. Delete when empty.',
235
241
  changes: buildTemplateChanges(complexitySignals),
242
+ references: ['path/to/read-first.ext'],
236
243
  non_goals: [],
237
244
  },
238
245
  acceptance: [
@@ -4,7 +4,10 @@
4
4
  * `{ path, assumption }` (probed at base: present → `refactors-existing`,
5
5
  * absent → `creates`), and a trailing parenthetical on a path is stripped.
6
6
  * Repairs are reported, not refused; an unsalvageable string is left for the
7
- * validator. Kept apart from the validator, whose collectors are pure.
7
+ * validator. A bare `references[]` entry naming a path present at base is
8
+ * derived as a read (`exists`); an absent one stays bare for the
9
+ * file-assumption probe to warn on. Kept apart from the validator, whose
10
+ * collectors are pure.
8
11
  *
9
12
  * @module lib/orchestration/plan-persist/changes-repair
10
13
  */
@@ -14,6 +17,8 @@ import { FILE_ASSUMPTION_VALUES } from '../file-assumption-enum.js';
14
17
 
15
18
  const CHANGES_HEADING_RE = /^#{2,3}\s+Changes\s*$/i;
16
19
 
20
+ const REFERENCES_HEADING_RE = /^#{2,3}\s+References\s*$/i;
21
+
17
22
  const ANY_HEADING_RE = /^#{1,6}\s+\S/;
18
23
 
19
24
  const TRAILING_PARENTHETICAL_RE = /\s*\([^)]*\)\s*$/;
@@ -150,7 +155,64 @@ function repairSectionLine(line, existsAtBase) {
150
155
  }
151
156
 
152
157
  /**
153
- * Touches only the `## Changes` section; the rest stays byte-identical.
158
+ * A bare reference present at base becomes `exists`; anything else is left.
159
+ *
160
+ * @param {unknown} item
161
+ * @param {(path: string) => boolean} existsAtBase
162
+ * @returns {{ entry: { path: string, assumption: 'exists' }, repair: object }|null}
163
+ */
164
+ function deriveReferenceItem(item, existsAtBase) {
165
+ const raw = typeof item === 'string' ? item : null;
166
+ const bareObject =
167
+ item !== null &&
168
+ typeof item === 'object' &&
169
+ item.assumption == null &&
170
+ typeof item.path === 'string';
171
+ const from = raw ?? (bareObject ? item.path : null);
172
+ if (from === null) return null;
173
+ const path = salvagePath(from);
174
+ if (path === null || !existsAtBase(path)) return null;
175
+ return {
176
+ entry: { path, assumption: 'exists' },
177
+ repair: {
178
+ field: 'references',
179
+ from,
180
+ path,
181
+ assumption: 'exists',
182
+ reason: 'derived-read',
183
+ },
184
+ };
185
+ }
186
+
187
+ /**
188
+ * @param {string} line
189
+ * @param {(path: string) => boolean} existsAtBase
190
+ * @returns {{ line: string, repair: object }|null}
191
+ */
192
+ function deriveReferenceLine(line, existsAtBase) {
193
+ const marker = line.match(/^(\s*[-*]\s+)/);
194
+ if (!marker) return null;
195
+ const content = line.slice(marker[1].length).trim();
196
+ if (content === '' || HUMANIZED_RE.test(content) || content.startsWith('{')) {
197
+ return null;
198
+ }
199
+ const derived = deriveReferenceItem(content, existsAtBase);
200
+ if (derived === null) return null;
201
+ return {
202
+ line: `${marker[1]}\`${derived.entry.path}\` — exists`,
203
+ repair: derived.repair,
204
+ };
205
+ }
206
+
207
+ /** Section repairers for the serialized body, keyed by heading. */
208
+ const SECTION_REPAIRERS = [
209
+ { heading: CHANGES_HEADING_RE, repairLine: repairSectionLine },
210
+ { heading: REFERENCES_HEADING_RE, repairLine: deriveReferenceLine },
211
+ ];
212
+
213
+ /**
214
+ * Touches only the `## Changes` / `## References` sections; the rest stays
215
+ * byte-identical.
154
216
  *
155
217
  * @param {string} body
156
218
  * @param {(path: string) => boolean} existsAtBase
@@ -159,19 +221,20 @@ function repairSectionLine(line, existsAtBase) {
159
221
  function repairSerializedBody(body, existsAtBase) {
160
222
  const lines = body.split('\n');
161
223
  const repairs = [];
162
- let inChanges = false;
224
+ let repairer = null;
163
225
  for (let i = 0; i < lines.length; i += 1) {
164
226
  const line = lines[i];
165
- if (CHANGES_HEADING_RE.test(line.trim())) {
166
- inChanges = true;
227
+ const opened = SECTION_REPAIRERS.find((r) => r.heading.test(line.trim()));
228
+ if (opened) {
229
+ repairer = opened;
167
230
  continue;
168
231
  }
169
- if (!inChanges) continue;
232
+ if (repairer === null) continue;
170
233
  if (ANY_HEADING_RE.test(line) || line.trim().startsWith('---')) {
171
- inChanges = false;
234
+ repairer = null;
172
235
  continue;
173
236
  }
174
- const repaired = repairSectionLine(line, existsAtBase);
237
+ const repaired = repairer.repairLine(line, existsAtBase);
175
238
  if (repaired === null) continue;
176
239
  lines[i] = repaired.line;
177
240
  repairs.push(repaired.repair);
@@ -179,6 +242,38 @@ function repairSerializedBody(body, existsAtBase) {
179
242
  return { body: lines.join('\n'), repairs };
180
243
  }
181
244
 
245
+ /**
246
+ * @param {unknown[]|null} list Mutated in place.
247
+ * @param {(item: unknown) => ({ entry: object, repair: object }|null)} repairItem
248
+ * @returns {object[]}
249
+ */
250
+ function repairList(list, repairItem) {
251
+ if (list === null) return [];
252
+ const repairs = [];
253
+ for (let i = 0; i < list.length; i += 1) {
254
+ const repaired = repairItem(list[i]);
255
+ if (repaired === null) continue;
256
+ list[i] = repaired.entry;
257
+ repairs.push(repaired.repair);
258
+ }
259
+ return repairs;
260
+ }
261
+
262
+ /**
263
+ * The body's own array when it has one, else the top-level field.
264
+ *
265
+ * @param {object} ticket
266
+ * @param {'changes'|'references'} field
267
+ * @returns {unknown[]|null}
268
+ */
269
+ function structuredList(ticket, field) {
270
+ const body = ticket.body;
271
+ if (body && typeof body === 'object' && Array.isArray(body[field])) {
272
+ return body[field];
273
+ }
274
+ return Array.isArray(ticket[field]) ? ticket[field] : null;
275
+ }
276
+
182
277
  /**
183
278
  * @param {object} ticket Mutated in place.
184
279
  * @param {(path: string) => boolean} existsAtBase
@@ -191,28 +286,39 @@ function repairTicket(ticket, existsAtBase) {
191
286
  if (repairs.length > 0) ticket.body = next;
192
287
  return repairs;
193
288
  }
194
- const changes =
195
- body && typeof body === 'object' && Array.isArray(body.changes)
196
- ? body.changes
197
- : Array.isArray(ticket.changes)
198
- ? ticket.changes
199
- : null;
200
- if (changes === null) return [];
201
- const repairs = [];
202
- for (let i = 0; i < changes.length; i += 1) {
203
- const repaired = repairStructuredItem(changes[i], existsAtBase);
204
- if (repaired === null) continue;
205
- changes[i] = repaired.entry;
206
- repairs.push(repaired.repair);
207
- }
208
- return repairs;
289
+ return [
290
+ ...repairList(structuredList(ticket, 'changes'), (item) =>
291
+ repairStructuredItem(item, existsAtBase),
292
+ ),
293
+ ...repairList(structuredList(ticket, 'references'), (item) =>
294
+ deriveReferenceItem(item, existsAtBase),
295
+ ),
296
+ ];
297
+ }
298
+
299
+ /**
300
+ * @param {{ slug: string, from: string, path: string, assumption: string, reason: string }} repair
301
+ * @returns {string}
302
+ */
303
+ export function renderChangeRepair(repair) {
304
+ return repair.reason === 'derived-read'
305
+ ? renderDerivedRead(repair)
306
+ : renderPathRepair(repair);
307
+ }
308
+
309
+ /**
310
+ * @param {{ slug: string, from: string, path: string }} repair
311
+ * @returns {string}
312
+ */
313
+ function renderDerivedRead({ slug, from, path }) {
314
+ return `Story "${slug}": references[] entry "${from}" derived as a read of an existing path — {"path":"${path}","assumption":"exists"} by probing base.`;
209
315
  }
210
316
 
211
317
  /**
212
318
  * @param {{ slug: string, from: string, path: string, assumption: string, reason: string }} repair
213
319
  * @returns {string}
214
320
  */
215
- export function renderChangeRepair({ slug, from, path, assumption, reason }) {
321
+ function renderPathRepair({ slug, from, path, assumption, reason }) {
216
322
  const why =
217
323
  reason === 'plain-string'
218
324
  ? 'plain-string bullet'
@@ -310,10 +310,11 @@ async function enforceReachability(reachability, config) {
310
310
  * @param {object} args
311
311
  * @returns {Promise<void>}
312
312
  */
313
- async function persistStoryArtifacts({ provider, created, summaryBody }) {
313
+ async function persistStoryArtifacts({ provider, created, summaryFor }) {
314
314
  await concurrentMap(
315
315
  created,
316
- (story) => writePlanSummaryComment(provider, story.id, summaryBody),
316
+ (story) =>
317
+ writePlanSummaryComment(provider, story.id, summaryFor(story.id)),
317
318
  { concurrency: FANOUT_CONCURRENCY },
318
319
  );
319
320
  await markStoriesReady({ provider, created });
@@ -506,22 +507,24 @@ export async function runPlanPersist({
506
507
  mode: dryRun ? 'dry-run' : 'persist',
507
508
  });
508
509
 
509
- const summaryBody = buildPlanSummaryCommentBody({
510
- epicId: primary.id,
511
- ticketCount: created.length,
512
- forceReview,
513
- freshness,
514
- healthcheck: { skipped: true },
515
- waveTable,
516
- mode: 'stories',
517
- planMetricsLine,
518
- stories: created,
519
- conflictFindings: assembledConflicts,
520
- waveCollisions,
521
- });
510
+ // Each Story's comment heading names that Story.
511
+ const summaryFor = (storyId) =>
512
+ buildPlanSummaryCommentBody({
513
+ storyId,
514
+ ticketCount: created.length,
515
+ forceReview,
516
+ freshness,
517
+ healthcheck: { skipped: true },
518
+ waveTable,
519
+ mode: 'stories',
520
+ planMetricsLine,
521
+ stories: created,
522
+ conflictFindings: assembledConflicts,
523
+ waveCollisions,
524
+ });
522
525
 
523
526
  if (!dryRun) {
524
- await persistStoryArtifacts({ provider, created, summaryBody });
527
+ await persistStoryArtifacts({ provider, created, summaryFor });
525
528
  }
526
529
 
527
530
  // Last among the writes: the Epic needs the children's numbers and database
@@ -202,6 +202,7 @@ function bodyObjectFromTicket(ticket) {
202
202
  goal: ticket.goal ?? '',
203
203
  slicing: ticket.slicing ?? '',
204
204
  spec: ticket.spec ?? '',
205
+ context: ticket.context ?? '',
205
206
  changes: ticket.changes ?? [],
206
207
  acceptance: ticket.acceptance ?? [],
207
208
  verify: ticket.verify ?? [],
@@ -89,11 +89,12 @@ function renderSharedEditorLines(conflictFindings) {
89
89
  }
90
90
 
91
91
  /**
92
- * @param {object} input
92
+ * @param {object} input `storyId` is the Story the comment is posted on; its
93
+ * heading names that Story, never a sibling.
93
94
  * @returns {string}
94
95
  */
95
96
  export function buildPlanSummaryCommentBody({
96
- epicId,
97
+ storyId,
97
98
  ticketCount,
98
99
  forceReview = false,
99
100
  freshness,
@@ -139,7 +140,7 @@ export function buildPlanSummaryCommentBody({
139
140
  : '/mandrel-deliver <storyId> [<storyId> ...]';
140
141
 
141
142
  return [
142
- `#### 📋 Plan Summary — Story #${epicId} is \`agent::ready\``,
143
+ `#### 📋 Plan Summary — Story #${storyId} is \`agent::ready\``,
143
144
  '',
144
145
  `- ${ticketCount} Story ticket(s) persisted: ${storyList}.`,
145
146
  ...reviewLines,