mandrel 2.81.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.
- package/.agents/scripts/lib/audit-to-stories/parse-audit-md.js +49 -24
- package/.agents/scripts/lib/baselines/duplication-scanner.js +9 -5
- package/.agents/scripts/lib/bootstrap/manifest.js +128 -159
- package/.agents/scripts/lib/orchestration/git-cleanup/phases/cli.js +31 -27
- package/.agents/scripts/lib/orchestration/git-cleanup/phases/render.js +25 -21
- package/.agents/scripts/lib/orchestration/pr-watch-poll.js +107 -0
- package/.agents/scripts/lib/orchestration/pr-watch.js +168 -235
- package/.agents/scripts/lib/orchestration/reassert-status-column.js +102 -72
- package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +21 -3
- package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +44 -2
- package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +257 -0
- package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +341 -0
- package/.agents/scripts/lib/orchestration/ticketing.js +0 -9
- package/docs/CHANGELOG.md +19 -0
- package/package.json +1 -1
|
@@ -20,6 +20,94 @@ function defaultSleep(ms) {
|
|
|
20
20
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
function requirePositiveInt(value, name) {
|
|
24
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
25
|
+
throw new TypeError(
|
|
26
|
+
`reassertStatusColumn requires a positive integer ${name}`,
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function assertArgs({ provider, ticketId, pollAttempts }) {
|
|
32
|
+
if (!provider || typeof provider.getTicket !== 'function') {
|
|
33
|
+
throw new TypeError(
|
|
34
|
+
'reassertStatusColumn requires a provider with getTicket',
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
if (typeof provider.graphql !== 'function') {
|
|
38
|
+
throw new TypeError(
|
|
39
|
+
'reassertStatusColumn requires a provider with graphql (for ColumnSync)',
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
requirePositiveInt(ticketId, 'ticketId');
|
|
43
|
+
requirePositiveInt(pollAttempts, 'pollAttempts');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `undefined` on a transient read failure (logged), else the column. */
|
|
47
|
+
async function readColumnOrSkip(ctx, i) {
|
|
48
|
+
try {
|
|
49
|
+
return await ctx.sync.readCurrentColumn(ctx.ticketId);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
ctx.logger?.warn?.(
|
|
52
|
+
`[reassertStatusColumn] drift-check #${i} failed (transient): ${
|
|
53
|
+
err?.message ?? err
|
|
54
|
+
}. Continuing.`,
|
|
55
|
+
);
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The re-fire envelope, or `null` on a transient failure (logged). */
|
|
61
|
+
async function refire(ctx, i) {
|
|
62
|
+
try {
|
|
63
|
+
return await ctx.sync.sync(ctx.ticketId, ctx.labels);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
ctx.logger?.warn?.(
|
|
66
|
+
`[reassertStatusColumn] re-fire attempt ${i} failed (transient): ${
|
|
67
|
+
err?.message ?? err
|
|
68
|
+
}. Continuing.`,
|
|
69
|
+
);
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* One drift-check tick. Returns a terminal envelope to stop polling, or
|
|
76
|
+
* `null` to keep going; `state` carries `attempts` and the last envelope.
|
|
77
|
+
*/
|
|
78
|
+
async function pollTick(ctx, state, i) {
|
|
79
|
+
await ctx.sleepFn(ctx.pollDelayMs);
|
|
80
|
+
const current = await readColumnOrSkip(ctx, i);
|
|
81
|
+
if (current === undefined) return null;
|
|
82
|
+
if (current === ctx.targetColumn) return state.lastEnvelope;
|
|
83
|
+
ctx.logger?.info?.(
|
|
84
|
+
`[reassertStatusColumn] drift detected on attempt ${i} (current=${
|
|
85
|
+
current ?? '<null>'
|
|
86
|
+
} target=${ctx.targetColumn}); re-firing.`,
|
|
87
|
+
);
|
|
88
|
+
const next = await refire(ctx, i);
|
|
89
|
+
if (next === null) return null;
|
|
90
|
+
state.attempts += 1;
|
|
91
|
+
state.lastEnvelope = { ...next, attempts: state.attempts };
|
|
92
|
+
// A skip after a successful sync is unexpected: stop retrying.
|
|
93
|
+
return next.status === 'synced' ? null : state.lastEnvelope;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function finalVerdict(ctx, state) {
|
|
97
|
+
let final = null;
|
|
98
|
+
try {
|
|
99
|
+
final = await ctx.sync.readCurrentColumn(ctx.ticketId);
|
|
100
|
+
} catch {
|
|
101
|
+
// An unreadable column after the budget reads as drift.
|
|
102
|
+
}
|
|
103
|
+
if (final === ctx.targetColumn) return state.lastEnvelope;
|
|
104
|
+
return {
|
|
105
|
+
status: 'drifted',
|
|
106
|
+
column: ctx.targetColumn,
|
|
107
|
+
attempts: state.attempts,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
23
111
|
/**
|
|
24
112
|
* Re-assert one ticket's Status column. Returns `ColumnSync.sync`'s envelope
|
|
25
113
|
* plus `attempts`: `synced` (confirmed), `drifted` (budget exhausted, still
|
|
@@ -48,26 +136,7 @@ export async function reassertStatusColumn(args) {
|
|
|
48
136
|
sleepFn = defaultSleep,
|
|
49
137
|
config,
|
|
50
138
|
} = args ?? {};
|
|
51
|
-
|
|
52
|
-
throw new TypeError(
|
|
53
|
-
'reassertStatusColumn requires a provider with getTicket',
|
|
54
|
-
);
|
|
55
|
-
}
|
|
56
|
-
if (typeof provider.graphql !== 'function') {
|
|
57
|
-
throw new TypeError(
|
|
58
|
-
'reassertStatusColumn requires a provider with graphql (for ColumnSync)',
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
if (!Number.isInteger(ticketId) || ticketId <= 0) {
|
|
62
|
-
throw new TypeError(
|
|
63
|
-
'reassertStatusColumn requires a positive integer ticketId',
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
if (!Number.isInteger(pollAttempts) || pollAttempts <= 0) {
|
|
67
|
-
throw new TypeError(
|
|
68
|
-
'reassertStatusColumn requires a positive integer pollAttempts',
|
|
69
|
-
);
|
|
70
|
-
}
|
|
139
|
+
assertArgs({ provider, ticketId, pollAttempts });
|
|
71
140
|
|
|
72
141
|
const ticket = await provider.getTicket(ticketId);
|
|
73
142
|
const labels = Array.isArray(ticket?.labels) ? ticket.labels : [];
|
|
@@ -81,60 +150,21 @@ export async function reassertStatusColumn(args) {
|
|
|
81
150
|
if (initial.status !== 'synced') {
|
|
82
151
|
return initial;
|
|
83
152
|
}
|
|
84
|
-
|
|
85
|
-
|
|
153
|
+
const ctx = {
|
|
154
|
+
sync,
|
|
155
|
+
ticketId,
|
|
156
|
+
labels,
|
|
157
|
+
targetColumn,
|
|
158
|
+
logger,
|
|
159
|
+
sleepFn,
|
|
160
|
+
pollDelayMs,
|
|
161
|
+
};
|
|
162
|
+
const state = { attempts: 1, lastEnvelope: { ...initial, attempts: 1 } };
|
|
86
163
|
|
|
87
164
|
// Bounded so a hostile bot cannot stall the close path.
|
|
88
165
|
for (let i = 1; i < pollAttempts; i += 1) {
|
|
89
|
-
await
|
|
90
|
-
|
|
91
|
-
try {
|
|
92
|
-
current = await sync.readCurrentColumn(ticketId);
|
|
93
|
-
} catch (err) {
|
|
94
|
-
logger?.warn?.(
|
|
95
|
-
`[reassertStatusColumn] drift-check #${i} failed (transient): ${
|
|
96
|
-
err?.message ?? err
|
|
97
|
-
}. Continuing.`,
|
|
98
|
-
);
|
|
99
|
-
continue;
|
|
100
|
-
}
|
|
101
|
-
if (current === targetColumn) {
|
|
102
|
-
return lastEnvelope;
|
|
103
|
-
}
|
|
104
|
-
logger?.info?.(
|
|
105
|
-
`[reassertStatusColumn] drift detected on attempt ${i} (current=${
|
|
106
|
-
current ?? '<null>'
|
|
107
|
-
} target=${targetColumn}); re-firing.`,
|
|
108
|
-
);
|
|
109
|
-
try {
|
|
110
|
-
const next = await sync.sync(ticketId, labels);
|
|
111
|
-
attempts += 1;
|
|
112
|
-
// A skip after a successful sync is unexpected: stop retrying.
|
|
113
|
-
if (next.status !== 'synced') {
|
|
114
|
-
return { ...next, attempts };
|
|
115
|
-
}
|
|
116
|
-
lastEnvelope = { ...next, attempts };
|
|
117
|
-
} catch (err) {
|
|
118
|
-
logger?.warn?.(
|
|
119
|
-
`[reassertStatusColumn] re-fire attempt ${i} failed (transient): ${
|
|
120
|
-
err?.message ?? err
|
|
121
|
-
}. Continuing.`,
|
|
122
|
-
);
|
|
123
|
-
}
|
|
166
|
+
const done = await pollTick(ctx, state, i);
|
|
167
|
+
if (done) return done;
|
|
124
168
|
}
|
|
125
|
-
|
|
126
|
-
let final;
|
|
127
|
-
try {
|
|
128
|
-
final = await sync.readCurrentColumn(ticketId);
|
|
129
|
-
} catch {
|
|
130
|
-
final = null;
|
|
131
|
-
}
|
|
132
|
-
if (final === targetColumn) {
|
|
133
|
-
return lastEnvelope;
|
|
134
|
-
}
|
|
135
|
-
return {
|
|
136
|
-
status: 'drifted',
|
|
137
|
-
column: targetColumn,
|
|
138
|
-
attempts,
|
|
139
|
-
};
|
|
169
|
+
return finalVerdict(ctx, state);
|
|
140
170
|
}
|
|
@@ -146,7 +146,10 @@ async function stepWorktreeReap({
|
|
|
146
146
|
};
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
/**
|
|
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
|
|
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
|
|
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,
|
|
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
|
|
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,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
|
+
}
|