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.
@@ -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';
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,25 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.82.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.81.0...mandrel-v2.82.0) (2026-10-11)
19
+
20
+
21
+ ### Added
22
+
23
+ * re-score the by-hand baselines automatically: duplication at close and nightly, dead-export and cyclomatic shrinks at close ([#5626](https://github.com/dsj1984/mandrel/issues/5626)) ([#5631](https://github.com/dsj1984/mandrel/issues/5631)) ([60407e7](https://github.com/dsj1984/mandrel/commit/60407e71d3828a2524efa3cbb6a199ef6d340f6c))
24
+
25
+
26
+ ### Fixed
27
+
28
+ * duplication scanner: drop clone sides whose end line exceeds the file length ([#5619](https://github.com/dsj1984/mandrel/issues/5619)) ([#5623](https://github.com/dsj1984/mandrel/issues/5623)) ([03c5ea3](https://github.com/dsj1984/mandrel/commit/03c5ea3e5e66ea443193b84e5822ddddda1d0bff))
29
+ * post-land ref cleanup also reaps the origin/story-&lt;id&gt; remote-tracking… ([#5620](https://github.com/dsj1984/mandrel/issues/5620)) ([#5621](https://github.com/dsj1984/mandrel/issues/5621)) ([487ff5e](https://github.com/dsj1984/mandrel/commit/487ff5e8ef8f95ec87ae41fccb328c7d268aad29))
30
+
31
+
32
+ ### Changed
33
+
34
+ * burn down the CRAP and cyclomatic debt in the audit-report parser ([#5627](https://github.com/dsj1984/mandrel/issues/5627)) ([#5630](https://github.com/dsj1984/mandrel/issues/5630)) ([e35cf33](https://github.com/dsj1984/mandrel/commit/e35cf3378c882c926ea2f2484127e709c9159547))
35
+ * burn down the orchestration and bootstrap hotspot clusters and tighten the CRAP and MI floors behind them ([#5628](https://github.com/dsj1984/mandrel/issues/5628)) ([#5632](https://github.com/dsj1984/mandrel/issues/5632)) ([ee56182](https://github.com/dsj1984/mandrel/commit/ee561820e1593eb5e6b56cbf0c4c4b5654033d9f))
36
+
18
37
  ## [2.81.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.80.0...mandrel-v2.81.0) (2026-10-11)
19
38
 
20
39
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.81.0",
3
+ "version": "2.82.0",
4
4
  "description": "Claude Code-first opinionated workflow framework: instructions, skills, rules, and SDLC workflows that govern AI coding assistants.",
5
5
  "files": [
6
6
  ".agents/",