mandrel 2.70.0 → 2.71.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 (64) 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/scripts/acceptance-eval.js +194 -15
  11. package/.agents/scripts/deliver-run.js +92 -43
  12. package/.agents/scripts/lib/audit-suite/index.js +1 -1
  13. package/.agents/scripts/lib/audit-suite/story-checklist.js +65 -0
  14. package/.agents/scripts/lib/audit-to-stories/audit-label-taxonomy.js +2 -2
  15. package/.agents/scripts/lib/bootstrap/issue-forms-template.js +1 -1
  16. package/.agents/scripts/lib/cli-args.js +22 -0
  17. package/.agents/scripts/lib/close-validation/gates.js +17 -3
  18. package/.agents/scripts/lib/config/agent-models.js +117 -0
  19. package/.agents/scripts/lib/config-settings-schema-delivery.js +13 -1
  20. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  21. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  22. package/.agents/scripts/lib/git/sync-from-base.js +89 -17
  23. package/.agents/scripts/lib/label-taxonomy.js +13 -3
  24. package/.agents/scripts/lib/notifications/notifier.js +11 -15
  25. package/.agents/scripts/lib/observability/close-telemetry.js +19 -3
  26. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  27. package/.agents/scripts/lib/orchestration/code-review.js +2 -2
  28. package/.agents/scripts/lib/orchestration/file-assumptions.js +45 -11
  29. package/.agents/scripts/lib/orchestration/plan-context.js +17 -10
  30. package/.agents/scripts/lib/orchestration/plan-persist/changes-repair.js +130 -24
  31. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +19 -16
  32. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +1 -0
  33. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +4 -3
  34. package/.agents/scripts/lib/orchestration/resolve-stories.js +10 -2
  35. package/.agents/scripts/lib/orchestration/review-providers/native.js +5 -165
  36. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +14 -2
  37. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +151 -56
  38. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +4 -0
  39. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +20 -4
  40. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +26 -17
  41. package/.agents/scripts/lib/orchestration/story-handoff.js +849 -0
  42. package/.agents/scripts/lib/orchestration/story-init-result.js +83 -0
  43. package/.agents/scripts/lib/orchestration/task-body-validator.js +35 -5
  44. package/.agents/scripts/lib/orchestration/ticket-validator-sizing.js +1 -1
  45. package/.agents/scripts/lib/orchestration/ticket-validator.js +20 -2
  46. package/.agents/scripts/lib/single-story/confirm-merge.js +44 -7
  47. package/.agents/scripts/lib/story-body/story-body.js +40 -5
  48. package/.agents/scripts/lib/templates/decomposer-prompts.js +33 -36
  49. package/.agents/scripts/single-story-close.js +8 -0
  50. package/.agents/scripts/single-story-init.js +17 -32
  51. package/.agents/scripts/story-handoff.js +112 -0
  52. package/.agents/scripts/sync-claude-agents.js +58 -27
  53. package/.agents/workflows/helpers/acceptance-self-eval.md +24 -18
  54. package/.agents/workflows/helpers/code-review.md +3 -3
  55. package/.agents/workflows/helpers/deliver-digest.md +79 -80
  56. package/.agents/workflows/helpers/deliver-light.md +9 -7
  57. package/.agents/workflows/helpers/deliver-reference.md +38 -22
  58. package/.agents/workflows/helpers/deliver-story-reference.md +11 -9
  59. package/.agents/workflows/helpers/deliver-story.md +30 -23
  60. package/.agents/workflows/helpers/plan-reference.md +24 -9
  61. package/docs/CHANGELOG.md +19 -0
  62. package/lib/cli/registry.js +7 -0
  63. package/package.json +4 -3
  64. package/.agents/scripts/lib/orchestration/review-providers/scoped-lint.js +0 -272
@@ -21,15 +21,10 @@ import {
21
21
  * Refuse when the declared baseline merge driver is unregistered: git would
22
22
  * text-merge generated baselines and silently land a wrong one on `main`.
23
23
  *
24
- * @param {string} cwd
25
- * @param {typeof defaultGitSpawn} gitSpawn
24
+ * @param {{ declared: boolean, command: string }} driver
26
25
  * @returns {{ synced: false, kind: 'merge-driver-missing', stderr: string, remedy: string }|null}
27
26
  */
28
- function refuseWithoutMergeDriver(cwd, gitSpawn) {
29
- const { declared, command } = probeBaselineMergeDriver({
30
- projectRoot: cwd,
31
- runGit: (args) => gitSpawn(cwd, ...args),
32
- });
27
+ function refuseWithoutMergeDriver({ declared, command }) {
33
28
  if (!declared || command.length > 0) return null;
34
29
  return {
35
30
  synced: false,
@@ -76,8 +71,41 @@ function diffPaths(gitSpawn, cwd, fromSha) {
76
71
  .filter((s) => s.length > 0);
77
72
  }
78
73
 
74
+ /** The paths `.gitattributes` routes through the driver: `baselines/*.json`. */
75
+ const DRIVER_OWNED_BASELINE = /^baselines\/[^/]+\.json$/;
76
+
79
77
  /**
80
- * A conflict is aborted before returning; the caller surfaces it.
78
+ * Take `origin/<base>`'s side of each conflicted baseline and commit the
79
+ * merge; the seat and close's gates re-derive the Story's rows. False on any
80
+ * failed step.
81
+ *
82
+ * @param {typeof defaultGitSpawn} gitSpawn
83
+ * @param {string} cwd
84
+ * @param {string} baseBranch
85
+ * @param {string[]} files
86
+ * @returns {boolean}
87
+ */
88
+ function resolveBaselinesToBase(gitSpawn, cwd, baseBranch, files) {
89
+ const steps = [
90
+ ['checkout', `origin/${baseBranch}`, '--', ...files],
91
+ ['add', '--', ...files],
92
+ ['commit', '--no-edit'],
93
+ ];
94
+ return steps.every((args) => gitSpawn(cwd, ...args).status === 0);
95
+ }
96
+
97
+ function unmergedPaths(gitSpawn, cwd) {
98
+ const unmerged = gitSpawn(cwd, 'diff', '--name-only', '--diff-filter=U');
99
+ return (unmerged.stdout ?? '')
100
+ .toString()
101
+ .split(/\r?\n/)
102
+ .map((s) => s.trim())
103
+ .filter((s) => s.length > 0);
104
+ }
105
+
106
+ /**
107
+ * A baseline-only conflict resolves to the base (`resolvedBaselineFiles`);
108
+ * any other conflict is aborted for the caller to surface.
81
109
  *
82
110
  * @param {object} opts
83
111
  * @param {string} opts.cwd Branch must already be checked out.
@@ -89,7 +117,7 @@ function diffPaths(gitSpawn, cwd, fromSha) {
89
117
  * @returns {Promise<
90
118
  * | { synced: true, kind: 'noop-already-current', changedPaths: string[] }
91
119
  * | { synced: true, kind: 'fast-forward', changedPaths: string[] }
92
- * | { synced: true, kind: 'merge-commit', changedPaths: string[] }
120
+ * | { synced: true, kind: 'merge-commit', changedPaths: string[], resolvedBaselineFiles?: string[] }
93
121
  * | { synced: false, kind: 'fetch-failed', stderr: string }
94
122
  * | { synced: false, kind: 'conflict', conflictFiles: string[] }
95
123
  * | { synced: false, kind: 'merge-failed', stderr: string }
@@ -111,7 +139,11 @@ export async function syncBranchFromBase({
111
139
  );
112
140
  }
113
141
 
114
- const driverGap = refuseWithoutMergeDriver(cwd, gitSpawn);
142
+ const driver = probeBaselineMergeDriver({
143
+ projectRoot: cwd,
144
+ runGit: (args) => gitSpawn(cwd, ...args),
145
+ });
146
+ const driverGap = refuseWithoutMergeDriver(driver);
115
147
  if (driverGap) {
116
148
  log('SYNC', driverGap.stderr);
117
149
  return driverGap;
@@ -166,16 +198,56 @@ export async function syncBranchFromBase({
166
198
  };
167
199
  }
168
200
 
169
- const unmerged = gitSpawn(cwd, 'diff', '--name-only', '--diff-filter=U');
170
- const conflictFiles = (unmerged.stdout ?? '')
171
- .toString()
172
- .split(/\r?\n/)
173
- .map((s) => s.trim())
174
- .filter((s) => s.length > 0);
201
+ const conflictFiles = unmergedPaths(gitSpawn, cwd);
202
+ const resolved = resolveBaselineOnlyConflict({
203
+ gitSpawn,
204
+ cwd,
205
+ baseBranch,
206
+ driver,
207
+ conflictFiles,
208
+ preMergeHead,
209
+ log,
210
+ });
211
+ if (resolved) return resolved;
175
212
 
176
- // Always abort: a half-merged worktree blocks the next recovery.
213
+ // A half-merged worktree blocks the next recovery.
177
214
  gitSpawn(cwd, 'merge', '--abort');
215
+ return failedMergeResult(conflictFiles, merge);
216
+ }
217
+
218
+ /** The resolved merge-commit result, or null for any other conflict. */
219
+ function resolveBaselineOnlyConflict({
220
+ gitSpawn,
221
+ cwd,
222
+ baseBranch,
223
+ driver,
224
+ conflictFiles,
225
+ preMergeHead,
226
+ log,
227
+ }) {
228
+ const baselineOnly =
229
+ driver.declared &&
230
+ conflictFiles.length > 0 &&
231
+ conflictFiles.every((f) => DRIVER_OWNED_BASELINE.test(f));
232
+ if (
233
+ !baselineOnly ||
234
+ !resolveBaselinesToBase(gitSpawn, cwd, baseBranch, conflictFiles)
235
+ ) {
236
+ return null;
237
+ }
238
+ log(
239
+ 'SYNC',
240
+ `Resolved baseline-only conflict to origin/${baseBranch}: ${conflictFiles.join(', ')}`,
241
+ );
242
+ return {
243
+ synced: true,
244
+ kind: 'merge-commit',
245
+ changedPaths: diffPaths(gitSpawn, cwd, preMergeHead),
246
+ resolvedBaselineFiles: conflictFiles,
247
+ };
248
+ }
178
249
 
250
+ function failedMergeResult(conflictFiles, merge) {
179
251
  if (conflictFiles.length > 0) {
180
252
  return { synced: false, kind: 'conflict', conflictFiles };
181
253
  }
@@ -32,13 +32,12 @@ export const LABEL_TAXONOMY = [
32
32
  name: AGENT_LABELS.REVIEW_SPEC,
33
33
  color: LABEL_COLORS.AGENT,
34
34
  description:
35
- 'Parking state — Tech Spec exists; awaiting human review before decomposition',
35
+ 'Parking state — awaiting planning before delivery; run /mandrel-plan <id>',
36
36
  },
37
37
  {
38
38
  name: AGENT_LABELS.READY,
39
39
  color: LABEL_COLORS.AGENT,
40
- description:
41
- 'Parking state — frozen dispatch manifest exists; awaiting local /mandrel-deliver',
40
+ description: 'Parking state — planned; awaiting local /mandrel-deliver',
42
41
  },
43
42
  {
44
43
  name: AGENT_LABELS.EXECUTING,
@@ -76,6 +75,17 @@ export const LABEL_TAXONOMY = [
76
75
  },
77
76
  ];
78
77
 
78
+ /**
79
+ * The repo-wide description for `name`, so another taxonomy that creates the
80
+ * same label carries this one instead of its own copy.
81
+ *
82
+ * @param {string} name
83
+ * @returns {string|undefined}
84
+ */
85
+ export function labelDescription(name) {
86
+ return LABEL_TAXONOMY.find((row) => row.name === name)?.description;
87
+ }
88
+
79
89
  /** @type {Array<{ name: string, type: 'single_select', options?: string[] }>} */
80
90
  export const PROJECT_FIELD_DEFS = [
81
91
  {
@@ -4,8 +4,9 @@
4
4
  * their event allowlists; severity is envelope metadata:
5
5
  * - low — routine progress; `transitionTicketState` skips `notify()`.
6
6
  * - medium — operator-visible milestones (Story/Epic done, merged).
7
- * - high — operator must act: webhook prefix `[Action Required]`, and
8
- * comments always `@mention` the operator.
7
+ * - high — operator must act (Story/Epic blocked): webhook prefix
8
+ * `[Action Required]`, and comments always `@mention` the
9
+ * operator.
9
10
  *
10
11
  * The webhook URL comes only from `process.env.NOTIFICATION_WEBHOOK_URL`,
11
12
  * never from `.agentrc.json` or `.mcp.json`.
@@ -16,9 +17,9 @@ import { AGENT_LABELS } from '../label-constants.js';
16
17
  export const SEVERITY_RANK = Object.freeze({ low: 0, medium: 1, high: 2 });
17
18
 
18
19
  /**
19
- * Only a Story/Epic reaching `agent::done` rates `medium`; transitions never
20
- * reach `high`, which is reserved for explicit operator-action `notify()`
21
- * calls.
20
+ * A Story/Epic entering `agent::blocked` rates `high` — the protocol's one
21
+ * runtime pause point, so the operator must act. A Story/Epic reaching
22
+ * `agent::done` rates `medium`. Every other transition is `low`.
22
23
  *
23
24
  * @param {{ kind?: string, ticket?: { type?: string }, toState?: string|null }} event
24
25
  */
@@ -26,6 +27,7 @@ export function eventSeverity(event) {
26
27
  if (event?.kind === 'state-transition') {
27
28
  const type = event.ticket?.type;
28
29
  const isStoryOrEpic = type === 'story' || type === 'epic';
30
+ if (isStoryOrEpic && event.toState === AGENT_LABELS.BLOCKED) return 'high';
29
31
  if (isStoryOrEpic && event.toState === AGENT_LABELS.DONE) return 'medium';
30
32
  }
31
33
  return 'low';
@@ -33,16 +35,10 @@ export function eventSeverity(event) {
33
35
 
34
36
  /** Used as both comment body and webhook text. */
35
37
  export function renderTransitionMessage(event) {
36
- const type = event.ticket?.type ?? 'ticket';
37
- const id = event.ticket?.id;
38
- const title = event.ticket?.title ?? '';
39
- const toState = event.toState ?? '';
40
- const fromState = event.fromState ?? '';
41
- let summary = fromState
42
- ? `${type} #${id} · \`${fromState}\` → \`${toState}\``
43
- : `${type} #${id} · → \`${toState}\``;
44
- if (title) summary += ` — ${title.slice(0, 80)}`;
45
- return summary;
38
+ const ticket = event.ticket ?? {};
39
+ const from = event.fromState ? `\`${event.fromState}\` ` : '';
40
+ const summary = `${ticket.type ?? 'ticket'} #${ticket.id} · ${from}→ \`${event.toState ?? ''}\``;
41
+ return ticket.title ? `${summary} — ${ticket.title.slice(0, 80)}` : summary;
46
42
  }
47
43
 
48
44
  export function resolveWebhookUrl() {
@@ -8,7 +8,7 @@
8
8
 
9
9
  import crypto from 'node:crypto';
10
10
 
11
- import { parseWorkerTokens } from '../cli-args.js';
11
+ import { parseWorkerModel, parseWorkerTokens } from '../cli-args.js';
12
12
  import { Logger } from '../Logger.js';
13
13
  import { EVENT_KINDS } from '../signals/schema.js';
14
14
  import {
@@ -246,13 +246,15 @@ async function readStoryTally({ storyId, config, readFn = forEachLine }) {
246
246
 
247
247
  /**
248
248
  * @param {{ storyId: number, config?: object, workerTokens?: number|null,
249
- * landed?: boolean, readFn?: typeof forEachLine }} args
249
+ * workerModel?: string|null, landed?: boolean,
250
+ * readFn?: typeof forEachLine }} args
250
251
  * @returns {Promise<object>}
251
252
  */
252
253
  async function buildCloseTelemetry({
253
254
  storyId,
254
255
  config,
255
256
  workerTokens = null,
257
+ workerModel = null,
256
258
  landed = false,
257
259
  readFn,
258
260
  }) {
@@ -265,6 +267,7 @@ async function buildCloseTelemetry({
265
267
  confirmedHaltsByProvider: confirmedHalts(tally, landed),
266
268
  },
267
269
  workerTokens: Number.isInteger(workerTokens) ? workerTokens : null,
270
+ workerModel,
268
271
  };
269
272
  }
270
273
 
@@ -296,12 +299,23 @@ export function resolveWorkerTokens(raw) {
296
299
  return tokens;
297
300
  }
298
301
 
302
+ /**
303
+ * @param {unknown} raw
304
+ * @returns {string|null}
305
+ */
306
+ export function resolveWorkerModel(raw) {
307
+ const { model, warning } = parseWorkerModel(raw);
308
+ if (warning) Logger.warn(`[single-story-close] ${warning}`);
309
+ return model;
310
+ }
311
+
299
312
  /**
300
313
  * The retry goes first so the summary counts it; a failure leaves
301
314
  * `telemetry: null` and the close's status untouched.
302
315
  *
303
316
  * @param {{ terminal: object, result?: object|null, config?: object,
304
- * workerTokens?: number|null, readFn?: typeof forEachLine }} args
317
+ * workerTokens?: number|null, workerModel?: string|null,
318
+ * readFn?: typeof forEachLine }} args
305
319
  * @returns {Promise<void>}
306
320
  */
307
321
  export async function recordCloseTelemetry({
@@ -309,6 +323,7 @@ export async function recordCloseTelemetry({
309
323
  result,
310
324
  config,
311
325
  workerTokens = null,
326
+ workerModel = null,
312
327
  readFn,
313
328
  }) {
314
329
  await emitCloseRetrySignal({ envelope: terminal, config });
@@ -318,6 +333,7 @@ export async function recordCloseTelemetry({
318
333
  storyId: result.storyId,
319
334
  config,
320
335
  workerTokens,
336
+ workerModel,
321
337
  landed: terminal?.status === 'landed',
322
338
  readFn,
323
339
  });
@@ -75,6 +75,7 @@ const FRAMEWORK_SCRIPT_BASENAMES = Object.freeze([
75
75
  'single-story-confirm-merge.js',
76
76
  'single-story-init.js',
77
77
  'stories-wave-tick.js',
78
+ 'story-handoff.js',
78
79
  'story-review-compute.js',
79
80
  'sync-agentrc.js',
80
81
  'sync-claude-agents.js',
@@ -143,8 +143,8 @@ function resolveProviderName(codeReviewConfig, reviewProvider) {
143
143
  /**
144
144
  * `opts.changedFiles` has three states: an array is used verbatim; `null`
145
145
  * means the caller already found the diff unenumerable (fail-safe tier, no
146
- * retry); absent means enumerate here. The close path always injects, so
147
- * review and lens pass agree on what changed.
146
+ * retry); absent means enumerate here. The close path always injects the
147
+ * change set it derived, so the review scores the same files close routed.
148
148
  */
149
149
  function resolveInjectedChangedFiles({ opts, baseRef, headRef }) {
150
150
  if (opts.changedFiles === undefined) {
@@ -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'