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
@@ -0,0 +1,341 @@
1
+ /**
2
+ * ratchet-shrink-writeback.js — at close, bank the burn-down of the dead-export
3
+ * (default and `--production`) and cyclomatic ratchets, whose checks exit 0 on
4
+ * removals so a burnt-down row would otherwise linger as slack.
5
+ *
6
+ * Shrink only: a baseline is rewritten only when its recomputed rows are a
7
+ * strict subset of (cyclomatic: no worse than) the committed rows, so a write
8
+ * never adds a row or raises a value. Rows come from each check's own
9
+ * machinery. One `baseline-refresh:` commit; every failure is a named skip.
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ import {
16
+ diffRows as defaultDiffDeadExportRows,
17
+ loadBaseline as loadJsonBaseline,
18
+ } from '../../../check-dead-exports.js';
19
+ import { getQuality } from '../../config-resolver.js';
20
+ import {
21
+ DEFAULT_CYCLOMATIC_BASELINE,
22
+ scanCyclomatic as defaultScanCyclomatic,
23
+ diffCyclomaticRows,
24
+ resolveCyclomaticPolicy,
25
+ } from '../../cyclomatic-ceiling.js';
26
+ import { resolveScanScope as defaultResolveScanScope } from '../../cyclomatic-scope.js';
27
+ import {
28
+ runKnip as defaultRunKnip,
29
+ extractRowsFromKnip,
30
+ } from '../../dead-exports-knip.js';
31
+ import { resolveDeadExportsMode } from '../../dead-exports-mode.js';
32
+ import { gitSync as defaultGitSync } from '../../git-utils.js';
33
+ import { Logger as DefaultLogger } from '../../Logger.js';
34
+ import { currentBranch, listDirtyPaths } from './format-autofix.js';
35
+
36
+ const TAG = '[ratchet-shrink]';
37
+
38
+ /**
39
+ * Carries the `baseline-refresh:` marker `refresh-ack.js` recognises.
40
+ *
41
+ * @param {number|string} storyId
42
+ * @returns {string}
43
+ */
44
+ function buildCommitSubject(storyId) {
45
+ return `chore(baselines): baseline-refresh: drop burnt-down ratchet rows (story #${storyId})`;
46
+ }
47
+
48
+ /**
49
+ * @param {Array<{ relPath: string, lines: string[] }>} shrinks
50
+ * @returns {string}
51
+ */
52
+ function buildCommitBody(shrinks) {
53
+ const out = [
54
+ 'Dead-export and cyclomatic rows this branch burnt down, banked so the',
55
+ 'ratchet stops holding slack the tree no longer spends. Additions and',
56
+ 'rises are never written here.',
57
+ ];
58
+ for (const s of shrinks) out.push('', `${s.relPath}:`, ...s.lines);
59
+ return out.join('\n');
60
+ }
61
+
62
+ /**
63
+ * @param {object} logger
64
+ * @param {string} reason
65
+ */
66
+ function skip(logger, reason) {
67
+ logger.info?.(`${TAG} no write-back (${reason}).`);
68
+ return { ran: false, committed: false, reason };
69
+ }
70
+
71
+ /**
72
+ * One dead-export mode: the shrunk envelope, or a skip reason.
73
+ *
74
+ * @param {{ workTree: string, production: boolean, runKnip: Function, diffRows: Function }} ctx
75
+ * @returns {{ relPath: string, envelope?: object, lines?: string[], reason?: string }}
76
+ */
77
+ function planDeadExportShrink({
78
+ workTree,
79
+ production,
80
+ runKnip = defaultRunKnip,
81
+ diffRows = defaultDiffDeadExportRows,
82
+ }) {
83
+ const { baseline } = resolveDeadExportsMode(production);
84
+ const relPath = baseline.split(path.sep).join('/');
85
+ const committed = loadJsonBaseline(path.join(workTree, baseline));
86
+ if (!Array.isArray(committed?.rows))
87
+ return { relPath, reason: 'no-baseline' };
88
+ const report = runKnip({ cwd: workTree, production });
89
+ // A failed or unrecognised report reads as "every row removed" — never shrink on it.
90
+ if (!report?.ok) return { relPath, reason: 'knip-failed' };
91
+ if (!Array.isArray(report.envelope?.issues)) {
92
+ return { relPath, reason: 'knip-report-unusable' };
93
+ }
94
+ const diff = diffRows(committed.rows, extractRowsFromKnip(report.envelope));
95
+ if (diff.added.length > 0) return { relPath, reason: 'not-a-shrink' };
96
+ if (diff.removed.length === 0) return { relPath, reason: 'no-shrink' };
97
+ const gone = new Set(diff.removed.map((r) => `${r.file}\0${r.symbol}`));
98
+ return {
99
+ relPath,
100
+ envelope: {
101
+ ...committed,
102
+ rows: committed.rows.filter((r) => !gone.has(`${r.file}\0${r.symbol}`)),
103
+ },
104
+ lines: diff.removed.map((r) => `- ${r.file}: ${r.symbol}`),
105
+ };
106
+ }
107
+
108
+ /**
109
+ * Lower each improved row to the measured values; never above the prior.
110
+ *
111
+ * @param {Array<object>} rows committed rows
112
+ * @param {{ removed: Array<object>, improved: Array<object> }} diff
113
+ * @returns {Array<object>}
114
+ */
115
+ function shrinkCyclomaticRows(rows, diff) {
116
+ const gone = new Set(diff.removed.map((r) => r.file));
117
+ const lowered = new Map(diff.improved.map((r) => [r.file, r]));
118
+ const out = [];
119
+ for (const row of rows) {
120
+ if (gone.has(row.file)) continue;
121
+ const cur = lowered.get(row.file);
122
+ out.push(
123
+ cur
124
+ ? {
125
+ ...row,
126
+ methodsAboveCeiling: Math.min(
127
+ row.methodsAboveCeiling,
128
+ cur.methodsAboveCeiling,
129
+ ),
130
+ maxCyclomatic: Math.min(row.maxCyclomatic, cur.maxCyclomatic),
131
+ }
132
+ : row,
133
+ );
134
+ }
135
+ return out;
136
+ }
137
+
138
+ /**
139
+ * The cyclomatic shrink: the lowered envelope, or a skip reason.
140
+ *
141
+ * @param {{ workTree: string, config: object, scanCyclomatic: Function, resolveScanScope: Function }} ctx
142
+ * @returns {{ relPath: string, envelope?: object, lines?: string[], reason?: string }}
143
+ */
144
+ function planCyclomaticShrink({
145
+ workTree,
146
+ config,
147
+ scanCyclomatic = defaultScanCyclomatic,
148
+ resolveScanScope = defaultResolveScanScope,
149
+ }) {
150
+ const relPath = DEFAULT_CYCLOMATIC_BASELINE;
151
+ const committed = loadJsonBaseline(path.join(workTree, relPath));
152
+ if (!Array.isArray(committed?.rows))
153
+ return { relPath, reason: 'no-baseline' };
154
+ const policy = resolveCyclomaticPolicy(getQuality(config));
155
+ if (committed.ceiling !== policy.mustFix) {
156
+ return { relPath, reason: 'ceiling-mismatch' };
157
+ }
158
+ const scan = scanCyclomatic({
159
+ targetDirs: policy.targetDirs,
160
+ ignoreGlobs: policy.ignoreGlobs,
161
+ ceiling: policy.mustFix,
162
+ cwd: workTree,
163
+ scopeFiles: resolveScanScope({
164
+ cwd: workTree,
165
+ config,
166
+ baselineRows: committed.rows,
167
+ }),
168
+ });
169
+ // An unparseable file yields no row, which would read as a burnt-down one.
170
+ if (scan.parseErrors > 0) return { relPath, reason: 'parse-errors' };
171
+ const diff = diffCyclomaticRows(committed.rows, scan.rows);
172
+ if (diff.added.length + diff.worsened.length > 0) {
173
+ return { relPath, reason: 'not-a-shrink' };
174
+ }
175
+ if (diff.removed.length + diff.improved.length === 0) {
176
+ return { relPath, reason: 'no-shrink' };
177
+ }
178
+ return {
179
+ relPath,
180
+ envelope: {
181
+ ...committed,
182
+ rows: shrinkCyclomaticRows(committed.rows, diff),
183
+ },
184
+ lines: [
185
+ ...diff.removed.map((r) => `- ${r.file}: removed`),
186
+ ...diff.improved.map(
187
+ (r) =>
188
+ `- ${r.file}: ${r.baselineCount}/${r.baselineMax} -> ${r.methodsAboveCeiling}/${r.maxCyclomatic}`,
189
+ ),
190
+ ],
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Run a planner; a throw becomes a named skip for that baseline only.
196
+ *
197
+ * @param {string} relPath
198
+ * @param {() => object} plan
199
+ * @returns {object}
200
+ */
201
+ function safePlan(relPath, plan) {
202
+ try {
203
+ return plan();
204
+ } catch (err) {
205
+ return { relPath, reason: `failed: ${err?.message ?? err}` };
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Write every shrunk envelope and fold them into one commit. On a rejected
211
+ * commit the files are restored so the gates score the tree the close found.
212
+ *
213
+ * @param {{ workTree: string, git: Function, shrinks: object[], storyId: number|string }} args
214
+ * @returns {string} the short sha
215
+ */
216
+ function commitShrinks({ workTree, git, shrinks, storyId }) {
217
+ const paths = shrinks.map((s) => s.relPath);
218
+ for (const s of shrinks) {
219
+ fs.writeFileSync(
220
+ path.join(workTree, s.relPath),
221
+ `${JSON.stringify(s.envelope, null, 2)}\n`,
222
+ );
223
+ }
224
+ git(['add', '--', ...paths], { cwd: workTree });
225
+ try {
226
+ git(
227
+ [
228
+ 'commit',
229
+ '-m',
230
+ buildCommitSubject(storyId),
231
+ '-m',
232
+ buildCommitBody(shrinks),
233
+ ],
234
+ { cwd: workTree },
235
+ );
236
+ } catch (err) {
237
+ git(['restore', '--staged', '--worktree', '--', ...paths], {
238
+ cwd: workTree,
239
+ });
240
+ throw err;
241
+ }
242
+ return String(
243
+ git(['rev-parse', '--short', 'HEAD'], { cwd: workTree }) ?? '',
244
+ ).trim();
245
+ }
246
+
247
+ /**
248
+ * Adapt `gitSync(cwd, ...args)` to the `(args, opts)` shape format-autofix uses.
249
+ *
250
+ * @param {(cwd: string, ...args: string[]) => string} gitSync
251
+ * @param {string} workTree
252
+ * @returns {(args: string[], opts?: { cwd?: string }) => string}
253
+ */
254
+ function bindGit(gitSync, workTree) {
255
+ return (args, opts = {}) => gitSync(opts.cwd ?? workTree, ...args);
256
+ }
257
+
258
+ /**
259
+ * @param {{
260
+ * cwd: string,
261
+ * worktreePath?: string|null,
262
+ * storyId: number|string,
263
+ * storyBranch?: string,
264
+ * config?: object,
265
+ * logger?: object,
266
+ * gitSync?: (cwd: string, ...args: string[]) => string,
267
+ * runKnip?: typeof defaultRunKnip,
268
+ * scanCyclomatic?: typeof defaultScanCyclomatic,
269
+ * resolveScanScope?: typeof defaultResolveScanScope,
270
+ * }} opts
271
+ * @returns {{ ran: boolean, committed: boolean, sha?: string, baselines?: string[], skipped?: Record<string, string>, reason?: string }}
272
+ */
273
+ export function runRatchetShrinkWriteback({
274
+ cwd,
275
+ worktreePath,
276
+ storyId,
277
+ storyBranch,
278
+ config,
279
+ logger = DefaultLogger,
280
+ gitSync = defaultGitSync,
281
+ runKnip = defaultRunKnip,
282
+ scanCyclomatic = defaultScanCyclomatic,
283
+ resolveScanScope = defaultResolveScanScope,
284
+ } = {}) {
285
+ if (!cwd || !storyBranch) return skip(logger, 'missing-context');
286
+ const workTree = worktreePath || cwd;
287
+ const git = bindGit(gitSync, workTree);
288
+ const relPaths = [
289
+ resolveDeadExportsMode(false).baseline,
290
+ resolveDeadExportsMode(true).baseline,
291
+ DEFAULT_CYCLOMATIC_BASELINE,
292
+ ].map((p) => p.split(path.sep).join('/'));
293
+ try {
294
+ if (currentBranch(workTree, git) !== storyBranch) {
295
+ return skip(logger, 'wrong-branch');
296
+ }
297
+ const dirty = listDirtyPaths(workTree, git);
298
+ if (relPaths.some((p) => dirty.includes(p))) {
299
+ return skip(logger, 'dirty-tree');
300
+ }
301
+ } catch (err) {
302
+ return skip(logger, `git-failed: ${err?.message ?? err}`);
303
+ }
304
+
305
+ const plans = [
306
+ safePlan(relPaths[0], () =>
307
+ planDeadExportShrink({ workTree, production: false, runKnip }),
308
+ ),
309
+ safePlan(relPaths[1], () =>
310
+ planDeadExportShrink({ workTree, production: true, runKnip }),
311
+ ),
312
+ safePlan(relPaths[2], () =>
313
+ planCyclomaticShrink({
314
+ workTree,
315
+ config,
316
+ scanCyclomatic,
317
+ resolveScanScope,
318
+ }),
319
+ ),
320
+ ];
321
+ const shrinks = plans.filter((p) => p.envelope);
322
+ const skipped = Object.fromEntries(
323
+ plans.filter((p) => p.reason).map((p) => [p.relPath, p.reason]),
324
+ );
325
+ if (shrinks.length === 0) {
326
+ const detail = Object.entries(skipped)
327
+ .map(([p, r]) => `${path.basename(p)}=${r}`)
328
+ .join(', ');
329
+ return { ...skip(logger, `no-shrink: ${detail}`), skipped };
330
+ }
331
+ try {
332
+ const sha = commitShrinks({ workTree, git, shrinks, storyId });
333
+ const baselines = shrinks.map((s) => s.relPath);
334
+ logger.warn?.(
335
+ `${TAG} dropped burnt-down rows from ${baselines.join(', ')} on story #${storyId}; committed as ${sha}.`,
336
+ );
337
+ return { ran: true, committed: true, sha, baselines, skipped };
338
+ } catch (err) {
339
+ return { ...skip(logger, `git-failed: ${err?.message ?? err}`), skipped };
340
+ }
341
+ }
@@ -6,24 +6,15 @@
6
6
  export {
7
7
  __resetParentCascadeLocks,
8
8
  __setCascadeRetryDelays,
9
- logCascadePartialFailures,
10
9
  } from './ticketing/bulk.js';
11
10
  export {
12
- _peekStructuredCommentCache,
13
11
  _resetStructuredCommentCache,
14
12
  assertValidStructuredCommentType,
15
- buildStorylessTicketSnapshot,
16
13
  findStructuredComment,
17
- isValidStructuredCommentType,
18
14
  STATE_LABELS,
19
- STRUCTURED_COMMENT_TYPES,
20
- structuredCommentMarker,
21
- WAVE_TYPE_PATTERN,
22
15
  } from './ticketing/reads.js';
23
16
  export {
24
17
  postStructuredComment,
25
- toggleTasklistCheckbox,
26
- transitionStoryDirect,
27
18
  transitionTicketState,
28
19
  upsertStructuredComment,
29
20
  } from './ticketing/state.js';
@@ -2,7 +2,7 @@
2
2
  * A full suite supervised as a process group. The suite may write
3
3
  * `$MANDREL_SUITE_READY_FILE` when its tests start; the kill timer then
4
4
  * re-arms a fresh `timeoutMs`, so a pre-test wait (bounded by `timeoutMs`
5
- * too) never spends the test budget. Close parses the timing line back.
5
+ * too) never spends the test budget.
6
6
  */
7
7
  import { spawn } from 'node:child_process';
8
8
  import crypto from 'node:crypto';
@@ -38,23 +38,6 @@ export function formatSuiteTimings({ lockWaitMs, hostWaitMs, testRunMs }) {
38
38
  return `⏲ suite timings: lockWaitMs=${Math.round(lockWaitMs)} hostWaitMs=${host} testRunMs=${Math.round(testRunMs)}`;
39
39
  }
40
40
 
41
- /**
42
- * @param {string} line
43
- * @returns {SuiteTimings|null}
44
- */
45
- export function parseSuiteTimings(line) {
46
- const match =
47
- /suite timings: lockWaitMs=(\d+) hostWaitMs=(\d+|n\/a) testRunMs=(\d+)/u.exec(
48
- String(line ?? ''),
49
- );
50
- if (!match) return null;
51
- return {
52
- lockWaitMs: Number(match[1]),
53
- hostWaitMs: match[2] === NO_HOST_WAIT ? null : Number(match[2]),
54
- testRunMs: Number(match[3]),
55
- };
56
- }
57
-
58
41
  function fileExists(fsImpl, file) {
59
42
  try {
60
43
  return fsImpl.existsSync(file);
@@ -160,9 +143,9 @@ export function superviseSuite(child, opts) {
160
143
  /**
161
144
  * A bare suite gets SIGKILL on a parent signal; a gate with its own cleanup
162
145
  * (a capture holding the lock) SIGTERM. A full-suite gate also gets the
163
- * handshake and emits its timing line on release.
146
+ * handshake and reports its timings on release.
164
147
  *
165
- * @param {{ fullSuiteLock?: boolean, timeoutMs?: number, signal?: AbortSignal, env?: Record<string, string> }} opts
148
+ * @param {{ fullSuiteLock?: boolean, timeoutMs?: number, signal?: AbortSignal, env?: Record<string, string>, onLockEvent?: (event: object) => void }} opts
166
149
  * @param {{ lockWaitMs?: number }} [lock]
167
150
  */
168
151
  export function gateSupervision(opts, lock = {}) {
@@ -180,14 +163,11 @@ export function gateSupervision(opts, lock = {}) {
180
163
  supervise: (child, output) =>
181
164
  reportOnRelease(
182
165
  superviseSuite(child, { ...base, readyFile: handshake.file }),
183
- (timings) =>
184
- output.emit(
185
- output.prefix +
186
- formatSuiteTimings({
187
- lockWaitMs: lock.lockWaitMs ?? 0,
188
- ...timings,
189
- }),
190
- ),
166
+ (timings) => {
167
+ const full = { lockWaitMs: lock.lockWaitMs ?? 0, ...timings };
168
+ output.emit(output.prefix + formatSuiteTimings(full));
169
+ opts.onLockEvent?.({ kind: 'suite-timings', ...full });
170
+ },
191
171
  ),
192
172
  };
193
173
  }