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
@@ -86,7 +86,7 @@ Project identity, filesystem roots, planner docs context, and the commands the c
86
86
  | `docsContextFiles` | No | `array<string>` | `["architecture.md","data-dictionary.md","decisions.md","patterns.md"]` | Files under `paths.docsRoot` the planner treats as standing context. Read digest-first — the docs digest names the file and the line range, and only the named section is pulled. |
87
87
  | `commands` | No | `object` | — | Shell commands the close-validation chain spawns. Each is run from the repo root. |
88
88
  | `commands.test` | No | `string` | `"npm test"` | Full test-suite command close's `test` gate spawns, and the identity its `test` credit is hashed under — the deposit `run-tests.js` makes, close's credit probe and `verify[]` credit all key on it, as does `mandrel doctor`'s `test-credit-path` check. Set it for a non-npm project (e.g. `python3 scripts/validation.py`); unset, it is `npm test`. Like every command here it must be a single argv (no `;`, `&&`, pipes or substitution). |
89
- | `commands.typecheck` | No | `string` \| `null` | `null` | Static type-check command. `null` disables the gate for projects with no type layer; the empty string is rejected so a typo cannot silently disable it. |
89
+ | `commands.typecheck` | No | `string` \| `null` | `null` | Static type-check command run as a close-validation gate. Left unset (the `null` default), it falls back to `npm run typecheck`. An explicit `null` disables the gate for projects with no type layer: close reports it as skipped (`typecheck-disabled`) and runs nothing. The empty string is rejected so a typo cannot silently disable it. |
90
90
  | `commands.lint` | No | `string` \| `null` | `null` | Lint command run as a close-validation gate. `null` (the default) uses `npm run lint`; the gate is mandatory, so unlike `typecheck` this key cannot disable it. Point it at the scoped command your hooks already run to stop paying for a third whole-repo lint at close — the gate still lints the diff, and CI still owns whole-repo drift. Like every command here it must be a single argv (no `;`, `&&`, pipes or substitution), so wrap a multi-linter pair in one npm script and name that. |
91
91
  | `commands.formatCheck` | No | `string` | `"npx biome format ."` | Non-mutating format verification run as a close-validation gate. |
92
92
  | `commands.formatWrite` | No | `string` | `"npx biome format --write ."` | Mutating format command the close-time format-autofix step spawns. |
@@ -294,8 +294,9 @@ names or defaults.
294
294
  and the audit-suite prompt artifacts). Override `tempRoot` to relocate it.
295
295
  - **`commands`.** Each string must be non-empty and pass the shell-injection
296
296
  guard (`safeString` — disallows `;`, `&`, `|`, backtick, `$`, `<`, `>`).
297
- `typecheck` is nullable; `null` is the canonical "not applicable for this
298
- repo" value. Read the block via `getCommands(config)`
297
+ `typecheck` is nullable; an explicit `null` is the canonical "not
298
+ applicable for this repo" value and makes close report the gate as skipped,
299
+ while leaving the key unset keeps the `npm run typecheck` fallback. Read the block via `getCommands(config)`
299
300
  ([`config-resolver.js`](../scripts/lib/config-resolver.js)).
300
301
  - **`docsContextFiles`.** Entries are **plain filenames, not globs** — each
301
302
  resolves to a single file under `paths.docsRoot`. For the decisions log this
@@ -91,7 +91,7 @@
91
91
  "type": "string",
92
92
  "pattern": "([;&|`]|\\$\\()"
93
93
  },
94
- "description": "Static type-check command. `null` disables the gate for projects with no type layer; the empty string is rejected so a typo cannot silently disable it.",
94
+ "description": "Static type-check command run as a close-validation gate. Left unset (the `null` default), it falls back to `npm run typecheck`. An explicit `null` disables the gate for projects with no type layer: close reports it as skipped (`typecheck-disabled`) and runs nothing. The empty string is rejected so a typo cannot silently disable it.",
95
95
  "default": null
96
96
  },
97
97
  "lint": {
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { getChangedFiles } from './lib/changed-files.js';
16
16
  import { isDirectInvocation } from './lib/cli-utils.js';
17
+ import { claimLockEventSink, lockEventHooks } from './lib/close-lock-events.js';
17
18
  import { getQuality, resolveConfig } from './lib/config-resolver.js';
18
19
  import {
19
20
  computeContentDigest,
@@ -68,6 +69,7 @@ export function parseArgs(argv) {
68
69
  * filterFilesUnderTargetsImpl?: typeof filterFilesUnderTargets,
69
70
  * logger?: { info: Function, warn: Function, error: Function },
70
71
  * lockOptions?: object,
72
+ * env?: Record<string, string|undefined>,
71
73
  * }} [deps]
72
74
  * @returns {Promise<number>}
73
75
  */
@@ -85,30 +87,26 @@ export async function runCoverageCapture(argv = process.argv, deps = {}) {
85
87
  filterFilesUnderTargetsImpl = filterFilesUnderTargets,
86
88
  logger = Logger,
87
89
  lockOptions = {},
90
+ env = process.env,
88
91
  } = deps;
92
+ const lockHooks = lockEventHooks(claimLockEventSink(env));
89
93
  const args = parseArgs(argv);
90
94
  const config = resolveConfigImpl({ cwd: args.cwd });
91
95
  const { crap, coverage } = getQualityImpl(config);
92
-
93
- if (crap.enabled === false) {
94
- logger.info('[coverage-capture] CRAP gate disabled — skipping capture.');
95
- return 0;
96
- }
97
-
98
- // Name the fix rather than propagate npm's opaque "Missing script" exit.
99
- if (!hasNpmScriptImpl(readPackageScriptsImpl(args.cwd), 'test:coverage')) {
100
- logger.error(
101
- '[coverage-capture] ✖ No "test:coverage" script in package.json. ' +
102
- 'Add one (e.g. "test:coverage": "node --test --experimental-test-coverage") ' +
103
- 'or disable the CRAP gate via delivery.quality.gates.crap.enabled=false.',
104
- );
105
- return 1;
106
- }
96
+ const refused = refusal({
97
+ crap,
98
+ cwd: args.cwd,
99
+ readPackageScriptsImpl,
100
+ hasNpmScriptImpl,
101
+ logger,
102
+ });
103
+ if (refused !== null) return refused;
107
104
 
108
105
  // Outermost first: the credit probe announces or refuses the run, and only
109
106
  // a surviving run reaches the host-level full-suite lock.
110
- const locked = lockedCapture(runCaptureImpl, config, process.env, {
107
+ const locked = lockedCapture(runCaptureImpl, config, env, {
111
108
  rerunCommand: rerunCommandFor(argv),
109
+ onLockOutcome: lockHooks.onLockOutcome,
112
110
  ...lockOptions,
113
111
  });
114
112
  const credited = creditedCapture(locked, {
@@ -139,10 +137,39 @@ export async function runCoverageCapture(argv = process.argv, deps = {}) {
139
137
  logger,
140
138
  },
141
139
  });
142
- if (timings) logger.info(`[coverage-capture] ${formatSuiteTimings(timings)}`);
140
+ if (timings) reportTimings(timings, logger, lockHooks);
143
141
  return code;
144
142
  }
145
143
 
144
+ /** @returns {number|null} The exit code when no capture may run. */
145
+ function refusal({
146
+ crap,
147
+ cwd,
148
+ readPackageScriptsImpl,
149
+ hasNpmScriptImpl,
150
+ logger,
151
+ }) {
152
+ if (crap.enabled === false) {
153
+ logger.info('[coverage-capture] CRAP gate disabled — skipping capture.');
154
+ return 0;
155
+ }
156
+ if (hasNpmScriptImpl(readPackageScriptsImpl(cwd), 'test:coverage')) {
157
+ return null;
158
+ }
159
+ // Name the fix rather than propagate npm's opaque "Missing script" exit.
160
+ logger.error(
161
+ '[coverage-capture] ✖ No "test:coverage" script in package.json. ' +
162
+ 'Add one (e.g. "test:coverage": "node --test --experimental-test-coverage") ' +
163
+ 'or disable the CRAP gate via delivery.quality.gates.crap.enabled=false.',
164
+ );
165
+ return 1;
166
+ }
167
+
168
+ function reportTimings(timings, logger, lockHooks) {
169
+ logger.info(`[coverage-capture] ${formatSuiteTimings(timings)}`);
170
+ lockHooks.onTimings(timings);
171
+ }
172
+
146
173
  /** @param {string[]} argv */
147
174
  function rerunCommandFor(argv) {
148
175
  return ['node', ...argv.slice(1)].join(' ');
@@ -189,17 +216,21 @@ async function runCaptureScopes({ crap, coverage, args, capture, deps }) {
189
216
  return await runFullScopeCapture(shared);
190
217
  }
191
218
 
219
+ // Module-level so coverage sees them even when no test spawns the CLI.
220
+ function exitWith(code) {
221
+ process.exit(code);
222
+ }
223
+
224
+ function exitOnUnexpectedError(err) {
225
+ Logger.error('[coverage-capture] unexpected error:', err);
226
+ process.exit(1);
227
+ }
228
+
192
229
  // cli-opt-out: main resolves an exit code that is forwarded via process.exit(code); runAsCli's async-main signature does not preserve the result code.
193
230
  if (isDirectInvocation(import.meta.url)) {
194
231
  // `--help` must not reach the core, which would spawn the whole suite.
195
232
  (handleCoverageCaptureHelp(process.argv)
196
233
  ? Promise.resolve(0)
197
234
  : runCoverageCapture()
198
- ).then(
199
- (code) => process.exit(code),
200
- (err) => {
201
- Logger.error('[coverage-capture] unexpected error:', err);
202
- process.exit(1);
203
- },
204
- );
235
+ ).then(exitWith, exitOnUnexpectedError);
205
236
  }
@@ -11,6 +11,7 @@
11
11
  import { spawnSync } from 'node:child_process';
12
12
  import { parseArgs } from 'node:util';
13
13
  import { runAsCli } from './lib/cli-utils.js';
14
+ import { claimLockEventSink, lockEventHooks } from './lib/close-lock-events.js';
14
15
  import { getQuality, resolveConfig } from './lib/config-resolver.js';
15
16
  import {
16
17
  fullSuiteLockPolicy,
@@ -228,12 +229,14 @@ export function runLockedSuite(
228
229
  } = {},
229
230
  ) {
230
231
  const timeoutMs = getQuality(config).coverage?.timeoutMs;
232
+ const lockHooks = lockEventHooks(claimLockEventSink(env));
231
233
  return withFullSuiteLockAsync(
232
234
  {
233
235
  ...fullSuiteLockPolicy(config, env),
234
236
  cwd,
235
237
  log,
236
238
  rerunCommand: ['node', ...process.argv.slice(1)].join(' '),
239
+ onLockOutcome: lockHooks.onLockOutcome,
237
240
  ...lockOptions,
238
241
  },
239
242
  ({ lockWaitMs }) =>
@@ -243,7 +246,10 @@ export function runLockedSuite(
243
246
  cwd,
244
247
  timeoutMs,
245
248
  lockWaitMs,
246
- onTimings: (t) => log(`[evidence-gate] ${formatSuiteTimings(t)}`),
249
+ onTimings: (t) => {
250
+ log(`[evidence-gate] ${formatSuiteTimings(t)}`);
251
+ lockHooks.onTimings(t);
252
+ },
247
253
  onTimeout: () =>
248
254
  log(
249
255
  `[evidence-gate] ⏱ ${cmd} ${args.join(' ')} exceeded ${timeoutMs}ms — killed its process group.`,
@@ -69,6 +69,50 @@ function deriveDimension(fields, fallbackDimension) {
69
69
  return fallbackDimension;
70
70
  }
71
71
 
72
+ /**
73
+ * Strip wrapping quotes/brackets, trailing punctuation, and a `Location:`
74
+ * anchor (`:line`, `:line:col`, `:start-end`) from a raw token.
75
+ *
76
+ * @param {string} raw
77
+ * @returns {string}
78
+ */
79
+ function stripTokenDecoration(raw) {
80
+ return raw
81
+ .replace(/^[`'"([]+/, '')
82
+ .replace(/[`'")\].,;]+$/, '')
83
+ .trim()
84
+ .replace(/:\d+(?:-\d+)?(?::\d+)?$/, '');
85
+ }
86
+
87
+ /**
88
+ * Drop the `repoRoot` prefix (either separator) from a token, if present.
89
+ *
90
+ * @param {string} token
91
+ * @param {string} [repoRoot]
92
+ * @returns {string}
93
+ */
94
+ function relativiseToRoot(token, repoRoot) {
95
+ if (typeof repoRoot !== 'string' || repoRoot.length === 0) return token;
96
+ for (const sep of ['/', '\\']) {
97
+ const root = repoRoot.endsWith(sep) ? repoRoot : `${repoRoot}${sep}`;
98
+ if (token.startsWith(root)) return token.slice(root.length);
99
+ }
100
+ return token;
101
+ }
102
+
103
+ function isAbsoluteToken(token) {
104
+ return /^(?:[/\\]|[A-Za-z]:)/.test(token);
105
+ }
106
+
107
+ /**
108
+ * A separator-less token passes only as a bare file with a known extension,
109
+ * and only where `requireSeparator` does not forbid it.
110
+ */
111
+ function isAcceptedShape(token, requireSeparator) {
112
+ if (token.includes('/') || token.includes('\\')) return true;
113
+ return !requireSeparator && FILE_EXT.test(token);
114
+ }
115
+
72
116
  /**
73
117
  * Repo-relative path, or `null` for an absolute (outside `repoRoot`) or
74
118
  * degenerate token. A bare root-level file (`AGENTS.md`) is accepted in
@@ -82,32 +126,12 @@ function deriveDimension(fields, fallbackDimension) {
82
126
  */
83
127
  function normalisePathToken(raw, repoRoot, { requireSeparator = false } = {}) {
84
128
  if (typeof raw !== 'string') return null;
85
- const stripped = raw
86
- .replace(/^[`'"([]+/, '')
87
- .replace(/[`'")\].,;]+$/, '')
88
- .trim();
89
- // `Location:` anchors appear as `:line`, `:line:col`, and `:start-end`.
90
- const cleaned = stripped.replace(/:\d+(?:-\d+)?(?::\d+)?$/, '');
129
+ const cleaned = stripTokenDecoration(raw);
91
130
  if (!cleaned || cleaned === '.' || cleaned === '..') return null;
92
-
93
- let out = cleaned;
94
- if (typeof repoRoot === 'string' && repoRoot.length > 0) {
95
- for (const sep of ['/', '\\']) {
96
- const root = repoRoot.endsWith(sep) ? repoRoot : `${repoRoot}${sep}`;
97
- if (out.startsWith(root)) {
98
- out = out.slice(root.length);
99
- break;
100
- }
101
- }
102
- }
131
+ const out = relativiseToRoot(cleaned, repoRoot);
103
132
  // Still absolute ⇒ outside the repo; never a valid group key.
104
- if (out.startsWith('/') || out.startsWith('\\') || /^[A-Za-z]:/.test(out)) {
105
- return null;
106
- }
107
- const hasSeparator = out.includes('/') || out.includes('\\');
108
- if (requireSeparator && !hasSeparator) return null;
109
- if (!hasSeparator && !FILE_EXT.test(out)) return null;
110
- return out;
133
+ if (isAbsoluteToken(out)) return null;
134
+ return isAcceptedShape(out, requireSeparator) ? out : null;
111
135
  }
112
136
 
113
137
  /**
@@ -468,6 +492,7 @@ export const __testing = {
468
492
  isGroupingHeader,
469
493
  foldGroupingHeaders,
470
494
  normaliseSeverity,
495
+ normalisePathToken,
471
496
  extractFilePaths,
472
497
  normaliseTitle,
473
498
  deriveDimension,
@@ -59,16 +59,20 @@ export function relativisePath(sourceId, cwd) {
59
59
  }
60
60
 
61
61
  /**
62
- * A side with `end.line < start.line` counts nothing: its real span is
63
- * unrecoverable, and widening it recorded hundreds of phantom lines.
62
+ * A side ending before it starts, or past its file's counted length, counts
63
+ * nothing: its real span is unrecoverable (jscpd 4 can report the other
64
+ * file's end line), and widening or clamping it records phantom lines.
64
65
  *
65
66
  * @param {{ start?: { line?: number }, end?: { line?: number } }} dup
67
+ * @param {number} [maxLine] the file's counted length, when known
66
68
  * @returns {Array<number>} the 1-based line numbers the clone covers
67
69
  */
68
- function cloneLineNumbers(dup) {
70
+ function cloneLineNumbers(dup, maxLine) {
69
71
  const start = dup?.start?.line;
70
72
  const end = dup?.end?.line;
71
- if (!Number.isInteger(start) || !Number.isInteger(end)) return [];
73
+ if (!Number.isInteger(start) || !Number.isInteger(end) || end > maxLine) {
74
+ return [];
75
+ }
72
76
  const lines = [];
73
77
  for (let n = start; n <= end; n += 1) lines.push(n);
74
78
  return lines;
@@ -100,7 +104,7 @@ export function buildDuplicationRows(
100
104
  const file = relativisePath(side.sourceId, cwd);
101
105
  if (!file) continue;
102
106
  const set = dupLinesByFile.get(file) ?? new Set();
103
- for (const line of cloneLineNumbers(side)) set.add(line);
107
+ for (const n of cloneLineNumbers(side, counts.get(file))) set.add(n);
104
108
  dupLinesByFile.set(file, set);
105
109
  }
106
110
  }
@@ -144,6 +148,30 @@ export function readLineCount(absPath) {
144
148
  return lines.length;
145
149
  }
146
150
 
151
+ /** fast-glob reads a backslash as an escape. */
152
+ function toGlobPath(p) {
153
+ return p.split(path.sep).join('/');
154
+ }
155
+
156
+ /**
157
+ * jscpd 4's finder globs with `cwd: process.cwd()` and ignores its `cwd`
158
+ * option, so a repo-relative ignore glob only ever matches the process tree.
159
+ * Anchor each one at `cwd`; absolute and `**\/`-prefixed globs pass through,
160
+ * as jscpd itself treats them.
161
+ *
162
+ * @param {unknown} ignoreGlobs
163
+ * @param {string} cwd
164
+ * @returns {string[]}
165
+ */
166
+ function anchorIgnoreGlobs(ignoreGlobs, cwd) {
167
+ if (!Array.isArray(ignoreGlobs)) return [];
168
+ return ignoreGlobs.map((glob) =>
169
+ path.isAbsolute(glob) || glob.startsWith('**/')
170
+ ? glob
171
+ : toGlobPath(path.resolve(cwd, glob)),
172
+ );
173
+ }
174
+
147
175
  /**
148
176
  * @param {{
149
177
  * targetDirs: string[],
@@ -170,14 +198,14 @@ export async function scanDuplication({
170
198
  }
171
199
  const dirs = Array.isArray(targetDirs) ? targetDirs : [];
172
200
  const clones = await detect({
173
- path: dirs,
201
+ path: dirs.map((dir) => toGlobPath(path.resolve(cwd, dir))),
174
202
  cwd,
175
203
  silent: true,
176
204
  gitignore: false,
177
205
  reporters: [],
178
206
  format: formats,
179
207
  minTokens,
180
- ignore: Array.isArray(ignoreGlobs) ? ignoreGlobs : [],
208
+ ignore: anchorIgnoreGlobs(ignoreGlobs, cwd),
181
209
  });
182
210
  const visited = collectVisitedFiles(clones, cwd);
183
211
  const fileLineCounts = new Map();
@@ -21,20 +21,6 @@ export const PHASE_GROUPS = Object.freeze({
21
21
  QUALITY_GATES: 'quality-gates',
22
22
  });
23
23
 
24
- /** @type {ReadonlySet<string>} */
25
- export const PHASE_GROUP_VALUES = Object.freeze(
26
- new Set(Object.values(PHASE_GROUPS)),
27
- );
28
-
29
- /** @type {readonly string[]} */
30
- export const MANIFEST_ENTRY_FIELDS = Object.freeze([
31
- 'phaseGroup',
32
- 'target',
33
- 'action',
34
- 'detail',
35
- 'reversible',
36
- ]);
37
-
38
24
  /**
39
25
  * @typedef {object} MutationManifestEntry
40
26
  * @property {'ide-wiring'|'repo-config'|'github-admin'|'quality-gates'} phaseGroup
@@ -44,6 +30,128 @@ export const MANIFEST_ENTRY_FIELDS = Object.freeze([
44
30
  * @property {boolean} reversible — false for remote-admin mutations.
45
31
  */
46
32
 
33
+ const rel = (...parts) => path.posix.join(...parts);
34
+
35
+ /**
36
+ * @param {MutationManifestEntry['phaseGroup']} phaseGroup
37
+ * @param {boolean} reversible
38
+ * @returns {(target: string, action: string, detail: string) => MutationManifestEntry}
39
+ */
40
+ function entryFor(phaseGroup, reversible) {
41
+ return (target, action, detail) => ({
42
+ phaseGroup,
43
+ target,
44
+ action,
45
+ detail,
46
+ reversible,
47
+ });
48
+ }
49
+
50
+ function ideWiringEntries() {
51
+ const e = entryFor(PHASE_GROUPS.IDE_WIRING, true);
52
+ return [
53
+ e(
54
+ rel('AGENTS.md'),
55
+ 'merge',
56
+ 'Wire the @.agents/instructions.md system-prompt import into AGENTS.md (folding any CLAUDE.md into it) so Claude Code hydrates the framework on cold start.',
57
+ ),
58
+ e(
59
+ rel('.claude', 'commands'),
60
+ 'run',
61
+ 'Generate the flat command surface (/<name>) from .agents/workflows/.',
62
+ ),
63
+ e(
64
+ rel('.gitignore'),
65
+ 'merge',
66
+ 'Ignore the .claude/commands/ and .claude/agents/ projections (generated by prepare), .mcp.json + .env (carry secrets), and the per-clone install ledger.',
67
+ ),
68
+ ];
69
+ }
70
+
71
+ function repoConfigEntries() {
72
+ const e = entryFor(PHASE_GROUPS.REPO_CONFIG, true);
73
+ // git-init is the most irreversible local mutation; the ledger must record it.
74
+ const gitInit = entryFor(PHASE_GROUPS.REPO_CONFIG, false)(
75
+ rel('.git'),
76
+ 'run',
77
+ 'Initialize the local git repository (git init + first commit) when absent. No-op when already a git repo.',
78
+ );
79
+ return [
80
+ gitInit,
81
+ e(
82
+ rel('package.json'),
83
+ 'merge',
84
+ 'Seed/merge the sync:commands, sync:agents, prepare, and bootstrap npm scripts. `prepare` is guarded: it exits 0 without writing when .agents/scripts/ is absent (a manifest-only container `npm ci`), and otherwise regenerates the .claude/commands/ and .claude/agents/ projections — both gitignored.',
85
+ ),
86
+ e(
87
+ rel('.agentrc.json'),
88
+ 'create',
89
+ 'Seed .agentrc.json from the bundled starter with the operator-supplied owner/repo/handle/base-branch.',
90
+ ),
91
+ e(
92
+ rel('.github', 'ISSUE_TEMPLATE'),
93
+ 'create',
94
+ 'Generate the Story/Epic GitHub Issue Forms from the body SSOT so human-filed tickets round-trip through story-body.parse(). Operator-edited forms are preserved.',
95
+ ),
96
+ ];
97
+ }
98
+
99
+ function qualityGateEntries() {
100
+ const e = entryFor(PHASE_GROUPS.QUALITY_GATES, true);
101
+ return [
102
+ e(
103
+ rel('.husky', 'pre-commit'),
104
+ 'configure',
105
+ 'Install the quality:preview pre-commit hook that blocks MI/CRAP drift at commit time.',
106
+ ),
107
+ e(
108
+ rel('package.json'),
109
+ 'merge',
110
+ 'Add the quality:preview and quality:watch npm scripts.',
111
+ ),
112
+ e(
113
+ rel('.agentrc.json'),
114
+ 'merge',
115
+ 'Seed delivery.quality coding-guardrails and auto-refresh defaults.',
116
+ ),
117
+ ];
118
+ }
119
+
120
+ function githubAdminEntries(answers) {
121
+ const repoSlug =
122
+ answers?.owner && answers?.repo
123
+ ? `${answers.owner}/${answers.repo}`
124
+ : 'the GitHub repository';
125
+ const e = entryFor(PHASE_GROUPS.GITHUB_ADMIN, false);
126
+ return [
127
+ e(
128
+ `${repoSlug} (repo)`,
129
+ 'create',
130
+ 'Create the GitHub repository (gh repo create --source=. --push) when absent. No-op when already pushed.',
131
+ ),
132
+ e(
133
+ `${repoSlug} labels`,
134
+ 'create',
135
+ 'Create the framework ticket-lifecycle labels (type::*, agent::*, meta::*, …).',
136
+ ),
137
+ e(
138
+ `${repoSlug} Projects V2`,
139
+ 'configure',
140
+ 'Create/adopt the Projects V2 board, status field, and saved views.',
141
+ ),
142
+ e(
143
+ `${repoSlug} branch protection`,
144
+ 'configure',
145
+ 'Apply the required-status-check branch-protection rule to the base branch.',
146
+ ),
147
+ e(
148
+ `${repoSlug} merge methods`,
149
+ 'configure',
150
+ 'Set the allowed pull-request merge methods to the framework stance (squash-only, auto-merge enabled).',
151
+ ),
152
+ ];
153
+ }
154
+
47
155
  /**
48
156
  * File targets are POSIX paths so output is platform-identical; the group
49
157
  * set honours the same flags the executing pipeline does.
@@ -55,149 +163,10 @@ export const MANIFEST_ENTRY_FIELDS = Object.freeze([
55
163
  * @returns {MutationManifestEntry[]}
56
164
  */
57
165
  export function buildMutationManifest(ctx = {}) {
58
- const rel = (...parts) => path.posix.join(...parts);
59
-
60
- const entries = [];
61
-
62
- entries.push(
63
- {
64
- phaseGroup: PHASE_GROUPS.IDE_WIRING,
65
- target: rel('AGENTS.md'),
66
- action: 'merge',
67
- detail:
68
- 'Wire the @.agents/instructions.md system-prompt import into AGENTS.md (folding any CLAUDE.md into it) so Claude Code hydrates the framework on cold start.',
69
- reversible: true,
70
- },
71
- {
72
- phaseGroup: PHASE_GROUPS.IDE_WIRING,
73
- target: rel('.claude', 'commands'),
74
- action: 'run',
75
- detail:
76
- 'Generate the flat command surface (/<name>) from .agents/workflows/.',
77
- reversible: true,
78
- },
79
- {
80
- phaseGroup: PHASE_GROUPS.IDE_WIRING,
81
- target: rel('.gitignore'),
82
- action: 'merge',
83
- detail:
84
- 'Ignore the .claude/commands/ and .claude/agents/ projections (generated by prepare), .mcp.json + .env (carry secrets), and the per-clone install ledger.',
85
- reversible: true,
86
- },
87
- );
88
-
89
- // git-init is the most irreversible local mutation; the ledger must record it.
90
- entries.push(
91
- {
92
- phaseGroup: PHASE_GROUPS.REPO_CONFIG,
93
- target: rel('.git'),
94
- action: 'run',
95
- detail:
96
- 'Initialize the local git repository (git init + first commit) when absent. No-op when already a git repo.',
97
- reversible: false,
98
- },
99
- {
100
- phaseGroup: PHASE_GROUPS.REPO_CONFIG,
101
- target: rel('package.json'),
102
- action: 'merge',
103
- detail:
104
- 'Seed/merge the sync:commands, sync:agents, prepare, and bootstrap npm scripts. `prepare` is guarded: it exits 0 without writing when .agents/scripts/ is absent (a manifest-only container `npm ci`), and otherwise regenerates the .claude/commands/ and .claude/agents/ projections — both gitignored.',
105
- reversible: true,
106
- },
107
- {
108
- phaseGroup: PHASE_GROUPS.REPO_CONFIG,
109
- target: rel('.agentrc.json'),
110
- action: 'create',
111
- detail:
112
- 'Seed .agentrc.json from the bundled starter with the operator-supplied owner/repo/handle/base-branch.',
113
- reversible: true,
114
- },
115
- {
116
- phaseGroup: PHASE_GROUPS.REPO_CONFIG,
117
- target: rel('.github', 'ISSUE_TEMPLATE'),
118
- action: 'create',
119
- detail:
120
- 'Generate the Story/Epic GitHub Issue Forms from the body SSOT so human-filed tickets round-trip through story-body.parse(). Operator-edited forms are preserved.',
121
- reversible: true,
122
- },
123
- );
124
-
125
- if (ctx.withQuality) {
126
- entries.push(
127
- {
128
- phaseGroup: PHASE_GROUPS.QUALITY_GATES,
129
- target: rel('.husky', 'pre-commit'),
130
- action: 'configure',
131
- detail:
132
- 'Install the quality:preview pre-commit hook that blocks MI/CRAP drift at commit time.',
133
- reversible: true,
134
- },
135
- {
136
- phaseGroup: PHASE_GROUPS.QUALITY_GATES,
137
- target: rel('package.json'),
138
- action: 'merge',
139
- detail: 'Add the quality:preview and quality:watch npm scripts.',
140
- reversible: true,
141
- },
142
- {
143
- phaseGroup: PHASE_GROUPS.QUALITY_GATES,
144
- target: rel('.agentrc.json'),
145
- action: 'merge',
146
- detail:
147
- 'Seed delivery.quality coding-guardrails and auto-refresh defaults.',
148
- reversible: true,
149
- },
150
- );
151
- }
152
-
153
- if (!ctx.skipGithub) {
154
- const repoSlug =
155
- ctx.answers?.owner && ctx.answers?.repo
156
- ? `${ctx.answers.owner}/${ctx.answers.repo}`
157
- : 'the GitHub repository';
158
- entries.push(
159
- {
160
- phaseGroup: PHASE_GROUPS.GITHUB_ADMIN,
161
- target: `${repoSlug} (repo)`,
162
- action: 'create',
163
- detail:
164
- 'Create the GitHub repository (gh repo create --source=. --push) when absent. No-op when already pushed.',
165
- reversible: false,
166
- },
167
- {
168
- phaseGroup: PHASE_GROUPS.GITHUB_ADMIN,
169
- target: `${repoSlug} labels`,
170
- action: 'create',
171
- detail:
172
- 'Create the framework ticket-lifecycle labels (type::*, agent::*, meta::*, …).',
173
- reversible: false,
174
- },
175
- {
176
- phaseGroup: PHASE_GROUPS.GITHUB_ADMIN,
177
- target: `${repoSlug} Projects V2`,
178
- action: 'configure',
179
- detail:
180
- 'Create/adopt the Projects V2 board, status field, and saved views.',
181
- reversible: false,
182
- },
183
- {
184
- phaseGroup: PHASE_GROUPS.GITHUB_ADMIN,
185
- target: `${repoSlug} branch protection`,
186
- action: 'configure',
187
- detail:
188
- 'Apply the required-status-check branch-protection rule to the base branch.',
189
- reversible: false,
190
- },
191
- {
192
- phaseGroup: PHASE_GROUPS.GITHUB_ADMIN,
193
- target: `${repoSlug} merge methods`,
194
- action: 'configure',
195
- detail:
196
- 'Set the allowed pull-request merge methods to the framework stance (squash-only, auto-merge enabled).',
197
- reversible: false,
198
- },
199
- );
200
- }
201
-
202
- return entries;
166
+ return [
167
+ ...ideWiringEntries(),
168
+ ...repoConfigEntries(),
169
+ ...(ctx.withQuality ? qualityGateEntries() : []),
170
+ ...(ctx.skipGithub ? [] : githubAdminEntries(ctx.answers)),
171
+ ];
203
172
  }