mandrel 2.81.0 → 2.83.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 (33) hide show
  1. package/.agents/docs/configuration.md +4 -3
  2. package/.agents/schemas/agentrc.schema.json +1 -1
  3. package/.agents/scripts/coverage-capture.js +55 -24
  4. package/.agents/scripts/evidence-gate.js +7 -1
  5. package/.agents/scripts/lib/audit-to-stories/parse-audit-md.js +49 -24
  6. package/.agents/scripts/lib/baselines/duplication-scanner.js +35 -7
  7. package/.agents/scripts/lib/bootstrap/manifest.js +128 -159
  8. package/.agents/scripts/lib/close-lock-events.js +109 -0
  9. package/.agents/scripts/lib/close-validation/commands.js +12 -0
  10. package/.agents/scripts/lib/close-validation/gates.js +6 -0
  11. package/.agents/scripts/lib/close-validation/process.js +5 -2
  12. package/.agents/scripts/lib/close-validation/runner.js +14 -4
  13. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  14. package/.agents/scripts/lib/full-suite-lock.js +20 -0
  15. package/.agents/scripts/lib/full-suite-queue.js +24 -56
  16. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  17. package/.agents/scripts/lib/orchestration/git-cleanup/phases/cli.js +31 -27
  18. package/.agents/scripts/lib/orchestration/git-cleanup/phases/render.js +25 -21
  19. package/.agents/scripts/lib/orchestration/pr-watch-poll.js +107 -0
  20. package/.agents/scripts/lib/orchestration/pr-watch.js +168 -235
  21. package/.agents/scripts/lib/orchestration/reassert-status-column.js +102 -72
  22. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +73 -63
  23. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +21 -3
  24. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +44 -2
  25. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +63 -0
  26. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +3 -0
  27. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +257 -0
  28. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +341 -0
  29. package/.agents/scripts/lib/orchestration/ticketing.js +0 -9
  30. package/.agents/scripts/lib/supervised-suite.js +8 -28
  31. package/README.md +167 -216
  32. package/docs/CHANGELOG.md +29 -0
  33. package/package.json +1 -1
@@ -6,13 +6,16 @@
6
6
  * replays its tail inline. Full-suite lock-wait lines are also teed to
7
7
  * `progress()` so a long wait doesn't read as a hang, and an expired wait
8
8
  * defers to `pending` rather than failing.
9
+ * `lockWait` / `suiteTimings` come from the lock-event channel, never output.
9
10
  */
10
11
 
12
+ import {
13
+ createLockEventChannel as defaultCreateLockEventChannel,
14
+ summarizeLockEvents,
15
+ } from '../../../close-lock-events.js';
11
16
  import { buildDefaultGates as defaultBuildDefaultGates } from '../../../close-validation/gates.js';
12
17
  import { runCloseValidation as defaultRunCloseValidation } from '../../../close-validation/runner.js';
13
18
  import { LOCK_WAIT_EXPIRED_EXIT_CODE } from '../../../full-suite-lock.js';
14
- import { parseLockWaitOutcome } from '../../../full-suite-queue.js';
15
- import { parseSuiteTimings } from '../../../supervised-suite.js';
16
19
  import { createGateLogSink as defaultCreateGateLogSink } from '../gate-log.js';
17
20
  import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
18
21
 
@@ -36,6 +39,7 @@ import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
36
39
  * runBaselineUpwardWriteback?: Function,
37
40
  * runContextBudgetWriteback?: Function,
38
41
  * createGateLogSink?: typeof defaultCreateGateLogSink,
42
+ * createLockEventChannel?: typeof defaultCreateLockEventChannel,
39
43
  * onPreGateStepsDone?: () => void,
40
44
  * }} args
41
45
  * @returns {Promise<{
@@ -61,29 +65,28 @@ export async function runCloseValidationPhase({
61
65
  runBaselineUpwardWriteback,
62
66
  runContextBudgetWriteback,
63
67
  createGateLogSink = defaultCreateGateLogSink,
68
+ createLockEventChannel = defaultCreateLockEventChannel,
64
69
  onPreGateStepsDone,
65
70
  }) {
66
- await runPreGateSteps({
67
- cwd,
68
- worktreePath,
69
- storyId,
70
- baseBranch,
71
- storyBranch,
72
- config,
73
- progress,
74
- runScopedFormatAutofix,
75
- runBaselineUpwardWriteback,
76
- runContextBudgetWriteback,
71
+ await prepareTree({
72
+ runPreGateSteps,
73
+ onPreGateStepsDone,
74
+ stepArgs: {
75
+ cwd,
76
+ worktreePath,
77
+ storyId,
78
+ baseBranch,
79
+ storyBranch,
80
+ config,
81
+ progress,
82
+ runScopedFormatAutofix,
83
+ runBaselineUpwardWriteback,
84
+ runContextBudgetWriteback,
85
+ },
77
86
  });
78
- onPreGateStepsDone?.();
79
-
80
- progress(
81
- 'VALIDATE',
82
- `Running close-validation gates against baseline ${baseBranch}${worktreePath ? ` in ${worktreePath}` : ''}...`,
83
- );
84
87
  // One sink for both `log` seams so nothing routes around the artifact.
85
88
  const gateLog = createGateLogSink({ storyId, config });
86
- const lockWaits = trackLockWaits({ sink: gateLog.log, progress });
89
+ const lockEvents = createLockEventChannel();
87
90
  const gateList = buildDefaultGates({
88
91
  config,
89
92
  baseBranch,
@@ -92,13 +95,15 @@ export async function runCloseValidationPhase({
92
95
  storyId,
93
96
  evidenceCwd: cwd,
94
97
  });
95
- let validation;
96
- try {
97
- validation = await runCloseValidation({
98
+ const { validation, lockWait, suiteTimings } = await runGateChain({
99
+ runCloseValidation,
100
+ gateLog,
101
+ lockEvents,
102
+ progress,
103
+ validationArgs: {
98
104
  cwd,
99
105
  worktreePath,
100
106
  gates: gateList,
101
- log: lockWaits.log,
102
107
  storyId,
103
108
  // Anchors the evidence cache on the Story id, so a re-close at an
104
109
  // unchanged HEAD skips already-passed gates.
@@ -107,13 +112,8 @@ export async function runCloseValidationPhase({
107
112
  baseBranch,
108
113
  storyBranch,
109
114
  config,
110
- });
111
- } finally {
112
- // The sink is async-buffered; settle it before anything reads it, on
113
- // the throw path too.
114
- await gateLog.flush();
115
- }
116
- const lockWait = lockWaits.summary();
115
+ },
116
+ });
117
117
  if (!validation.ok) {
118
118
  return settleFailedValidation({ validation, lockWait, gateLog, progress });
119
119
  }
@@ -121,11 +121,46 @@ export async function runCloseValidationPhase({
121
121
  return {
122
122
  gates: gateOutcomes(gateList, validation),
123
123
  lockWait,
124
- suiteTimings: lockWaits.suiteTimings(),
124
+ suiteTimings,
125
125
  pending: false,
126
126
  };
127
127
  }
128
128
 
129
+ async function prepareTree({ runPreGateSteps, onPreGateStepsDone, stepArgs }) {
130
+ await runPreGateSteps(stepArgs);
131
+ onPreGateStepsDone?.();
132
+ const { baseBranch, worktreePath, progress } = stepArgs;
133
+ progress(
134
+ 'VALIDATE',
135
+ `Running close-validation gates against baseline ${baseBranch}${worktreePath ? ` in ${worktreePath}` : ''}...`,
136
+ );
137
+ }
138
+
139
+ async function runGateChain({
140
+ runCloseValidation,
141
+ gateLog,
142
+ lockEvents,
143
+ progress,
144
+ validationArgs,
145
+ }) {
146
+ let validation;
147
+ let events;
148
+ try {
149
+ validation = await runCloseValidation({
150
+ ...validationArgs,
151
+ log: teeLockLines({ sink: gateLog.log, progress }),
152
+ lockEvents,
153
+ });
154
+ } finally {
155
+ // The sink is async-buffered; settle it before anything reads it, on
156
+ // the throw path too.
157
+ await gateLog.flush();
158
+ events = lockEvents.read();
159
+ lockEvents.dispose();
160
+ }
161
+ return { validation, ...summarizeLockEvents(events) };
162
+ }
163
+
129
164
  /**
130
165
  * Deferred on an expired lock wait → `pending`; otherwise throws.
131
166
  *
@@ -157,40 +192,15 @@ function settleFailedValidation({ validation, lockWait, gateLog, progress }) {
157
192
  }
158
193
 
159
194
  /**
160
- * Parsed from the gate log: the one place that sees waits and timings both
161
- * in-process and in gate children.
195
+ * Display only: no figure is read back from these lines.
162
196
  *
163
197
  * @param {{ sink: (m: string) => void, progress: (tag: string, msg: string) => void }} args
164
- * @returns {{ log: (m: string) => void, summary: () => { waitedSeconds: number, expired: boolean, holder?: object }|null, suiteTimings: () => object|null }}
165
- */
166
- function trackLockWaits({ sink, progress }) {
167
- let tally = null;
168
- let timings = null;
169
- return {
170
- log(line) {
171
- sink(line);
172
- timings = parseSuiteTimings(line) ?? timings;
173
- if (!String(line).includes('[full-suite-lock]')) return;
174
- progress('LOCK', line);
175
- const outcome = parseLockWaitOutcome(line);
176
- if (!outcome) return;
177
- tally = mergeLockWait(tally, outcome);
178
- },
179
- summary: () => tally,
180
- suiteTimings: () => timings,
181
- };
182
- }
183
-
184
- /**
185
- * @param {{ waitedSeconds: number, expired: boolean, holder?: object }|null} tally
186
- * @param {{ waitedSeconds: number, expired: boolean, holder?: object }} outcome
198
+ * @returns {(line: string) => void}
187
199
  */
188
- function mergeLockWait(tally, outcome) {
189
- const holder = outcome.holder ?? tally?.holder;
190
- return {
191
- waitedSeconds: (tally?.waitedSeconds ?? 0) + outcome.waitedSeconds,
192
- expired: Boolean(tally?.expired) || outcome.expired,
193
- ...(holder ? { holder } : {}),
200
+ function teeLockLines({ sink, progress }) {
201
+ return (line) => {
202
+ sink(line);
203
+ if (String(line).includes('[full-suite-lock]')) progress('LOCK', line);
194
204
  };
195
205
  }
196
206
 
@@ -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
  }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * phases/reconcile-done.js — a Story closed as completed can still carry a
3
+ * stale lifecycle label: a close that blocked before auto-merge landed its
4
+ * PR leaves `agent::blocked` on the closed issue, and the re-run takes the
5
+ * already-closed early return. With merge evidence on the Story branch, this
6
+ * finishes the flip through the shared `agent::done` confirm. Best-effort —
7
+ * the land already happened, so nothing here may change the `landed`
8
+ * terminal; every failure is logged and swallowed.
9
+ */
10
+
11
+ import { gh as defaultGh } from '../../../gh-exec.js';
12
+ import { Logger } from '../../../Logger.js';
13
+ import { confirmStoryMerged } from '../../../single-story/confirm-merge.js';
14
+ import { STATE_LABELS } from '../../ticketing.js';
15
+ import { parsePrNumber } from './code-review.js';
16
+ import { pickHeadPullRequest } from './pull-request.js';
17
+
18
+ /** Close reasons meaning nothing merged — no label is owed. */
19
+ const UNLANDED_CLOSE_REASONS = new Set(['not_planned', 'duplicate']);
20
+
21
+ /**
22
+ * @param {{ storyId: number, storyBranch: string, options: { cwd: string },
23
+ * story: { labels?: string[], stateReason?: string|null } }} ctx
24
+ * @param {{ provider: object, config: object, gh?: object,
25
+ * notify?: Function, sleep?: Function }} deps
26
+ * @param {(tag: string, msg: string) => void} progress
27
+ * @returns {Promise<void>}
28
+ */
29
+ export async function reconcileDoneLabel(ctx, deps, progress) {
30
+ const { storyId, story, storyBranch } = ctx;
31
+ if (UNLANDED_CLOSE_REASONS.has(story.stateReason)) return;
32
+ if (story.labels?.includes(STATE_LABELS.DONE)) return;
33
+ try {
34
+ const rows = await (deps.gh ?? defaultGh).pr.list(
35
+ ['--head', storyBranch, '--state', 'all'],
36
+ ['url', 'state', 'mergedAt'],
37
+ );
38
+ const head = pickHeadPullRequest(rows);
39
+ if (head?.state !== 'MERGED') {
40
+ progress(
41
+ 'NOOP',
42
+ `No merged PR on ${storyBranch} — leaving Story #${storyId}'s labels as they are.`,
43
+ );
44
+ return;
45
+ }
46
+ await confirmStoryMerged({
47
+ provider: deps.provider,
48
+ storyId,
49
+ prNumber: parsePrNumber(head.url),
50
+ prUrl: head.url,
51
+ cwd: ctx.options.cwd,
52
+ config: deps.config,
53
+ progress,
54
+ injectedNotify: deps.notify,
55
+ prState: { state: 'MERGED', mergedAt: null },
56
+ sleepFn: deps.sleep,
57
+ });
58
+ } catch (err) {
59
+ Logger.warn(
60
+ `[single-story-close] ⚠️ Could not reconcile Story #${storyId} to agent::done: ${err?.message ?? err}`,
61
+ );
62
+ }
63
+ }
@@ -47,6 +47,7 @@ import {
47
47
  pickHeadPullRequest,
48
48
  } from './phases/pull-request.js';
49
49
  import { pushStoryBranch } from './phases/push.js';
50
+ import { reconcileDoneLabel } from './phases/reconcile-done.js';
50
51
  import { handleCriticalReviewBlock } from './phases/review-block.js';
51
52
  import { handleOverriddenReviewBlock } from './phases/review-override.js';
52
53
  import {
@@ -588,6 +589,7 @@ function resolveCloseDeps(options, injected) {
588
589
  gitSpawn: injected.injectedGitSpawn,
589
590
  releaseLease: injected.injectedReleaseLease ?? releaseStoryLease,
590
591
  graphqlProbe: injected.injectedGraphqlProbe,
592
+ sleep: injected.injectedSleep,
591
593
  };
592
594
  }
593
595
 
@@ -934,6 +936,7 @@ async function loadStoryPhase(ctx, deps) {
934
936
  progress('INIT', `Closing standalone Story #${ctx.storyId}...`);
935
937
  ctx.story = await deps.provider.getTicket(ctx.storyId);
936
938
  if (ctx.story.state !== 'closed') return null;
939
+ await reconcileDoneLabel(ctx, deps, progress);
937
940
  return await alreadyClosedResult(
938
941
  ctx.storyId,
939
942
  ctx.story.stateReason,
@@ -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
+ }