mandrel 2.112.0 → 2.114.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,60 @@
1
+ /**
2
+ * baseline-conflict-rows.js — re-merge one conflicted `baselines/*.json`
3
+ * from its index stages so a row only the Story carries survives a
4
+ * baseline-only base-sync conflict.
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { decodeEnvelope } from '../baselines/codec.js';
10
+ import { mergeBaselineTheirsWins } from '../baselines/merge-envelopes.js';
11
+ import { writeFile as writeEnvelopeFile } from '../baselines/writer.js';
12
+
13
+ /** One index stage, decoded: `null` when absent, `undefined` when undecodable. */
14
+ function readStage(gitSpawn, cwd, stage, file) {
15
+ const show = gitSpawn(cwd, 'show', `:${stage}:${file}`);
16
+ if (show.status !== 0) return null;
17
+ try {
18
+ return decodeEnvelope(JSON.parse((show.stdout ?? '').toString()));
19
+ } catch {
20
+ return undefined;
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Row-merge one conflicted baseline from its index stages, the base side
26
+ * winning every conflict. The Story-only row count, or null to fall back.
27
+ */
28
+ function keepStoryRows(gitSpawn, cwd, file) {
29
+ const [base, ours, theirs] = [1, 2, 3].map((stage) =>
30
+ readStage(gitSpawn, cwd, stage, file),
31
+ );
32
+ if ([base, ours, theirs].includes(undefined)) return null;
33
+ try {
34
+ const merged = mergeBaselineTheirsWins({ base, ours, theirs });
35
+ if (!merged) return null;
36
+ const abs = path.join(cwd, file);
37
+ if (merged.envelopeKind) writeEnvelopeFile(abs, merged.envelope);
38
+ else fs.writeFileSync(abs, `${JSON.stringify(merged.envelope, null, 2)}\n`);
39
+ return merged.storyOnlyRows;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Row-merge each conflicted baseline in place; `wholeFile` lists the ones
47
+ * that must take `origin/<base>`'s whole file instead.
48
+ *
49
+ * @returns {{ kept: number, wholeFile: string[] }}
50
+ */
51
+ export function keepStoryRowsIn(gitSpawn, cwd, files) {
52
+ let kept = 0;
53
+ const wholeFile = [];
54
+ for (const file of files) {
55
+ const rows = keepStoryRows(gitSpawn, cwd, file);
56
+ if (rows === null) wholeFile.push(file);
57
+ else kept += rows;
58
+ }
59
+ return { kept, wholeFile };
60
+ }
@@ -16,6 +16,7 @@ import {
16
16
  gitFetchWithRetry as defaultGitFetchWithRetry,
17
17
  gitSpawn as defaultGitSpawn,
18
18
  } from '../git-utils.js';
19
+ import { keepStoryRowsIn } from './baseline-conflict-rows.js';
19
20
 
20
21
  /**
21
22
  * Refuse when the declared baseline merge driver is unregistered: git would
@@ -75,19 +76,25 @@ function diffPaths(gitSpawn, cwd, fromSha) {
75
76
  const DRIVER_OWNED_BASELINE = /^baselines\/[^/]+\.json$/;
76
77
 
77
78
  /**
78
- * Take `origin/<base>`'s side of each conflicted baseline and commit the
79
- * merge; the seat and close's gates re-derive the Story's rows. False on any
80
- * failed step.
79
+ * Take `origin/<base>`'s whole file for each of `wholeFile` (the baselines
80
+ * that could not be row-merged), stage every conflicted baseline and commit
81
+ * the merge. False on any failed step.
81
82
  *
82
83
  * @param {typeof defaultGitSpawn} gitSpawn
83
84
  * @param {string} cwd
84
85
  * @param {string} baseBranch
85
86
  * @param {string[]} files
87
+ * @param {string[]} wholeFile
86
88
  * @returns {boolean}
87
89
  */
88
- function resolveBaselinesToBase(gitSpawn, cwd, baseBranch, files) {
90
+ function resolveBaselinesToBase(gitSpawn, cwd, baseBranch, files, wholeFile) {
89
91
  const steps = [
90
- ['checkout', `origin/${baseBranch}`, '--', ...files],
92
+ ...wholeFile.map((file) => [
93
+ 'checkout',
94
+ `origin/${baseBranch}`,
95
+ '--',
96
+ file,
97
+ ]),
91
98
  ['add', '--', ...files],
92
99
  ['commit', '--no-edit'],
93
100
  ];
@@ -104,7 +111,8 @@ function unmergedPaths(gitSpawn, cwd) {
104
111
  }
105
112
 
106
113
  /**
107
- * A baseline-only conflict resolves to the base (`resolvedBaselineFiles`);
114
+ * A baseline-only conflict resolves row by row, base winning
115
+ * (`resolvedBaselineFiles`);
108
116
  * any other conflict is aborted for the caller to surface.
109
117
  *
110
118
  * @param {object} opts
@@ -230,15 +238,16 @@ function resolveBaselineOnlyConflict({
230
238
  driver.declared &&
231
239
  conflictFiles.length > 0 &&
232
240
  conflictFiles.every((f) => DRIVER_OWNED_BASELINE.test(f));
241
+ if (!baselineOnly) return null;
242
+ const { kept, wholeFile } = keepStoryRowsIn(gitSpawn, cwd, conflictFiles);
233
243
  if (
234
- !baselineOnly ||
235
- !resolveBaselinesToBase(gitSpawn, cwd, baseBranch, conflictFiles)
244
+ !resolveBaselinesToBase(gitSpawn, cwd, baseBranch, conflictFiles, wholeFile)
236
245
  ) {
237
246
  return null;
238
247
  }
239
248
  log(
240
249
  'SYNC',
241
- `Resolved baseline-only conflict to origin/${baseBranch}: ${conflictFiles.join(', ')}`,
250
+ `Resolved baseline-only conflict to origin/${baseBranch} (${kept} Story-only row(s) kept): ${conflictFiles.join(', ')}`,
242
251
  );
243
252
  return {
244
253
  synced: true,
@@ -69,6 +69,7 @@ export async function rescoreDuplication(ctx, readHead) {
69
69
  storyId: ctx.storyId,
70
70
  baseBranch: ctx.baseBranch,
71
71
  storyBranch: ctx.branch,
72
+ baselineRef: ctx.baselineRef,
72
73
  config: ctx.config,
73
74
  logger: { info: log, warn: log },
74
75
  });
@@ -5,6 +5,7 @@
5
5
  * @typedef {import('./types.js').Finding} Finding
6
6
  */
7
7
 
8
+ import { redactPii } from '../../error-redactor.js';
8
9
  import { isObject } from '../../json-utils.js';
9
10
  import { CLAIM_SCHEMA } from './claim-grounding.js';
10
11
  import { buildFinding, unwrapEnvelope } from './parse-findings.js';
@@ -63,13 +64,21 @@ function tryParseJson(text) {
63
64
  }
64
65
  }
65
66
 
67
+ const AUTH_PREFIX_CHARS = 200;
68
+ const AUTH_RETRY_DELAY_MS = 2000;
69
+
70
+ /** A PII-free, length-capped prefix of raw CLI output. */
71
+ const prefixOf = (text) =>
72
+ redactPii(text).replace(/\s+/g, ' ').trim().slice(0, AUTH_PREFIX_CHARS);
73
+
66
74
  /**
67
75
  * `claude auth status --json`. Only `authMethod` and `subscriptionType`
68
76
  * are ever named: the payload also carries the account email, org name
69
- * and ids, which no reason or log line may repeat.
77
+ * and ids, which no reason or log line may repeat. Non-JSON output on a
78
+ * zero exit is transient, so it is `retryable` after `delayMs`.
70
79
  *
71
- * @param {{ status: number, stdout: string }} result
72
- * @returns {{ ok: true, detail: string } | { ok: false, reason: string }}
80
+ * @param {{ status: number, stdout: string, stderr?: string }} result
81
+ * @returns {{ ok: true, detail: string } | { ok: false, reason: string, retryable?: boolean, delayMs?: number }}
73
82
  */
74
83
  export function readAuthStatus(result) {
75
84
  if (result.status !== 0) {
@@ -82,7 +91,12 @@ export function readAuthStatus(result) {
82
91
  if (!parsed || typeof parsed !== 'object') {
83
92
  return {
84
93
  ok: false,
85
- reason: 'claude auth status returned unparseable output',
94
+ reason:
95
+ 'claude auth status returned unparseable output ' +
96
+ `(stdout: "${prefixOf(result.stdout)}", ` +
97
+ `stderr: "${prefixOf(result.stderr)}")`,
98
+ retryable: true,
99
+ delayMs: AUTH_RETRY_DELAY_MS,
86
100
  };
87
101
  }
88
102
  const method =
@@ -35,6 +35,7 @@ import {
35
35
  } from '../../child-exec.js';
36
36
  import { gitSpawn } from '../../git-utils.js';
37
37
  import { PROJECT_ROOT } from '../../project-root.js';
38
+ import { defaultSleep } from '../../util/sleep.js';
38
39
  import { buildCallersSection } from './callers-context.js';
39
40
  import {
40
41
  FINDINGS_SCHEMA_JSON,
@@ -317,6 +318,11 @@ async function reviewInTempDir(prompt, effort, deps) {
317
318
  }
318
319
  }
319
320
 
321
+ /** Waits out the failure's `delayMs`, when it names one. */
322
+ async function pauseFor({ delayMs }, deps) {
323
+ if (delayMs) await (deps.sleepFn ?? defaultSleep)(delayMs);
324
+ }
325
+
320
326
  /** One invocation, re-run once when its failure is transient-shaped. */
321
327
  async function reviewWithRetry(prompt, effort, deps) {
322
328
  const first = await reviewInTempDir(prompt, effort, deps);
@@ -324,6 +330,7 @@ async function reviewWithRetry(prompt, effort, deps) {
324
330
  deps.logger?.warn?.(
325
331
  `[code-review] No verdict (${first.reason}); retrying once.`,
326
332
  );
333
+ await pauseFor(first, deps);
327
334
  return reviewInTempDir(prompt, effort, deps);
328
335
  }
329
336
 
@@ -346,6 +353,7 @@ function assertCliPresent(probeFn) {
346
353
  * gitSpawnFn?: typeof gitSpawn,
347
354
  * spawnFn?: Function,
348
355
  * authSpawnFn?: Function,
356
+ * sleepFn?: (ms: number) => Promise<void>,
349
357
  * platform?: string,
350
358
  * logger?: { info?: Function, warn?: Function },
351
359
  * }} [deps] - `spawnFn` / `authSpawnFn` replace the async runner for the
@@ -94,6 +94,10 @@ export function reviewGapLines(degradations) {
94
94
 
95
95
  /** The fix each no-verdict cause needs; matched on the record, never on PII. */
96
96
  const NO_VERDICT_FIXES = [
97
+ [
98
+ /auth status returned unparseable output/,
99
+ 'the auth preflight output was transient; re-run `story-review-compute.js`',
100
+ ],
97
101
  [/not logged in|auth status/, 'run `claude auth login`'],
98
102
  [/out of quota|usage limit/, 'wait for the usage-limit reset'],
99
103
  [/skipped/, 'install the `claude` or `codex` CLI'],
@@ -86,6 +86,7 @@ export async function runCloseValidationPhase({
86
86
  storyId,
87
87
  baseBranch,
88
88
  storyBranch,
89
+ baselineRef: baseSync?.baselineRef,
89
90
  config,
90
91
  progress,
91
92
  runScopedFormatAutofix,
@@ -181,7 +181,8 @@ export async function runPreGateSteps({
181
181
  run: () =>
182
182
  writebackStep(ctx, {
183
183
  tag: 'DUPLICATION',
184
- run: runDuplicationCloseRescore,
184
+ run: (args) =>
185
+ runDuplicationCloseRescore({ ...args, baselineRef: ctx.baselineRef }),
185
186
  noun: 'duplication re-score commit',
186
187
  describe: (w) =>
187
188
  `Re-scored ${w.movedPaths?.length ?? 0} duplication row(s) (untagged)`,
@@ -7,6 +7,10 @@
7
7
  * adds clones to a file it changed fails the head-vs-base compare at close.
8
8
  * The scan covers the whole tree (clones are pairwise); only changed-file rows
9
9
  * and their clone partners' rows are written. Every failure is a named skip, never a failed close.
10
+ *
11
+ * A skipped base sync passes `baselineRef` (the merge-base): the change set is
12
+ * scoped on it, and no row is written for a path `origin/<base>` changed since,
13
+ * because the tree holds that file's merge-base version and main owns its row.
10
14
  */
11
15
 
12
16
  import fs from 'node:fs';
@@ -98,11 +102,44 @@ function resolveScopeBase({ workTree, git, baseBranch }) {
98
102
  }
99
103
 
100
104
  /**
101
- * Guards plus the scoped file list. A dirty baseline file would otherwise be
102
- * swept into the commit.
105
+ * Paths `origin/<base>` changed since `baselineRef`; the base-sync probe's
106
+ * raw-path rule. Throws on a failed diff.
107
+ *
108
+ * @param {{ workTree: string, git: Function, scopeBase: string, baselineRef: string }} ctx
109
+ * @returns {string[]}
110
+ */
111
+ function listIncomingFiles({ workTree, git, scopeBase, baselineRef }) {
112
+ const out = git(
113
+ ['diff', '--name-only', '--no-renames', baselineRef, scopeBase],
114
+ { cwd: workTree },
115
+ );
116
+ return String(out ?? '')
117
+ .split('\n')
118
+ .map((line) => line.trim())
119
+ .filter((line) => line.length > 0);
120
+ }
121
+
122
+ /**
123
+ * The change-set base and the incoming paths a skipped base sync excludes.
103
124
  *
104
- * @param {{ workTree: string, baseBranch: string, storyBranch: string, git: Function, relPath: string, additionalFormats?: string[] }} ctx
105
- * @returns {{ reason: string } | { files: string[] }}
125
+ * @param {{ workTree: string, git: Function, baseBranch: string, baselineRef?: string }} ctx
126
+ * @returns {{ diffBase: string, exclude: string[] }}
127
+ */
128
+ function resolveScopeRefs({ workTree, git, baseBranch, baselineRef }) {
129
+ const scopeBase = resolveScopeBase({ workTree, git, baseBranch });
130
+ if (!baselineRef) return { diffBase: scopeBase, exclude: [] };
131
+ return {
132
+ diffBase: baselineRef,
133
+ exclude: listIncomingFiles({ workTree, git, scopeBase, baselineRef }),
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Guards plus the scoped file list and the paths whose rows stay untouched. A
139
+ * dirty baseline file would otherwise be swept into the commit.
140
+ *
141
+ * @param {{ workTree: string, baseBranch: string, storyBranch: string, git: Function, relPath: string, additionalFormats?: string[], baselineRef?: string }} ctx
142
+ * @returns {{ reason: string } | { files: string[], exclude: string[] }}
106
143
  */
107
144
  function resolveScope({
108
145
  workTree,
@@ -111,6 +148,7 @@ function resolveScope({
111
148
  git,
112
149
  relPath,
113
150
  additionalFormats,
151
+ baselineRef,
114
152
  }) {
115
153
  if (currentBranch(workTree, git) !== storyBranch) {
116
154
  return { reason: 'wrong-branch' };
@@ -118,14 +156,22 @@ function resolveScope({
118
156
  if (listDirtyPaths(workTree, git).includes(relPath)) {
119
157
  return { reason: 'dirty-tree' };
120
158
  }
159
+ const { diffBase, exclude } = resolveScopeRefs({
160
+ workTree,
161
+ git,
162
+ baseBranch,
163
+ baselineRef,
164
+ });
121
165
  const isScorable = fileFilterFor(KIND, { additionalFormats });
122
166
  const files = listChangedFiles({
123
167
  cwd: workTree,
124
- baseBranch: resolveScopeBase({ workTree, git, baseBranch }),
168
+ baseBranch: diffBase,
125
169
  storyBranch,
126
170
  git,
127
171
  }).filter((f) => isScorable(f));
128
- return files.length === 0 ? { reason: 'no-changed-files' } : { files };
172
+ return files.length === 0
173
+ ? { reason: 'no-changed-files' }
174
+ : { files, exclude };
129
175
  }
130
176
 
131
177
  /**
@@ -190,6 +236,7 @@ async function attempt(fn, label) {
190
236
  * storyId: number|string,
191
237
  * baseBranch: string,
192
238
  * storyBranch?: string,
239
+ * baselineRef?: string,
193
240
  * config?: object,
194
241
  * logger?: object,
195
242
  * gitSync?: (cwd: string, ...args: string[]) => string,
@@ -205,6 +252,7 @@ export async function runDuplicationCloseRescore({
205
252
  storyId,
206
253
  baseBranch,
207
254
  storyBranch,
255
+ baselineRef,
208
256
  config,
209
257
  logger = DefaultLogger,
210
258
  gitSync = defaultGitSync,
@@ -236,12 +284,13 @@ export async function runDuplicationCloseRescore({
236
284
  git,
237
285
  relPath,
238
286
  additionalFormats: gate.value.additionalFormats,
287
+ baselineRef,
239
288
  }),
240
289
  'git-failed',
241
290
  );
242
291
  if (scope.reason) return skip(logger, scope.reason);
243
292
  if (scope.value.reason) return skip(logger, scope.value.reason);
244
- const { files } = scope.value;
293
+ const { files, exclude } = scope.value;
245
294
 
246
295
  const priorRows = readPriorEnvelope(writePath, fs)?.rows ?? [];
247
296
  const refreshed = await attempt(
@@ -251,6 +300,7 @@ export async function runDuplicationCloseRescore({
251
300
  cwd: workTree,
252
301
  writePath,
253
302
  scopeFiles: files,
303
+ excludeWriteFiles: exclude,
254
304
  epsilon: getBaselineEpsilon(KIND),
255
305
  ...(scorer ? { scorer } : {}),
256
306
  }),
@@ -489,15 +489,37 @@ async function runPreflightCheck(ctx, check, pass, env) {
489
489
  check.args,
490
490
  env,
491
491
  );
492
- const detail = preflightFinding(check, run);
493
- if (check.key === 'lint') pass.lint = detail ? 'failed' : 'passed';
494
- if (!detail) {
492
+ const finding = preflightFinding(check, run);
493
+ if (check.key === 'lint') pass.lint = finding ? 'failed' : 'passed';
494
+ if (!finding) {
495
495
  creditCheck(ctx, check);
496
496
  return null;
497
497
  }
498
+ const detail = finding + seatHint(ctx, check);
498
499
  return { check: check.key, detail, evidencePath: run.evidencePath };
499
500
  }
500
501
 
502
+ /**
503
+ * A failed lint on a change set that adds files may be a missing coverage or
504
+ * CRAP row the seat writes only after preflight: name the downgrade contract.
505
+ */
506
+ function seatHint(ctx, check) {
507
+ if (check.key !== 'lint') return '';
508
+ const added = gitLine(ctx.git, ctx.cwd, [
509
+ 'diff',
510
+ '--name-only',
511
+ '--diff-filter=A',
512
+ `origin/${ctx.baseBranch}...HEAD`,
513
+ ]);
514
+ if (!added) return '';
515
+ return (
516
+ '\n hint: this change set adds files, whose coverage and CRAP rows are seated after preflight; ' +
517
+ 'a check refusing a missing row for a change-set file must downgrade under ' +
518
+ 'MANDREL_HANDOFF_STEP=preflight and be declared in delivery.handoff.postSeatChecks ' +
519
+ '(.agents/docs/configuration.md § delivery.handoff.postSeatChecks)'
520
+ );
521
+ }
522
+
501
523
  /**
502
524
  * Why a covered ratchet does not spawn: `covered` once this pass's whole-tree
503
525
  * lint exited 0, `lint-failed` once it failed (its finding stands). Anything
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,22 @@ 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.114.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.113.0...mandrel-v2.114.0) (2026-11-08)
19
+
20
+
21
+ ### Added
22
+
23
+ * run the duplication re-score's jscpd scan in a child process with its own configurable heap ([#6028](https://github.com/dsj1984/mandrel/issues/6028)) ([#6029](https://github.com/dsj1984/mandrel/issues/6029)) ([3080b96](https://github.com/dsj1984/mandrel/commit/3080b9625a455070f7d30da15c7b01950202788a))
24
+
25
+ ## [2.113.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.112.0...mandrel-v2.113.0) (2026-11-07)
26
+
27
+
28
+ ### Fixed
29
+
30
+ * base sync keeps Story-only baseline rows on a baseline-only conflict, and preflight lint names the handoff-step downgrade ([#6022](https://github.com/dsj1984/mandrel/issues/6022)) ([#6026](https://github.com/dsj1984/mandrel/issues/6026)) ([1c281cd](https://github.com/dsj1984/mandrel/commit/1c281cd3840c52df9025a2a00b3cfede2ae0d171))
31
+ * code-review auth probe retries a non-JSON `claude auth status` once and records a redacted output prefix ([#6021](https://github.com/dsj1984/mandrel/issues/6021)) ([#6024](https://github.com/dsj1984/mandrel/issues/6024)) ([b719dd3](https://github.com/dsj1984/mandrel/commit/b719dd3281fecaa061abcf94610b0dfaa59ed904))
32
+ * duplication re-score moves only the rows a Story caused when baseSync on-conflict skipped the base merge ([#6019](https://github.com/dsj1984/mandrel/issues/6019)) ([#6025](https://github.com/dsj1984/mandrel/issues/6025)) ([1b9354a](https://github.com/dsj1984/mandrel/commit/1b9354af75976a3037db235f49769fc0eae3ae8a))
33
+
18
34
  ## [2.112.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.111.0...mandrel-v2.112.0) (2026-11-07)
19
35
 
20
36
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.112.0",
3
+ "version": "2.114.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/",