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
@@ -12,12 +12,12 @@ import { createHash } from 'node:crypto';
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
14
  import { parseArgs } from 'node:util';
15
- import { buildDispatchChecklist } from './lib/audit-suite/index.js';
15
+ import { buildStoryChecklist } from './lib/audit-suite/index.js';
16
16
  import { runAsCli } from './lib/cli-utils.js';
17
+ import { resolveStoryWorkerModel } from './lib/config/agent-models.js';
17
18
  import { getPaths, resolveConfig } from './lib/config-resolver.js';
18
19
  import { Logger } from './lib/Logger.js';
19
20
  import { ensureDocsDigest } from './lib/orchestration/docs-digest.js';
20
- import { parse as parseStoryBody } from './lib/story-body/story-body.js';
21
21
  import { expandIdList } from './lib/util/parse-id-list.js';
22
22
  import { runProbedStoriesWaveTick } from './stories-wave-tick.js';
23
23
 
@@ -122,20 +122,68 @@ function writeLedger(
122
122
  /**
123
123
  * `--merge-watch-mode async` is a run-topology call close cannot make: with
124
124
  * siblings, sync closes serialize every merge wait; alone, sync lands fastest.
125
- * @param {{ storyId: number, mainRepo: string, storyCount: number }} args
125
+ * `--worker-model` rides only a multi-Story close — a one-Story run is inline.
126
+ * @param {{ storyId: number, mainRepo: string, storyCount: number,
127
+ * workerModel?: string|null }} args
126
128
  * @returns {string}
127
129
  */
128
- export function renderCloseCommand({ storyId, mainRepo, storyCount }) {
130
+ export function renderCloseCommand({
131
+ storyId,
132
+ mainRepo,
133
+ storyCount,
134
+ workerModel,
135
+ }) {
129
136
  const parts = [
130
137
  'node',
131
138
  path.join(mainRepo, '.agents', 'scripts', 'single-story-close.js'),
132
139
  `--story ${storyId}`,
133
140
  `--cwd ${mainRepo}`,
134
141
  ];
135
- if (storyCount > 1) parts.push('--merge-watch-mode async');
142
+ if (storyCount > 1) parts.push(...multiStoryCloseFlags(workerModel));
136
143
  return parts.join(' ');
137
144
  }
138
145
 
146
+ /**
147
+ * @param {string|null|undefined} workerModel
148
+ * @returns {string[]}
149
+ */
150
+ function multiStoryCloseFlags(workerModel) {
151
+ const flags = ['--merge-watch-mode async'];
152
+ if (workerModel) flags.push(`--worker-model ${workerModel}`);
153
+ return flags;
154
+ }
155
+
156
+ /** The planner handoff sections the dispatch prompt embeds verbatim. */
157
+ const EMBEDDED_SECTIONS = Object.freeze(['Context', 'References']);
158
+
159
+ /**
160
+ * Each of the Story body's `## Context` / `## References` sections, verbatim
161
+ * (heading included, trailing blank lines trimmed), in that order; an absent
162
+ * or empty section is omitted.
163
+ *
164
+ * @param {string} body
165
+ * @returns {string[]}
166
+ */
167
+ export function extractBodySections(body) {
168
+ const lines = `${body ?? ''}`.split(/\r?\n/);
169
+ return EMBEDDED_SECTIONS.map((heading) => {
170
+ const start = lines.findIndex((l) => l.trim() === `## ${heading}`);
171
+ if (start === -1) return null;
172
+ const rest = lines.slice(start + 1);
173
+ const end = rest.findIndex((l) => /^##\s/.test(l));
174
+ const content = (end === -1 ? rest : rest.slice(0, end)).join('\n').trim();
175
+ return content.length > 0 ? `## ${heading}\n\n${content}` : null;
176
+ }).filter(Boolean);
177
+ }
178
+
179
+ /**
180
+ * @param {string[]} [sections]
181
+ * @returns {string[]} each section followed by a blank line.
182
+ */
183
+ function embeddedSectionLines(sections = []) {
184
+ return sections.flatMap((section) => [section, '']);
185
+ }
186
+
139
187
  /**
140
188
  * The whole spawn payload for one ready Story.
141
189
  * @param {object} args
@@ -143,6 +191,7 @@ export function renderCloseCommand({ storyId, mainRepo, storyCount }) {
143
191
  * @param {string} args.mainRepo
144
192
  * @param {string|null} args.docsDigestPath
145
193
  * @param {string|null} args.checklistPath
194
+ * @param {string[]} [args.bodySections] - verbatim `## Context` / `## References`.
146
195
  * @returns {string}
147
196
  */
148
197
  export function renderDispatchPrompt({
@@ -150,26 +199,27 @@ export function renderDispatchPrompt({
150
199
  mainRepo,
151
200
  docsDigestPath,
152
201
  checklistPath,
202
+ bodySections,
153
203
  }) {
154
204
  const lines = [
155
205
  `# Deliver Story #${storyId}`,
156
206
  '',
157
207
  `Main checkout: \`${mainRepo}\`.`,
158
208
  '',
159
- `You own Steps 0 through 2.5 of \`.agents/workflows/helpers/deliver-story.md\`.`,
160
- 'The orchestrator owns Step 3 (close): do not open a PR, do not run',
161
- '`single-story-close.js`, and do not compose a terminal envelope.',
209
+ 'Your `story-worker` boot context carries every worker MUST. You own init',
210
+ 'through the pushed branch; the orchestrator owns close: do not open a PR,',
211
+ 'do not run `single-story-close.js`, and do not compose a terminal envelope.',
162
212
  '',
163
213
  '## Reads',
164
214
  '',
165
- '1. `.agents/workflows/helpers/deliver-digest.md` — once, first.',
166
- '2. `.agents/workflows/helpers/deliver-story.md` — the steps.',
167
- `3. The Story body (\`gh issue view ${storyId}\`) — its \`## Spec\`,`,
215
+ `1. The Story body (\`gh issue view ${storyId}\`) — its \`## Spec\`,`,
168
216
  ' `acceptance[]` and `verify[]` are the contract.',
217
+ '2. The write-time checklist below, when one matched.',
169
218
  '',
170
219
  `- Docs digest: ${docsDigestPath ? `\`${docsDigestPath}\`` : 'none (project.docsContextFiles is unset) — no mandatory docs read'}`,
171
220
  `- Write-time checklist: ${checklistPath ? `\`${checklistPath}\`` : 'none matched this footprint — the maker-blind close-scope pass still covers it'}`,
172
221
  '',
222
+ ...embeddedSectionLines(bodySections),
173
223
  '## Worktree',
174
224
  '',
175
225
  'Initialize from the main checkout, synchronously, at the maximum Bash',
@@ -184,23 +234,27 @@ export function renderDispatchPrompt({
184
234
  'scope those tools. `remoteVerified: false` → flip `agent::blocked` quoting',
185
235
  '`remoteProbe.detail` and stop.',
186
236
  '',
187
- '## Change-set discipline',
237
+ '## Tail',
188
238
  '',
189
- 'Derive the change set, the level and the ceremony with **one** call, and',
190
- 'hand that one list to the verdict owner — never let a critic re-run its',
191
- 'own `git diff`:',
239
+ 'Once the implementation is committed, write the verdict skeleton — it',
240
+ 'prints the one change set (`files`) and the `verdictOwner`; hand that list',
241
+ 'to the owner and never let a critic re-run its own `git diff` — then fill',
242
+ 'and score it:',
192
243
  '',
193
244
  '```bash',
194
- `node ${path.join(mainRepo, '.agents', 'scripts', 'ceremony-derive.js')} --story ${storyId} --cwd <workCwd>`,
245
+ `node ${path.join(mainRepo, '.agents', 'scripts', 'acceptance-eval.js')} --story ${storyId} --init --cwd <workCwd>`,
195
246
  '```',
196
247
  '',
197
- '## Hand-off',
248
+ 'On `proceed`, run the one handoff command. `fix-required` → fix, commit,',
249
+ 're-run it; `blocked` → it already flipped `agent::blocked`, exit non-zero:',
198
250
  '',
199
- 'Run the bounded acceptance self-eval (digest § 4), the one credited suite',
200
- 'run (digest § 5), then push `story-' + storyId + '` to `origin` and',
201
- 'confirm the remote ref moved. Return: Story id, `workCwd`, branch, pushed',
202
- 'head SHA, the self-eval verdict, and the `verify[]` evidence. Say the',
203
- 'branch is pushed and unclosed.',
251
+ '```bash',
252
+ `node ${path.join(mainRepo, '.agents', 'scripts', 'story-handoff.js')} --story ${storyId} --cwd <workCwd>`,
253
+ '```',
254
+ '',
255
+ 'Return its `ready` envelope (Story id, `workCwd`, branch, pushed head SHA,',
256
+ 'review tally) plus the self-eval verdict and the `verify[]` evidence. Say',
257
+ 'the branch is pushed and unclosed.',
204
258
  '',
205
259
  ];
206
260
  return lines.join('\n');
@@ -213,33 +267,21 @@ export function renderDispatchPrompt({
213
267
  * @param {string} args.runTempDir
214
268
  * @param {string} args.mainRepo
215
269
  * @param {string|null} args.docsDigestPath
270
+ * @param {object} [args.config]
216
271
  * @param {object} [deps]
217
272
  * @returns {{ id: number, promptPath: string }}
218
273
  */
219
274
  function buildDispatchEntry(
220
- { storyId, body, runTempDir, mainRepo, docsDigestPath },
221
- {
222
- buildChecklistFn = buildDispatchChecklist,
223
- writeFileFn = fs.writeFileSync,
224
- } = {},
275
+ { storyId, body, runTempDir, mainRepo, docsDigestPath, config },
276
+ { buildChecklistFn, writeFileFn = fs.writeFileSync } = {},
225
277
  ) {
226
- let changes = [];
227
- let references = [];
228
- try {
229
- // Path entries live on `.body`, not at the top level of the parse result.
230
- const { body: parsed } = parseStoryBody(body ?? '');
231
- changes = parsed?.changes ?? [];
232
- references = parsed?.references ?? [];
233
- } catch {
234
- // Costs the checklist, never the dispatch: the worker reads the body itself.
235
- changes = [];
236
- references = [];
237
- }
238
- const { checklistPath } = buildChecklistFn({
278
+ // The same Story-scoped path single-story-init returns in its envelope.
279
+ const { checklistPath } = buildStoryChecklist({
239
280
  storyId,
240
- changes,
241
- references,
242
- runTempDir,
281
+ body,
282
+ config,
283
+ // `undefined` falls through to the helper's own default builder.
284
+ buildChecklistFn,
243
285
  });
244
286
  const promptPath = path.join(runTempDir, `dispatch-${storyId}.md`);
245
287
  writeFileFn(
@@ -249,6 +291,7 @@ function buildDispatchEntry(
249
291
  mainRepo,
250
292
  docsDigestPath,
251
293
  checklistPath,
294
+ bodySections: extractBodySections(body),
252
295
  }),
253
296
  'utf8',
254
297
  );
@@ -418,6 +461,10 @@ export async function runDeliverRunBeat(
418
461
  : [];
419
462
 
420
463
  const readyIds = Array.isArray(tick.ready) ? tick.ready : [];
464
+ const workerModel = resolveStoryWorkerModel(
465
+ { config: resolved, mainRepo },
466
+ entryDeps,
467
+ );
421
468
  const digest = await ensureDocsDigestFn({
422
469
  docsContextFiles: resolved?.project?.docsContextFiles,
423
470
  docsRoot: getPaths(resolved).docsRoot,
@@ -436,6 +483,7 @@ export async function runDeliverRunBeat(
436
483
  runTempDir,
437
484
  mainRepo,
438
485
  docsDigestPath,
486
+ config: resolved,
439
487
  },
440
488
  entryDeps,
441
489
  ),
@@ -459,6 +507,7 @@ export async function runDeliverRunBeat(
459
507
  storyId,
460
508
  mainRepo,
461
509
  storyCount: ids.length,
510
+ workerModel,
462
511
  }),
463
512
  })),
464
513
  done: tick.epilogueDue === true,
@@ -6,7 +6,6 @@ export {
6
6
  matchLocalLenses,
7
7
  readAuditRules,
8
8
  } from './checklist-threading.js';
9
- export { buildDispatchChecklist } from './dispatch-checklist.js';
10
9
  export {
11
10
  LENS_TIERS,
12
11
  matchesAnyFilePattern,
@@ -14,3 +13,4 @@ export {
14
13
  resolveLensTier,
15
14
  selectAudits,
16
15
  } from './selector.js';
16
+ export { buildStoryChecklist } from './story-checklist.js';
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The one write-time checklist call both delivery paths make —
3
+ * `single-story-init.js` (every path, a one-Story inline run included) and
4
+ * `deliver-run.js` (the multi-Story dispatch prompt) — so both name the SAME
5
+ * Story-scoped path under `<tempRoot>/standalone/stories/story-<id>/`.
6
+ */
7
+
8
+ import { storyTempDir } from '../config/temp-paths.js';
9
+ import { parse as parseStoryBody } from '../story-body/story-body.js';
10
+ import { buildDispatchChecklist } from './dispatch-checklist.js';
11
+
12
+ /**
13
+ * `changes[]` + `references[]` off the Story body; an unparseable body is an
14
+ * empty footprint.
15
+ *
16
+ * @param {string} body
17
+ * @returns {{ changes: unknown[], references: unknown[] }}
18
+ */
19
+ function footprintOf(body) {
20
+ try {
21
+ // Path entries live on `.body`, not at the top level of the parse result.
22
+ const { body: parsed } = parseStoryBody(body ?? '');
23
+ return {
24
+ changes: parsed?.changes ?? [],
25
+ references: parsed?.references ?? [],
26
+ };
27
+ } catch {
28
+ return { changes: [], references: [] };
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Never throws: a builder failure costs the checklist (`checklistPath: null`),
34
+ * never the caller.
35
+ *
36
+ * @param {object} args
37
+ * @param {number} args.storyId
38
+ * @param {string} [args.body]
39
+ * @param {object} [args.config]
40
+ * @param {(tag: string, msg: string) => void} [args.progress]
41
+ * @param {typeof buildDispatchChecklist} [args.buildChecklistFn]
42
+ * @returns {{ checklistPath: string|null }}
43
+ */
44
+ export function buildStoryChecklist({
45
+ storyId,
46
+ body,
47
+ config,
48
+ progress = () => {},
49
+ buildChecklistFn = buildDispatchChecklist,
50
+ }) {
51
+ try {
52
+ const { checklistPath } = buildChecklistFn({
53
+ storyId,
54
+ ...footprintOf(body),
55
+ runTempDir: storyTempDir(null, storyId, config),
56
+ });
57
+ return { checklistPath: checklistPath ?? null };
58
+ } catch (err) {
59
+ progress(
60
+ 'CHECKLIST',
61
+ `⚠ write-time checklist skipped: ${err?.message ?? err}`,
62
+ );
63
+ return { checklistPath: null };
64
+ }
65
+ }
@@ -11,6 +11,7 @@ import {
11
11
  RISK_LABELS,
12
12
  TYPE_LABELS,
13
13
  } from '../label-constants.js';
14
+ import { labelDescription } from '../label-taxonomy.js';
14
15
  import { AUDIT_LENSES, auditLabelsForFindings } from './audit-lenses.js';
15
16
 
16
17
  /** A lens absent here falls back to {@link DEFAULT_LENS_META}. */
@@ -106,8 +107,7 @@ const AUDIT_STORY_AXIS_LABELS = Object.freeze([
106
107
  {
107
108
  name: AGENT_LABELS.READY,
108
109
  color: hex(LABEL_COLORS.AGENT),
109
- description:
110
- 'Parking state — frozen dispatch manifest exists; awaiting local /mandrel-deliver',
110
+ description: labelDescription(AGENT_LABELS.READY),
111
111
  },
112
112
  {
113
113
  name: RISK_LABELS.HIGH,
@@ -36,7 +36,7 @@ export function toCanonicalFinding(finding) {
36
36
  * @param {object} finding
37
37
  * @returns {{ short: string, full: string, components: object }}
38
38
  */
39
- export function fingerprintAuditFinding(finding) {
39
+ function fingerprintAuditFinding(finding) {
40
40
  return fingerprintFinding(toCanonicalFinding(finding));
41
41
  }
42
42
 
@@ -183,7 +183,7 @@ body:
183
183
  value: |
184
184
  Fill the fields below. They serialize to the canonical Story body
185
185
  the framework parses — keep each section's content under its own
186
- heading. Machine-managed sections (dispatch manifest, lifecycle
186
+ heading. Machine-managed sections (the plan summary, lifecycle
187
187
  transitions) are added by the runtime; you do not author them here.
188
188
  ${fieldBlocks}
189
189
  ${renderDependsOnBlock()}
@@ -1,4 +1,5 @@
1
1
  import { parseArgs } from 'node:util';
2
+ import { AGENT_MODEL_PATTERN } from './config/agent-models.js';
2
3
 
3
4
  /**
4
5
  * Positive integer with an optional leading `#`; `null` when invalid.
@@ -157,6 +158,25 @@ export function parseWorkerTokens(value) {
157
158
  };
158
159
  }
159
160
 
161
+ /**
162
+ * Best-effort, like {@link parseWorkerTokens}, except that absence is the
163
+ * normal inline case and carries no warning.
164
+ *
165
+ * @param {unknown} value
166
+ * @returns {{ model: string|null, warning: string|null }}
167
+ */
168
+ export function parseWorkerModel(value) {
169
+ if (value == null) return { model: null, warning: null };
170
+ const raw = String(value).trim();
171
+ if (new RegExp(AGENT_MODEL_PATTERN).test(raw)) {
172
+ return { model: raw, warning: null };
173
+ }
174
+ return {
175
+ model: null,
176
+ warning: `--worker-model must be an agent model value (got ${JSON.stringify(value)}); telemetry.workerModel records null.`,
177
+ };
178
+ }
179
+
160
180
  /**
161
181
  * Throws when a validating flag parser rejects a value; error handlers use
162
182
  * {@link parseSprintArgsTolerant} instead of re-calling this.
@@ -189,6 +209,7 @@ export function parseSprintArgs(
189
209
  'rerun-advisory': { type: 'string' },
190
210
  'override-review-block': { type: 'string' },
191
211
  'worker-tokens': { type: 'string' },
212
+ 'worker-model': { type: 'string' },
192
213
  executor: { type: 'string' },
193
214
  cwd: { type: 'string' },
194
215
  'recut-of': { type: 'string' },
@@ -220,6 +241,7 @@ export function parseSprintArgs(
220
241
  ? tolerantOverrideReviewBlock(values['override-review-block'])
221
242
  : parseOverrideReviewBlock(values['override-review-block']),
222
243
  workerTokens: values['worker-tokens'],
244
+ workerModel: values['worker-model'],
223
245
  executor: values.executor ?? null,
224
246
  cwd:
225
247
  (typeof values.cwd === 'string' && values.cwd.trim()) ||
@@ -60,12 +60,27 @@ function buildBaselinesGateEnv(baseBranch) {
60
60
  * @param {object|undefined|null} config - Canonical resolved config.
61
61
  * @returns {boolean}
62
62
  */
63
- function isCrapGateEnabled(config) {
63
+ export function isCrapGateEnabled(config) {
64
64
  if (!config || typeof config !== 'object') return true;
65
65
  const enabled = config?.delivery?.quality?.gates?.crap?.enabled;
66
66
  return typeof enabled === 'boolean' ? enabled : true;
67
67
  }
68
68
 
69
+ /**
70
+ * The credited-run depositor predicate — the ONE home, shared by close's gate
71
+ * registration and the worker's `story-handoff.js`, so the two cannot pick
72
+ * different depositors: coverage-capture runs the suite when the CRAP gate is
73
+ * on AND a `test:coverage` script exists; any other project takes the plain
74
+ * `test` gate (the evidence-gate `npm test` credit).
75
+ *
76
+ * @param {object|undefined|null} config - Canonical resolved config.
77
+ * @param {Record<string, string>|null|undefined} scripts - `package.json` scripts.
78
+ * @returns {boolean}
79
+ */
80
+ export function isCoverageCaptureActive(config, scripts) {
81
+ return isCrapGateEnabled(config) && hasNpmScript(scripts, 'test:coverage');
82
+ }
83
+
69
84
  /**
70
85
  * The plain `test` gate, unless coverage-capture will run the suite — every
71
86
  * close must keep exactly one working test gate.
@@ -381,8 +396,7 @@ export function buildDefaultGates({
381
396
  shouldSkipImpl,
382
397
  } = {}) {
383
398
  const scripts = packageScripts ?? readPackageScripts(cwd);
384
- const coverageCaptureActive =
385
- isCrapGateEnabled(config) && hasNpmScript(scripts, 'test:coverage');
399
+ const coverageCaptureActive = isCoverageCaptureActive(config, scripts);
386
400
  // A credited bare `npm test` registers the plain `test` gate beside the
387
401
  // capture so the credit is reported, never re-spent.
388
402
  const testCredited = resolveTestCredited({
@@ -0,0 +1,117 @@
1
+ /**
2
+ * `delivery.routing.agentModels`: a per-role override of the `model:`
3
+ * frontmatter default each `.agents/agents/<role>.md` declares, applied when
4
+ * `sync-claude-agents` projects `.claude/agents/`. It never selects or changes
5
+ * the operator's session model.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ import { getDeliveryRouting } from './delivery-routing.js';
12
+
13
+ /** The role-scoped agents `.agents/agents/` ships — the `agentModels` keys. */
14
+ export const ROLE_AGENT_NAMES = Object.freeze([
15
+ 'story-worker',
16
+ 'acceptance-critic',
17
+ 'plan-critic',
18
+ 'auditor',
19
+ ]);
20
+
21
+ /** A model alias, a full model id, or `inherit` — shell-safe by construction. */
22
+ export const AGENT_MODEL_PATTERN = '^[A-Za-z0-9][A-Za-z0-9._:-]*$';
23
+
24
+ /** What an agent with no `model:` runs on: the operator's session model. */
25
+ const INHERIT_MODEL = 'inherit';
26
+
27
+ const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
28
+ const MODEL_LINE_RE = /^model:[^\r\n]*$/m;
29
+
30
+ /**
31
+ * The valid overrides only: an unknown role or an unsafe value is dropped
32
+ * (config validation already refuses both on load).
33
+ *
34
+ * @param {object | null | undefined} config
35
+ * @returns {Record<string, string>}
36
+ */
37
+ export function getAgentModels(config) {
38
+ const raw = config?.delivery?.routing?.agentModels;
39
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
40
+ const pattern = new RegExp(AGENT_MODEL_PATTERN);
41
+ return Object.fromEntries(
42
+ Object.entries(raw).filter(
43
+ ([role, model]) =>
44
+ ROLE_AGENT_NAMES.includes(role) &&
45
+ typeof model === 'string' &&
46
+ pattern.test(model),
47
+ ),
48
+ );
49
+ }
50
+
51
+ /**
52
+ * The `model:` a role file's frontmatter declares, or null.
53
+ *
54
+ * @param {string} content
55
+ * @returns {string|null}
56
+ */
57
+ function frontmatterModel(content) {
58
+ const block = String(content ?? '').match(FRONTMATTER_RE);
59
+ const line = block?.[1].match(MODEL_LINE_RE);
60
+ const value = line?.[0].slice('model:'.length).trim();
61
+ return value || null;
62
+ }
63
+
64
+ /**
65
+ * The model a role runs on: its `agentModels` override, else its frontmatter
66
+ * default, else `inherit`.
67
+ *
68
+ * @param {{ role: string, config?: object|null, content?: string }} args
69
+ * @returns {string}
70
+ */
71
+ function resolveAgentModel({ role, config, content }) {
72
+ const override = getAgentModels(config)[role];
73
+ return override ?? frontmatterModel(content) ?? INHERIT_MODEL;
74
+ }
75
+
76
+ /**
77
+ * Write `model` into a role file's frontmatter, replacing a declared default
78
+ * or appending one; content without frontmatter is returned unchanged.
79
+ *
80
+ * @param {string} content
81
+ * @param {string} model
82
+ * @returns {string}
83
+ */
84
+ export function applyAgentModel(content, model) {
85
+ const block = content.match(FRONTMATTER_RE);
86
+ if (!block) return content;
87
+ const inner = MODEL_LINE_RE.test(block[1])
88
+ ? block[1].replace(MODEL_LINE_RE, `model: ${model}`)
89
+ : `${block[1]}\nmodel: ${model}`;
90
+ return `---\n${inner}\n---\n${content.slice(block[0].length)}`;
91
+ }
92
+
93
+ /**
94
+ * The model a dispatched story-worker runs on: its `agentModels` override,
95
+ * else the role file's default. With role-scoped agents off, the worker is a
96
+ * `general-purpose` spawn on the session model.
97
+ *
98
+ * @param {{ config?: object, mainRepo: string }} args
99
+ * @param {{ readFileFn?: typeof fs.readFileSync }} [deps]
100
+ * @returns {string}
101
+ */
102
+ export function resolveStoryWorkerModel(
103
+ { config, mainRepo },
104
+ { readFileFn = fs.readFileSync } = {},
105
+ ) {
106
+ if (!getDeliveryRouting(config).roleScopedAgents) return INHERIT_MODEL;
107
+ let content = '';
108
+ try {
109
+ content = readFileFn(
110
+ path.join(mainRepo, '.agents', 'agents', 'story-worker.md'),
111
+ 'utf8',
112
+ );
113
+ } catch {
114
+ // An absent role file declares no default: the resolver falls to inherit.
115
+ }
116
+ return resolveAgentModel({ role: 'story-worker', config, content });
117
+ }
@@ -3,6 +3,10 @@
3
3
  // delivery.* sub-schemas of AGENTRC_SCHEMA.
4
4
 
5
5
  import { ACCEPTANCE_EVAL_DEFAULTS } from './config/acceptance-eval.js';
6
+ import {
7
+ AGENT_MODEL_PATTERN,
8
+ ROLE_AGENT_NAMES,
9
+ } from './config/agent-models.js';
6
10
  import { CI_DELIVERY_DEFAULTS } from './config/ci.js';
7
11
  import { DELIVERY_ROUTING_DEFAULTS } from './config/delivery-routing.js';
8
12
  import { DEFAULT_CODE_REVIEW } from './config/runners.js';
@@ -189,6 +193,14 @@ const ROUTING_SCHEMA = {
189
193
  'When true (default), single-story-close lands through merge in one close. Opt out per-run with --no-wait-merge.',
190
194
  default: DELIVERY_ROUTING_DEFAULTS.closeAndLand,
191
195
  },
196
+ agentModels: {
197
+ type: 'object',
198
+ description:
199
+ 'Per-role model override for the role-scoped agents, keyed by role name (`story-worker`, `acceptance-critic`, `plan-critic`, `auditor`; any other key is a validation error). A value is a Claude Code agent model: an alias (`sonnet`, `opus`, `haiku`), a full model id, or `inherit` (the operator\'s session model). It replaces the role file\'s `model:` frontmatter default when `sync-claude-agents` projects `.claude/agents/<role>.md`. Defaults: story-worker, acceptance-critic and plan-critic `inherit` (a checker runs at least as strong as the maker); auditor `sonnet` (a read-heavy lens sweep). Nothing here selects or changes the operator\'s session model, and a one-Story run stays inline in that session. A multi-Story close records the dispatched story-worker\'s resolved model as `telemetry.workerModel` beside `workerTokens` (null for an inline close), so opting workers down, e.g. `{ "story-worker": "sonnet" }`, is decided from measured outcomes.',
200
+ propertyNames: { enum: [...ROLE_AGENT_NAMES] },
201
+ additionalProperties: { type: 'string', pattern: AGENT_MODEL_PATTERN },
202
+ default: {},
203
+ },
192
204
  },
193
205
  additionalProperties: false,
194
206
  };
@@ -202,7 +214,7 @@ const CI_DELIVERY_SCHEMA = {
202
214
  type: 'string',
203
215
  enum: ['trust-ci', 'strict'],
204
216
  description:
205
- "Story #4356 (Epic #4355). Merge posture. 'trust-ci' (default) merges once required checks pass; 'strict' additionally requires a clean review gate.",
217
+ "Story #4356 (Epic #4355). Merge posture. 'trust-ci' (default) merges once required checks pass; 'strict' skips arming auto-merge, so the operator owns the merge; it adds no review gate.",
206
218
  default: CI_DELIVERY_DEFAULTS.autoMerge,
207
219
  },
208
220
  blockOnAdvisoryFailure: {
@@ -132,7 +132,7 @@ export const CODE_REVIEW_SCHEMA = {
132
132
  additionalProperties: false,
133
133
  },
134
134
  description:
135
- "Review-provider chain (Story #2871). When unset or empty, falls back to this default: `native` (scoped lint + MI) then an optional story-scoped `code-review` — a low-effort `claude --print` bug review whose every finding is critical and halts close before auto-merge; hosts without the `claude` CLI skip it. `security-review` and `ultrareview` are opt-in. The orchestrator iterates inline entries in declaration order and merges their Finding[] before posting one structured comment; manual-prompt entries (e.g. ultrareview) contribute a trailing 'Manual review suggestions' section. Selecting an adapter whose probe fails hard-fails at factory construction unless declared `optional: true` in the chain.",
135
+ "Review-provider chain (Story #2871). When unset or empty, falls back to this default: `native` (maintainability scoring of the changed files) then an optional story-scoped `code-review` — a low-effort `claude --print` bug review whose every finding is critical and halts close before auto-merge; hosts without the `claude` CLI skip it. `security-review` and `ultrareview` are opt-in. The orchestrator iterates inline entries in declaration order and merges their Finding[] before posting one structured comment; manual-prompt entries (e.g. ultrareview) contribute a trailing 'Manual review suggestions' section. Selecting an adapter whose probe fails hard-fails at factory construction unless declared `optional: true` in the chain.",
136
136
  default: DEFAULT_REVIEW_PROVIDERS,
137
137
  },
138
138
  autoFixSeverity: {
@@ -190,6 +190,21 @@ function parseAllFooterValues(text, pattern, isValid) {
190
190
  return out;
191
191
  }
192
192
 
193
+ /**
194
+ * Every provenance footer in `text`, verbatim, one per line — the whole of
195
+ * what `carryProvenanceFooters` and `parseAuditLabelFooter` read from a seed,
196
+ * small enough to survive a seed that is cut for size.
197
+ *
198
+ * @param {unknown} text
199
+ * @returns {string}
200
+ */
201
+ export function extractProvenanceFooters(text) {
202
+ if (typeof text !== 'string') return '';
203
+ const pattern =
204
+ /<!--\s*audit-(?:fingerprints|semantic-keys|labels):[^>]*-->/g;
205
+ return [...text.matchAll(pattern)].map((m) => m[0]).join('\n');
206
+ }
207
+
193
208
  /**
194
209
  * Append the seed's provenance footers missing from `into`, so the next
195
210
  * sweep recognises the Story. Additive and idempotent.