mandrel 2.89.0 → 2.91.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 (175) hide show
  1. package/.agents/README.md +47 -7
  2. package/.agents/agents/story-worker.md +20 -0
  3. package/.agents/audit-checklists/lean.md +26 -0
  4. package/.agents/docs/agentrc-reference.json +5 -6
  5. package/.agents/docs/configuration.md +38 -30
  6. package/.agents/docs/workflows.md +7 -1
  7. package/.agents/instructions.md +3 -1
  8. package/.agents/runtime-deps.json +0 -2
  9. package/.agents/schemas/agentrc.schema.json +46 -45
  10. package/.agents/schemas/audit-rules.json +19 -0
  11. package/.agents/scripts/acceptance-eval.js +2 -6
  12. package/.agents/scripts/audit-exceptions.js +2 -4
  13. package/.agents/scripts/board-backfill.js +253 -0
  14. package/.agents/scripts/check-arch-cycles.js +1 -5
  15. package/.agents/scripts/check-context-budget.js +1 -5
  16. package/.agents/scripts/check-cyclomatic.js +1 -5
  17. package/.agents/scripts/check-dead-exports.js +23 -14
  18. package/.agents/scripts/check-doc-links.js +4 -4
  19. package/.agents/scripts/check-test-temp-hygiene.js +29 -33
  20. package/.agents/scripts/coverage-capture.js +14 -6
  21. package/.agents/scripts/diagnose-friction.js +8 -10
  22. package/.agents/scripts/generate-workflows-doc.js +5 -0
  23. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +2 -0
  24. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +36 -27
  25. package/.agents/scripts/lib/audit-exceptions/adapters/shortcut-markers.js +70 -0
  26. package/.agents/scripts/lib/audit-exceptions/adapters/source-scan.js +26 -0
  27. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  28. package/.agents/scripts/lib/baseline-schema-registry.js +3 -5
  29. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +11 -28
  30. package/.agents/scripts/lib/baselines/components.js +5 -5
  31. package/.agents/scripts/lib/baselines/crap-preview-scan.js +4 -1
  32. package/.agents/scripts/lib/baselines/crap-updater-cli.js +6 -4
  33. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -10
  34. package/.agents/scripts/lib/baselines/kinds/crap.js +4 -2
  35. package/.agents/scripts/lib/baselines/kinds/duplication.js +4 -2
  36. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +13 -6
  37. package/.agents/scripts/lib/baselines/refresh-service.js +10 -13
  38. package/.agents/scripts/lib/baselines/writer.js +4 -4
  39. package/.agents/scripts/lib/bdd-scenario-scanner.js +26 -31
  40. package/.agents/scripts/lib/bootstrap/gh-list.js +4 -5
  41. package/.agents/scripts/lib/bootstrap/gh-preflight.js +13 -8
  42. package/.agents/scripts/lib/child-exec.js +4 -4
  43. package/.agents/scripts/lib/claude/agents-projection.js +170 -0
  44. package/.agents/scripts/lib/claude/commands-projection.js +184 -0
  45. package/.agents/scripts/lib/close-validation/commands.js +28 -117
  46. package/.agents/scripts/lib/close-validation/gates.js +54 -48
  47. package/.agents/scripts/lib/close-validation/process.js +5 -1
  48. package/.agents/scripts/lib/close-validation/projections/crap.js +2 -1
  49. package/.agents/scripts/lib/close-validation/projections/maintainability.js +50 -15
  50. package/.agents/scripts/lib/config/agentrc-overlay.js +4 -7
  51. package/.agents/scripts/lib/config/commands.js +82 -7
  52. package/.agents/scripts/lib/config/explain.js +2 -1
  53. package/.agents/scripts/lib/config/gates/coverage.schema.js +39 -3
  54. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  55. package/.agents/scripts/lib/config/gates/crap.schema.js +5 -3
  56. package/.agents/scripts/lib/config/gates/duplication.schema.js +6 -11
  57. package/.agents/scripts/lib/config/gates/shared.js +2 -2
  58. package/.agents/scripts/lib/config/git-roots.js +120 -0
  59. package/.agents/scripts/lib/config/quality.js +46 -50
  60. package/.agents/scripts/lib/config/review-chain-default.js +4 -3
  61. package/.agents/scripts/lib/config/review-provider-clis.js +11 -0
  62. package/.agents/scripts/lib/config/temp-paths.js +3 -37
  63. package/.agents/scripts/lib/config-resolver.js +5 -9
  64. package/.agents/scripts/lib/config-settings-schema-delivery.js +2 -2
  65. package/.agents/scripts/lib/config-settings-schema-quality.js +3 -2
  66. package/.agents/scripts/lib/config-settings-schema.js +6 -7
  67. package/.agents/scripts/lib/coverage-baseline.js +2 -1
  68. package/.agents/scripts/lib/coverage-capture-affected.js +4 -3
  69. package/.agents/scripts/lib/coverage-capture-fullscope.js +3 -1
  70. package/.agents/scripts/lib/coverage-capture-passes.js +119 -34
  71. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  72. package/.agents/scripts/lib/coverage-capture.js +80 -43
  73. package/.agents/scripts/lib/coverage-utils.js +34 -16
  74. package/.agents/scripts/lib/cpu-pool.js +2 -4
  75. package/.agents/scripts/lib/crap-engine.js +19 -1
  76. package/.agents/scripts/lib/crap-utils.js +2 -1
  77. package/.agents/scripts/lib/dead-exports-knip.js +29 -11
  78. package/.agents/scripts/lib/detect-package-manager.js +13 -0
  79. package/.agents/scripts/lib/feedback-loop/graduator-gh.js +4 -2
  80. package/.agents/scripts/lib/full-suite-lock.js +25 -9
  81. package/.agents/scripts/lib/gates/baseline-store.js +2 -10
  82. package/.agents/scripts/lib/generated/agentrc-validator.js +4 -1
  83. package/.agents/scripts/lib/gh-env.js +72 -0
  84. package/.agents/scripts/lib/gh-exec.js +26 -1
  85. package/.agents/scripts/lib/maintainability-utils.js +8 -8
  86. package/.agents/scripts/lib/npm-scripts.js +1 -1
  87. package/.agents/scripts/lib/observability/signal-validator.js +2 -6
  88. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  89. package/.agents/scripts/lib/observability/terse-result.js +2 -6
  90. package/.agents/scripts/lib/orchestration/board-access-latch.js +112 -0
  91. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +10 -13
  92. package/.agents/scripts/lib/orchestration/column-sync.js +107 -52
  93. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  94. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +3 -3
  95. package/.agents/scripts/lib/orchestration/lifecycle/emit-ledger-event.js +2 -6
  96. package/.agents/scripts/lib/orchestration/light-suitability.js +5 -7
  97. package/.agents/scripts/lib/orchestration/pr-watch.js +7 -7
  98. package/.agents/scripts/lib/orchestration/project-meta-cache.js +2 -11
  99. package/.agents/scripts/lib/orchestration/project-meta-resolver.js +44 -17
  100. package/.agents/scripts/lib/orchestration/review-deposit.js +2 -9
  101. package/.agents/scripts/lib/orchestration/review-providers/callers-context.js +219 -0
  102. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +53 -5
  103. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +2 -2
  104. package/.agents/scripts/lib/orchestration/review-providers/llm-review.js +96 -0
  105. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  106. package/.agents/scripts/lib/orchestration/review-providers/native.js +13 -19
  107. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +3 -2
  108. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +2 -0
  109. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +11 -3
  110. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -3
  111. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  112. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  113. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  114. package/.agents/scripts/lib/orchestration/story-handoff.js +27 -6
  115. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  116. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  117. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  118. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  119. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  120. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  121. package/.agents/scripts/lib/source-extensions.js +30 -15
  122. package/.agents/scripts/lib/test-run-credit.js +1 -9
  123. package/.agents/scripts/lib/test-temp.js +22 -21
  124. package/.agents/scripts/lib/util/ajv.js +111 -0
  125. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  126. package/.agents/scripts/lib/util/paths.js +51 -0
  127. package/.agents/scripts/lib/util/sleep.js +6 -0
  128. package/.agents/scripts/lib/util/slug.js +12 -0
  129. package/.agents/scripts/lib/validation-evidence.js +19 -40
  130. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  131. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  132. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  133. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  134. package/.agents/scripts/lint-issue-body.js +2 -2
  135. package/.agents/scripts/plan-context.js +2 -7
  136. package/.agents/scripts/providers/github/auth.js +3 -3
  137. package/.agents/scripts/providers/github/board-add.js +18 -9
  138. package/.agents/scripts/providers/github/errors.js +3 -1
  139. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  140. package/.agents/scripts/providers/github/issues.js +6 -2
  141. package/.agents/scripts/providers/github/mappers.js +1 -5
  142. package/.agents/scripts/providers/github/projects-v2-graphql.js +26 -6
  143. package/.agents/scripts/providers/github/search-budget.js +3 -1
  144. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  145. package/.agents/scripts/sync-agentrc.js +5 -14
  146. package/.agents/scripts/sync-claude-agents.js +38 -150
  147. package/.agents/scripts/sync-claude-commands.js +35 -218
  148. package/.agents/scripts/update-coverage-baseline.js +1 -1
  149. package/.agents/scripts/update-crap-baseline.js +1 -1
  150. package/.agents/scripts/update-duplication-baseline.js +2 -16
  151. package/.agents/scripts/validate-skills.js +6 -10
  152. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  153. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  154. package/.agents/workflows/audit-exceptions.md +9 -0
  155. package/.agents/workflows/audit-lean.md +129 -0
  156. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  157. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  158. package/.agents/workflows/helpers/code-review.md +15 -1
  159. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  160. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  161. package/.agents/workflows/mandrel-plan.md +2 -2
  162. package/docs/CHANGELOG.md +48 -0
  163. package/lib/cli/doctor-checks/codex.js +6 -5
  164. package/lib/cli/doctor-checks/llm-review.js +102 -0
  165. package/lib/cli/doctor-checks/project-access.js +124 -0
  166. package/lib/cli/doctor-checks/sync-parity.js +65 -140
  167. package/lib/cli/doctor-checks/test-credit-path.js +69 -28
  168. package/lib/cli/doctor-checks/toolchain.js +5 -3
  169. package/lib/cli/registry.js +11 -0
  170. package/lib/migrations/helpers/retire-agentrc-key.js +3 -3
  171. package/lib/migrations/index.js +6 -0
  172. package/lib/migrations/steps/2.91.0-move-shared-crap-capture-script.js +84 -0
  173. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +23 -0
  174. package/lib/migrations/steps/2.91.0-unset-null-lint-command.js +54 -0
  175. package/package.json +1 -3
@@ -0,0 +1,253 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * board-backfill.js — add open Stories/Epics missing from the Projects v2
5
+ * board and sync each Story's Status from its `agent::*` label. Idempotent.
6
+ */
7
+
8
+ import { parseArgs } from 'node:util';
9
+
10
+ import { runAsCli } from './lib/cli-utils.js';
11
+ import { resolveConfig } from './lib/config-resolver.js';
12
+ import { Logger, routeAllOutputToStderr } from './lib/Logger.js';
13
+ import {
14
+ isProjectAccessFailure,
15
+ toProjectAccessError,
16
+ } from './lib/orchestration/board-access-latch.js';
17
+ import {
18
+ ColumnSync,
19
+ columnForLabels,
20
+ } from './lib/orchestration/column-sync.js';
21
+ import {
22
+ ProjectAccessError,
23
+ resolveProjectMeta,
24
+ } from './lib/orchestration/project-meta-resolver.js';
25
+ import { createProvider } from './lib/provider-factory.js';
26
+
27
+ const BOARD_TYPE_LABELS = Object.freeze(['type::story', 'type::epic']);
28
+
29
+ const OPEN_ISSUES_QUERY = `
30
+ query($owner: String!, $repo: String!, $label: String!, $after: String) {
31
+ repository(owner: $owner, name: $repo) {
32
+ issues(states: OPEN, labels: [$label], first: 100, after: $after) {
33
+ pageInfo { hasNextPage endCursor }
34
+ nodes {
35
+ number
36
+ id
37
+ labels(first: 50) { nodes { name } }
38
+ projectItems(first: 20) {
39
+ nodes {
40
+ id
41
+ project { id }
42
+ fieldValueByName(name: "Status") {
43
+ ... on ProjectV2ItemFieldSingleSelectValue { name }
44
+ }
45
+ }
46
+ }
47
+ }
48
+ }
49
+ }
50
+ }`;
51
+
52
+ const ADD_ITEM_MUTATION = `
53
+ mutation($projectId: ID!, $contentId: ID!) {
54
+ addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) {
55
+ item { id }
56
+ }
57
+ }`;
58
+
59
+ /**
60
+ * Raise a scope/auth refusal as the typed error; return anything else.
61
+ *
62
+ * @param {unknown} err
63
+ * @returns {unknown}
64
+ */
65
+ function classify(err) {
66
+ if (isProjectAccessFailure(err)) throw toProjectAccessError(err);
67
+ return err;
68
+ }
69
+
70
+ /**
71
+ * Open issues carrying any board type label, deduped by number.
72
+ *
73
+ * @param {{ graphql: Function, owner: string, repo: string }} provider
74
+ * @returns {Promise<Array<{ number: number, nodeId: string, labels: string[], items: object[] }>>}
75
+ */
76
+ export async function listBoardCandidates(provider) {
77
+ const byNumber = new Map();
78
+ for (const label of BOARD_TYPE_LABELS) {
79
+ let after = null;
80
+ do {
81
+ let data;
82
+ try {
83
+ data = await provider.graphql(OPEN_ISSUES_QUERY, {
84
+ owner: provider.owner,
85
+ repo: provider.repo,
86
+ label,
87
+ after,
88
+ });
89
+ } catch (err) {
90
+ throw classify(err);
91
+ }
92
+ const page = data?.repository?.issues;
93
+ for (const node of page?.nodes ?? []) {
94
+ if (!node || byNumber.has(node.number)) continue;
95
+ byNumber.set(node.number, {
96
+ number: node.number,
97
+ nodeId: node.id,
98
+ labels: (node.labels?.nodes ?? []).map((l) => l.name),
99
+ items: node.projectItems?.nodes ?? [],
100
+ });
101
+ }
102
+ after = page?.pageInfo?.hasNextPage ? page.pageInfo.endCursor : null;
103
+ } while (after);
104
+ }
105
+ return [...byNumber.values()].sort((a, b) => a.number - b.number);
106
+ }
107
+
108
+ /**
109
+ * What the board needs for one issue: an add, a Status sync, both, or
110
+ * nothing. Epics never get a Status target here.
111
+ *
112
+ * @param {{ labels: string[], items: object[] }} issue
113
+ * @param {string} projectId
114
+ */
115
+ export function planIssue(issue, projectId) {
116
+ const isEpic = issue.labels.includes('type::epic');
117
+ const target = isEpic ? null : columnForLabels(issue.labels);
118
+ const item = issue.items.find((n) => n?.project?.id === projectId);
119
+ const current = item?.fieldValueByName?.name ?? null;
120
+ return {
121
+ number: issue.number,
122
+ type: isEpic ? 'epic' : 'story',
123
+ add: !item,
124
+ status: target && target !== current ? target : null,
125
+ };
126
+ }
127
+
128
+ /**
129
+ * @param {{
130
+ * provider: { graphql: Function, owner: string, repo: string, projectNumber?: number|null, projectOwner?: string|null },
131
+ * config?: object,
132
+ * dryRun?: boolean,
133
+ * columnSync?: { sync: Function },
134
+ * }} args
135
+ * @returns {Promise<{ dryRun: boolean, added: number, synced: number, skipped: number, failed: number, planned: object[] }>}
136
+ * @throws {ProjectAccessError} when the token cannot read or write the board.
137
+ */
138
+ export async function runBackfill({
139
+ provider,
140
+ config,
141
+ dryRun = false,
142
+ columnSync,
143
+ }) {
144
+ const projectNumber =
145
+ config?.github?.projectNumber ?? provider.projectNumber ?? null;
146
+ if (!projectNumber) {
147
+ throw new Error(
148
+ 'No github.projectNumber configured — nothing to backfill.',
149
+ );
150
+ }
151
+ const project = await resolveProjectMeta({
152
+ provider,
153
+ owner: provider.projectOwner ?? provider.owner ?? null,
154
+ projectNumber,
155
+ projectFields: 'id',
156
+ });
157
+ if (!project) {
158
+ throw new Error(`Project #${projectNumber} not found.`);
159
+ }
160
+ const sync =
161
+ columnSync ??
162
+ new ColumnSync({ provider, projectNumber, logger: Logger, config });
163
+ const summary = { dryRun, added: 0, synced: 0, skipped: 0, failed: 0 };
164
+ const planned = [];
165
+ for (const issue of await listBoardCandidates(provider)) {
166
+ const plan = planIssue(issue, project.id);
167
+ if (!plan.add && !plan.status) {
168
+ summary.skipped += 1;
169
+ continue;
170
+ }
171
+ planned.push(plan);
172
+ if (dryRun) continue;
173
+ await applyPlan({
174
+ plan,
175
+ issue,
176
+ provider,
177
+ projectId: project.id,
178
+ sync,
179
+ summary,
180
+ });
181
+ }
182
+ return { ...summary, planned };
183
+ }
184
+
185
+ async function applyPlan({ plan, issue, provider, projectId, sync, summary }) {
186
+ if (plan.add) {
187
+ try {
188
+ await provider.graphql(ADD_ITEM_MUTATION, {
189
+ projectId,
190
+ contentId: issue.nodeId,
191
+ });
192
+ summary.added += 1;
193
+ } catch (err) {
194
+ classify(err);
195
+ Logger.warn(
196
+ `[board-backfill] could not add #${issue.number}: ${err?.message ?? err}`,
197
+ );
198
+ summary.failed += 1;
199
+ return;
200
+ }
201
+ }
202
+ if (!plan.status) return;
203
+ const result = await sync
204
+ .sync(issue.number, issue.labels)
205
+ .catch((err) => ({ status: 'failed', error: classify(err) }));
206
+ if (result?.reason === 'insufficient-scope') {
207
+ throw toProjectAccessError(new Error('Status update refused'));
208
+ }
209
+ if (result?.status === 'synced') summary.synced += 1;
210
+ else summary.failed += 1;
211
+ }
212
+
213
+ /* node:coverage ignore next */
214
+ export async function main(argv = process.argv.slice(2)) {
215
+ const { values } = parseArgs({
216
+ args: argv,
217
+ options: { 'dry-run': { type: 'boolean', default: false } },
218
+ strict: true,
219
+ });
220
+ routeAllOutputToStderr();
221
+ const config = resolveConfig();
222
+ const provider = createProvider(config);
223
+ try {
224
+ const result = await runBackfill({
225
+ provider,
226
+ config,
227
+ dryRun: values['dry-run'],
228
+ });
229
+ process.stdout.write(`${JSON.stringify(result)}\n`);
230
+ } catch (err) {
231
+ if (err instanceof ProjectAccessError) {
232
+ process.stderr.write(
233
+ `[board-backfill] ${err.message}\nRemedy: ${err.remedy}\n`,
234
+ );
235
+ process.exitCode = 1;
236
+ return;
237
+ }
238
+ throw err;
239
+ }
240
+ }
241
+
242
+ runAsCli(import.meta.url, main, {
243
+ source: 'board-backfill',
244
+ usage: {
245
+ invocation: 'node .agents/scripts/board-backfill.js [--dry-run]',
246
+ summary:
247
+ "Add open type::story / type::epic issues missing from the configured Projects v2 board and sync each Story's Status from its agent::* label. Idempotent; prints a JSON summary { added, synced, skipped, failed } on stdout.",
248
+ flags: [
249
+ ['--dry-run', 'List what would be added or synced; change nothing.'],
250
+ ['--help', 'Show this message.'],
251
+ ],
252
+ },
253
+ });
@@ -220,11 +220,7 @@ export async function runCli({
220
220
  return exitCode;
221
221
  }
222
222
 
223
- async function main() {
224
- return runCli();
225
- }
226
-
227
- runAsCli(import.meta.url, main, {
223
+ runAsCli(import.meta.url, runCli, {
228
224
  source: 'arch-cycles',
229
225
  propagateExitCode: true,
230
226
  errorPrefix: '[arch-cycles] ❌ Fatal error',
@@ -467,11 +467,7 @@ export async function runCli({
467
467
  return report.exitCode;
468
468
  }
469
469
 
470
- async function main() {
471
- return runCli();
472
- }
473
-
474
- runAsCli(import.meta.url, main, {
470
+ runAsCli(import.meta.url, runCli, {
475
471
  source: 'context-budget',
476
472
  propagateExitCode: true,
477
473
  errorPrefix: '[context-budget] ❌ Fatal error',
@@ -198,11 +198,7 @@ export async function runCli({
198
198
  return exitCode;
199
199
  }
200
200
 
201
- async function main() {
202
- return runCli();
203
- }
204
-
205
- runAsCli(import.meta.url, main, {
201
+ runAsCli(import.meta.url, runCli, {
206
202
  source: 'cyclomatic',
207
203
  propagateExitCode: true,
208
204
  errorPrefix: '[cyclomatic] ❌ Fatal error',
@@ -1,9 +1,8 @@
1
1
  /**
2
2
  * CLI: ratchet-down dead-export gate built on knip. Diffs knip's unused
3
3
  * exports — plus a `{ file, symbol: '*' }` row per module nothing imports —
4
- * against `baselines/dead-exports.json` by `(file, symbol)`. Exit 1 only on an
5
- * added row; a knip spawn/parse failure is advisory (exit 0 + warning) so a
6
- * broken knip cannot block CI.
4
+ * against `baselines/dead-exports.json` by `(file, symbol)`. Exit 1 on an
5
+ * added row; exit 2 when knip produced no report (fail closed).
7
6
  *
8
7
  * `--production` discounts test-only importers (production-dead code hides
9
8
  * behind its own tests) and uses its own baseline — see
@@ -67,6 +66,8 @@ export function diffRows(baselineRows, currentRows) {
67
66
  };
68
67
  }
69
68
 
69
+ const EXIT = Object.freeze({ CLEAN: 0, ADDED: 1, KNIP_FAILED: 2 });
70
+
70
71
  /**
71
72
  * `+`/`-` rows then a summary line. `label` tells the two back-to-back passes
72
73
  * apart in CI logs.
@@ -95,7 +96,7 @@ export function renderDiff(diff, label = 'dead-exports') {
95
96
  * runKnipImpl?: typeof runKnip,
96
97
  * loadBaselineImpl?: typeof readJsonBaseline,
97
98
  * }} [opts]
98
- * @returns {Promise<number>} exit code: 0 = clean or removals-only; 1 = added exports detected
99
+ * @returns {Promise<number>} exit code: 0 = clean or removals-only; 1 = added exports detected; 2 = no knip report
99
100
  */
100
101
  export async function runCli({
101
102
  argv = process.argv.slice(2),
@@ -135,7 +136,7 @@ export async function runCli({
135
136
  const currentRows = extractRowsFromKnip(knipEnvelope);
136
137
  const diff = diffRows(baselineRows, currentRows);
137
138
 
138
- const exitCode = knipError === null && diff.added.length > 0 ? 1 : 0;
139
+ const exitCode = gateExitCode(knipError, diff);
139
140
 
140
141
  if (json) {
141
142
  const envelope = {
@@ -156,21 +157,29 @@ export async function runCli({
156
157
  `[${label}] ⚠ baseline not found at ${resolvedBaselinePath} — treating as empty\n`,
157
158
  );
158
159
  }
159
- if (knipError) {
160
- stderr.write(`[${label}] ⚠ knip run failed: ${knipError}\n`);
161
- }
162
- stdout.write(`\n--- ${label} preview ---\n`);
163
- stdout.write(`${renderDiff(diff, label)}\n`);
160
+ writeTextReport({ stdout, stderr, label, knipError, diff });
164
161
  }
165
162
 
166
163
  return exitCode;
167
164
  }
168
165
 
169
- async function main() {
170
- return runCli();
166
+ function gateExitCode(knipError, diff) {
167
+ if (knipError !== null) return EXIT.KNIP_FAILED;
168
+ return diff.added.length > 0 ? EXIT.ADDED : EXIT.CLEAN;
169
+ }
170
+
171
+ /** A failed knip run has no meaningful diff, so it prints the failure alone. */
172
+ function writeTextReport({ stdout, stderr, label, knipError, diff }) {
173
+ if (knipError) {
174
+ stderr.write(`[${label}] ❌ knip run failed: ${knipError}\n`);
175
+ stdout.write(`! knip run failed: ${knipError} (gate fail)\n`);
176
+ return;
177
+ }
178
+ stdout.write(`\n--- ${label} preview ---\n`);
179
+ stdout.write(`${renderDiff(diff, label)}\n`);
171
180
  }
172
181
 
173
- runAsCli(import.meta.url, main, {
182
+ runAsCli(import.meta.url, runCli, {
174
183
  source: 'dead-exports',
175
184
  propagateExitCode: true,
176
185
  errorPrefix: '[dead-exports] ❌ Fatal error',
@@ -192,7 +201,7 @@ runAsCli(import.meta.url, main, {
192
201
  ['--json', 'Emit the comparison envelope as JSON.'],
193
202
  ],
194
203
  notes: [
195
- 'Exit codes:\n 0 clean, or removals only\n 1 newly added unused exports',
204
+ 'Exit codes:\n 0 clean, or removals only\n 1 newly added unused exports\n 2 knip produced no report (spawn error, overflow, error exit, empty or unparseable output)',
196
205
  ],
197
206
  },
198
207
  });
@@ -8,7 +8,7 @@
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
- import { minimatch } from 'minimatch';
11
+ import picomatch from 'picomatch';
12
12
  import { parseStandardCliArgs } from './lib/cli/standard-args.js';
13
13
  import { runAsCli } from './lib/cli-utils.js';
14
14
  import { Logger } from './lib/Logger.js';
@@ -155,7 +155,7 @@ function walkMarkdown(dirAbs, repoRoot, out) {
155
155
  /**
156
156
  * @param {string} rootAbs
157
157
  * @param {string[]} scanRoots
158
- * @param {string[]} [exclude] minimatch globs over repo-relative POSIX paths
158
+ * @param {string[]} [exclude] picomatch globs over repo-relative POSIX paths
159
159
  */
160
160
  export function discoverMarkdown(rootAbs, scanRoots, exclude = []) {
161
161
  const out = [];
@@ -166,7 +166,7 @@ export function discoverMarkdown(rootAbs, scanRoots, exclude = []) {
166
166
  const filtered = exclude.length
167
167
  ? out.filter((abs) => {
168
168
  const rel = path.relative(rootAbs, abs).split(path.sep).join('/');
169
- return !exclude.some((g) => minimatch(rel, g, { dot: true }));
169
+ return !exclude.some((g) => picomatch.isMatch(rel, g, { dot: true }));
170
170
  })
171
171
  : out;
172
172
  filtered.sort();
@@ -459,7 +459,7 @@ runAsCli(import.meta.url, main, {
459
459
  ],
460
460
  [
461
461
  '--exclude <glob>',
462
- 'Repeatable. minimatch glob; matching files are dropped from the scan.',
462
+ 'Repeatable. picomatch glob; matching files are dropped from the scan.',
463
463
  ],
464
464
  ],
465
465
  notes: [
@@ -21,6 +21,7 @@ import {
21
21
  import os from 'node:os';
22
22
  import path from 'node:path';
23
23
  import { fileURLToPath } from 'node:url';
24
+ import { parseGateArgv } from './lib/cli-args.js';
24
25
  import { runAsCli } from './lib/cli-utils.js';
25
26
  import { mainCheckoutRoot } from './lib/config/temp-paths.js';
26
27
  import {
@@ -326,44 +327,39 @@ export function assertNoReservedIdStreams({
326
327
  return 1;
327
328
  }
328
329
 
330
+ const MODE_FLAGS = ['--snapshot', '--assert', '--clean'];
331
+
329
332
  /**
330
333
  * @param {string[]} argv
331
334
  * @returns {{ mode: 'snapshot'|'assert'|'clean', apply: boolean, ids: number[]|null, repoRoot: string, baseline: string|null, lintGlobs: string[] }}
332
335
  */
333
336
  export function parseArgv(argv) {
334
- let mode = 'assert';
335
- let apply = false;
336
- let ids = null;
337
- let repoRoot = REPO_ROOT;
338
- let baseline = null;
339
- let lintGlobs = [];
340
- for (let i = 0; i < argv.length; i += 1) {
341
- const arg = argv[i];
342
- if (arg === '--snapshot') mode = 'snapshot';
343
- else if (arg === '--assert') mode = 'assert';
344
- else if (arg === '--clean') mode = 'clean';
345
- else if (arg === '--yes') apply = true;
346
- else if (arg === '--lint-globs') {
347
- i += 1;
348
- lintGlobs = String(argv[i] ?? '')
349
- .split(',')
350
- .map((s) => s.trim())
351
- .filter(Boolean);
352
- } else if (arg === '--ids') {
353
- i += 1;
354
- ids = String(argv[i] ?? '')
355
- .split(',')
356
- .map((s) => Number(s.trim()))
357
- .filter((n) => Number.isInteger(n) && n > 0);
358
- } else if (arg === '--root') {
359
- i += 1;
360
- repoRoot = path.resolve(String(argv[i] ?? '.'));
361
- } else if (arg === '--baseline') {
362
- i += 1;
363
- baseline = path.resolve(String(argv[i] ?? '.'));
364
- }
365
- }
366
- return { mode, apply, ids, repoRoot, baseline, lintGlobs };
337
+ const values = parseGateArgv(argv, {
338
+ strings: ['lint-globs', 'ids', 'root', 'baseline'],
339
+ booleans: ['yes'],
340
+ });
341
+ const modeFlag = argv.filter((arg) => MODE_FLAGS.includes(arg)).at(-1);
342
+ return {
343
+ mode: modeFlag ? modeFlag.slice(2) : 'assert',
344
+ apply: values.yes,
345
+ ids:
346
+ values.ids === null
347
+ ? null
348
+ : splitList(values.ids)
349
+ .map(Number)
350
+ .filter((n) => Number.isInteger(n) && n > 0),
351
+ repoRoot: values.root === null ? REPO_ROOT : path.resolve(values.root),
352
+ baseline: values.baseline === null ? null : path.resolve(values.baseline),
353
+ lintGlobs: splitList(values['lint-globs'] ?? ''),
354
+ };
355
+ }
356
+
357
+ /** @param {string} raw */
358
+ function splitList(raw) {
359
+ return raw
360
+ .split(',')
361
+ .map((s) => s.trim())
362
+ .filter(Boolean);
367
363
  }
368
364
 
369
365
  /**
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Ensures `coverage/coverage-final.json` is fresh before the CRAP gate: skip
4
- * when the gate is off, no changed file is under `crap.targetDirs`, or the
5
- * content-digest stamp matches; otherwise run `test:coverage` (or, under
6
- * `coverage.captureScope: "affected"`, the consumer's `test:coverage:affected`)
3
+ * Ensures the coverage artifact (`coverage.coveragePath`) is fresh before the
4
+ * coverage and CRAP gates: skip when both are off, no changed file is under
5
+ * `crap.targetDirs`, or the content-digest stamp matches; otherwise run the
6
+ * coverage gate's `captureScript` as `<pm> run <script>` (or, under
7
+ * `coverage.captureScope: "affected"`, the consumer's affected variant)
7
8
  * behind the host-level full-suite lock and stamp on success. A green run that
8
9
  * leaves no artifact at `coveragePath` fails (exit 1) and is never stamped.
9
10
  * An own CRAP source gets a second, always full-scope pass via
@@ -31,6 +32,7 @@ import {
31
32
  import { tryScopedCapture } from './lib/coverage-capture-affected.js';
32
33
  import { runFullScopeCapture } from './lib/coverage-capture-fullscope.js';
33
34
  import {
35
+ captureGates,
34
36
  captureRefusal,
35
37
  runCapturePasses,
36
38
  } from './lib/coverage-capture-passes.js';
@@ -102,9 +104,15 @@ export async function runCoverageCapture(argv = process.argv, deps = {}) {
102
104
  const lockHooks = lockEventHooks(claimLockEventSink(env));
103
105
  const args = parseArgs(argv);
104
106
  const config = resolveConfigImpl({ cwd: args.cwd });
105
- const { crap, coverage } = getQualityImpl(config);
107
+ const { crap, coverage } = captureGates(getQualityImpl(config));
106
108
  const scripts = readPackageScriptsImpl(args.cwd);
107
- const refused = captureRefusal({ crap, scripts, hasNpmScriptImpl, logger });
109
+ const refused = captureRefusal({
110
+ crap,
111
+ coverage,
112
+ scripts,
113
+ hasNpmScriptImpl,
114
+ logger,
115
+ });
108
116
  if (refused !== null) return refused;
109
117
 
110
118
  // Outermost first: the credit probe announces or refuses the run, and only
@@ -7,10 +7,9 @@
7
7
  * never a ticket comment. With no resolvable Story the write is skipped: a
8
8
  * missing signal beats a halted runner.
9
9
  */
10
- import { spawnSync } from 'node:child_process';
11
10
  import crypto from 'node:crypto';
12
11
  import { constants as osConstants } from 'node:os';
13
- import { INTERCEPTOR_MAX_BUFFER_BYTES } from './lib/child-exec.js';
12
+ import { REPORTED_MAX_BUFFER_BYTES, spawnChild } from './lib/child-exec.js';
14
13
  import { getLimits, resolveConfig } from './lib/config-resolver.js';
15
14
  import { Logger } from './lib/Logger.js';
16
15
  import { appendSignal } from './lib/observability/signals-writer.js';
@@ -85,6 +84,8 @@ const OVERFLOW_ERROR_CODE = 'ENOBUFS';
85
84
 
86
85
  const SIGNAL_EXIT_BASE = 128;
87
86
 
87
+ const BYTES_PER_MIB = 1024 * 1024;
88
+
88
89
  /**
89
90
  * For a `null` status, which must never reach `process.exit` (null exits 0).
90
91
  * SIGTERM + ENOBUFS = buffer overflow, SIGTERM otherwise = timeout, any other
@@ -125,7 +126,7 @@ function describeAbnormalExit(
125
126
  const shapes = {
126
127
  'buffer-overflow': {
127
128
  category: 'Tool Limitation',
128
- remediation: ` - ${signal} was sent because the command's output overflowed the interceptor's executionMaxBuffer bound (${executionMaxBuffer} bytes / 10 MiB) — the executionTimeoutMs bound (${executionTimeoutMs}ms) did not fire. Do NOT split the command into smaller steps: quieten or redirect its output, or raise the buffer bound.`,
129
+ remediation: ` - ${signal} was sent because the command's output overflowed the interceptor's executionMaxBuffer bound (${executionMaxBuffer} bytes / ${executionMaxBuffer / BYTES_PER_MIB} MiB) — the executionTimeoutMs bound (${executionTimeoutMs}ms) did not fire. Do NOT split the command into smaller steps: quieten or redirect its output, or raise the buffer bound.`,
129
130
  extraDetails: { executionMaxBuffer },
130
131
  },
131
132
  'interceptor-timeout': {
@@ -220,18 +221,15 @@ export async function main(args = process.argv.slice(2)) {
220
221
 
221
222
  const config = resolveConfig();
222
223
  const { executionTimeoutMs } = getLimits();
223
- // Deliberately below `MAX_BUFFER_BYTES`: a reported policy bound, not an
224
- // overflow guard.
225
- const executionMaxBuffer = INTERCEPTOR_MAX_BUFFER_BYTES;
224
+ // Reported, never passed: the wrapper applies its own ceiling, so the row
225
+ // names the bound that actually fires on an overflow.
226
+ const executionMaxBuffer = REPORTED_MAX_BUFFER_BYTES;
226
227
 
227
228
  const commandStr = cmdArgs.join(' ');
228
229
  Logger.error(`[Diagnostic Interceptor] Executing: ${commandStr}`);
229
230
 
230
- const result = spawnSync(cmdArgs[0], cmdArgs.slice(1), {
231
- stdio: 'pipe',
232
- encoding: 'utf-8',
231
+ const result = spawnChild(cmdArgs[0], cmdArgs.slice(1), {
233
232
  timeout: executionTimeoutMs,
234
- maxBuffer: executionMaxBuffer,
235
233
  });
236
234
 
237
235
  if (result.stdout) process.stdout.write(result.stdout);
@@ -81,6 +81,11 @@ export function renderWorkflowsDoc(catalog, loopCatalog = []) {
81
81
  '`.agents/skills/workflows/<name>/SKILL.md`, invoked as `$<name>` (e.g.',
82
82
  '`$mandrel-plan`; loop units as `$loops-<name>`). Each skill points Codex at',
83
83
  'the workflow file and passes the text after `$<name>` as its arguments.',
84
+ 'A `$loops-<name>` unit runs once per invocation: Codex has no `/loop`',
85
+ 'cadence, so re-invoke it (or schedule it) to iterate. At close, the default',
86
+ "review chain's `llm-review` entry reviews through `codex exec` when `claude`",
87
+ "is absent (`claude` wins when both are present); `mandrel doctor`'s",
88
+ '`llm-review-provider` check names the CLI that will serve it.',
84
89
  '`npm run sync:agents` likewise writes the role agents a workflow dispatches',
85
90
  '(`subagent_type: <role>`) as Codex custom agents',
86
91
  '`.codex/agents/mandrel-<role>.toml`; Codex loads those only in a trusted',
@@ -13,6 +13,7 @@ import { dependencyPins } from './dependency-pins.js';
13
13
  import { dependencyPolicy } from './dependency-policy.js';
14
14
  import { inlineSuppressions } from './inline-suppressions.js';
15
15
  import { scaExceptions } from './sca-exceptions.js';
16
+ import { shortcutMarkers } from './shortcut-markers.js';
16
17
  import { testSkips } from './test-skips.js';
17
18
  import { toolConfig } from './tool-config.js';
18
19
 
@@ -27,4 +28,5 @@ export const ADAPTERS = Object.freeze([
27
28
  ciGates,
28
29
  testSkips,
29
30
  codeAllowlists,
31
+ shortcutMarkers,
30
32
  ]);