mandrel 2.79.0 → 2.81.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 (55) hide show
  1. package/.agents/agents/auditor.md +8 -3
  2. package/.agents/audit-checklists/data-model.md +9 -1
  3. package/.agents/audit-checklists/security.md +15 -1
  4. package/.agents/docs/agentrc-reference.json +4 -0
  5. package/.agents/docs/configuration.md +4 -3
  6. package/.agents/docs/execution-reference.md +25 -5
  7. package/.agents/docs/workflows.md +2 -2
  8. package/.agents/schemas/agentrc.schema.json +31 -3
  9. package/.agents/schemas/audit-rules.json +15 -2
  10. package/.agents/scripts/deliver-run.js +43 -8
  11. package/.agents/scripts/lib/audit-to-stories/seed-from-findings.js +37 -2
  12. package/.agents/scripts/lib/baselines/duplication-scanner.js +7 -1
  13. package/.agents/scripts/lib/baselines/refresh-service.js +6 -0
  14. package/.agents/scripts/lib/cli-args.js +16 -2
  15. package/.agents/scripts/lib/config/explain.js +1 -1
  16. package/.agents/scripts/lib/config/gates/duplication.schema.js +10 -2
  17. package/.agents/scripts/lib/config-settings-schema.js +18 -1
  18. package/.agents/scripts/lib/findings/audit-finding-record.js +95 -0
  19. package/.agents/scripts/lib/findings/route-finding.js +4 -3
  20. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  21. package/.agents/scripts/lib/observability/close-telemetry.js +17 -2
  22. package/.agents/scripts/lib/orchestration/complexity-gate.js +58 -11
  23. package/.agents/scripts/lib/orchestration/plan-persist/audit-attribution.js +182 -0
  24. package/.agents/scripts/lib/orchestration/plan-persist/audit-provenance.js +11 -10
  25. package/.agents/scripts/lib/orchestration/plan-persist/collision-message.js +52 -0
  26. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +56 -9
  27. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +177 -0
  28. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +202 -57
  29. package/.agents/scripts/lib/orchestration/plan-persist/supersede-ops.js +57 -15
  30. package/.agents/scripts/lib/orchestration/plan-persist/wave-collision-gate.js +8 -4
  31. package/.agents/scripts/lib/orchestration/plan-persist/wave-serialisation.js +3 -2
  32. package/.agents/scripts/lib/orchestration/resolve-stories.js +12 -3
  33. package/.agents/scripts/lib/orchestration/resume-effort.js +121 -0
  34. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +13 -2
  35. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +10 -2
  36. package/.agents/scripts/lib/orchestration/ticketing/reads.js +3 -0
  37. package/.agents/scripts/lib/qa/resolve-qa-contract.js +28 -9
  38. package/.agents/scripts/lib/templates/decomposer-prompts.js +2 -2
  39. package/.agents/scripts/lib/wave-runner/footprint.js +114 -17
  40. package/.agents/scripts/lib/wave-runner/ready-set.js +16 -5
  41. package/.agents/scripts/plan-persist.js +20 -6
  42. package/.agents/scripts/providers/github/tickets.js +2 -1
  43. package/.agents/scripts/resolve-stories.js +8 -2
  44. package/.agents/scripts/single-story-close.js +11 -3
  45. package/.agents/workflows/audit-data-model.md +94 -10
  46. package/.agents/workflows/audit-security.md +136 -49
  47. package/.agents/workflows/audit-to-stories.md +22 -7
  48. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  49. package/.agents/workflows/helpers/deliver-reference.md +7 -2
  50. package/.agents/workflows/helpers/deliver-story.md +5 -3
  51. package/.agents/workflows/helpers/plan-reference.md +53 -5
  52. package/.agents/workflows/mandrel-deliver.md +9 -4
  53. package/.agents/workflows/mandrel-plan.md +7 -1
  54. package/docs/CHANGELOG.md +25 -0
  55. package/package.json +2 -1
@@ -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
+ }
@@ -24,10 +24,12 @@ import {
24
24
  concurrentMap,
25
25
  FANOUT_CONCURRENCY,
26
26
  } from '../../util/concurrent-map.js';
27
+ import { attributeSeedProvenance } from './audit-attribution.js';
27
28
  import {
28
29
  externalDependencyId,
29
30
  isExternalDependencyRef,
30
31
  } from './external-deps.js';
32
+ import { rewriteSourceTicket } from './source-rewrite.js';
31
33
  import {
32
34
  normalizeSupersedes,
33
35
  resolveSupersedePartition,
@@ -329,20 +331,21 @@ export function foldSpecIntoStoryBody(bodyObject, slug, opts = {}) {
329
331
 
330
332
  /**
331
333
  * An authored `provenance` stamps exactly the identities this Story owns;
332
- * otherwise the whole seed's footers are carried. Keep that union fallback:
333
- * without it a non-attributing plan persists Stories with no provenance and
334
- * the next audit sweep re-files planned work.
334
+ * otherwise the source `attributeSeedProvenance` resolved — the findings path
335
+ * attribution gave this Story, or the whole seed's union. Keep that union
336
+ * fallback: without it a non-attributing plan persists Stories with no
337
+ * provenance and the next audit sweep re-files planned work.
335
338
  *
336
339
  * @param {{ fingerprints: string[], semanticKeys: string[] }|null} provenance
337
- * @param {object} opts
340
+ * @param {string} resolved
338
341
  * @returns {string}
339
342
  */
340
- function resolveProvenanceSource(provenance, opts) {
343
+ function resolveProvenanceSource(provenance, resolved) {
341
344
  if (provenance !== null) return ownedProvenanceSource(provenance);
342
- return opts.provenanceSource ?? '';
345
+ return resolved;
343
346
  }
344
347
 
345
- function assembleOnePlanStory(ticket, opts) {
348
+ function assembleOnePlanStory(normalized, attributed, opts) {
346
349
  const {
347
350
  slug,
348
351
  title,
@@ -351,7 +354,7 @@ function assembleOnePlanStory(ticket, opts) {
351
354
  labels,
352
355
  supersedes,
353
356
  provenance,
354
- } = normalizeStoryTicket(ticket);
357
+ } = normalized;
355
358
  const { bodyObject: folded } = foldSpecIntoStoryBody(bodyObject, slug, {
356
359
  sharedSpec: opts.sharedSpec ?? null,
357
360
  });
@@ -359,7 +362,7 @@ function assembleOnePlanStory(ticket, opts) {
359
362
  // Mechanical on purpose: the authoring agent is not asked to hand-carry
360
363
  // audit footers. A non-audit seed has none, so this is a no-op there.
361
364
  const { body } = carryProvenanceFooters({
362
- from: resolveProvenanceSource(provenance, opts),
365
+ from: resolveProvenanceSource(provenance, attributed),
363
366
  into: serialized,
364
367
  });
365
368
  const fingerprint = planStoryFingerprint({ slug, title, body });
@@ -402,6 +405,8 @@ function assertSharedSpecAllowed(tickets, sharedSpec) {
402
405
  * @param {object} [opts]
403
406
  * @param {string|null} [opts.sharedSpec]
404
407
  * @param {number[]} [opts.sourceTicketIds] Ids passed to `/mandrel-plan --tickets`.
408
+ * @param {string} [opts.provenanceSource] The seed's provenance footers; an
409
+ * N>1 draft attributes its `audit-finding` records per Story.
405
410
  * @returns {{ stories: Array<{ slug: string, title: string, body: string, acceptance: string[], depends_on: string[], supersedes: Array<{ id: number, note: string|null }> }>, warnings: string[] }}
406
411
  */
407
412
  export function assemblePlanStories(tickets, opts = {}) {
@@ -413,14 +418,24 @@ export function assemblePlanStories(tickets, opts = {}) {
413
418
 
414
419
  assertSharedSpecAllowed(tickets, opts.sharedSpec);
415
420
 
421
+ const normalized = tickets.map(normalizeStoryTicket);
422
+ const attribution = attributeSeedProvenance(
423
+ normalized.map((n) => ({
424
+ provenance: n.provenance,
425
+ changes: n.bodyObject.changes,
426
+ })),
427
+ opts.provenanceSource,
428
+ );
416
429
  const stories = orderStoriesByDependencies(
417
- tickets.map((ticket) => assembleOnePlanStory(ticket, opts).story),
430
+ normalized.map(
431
+ (n, i) => assembleOnePlanStory(n, attribution.sources[i], opts).story,
432
+ ),
418
433
  );
419
434
 
420
- const warnings = resolveSupersedePartition(
421
- stories,
422
- opts.sourceTicketIds ?? [],
423
- );
435
+ const warnings = [
436
+ ...attribution.warnings,
437
+ ...resolveSupersedePartition(stories, opts.sourceTicketIds ?? []),
438
+ ];
424
439
 
425
440
  return { stories, warnings };
426
441
  }
@@ -708,11 +723,167 @@ async function ensurePersistLabel({
708
723
  }
709
724
  }
710
725
 
726
+ /**
727
+ * Label mutations for a rewritten source: the Story's labels on, and every
728
+ * `agent::*` plus any earlier run's cohort label off — the source now belongs
729
+ * to this run and is not deliverable until the terminal ready flip.
730
+ *
731
+ * @param {string[]} currentLabels
732
+ * @param {string[]} add
733
+ * @returns {{ add: string[], remove: string[] }}
734
+ */
735
+ function rewriteLabelMutations(currentLabels, add) {
736
+ const agentLabels = Object.values(AGENT_LABELS);
737
+ const remove = (currentLabels ?? []).filter(
738
+ (label) =>
739
+ !add.includes(label) &&
740
+ (agentLabels.includes(label) || label.startsWith(PLAN_RUN_LABEL_PREFIX)),
741
+ );
742
+ return { add, remove };
743
+ }
744
+
745
+ /**
746
+ * Dry-run receipts: placeholder ids, or the source's id for a rewrite.
747
+ *
748
+ * @param {object[]} list
749
+ * @param {{ id: number }|null} rewriting
750
+ * @returns {object[]}
751
+ */
752
+ function dryRunEntries(list, rewriting) {
753
+ if (rewriting) {
754
+ return list.map((s) => ({
755
+ slug: s.slug,
756
+ id: rewriting.id,
757
+ title: s.title,
758
+ url: undefined,
759
+ adopted: false,
760
+ rewritten: true,
761
+ }));
762
+ }
763
+ return list.map((s, i) => ({
764
+ slug: s.slug,
765
+ id: -(i + 1),
766
+ title: s.title,
767
+ url: undefined,
768
+ adopted: false,
769
+ }));
770
+ }
771
+
772
+ /**
773
+ * A resumed Story; when it is the rewrite target, the source already carries
774
+ * this Story, so it stays `rewritten`.
775
+ *
776
+ * @param {{ slug: string, title: string }} story
777
+ * @param {{ id: number, url?: string }} already
778
+ * @param {{ id: number }|null} rewriting
779
+ * @returns {object}
780
+ */
781
+ function adoptedEntry(story, already, rewriting) {
782
+ const entry = {
783
+ slug: story.slug,
784
+ id: already.id,
785
+ title: story.title,
786
+ url: already.url,
787
+ adopted: true,
788
+ };
789
+ if (already.id === rewriting?.id) entry.rewritten = true;
790
+ return entry;
791
+ }
792
+
793
+ /**
794
+ * @param {object} args
795
+ * @param {object} args.provider
796
+ * @param {object} args.story
797
+ * @param {{ id: number, ticket: object }} args.rewriting
798
+ * @param {string[]} args.labels
799
+ * @param {Map<string, number>} args.idBySlug
800
+ * @returns {Promise<object>} The `created[]` entry.
801
+ */
802
+ async function rewriteInPlace({
803
+ provider,
804
+ story,
805
+ rewriting,
806
+ labels,
807
+ idBySlug,
808
+ }) {
809
+ await rewriteSourceTicket({
810
+ provider,
811
+ target: rewriting,
812
+ title: story.title,
813
+ body: renderStoryBodyForCreate(story, idBySlug),
814
+ labels: rewriteLabelMutations(rewriting.ticket.labels, labels),
815
+ });
816
+ Logger.info(
817
+ `[plan-persist] rewrote source ticket #${rewriting.id} in place as ` +
818
+ `Story "${story.slug}" — no new issue filed.`,
819
+ );
820
+ return {
821
+ slug: story.slug,
822
+ id: rewriting.id,
823
+ title: story.title,
824
+ url: rewriting.ticket.url,
825
+ internalId: rewriting.ticket.internalId,
826
+ adopted: false,
827
+ rewritten: true,
828
+ };
829
+ }
830
+
831
+ /**
832
+ * POST one Story, adopting a lost-response first attempt by fingerprint.
833
+ *
834
+ * @param {object} args
835
+ * @param {object} args.provider
836
+ * @param {object} args.story
837
+ * @param {string[]} args.labels
838
+ * @param {Map<string, number>} args.idBySlug
839
+ * @param {Map<string, number[]>} args.idsByTitle
840
+ * @returns {Promise<object>} The `created[]` entry.
841
+ */
842
+ async function createOneStory({
843
+ provider,
844
+ story,
845
+ labels,
846
+ idBySlug,
847
+ idsByTitle,
848
+ }) {
849
+ warnOnDivergentSameTitleStory(story, idsByTitle);
850
+ const result = await provider.createIssue({
851
+ title: story.title,
852
+ body: renderStoryBodyForCreate(story, idBySlug),
853
+ labels,
854
+ findExisting: () =>
855
+ findOpenStoryByPlanFingerprint({
856
+ provider,
857
+ fingerprint: story.fingerprint,
858
+ }),
859
+ });
860
+ const id = result?.id ?? result?.number;
861
+ if (!Number.isInteger(id)) {
862
+ throw new Error(
863
+ `[plan-persist] createIssue for slug "${story.slug}" did not return a numeric id`,
864
+ );
865
+ }
866
+ return {
867
+ slug: story.slug,
868
+ id,
869
+ title: story.title,
870
+ url: result.url,
871
+ // The database id — the only id the native sub-issue write accepts.
872
+ internalId: result.internalId,
873
+ // True when the retry probe adopted a lost-response first attempt.
874
+ adopted: result.adopted === true,
875
+ };
876
+ }
877
+
711
878
  /**
712
879
  * Create Story issues resumably, adopting any open Story whose fingerprint
713
880
  * matches. Stories are born without `agent::ready`; `markStoriesReady` flips
714
881
  * it last, once every plan comment is on the ticket.
715
882
  *
883
+ * With `opts.rewriteTarget` (a one-for-one plan), the single Story is written
884
+ * over that source ticket instead of POSTed; its entry carries
885
+ * `rewritten: true` and the source's id.
886
+ *
716
887
  * The loop stays serial: `idBySlug` is filled in loop order by the POSTs, and
717
888
  * a concurrent create would render `#undefined` dependency refs.
718
889
  *
@@ -721,8 +892,9 @@ async function ensurePersistLabel({
721
892
  * @param {ReturnType<typeof assemblePlanStories>['stories']} args.stories
722
893
  * @param {object} [args.opts]
723
894
  * @param {boolean} [args.opts.dryRun=false]
895
+ * @param {{ id: number, ticket: object }|null} [args.opts.rewriteTarget=null]
724
896
  * @returns {Promise<{
725
- * created: Array<{ slug: string, id: number, url?: string, title: string, adopted: boolean }>,
897
+ * created: Array<{ slug: string, id: number, url?: string, title: string, adopted: boolean, rewritten?: boolean }>,
726
898
  * dependencyEdges: { edgesAdded: number, edgesSkipped: number, edgesFailed: number, storiesProcessed: number }|null,
727
899
  * planRunLabel: string,
728
900
  * planRunLabelApplied: boolean,
@@ -736,6 +908,7 @@ export async function createStoryIssues({ provider, stories, opts = {} }) {
736
908
  }
737
909
 
738
910
  const list = Array.isArray(stories) ? stories : [];
911
+ const rewriting = list.length === 1 ? (opts.rewriteTarget ?? null) : null;
739
912
 
740
913
  const cohortLabel = planRunLabel(
741
914
  derivePlanRunId(list.map((story) => story.fingerprint)),
@@ -743,13 +916,7 @@ export async function createStoryIssues({ provider, stories, opts = {} }) {
743
916
 
744
917
  if (opts.dryRun) {
745
918
  return {
746
- created: list.map((s, i) => ({
747
- slug: s.slug,
748
- id: -(i + 1),
749
- title: s.title,
750
- url: undefined,
751
- adopted: false,
752
- })),
919
+ created: dryRunEntries(list, rewriting),
753
920
  dependencyEdges: null,
754
921
  planRunLabel: cohortLabel,
755
922
  planRunLabelApplied: false,
@@ -768,55 +935,33 @@ export async function createStoryIssues({ provider, stories, opts = {} }) {
768
935
  const { byFingerprint, idsByTitle } = await indexExistingStories(provider);
769
936
  const created = [];
770
937
  const idBySlug = new Map();
938
+ const cohortLabels = applyCohortLabel ? [cohortLabel] : [];
771
939
 
772
940
  // Already dependency-ordered; re-sorting would disagree on the primary.
773
941
  for (const story of list) {
774
942
  const already = byFingerprint.get(story.fingerprint);
775
- if (!already) warnOnDivergentSameTitleStory(story, idsByTitle);
776
943
  if (already) {
777
944
  Logger.info(
778
945
  `[plan-persist] resuming: Story "${story.slug}" already exists as ` +
779
946
  `#${already.id} with byte-identical authored content ` +
780
947
  `(plan fingerprint ${story.fingerprint}) — skipping create.`,
781
948
  );
782
- created.push({
783
- slug: story.slug,
784
- id: already.id,
785
- title: story.title,
786
- url: already.url,
787
- adopted: true,
788
- });
949
+ created.push(adoptedEntry(story, already, rewriting));
789
950
  idBySlug.set(story.slug, already.id);
790
951
  continue;
791
952
  }
792
953
 
793
- const result = await provider.createIssue({
794
- title: story.title,
795
- body: renderStoryBodyForCreate(story, idBySlug),
796
- labels: [...story.labels, ...(applyCohortLabel ? [cohortLabel] : [])],
797
- findExisting: () =>
798
- findOpenStoryByPlanFingerprint({
799
- provider,
800
- fingerprint: story.fingerprint,
801
- }),
802
- });
803
- const id = result?.id ?? result?.number;
804
- if (!Number.isInteger(id)) {
805
- throw new Error(
806
- `[plan-persist] createIssue for slug "${story.slug}" did not return a numeric id`,
807
- );
808
- }
809
- created.push({
810
- slug: story.slug,
811
- id,
812
- title: story.title,
813
- url: result.url,
814
- // The database id — the only id the native sub-issue write accepts.
815
- internalId: result.internalId,
816
- // True when the retry probe adopted a lost-response first attempt.
817
- adopted: result.adopted === true,
818
- });
819
- idBySlug.set(story.slug, id);
954
+ const args = {
955
+ provider,
956
+ story,
957
+ labels: [...story.labels, ...cohortLabels],
958
+ idBySlug,
959
+ };
960
+ const entry = rewriting
961
+ ? await rewriteInPlace({ ...args, rewriting })
962
+ : await createOneStory({ ...args, idsByTitle });
963
+ created.push(entry);
964
+ idBySlug.set(story.slug, entry.id);
820
965
  }
821
966
 
822
967
  // Includes adopted ids, so a resume mirrors the whole cohort (idempotent).
@@ -379,6 +379,8 @@ async function closeOneSupersededTicket({
379
379
  * @property {string|null} reason Why the phase was skipped wholesale.
380
380
  * @property {'flag'|'envelope'|'none'} [sourceTicketOrigin] Stamped by `runPlanPersist`.
381
381
  * @property {number[]} closed
382
+ * @property {number[]} rewritten Sources rewritten in place as their Story —
383
+ * never commented on or closed (dry runs list the planned rewrite).
382
384
  * @property {Array<{ ticket: number, storySlug: string }>} planned Dry-run
383
385
  * only; keyed by slug because dry-run Story ids are placeholders.
384
386
  * @property {Array<{ ticket: number, reason: string }>} skipped
@@ -392,6 +394,7 @@ function emptyReport(overrides) {
392
394
  dryRun: false,
393
395
  reason: null,
394
396
  closed: [],
397
+ rewritten: [],
395
398
  planned: [],
396
399
  skipped: [],
397
400
  failed: [],
@@ -471,19 +474,7 @@ export async function closeSupersededTickets({
471
474
  // the probe → comment → close sequence stays strictly ordered.
472
475
  const outcomes = await concurrentMap(
473
476
  units,
474
- ({ id, note, createdStory }) => {
475
- if (!createdStory) {
476
- return { outcome: 'skipped', reason: 'story-not-created' };
477
- }
478
- if (dryRun) return { outcome: 'planned' };
479
- return closeOneSupersededTicket({
480
- provider,
481
- id,
482
- note,
483
- story: createdStory,
484
- sourceTicketIds: sources,
485
- });
486
- },
477
+ (unit) => supersedeUnit(unit, { provider, dryRun, sources }),
487
478
  { concurrency: FANOUT_CONCURRENCY },
488
479
  );
489
480
 
@@ -520,6 +511,45 @@ function collectSupersedeUnits(stories, createdBySlug) {
520
511
  return units;
521
512
  }
522
513
 
514
+ /**
515
+ * One unit's outcome. Never throws.
516
+ *
517
+ * @param {{ id: number, note: string|null, createdStory: object|undefined }} unit
518
+ * @param {{ provider: object, dryRun: boolean, sources: number[] }} ctx
519
+ * @returns {Promise<{ outcome: string, reason?: string }>|{ outcome: string, reason?: string }}
520
+ */
521
+ function supersedeUnit(
522
+ { id, note, createdStory },
523
+ { provider, dryRun, sources },
524
+ ) {
525
+ if (!createdStory) {
526
+ return { outcome: 'skipped', reason: 'story-not-created' };
527
+ }
528
+ if (isRewrittenSource(createdStory, id)) return { outcome: 'rewritten' };
529
+ if (dryRun) return { outcome: 'planned' };
530
+ return closeOneSupersededTicket({
531
+ provider,
532
+ id,
533
+ note,
534
+ story: createdStory,
535
+ sourceTicketIds: sources,
536
+ });
537
+ }
538
+
539
+ /**
540
+ * The source IS the Story now; closing it would close the work.
541
+ *
542
+ * @param {{ id: number, rewritten?: boolean }} createdStory
543
+ * @param {number} id
544
+ * @returns {boolean}
545
+ */
546
+ function isRewrittenSource(createdStory, id) {
547
+ return createdStory.rewritten === true && createdStory.id === id;
548
+ }
549
+
550
+ /** Outcomes recorded as a bare ticket id. */
551
+ const ID_OUTCOMES = new Set(['closed', 'rewritten']);
552
+
523
553
  /**
524
554
  * @param {SupersedeReport} report
525
555
  * @param {{ id: number, createdStory: object|undefined }} unit
@@ -527,8 +557,8 @@ function collectSupersedeUnits(stories, createdBySlug) {
527
557
  * @returns {void}
528
558
  */
529
559
  function recordSupersedeOutcome(report, unit, result) {
530
- if (result.outcome === 'closed') {
531
- report.closed.push(unit.id);
560
+ if (ID_OUTCOMES.has(result.outcome)) {
561
+ report[result.outcome].push(unit.id);
532
562
  return;
533
563
  }
534
564
  if (result.outcome === 'planned') {
@@ -545,10 +575,22 @@ function recordSupersedeOutcome(report, unit, result) {
545
575
  report.failed.push({ ticket: unit.id, reason: result.reason });
546
576
  }
547
577
 
578
+ /**
579
+ * @param {SupersedeReport} report
580
+ */
581
+ function logRewrittenSources(report) {
582
+ const line = report.dryRun
583
+ ? (id) =>
584
+ `[plan-persist] dry-run: would rewrite #${id} in place as its Story.`
585
+ : (id) => `[plan-persist] #${id} was rewritten in place — not closed.`;
586
+ for (const id of report.rewritten) Logger.info(line(id));
587
+ }
588
+
548
589
  /**
549
590
  * @param {SupersedeReport} report
550
591
  */
551
592
  function logSupersedeReport(report) {
593
+ logRewrittenSources(report);
552
594
  if (report.dryRun) {
553
595
  for (const { ticket, storySlug } of report.planned) {
554
596
  Logger.info(
@@ -5,6 +5,7 @@
5
5
  * @module lib/orchestration/plan-persist/wave-collision-gate
6
6
  */
7
7
 
8
+ import { declarerClauses } from './collision-message.js';
8
9
  import { predictWaveSerialisation } from './wave-serialisation.js';
9
10
 
10
11
  /**
@@ -27,12 +28,15 @@ function withDeclaredFootprint(story) {
27
28
  }
28
29
 
29
30
  /**
30
- * @param {{ wave: number, slugs: [string, string], paths: string[], source: string }} collision
31
+ * One refusal line per colliding path, each naming its declarer.
32
+ *
33
+ * @param {{ wave: number, slugs: [string, string], paths: string[], source: string, declaredBy?: Record<string, string> }} collision
31
34
  * @returns {string}
32
35
  */
33
- function formatCollision({ wave, slugs, paths, source }) {
34
- const declared = paths.map((p) => `\`${p}\``).join(', ');
35
- return ` - wave ${wave}: "${slugs[0]}" + "${slugs[1]}" both declare ${declared} (${source})`;
36
+ function formatCollision({ wave, source, ...collision }) {
37
+ return declarerClauses(collision)
38
+ .map((clause) => ` - wave ${wave}: ${clause} (${source})`)
39
+ .join('\n');
36
40
  }
37
41
 
38
42
  /**