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
@@ -29,6 +29,7 @@ import {
29
29
  externalDependencyId,
30
30
  isExternalDependencyRef,
31
31
  } from './external-deps.js';
32
+ import { rewriteSourceTicket } from './source-rewrite.js';
32
33
  import {
33
34
  normalizeSupersedes,
34
35
  resolveSupersedePartition,
@@ -722,11 +723,167 @@ async function ensurePersistLabel({
722
723
  }
723
724
  }
724
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
+
725
878
  /**
726
879
  * Create Story issues resumably, adopting any open Story whose fingerprint
727
880
  * matches. Stories are born without `agent::ready`; `markStoriesReady` flips
728
881
  * it last, once every plan comment is on the ticket.
729
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
+ *
730
887
  * The loop stays serial: `idBySlug` is filled in loop order by the POSTs, and
731
888
  * a concurrent create would render `#undefined` dependency refs.
732
889
  *
@@ -735,8 +892,9 @@ async function ensurePersistLabel({
735
892
  * @param {ReturnType<typeof assemblePlanStories>['stories']} args.stories
736
893
  * @param {object} [args.opts]
737
894
  * @param {boolean} [args.opts.dryRun=false]
895
+ * @param {{ id: number, ticket: object }|null} [args.opts.rewriteTarget=null]
738
896
  * @returns {Promise<{
739
- * 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 }>,
740
898
  * dependencyEdges: { edgesAdded: number, edgesSkipped: number, edgesFailed: number, storiesProcessed: number }|null,
741
899
  * planRunLabel: string,
742
900
  * planRunLabelApplied: boolean,
@@ -750,6 +908,7 @@ export async function createStoryIssues({ provider, stories, opts = {} }) {
750
908
  }
751
909
 
752
910
  const list = Array.isArray(stories) ? stories : [];
911
+ const rewriting = list.length === 1 ? (opts.rewriteTarget ?? null) : null;
753
912
 
754
913
  const cohortLabel = planRunLabel(
755
914
  derivePlanRunId(list.map((story) => story.fingerprint)),
@@ -757,13 +916,7 @@ export async function createStoryIssues({ provider, stories, opts = {} }) {
757
916
 
758
917
  if (opts.dryRun) {
759
918
  return {
760
- created: list.map((s, i) => ({
761
- slug: s.slug,
762
- id: -(i + 1),
763
- title: s.title,
764
- url: undefined,
765
- adopted: false,
766
- })),
919
+ created: dryRunEntries(list, rewriting),
767
920
  dependencyEdges: null,
768
921
  planRunLabel: cohortLabel,
769
922
  planRunLabelApplied: false,
@@ -782,55 +935,33 @@ export async function createStoryIssues({ provider, stories, opts = {} }) {
782
935
  const { byFingerprint, idsByTitle } = await indexExistingStories(provider);
783
936
  const created = [];
784
937
  const idBySlug = new Map();
938
+ const cohortLabels = applyCohortLabel ? [cohortLabel] : [];
785
939
 
786
940
  // Already dependency-ordered; re-sorting would disagree on the primary.
787
941
  for (const story of list) {
788
942
  const already = byFingerprint.get(story.fingerprint);
789
- if (!already) warnOnDivergentSameTitleStory(story, idsByTitle);
790
943
  if (already) {
791
944
  Logger.info(
792
945
  `[plan-persist] resuming: Story "${story.slug}" already exists as ` +
793
946
  `#${already.id} with byte-identical authored content ` +
794
947
  `(plan fingerprint ${story.fingerprint}) — skipping create.`,
795
948
  );
796
- created.push({
797
- slug: story.slug,
798
- id: already.id,
799
- title: story.title,
800
- url: already.url,
801
- adopted: true,
802
- });
949
+ created.push(adoptedEntry(story, already, rewriting));
803
950
  idBySlug.set(story.slug, already.id);
804
951
  continue;
805
952
  }
806
953
 
807
- const result = await provider.createIssue({
808
- title: story.title,
809
- body: renderStoryBodyForCreate(story, idBySlug),
810
- labels: [...story.labels, ...(applyCohortLabel ? [cohortLabel] : [])],
811
- findExisting: () =>
812
- findOpenStoryByPlanFingerprint({
813
- provider,
814
- fingerprint: story.fingerprint,
815
- }),
816
- });
817
- const id = result?.id ?? result?.number;
818
- if (!Number.isInteger(id)) {
819
- throw new Error(
820
- `[plan-persist] createIssue for slug "${story.slug}" did not return a numeric id`,
821
- );
822
- }
823
- created.push({
824
- slug: story.slug,
825
- id,
826
- title: story.title,
827
- url: result.url,
828
- // The database id — the only id the native sub-issue write accepts.
829
- internalId: result.internalId,
830
- // True when the retry probe adopted a lost-response first attempt.
831
- adopted: result.adopted === true,
832
- });
833
- 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);
834
965
  }
835
966
 
836
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(
@@ -0,0 +1,107 @@
1
+ /**
2
+ * pr-watch-poll.js — the pure outcome helpers and the bounded poll loop
3
+ * behind `watchPrToTerminal` (pr-watch.js).
4
+ */
5
+
6
+ import { checkVerdict, classifyRequiredCheck } from './check-state.js';
7
+
8
+ /** Entries with a string `name`; `[]` for malformed input. */
9
+ export function parseGhPrChecks(stdout) {
10
+ const trimmed = String(stdout ?? '').trim();
11
+ if (trimmed.length === 0) return [];
12
+ try {
13
+ const parsed = JSON.parse(trimmed);
14
+ if (!Array.isArray(parsed)) return [];
15
+ return parsed.filter(
16
+ (e) => e && typeof e === 'object' && typeof e.name === 'string',
17
+ );
18
+ } catch {
19
+ return [];
20
+ }
21
+ }
22
+
23
+ /** `{ checkName: outcome }`; a repeated name (matrix, retry) — last wins. */
24
+ export function reduceOutcomes(entries) {
25
+ const out = {};
26
+ for (const e of entries) {
27
+ out[e.name] = classifyRequiredCheck(e);
28
+ }
29
+ return out;
30
+ }
31
+
32
+ /** Only `'pending'` is non-terminal (the classifier collapses running states). */
33
+ export function allTerminal(outcomes) {
34
+ for (const v of Object.values(outcomes)) {
35
+ if (v === 'pending') return false;
36
+ }
37
+ return true;
38
+ }
39
+
40
+ /** Slow CI, not red: "re-arm the watch", never "the change is broken". */
41
+ const STILL_RUNNING = 'still-running';
42
+
43
+ /** Leftover `'pending'` → `'still-running'` (the schema forbids pending). */
44
+ export function promotePendingToStillRunning(outcomes) {
45
+ const out = {};
46
+ for (const [k, v] of Object.entries(outcomes)) {
47
+ out[k] = v === 'pending' ? STILL_RUNNING : v;
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /** A genuinely red check: the hard stop that consumes no resume budget. */
53
+ export function hasFailingCheck(outcomes) {
54
+ return Object.values(outcomes).some((v) => checkVerdict(v) === 'fail');
55
+ }
56
+
57
+ async function identityDiscount(_entries, outcomes) {
58
+ return outcomes;
59
+ }
60
+
61
+ /**
62
+ * A transient `gh` failure is skipped; `maxPolls` bounds a broken `gh`.
63
+ *
64
+ * @param {object} opts
65
+ * @param {string} opts.prUrl
66
+ * @param {string} opts.cwd
67
+ * @param {string|null} [opts.repo] `owner/repo` passed to `gh` as `--repo`.
68
+ * @param {object} opts.outcomes Initial `{ checkName: outcome }` map.
69
+ * @param {number} opts.polls Current poll counter.
70
+ * @param {number} opts.maxPolls Hard cap on total poll iterations.
71
+ * @param {Function} opts.ghPrChecksFn
72
+ * @param {number} opts.pollIntervalMs
73
+ * @param {Function} opts.sleepFn
74
+ * @param {Function} [opts.discountFn]
75
+ * @param {{ warn?: Function }} opts.logger
76
+ * @returns {Promise<{ outcomes: object, polls: number }>}
77
+ */
78
+ export async function pollUntilTerminal({
79
+ prUrl,
80
+ cwd,
81
+ repo = null,
82
+ outcomes,
83
+ polls,
84
+ maxPolls,
85
+ ghPrChecksFn,
86
+ pollIntervalMs,
87
+ sleepFn,
88
+ discountFn = identityDiscount,
89
+ logger,
90
+ }) {
91
+ let currentOutcomes = outcomes;
92
+ let currentPolls = polls;
93
+ while (!allTerminal(currentOutcomes) && currentPolls < maxPolls) {
94
+ await sleepFn(pollIntervalMs);
95
+ currentPolls += 1;
96
+ const probe = ghPrChecksFn({ prUrl, cwd, repo });
97
+ const entries = parseGhPrChecks(probe.stdout);
98
+ if (entries.length === 0 && probe.status !== 0 && probe.status !== 8) {
99
+ logger.warn?.(
100
+ `[Watcher] gh pr checks transient failure (status=${probe.status}): ${probe.stderr}`,
101
+ );
102
+ continue;
103
+ }
104
+ currentOutcomes = await discountFn(entries, reduceOutcomes(entries));
105
+ }
106
+ return { outcomes: currentOutcomes, polls: currentPolls };
107
+ }