mandrel 2.69.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 (76) 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/audit-to-stories.js +39 -247
  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/audit-to-stories/finding-adapter.js +1 -1
  17. package/.agents/scripts/lib/bootstrap/issue-forms-template.js +1 -1
  18. package/.agents/scripts/lib/cli-args.js +22 -0
  19. package/.agents/scripts/lib/close-validation/gates.js +17 -3
  20. package/.agents/scripts/lib/config/agent-models.js +117 -0
  21. package/.agents/scripts/lib/config-settings-schema-delivery.js +13 -1
  22. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  23. package/.agents/scripts/lib/findings/route-finding.js +15 -0
  24. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  25. package/.agents/scripts/lib/git/sync-from-base.js +89 -17
  26. package/.agents/scripts/lib/label-taxonomy.js +13 -3
  27. package/.agents/scripts/lib/notifications/notifier.js +11 -15
  28. package/.agents/scripts/lib/observability/close-telemetry.js +19 -3
  29. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  30. package/.agents/scripts/lib/orchestration/code-review.js +2 -2
  31. package/.agents/scripts/lib/orchestration/file-assumptions.js +45 -11
  32. package/.agents/scripts/lib/orchestration/plan-context.js +31 -11
  33. package/.agents/scripts/lib/orchestration/plan-persist/audit-provenance.js +35 -117
  34. package/.agents/scripts/lib/orchestration/plan-persist/changes-repair.js +130 -24
  35. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +24 -22
  36. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +1 -0
  37. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +4 -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/base-sync.js +151 -56
  42. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +4 -0
  43. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +20 -4
  44. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +26 -17
  45. package/.agents/scripts/lib/orchestration/story-handoff.js +849 -0
  46. package/.agents/scripts/lib/orchestration/story-init-result.js +83 -0
  47. package/.agents/scripts/lib/orchestration/task-body-validator.js +35 -5
  48. package/.agents/scripts/lib/orchestration/ticket-validator-sizing.js +1 -1
  49. package/.agents/scripts/lib/orchestration/ticket-validator.js +20 -2
  50. package/.agents/scripts/lib/single-story/confirm-merge.js +44 -7
  51. package/.agents/scripts/lib/story-body/story-body.js +40 -5
  52. package/.agents/scripts/lib/templates/decomposer-prompts.js +33 -36
  53. package/.agents/scripts/single-story-close.js +8 -0
  54. package/.agents/scripts/single-story-init.js +17 -32
  55. package/.agents/scripts/story-handoff.js +112 -0
  56. package/.agents/scripts/sync-claude-agents.js +58 -27
  57. package/.agents/templates/docs/audit-sweep-runbook.md +29 -59
  58. package/.agents/workflows/audit-to-stories.md +40 -67
  59. package/.agents/workflows/helpers/acceptance-self-eval.md +24 -18
  60. package/.agents/workflows/helpers/code-review.md +3 -3
  61. package/.agents/workflows/helpers/deliver-digest.md +79 -80
  62. package/.agents/workflows/helpers/deliver-light.md +9 -7
  63. package/.agents/workflows/helpers/deliver-reference.md +38 -22
  64. package/.agents/workflows/helpers/deliver-story-reference.md +11 -9
  65. package/.agents/workflows/helpers/deliver-story.md +30 -23
  66. package/.agents/workflows/helpers/plan-reference.md +24 -9
  67. package/docs/CHANGELOG.md +30 -0
  68. package/lib/cli/registry.js +7 -0
  69. package/lib/migrations/index.js +2 -0
  70. package/lib/migrations/steps/2.70.0-retire-audit-ledger.js +36 -0
  71. package/package.json +4 -3
  72. package/.agents/scripts/lib/audit-to-stories/ledger-commit.js +0 -184
  73. package/.agents/scripts/lib/audit-to-stories/ledger-pr.js +0 -279
  74. package/.agents/scripts/lib/audit-to-stories/ledger-record.js +0 -88
  75. package/.agents/scripts/lib/findings/audit-ledger.js +0 -289
  76. 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
  /**
@@ -11,6 +11,7 @@ import {
11
11
  matchesAnyFilePattern,
12
12
  } from '../audit-suite/selector.js';
13
13
  import { findSimilarOpenStories } from '../duplicate-search.js';
14
+ import { extractProvenanceFooters } from '../findings/route-finding.js';
14
15
  import { Logger } from '../Logger.js';
15
16
  import { parse as parseStoryBody } from '../story-body/story-body.js';
16
17
  import {
@@ -36,6 +37,12 @@ const TRUNCATION_MARKER =
36
37
 
37
38
  const MAX_TRUNCATION_ROUNDS = 8;
38
39
 
40
+ /**
41
+ * Never cut: `seed.provenance` is the audit footers persist stamps onto every
42
+ * Story, and a dropped footer re-files that finding on the next sweep.
43
+ */
44
+ const UNCUTTABLE_KEYS = new Set(['provenance']);
45
+
39
46
  /**
40
47
  * @param {unknown} value
41
48
  * @returns {number}
@@ -91,6 +98,7 @@ function truncateField(value, excess) {
91
98
  }
92
99
  if (value && typeof value === 'object') {
93
100
  const [key] = Object.entries(value)
101
+ .filter(([k]) => !UNCUTTABLE_KEYS.has(k))
94
102
  .filter(([, v]) => typeof v === 'string')
95
103
  .map(([k, v]) => [k, Buffer.byteLength(v, 'utf-8')])
96
104
  .sort((a, b) => b[1] - a[1])[0] ?? [null];
@@ -211,20 +219,27 @@ export function renderStoriesTemplate({ complexitySignals = null } = {}) {
211
219
  body: {
212
220
  goal: 'Fill: one sentence stating why this Story exists.',
213
221
  // A filled example: each line is a commit-boundary stage of the
214
- // 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.
215
224
  slicing:
216
- '1. Re-anchor the shared constant and its consumers.\n' +
217
- '2. Move the gate ahead of the first write and arm the refusal.\n' +
218
- '3. Delete the superseded module, its test and its flag.\n' +
219
- '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',
220
229
  spec:
221
- 'Optional — contract and invariants only: interfaces, status ' +
222
- 'codes, security invariants, and load-bearing constraints with ' +
223
- 'their why. Implementation choices belong to the deliverer unless ' +
224
- 'load-bearing. No per-file behavior paragraphs, no current-state ' +
225
- '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. ' +
226
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.',
227
241
  changes: buildTemplateChanges(complexitySignals),
242
+ references: ['path/to/read-first.ext'],
228
243
  non_goals: [],
229
244
  },
230
245
  acceptance: [
@@ -651,7 +666,12 @@ async function buildSeedFileModeEnvelope({
651
666
 
652
667
  return {
653
668
  mode: modeLabel,
654
- seed: { path: seedFilePath ?? null, content },
669
+ // Carried apart from `content` so a size cut cannot drop a footer.
670
+ seed: {
671
+ path: seedFilePath ?? null,
672
+ content,
673
+ provenance: extractProvenanceFooters(content),
674
+ },
655
675
  // Advisory only — no routing authority.
656
676
  complexitySignals,
657
677
  duplicates,
@@ -1,33 +1,44 @@
1
1
  /**
2
- * What an audit-seeded plan leaves for the next sweep: `audit::*` labels (the
3
- * dedup corpus is label-listed, so footers alone are invisible to an indexed
4
- * sweep) and cross-run ledger entries.
2
+ * What an audit-seeded plan leaves for the next sweep: the provenance footers
3
+ * every Story carries (the cross-run dedup memory) and the `audit::*` labels
4
+ * (the dedup corpus is label-listed, so footers alone are invisible to an
5
+ * indexed sweep).
5
6
  */
6
7
 
7
- import {
8
- DEFAULT_LEDGER_PATH,
9
- readLedger,
10
- recordFiledIdentities,
11
- writeLedger,
12
- } from '../../findings/audit-ledger.js';
13
- import {
14
- parseAuditLabelFooter,
15
- parseFingerprintFooter,
16
- parseSemanticKeyFooter,
17
- } from '../../findings/route-finding.js';
18
- import { Logger } from '../../Logger.js';
8
+ import { parseAuditLabelFooter } from '../../findings/route-finding.js';
19
9
 
20
10
  /**
21
- * @param {string} [ledgerPath]
22
- * @returns {{ path: string, ledger: object|null, recorded: number, ambiguous: number }}
11
+ * @param {object|null} envelope
12
+ * @returns {boolean}
23
13
  */
24
- function newAuditLedgerRecord(ledgerPath) {
25
- return {
26
- path: ledgerPath ?? DEFAULT_LEDGER_PATH,
27
- ledger: null,
28
- recorded: 0,
29
- ambiguous: 0,
30
- };
14
+ function seedWasTruncated(envelope) {
15
+ return (envelope?.truncated ?? []).some((t) => t?.field === 'seed');
16
+ }
17
+
18
+ /**
19
+ * The seed's provenance footers, in full. plan-context carries them apart
20
+ * from the seed text (`seed.provenance`) so a size cut cannot drop one; an
21
+ * envelope whose seed was cut and carries no such field cannot prove it
22
+ * kept them, so persist refuses before creating anything — a dropped footer
23
+ * is a finding silently re-filed by the next sweep.
24
+ *
25
+ * @param {object|null} envelope — the plan-context envelope, or null.
26
+ * @returns {string}
27
+ * @throws {Error} when the seed was truncated and its footers were not carried.
28
+ */
29
+ export function resolveSeedProvenance(envelope) {
30
+ const seed = envelope?.seed;
31
+ if (typeof seed?.provenance === 'string') return seed.provenance;
32
+ if (typeof seed?.content === 'string' && seedWasTruncated(envelope)) {
33
+ throw new Error(
34
+ '[plan-persist] the plan-context envelope truncated the seed and carries ' +
35
+ 'no seed.provenance, so audit provenance footers past the cut would be ' +
36
+ 'silently dropped and the next audit sweep would re-file those findings. ' +
37
+ 'Re-run plan-context with this Mandrel version to regenerate the ' +
38
+ 'envelope. No Issue was created.',
39
+ );
40
+ }
41
+ return seed?.content ?? '';
31
42
  }
32
43
 
33
44
  /**
@@ -47,96 +58,3 @@ export function withAuditLabels(stories, provenanceSource) {
47
58
  labels: [...new Set([...story.labels, ...fromSeed])],
48
59
  }));
49
60
  }
50
-
51
- /**
52
- * Identities are read off the stamped body. Union-carried (unattributed)
53
- * footers are never recorded: every sibling carries them, and a wrong
54
- * binding is worse than none.
55
- *
56
- * @param {{ story: object, id: number, ledgerRecord: object, attributed: boolean }} args
57
- */
58
- function recordAuditFiling({ story, id, ledgerRecord, attributed }) {
59
- const fingerprints = parseFingerprintFooter(story.body);
60
- if (fingerprints.length === 0) return;
61
- if (!attributed) {
62
- ledgerRecord.ambiguous += fingerprints.length;
63
- return;
64
- }
65
- const semanticKeys = parseSemanticKeyFooter(story.body);
66
- const identities = fingerprints.map((fingerprint, i) => ({
67
- fingerprint,
68
- semanticKey: semanticKeys[i] ?? '',
69
- title: story.title,
70
- }));
71
- const { ledger, recorded } = recordFiledIdentities({
72
- ledger: ledgerRecord.ledger ?? readLedger(ledgerRecord.path),
73
- identities,
74
- issue: { number: id },
75
- });
76
- ledgerRecord.ledger = ledger;
77
- ledgerRecord.recorded += recorded;
78
- }
79
-
80
- /**
81
- * @param {object} ledgerRecord
82
- * @param {{ warn: Function }} logger
83
- */
84
- function flushAuditLedger(ledgerRecord, logger) {
85
- if (ledgerRecord.ambiguous > 0) {
86
- logger.warn(
87
- `[plan-persist] audit ledger: ${ledgerRecord.ambiguous} identity(ies) not recorded — ` +
88
- 'the seed carried provenance footers but no Story attributed them, so ownership is ' +
89
- 'ambiguous. Author per-Story `provenance` to record them.',
90
- );
91
- }
92
- if (!ledgerRecord.ledger || ledgerRecord.recorded === 0) return;
93
- writeLedger(ledgerRecord.path, ledgerRecord.ledger);
94
- logger.warn(
95
- `[plan-persist] audit ledger: recorded ${ledgerRecord.recorded} filed finding(s) ` +
96
- `to ${ledgerRecord.path}.`,
97
- );
98
- }
99
-
100
- /**
101
- * One ledger write per plan, not per Story — the ledger is committed state.
102
- * A run that recorded nothing writes nothing.
103
- *
104
- * @param {object} params
105
- * @param {Array<object>} params.stories
106
- * @param {Array<{ slug: string, id: number }>} params.created
107
- * @param {Array<object>} params.tickets
108
- * @param {string} [params.ledgerPath]
109
- * @param {{ warn: Function }} [params.logger]
110
- * @param {boolean} [params.dryRun]
111
- * @returns {{ recorded: number, ambiguous: number }}
112
- */
113
- export function recordAuditFilings({
114
- stories,
115
- created,
116
- tickets,
117
- ledgerPath,
118
- logger,
119
- dryRun = false,
120
- }) {
121
- if (dryRun) return { recorded: 0, ambiguous: 0 };
122
- const record = newAuditLedgerRecord(ledgerPath);
123
- const idBySlug = new Map((created ?? []).map((c) => [c.slug, c.id]));
124
- // Attribution is what the plan authored, so read it off the raw tickets.
125
- const attributedSlugs = new Set(
126
- (tickets ?? [])
127
- .filter((t) => t?.provenance !== undefined && t?.provenance !== null)
128
- .map((t) => t?.slug),
129
- );
130
- for (const story of stories ?? []) {
131
- const id = idBySlug.get(story.slug);
132
- if (typeof id !== 'number') continue;
133
- recordAuditFiling({
134
- story,
135
- id,
136
- ledgerRecord: record,
137
- attributed: attributedSlugs.has(story.slug),
138
- });
139
- }
140
- flushAuditLedger(record, logger ?? Logger);
141
- return { recorded: record.recorded, ambiguous: record.ambiguous };
142
- }