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
@@ -278,6 +278,9 @@ export async function readNativeBlockedBy({
278
278
  * @param {Map<number, number[]>} nativeEdges
279
279
  * @param {number[]} foreignDone Ids outside the set already satisfied.
280
280
  * @param {(msg: string) => void} [warn]
281
+ * @param {Map<number, number>} [priorBlocksById] Local prior-block count per
282
+ * Story; absent counts 0.
283
+ * @param {boolean} [roleScopedAgents] `delivery.routing.roleScopedAgents`.
281
284
  * @returns {{ kind: string, stories: object[], dag: object[], done: number[] }}
282
285
  */
283
286
  export function buildStoriesEnvelope({
@@ -285,13 +288,16 @@ export function buildStoriesEnvelope({
285
288
  nativeEdges = new Map(),
286
289
  foreignDone = [],
287
290
  warn,
291
+ priorBlocksById = new Map(),
292
+ roleScopedAgents = false,
288
293
  }) {
289
294
  const sorted = [...stories].sort((a, b) => a.id - b.id);
290
295
  const inSetDone = sorted.filter(isSatisfiedBlocker).map((s) => s.id);
291
296
  return {
292
297
  kind: 'stories',
293
298
  // `inline` (the router's own session) only for a single-Story set, so no
294
- // sibling can claim that session. Decided on the resolved set size, not
299
+ // sibling can claim that session — unless a one-Story resume needs a
300
+ // spawn for its per-call effort. Decided on the resolved set size, not
295
301
  // the undelivered remainder, so the mode never changes mid-run.
296
302
  stories: sorted.map(({ id, title, url, labels, state }) => ({
297
303
  id,
@@ -299,8 +305,11 @@ export function buildStoriesEnvelope({
299
305
  url,
300
306
  labels,
301
307
  state,
302
- dispatchMode: resolveStoryDispatchMode({ storyCount: sorted.length })
303
- .mode,
308
+ dispatchMode: resolveStoryDispatchMode({
309
+ storyCount: sorted.length,
310
+ priorBlocks: priorBlocksById.get(id) ?? 0,
311
+ roleScopedAgents,
312
+ }).mode,
304
313
  })),
305
314
  dag: storiesToDag(sorted, nativeEdges, warn),
306
315
  done: [...new Set([...inSetDone, ...foreignDone])].sort((a, b) => a - b),
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Per-call story-worker effort for a resumed blocked Story, from its local
3
+ * signals only.
4
+ *
5
+ * @module lib/orchestration/resume-effort
6
+ */
7
+
8
+ import { getDeliveryRouting } from '../config/delivery-routing.js';
9
+ import { Logger } from '../Logger.js';
10
+ import { RUNTIME_FRICTION_CATEGORIES } from '../observability/runtime-friction.js';
11
+ import { forEachLine } from '../observability/signals-writer.js';
12
+ import { EVENT_KINDS } from '../signals/schema.js';
13
+
14
+ const AGENT_EFFORT_LEVELS = Object.freeze([
15
+ 'low',
16
+ 'medium',
17
+ 'high',
18
+ 'xhigh',
19
+ 'max',
20
+ ]);
21
+
22
+ /**
23
+ * @param {unknown} value
24
+ * @returns {{ effort: string|null, warning: string|null }}
25
+ */
26
+ export function parseWorkerEffort(value) {
27
+ if (value == null) return { effort: null, warning: null };
28
+ const raw = String(value).trim();
29
+ if (AGENT_EFFORT_LEVELS.includes(raw)) {
30
+ return { effort: raw, warning: null };
31
+ }
32
+ return {
33
+ effort: null,
34
+ warning: `--worker-effort must be one of ${AGENT_EFFORT_LEVELS.join('|')} (got ${JSON.stringify(value)}); telemetry.workerEffort records null.`,
35
+ };
36
+ }
37
+
38
+ /**
39
+ * @param {unknown} record
40
+ * @returns {boolean}
41
+ */
42
+ function isPriorBlockRecord(record) {
43
+ return (
44
+ record !== null &&
45
+ typeof record === 'object' &&
46
+ record.kind === EVENT_KINDS.FRICTION &&
47
+ record.category === RUNTIME_FRICTION_CATEGORIES.STORY_BLOCKED &&
48
+ record.details?.recovered !== true
49
+ );
50
+ }
51
+
52
+ /**
53
+ * The ladder's single source; absolute, not relative to session effort.
54
+ *
55
+ * @param {number} priorBlocks
56
+ * @returns {'high'|'xhigh'|null}
57
+ */
58
+ function resumeEffortFor(priorBlocks) {
59
+ if (priorBlocks < 1) return null;
60
+ return priorBlocks === 1 ? 'high' : 'xhigh';
61
+ }
62
+
63
+ /**
64
+ * @param {number} storyId
65
+ * @param {{ config?: object, readFn?: typeof forEachLine }} [opts]
66
+ * @returns {Promise<number>}
67
+ */
68
+ async function countPriorBlocks(
69
+ storyId,
70
+ { config, readFn = forEachLine } = {},
71
+ ) {
72
+ let count = 0;
73
+ try {
74
+ await readFn(
75
+ null,
76
+ storyId,
77
+ (record) => {
78
+ if (isPriorBlockRecord(record)) count += 1;
79
+ },
80
+ config,
81
+ );
82
+ } catch (err) {
83
+ Logger.warn(
84
+ `[resume-effort] signal read failed for Story #${storyId}: ${
85
+ err instanceof Error ? err.message : String(err)
86
+ } — counting 0 prior blocks.`,
87
+ );
88
+ return 0;
89
+ }
90
+ return count;
91
+ }
92
+
93
+ /**
94
+ * @param {number} storyId
95
+ * @param {{ config?: object, readFn?: typeof forEachLine }} [opts]
96
+ * @returns {Promise<'high'|'xhigh'|null>}
97
+ */
98
+ export async function resolveResumeEffort(storyId, opts) {
99
+ return resumeEffortFor(await countPriorBlocks(storyId, opts));
100
+ }
101
+
102
+ /**
103
+ * @param {Array<{ id: number }>} stories
104
+ * @param {{ config?: object, countFn?: typeof countPriorBlocks }} [opts]
105
+ * @returns {Promise<{ priorBlocksById: Map<number, number>,
106
+ * roleScopedAgents: boolean }>}
107
+ */
108
+ export async function resolveRunDispatchInputs(
109
+ stories,
110
+ { config, countFn = countPriorBlocks } = {},
111
+ ) {
112
+ const priorBlocksById = new Map();
113
+ if (stories.length === 1) {
114
+ const [{ id }] = stories;
115
+ priorBlocksById.set(id, await countFn(id, { config }));
116
+ }
117
+ return {
118
+ priorBlocksById,
119
+ roleScopedAgents: getDeliveryRouting(config).roleScopedAgents,
120
+ };
121
+ }
@@ -126,11 +126,20 @@ function workerFlags(tokensParam, modelParam, parsed) {
126
126
  };
127
127
  }
128
128
 
129
+ /**
130
+ * @param {unknown} effortParam
131
+ * @param {{ workerEffort?: unknown }} parsed
132
+ * @returns {unknown}
133
+ */
134
+ function workerEffortFlag(effortParam, parsed) {
135
+ return resolveFlag(effortParam, parsed.workerEffort);
136
+ }
137
+
129
138
  /**
130
139
  * Returns raw wait-for-merge intent; the runner resolves it after the arm.
131
140
  *
132
- * @param {{ storyIdParam, cwdParam, skipValidationParam, skipSyncParam, noAutoMergeParam, waitForMergeParam, noWaitForMergeParam, maxWaitSecondsParam, mergeWatchModeParam, rerunAdvisoryParam, overrideReviewBlockParam, workerTokensParam, workerModelParam }} raw
133
- * @returns {{ storyId, cwd, skipValidation, skipSync, noAutoMerge, waitForMergeExplicit, noWaitForMerge, maxWaitSeconds, mergeWatchMode, rerunAdvisory, overrideReviewBlock, workerTokens, workerModel }}
141
+ * @param {{ storyIdParam, cwdParam, skipValidationParam, skipSyncParam, noAutoMergeParam, waitForMergeParam, noWaitForMergeParam, maxWaitSecondsParam, mergeWatchModeParam, rerunAdvisoryParam, overrideReviewBlockParam, workerTokensParam, workerModelParam, workerEffortParam }} raw
142
+ * @returns {{ storyId, cwd, skipValidation, skipSync, noAutoMerge, waitForMergeExplicit, noWaitForMerge, maxWaitSeconds, mergeWatchMode, rerunAdvisory, overrideReviewBlock, workerTokens, workerModel, workerEffort }}
134
143
  */
135
144
  export function parseCloseOptions({
136
145
  storyIdParam,
@@ -146,6 +155,7 @@ export function parseCloseOptions({
146
155
  overrideReviewBlockParam,
147
156
  workerTokensParam,
148
157
  workerModelParam,
158
+ workerEffortParam,
149
159
  }) {
150
160
  // An injecting caller never reads argv (the host's flags are not its
151
161
  // business), so `parsed` stays empty and the retired-flag guard is skipped.
@@ -187,5 +197,6 @@ export function parseCloseOptions({
187
197
  resolveFlag(overrideReviewBlockParam, parsed.overrideReviewBlock),
188
198
  ),
189
199
  ...workerFlags(workerTokensParam, workerModelParam, parsed),
200
+ workerEffort: workerEffortFlag(workerEffortParam, parsed),
190
201
  };
191
202
  }
@@ -146,7 +146,10 @@ async function stepWorktreeReap({
146
146
  };
147
147
  }
148
148
 
149
- /** Reap the local `story-<id>` ref; already absent is success. */
149
+ /**
150
+ * Reap the local `story-<id>` ref, then its tracking ref; already absent is
151
+ * success.
152
+ */
150
153
  async function stepRefCleanup({ cwd, storyBranch, progress, gitSpawnFn }) {
151
154
  const exists = gitSpawnFn(
152
155
  cwd,
@@ -157,14 +160,29 @@ async function stepRefCleanup({ cwd, storyBranch, progress, gitSpawnFn }) {
157
160
  );
158
161
  if (exists.status !== 0) {
159
162
  progress?.('POST-LAND', `⏭ local ${storyBranch} already absent.`);
160
- return { ok: true, detail: null };
163
+ return reapTrackingRef(cwd, storyBranch, gitSpawnFn);
161
164
  }
162
165
  const del = gitSpawnFn(cwd, 'branch', '-D', storyBranch);
163
166
  if (del.status !== 0) {
164
167
  return { ok: false, detail: `git branch -D failed: ${del.stderr ?? ''}` };
165
168
  }
166
169
  progress?.('POST-LAND', `🧹 reaped local ${storyBranch}.`);
167
- return { ok: true, detail: null };
170
+ return reapTrackingRef(cwd, storyBranch, gitSpawnFn);
171
+ }
172
+
173
+ /**
174
+ * Drop `origin/<storyBranch>`: GitHub's branch auto-delete never touches a
175
+ * clone's tracking ref, so without this every delivered Story leaves one
176
+ * behind until a `fetch --prune`. Absent is success (`update-ref -d` exits 0).
177
+ */
178
+ function reapTrackingRef(cwd, storyBranch, gitSpawnFn) {
179
+ const ref = `refs/remotes/origin/${storyBranch}`;
180
+ const del = gitSpawnFn(cwd, 'update-ref', '-d', ref);
181
+ if (del.status === 0) return { ok: true, detail: null };
182
+ return {
183
+ ok: false,
184
+ detail: `git update-ref -d ${ref} failed: ${del.stderr ?? ''}`,
185
+ };
168
186
  }
169
187
 
170
188
  /**
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * phases/pre-gate-steps.js — self-heal steps run on the Story branch before
3
3
  * the gates: scoped format-autofix, the upward maintainability baseline
4
- * write-back, and the context-budget write-back. Each may commit on
4
+ * write-back, the context-budget write-back, the duplication re-score of the
5
+ * changed files (untagged, both directions), and the dead-export/cyclomatic
6
+ * shrink write-back. Each may commit on
5
7
  * `story-<id>` (so the gates score it) and none may ever fail the close — an
6
8
  * authoritative gate for each runs right after.
7
9
  */
@@ -9,7 +11,9 @@
9
11
  import { Logger } from '../../../Logger.js';
10
12
  import { runBaselineUpwardWriteback as defaultRunBaselineUpwardWriteback } from '../../story-close/baseline-upward-writeback.js';
11
13
  import { runContextBudgetWriteback as defaultRunContextBudgetWriteback } from '../../story-close/context-budget-writeback.js';
14
+ import { runDuplicationCloseRescore as defaultRunDuplicationCloseRescore } from '../../story-close/duplication-close-rescore.js';
12
15
  import { runScopedFormatAutofix as defaultRunScopedFormatAutofix } from '../../story-close/format-autofix.js';
16
+ import { runRatchetShrinkWriteback as defaultRunRatchetShrinkWriteback } from '../../story-close/ratchet-shrink-writeback.js';
13
17
 
14
18
  /**
15
19
  * @param {object} ctx the shared step context (see {@link runPreGateSteps})
@@ -47,7 +51,7 @@ function formatAutofixStep({
47
51
  }
48
52
 
49
53
  /**
50
- * Serves both write-backs, which share an input and result shape.
54
+ * Serves every write-back, which share an input and result shape.
51
55
  *
52
56
  * @param {object} ctx the shared step context (see {@link runPreGateSteps})
53
57
  * @param {{ tag: string, run: Function, describe: (w: object) => string, noun: string }} step
@@ -105,6 +109,8 @@ async function bestEffort({ tag, label, progress, run }) {
105
109
  * runScopedFormatAutofix?: typeof defaultRunScopedFormatAutofix,
106
110
  * runBaselineUpwardWriteback?: typeof defaultRunBaselineUpwardWriteback,
107
111
  * runContextBudgetWriteback?: typeof defaultRunContextBudgetWriteback,
112
+ * runDuplicationCloseRescore?: typeof defaultRunDuplicationCloseRescore,
113
+ * runRatchetShrinkWriteback?: typeof defaultRunRatchetShrinkWriteback,
108
114
  * }} args
109
115
  * @returns {Promise<void>}
110
116
  */
@@ -112,6 +118,8 @@ export async function runPreGateSteps({
112
118
  runScopedFormatAutofix = defaultRunScopedFormatAutofix,
113
119
  runBaselineUpwardWriteback = defaultRunBaselineUpwardWriteback,
114
120
  runContextBudgetWriteback = defaultRunContextBudgetWriteback,
121
+ runDuplicationCloseRescore = defaultRunDuplicationCloseRescore,
122
+ runRatchetShrinkWriteback = defaultRunRatchetShrinkWriteback,
115
123
  ...ctx
116
124
  }) {
117
125
  const { storyBranch, progress } = ctx;
@@ -122,6 +130,14 @@ export async function runPreGateSteps({
122
130
  'BUDGET',
123
131
  '⏭ Skipped context-budget write-back (no story branch).',
124
132
  );
133
+ progress(
134
+ 'DUPLICATION',
135
+ '⏭ Skipped duplication re-score (no story branch).',
136
+ );
137
+ progress(
138
+ 'RATCHET',
139
+ '⏭ Skipped ratchet shrink write-back (no story branch).',
140
+ );
125
141
  return;
126
142
  }
127
143
  await bestEffort({
@@ -156,4 +172,30 @@ export async function runPreGateSteps({
156
172
  `Wrote back lower context-budget totals (${w.tiers?.join(', ')})`,
157
173
  }),
158
174
  });
175
+ await bestEffort({
176
+ tag: 'DUPLICATION',
177
+ label: 'duplication re-score',
178
+ progress,
179
+ run: () =>
180
+ writebackStep(ctx, {
181
+ tag: 'DUPLICATION',
182
+ run: runDuplicationCloseRescore,
183
+ noun: 'duplication re-score commit',
184
+ describe: (w) =>
185
+ `Re-scored ${w.movedPaths?.length ?? 0} duplication row(s) (untagged)`,
186
+ }),
187
+ });
188
+ await bestEffort({
189
+ tag: 'RATCHET',
190
+ label: 'ratchet shrink write-back',
191
+ progress,
192
+ run: () =>
193
+ writebackStep(ctx, {
194
+ tag: 'RATCHET',
195
+ run: runRatchetShrinkWriteback,
196
+ noun: 'ratchet shrink write-back',
197
+ describe: (w) =>
198
+ `Dropped burnt-down rows from ${w.baselines?.join(', ')}`,
199
+ }),
200
+ });
159
201
  }
@@ -12,6 +12,7 @@ import { Logger } from '../../Logger.js';
12
12
  import {
13
13
  emitReviewBlockedFriction,
14
14
  recordCloseTelemetry,
15
+ resolveWorkerEffort,
15
16
  resolveWorkerModel,
16
17
  resolveWorkerTokens,
17
18
  } from '../../observability/close-telemetry.js';
@@ -104,7 +105,11 @@ function createPhaseTimer(nowMs = Date.now) {
104
105
  const UNTIMED = Object.freeze({ stamp() {} });
105
106
 
106
107
  /** No worker figures: an inline close, or an ending before they resolve. */
107
- const NO_WORKER = Object.freeze({ workerTokens: null, workerModel: null });
108
+ const NO_WORKER = Object.freeze({
109
+ workerTokens: null,
110
+ workerModel: null,
111
+ workerEffort: null,
112
+ });
108
113
 
109
114
  /**
110
115
  * The single terminal writer: the retry signal, the result summary (with its
@@ -600,6 +605,7 @@ export async function runSingleStoryClose({
600
605
  overrideReviewBlock: overrideReviewBlockParam,
601
606
  workerTokens: workerTokensParam,
602
607
  workerModel: workerModelParam,
608
+ workerEffort: workerEffortParam,
603
609
  ...injected
604
610
  } = {}) {
605
611
  const options = parseCloseOptions({
@@ -616,10 +622,11 @@ export async function runSingleStoryClose({
616
622
  overrideReviewBlockParam,
617
623
  workerTokensParam,
618
624
  workerModelParam,
625
+ workerEffortParam,
619
626
  });
620
627
  if (!options.storyId) {
621
628
  throw new Error(
622
- 'Usage: node single-story-close.js --story <STORY_ID> [--cwd <main-repo>] [--skip-validation] [--skip-sync] [--no-auto-merge] [--wait-merge|--no-wait-merge] [--max-wait-seconds <n>] [--merge-watch-mode <sync|async>] [--rerun-advisory <n>] [--override-review-block <reason>] [--worker-tokens <n>] [--worker-model <model>]',
629
+ 'Usage: node single-story-close.js --story <STORY_ID> [--cwd <main-repo>] [--skip-validation] [--skip-sync] [--no-auto-merge] [--wait-merge|--no-wait-merge] [--max-wait-seconds <n>] [--merge-watch-mode <sync|async>] [--rerun-advisory <n>] [--override-review-block <reason>] [--worker-tokens <n>] [--worker-model <model>] [--worker-effort <level>]',
623
630
  );
624
631
  }
625
632
 
@@ -1212,6 +1219,7 @@ async function runClosePipeline(run, deps) {
1212
1219
  worker: {
1213
1220
  workerTokens: resolveWorkerTokens(run.options.workerTokens),
1214
1221
  workerModel: resolveWorkerModel(run.options.workerModel),
1222
+ workerEffort: resolveWorkerEffort(run.options.workerEffort),
1215
1223
  },
1216
1224
  };
1217
1225
  for (const phase of CLOSE_PIPELINE) {
@@ -0,0 +1,257 @@
1
+ /**
2
+ * duplication-close-rescore.js — at close, re-score the duplication rows of
3
+ * the files the Story changed and commit any row that moved, either way.
4
+ *
5
+ * The commit is deliberately UNTAGGED (no `baseline-refresh:`): a tagged
6
+ * commit would acknowledge the very rise it exists to expose, so a Story that
7
+ * adds clones to a file it changed fails the head-vs-base compare at close.
8
+ * The scan covers the whole tree (clones are pairwise); only changed-file rows
9
+ * are written. Every failure is a named skip, never a failed close.
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ import {
16
+ refreshBaseline as defaultRefreshBaseline,
17
+ fileFilterFor,
18
+ readPriorEnvelope,
19
+ } from '../../baselines/refresh-service.js';
20
+ import { getBaselineEpsilon } from '../../config/quality.js';
21
+ import { getQuality } from '../../config-resolver.js';
22
+ import { gitSync as defaultGitSync } from '../../git-utils.js';
23
+ import { Logger as DefaultLogger } from '../../Logger.js';
24
+ import {
25
+ currentBranch,
26
+ listChangedFiles,
27
+ listDirtyPaths,
28
+ } from './format-autofix.js';
29
+
30
+ const TAG = '[duplication-rescore]';
31
+
32
+ const KIND = 'duplication';
33
+
34
+ const DEFAULT_BASELINE_REL_PATH = 'baselines/duplication.json';
35
+
36
+ /**
37
+ * Untagged on purpose (see the module header): never `baseline-refresh:`.
38
+ *
39
+ * @param {number|string} storyId
40
+ * @returns {string}
41
+ */
42
+ function buildCommitSubject(storyId) {
43
+ return `chore(baselines): re-score duplication rows for changed files (story #${storyId})`;
44
+ }
45
+
46
+ /**
47
+ * @param {Array<{ path: string, before: number|null, after: number|null }>} moved
48
+ * @returns {string}
49
+ */
50
+ function buildCommitBody(moved) {
51
+ const fmt = (v) => (v === null ? 'none' : `${v}%`);
52
+ return [
53
+ 'Duplication rows for files this branch changed, re-scored at close so',
54
+ 'the head-vs-base duplication compare scores the tree rather than a',
55
+ 'stale committed row. Untagged: a rise here is a gate failure, not an',
56
+ 'acknowledged refresh.',
57
+ '',
58
+ ...moved.map((m) => `- ${m.path}: ${fmt(m.before)} -> ${fmt(m.after)}`),
59
+ ].join('\n');
60
+ }
61
+
62
+ /**
63
+ * @param {object} logger
64
+ * @param {string} reason
65
+ */
66
+ function skip(logger, reason) {
67
+ logger.info?.(`${TAG} no re-score commit (${reason}).`);
68
+ return { ran: false, committed: false, reason };
69
+ }
70
+
71
+ /**
72
+ * Prefer `origin/<base>`: a stale local base widens the three-dot range.
73
+ *
74
+ * @param {{ workTree: string, git: Function, baseBranch: string }} ctx
75
+ * @returns {string}
76
+ */
77
+ function resolveScopeBase({ workTree, git, baseBranch }) {
78
+ try {
79
+ git(
80
+ ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${baseBranch}`],
81
+ { cwd: workTree },
82
+ );
83
+ return `origin/${baseBranch}`;
84
+ } catch {
85
+ return baseBranch;
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Guards plus the scoped file list. A dirty baseline file would otherwise be
91
+ * swept into the commit.
92
+ *
93
+ * @param {{ workTree: string, baseBranch: string, storyBranch: string, git: Function, relPath: string }} ctx
94
+ * @returns {{ reason: string } | { files: string[] }}
95
+ */
96
+ function resolveScope({ workTree, baseBranch, storyBranch, git, relPath }) {
97
+ if (currentBranch(workTree, git) !== storyBranch) {
98
+ return { reason: 'wrong-branch' };
99
+ }
100
+ if (listDirtyPaths(workTree, git).includes(relPath)) {
101
+ return { reason: 'dirty-tree' };
102
+ }
103
+ const isScorable = fileFilterFor(KIND);
104
+ const files = listChangedFiles({
105
+ cwd: workTree,
106
+ baseBranch: resolveScopeBase({ workTree, git, baseBranch }),
107
+ storyBranch,
108
+ git,
109
+ }).filter((f) => isScorable(f));
110
+ return files.length === 0 ? { reason: 'no-changed-files' } : { files };
111
+ }
112
+
113
+ /**
114
+ * Scoped rows whose percentage moved, appeared or vanished.
115
+ *
116
+ * @param {{ files: string[], priorRows: object[], nextRows: object[] }} args
117
+ * @returns {Array<{ path: string, before: number|null, after: number|null }>}
118
+ */
119
+ function diffScopedRows({ files, priorRows, nextRows }) {
120
+ const byPath = (rows) =>
121
+ new Map((rows ?? []).map((r) => [r?.path, r?.percentage ?? null]));
122
+ const before = byPath(priorRows);
123
+ const after = byPath(nextRows);
124
+ const moved = [];
125
+ for (const file of files) {
126
+ const b = before.get(file) ?? null;
127
+ const a = after.get(file) ?? null;
128
+ if (b !== a) moved.push({ path: file, before: b, after: a });
129
+ }
130
+ return moved;
131
+ }
132
+
133
+ /**
134
+ * Stage and commit with hooks enabled; on a rejected commit restore the file
135
+ * so the gates score the tree the close found.
136
+ *
137
+ * @param {{ workTree: string, git: Function, relPath: string, subject: string, body: string }} args
138
+ * @returns {string} the short sha
139
+ */
140
+ function commitBaseline({ workTree, git, relPath, subject, body }) {
141
+ git(['add', '--', relPath], { cwd: workTree });
142
+ try {
143
+ git(['commit', '-m', subject, '-m', body], { cwd: workTree });
144
+ } catch (err) {
145
+ git(['restore', '--staged', '--worktree', '--', relPath], {
146
+ cwd: workTree,
147
+ });
148
+ throw err;
149
+ }
150
+ return String(
151
+ git(['rev-parse', '--short', 'HEAD'], { cwd: workTree }) ?? '',
152
+ ).trim();
153
+ }
154
+
155
+ /**
156
+ * @param {() => Promise<object>|object} fn
157
+ * @param {string} label the skip-reason prefix on a throw
158
+ * @returns {Promise<{ value?: object, reason?: string }>}
159
+ */
160
+ async function attempt(fn, label) {
161
+ try {
162
+ return { value: await fn() };
163
+ } catch (err) {
164
+ return { reason: `${label}: ${err?.message ?? err}` };
165
+ }
166
+ }
167
+
168
+ /**
169
+ * @param {{
170
+ * cwd: string,
171
+ * worktreePath?: string|null,
172
+ * storyId: number|string,
173
+ * baseBranch: string,
174
+ * storyBranch?: string,
175
+ * config?: object,
176
+ * logger?: object,
177
+ * gitSync?: (cwd: string, ...args: string[]) => string,
178
+ * refreshBaseline?: typeof defaultRefreshBaseline,
179
+ * scorer?: (files: string[], opts: object) => Promise<object[]>|object[],
180
+ * }} opts
181
+ * @returns {Promise<{ ran: boolean, committed: boolean, sha?: string, movedPaths?: string[], reason?: string }>}
182
+ */
183
+ export async function runDuplicationCloseRescore({
184
+ cwd,
185
+ worktreePath,
186
+ storyId,
187
+ baseBranch,
188
+ storyBranch,
189
+ config,
190
+ logger = DefaultLogger,
191
+ gitSync = defaultGitSync,
192
+ refreshBaseline = defaultRefreshBaseline,
193
+ scorer,
194
+ } = {}) {
195
+ if (!cwd || !baseBranch || !storyBranch) {
196
+ return skip(logger, 'missing-context');
197
+ }
198
+ const workTree = worktreePath || cwd;
199
+ const git = (args, opts = {}) => gitSync(opts.cwd ?? workTree, ...args);
200
+
201
+ // The DECLARED `gates.duplication` block — `quality.duplication` is undefined.
202
+ const gate = await attempt(
203
+ () => getQuality(config)?.gates?.[KIND] ?? {},
204
+ 'config-failed',
205
+ );
206
+ if (gate.reason) return skip(logger, gate.reason);
207
+ if (gate.value.enabled === false) return skip(logger, 'gate-disabled');
208
+
209
+ const relPath = gate.value.baselinePath ?? DEFAULT_BASELINE_REL_PATH;
210
+ const writePath = path.resolve(workTree, relPath);
211
+ const scope = await attempt(
212
+ () => resolveScope({ workTree, baseBranch, storyBranch, git, relPath }),
213
+ 'git-failed',
214
+ );
215
+ if (scope.reason) return skip(logger, scope.reason);
216
+ if (scope.value.reason) return skip(logger, scope.value.reason);
217
+ const { files } = scope.value;
218
+
219
+ const priorRows = readPriorEnvelope(writePath, fs)?.rows ?? [];
220
+ const refreshed = await attempt(
221
+ () =>
222
+ refreshBaseline({
223
+ kind: KIND,
224
+ cwd: workTree,
225
+ writePath,
226
+ scopeFiles: files,
227
+ epsilon: getBaselineEpsilon(KIND),
228
+ ...(scorer ? { scorer } : {}),
229
+ }),
230
+ 'scorer-failed',
231
+ );
232
+ if (refreshed.reason) return skip(logger, refreshed.reason);
233
+ if (!refreshed.value?.wrote) return skip(logger, 'unchanged');
234
+
235
+ const moved = diffScopedRows({
236
+ files,
237
+ priorRows,
238
+ nextRows: refreshed.value.envelope?.rows,
239
+ });
240
+ const committed = await attempt(
241
+ () =>
242
+ commitBaseline({
243
+ workTree,
244
+ git,
245
+ relPath,
246
+ subject: buildCommitSubject(storyId),
247
+ body: buildCommitBody(moved),
248
+ }),
249
+ 'git-failed',
250
+ );
251
+ if (committed.reason) return skip(logger, committed.reason);
252
+ const movedPaths = moved.map((m) => m.path);
253
+ logger.warn?.(
254
+ `${TAG} re-scored ${movedPaths.length} duplication row(s) on story #${storyId}; committed as ${committed.value}.`,
255
+ );
256
+ return { ran: true, committed: true, sha: committed.value, movedPaths };
257
+ }