mandrel 2.80.0 → 2.82.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 (48) hide show
  1. package/.agents/audit-checklists/security.md +15 -1
  2. package/.agents/docs/agentrc-reference.json +1 -0
  3. package/.agents/docs/configuration.md +3 -2
  4. package/.agents/docs/execution-reference.md +25 -5
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +12 -2
  7. package/.agents/schemas/audit-rules.json +10 -1
  8. package/.agents/scripts/deliver-run.js +43 -8
  9. package/.agents/scripts/lib/audit-to-stories/parse-audit-md.js +49 -24
  10. package/.agents/scripts/lib/baselines/duplication-scanner.js +16 -6
  11. package/.agents/scripts/lib/baselines/refresh-service.js +6 -0
  12. package/.agents/scripts/lib/bootstrap/manifest.js +128 -159
  13. package/.agents/scripts/lib/cli-args.js +16 -2
  14. package/.agents/scripts/lib/config/gates/duplication.schema.js +10 -2
  15. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  16. package/.agents/scripts/lib/observability/close-telemetry.js +17 -2
  17. package/.agents/scripts/lib/orchestration/complexity-gate.js +58 -11
  18. package/.agents/scripts/lib/orchestration/git-cleanup/phases/cli.js +31 -27
  19. package/.agents/scripts/lib/orchestration/git-cleanup/phases/render.js +25 -21
  20. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +51 -6
  21. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +177 -0
  22. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +174 -43
  23. package/.agents/scripts/lib/orchestration/plan-persist/supersede-ops.js +57 -15
  24. package/.agents/scripts/lib/orchestration/pr-watch-poll.js +107 -0
  25. package/.agents/scripts/lib/orchestration/pr-watch.js +168 -235
  26. package/.agents/scripts/lib/orchestration/reassert-status-column.js +102 -72
  27. package/.agents/scripts/lib/orchestration/resolve-stories.js +12 -3
  28. package/.agents/scripts/lib/orchestration/resume-effort.js +121 -0
  29. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +13 -2
  30. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +21 -3
  31. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +44 -2
  32. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +10 -2
  33. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +257 -0
  34. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +341 -0
  35. package/.agents/scripts/lib/orchestration/ticketing/reads.js +3 -0
  36. package/.agents/scripts/lib/orchestration/ticketing.js +0 -9
  37. package/.agents/scripts/plan-persist.js +20 -6
  38. package/.agents/scripts/providers/github/tickets.js +2 -1
  39. package/.agents/scripts/resolve-stories.js +8 -2
  40. package/.agents/scripts/single-story-close.js +11 -3
  41. package/.agents/workflows/audit-security.md +136 -49
  42. package/.agents/workflows/helpers/deliver-reference.md +7 -2
  43. package/.agents/workflows/helpers/deliver-story.md +5 -3
  44. package/.agents/workflows/helpers/plan-reference.md +42 -2
  45. package/.agents/workflows/mandrel-deliver.md +9 -4
  46. package/.agents/workflows/mandrel-plan.md +7 -1
  47. package/docs/CHANGELOG.md +35 -0
  48. package/package.json +2 -1
@@ -10,6 +10,7 @@ import crypto from 'node:crypto';
10
10
 
11
11
  import { parseWorkerModel, parseWorkerTokens } from '../cli-args.js';
12
12
  import { Logger } from '../Logger.js';
13
+ import { parseWorkerEffort } from '../orchestration/resume-effort.js';
13
14
  import { EVENT_KINDS } from '../signals/schema.js';
14
15
  import {
15
16
  emitRuntimeFriction,
@@ -246,7 +247,7 @@ async function readStoryTally({ storyId, config, readFn = forEachLine }) {
246
247
 
247
248
  /**
248
249
  * @param {{ storyId: number, config?: object, workerTokens?: number|null,
249
- * workerModel?: string|null, landed?: boolean,
250
+ * workerModel?: string|null, workerEffort?: string|null, landed?: boolean,
250
251
  * readFn?: typeof forEachLine }} args
251
252
  * @returns {Promise<object>}
252
253
  */
@@ -255,6 +256,7 @@ async function buildCloseTelemetry({
255
256
  config,
256
257
  workerTokens = null,
257
258
  workerModel = null,
259
+ workerEffort = null,
258
260
  landed = false,
259
261
  readFn,
260
262
  }) {
@@ -268,6 +270,7 @@ async function buildCloseTelemetry({
268
270
  },
269
271
  workerTokens: Number.isInteger(workerTokens) ? workerTokens : null,
270
272
  workerModel,
273
+ workerEffort,
271
274
  };
272
275
  }
273
276
 
@@ -309,13 +312,23 @@ export function resolveWorkerModel(raw) {
309
312
  return model;
310
313
  }
311
314
 
315
+ /**
316
+ * @param {unknown} raw
317
+ * @returns {string|null}
318
+ */
319
+ export function resolveWorkerEffort(raw) {
320
+ const { effort, warning } = parseWorkerEffort(raw);
321
+ if (warning) Logger.warn(`[single-story-close] ${warning}`);
322
+ return effort;
323
+ }
324
+
312
325
  /**
313
326
  * The retry goes first so the summary counts it; a failure leaves
314
327
  * `telemetry: null` and the close's status untouched.
315
328
  *
316
329
  * @param {{ terminal: object, result?: object|null, config?: object,
317
330
  * workerTokens?: number|null, workerModel?: string|null,
318
- * readFn?: typeof forEachLine }} args
331
+ * workerEffort?: string|null, readFn?: typeof forEachLine }} args
319
332
  * @returns {Promise<void>}
320
333
  */
321
334
  export async function recordCloseTelemetry({
@@ -324,6 +337,7 @@ export async function recordCloseTelemetry({
324
337
  config,
325
338
  workerTokens = null,
326
339
  workerModel = null,
340
+ workerEffort = null,
327
341
  readFn,
328
342
  }) {
329
343
  await emitCloseRetrySignal({ envelope: terminal, config });
@@ -334,6 +348,7 @@ export async function recordCloseTelemetry({
334
348
  config,
335
349
  workerTokens,
336
350
  workerModel,
351
+ workerEffort,
337
352
  landed: terminal?.status === 'landed',
338
353
  readFn,
339
354
  });
@@ -332,20 +332,54 @@ export function deriveStoryShape({
332
332
  * run would put several engines on one session and checkout. Only *where*
333
333
  * changes; close gates, PR and terminal envelope are identical.
334
334
  *
335
- * @param {{ storyCount?: unknown }} [args] Anything but exactly 1 dispatches
336
- * as a sub-agent.
335
+ * A resumed one-Story run spawns: only a spawn carries per-call effort.
336
+ *
337
+ * @param {{ storyCount?: unknown, priorBlocks?: unknown,
338
+ * roleScopedAgents?: unknown }} [args] Anything but exactly 1 Story
339
+ * dispatches as a sub-agent.
337
340
  * @returns {{ mode: 'inline'|'subagent', reasons: string[] }}
338
341
  */
339
- export function resolveStoryDispatchMode({ storyCount } = {}) {
340
- if (storyCount === 1) {
341
- return {
342
- mode: 'inline',
343
- reasons: [
344
- 'single-Story run — execute deliver-story inline; sub-agent isolation is load-bearing only for concurrent dispatch, and a one-Story run has no sibling to race (close gates, PR, and terminal envelope unchanged)',
345
- ],
346
- };
347
- }
342
+ export function resolveStoryDispatchMode({
343
+ storyCount,
344
+ priorBlocks,
345
+ roleScopedAgents,
346
+ } = {}) {
347
+ if (storyCount !== 1) return multiStoryDispatch();
348
+ return singleStoryDispatch(priorBlocks, roleScopedAgents);
349
+ }
350
+
351
+ /**
352
+ * @param {unknown} priorBlocks
353
+ * @param {unknown} roleScopedAgents
354
+ * @returns {{ mode: 'inline'|'subagent', reasons: string[] }}
355
+ */
356
+ function singleStoryDispatch(priorBlocks, roleScopedAgents) {
357
+ return isResumeDispatch(priorBlocks, roleScopedAgents)
358
+ ? resumeDispatch(Number(priorBlocks))
359
+ : inlineDispatch();
360
+ }
361
+
362
+ /**
363
+ * @param {unknown} priorBlocks
364
+ * @param {unknown} roleScopedAgents
365
+ * @returns {boolean}
366
+ */
367
+ function isResumeDispatch(priorBlocks, roleScopedAgents) {
368
+ return roleScopedAgents === true && Number(priorBlocks) >= 1;
369
+ }
348
370
 
371
+ /** @returns {{ mode: 'inline', reasons: string[] }} */
372
+ function inlineDispatch() {
373
+ return {
374
+ mode: 'inline',
375
+ reasons: [
376
+ 'single-Story run — execute deliver-story inline; sub-agent isolation is load-bearing only for concurrent dispatch, and a one-Story run has no sibling to race (close gates, PR, and terminal envelope unchanged)',
377
+ ],
378
+ };
379
+ }
380
+
381
+ /** @returns {{ mode: 'subagent', reasons: string[] }} */
382
+ function multiStoryDispatch() {
349
383
  return {
350
384
  mode: 'subagent',
351
385
  reasons: [
@@ -353,3 +387,16 @@ export function resolveStoryDispatchMode({ storyCount } = {}) {
353
387
  ],
354
388
  };
355
389
  }
390
+
391
+ /**
392
+ * @param {number} priorBlocks
393
+ * @returns {{ mode: 'subagent', reasons: string[] }}
394
+ */
395
+ function resumeDispatch(priorBlocks) {
396
+ return {
397
+ mode: 'subagent',
398
+ reasons: [
399
+ `single-Story resume after ${priorBlocks} prior block(s) — dispatch a story-worker sub-agent so the resume effort rides the Agent call's per-call effort instead of raising session effort (close gates, PR, and terminal envelope unchanged)`,
400
+ ],
401
+ };
402
+ }
@@ -17,19 +17,26 @@ import {
17
17
  } from './phase-drivers.js';
18
18
  import { buildJsonEnvelope, computeExitCode } from './render.js';
19
19
 
20
- /* node:coverage ignore next */
21
- function resolveBaseBranch(cwd, override) {
20
+ const DEFAULT_DEPS = Object.freeze({
21
+ runFastForwardPhase,
22
+ runPrunePhase,
23
+ runBranchPhase,
24
+ runStashPhase,
25
+ resolveConfig,
26
+ write: (text) => process.stdout.write(text),
27
+ });
28
+
29
+ function resolveBaseBranch(cwd, override, deps) {
22
30
  if (override) return override;
23
31
  try {
24
- const cfg = resolveConfig({ cwd });
32
+ const cfg = deps.resolveConfig({ cwd });
25
33
  return cfg?.project?.baseBranch || 'main';
26
34
  } catch {
27
35
  return 'main';
28
36
  }
29
37
  }
30
38
 
31
- /* node:coverage ignore next */
32
- async function runActivePhases(opts, cwd, baseBranch) {
39
+ async function runActivePhases(opts, cwd, baseBranch, deps) {
33
40
  const out = {
34
41
  fastForward: null,
35
42
  prune: null,
@@ -38,24 +45,23 @@ async function runActivePhases(opts, cwd, baseBranch) {
38
45
  stashes: null,
39
46
  };
40
47
  if (opts.phases.fastForwardMain) {
41
- out.fastForward = await runFastForwardPhase(opts, cwd, baseBranch);
48
+ out.fastForward = await deps.runFastForwardPhase(opts, cwd, baseBranch);
42
49
  }
43
50
  if (opts.phases.pruneRemotes) {
44
- out.prune = await runPrunePhase(opts, cwd);
51
+ out.prune = await deps.runPrunePhase(opts, cwd);
45
52
  }
46
53
  if (opts.phases.branches) {
47
- const r = await runBranchPhase(opts, cwd, baseBranch);
54
+ const r = await deps.runBranchPhase(opts, cwd, baseBranch);
48
55
  out.branchesPlan = r.plan;
49
56
  out.branchesResult = r.result;
50
57
  }
51
58
  if (opts.phases.stashes) {
52
- out.stashes = await runStashPhase(opts, cwd);
59
+ out.stashes = await deps.runStashPhase(opts, cwd);
53
60
  }
54
61
  return out;
55
62
  }
56
63
 
57
- /* node:coverage ignore next */
58
- function maybeEmitJson(opts, baseBranch, phaseResults) {
64
+ function maybeEmitJson(opts, baseBranch, phaseResults, deps) {
59
65
  if (!opts.json) return;
60
66
  const envelope = buildJsonEnvelope({
61
67
  dryRun: opts.dryRun,
@@ -66,7 +72,7 @@ function maybeEmitJson(opts, baseBranch, phaseResults) {
66
72
  prune: phaseResults.prune,
67
73
  stashes: phaseResults.stashes,
68
74
  });
69
- process.stdout.write(`${JSON.stringify(envelope)}\n`);
75
+ deps.write(`${JSON.stringify(envelope)}\n`);
70
76
  }
71
77
 
72
78
  /**
@@ -75,21 +81,19 @@ function maybeEmitJson(opts, baseBranch, phaseResults) {
75
81
  * `runAsCli(...)` and applies `process.exit(envelope.exitCode)` at the
76
82
  * harness boundary so library code stays free of direct `process.exit`
77
83
  * calls (see `tests/enforcement/process-exit.test.js`).
84
+ *
85
+ * @param {{ argv?: string[], deps?: Partial<typeof DEFAULT_DEPS> }} [args]
86
+ * `deps` overrides the phase drivers, config resolver and stdout writer.
78
87
  */
79
- /* node:coverage ignore next */
80
- export async function runCleanup() {
81
- const opts = parseCleanupArgs(process.argv.slice(2));
88
+ export async function runCleanup({
89
+ argv = process.argv.slice(2),
90
+ deps = {},
91
+ } = {}) {
92
+ const d = { ...DEFAULT_DEPS, ...deps };
93
+ const opts = parseCleanupArgs(argv);
82
94
  const cwd = path.resolve(opts.cwd ?? PROJECT_ROOT);
83
- const baseBranch = resolveBaseBranch(cwd, opts.base);
84
- const phaseResults = await runActivePhases(opts, cwd, baseBranch);
85
- maybeEmitJson(opts, baseBranch, phaseResults);
86
- return {
87
- exitCode: computeExitCode({
88
- branchesPlan: phaseResults.branchesPlan,
89
- branchesResult: phaseResults.branchesResult,
90
- fastForward: phaseResults.fastForward,
91
- prune: phaseResults.prune,
92
- stashes: phaseResults.stashes,
93
- }),
94
- };
95
+ const baseBranch = resolveBaseBranch(cwd, opts.base, d);
96
+ const phaseResults = await runActivePhases(opts, cwd, baseBranch, d);
97
+ maybeEmitJson(opts, baseBranch, phaseResults, d);
98
+ return { exitCode: computeExitCode(phaseResults) };
95
99
  }
@@ -281,6 +281,30 @@ function legacyExitCode(plan, result) {
281
281
  return 0;
282
282
  }
283
283
 
284
+ function anyPhaseFailed({ branchesResult, fastForward, prune, stashes }) {
285
+ return [branchesResult, fastForward, prune, stashes].some(
286
+ (phase) => phase && !phase.ok,
287
+ );
288
+ }
289
+
290
+ function stashDropped(stashes) {
291
+ return (stashes?.actions ?? []).some((a) => a.action === 'drop' && a.dropped);
292
+ }
293
+
294
+ function anyPhaseWork({ branchesPlan, fastForward, prune, stashes }) {
295
+ return Boolean(
296
+ (branchesPlan?.candidates.length ?? 0) > 0 ||
297
+ fastForward?.applied ||
298
+ (prune?.pruned?.length ?? 0) > 0 ||
299
+ stashDropped(stashes),
300
+ );
301
+ }
302
+
303
+ function multiPhaseExitCode(ctx) {
304
+ if (anyPhaseFailed(ctx)) return 1;
305
+ return anyPhaseWork(ctx) ? 0 : 2;
306
+ }
307
+
284
308
  /**
285
309
  * Accepts `(plan, result)` or a multi-phase context object.
286
310
  *
@@ -292,25 +316,5 @@ export function computeExitCode(ctx, legacyResult) {
292
316
  if (legacyResult !== undefined || Array.isArray(ctx?.candidates)) {
293
317
  return legacyExitCode(ctx, legacyResult);
294
318
  }
295
- const {
296
- branchesPlan = null,
297
- branchesResult = null,
298
- fastForward = null,
299
- prune = null,
300
- stashes = null,
301
- } = ctx ?? {};
302
- const anyFailure =
303
- (branchesResult && !branchesResult.ok) ||
304
- (fastForward && !fastForward.ok) ||
305
- (prune && !prune.ok) ||
306
- (stashes && !stashes.ok);
307
- if (anyFailure) return 1;
308
- const anyWork =
309
- (branchesPlan && branchesPlan.candidates.length > 0) ||
310
- fastForward?.applied ||
311
- (prune && (prune.pruned?.length ?? 0) > 0) ||
312
- (stashes &&
313
- (stashes.actions ?? []).some((a) => a.action === 'drop' && a.dropped));
314
- if (!anyWork) return 2;
315
- return 0;
319
+ return multiPhaseExitCode(ctx ?? {});
316
320
  }
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Flat Story persist. Hard gates refuse; everything else is a warning the
3
3
  * dry-run lists. Order: validate → reachability → wave-collision gate →
4
- * create (without `agent::ready`) → plan comment on every Story → flip to
4
+ * create (without `agent::ready`) — or, for a one-for-one `--tickets` plan,
5
+ * rewrite the source in place → plan comment on every Story → flip to
5
6
  * `agent::ready` last, so `ready` implies "plan comments written" → close
6
7
  * superseded sources (never fails the run) → temp cleanup.
7
8
  *
@@ -40,6 +41,7 @@ import {
40
41
  } from './cross-plan-links.js';
41
42
  import { validateTickets } from './persist-helpers.js';
42
43
  import { surfaceSoftConflictFindings } from './soft-findings.js';
44
+ import { resolveRewriteTarget } from './source-rewrite.js';
43
45
  import {
44
46
  assemblePlanStories,
45
47
  createStoryIssues,
@@ -163,6 +165,7 @@ async function runSupersedePhase(args) {
163
165
  dryRun: args.dryRun === true,
164
166
  reason: `phase-error: ${err.message}`,
165
167
  closed: [],
168
+ rewritten: [],
166
169
  planned: [],
167
170
  epicRollup: { closed: [], pending: [] },
168
171
  skipped: [],
@@ -335,6 +338,36 @@ async function cleanupPlanDirs({ config, planDir, skipCleanup }) {
335
338
  await reapStalePlanDirs({ config, keepDir: skipCleanup ? planDir : null });
336
339
  }
337
340
 
341
+ /**
342
+ * Reads only, so the dry run probes too and reports the planned rewrite. A
343
+ * refused one-for-one lands in the run's warnings.
344
+ *
345
+ * @param {Parameters<typeof resolveRewriteTarget>[0]} args
346
+ * @param {string[]} warnings Appended to in place.
347
+ * @returns {ReturnType<typeof resolveRewriteTarget>}
348
+ */
349
+ async function resolveRewrite(args, warnings) {
350
+ const rewrite = await resolveRewriteTarget(args);
351
+ warnings.push(...rewrite.warnings);
352
+ logWarnings(rewrite.warnings);
353
+ return rewrite;
354
+ }
355
+
356
+ /**
357
+ * @param {object[]} created
358
+ * @param {{ id: number, rewritten?: boolean }} primary
359
+ * @returns {string}
360
+ */
361
+ function persistHeadline(created, primary) {
362
+ if (primary.rewritten) {
363
+ return `[plan-persist] Rewrote #${primary.id} in place; it is agent::ready.`;
364
+ }
365
+ return (
366
+ `[plan-persist] Persisted ${created.length} Story(ies)` +
367
+ `; primary #${primary.id} is agent::ready.`
368
+ );
369
+ }
370
+
338
371
  /**
339
372
  * @param {{
340
373
  * created: object[],
@@ -357,10 +390,7 @@ function logPersistEpilogue({
357
390
  `from a previous persist: ${adopted.map((s2) => `#${s2.id}`).join(', ')}.`,
358
391
  );
359
392
  }
360
- Logger.info(
361
- `[plan-persist] Persisted ${created.length} Story(ies)` +
362
- `; primary #${primary.id} is agent::ready.`,
363
- );
393
+ Logger.info(persistHeadline(created, primary));
364
394
  Logger.info(
365
395
  `[plan-persist] Deliver with: /mandrel-deliver ${created.map((s2) => s2.id).join(' ')}`,
366
396
  );
@@ -392,6 +422,7 @@ function logPersistEpilogue({
392
422
  * sourceTicketIds?: number[],
393
423
  * sourceTicketOrigin?: 'flag'|'envelope'|'none',
394
424
  * closeSuperseded?: boolean,
425
+ * rewriteSource?: boolean,
395
426
  * },
396
427
  * }} input
397
428
  */
@@ -416,6 +447,8 @@ export async function runPlanPersist({
416
447
  sourceTicketIds = [],
417
448
  sourceTicketOrigin = 'none',
418
449
  closeSuperseded = true,
450
+ // One-for-one plans rewrite their source in place unless opted out.
451
+ rewriteSource = true,
419
452
  // Optional container Epic; only set when the operator confirmed one.
420
453
  epic = null,
421
454
  } = opts;
@@ -493,11 +526,22 @@ export async function runPlanPersist({
493
526
  tempRoot: getPaths(config).tempRoot,
494
527
  });
495
528
 
529
+ const rewrite = await resolveRewrite(
530
+ {
531
+ provider,
532
+ storyCount: stories.length,
533
+ sourceTicketIds,
534
+ rewriteSource,
535
+ closeSuperseded,
536
+ },
537
+ warnings,
538
+ );
539
+
496
540
  const { created, planRunLabel, planRunLabelApplied } =
497
541
  await createStoryIssues({
498
542
  provider,
499
543
  stories,
500
- opts: { dryRun },
544
+ opts: { dryRun, rewriteTarget: rewrite.target },
501
545
  });
502
546
 
503
547
  const primary = created[0];
@@ -573,6 +617,7 @@ export async function runPlanPersist({
573
617
  assumptionNormalizations: validated.normalizations ?? [],
574
618
  waveCollisions,
575
619
  supersede,
620
+ rewrite: { ticket: rewrite.ticketId, reason: rewrite.reason },
576
621
  epic: containerEpic,
577
622
  };
578
623
  }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * source-rewrite.js — rewrite a one-for-one `/mandrel-plan --tickets` source
3
+ * ticket in place instead of filing a new Story and closing the source as its
4
+ * duplicate. Eligibility is decided here from the flags and one fresh probe of
5
+ * the source; every other shape keeps the create-and-close path.
6
+ *
7
+ * @module lib/orchestration/plan-persist/source-rewrite
8
+ */
9
+
10
+ import { AGENT_LABELS, TYPE_LABELS } from '../../label-constants.js';
11
+ import {
12
+ findStructuredComment,
13
+ upsertStructuredComment,
14
+ } from '../ticketing.js';
15
+
16
+ /** First write wins: a re-plan never replaces the pre-plan record. */
17
+ const PLAN_REWRITE_COMMENT_TYPE = 'plan-rewrite';
18
+
19
+ /**
20
+ * An open PR (`closing`) is as live as an implementing session, and
21
+ * `blocked` is a paused one — its worktree, branch and PR still exist.
22
+ */
23
+ const MID_DELIVERY_LABELS = Object.freeze([
24
+ AGENT_LABELS.EXECUTING,
25
+ AGENT_LABELS.CLOSING,
26
+ AGENT_LABELS.BLOCKED,
27
+ ]);
28
+
29
+ /**
30
+ * @typedef {object} RewriteResolution
31
+ * @property {{ id: number, ticket: object }|null} target The source to
32
+ * rewrite, carrying the probe's fresh copy so the rewrite needs no re-read.
33
+ * @property {number|null} ticketId The rewritten source's id, or null.
34
+ * @property {string|null} reason Why there is no target.
35
+ * @property {string[]} warnings One entry when a one-for-one shape was refused
36
+ * on the source's state — the operator expected a rewrite and gets a new
37
+ * Story.
38
+ */
39
+
40
+ /**
41
+ * @param {string} reason
42
+ * @param {string[]} [warnings]
43
+ * @returns {RewriteResolution}
44
+ */
45
+ function noRewrite(reason, warnings = []) {
46
+ return { target: null, ticketId: null, reason, warnings };
47
+ }
48
+
49
+ /**
50
+ * @param {object} ticket
51
+ * @returns {string|null} Why this source cannot be rewritten in place.
52
+ */
53
+ function stateRefusal(ticket) {
54
+ if (String(ticket.state ?? 'open').toLowerCase() === 'closed') {
55
+ return 'closed';
56
+ }
57
+ const labels = Array.isArray(ticket.labels) ? ticket.labels : [];
58
+ // A container has children and is never a work item.
59
+ if (labels.includes(TYPE_LABELS.EPIC)) return 'epic-container';
60
+ // Its contract is mid-delivery; rewriting it would move the goalposts.
61
+ if (MID_DELIVERY_LABELS.some((label) => labels.includes(label))) {
62
+ return 'mid-delivery';
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /**
68
+ * @param {object} provider
69
+ * @param {number} id
70
+ * @returns {Promise<{ ticket: object|null, reason: string|null }>}
71
+ */
72
+ async function probeSource(provider, id) {
73
+ try {
74
+ const ticket = await provider.getTicket(id, { fresh: true });
75
+ if (!ticket) return { ticket: null, reason: 'not-found' };
76
+ return { ticket, reason: stateRefusal(ticket) };
77
+ } catch (err) {
78
+ return { ticket: null, reason: `inaccessible: ${err.message}` };
79
+ }
80
+ }
81
+
82
+ /**
83
+ * One source ticket planned into one Story is a rewrite, unless the operator
84
+ * opted out (`--no-rewrite-source`) or asked to keep the source open
85
+ * (`--no-close-superseded`: the remainder must survive as itself).
86
+ *
87
+ * @param {object} args
88
+ * @param {object} args.provider
89
+ * @param {number} args.storyCount
90
+ * @param {number[]} args.sourceTicketIds
91
+ * @param {boolean} [args.rewriteSource=true]
92
+ * @param {boolean} [args.closeSuperseded=true]
93
+ * @returns {Promise<RewriteResolution>}
94
+ */
95
+ export async function resolveRewriteTarget({
96
+ provider,
97
+ storyCount,
98
+ sourceTicketIds,
99
+ rewriteSource = true,
100
+ closeSuperseded = true,
101
+ }) {
102
+ const ids = Array.isArray(sourceTicketIds) ? sourceTicketIds : [];
103
+ if (ids.length !== 1 || storyCount !== 1) return noRewrite('not-one-for-one');
104
+ if (!rewriteSource) return noRewrite('disabled-by-flag');
105
+ if (!closeSuperseded) return noRewrite('no-close-superseded');
106
+ const [id] = ids;
107
+ const { ticket, reason } = await probeSource(provider, id);
108
+ if (reason !== null) {
109
+ return noRewrite(reason, [
110
+ `source ticket #${id} cannot be rewritten in place (${reason}) — ` +
111
+ `filing a new Story and closing #${id} instead.`,
112
+ ]);
113
+ }
114
+ return { target: { id, ticket }, ticketId: id, reason: null, warnings: [] };
115
+ }
116
+
117
+ /**
118
+ * @param {{ title?: string, body?: string }} ticket
119
+ * @returns {string}
120
+ */
121
+ function buildPlanRewriteCommentBody(ticket) {
122
+ const body = (ticket.body ?? '').trim();
123
+ return [
124
+ '**Rewritten in place by `/mandrel-plan`.** The original title and body ' +
125
+ 'are kept below as the pre-plan record; the issue body now carries the ' +
126
+ 'delivery contract.',
127
+ '',
128
+ `<details><summary>Original: ${ticket.title ?? '(untitled)'}</summary>`,
129
+ '',
130
+ body === '' ? '_(empty body)_' : body,
131
+ '',
132
+ '</details>',
133
+ ].join('\n');
134
+ }
135
+
136
+ /**
137
+ * Preserve the original (once), then rewrite title, body and labels in one
138
+ * PATCH. The caller strips every `agent::*` label in that PATCH, so a source
139
+ * already at `agent::ready` is never deliverable mid-rewrite; the ready flip
140
+ * stays the persist's terminal step.
141
+ *
142
+ * @param {object} args
143
+ * @param {object} args.provider
144
+ * @param {{ id: number, ticket: object }} args.target
145
+ * @param {string} args.title
146
+ * @param {string} args.body
147
+ * @param {{ add: string[], remove: string[] }} args.labels
148
+ * @returns {Promise<void>}
149
+ */
150
+ export async function rewriteSourceTicket({
151
+ provider,
152
+ target,
153
+ title,
154
+ body,
155
+ labels,
156
+ }) {
157
+ const { id, ticket } = target;
158
+ const preserved = await findStructuredComment(
159
+ provider,
160
+ id,
161
+ PLAN_REWRITE_COMMENT_TYPE,
162
+ );
163
+ if (!preserved) {
164
+ await upsertStructuredComment(
165
+ provider,
166
+ id,
167
+ PLAN_REWRITE_COMMENT_TYPE,
168
+ buildPlanRewriteCommentBody(ticket),
169
+ );
170
+ }
171
+ await provider.updateTicket(id, {
172
+ title,
173
+ body,
174
+ labels,
175
+ _ticketSnapshot: ticket,
176
+ });
177
+ }