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
@@ -310,10 +310,11 @@ async function enforceReachability(reachability, config) {
310
310
  * @param {object} args
311
311
  * @returns {Promise<void>}
312
312
  */
313
- async function persistStoryArtifacts({ provider, created, summaryBody }) {
313
+ async function persistStoryArtifacts({ provider, created, summaryFor }) {
314
314
  await concurrentMap(
315
315
  created,
316
- (story) => writePlanSummaryComment(provider, story.id, summaryBody),
316
+ (story) =>
317
+ writePlanSummaryComment(provider, story.id, summaryFor(story.id)),
317
318
  { concurrency: FANOUT_CONCURRENCY },
318
319
  );
319
320
  await markStoriesReady({ provider, created });
@@ -506,22 +507,24 @@ export async function runPlanPersist({
506
507
  mode: dryRun ? 'dry-run' : 'persist',
507
508
  });
508
509
 
509
- const summaryBody = buildPlanSummaryCommentBody({
510
- epicId: primary.id,
511
- ticketCount: created.length,
512
- forceReview,
513
- freshness,
514
- healthcheck: { skipped: true },
515
- waveTable,
516
- mode: 'stories',
517
- planMetricsLine,
518
- stories: created,
519
- conflictFindings: assembledConflicts,
520
- waveCollisions,
521
- });
510
+ // Each Story's comment heading names that Story.
511
+ const summaryFor = (storyId) =>
512
+ buildPlanSummaryCommentBody({
513
+ storyId,
514
+ ticketCount: created.length,
515
+ forceReview,
516
+ freshness,
517
+ healthcheck: { skipped: true },
518
+ waveTable,
519
+ mode: 'stories',
520
+ planMetricsLine,
521
+ stories: created,
522
+ conflictFindings: assembledConflicts,
523
+ waveCollisions,
524
+ });
522
525
 
523
526
  if (!dryRun) {
524
- await persistStoryArtifacts({ provider, created, summaryBody });
527
+ await persistStoryArtifacts({ provider, created, summaryFor });
525
528
  }
526
529
 
527
530
  // Last among the writes: the Epic needs the children's numbers and database
@@ -202,6 +202,7 @@ function bodyObjectFromTicket(ticket) {
202
202
  goal: ticket.goal ?? '',
203
203
  slicing: ticket.slicing ?? '',
204
204
  spec: ticket.spec ?? '',
205
+ context: ticket.context ?? '',
205
206
  changes: ticket.changes ?? [],
206
207
  acceptance: ticket.acceptance ?? [],
207
208
  verify: ticket.verify ?? [],
@@ -89,11 +89,12 @@ function renderSharedEditorLines(conflictFindings) {
89
89
  }
90
90
 
91
91
  /**
92
- * @param {object} input
92
+ * @param {object} input `storyId` is the Story the comment is posted on; its
93
+ * heading names that Story, never a sibling.
93
94
  * @returns {string}
94
95
  */
95
96
  export function buildPlanSummaryCommentBody({
96
- epicId,
97
+ storyId,
97
98
  ticketCount,
98
99
  forceReview = false,
99
100
  freshness,
@@ -139,7 +140,7 @@ export function buildPlanSummaryCommentBody({
139
140
  : '/mandrel-deliver <storyId> [<storyId> ...]';
140
141
 
141
142
  return [
142
- `#### 📋 Plan Summary — Story #${epicId} is \`agent::ready\``,
143
+ `#### 📋 Plan Summary — Story #${storyId} is \`agent::ready\``,
143
144
  '',
144
145
  `- ${ticketCount} Story ticket(s) persisted: ${storyList}.`,
145
146
  ...reviewLines,
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  import { extractEpicIdFromBody, parseBlockedBy } from '../dependency-parser.js';
10
- import { TYPE_LABELS } from '../label-constants.js';
10
+ import { AGENT_LABELS, TYPE_LABELS } from '../label-constants.js';
11
11
  import { buildStoryAdjacency } from '../story-adjacency.js';
12
12
  import {
13
13
  extractChangePaths,
@@ -83,13 +83,21 @@ export function toStoryRecord(issue, requestedId, { allowUnlabelled } = {}) {
83
83
  }
84
84
 
85
85
  /**
86
- * Refuse an unplanned Story (audit sweeps file them unlabelled on purpose).
86
+ * Refuse a Story still awaiting planning (`agent::review-spec`, which the
87
+ * issue form applies) or an unplanned one (audit sweeps file them unlabelled
88
+ * on purpose).
87
89
  *
88
90
  * @param {number} id
89
91
  * @param {string[]} labels
90
92
  * @param {boolean} [allowUnlabelled]
91
93
  */
92
94
  function assertDispatchable(id, labels, allowUnlabelled) {
95
+ if (labels.includes(AGENT_LABELS.REVIEW_SPEC)) {
96
+ throw new Error(
97
+ `[resolve-stories] Story #${id} is labelled ${AGENT_LABELS.REVIEW_SPEC}, so it is awaiting ` +
98
+ `planning before delivery. Run /mandrel-plan ${id} first, which applies agent::ready.`,
99
+ );
100
+ }
93
101
  if (allowUnlabelled) return;
94
102
  if (labels.some((l) => l.startsWith(AGENT_LABEL_PREFIX))) return;
95
103
  throw new Error(
@@ -1,7 +1,8 @@
1
1
  /**
2
- * review-providers/native.js — in-process ReviewProvider: scoped lint plus
3
- * maintainability scoring of the changed files. MI honours the gate's
4
- * exemptions (lint has its own); `input.depth` is ignored by design.
2
+ * review-providers/native.js — in-process ReviewProvider: maintainability
3
+ * scoring of the changed files, honouring the gate's exemptions. It runs no
4
+ * lint — lint is a close-validation gate the worker's preflight also runs.
5
+ * `input.depth` is ignored by design.
5
6
  *
6
7
  * @typedef {import('./types.js').Finding} Finding
7
8
  * @typedef {import('./types.js').ReviewInput} ReviewInput
@@ -15,23 +16,12 @@ import {
15
16
  calculateReport,
16
17
  classifyReport,
17
18
  } from '../../maintainability-engine.js';
18
- import {
19
- emitRuntimeFriction,
20
- RUNTIME_FRICTION_CATEGORIES,
21
- } from '../../observability/runtime-friction.js';
22
19
  import { PROJECT_ROOT } from '../../project-root.js';
23
20
  import { transpileIfNeeded } from '../../transpile.js';
24
21
  import {
25
22
  resolveMaintainabilityIgnoreGlobs,
26
23
  scopeMaintainabilityFiles,
27
24
  } from './mi-exemptions.js';
28
- import {
29
- parseLintOutput,
30
- partitionFilesForLint,
31
- runScopedLint,
32
- } from './scoped-lint.js';
33
-
34
- export { parseLintOutput, partitionFilesForLint, runScopedLint };
35
25
 
36
26
  const MAINTAINABILITY_REPORT_WORKER_URL = new URL(
37
27
  '../../workers/maintainability-report-worker.js',
@@ -244,138 +234,29 @@ export async function analyzeChangedFiles(
244
234
  return results;
245
235
  }
246
236
 
247
- /**
248
- * Findings come from parsed counts, never `executionFailed` (an OR across
249
- * surfaces), so one absent runner cannot discard the other's errors.
250
- *
251
- * @param {{ errors: number, warnings: number, parsed?: boolean, skipped?: boolean, mode?: string, executionFailed?: boolean, evidenceSkipped?: boolean }} lintSummary
252
- * @returns {Finding[]}
253
- */
254
- export function buildLintFindings(lintSummary) {
255
- if (lintSummary.mode === 'off') return [];
256
- if (lintSummary.evidenceSkipped) return [];
257
- if (lintSummary.skipped) return [];
258
- if (lintSummary.parsed === false) return [];
259
- const findings = [];
260
- if (lintSummary.errors > 0) {
261
- findings.push({
262
- severity: 'high',
263
- title: `Lint check failed (${lintSummary.errors} error(s))`,
264
- body:
265
- `Scoped lint reported ${lintSummary.errors} error(s) and ` +
266
- `${lintSummary.warnings} warning(s) on the changed surface. ` +
267
- 'Fix errors before merging.',
268
- category: 'lint',
269
- });
270
- } else if (lintSummary.warnings > 0) {
271
- findings.push({
272
- severity: 'suggestion',
273
- title: `Lint check passed with ${lintSummary.warnings} warning(s)`,
274
- body:
275
- `Scoped lint reported ${lintSummary.warnings} warning(s) on the ` +
276
- 'changed surface. Treat as suggestions.',
277
- category: 'lint',
278
- });
279
- }
280
- return findings;
281
- }
282
-
283
- async function runLintPhase({
284
- scopeLint,
285
- changedFiles,
286
- runScopedLintFn,
287
- logger,
288
- }) {
289
- if (scopeLint === 'off') {
290
- logger?.info?.(
291
- '[native-review] Lint scoped off (scopeLint=off); skipping.',
292
- );
293
- return {
294
- errors: 0,
295
- warnings: 0,
296
- parsed: false,
297
- skipped: true,
298
- mode: 'off',
299
- executionFailed: false,
300
- degradations: [],
301
- surfaces: [],
302
- };
303
- }
304
- logger?.info?.(
305
- '[native-review] Linting changed files only (biome + markdownlint, scoped to diff)...',
306
- );
307
- return runScopedLintFn(changedFiles, PROJECT_ROOT);
308
- }
309
-
310
- /**
311
- * Degradation records for an `executionFailed` summary; one without
312
- * per-surface rows degrades to a single gate-wide record, never silence.
313
- *
314
- * @param {{ executionFailed?: boolean, degradations?: Array<{ surface: string, reason: string }> }} lintSummary
315
- * @returns {Array<{ tool: string, gate: string, surface: string, reason: string }>}
316
- */
317
- function buildLintDegradations(lintSummary) {
318
- if (!lintSummary.executionFailed) return [];
319
- const rows = Array.isArray(lintSummary.degradations)
320
- ? lintSummary.degradations
321
- : [];
322
- const surfaces =
323
- rows.length > 0
324
- ? rows
325
- : [{ surface: 'scoped-lint', reason: 'unparseable-output' }];
326
- return surfaces.map((row) => ({
327
- tool: 'native-review-lint',
328
- gate: 'scoped-lint',
329
- surface: row.surface,
330
- reason: row.reason,
331
- }));
332
- }
333
-
334
237
  /**
335
238
  * @param {{
336
239
  * gitSpawnFn?: typeof gitSpawn,
337
- * runScopedLintFn?: typeof runScopedLint,
338
240
  * analyzeChangedFilesFn?: typeof analyzeChangedFiles,
339
- * buildLintFindingsFn?: typeof buildLintFindings,
340
- * emitToolDegradationFn?: typeof emitRuntimeFriction,
341
241
  * resolveIgnoreGlobsFn?: typeof resolveMaintainabilityIgnoreGlobs,
342
242
  * logger?: { info?: Function, warn?: Function, error?: Function },
343
- * scopeLint?: 'changed-only'|'off',
344
243
  * }} [deps]
345
244
  * @returns {ReviewProvider}
346
245
  */
347
246
  export function createNativeProvider(deps = {}) {
348
247
  const {
349
248
  gitSpawnFn = gitSpawn,
350
- runScopedLintFn = runScopedLint,
351
249
  analyzeChangedFilesFn = analyzeChangedFiles,
352
- buildLintFindingsFn = buildLintFindings,
353
- emitToolDegradationFn = emitRuntimeFriction,
354
250
  resolveIgnoreGlobsFn = resolveMaintainabilityIgnoreGlobs,
355
251
  logger,
356
- scopeLint = 'changed-only',
357
252
  } = deps;
358
253
 
359
- /**
360
- * Degradations from the latest `runReview`, travelling beside findings.
361
- *
362
- * @type {Array<{ tool: string, gate: string, surface: string, reason: string }>}
363
- */
364
- let recordedDegradations = [];
365
-
366
254
  return {
367
- /**
368
- * @returns {Array<{ tool: string, gate: string, surface: string, reason: string }>}
369
- */
370
- getDegradations() {
371
- return recordedDegradations;
372
- },
373
255
  /**
374
256
  * @param {ReviewInput} input
375
257
  * @returns {Promise<Finding[]>}
376
258
  */
377
259
  async runReview(input) {
378
- recordedDegradations = [];
379
260
  const { scope, ticketId, baseRef, headRef } = input ?? {};
380
261
  if (!baseRef || !headRef) {
381
262
  throw new TypeError(
@@ -427,49 +308,8 @@ export function createNativeProvider(deps = {}) {
427
308
  gitSpawnFn,
428
309
  });
429
310
 
430
- const lintSummary = await runLintPhase({
431
- scopeLint,
432
- changedFiles,
433
- runScopedLintFn,
434
- logger,
435
- });
436
-
437
- if (lintSummary.executionFailed) {
438
- // A tool that could not execute is a degradation, recorded on the
439
- // outcome and in friction telemetry — never a finding.
440
- recordedDegradations = buildLintDegradations(lintSummary);
441
- logger?.warn?.(
442
- `[native-review] Lint runner could not execute (${recordedDegradations
443
- .map((d) => `${d.surface}: ${d.reason}`)
444
- .join(
445
- '; ',
446
- )}) — reported as a degraded gate on the review outcome and recorded as friction telemetry; the degradation itself is never a finding, and any surface that did run still reports its own errors. Verify with the canonical \`npm run lint\` before merging.`,
447
- );
448
- try {
449
- await emitToolDegradationFn({
450
- storyId: ticketId,
451
- category: RUNTIME_FRICTION_CATEGORIES.TOOL_DEGRADED,
452
- tool: 'native-review-lint',
453
- details: {
454
- surface: 'scoped-lint',
455
- reason:
456
- 'lint runner produced no parseable output (binary missing, parse failure, or environment issue)',
457
- },
458
- });
459
- } catch {
460
- // Observability must never fail the review.
461
- }
462
- }
463
-
464
- const lintFindings = buildLintFindingsFn(lintSummary);
465
-
466
311
  // Severity order; only matters for fixture stability.
467
- return [
468
- ...results.criticalFindings,
469
- ...lintFindings.filter((f) => f.severity === 'high'),
470
- ...results.mediumFindings,
471
- ...lintFindings.filter((f) => f.severity === 'suggestion'),
472
- ];
312
+ return [...results.criticalFindings, ...results.mediumFindings];
473
313
  },
474
314
  };
475
315
  }
@@ -82,10 +82,22 @@ export function gatesForFailedPhase(phase, args = {}) {
82
82
  return { ...gates, ...baselinesGatesObserved(args.observedGates) };
83
83
  }
84
84
 
85
+ /**
86
+ * @param {unknown} err
87
+ * @param {number} storyId
88
+ * @returns {string}
89
+ */
90
+ function nextCommandFor(err, storyId) {
91
+ const tagged = err?.closeNextCommand;
92
+ return typeof tagged === 'string' ? tagged : NEXT_COMMANDS.recover(storyId);
93
+ }
94
+
85
95
  /**
86
96
  * Never throws: a build failure here must not replace the original error as
87
97
  * the run's reported cause, so it returns null and the caller rethrows.
88
- * `err.closePhase` and `err.closeGates` are tagged by the runner.
98
+ * `err.closePhase` and `err.closeGates` are tagged by the runner; a phase
99
+ * that knows its own resume (a handed-back base-sync conflict re-runs close)
100
+ * tags `err.closeNextCommand`.
89
101
  *
90
102
  * @param {unknown} err
91
103
  * @param {{ storyId?: string|number, skipValidation?: boolean, skipSync?: boolean }} args
@@ -105,7 +117,7 @@ export function failedTerminalFor(err, args = {}) {
105
117
  observedGates: err?.closeGates ?? null,
106
118
  }),
107
119
  failure: { reason: String(err?.message ?? err) },
108
- nextCommand: NEXT_COMMANDS.recover(storyId),
120
+ nextCommand: nextCommandFor(err, storyId),
109
121
  elapsedSeconds: 0,
110
122
  phaseDurations: err?.closePhaseDurations ?? undefined,
111
123
  });
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * phases/base-sync.js — sync the Story branch from `origin/<baseBranch>`
3
3
  * before push, so a PR does not open behind a base a sibling's merge just
4
- * moved. Runs in the worktree (else the main checkout); a failure blocks the
5
- * Story and throws.
4
+ * moved. Runs in the worktree (else the main checkout). A baseline-only
5
+ * conflict resolves inside the sync; any other conflict against a confirmed
6
+ * base goes back to the delivering agent (friction, labels unchanged); every
7
+ * other failure blocks the Story. All failures throw.
6
8
  */
7
9
 
8
10
  import { getQuality } from '../../../config/quality.js';
@@ -11,6 +13,7 @@ import { filterFilesUnderTargets } from '../../../coverage-capture.js';
11
13
  import { syncBranchFromBase } from '../../../git/sync-from-base.js';
12
14
  import { Logger } from '../../../Logger.js';
13
15
  import { AGENT_LABELS } from '../../../label-constants.js';
16
+ import { NEXT_COMMANDS } from '../../story-deliver-terminal.js';
14
17
  import {
15
18
  STATE_LABELS,
16
19
  transitionTicketState,
@@ -57,7 +60,7 @@ export async function runBaseSyncPhase({
57
60
  log: (tag, msg) => progress(tag, msg),
58
61
  });
59
62
  if (!syncResult.synced) {
60
- await handleSyncFailure({
63
+ const { handedBack } = await handleSyncFailure({
61
64
  provider,
62
65
  storyId,
63
66
  syncCwd,
@@ -67,17 +70,18 @@ export async function runBaseSyncPhase({
67
70
  result: syncResult,
68
71
  progress,
69
72
  });
70
- throw new Error(
71
- `[single-story-close] Base-sync failed (${syncResult.kind})` +
72
- (syncResult.conflictFiles
73
- ? `: conflicting files = ${syncResult.conflictFiles.join(', ')}`
74
- : syncResult.stderr
75
- ? `: ${syncResult.stderr.slice(0, 200)}`
76
- : '') +
77
- `. Story transitioned to ${AGENT_LABELS.BLOCKED}; resolve in ${syncCwd} and re-run \`/mandrel-deliver ${storyId}\`.`,
78
- );
73
+ throw buildSyncFailureError({ storyId, syncCwd, syncResult, handedBack });
79
74
  }
80
75
  progress('SYNC', `✅ Synced from origin/${baseBranch} (${syncResult.kind}).`);
76
+ const resolved = syncResult.resolvedBaselineFiles ?? [];
77
+ if (resolved.length > 0) {
78
+ progress(
79
+ 'SYNC',
80
+ `♻️ Baseline-only conflict resolved to origin/${baseBranch}'s version ` +
81
+ `(the insert-only seat and close's gates re-derive this Story's rows): ` +
82
+ resolved.join(', '),
83
+ );
84
+ }
81
85
  for (const line of buildStampInvalidatedWarning({
82
86
  baseBranch,
83
87
  result: syncResult,
@@ -87,6 +91,36 @@ export async function runBaseSyncPhase({
87
91
  }
88
92
  }
89
93
 
94
+ /** A handed-back conflict re-runs close next (`closeNextCommand`). */
95
+ function buildSyncFailureError({ storyId, syncCwd, syncResult, handedBack }) {
96
+ const err = new Error(
97
+ `[single-story-close] Base-sync failed (${syncResult.kind})` +
98
+ syncFailureDetail(syncResult) +
99
+ (handedBack
100
+ ? `. Labels unchanged — resolve the conflict in ${syncCwd}, commit, and re-run close.`
101
+ : `. Story transitioned to ${AGENT_LABELS.BLOCKED}; resolve in ${syncCwd} and re-run \`/mandrel-deliver ${storyId}\`.`),
102
+ );
103
+ if (handedBack) err.closeNextCommand = NEXT_COMMANDS.close(storyId);
104
+ return err;
105
+ }
106
+
107
+ function syncFailureDetail({ conflictFiles, stderr }) {
108
+ if (conflictFiles) return `: conflicting files = ${conflictFiles.join(', ')}`;
109
+ return stderr ? `: ${stderr.slice(0, 200)}` : '';
110
+ }
111
+
112
+ /**
113
+ * A source conflict against a confirmed base is the delivering agent's to
114
+ * resolve; every other sync failure needs a human.
115
+ *
116
+ * @param {{ kind: string }} result
117
+ * @param {boolean} baseConfirmed
118
+ * @returns {boolean}
119
+ */
120
+ function isHandedBack(result, baseConfirmed) {
121
+ return result.kind === 'conflict' && baseConfirmed === true;
122
+ }
123
+
90
124
  /**
91
125
  * The CRAP scoring scope, or `[]` when unresolvable.
92
126
  *
@@ -142,7 +176,8 @@ function buildStampInvalidatedWarning({ baseBranch, result, targetDirs }) {
142
176
  }
143
177
 
144
178
  /**
145
- * Post a `friction` comment and block the Story; both best-effort.
179
+ * Post a `friction` comment, then block the Story unless the failure is
180
+ * handed back to the delivering agent; both best-effort.
146
181
  *
147
182
  * @param {{
148
183
  * provider: object,
@@ -154,6 +189,7 @@ function buildStampInvalidatedWarning({ baseBranch, result, targetDirs }) {
154
189
  * result: { kind: string, conflictFiles?: string[], stderr?: string },
155
190
  * progress: (tag: string, msg: string) => void,
156
191
  * }} args
192
+ * @returns {Promise<{ handedBack: boolean }>}
157
193
  */
158
194
  export async function handleSyncFailure({
159
195
  provider,
@@ -185,6 +221,25 @@ export async function handleSyncFailure({
185
221
  );
186
222
  }
187
223
 
224
+ const handedBack = isHandedBack(result, baseConfirmed);
225
+ await settleSyncFailureLabels({ provider, storyId, handedBack, progress });
226
+ return { handedBack };
227
+ }
228
+
229
+ /** A handed-back conflict leaves the labels alone; anything else blocks. */
230
+ async function settleSyncFailureLabels({
231
+ provider,
232
+ storyId,
233
+ handedBack,
234
+ progress,
235
+ }) {
236
+ if (handedBack) {
237
+ progress(
238
+ 'SYNC',
239
+ `↩️ Conflict handed back to the delivering agent; Story #${storyId} labels unchanged.`,
240
+ );
241
+ return;
242
+ }
188
243
  // The canonical mutator: a bare label write skips the Projects v2 sync.
189
244
  try {
190
245
  await transitionTicketState(provider, storyId, STATE_LABELS.BLOCKED, {});
@@ -196,6 +251,80 @@ export async function handleSyncFailure({
196
251
  }
197
252
  }
198
253
 
254
+ const CLOSE_RERUN = (storyId) =>
255
+ `node .agents/scripts/single-story-close.js --story ${storyId}`;
256
+
257
+ function commentLede(handedBack, baseBranch) {
258
+ if (handedBack) {
259
+ return [
260
+ `**For the delivering agent:** the pre-push sync against \`origin/${baseBranch}\``,
261
+ 'conflicts. Labels are unchanged — this is not a block. Resolve the',
262
+ 'conflict in the worktree, commit, and re-run close:',
263
+ ];
264
+ }
265
+ return [
266
+ `The pre-push sync against \`origin/${baseBranch}\` could not complete. The`,
267
+ 'Story has been transitioned to `agent::blocked`. To resume:',
268
+ ];
269
+ }
270
+
271
+ function mergeAdvice({ storyId, syncCwd, baseBranch, handedBack }) {
272
+ const lines = [
273
+ '```bash',
274
+ `cd ${syncCwd}`,
275
+ `git fetch origin ${baseBranch}`,
276
+ `git merge --no-edit origin/${baseBranch}`,
277
+ '# resolve any conflicts, then:',
278
+ `git add -A ; git commit --no-edit`,
279
+ '# re-run close:',
280
+ CLOSE_RERUN(storyId),
281
+ '```',
282
+ ];
283
+ if (!handedBack) return lines;
284
+ return [
285
+ ...lines,
286
+ '',
287
+ 'Only an agent that cannot resolve it takes the blocked path: post why,',
288
+ `then \`node .agents/scripts/update-ticket-state.js --ticket ${storyId} --state agent::blocked\`.`,
289
+ ];
290
+ }
291
+
292
+ function unconfirmedBaseAdvice({ storyId, storyBranch, baseBranch }) {
293
+ return [
294
+ `⚠️ **No merge advice: \`${baseBranch}\` is unconfirmed.** This close could not`,
295
+ `read the base branch \`${storyBranch}\` was seeded from off the run's`,
296
+ 'init receipt, so merging that base in could contaminate the branch',
297
+ 'and its PR diff with an unrelated base. Establish the real base first —',
298
+ `check \`temp/orchestration/story-init-result-${storyId}.log\` and \`project.baseBranch\` in`,
299
+ '`.agentrc.json` / `.agentrc.local.json` — then merge that base and re-run:',
300
+ '',
301
+ '```bash',
302
+ CLOSE_RERUN(storyId),
303
+ '```',
304
+ ];
305
+ }
306
+
307
+ function failureEvidence(kind, result) {
308
+ const files = result.conflictFiles ?? [];
309
+ if (kind === 'conflict' && files.length > 0) {
310
+ return [
311
+ '',
312
+ '**Conflicting files:**',
313
+ '',
314
+ ...files.map((f) => `- \`${f}\``),
315
+ ];
316
+ }
317
+ if (!result.stderr) return [];
318
+ return [
319
+ '',
320
+ '**git stderr:**',
321
+ '',
322
+ '```',
323
+ result.stderr.slice(0, 1000),
324
+ '```',
325
+ ];
326
+ }
327
+
199
328
  /**
200
329
  * `baseConfirmed` (default false, fail-closed) gates the merge-the-base
201
330
  * advice: merging a base the Story was not seeded from contaminates the
@@ -213,54 +342,20 @@ export function buildSyncFailureCommentBody({
213
342
  result,
214
343
  }) {
215
344
  const kind = result.kind ?? 'unknown';
345
+ const handedBack = isHandedBack(result, baseConfirmed);
216
346
  const heading =
217
347
  kind === 'conflict'
218
348
  ? `Base-sync conflict on close: ${storyBranch} ↔ origin/${baseBranch}`
219
349
  : `Base-sync failed on close (${kind}): ${storyBranch} ↔ origin/${baseBranch}`;
220
- const fileList = (result.conflictFiles ?? []).map((f) => `- \`${f}\``);
221
- const lines = [
350
+ const advice = baseConfirmed
351
+ ? mergeAdvice({ storyId, syncCwd, baseBranch, handedBack })
352
+ : unconfirmedBaseAdvice({ storyId, storyBranch, baseBranch });
353
+ return [
222
354
  `### ${heading}`,
223
355
  '',
224
- '`/mandrel-deliver` close-validation passed, but the pre-push',
225
- `sync against \`origin/${baseBranch}\` could not complete. The Story has`,
226
- `been transitioned to \`agent::blocked\`. To resume:`,
356
+ ...commentLede(handedBack, baseBranch),
227
357
  '',
228
- ...(baseConfirmed
229
- ? [
230
- '```bash',
231
- `cd ${syncCwd}`,
232
- `git fetch origin ${baseBranch}`,
233
- `git merge --no-edit origin/${baseBranch}`,
234
- '# resolve any conflicts, then:',
235
- `git add -A ; git commit --no-edit`,
236
- '# re-run close:',
237
- `node .agents/scripts/single-story-close.js --story ${storyId}`,
238
- '```',
239
- ]
240
- : [
241
- `⚠️ **No merge advice: \`${baseBranch}\` is unconfirmed.** This close could not`,
242
- `read the base branch \`${storyBranch}\` was seeded from off the run's`,
243
- 'init receipt, so merging that base in could contaminate the branch',
244
- 'and its PR diff with an unrelated base. Establish the real base first —',
245
- `check \`temp/orchestration/story-init-result-${storyId}.log\` and \`project.baseBranch\` in`,
246
- '`.agentrc.json` / `.agentrc.local.json` — then merge that base and re-run:',
247
- '',
248
- '```bash',
249
- `node .agents/scripts/single-story-close.js --story ${storyId}`,
250
- '```',
251
- ]),
252
- ];
253
- if (kind === 'conflict' && fileList.length > 0) {
254
- lines.push('', '**Conflicting files:**', '', ...fileList);
255
- } else if (result.stderr) {
256
- lines.push(
257
- '',
258
- '**git stderr:**',
259
- '',
260
- '```',
261
- result.stderr.slice(0, 1000),
262
- '```',
263
- );
264
- }
265
- return lines.join('\n');
358
+ ...advice,
359
+ ...failureEvidence(kind, result),
360
+ ].join('\n');
266
361
  }
@@ -942,6 +942,7 @@ async function onMergeObserved({
942
942
  emitMergeFlipFailedFn,
943
943
  prProbe,
944
944
  elapsedSeconds,
945
+ sleepFn,
945
946
  }) {
946
947
  const confirmation = await confirmStoryMergedFn({
947
948
  provider,
@@ -956,6 +957,8 @@ async function onMergeObserved({
956
957
  readPrMergeStateFn,
957
958
  // Saves confirmation a second `gh pr view`.
958
959
  prState: prProbe,
960
+ // The done-flip retry backs off on the wait's own clock.
961
+ sleepFn,
959
962
  });
960
963
 
961
964
  if (confirmation.merged && confirmation.action === 'flip-failed') {
@@ -1401,6 +1404,7 @@ export async function runConfirmMergePhase({
1401
1404
  issued: new Set(),
1402
1405
  },
1403
1406
  confirmStoryMergedFn,
1407
+ sleepFn,
1404
1408
  readPrWaitProbeFn,
1405
1409
  readPrMergeStateFn,
1406
1410
  classifyMergeBlockFn,