@bensandee/tooling 0.102.0 → 0.104.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.
package/dist/bin.mjs CHANGED
@@ -173,7 +173,7 @@ function loadEnvFileForBin(rawArgs, bin, io = processIo) {
173
173
  // src/env-file-preload.ts
174
174
  const envFileLoad = loadEnvFileForBin(process.argv.slice(2), {
175
175
  name: "bst",
176
- version: "0.102.0"
176
+ version: "0.104.0"
177
177
  });
178
178
  // ../cli-kit/src/logger.ts
179
179
  const RANK = {
@@ -846,6 +846,7 @@ const TolerantDockerCheckConfigSchema = z.object({
846
846
  });
847
847
  const DEFAULT_BRANCH_NAME_PATTERN = /^(?!refs\/)(?!.*\/\/)(?!.*\.\.)(?!.*\/$)(?!.*\.lock$)[A-Za-z0-9][A-Za-z0-9._/-]*$/;
848
848
  const DefaultBranchNameSchema = z.string().regex(DEFAULT_BRANCH_NAME_PATTERN, "must be a plain branch name: ASCII letters, digits, '.', '_', '-' and '/', starting with a letter or digit, with no leading 'refs/', no '//', '..', trailing '/', or '.lock' suffix");
849
+ const TrustedRunnerLabelSchema = z.string().regex(/^(?!ubuntu-latest$)[A-Za-z0-9][A-Za-z0-9._-]*$/, "must be a plain runner label: ASCII letters, digits, '.', '_' and '-', starting with a letter or digit, non-empty, and not 'ubuntu-latest' (the shared label this setting moves work off)");
849
850
  const AgentEnabledSliceSchema = z.looseObject({ agent: z.looseObject({ enabled: z.boolean().optional() }).optional() });
850
851
  function agentEnabledIn(raw) {
851
852
  try {
@@ -1802,6 +1803,7 @@ const ToolingConfigSchema = z.strictObject({
1802
1803
  deploy: DeployConfigSchema.optional().meta({ description: "Generate a deploy-dispatch step in the release workflow that triggers a workflow_dispatch event in another repo after a successful release. The resolved release token must have rights on `dispatchRepo`." }),
1803
1804
  pnpmWorkspace: z.literal(false).optional().meta({ description: "Set to false to opt out of pnpm-workspace.yaml management (skips both generation and the repo:sync --check validation)." }),
1804
1805
  defaultBranch: DefaultBranchNameSchema.optional().meta({ description: "Repository default branch name. Drives the generated CI `on.push` trigger and every default-branch gate in `ci.yml` and `release.yml`, the release path (`release:changesets`, the version PR, `release:trigger`) and `checks:run`'s coverage gate. Generated output uses 'main' when unset; `checks:run` still falls back to `origin/HEAD`. Must be a plain branch name: ASCII letters, digits, '.', '_', '-' and '/', with no leading 'refs/'." }),
1806
+ trustedRunner: TrustedRunnerLabelSchema.optional().meta({ description: "Self-hosted runner label for default-branch CI jobs: they run on this label while pull request jobs stay on 'ubuntu-latest'. Only a workflow edit moves a job, so the runner must be scoped so no other repository can name this label. A job aimed at a label no runner serves waits forever, so set this key only once the runner exists." }),
1805
1807
  unmanagedDevDependencies: UnmanagedDevDependenciesSchema.optional().meta({ description: "devDependency names repo:sync must never add or re-pin. Escape hatch for holding a tooling-managed dep (oxlint, vitest, knip, ...) at a deliberately off-canonical version; without it, repo:sync raises any managed devDep whose version has drifted below the canonical pin." }),
1806
1808
  stack: StackSchema.optional().meta({ description: "Whether the repo has TS/JS source. Detected from source evidence; TypeScript is never inferred from absence. Setting this key pins its value, even one that equals detection, and repo:sync keeps it until the key is deleted." }),
1807
1809
  builder: z.enum([
@@ -4820,6 +4822,10 @@ function branchNameLiteral(name) {
4820
4822
  if (DEFAULT_BRANCH_NAME_PATTERN.test(name)) return name;
4821
4823
  return name.replace(/'/g, "''");
4822
4824
  }
4825
+ const TrustedRunnerSliceSchema = z.object({ trustedRunner: TrustedRunnerLabelSchema.optional() });
4826
+ function configuredTrustedRunner(raw) {
4827
+ return parseToolingConfigSlice(raw, TrustedRunnerSliceSchema, { block: "trustedRunner" })?.trustedRunner;
4828
+ }
4823
4829
  function isDefaultBranch(name) {
4824
4830
  return `github.ref == 'refs/heads/${branchNameLiteral(name)}'`;
4825
4831
  }
@@ -5800,7 +5806,7 @@ function buildManagedDevDeps(ctx) {
5800
5806
  const devDeps = { ...rootDevDeps(ctx.config) };
5801
5807
  if (!isMonorepo) Object.assign(devDeps, perPackageDevDeps(ctx.config));
5802
5808
  if (ctx.config.stack !== "none") devDeps["@bensandee/config"] = isWorkspacePackage(ctx, "@bensandee/config") ? "workspace:*" : "0.15.1";
5803
- if (!isWorkspacePackage(ctx, "@bensandee/tooling")) devDeps["@bensandee/tooling"] = "0.102.0";
5809
+ if (!isWorkspacePackage(ctx, "@bensandee/tooling")) devDeps["@bensandee/tooling"] = "0.104.0";
5804
5810
  if (ctx.config.useEslintPlugin && ctx.config.stack !== "none") devDeps["@bensandee/eslint-plugin"] = isWorkspacePackage(ctx, "@bensandee/eslint-plugin") ? "workspace:*" : "0.18.0";
5805
5811
  if (wantsAgentCli(ctx)) devDeps[AGENT_CLI_PACKAGE] = "0.3.1";
5806
5812
  if (ctx.config.formatter === "oxfmt") devDeps["oxfmt"] = {
@@ -7844,6 +7850,7 @@ function postReleaseHookJob(opts) {
7844
7850
  return {
7845
7851
  needs: opts.needsJob,
7846
7852
  if: onlyOnDefaultBranch(opts.defaultBranch, opts.publishCondition),
7853
+ ...opts.runsOn && { runsOn: opts.runsOn },
7847
7854
  "continue-on-error": true,
7848
7855
  steps: [...commonSteps(opts.ci), { step: {
7849
7856
  name: "Post-release hook",
@@ -7988,6 +7995,7 @@ async function generateReleaseCi(ctx) {
7988
7995
  const filePath = "release-ci";
7989
7996
  const isGitHub = ctx.config.ci === "github";
7990
7997
  const defaultBranch = configuredDefaultBranch(ctx.read(".tooling.json"));
7998
+ const trustedRunner = configuredTrustedRunner(ctx.read(".tooling.json"));
7991
7999
  if (ctx.config.ci === "none" || ctx.config.releaseStrategy === "none") return {
7992
8000
  filePath,
7993
8001
  action: "skipped",
@@ -8044,6 +8052,7 @@ async function generateReleaseCi(ctx) {
8044
8052
  defaultBranch,
8045
8053
  ci: ctx.config.ci,
8046
8054
  needsJob: "release",
8055
+ ...trustedRunner && { runsOn: trustedRunner },
8047
8056
  publishCondition: "needs.release.outputs.pushed == 'true'",
8048
8057
  releaseTagExpr: actionsExpr("needs.release.outputs.tag"),
8049
8058
  command: getPostReleaseHookCommand(ctx),
@@ -8058,6 +8067,7 @@ async function generateReleaseCi(ctx) {
8058
8067
  ...isGitHub && { permissions: { contents: "write" } },
8059
8068
  jobName: "release",
8060
8069
  jobIf: isDefaultBranch(defaultBranch),
8070
+ ...trustedRunner && { runsOn: trustedRunner },
8061
8071
  ...jobOutputs && { jobOutputs },
8062
8072
  steps,
8063
8073
  ...extraJobs && { extraJobs }
@@ -8164,6 +8174,10 @@ function ciConcurrency(ci, defaultBranch) {
8164
8174
  "cancel-in-progress": actionsExpr(isNotDefaultBranch(defaultBranch))
8165
8175
  };
8166
8176
  }
8177
+ function checkJobRunsOn(defaultBranch, trustedRunner) {
8178
+ if (trustedRunner === void 0) return void 0;
8179
+ return actionsExpr(`${isDefaultBranch(defaultBranch)} && '${trustedRunner}' || 'ubuntu-latest'`);
8180
+ }
8167
8181
  function checkSteps(ci, coverageEnabled, emitDockerSweepStep) {
8168
8182
  const checkCommand = coverageEnabled ? "pnpm ci:check" : "pnpm ci:check --no-coverage";
8169
8183
  return [
@@ -8193,6 +8207,8 @@ async function generateCi(ctx) {
8193
8207
  description: "CI workflow not requested"
8194
8208
  };
8195
8209
  const defaultBranch = configuredDefaultBranch(ctx.read(".tooling.json"));
8210
+ const trustedRunner = configuredTrustedRunner(ctx.read(".tooling.json"));
8211
+ const checkRunsOn = checkJobRunsOn(defaultBranch, trustedRunner);
8196
8212
  const isGitHub = ctx.config.ci === "github";
8197
8213
  const isForgejo = !isGitHub;
8198
8214
  const isChangesets = ctx.config.releaseStrategy === "changesets";
@@ -8261,6 +8277,7 @@ async function generateCi(ctx) {
8261
8277
  defaultBranch,
8262
8278
  ci: ctx.config.ci,
8263
8279
  needsJob: "check",
8280
+ ...trustedRunner && { runsOn: trustedRunner },
8264
8281
  publishCondition: "needs.check.outputs.published == 'true'",
8265
8282
  releaseTagExpr: actionsExpr("needs.check.outputs.tag"),
8266
8283
  command: hookCommand,
@@ -8284,6 +8301,7 @@ async function generateCi(ctx) {
8284
8301
  enableEmailNotifications: isForgejo,
8285
8302
  ...isChangesets && { concurrency: ciConcurrency(ctx.config.ci, defaultBranch) },
8286
8303
  jobName: "check",
8304
+ ...checkRunsOn && { runsOn: checkRunsOn },
8287
8305
  ...skipOnVersionPr && { jobIf: `github.head_ref != '${versionPrBranch(defaultBranch)}'` },
8288
8306
  ...Object.keys(checkJobEnv).length > 0 && { jobEnv: checkJobEnv },
8289
8307
  ...jobOutputs && { jobOutputs },
@@ -9597,7 +9615,7 @@ const AGENT_RULES_HEAD = [
9597
9615
  "- Use pnpm, not npm/yarn/npx. Run binaries with `pnpm exec`.",
9598
9616
  "- `mise install` provides the toolchain (`mise.toml`); a non-interactive session finds it only through mise's shims (`mise activate --shims` in the login profile)."
9599
9617
  ];
9600
- const TS_TYPECAST_RULE = "- No typecasts (`as`/`any`). Use zod schemas, type guards, or narrowing.";
9618
+ const TS_TYPECAST_RULE = "- Never overrule the type checker: no `as T` assertions and no `any`. Narrow instead, with a zod schema, a type guard, or a control-flow check. `as const` and `satisfies` are fine, because they make a type stricter, not looser.";
9601
9619
  const AGENT_RULES_MID = [
9602
9620
  "- Fix lint violations; don't suppress them. For `no-empty-function`, use a `{ /* no-op */ }` body, not a disable comment.",
9603
9621
  "- Write text in any language; letters, accents and other scripts are fine. Keep out what `chars:check` denies: LLM-tell punctuation (curly quotes, ellipsis, en and em dashes, arrows, box-drawing, status glyphs) and invisible or deceptive characters (bidi controls, zero-width and tag characters, odd spaces). Write `...`, `-`/`--`, straight quotes, `->` and `-`/`|`/`+` instead. Where a denied character must survive to output, escape it for its context: `\\uXXXX` in a JS/TS/Kotlin/Java string, char or regex; `&#xXXXX;` in JSX or XML; a spliced `${'\\uXXXX'}` in a Kotlin raw string. `pnpm exec bst chars:check --fix` applies the safe rewrites (`--fix-ambiguous` for em dashes and status glyphs) and flags the rest.",
@@ -9745,7 +9763,7 @@ const PLANNING_GUIDE_BODY = [
9745
9763
  "",
9746
9764
  "## The spec",
9747
9765
  "",
9748
- "Say why and what, not how: the problem, who it is for, the constraints, what done looks like, and the alternatives you rejected, each with its reason. Work with several independent parts gets one spec per part. Save it as `docs/specs/<YYYY-MM-DD>-<topic>-design.md`.",
9766
+ "Say why and what, not how: the problem, who it is for, the constraints, what done looks like, and the alternatives you rejected, each with its reason -- an established tool you chose not to use among them, by name. Work with several independent parts gets one spec per part. Save it as `docs/specs/<YYYY-MM-DD>-<topic>-design.md`.",
9749
9767
  "",
9750
9768
  "## The plan",
9751
9769
  "",
@@ -9827,6 +9845,23 @@ const DEBUGGING_GUIDE_BODY = [
9827
9845
  "- Three failed fixes mean the approach is wrong. Stop, question the design, and say what you do not understand, instead of trying a fourth.",
9828
9846
  "- A fixed bug gets a regression test that you have seen fail against the unfixed code."
9829
9847
  ].join("\n");
9848
+ const TOOLS_GUIDE_BODY = [
9849
+ "# Established tools",
9850
+ "",
9851
+ "**Before you design or write a general-purpose mechanism, look for the tool that already does it, and use it.** That covers a grammar or expression language, a parser, a scheduler or schedule format, and a date, retry, queue or validation helper.",
9852
+ "",
9853
+ "1. The platform or the language's standard library first.",
9854
+ "2. If it does not do the job, an established package.",
9855
+ "3. Your own code only when neither fits.",
9856
+ "",
9857
+ "An established package is maintained and widely used, has a license compatible with this repo's, ideally has few dependencies of its own, and has safety limits where its input is untrusted. Check these facts before you recommend a package -- its registry page, repository and license -- rather than recalling them.",
9858
+ "",
9859
+ "Keep only the domain part as your own code. In a design for scheduled prompts, the catalog of facts a condition reads is ours; the expression language (CEL) and the schedule format (cron) come from libraries.",
9860
+ "",
9861
+ "Adding an established dependency is not a cost to avoid. A homemade copy of what it does is the cost: code you own, test and secure for no gain.",
9862
+ "",
9863
+ "When you decide against an established tool, name it and the reason: in the spec's rejected alternatives, or in the commit body when there is no spec."
9864
+ ].join("\n");
9830
9865
  function webUiGuideBody() {
9831
9866
  const mwg = `pnpm dlx modern-web-guidance@${{
9832
9867
  "@changesets/cli": "3.0.3",
@@ -9941,7 +9976,7 @@ const HEALTH_RULE_TAIL = [
9941
9976
  "",
9942
9977
  "**An exemption takes a module or directory out of the gate.** It is listed with its count and reason in `health:summary --explain`, carries no ceiling, and is counted in no metric. `crowdedDirectories` is exemptable by directory path. A key may be a glob. Adding one is a raise too.",
9943
9978
  "",
9944
- "**A raise travels with the code that caused it.** A raise is a higher count or ceiling, a ceiling for a module that has none, a new exemption, or a higher limit. Write it with `pnpm exec bst health:raise` in the pull request whose code crossed the budget; say in the commit why, and a person merges it. Its `--exempt <leaf> --reason \"<text>\"` is for a hub by construction. Never raise a limit to pass. `--update-baseline --reset` rebuilds a baseline, never one branch.",
9979
+ "**A raise travels with the code that caused it.** A raise is a higher count or ceiling, a ceiling for a module that has none, a new exemption, or a higher limit. Write it with `pnpm exec bst health:raise` in the pull request whose code crossed the budget; say in the commit why, and a person merges it. Its `--exempt <leaf> --reason \"<text>\"` is for a hub by construction. Never raise a limit to pass. `--update-baseline --reset` rebuilds a baseline, never one branch. A lowering travels the same way: `pnpm exec bst health:tighten` writes it, from the measurement.",
9945
9980
  "",
9946
9981
  "Prefer an exemption to raising `fanInLimit` or `fanOutLimit`: an exemption names the hub in `health:summary --explain`, while a higher limit silently un-tracks every module beneath it. A per-module ceiling has no such shadow -- it ratchets one module at one count and fails again one edge later.",
9947
9982
  "",
@@ -10042,6 +10077,12 @@ function agentGuides(config, coverageEnabled, healthEnabled, webUiEnabled) {
10042
10077
  body: DEBUGGING_GUIDE_BODY,
10043
10078
  enabled: true
10044
10079
  },
10080
+ {
10081
+ name: "tools.md",
10082
+ trigger: "design or write a general-purpose mechanism -- a grammar or expression language, a parser, a scheduler or schedule format, or a date, retry, queue or validation helper",
10083
+ body: TOOLS_GUIDE_BODY,
10084
+ enabled: true
10085
+ },
10045
10086
  {
10046
10087
  name: "web-ui.md",
10047
10088
  trigger: "build or change a web UI -- markup, styles, components, or client-side behaviour",
@@ -10402,7 +10443,7 @@ function reportFailures(failed, command) {
10402
10443
  function generateMigratePrompt(results, config, detected) {
10403
10444
  const sections = [];
10404
10445
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
10405
- sections.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.102.0 repo:sync\` on ${timestamp}_\n`);
10446
+ sections.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.104.0 repo:sync\` on ${timestamp}_\n`);
10406
10447
  const changed = results.filter((r) => r.action === "created" || r.action === "updated" || r.action === "archived");
10407
10448
  if (changed.length > 0) {
10408
10449
  const items = changed.map((r) => {
@@ -11335,7 +11376,7 @@ function createRealHealthExecutor(rootDir) {
11335
11376
  };
11336
11377
  }
11337
11378
  // src/codebase-health/reference.ts
11338
- const BASELINE_FILE$2 = "health-baseline.json";
11379
+ const BASELINE_FILE$3 = "health-baseline.json";
11339
11380
  const TOOLING_FILE$1 = ".tooling.json";
11340
11381
  function repoPrefix(executor, cwd) {
11341
11382
  const result = executor.exec("git", ["rev-parse", "--show-prefix"], { cwd });
@@ -11416,7 +11457,7 @@ function readReference(executor, opts) {
11416
11457
  kind: "unavailable",
11417
11458
  reason: `health: cannot read the reference at the merge base with origin/${branch}. Run \`git fetch origin ${branch}\` so the default branch is present (a shallow clone or a missing remote-tracking ref makes it absent), or set .tooling.json#defaultBranch on the default branch if it has another name -- once that branch is fetched, its own copy of the setting decides, not this branch's. health:check fails closed without a reference.`
11418
11459
  };
11419
- const baselineText = showAt(executor, opts.cwd, sha, `${prefix}${BASELINE_FILE$2}`);
11460
+ const baselineText = showAt(executor, opts.cwd, sha, `${prefix}${BASELINE_FILE$3}`);
11420
11461
  const toolingText = showAt(executor, opts.cwd, sha, `${prefix}${TOOLING_FILE$1}`);
11421
11462
  const health = resolveHealthConfigFromContext({
11422
11463
  exists: (rel) => rel === TOOLING_FILE$1 && toolingText !== void 0,
@@ -11569,7 +11610,7 @@ function baselineRaises(reference, current) {
11569
11610
  }
11570
11611
  }
11571
11612
  if (reference.baseline !== void 0 && current.baseline === void 0) raises.push({
11572
- leaf: BASELINE_FILE$2,
11613
+ leaf: BASELINE_FILE$3,
11573
11614
  reference: "present",
11574
11615
  current: "absent"
11575
11616
  });
@@ -23358,13 +23399,13 @@ function serializeBaseline(baseline) {
23358
23399
  }
23359
23400
  // src/commands/coverage-check.ts
23360
23401
  const COVERAGE_SUMMARY_FILE$1 = "coverage/coverage-summary.json";
23361
- const BASELINE_FILE$1 = "coverage-baseline.json";
23362
- const MIGRATION_NOTICE = `${BASELINE_FILE$1} predates coverage.include scoping (no scope marker). Totals may have shifted because previously-untested files entered the denominator for the first time -- that is not necessarily a regression. This comparison is advisory only until the baseline is migrated: run \`pnpm test:coverage && pnpm exec bst coverage:check --update-baseline --reset\` once to adopt the honest, marked baseline. Normal gating resumes after that.`;
23402
+ const BASELINE_FILE$2 = "coverage-baseline.json";
23403
+ const MIGRATION_NOTICE = `${BASELINE_FILE$2} predates coverage.include scoping (no scope marker). Totals may have shifted because previously-untested files entered the denominator for the first time -- that is not necessarily a regression. This comparison is advisory only until the baseline is migrated: run \`pnpm test:coverage && pnpm exec bst coverage:check --update-baseline --reset\` once to adopt the honest, marked baseline. Normal gating resumes after that.`;
23363
23404
  function applyBaselineUpdate$1(out, baselinePath, baseline, current, options) {
23364
23405
  const { reset, floorPp } = options;
23365
23406
  if (reset) {
23366
23407
  writeFileSync(baselinePath, serializeBaseline(current));
23367
- out.notice(`Updated ${BASELINE_FILE$1} (--reset: unconditional).`);
23408
+ out.notice(`Updated ${BASELINE_FILE$2} (--reset: unconditional).`);
23368
23409
  } else if (floorPp !== void 0) {
23369
23410
  const merged = mergeTotalsWithFloor(baseline.totals, current.totals, floorPp);
23370
23411
  writeFileSync(baselinePath, serializeBaseline({
@@ -23372,10 +23413,10 @@ function applyBaselineUpdate$1(out, baselinePath, baseline, current, options) {
23372
23413
  totals: merged
23373
23414
  }));
23374
23415
  const held = TOTAL_KEYS.filter((key) => merged[key] !== current.totals[key]);
23375
- out.notice(held.length === 0 ? `Updated ${BASELINE_FILE$1} (floor ${String(floorPp)}%).` : `Updated ${BASELINE_FILE$1} (floor ${String(floorPp)}%; held at baseline below the floor: ${held.join(", ")}).`);
23416
+ out.notice(held.length === 0 ? `Updated ${BASELINE_FILE$2} (floor ${String(floorPp)}%).` : `Updated ${BASELINE_FILE$2} (floor ${String(floorPp)}%; held at baseline below the floor: ${held.join(", ")}).`);
23376
23417
  } else if (isFlatOrUp(baseline.totals, current.totals)) {
23377
23418
  writeFileSync(baselinePath, serializeBaseline(current));
23378
- out.notice(`Updated ${BASELINE_FILE$1} (all four totals flat-or-up).`);
23419
+ out.notice(`Updated ${BASELINE_FILE$2} (all four totals flat-or-up).`);
23379
23420
  } else out.notice(`Skipped baseline update: at least one total dropped below baseline. Add tests or adjust coverage.exclude before updating.`);
23380
23421
  }
23381
23422
  const coverageCheckCommand = defineCommand({
@@ -23421,20 +23462,20 @@ const coverageCheckCommand = defineCommand({
23421
23462
  return;
23422
23463
  }
23423
23464
  const summaryPath = path.join(targetDir, COVERAGE_SUMMARY_FILE$1);
23424
- const baselinePath = path.join(targetDir, BASELINE_FILE$1);
23465
+ const baselinePath = path.join(targetDir, BASELINE_FILE$2);
23425
23466
  if (!existsSync(summaryPath)) throw new FatalError(missingSummaryMessage(targetDir));
23426
23467
  const current = deriveBaseline(parseV8Summary(readFileSync(summaryPath, "utf-8")), { rootDir: targetDir });
23427
23468
  if (!existsSync(baselinePath)) {
23428
23469
  if (args["update-baseline"] === true) {
23429
23470
  writeFileSync(baselinePath, serializeBaseline(current));
23430
- out.notice(`Created ${BASELINE_FILE$1} (no prior baseline).`);
23471
+ out.notice(`Created ${BASELINE_FILE$2} (no prior baseline).`);
23431
23472
  out.json({
23432
23473
  status: "baseline-created",
23433
23474
  totals: current.totals
23434
23475
  });
23435
23476
  return;
23436
23477
  }
23437
- const message = `${BASELINE_FILE$1} not found. Run with --update-baseline to create one from the current run.`;
23478
+ const message = `${BASELINE_FILE$2} not found. Run with --update-baseline to create one from the current run.`;
23438
23479
  if (args["fail-on-missing-baseline"] === false) {
23439
23480
  out.notice(message);
23440
23481
  out.json({
@@ -23588,6 +23629,17 @@ function serializeHealthBaseline(metrics, ceilings, sizeBudgets) {
23588
23629
  if (sizeBudgets !== void 0 && Object.keys(sizeBudgets).length > 0) ordered["sizeBudgets"] = sizeBudgets;
23589
23630
  return JSON.stringify(ordered, null, 2) + "\n";
23590
23631
  }
23632
+ function healthFileFormatter(targetDir) {
23633
+ const detected = computeDefaults(targetDir);
23634
+ return createContentFormatter({
23635
+ targetDir,
23636
+ formatter: loadToolingConfig(targetDir)?.formatter ?? detected.formatter
23637
+ });
23638
+ }
23639
+ function writeHealthBaseline(targetDir, baseline) {
23640
+ const format = healthFileFormatter(targetDir);
23641
+ writeFileSync(path.join(targetDir, "health-baseline.json"), format("health-baseline.json", serializeHealthBaseline(baseline, baseline.moduleCeilings, baseline.sizeBudgets)));
23642
+ }
23591
23643
  // src/codebase-health/exclude.ts
23592
23644
  function normalize(rel) {
23593
23645
  const posix = rel.replace(/\\/g, "/");
@@ -24317,8 +24369,7 @@ function compareMetrics(baseline, current, tolerance = DEFAULT_TOLERANCE, curren
24317
24369
  };
24318
24370
  }
24319
24371
  function needsBaseMeasurement(result) {
24320
- const failedKeys = new Set(result.metrics.filter((m) => m.pass === false).map((m) => m.key));
24321
- return RATCHETED_METRIC_KEYS.some((key) => failedKeys.has(key) && result.uncoveredOutliers.some((o) => o.key === key));
24372
+ return result.uncoveredOutliers.length > 0;
24322
24373
  }
24323
24374
  function attributeOutliers(uncovered, base) {
24324
24375
  if (base.status !== "measured") return {
@@ -24380,168 +24431,227 @@ function isFlatOrBetter(baseline, current, currentCeilings = {}, sizes = []) {
24380
24431
  });
24381
24432
  return metricsFlat && ceilingsFlat && sizesFlat;
24382
24433
  }
24383
- // src/codebase-health/base-checkout.ts
24384
- const TEMP_PREFIX = "bst-health-base-";
24385
- function withMergeBaseCheckout(executor, targetDir, mergeBase, use) {
24386
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), TEMP_PREFIX));
24387
- const tree = path.join(tmp, "tree");
24388
- const index = path.join(tmp, "index");
24389
- try {
24390
- fs.mkdirSync(tree, { recursive: true });
24391
- const gitDir = gitOutput(executor.exec("git", ["rev-parse", "--absolute-git-dir"], { cwd: targetDir }), "git rev-parse --absolute-git-dir").trim();
24392
- const workRoot = gitOutput(executor.exec("git", ["rev-parse", "--show-toplevel"], { cwd: targetDir }), "git rev-parse --show-toplevel").trim();
24393
- const intoCheckout = (args) => executor.exec("git", [
24394
- `--git-dir=${gitDir}`,
24395
- `--work-tree=${tree}`,
24396
- ...args
24397
- ], {
24398
- cwd: tree,
24399
- env: { GIT_INDEX_FILE: index }
24400
- });
24401
- gitOutput(intoCheckout(["read-tree", mergeBase]), `git read-tree ${mergeBase.slice(0, 12)}`);
24402
- gitOutput(intoCheckout(["checkout-index", "-a"]), "git checkout-index -a");
24403
- mirrorNodeModules(workRoot, tree);
24404
- return use(tree);
24405
- } finally {
24406
- fs.rmSync(tmp, {
24407
- recursive: true,
24408
- force: true
24409
- });
24410
- }
24434
+ // src/codebase-health/raise.ts
24435
+ const SIZE_RAISE_FACTOR = 1.01;
24436
+ function sizeRaiseValue(measured) {
24437
+ return Math.floor(measured * SIZE_RAISE_FACTOR) + 1;
24411
24438
  }
24412
- function gitOutput(result, command) {
24413
- if (result.exitCode === 0) return result.stdout;
24414
- const detail = result.stderr.trim().split("\n")[0] ?? "";
24415
- throw new TransientError(`${command} failed: ${detail === "" ? `exit ${String(result.exitCode)}` : detail}`);
24439
+ const JsonObjectSchema = z.record(z.string(), z.unknown());
24440
+ const EXEMPT_LEAF_KEYS = [
24441
+ {
24442
+ prefix: "fan-in",
24443
+ key: "fanInOutliers"
24444
+ },
24445
+ {
24446
+ prefix: "fan-out",
24447
+ key: "fanOutOutliers"
24448
+ },
24449
+ {
24450
+ prefix: "crowding",
24451
+ key: "crowdedDirectories"
24452
+ }
24453
+ ];
24454
+ function refuseDeniableReason(leaf, reason) {
24455
+ const fixed = fixText(`// ${reason}`, {
24456
+ offenders: resolveOffenders(),
24457
+ path: "health-raise.ts"
24458
+ });
24459
+ const refused = fixed.decisions.find((decision) => !decision.applied);
24460
+ if (refused !== void 0) throw new FatalError(`health:raise: the reason for --exempt "${leaf}" carries ${refused.hit.offender.codepoint} (${refused.hit.offender.name}): ${refused.reason ?? "this gate denies it"}. Rewrite it in ASCII.`);
24461
+ return fixed.text.slice(3);
24416
24462
  }
24417
- function mirrorNodeModules(workingRoot, checkoutRoot) {
24418
- mirrorTree(workingRoot, checkoutRoot, "");
24463
+ function parseExemptLeaf(leaf) {
24464
+ const separator = leaf.indexOf(":");
24465
+ const prefix = separator < 0 ? "" : leaf.slice(0, separator).trim();
24466
+ const path = separator < 0 ? "" : leaf.slice(separator + 1).trim();
24467
+ if (prefix === "size") throw new FatalError(`health:raise: --exempt "${leaf}" names a size budget, which has no module to exempt. Run without --exempt: "health:raise" widens a grown size budget by measurement.`);
24468
+ const named = EXEMPT_LEAF_KEYS.find((entry) => entry.prefix === prefix);
24469
+ if (named === void 0 || path === "") throw new FatalError(`health:raise: --exempt "${leaf}" names no exemptable leaf. Pass one "health:check" printed: "fan-in: <path>", "fan-out: <path>", "crowding: <path>".`);
24470
+ return {
24471
+ key: named.key,
24472
+ path
24473
+ };
24419
24474
  }
24420
- function mirrorTree(workingRoot, checkoutRoot, rel) {
24421
- mirrorEntries(path.join(workingRoot, rel, "node_modules"), path.join(checkoutRoot, rel, "node_modules"));
24422
- let entries;
24423
- try {
24424
- entries = fs.readdirSync(path.join(checkoutRoot, rel), { withFileTypes: true });
24425
- } catch (_error) {
24426
- return;
24427
- }
24428
- for (const entry of entries) {
24429
- if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
24430
- if (entry.name === ".git" || entry.name === "node_modules") continue;
24431
- mirrorTree(workingRoot, checkoutRoot, path.join(rel, entry.name));
24475
+ function copyCeilings$1(ceilings) {
24476
+ const copy = {};
24477
+ for (const key of RATCHETED_METRIC_KEYS) {
24478
+ const byModule = ceilings?.[key];
24479
+ if (byModule !== void 0) copy[key] = { ...byModule };
24432
24480
  }
24481
+ return copy;
24433
24482
  }
24434
- function mirrorEntries(source, dest) {
24435
- let entries;
24436
- try {
24437
- entries = fs.readdirSync(source, { withFileTypes: true });
24438
- } catch (_error) {
24439
- return;
24440
- }
24441
- fs.mkdirSync(dest, { recursive: true });
24442
- for (const entry of entries) {
24443
- const src = path.join(source, entry.name);
24444
- const target = path.join(dest, entry.name);
24445
- if (entry.isSymbolicLink()) {
24446
- const link = safeReadlink(src);
24447
- if (link !== void 0 && !path.isAbsolute(link)) {
24448
- linkRelative(link, target);
24449
- continue;
24450
- }
24451
- } else if (entry.isDirectory() && entry.name.startsWith("@")) {
24452
- mirrorEntries(src, target);
24483
+ function writeCeiling$1(ceilings, key, module, to) {
24484
+ const byModule = ceilings[key] ?? {};
24485
+ byModule[module] = to;
24486
+ ceilings[key] = byModule;
24487
+ }
24488
+ function headlineFor(baseline, comparison, key, exemptCount) {
24489
+ const measured = comparison.metrics.find((metric) => metric.key === key)?.current;
24490
+ if (measured === void 0) return void 0;
24491
+ const remaining = Math.max(0, measured - exemptCount);
24492
+ return baseline[key] === void 0 ? remaining : Math.max(baseline[key] ?? 0, remaining);
24493
+ }
24494
+ function exemptionWrites(input) {
24495
+ const writes = [];
24496
+ const notes = [];
24497
+ for (const request of input.exemptions) {
24498
+ const parsed = parseExemptLeaf(request.leaf);
24499
+ if (parsed === void 0) continue;
24500
+ const recorded = input.config.exempt[parsed.key]?.[parsed.path];
24501
+ if (recorded !== void 0) {
24502
+ notes.push(`health.exempt.${parsed.key}.${parsed.path} already reads "${recorded}"; the reason was not overwritten.`);
24453
24503
  continue;
24454
24504
  }
24455
- try {
24456
- fs.symlinkSync(src, target, entry.isDirectory() ? "dir" : "file");
24457
- } catch (_error) {}
24458
- }
24459
- }
24460
- function safeReadlink(file) {
24461
- try {
24462
- return fs.readlinkSync(file);
24463
- } catch (_error) {
24464
- return;
24505
+ writes.push({
24506
+ key: parsed.key,
24507
+ path: parsed.path,
24508
+ reason: refuseDeniableReason(request.leaf, request.reason)
24509
+ });
24465
24510
  }
24466
- }
24467
- function linkRelative(link, target) {
24468
- try {
24469
- fs.symlinkSync(link, target);
24470
- } catch (_error) {}
24471
- }
24472
- // src/codebase-health/base-outliers.ts
24473
- function unavailable(reason) {
24474
24511
  return {
24475
- status: "unavailable",
24476
- reason: firstLine(reason)
24512
+ writes,
24513
+ notes
24477
24514
  };
24478
24515
  }
24479
- function firstLine(text) {
24480
- return text.trim().split("\n")[0] ?? "";
24481
- }
24482
- function measureBaseOutliers(opts) {
24483
- const collect = opts.collect ?? collectDetails;
24484
- try {
24485
- return withMergeBaseCheckout(opts.executor, opts.targetDir, opts.mergeBase, (checkoutRoot) => {
24486
- const baseTarget = path.join(checkoutRoot, opts.prefix);
24487
- const collectConfig = buildCollectConfig(opts.config, { tsConfig: existsSync(path.join(baseTarget, "tsconfig.json")) ? "tsconfig.json" : void 0 });
24488
- const details = collect(createRealHealthExecutor(baseTarget), collectConfig);
24489
- const unresolved = details.unresolvedFirstParty;
24490
- if (unresolved !== void 0 && unresolved.length > 0) return unavailable(`the base cruise could not resolve ${String(unresolved.length)} first-party imports`);
24491
- if (opts.config.graphMetricsEnabled && details.circularDependencies === void 0) return unavailable("the base cruise produced no graph metrics");
24492
- return {
24493
- status: "measured",
24494
- ceilings: ceilingsFromDetails(details)
24495
- };
24496
- });
24497
- } catch (error) {
24498
- return unavailable(describeError$1(error));
24499
- }
24516
+ function objectAt(parent, key, where) {
24517
+ const existing = parent[key];
24518
+ if (existing === void 0) return {};
24519
+ const parsed = JsonObjectSchema.safeParse(existing);
24520
+ if (!parsed.success) throw new FatalError(`health:raise: ${where}#${key} is not an object, so an exemption cannot be written there.`);
24521
+ return { ...parsed.data };
24500
24522
  }
24501
- // src/codebase-health/render.ts
24502
- const GRAPH_METRIC_KEYS = METRIC_KEYS.filter((key) => key !== "crowdedDirectories");
24503
- const LABELS = {
24504
- crowdedDirectories: "crowded directories",
24505
- circularDependencies: "circular dependencies",
24506
- fanInOutliers: "fan-in outliers",
24507
- fanOutOutliers: "fan-out outliers",
24508
- linesOfCode: "lines of code"
24509
- };
24510
- const CEILING_LABELS = {
24511
- crowdedDirectories: "crowding",
24512
- fanInOutliers: "fan-in",
24513
- fanOutOutliers: "fan-out"
24514
- };
24515
- function formatMetricsSummary(metrics) {
24516
- const lines = ["codebase health"];
24517
- for (const key of METRIC_KEYS) {
24518
- const value = metrics[key];
24519
- if (value === void 0) continue;
24520
- lines.push(` ${LABELS[key]}: ${value}`);
24521
- }
24522
- for (const key of OBSERVED_KEYS) {
24523
- const value = metrics[key];
24524
- if (value === void 0) continue;
24525
- lines.push(` ${LABELS[key]}: ${value}`);
24523
+ function applyExemptions(tooling, writes) {
24524
+ if (writes.length === 0) return void 0;
24525
+ const file = JsonObjectSchema.safeParse(tooling ?? {});
24526
+ if (!file.success) throw new FatalError(`health:raise: .tooling.json is not a JSON object, so no exemption can be written.`);
24527
+ const result = { ...file.data };
24528
+ for (const write of writes) {
24529
+ const health = objectAt(result, "health", ".tooling.json");
24530
+ const exempt = objectAt(health, "exempt", ".tooling.json#health");
24531
+ const table = objectAt(exempt, write.key, ".tooling.json#health.exempt");
24532
+ table[write.path] = write.reason;
24533
+ exempt[write.key] = table;
24534
+ health["exempt"] = exempt;
24535
+ result["health"] = health;
24526
24536
  }
24527
- if (metrics.coverageNote) lines.push(metrics.coverageNote);
24528
- return lines.join("\n");
24529
- }
24530
- function formatStatus(records) {
24531
- if (records.length === 0) return "health: no history recorded yet.";
24532
- const lines = ["health trend (oldest first):"];
24533
- for (const r of records) lines.push(` ${r.sha.slice(0, 7)} crowded=${r.crowdedDirectories}` + (r.circularDependencies === void 0 ? "" : ` cycles=${r.circularDependencies}`) + (r.linesOfCode === void 0 ? "" : ` loc=${r.linesOfCode}`));
24534
- return lines.join("\n");
24535
- }
24536
- const EXPLAIN_CAP = 25;
24537
- function capRows(rows) {
24538
- if (rows.length <= EXPLAIN_CAP) return rows;
24539
- return [...rows.slice(0, EXPLAIN_CAP), `... +${String(rows.length - EXPLAIN_CAP)} more`];
24537
+ return result;
24540
24538
  }
24541
- function offenderRows(details, key) {
24542
- switch (key) {
24543
- case "crowdedDirectories": return capRows(details.crowdedDirectories.map((d) => `${d.module} (${String(d.count)})`));
24544
- case "circularDependencies": return capRows((details.circularDependencies ?? []).map((c) => `${c.from} -> ${c.to}`));
24539
+ function planHealthRaise(input) {
24540
+ const ceilings = copyCeilings$1(input.baseline.moduleCeilings);
24541
+ const ceilingWrites = [];
24542
+ const headlines = {};
24543
+ const notes = [];
24544
+ const exemptions = exemptionWrites(input);
24545
+ notes.push(...exemptions.notes);
24546
+ const isExcused = (key, module) => exemptions.writes.some((write) => write.key === key && exemptKeyMatcher(write.path)(module));
24547
+ const exemptedCount = /* @__PURE__ */ new Map();
24548
+ const countExcused = (key, module) => {
24549
+ if (isExcused(key, module)) exemptedCount.set(key, (exemptedCount.get(key) ?? 0) + 1);
24550
+ };
24551
+ for (const outlier of input.attribution.newOutliers) countExcused(outlier.key, outlier.module);
24552
+ for (const ceiling of input.comparison.ceilings) if (!ceiling.pass) countExcused(ceiling.key, ceiling.module);
24553
+ const outlierBase = input.attribution.outlierBase;
24554
+ if (outlierBase.status === "unavailable") notes.push(`no "(new)" ceiling was written: the merge base ${outlierBase.mergeBase} could not be measured (${outlierBase.reason}), so nothing could be called a first crossing.`);
24555
+ for (const outlier of input.attribution.newOutliers) {
24556
+ if (isExcused(outlier.key, outlier.module)) continue;
24557
+ writeCeiling$1(ceilings, outlier.key, outlier.module, outlier.current);
24558
+ const headline = headlineFor(input.baseline, input.comparison, outlier.key, exemptedCount.get(outlier.key) ?? 0);
24559
+ if (headline !== void 0) headlines[outlier.key] = headline;
24560
+ ceilingWrites.push({
24561
+ key: outlier.key,
24562
+ module: outlier.module,
24563
+ value: outlier.current,
24564
+ ...headline === void 0 ? {} : { headline }
24565
+ });
24566
+ }
24567
+ for (const ceiling of input.comparison.ceilings) {
24568
+ if (ceiling.pass) continue;
24569
+ if (isExcused(ceiling.key, ceiling.module)) continue;
24570
+ writeCeiling$1(ceilings, ceiling.key, ceiling.module, ceiling.current);
24571
+ ceilingWrites.push({
24572
+ key: ceiling.key,
24573
+ module: ceiling.module,
24574
+ value: ceiling.current
24575
+ });
24576
+ }
24577
+ const sizeBudgets = { ...input.baseline.sizeBudgets };
24578
+ const sizeWrites = [];
24579
+ for (const size of input.comparison.sizeResults) {
24580
+ if (size.pass || size.measured === void 0 || size.ceiling === void 0) continue;
24581
+ if (size.measured <= size.ceiling) continue;
24582
+ const value = sizeRaiseValue(size.measured);
24583
+ sizeBudgets[size.id] = value;
24584
+ sizeWrites.push({
24585
+ id: size.id,
24586
+ value
24587
+ });
24588
+ }
24589
+ return {
24590
+ baseline: widenedBaseline(input.baseline, headlines, ceilings, sizeBudgets),
24591
+ tooling: applyExemptions(input.tooling, exemptions.writes),
24592
+ ceilings: ceilingWrites,
24593
+ sizes: sizeWrites,
24594
+ exemptions: exemptions.writes,
24595
+ notes
24596
+ };
24597
+ }
24598
+ function widenedBaseline(baseline, headlines, ceilings, sizeBudgets) {
24599
+ const widened = { ...baseline };
24600
+ for (const key of METRIC_KEYS) {
24601
+ const headline = headlines[key];
24602
+ if (headline !== void 0) widened[key] = headline;
24603
+ }
24604
+ widened.moduleCeilings = Object.keys(ceilings).length > 0 ? ceilings : void 0;
24605
+ widened.sizeBudgets = Object.keys(sizeBudgets).length > 0 ? sizeBudgets : void 0;
24606
+ return widened;
24607
+ }
24608
+ function planHasWrites(plan) {
24609
+ return plan.ceilings.length > 0 || plan.sizes.length > 0 || plan.exemptions.length > 0;
24610
+ }
24611
+ // src/codebase-health/render.ts
24612
+ const GRAPH_METRIC_KEYS$1 = METRIC_KEYS.filter((key) => key !== "crowdedDirectories");
24613
+ const LABELS = {
24614
+ crowdedDirectories: "crowded directories",
24615
+ circularDependencies: "circular dependencies",
24616
+ fanInOutliers: "fan-in outliers",
24617
+ fanOutOutliers: "fan-out outliers",
24618
+ linesOfCode: "lines of code"
24619
+ };
24620
+ const CEILING_LABELS = {
24621
+ crowdedDirectories: "crowding",
24622
+ fanInOutliers: "fan-in",
24623
+ fanOutOutliers: "fan-out"
24624
+ };
24625
+ function formatMetricsSummary(metrics) {
24626
+ const lines = ["codebase health"];
24627
+ for (const key of METRIC_KEYS) {
24628
+ const value = metrics[key];
24629
+ if (value === void 0) continue;
24630
+ lines.push(` ${LABELS[key]}: ${value}`);
24631
+ }
24632
+ for (const key of OBSERVED_KEYS) {
24633
+ const value = metrics[key];
24634
+ if (value === void 0) continue;
24635
+ lines.push(` ${LABELS[key]}: ${value}`);
24636
+ }
24637
+ if (metrics.coverageNote) lines.push(metrics.coverageNote);
24638
+ return lines.join("\n");
24639
+ }
24640
+ function formatStatus(records) {
24641
+ if (records.length === 0) return "health: no history recorded yet.";
24642
+ const lines = ["health trend (oldest first):"];
24643
+ for (const r of records) lines.push(` ${r.sha.slice(0, 7)} crowded=${r.crowdedDirectories}` + (r.circularDependencies === void 0 ? "" : ` cycles=${r.circularDependencies}`) + (r.linesOfCode === void 0 ? "" : ` loc=${r.linesOfCode}`));
24644
+ return lines.join("\n");
24645
+ }
24646
+ const EXPLAIN_CAP = 25;
24647
+ function capRows(rows) {
24648
+ if (rows.length <= EXPLAIN_CAP) return rows;
24649
+ return [...rows.slice(0, EXPLAIN_CAP), `... +${String(rows.length - EXPLAIN_CAP)} more`];
24650
+ }
24651
+ function offenderRows(details, key) {
24652
+ switch (key) {
24653
+ case "crowdedDirectories": return capRows(details.crowdedDirectories.map((d) => `${d.module} (${String(d.count)})`));
24654
+ case "circularDependencies": return capRows((details.circularDependencies ?? []).map((c) => `${c.from} -> ${c.to}`));
24545
24655
  case "fanInOutliers": return capRows((details.fanInOutliers ?? []).map((f) => f.lines === void 0 ? `${f.module} (${String(f.count)} importers)` : `${f.module} (${String(f.count)} importers, ${String(f.lines)} lines)`));
24546
24656
  case "fanOutOutliers": return capRows((details.fanOutOutliers ?? []).map((f) => `${f.module} (${String(f.count)} deps)`));
24547
24657
  }
@@ -24587,7 +24697,6 @@ function outlierAttributionLines(attribution, failedKeys) {
24587
24697
  const lines = [];
24588
24698
  let printedAttribution = false;
24589
24699
  for (const o of attribution.newOutliers) {
24590
- if (!failedKeys.has(o.key)) continue;
24591
24700
  lines.push(` ${CEILING_LABELS[o.key]}: ${o.module} -- -> ${o.current} (new)`);
24592
24701
  printedAttribution = true;
24593
24702
  }
@@ -24635,12 +24744,12 @@ function formatCompareDiff(result, details, attribution) {
24635
24744
  }
24636
24745
  const failedKeys = new Set(result.metrics.filter((m) => m.pass === false).map((m) => m.key));
24637
24746
  lines.push(...outlierAttributionLines(attribution, failedKeys));
24638
- lines.push(result.pass ? "health: PASS" : "health: FAIL");
24747
+ lines.push(result.pass && attribution.newOutliers.length === 0 ? "health: PASS" : "health: FAIL");
24639
24748
  return lines.join("\n");
24640
24749
  }
24641
24750
  function formatGraphUnavailable(baseline, details, graphMetricsEnabled, diagnostic) {
24642
24751
  if (!graphMetricsEnabled || details.circularDependencies !== void 0) return void 0;
24643
- const missing = GRAPH_METRIC_KEYS.filter((key) => baseline[key] !== void 0);
24752
+ const missing = GRAPH_METRIC_KEYS$1.filter((key) => baseline[key] !== void 0);
24644
24753
  if (missing.length === 0) return void 0;
24645
24754
  return [`health: the dependency graph was not measured this run, but the baseline records ${missing.map((key) => LABELS[key]).join(", ")}.`, ...diagnosticDetailLines(diagnostic)].join("\n");
24646
24755
  }
@@ -24650,7 +24759,7 @@ function diagnosticDetailLines(diagnostic) {
24650
24759
  }
24651
24760
  function formatGraphUnavailableForSummary(details, graphMetricsEnabled, diagnostic) {
24652
24761
  if (!graphMetricsEnabled || details.circularDependencies !== void 0) return void 0;
24653
- return [`health: graph metrics unavailable this run (${GRAPH_METRIC_KEYS.map((key) => LABELS[key]).join(", ")}).`, ...diagnosticDetailLines(diagnostic)].join("\n");
24762
+ return [`health: graph metrics unavailable this run (${GRAPH_METRIC_KEYS$1.map((key) => LABELS[key]).join(", ")}).`, ...diagnosticDetailLines(diagnostic)].join("\n");
24654
24763
  }
24655
24764
  function formatStaleEntries(stale) {
24656
24765
  return stale.map((entry) => {
@@ -24691,10 +24800,326 @@ function formatUnresolvedFirstParty(entries) {
24691
24800
  lines.push(` An unresolved first-party import leaves the dependency graph, improving every health`, ` metric. Fix the import, or the resolve options that were supposed to follow it.`);
24692
24801
  return lines.join("\n");
24693
24802
  }
24803
+ function formatSlack(entries) {
24804
+ if (entries.length === 0) return [];
24805
+ const lines = [`slack: ${String(entries.length)} recorded ${entries.length === 1 ? "value" : "values"} above what this run measures. Run "pnpm exec bst health:tighten" to lower them.`];
24806
+ for (const entry of entries) {
24807
+ const suffix = slackSuffix(entry.kind);
24808
+ const from = entry.recorded ?? "--";
24809
+ const to = entry.measured ?? "--";
24810
+ lines.push(` ${entry.leaf} ${String(from)} -> ${String(to)} ${suffix}`);
24811
+ }
24812
+ return lines;
24813
+ }
24814
+ function slackSuffix(kind) {
24815
+ if (kind === "dead-ceiling") return "(dead ceiling)";
24816
+ if (kind === "uncapped") return "(uncapped)";
24817
+ return "(slack)";
24818
+ }
24694
24819
  const CARRIED_RAISES_FIRST_LINE = "raises carried by this branch:";
24695
24820
  function formatCarriedRaises(raises) {
24696
24821
  return [CARRIED_RAISES_FIRST_LINE, ...raises.map((r) => ` ${r.leaf}: ${r.reference} -> ${r.current}`)].join("\n");
24697
24822
  }
24823
+ // src/codebase-health/tighten.ts
24824
+ const GRAPH_METRIC_KEYS = new Set(METRIC_KEYS.filter((key) => key !== "crowdedDirectories"));
24825
+ function isGraphMetric(key) {
24826
+ return GRAPH_METRIC_KEYS.has(key);
24827
+ }
24828
+ function ceilingLeaf(key, module) {
24829
+ return `${CEILING_LABELS[key]}: ${module}`;
24830
+ }
24831
+ function copyCeilings(ceilings) {
24832
+ const copy = {};
24833
+ for (const key of RATCHETED_METRIC_KEYS) {
24834
+ const byModule = ceilings?.[key];
24835
+ if (byModule !== void 0) copy[key] = { ...byModule };
24836
+ }
24837
+ return copy;
24838
+ }
24839
+ function writeCeiling(ceilings, key, module, to) {
24840
+ const byModule = ceilings[key] ?? {};
24841
+ byModule[module] = to;
24842
+ ceilings[key] = byModule;
24843
+ }
24844
+ function dropCeiling(ceilings, key, module) {
24845
+ const byModule = ceilings[key];
24846
+ if (byModule === void 0) return;
24847
+ delete byModule[module];
24848
+ if (Object.keys(byModule).length === 0) delete ceilings[key];
24849
+ }
24850
+ function slackRecords(input) {
24851
+ const { comparison, attribution, baseline, graphMeasured } = input;
24852
+ const records = [];
24853
+ for (const key of METRIC_KEYS) {
24854
+ if (!graphMeasured && isGraphMetric(key)) continue;
24855
+ const recorded = baseline[key];
24856
+ const measured = comparison.metrics.find((metric) => metric.key === key)?.current;
24857
+ if (recorded === void 0 || measured === void 0) continue;
24858
+ if (measured >= recorded) continue;
24859
+ records.push({
24860
+ kind: "count",
24861
+ key,
24862
+ leaf: key,
24863
+ recorded,
24864
+ measured
24865
+ });
24866
+ }
24867
+ const measuredLeaves = new Set(comparison.ceilings.map((ceiling) => ceilingLeaf(ceiling.key, ceiling.module)));
24868
+ for (const ceiling of comparison.ceilings) {
24869
+ if (!graphMeasured && isGraphMetric(ceiling.key)) continue;
24870
+ if (ceiling.current >= ceiling.baseline) continue;
24871
+ records.push({
24872
+ kind: "ceiling",
24873
+ key: ceiling.key,
24874
+ module: ceiling.module,
24875
+ leaf: ceilingLeaf(ceiling.key, ceiling.module),
24876
+ recorded: ceiling.baseline,
24877
+ measured: ceiling.current
24878
+ });
24879
+ }
24880
+ for (const key of RATCHETED_METRIC_KEYS) {
24881
+ if (!graphMeasured && isGraphMetric(key)) continue;
24882
+ for (const [module, recorded] of Object.entries(baseline.moduleCeilings?.[key] ?? {})) {
24883
+ if (measuredLeaves.has(ceilingLeaf(key, module))) continue;
24884
+ records.push({
24885
+ kind: "dead-ceiling",
24886
+ key,
24887
+ module,
24888
+ leaf: ceilingLeaf(key, module),
24889
+ recorded
24890
+ });
24891
+ }
24892
+ }
24893
+ for (const outlier of attribution.baseOutliers) {
24894
+ if (!graphMeasured && isGraphMetric(outlier.key)) continue;
24895
+ records.push({
24896
+ kind: "uncapped",
24897
+ key: outlier.key,
24898
+ module: outlier.module,
24899
+ leaf: ceilingLeaf(outlier.key, outlier.module),
24900
+ measured: outlier.current
24901
+ });
24902
+ }
24903
+ for (const size of comparison.sizeResults) {
24904
+ const recorded = baseline.sizeBudgets?.[size.id];
24905
+ if (recorded === void 0 || size.measured === void 0) continue;
24906
+ const to = sizeRaiseValue(size.measured);
24907
+ if (recorded <= to) continue;
24908
+ records.push({
24909
+ kind: "size",
24910
+ id: size.id,
24911
+ leaf: `size: ${size.id}`,
24912
+ recorded,
24913
+ measured: size.measured,
24914
+ to
24915
+ });
24916
+ }
24917
+ return records;
24918
+ }
24919
+ function slackEntry(record) {
24920
+ if (record.kind === "uncapped") return {
24921
+ kind: record.kind,
24922
+ leaf: record.leaf,
24923
+ measured: record.measured
24924
+ };
24925
+ if (record.kind === "dead-ceiling") return {
24926
+ kind: record.kind,
24927
+ leaf: record.leaf,
24928
+ recorded: record.recorded
24929
+ };
24930
+ return {
24931
+ kind: record.kind,
24932
+ leaf: record.leaf,
24933
+ recorded: record.recorded,
24934
+ measured: record.measured
24935
+ };
24936
+ }
24937
+ function findSlack(input) {
24938
+ return slackRecords(input).map(slackEntry);
24939
+ }
24940
+ function planHealthTighten(input) {
24941
+ const ceilings = copyCeilings(input.baseline.moduleCeilings);
24942
+ const sizeBudgets = { ...input.baseline.sizeBudgets };
24943
+ const tightened = { ...input.baseline };
24944
+ const lowered = [];
24945
+ const removed = [];
24946
+ const caps = [];
24947
+ for (const record of slackRecords(input)) switch (record.kind) {
24948
+ case "count":
24949
+ tightened[record.key] = record.measured;
24950
+ lowered.push({
24951
+ leaf: record.leaf,
24952
+ from: record.recorded,
24953
+ to: record.measured
24954
+ });
24955
+ break;
24956
+ case "ceiling":
24957
+ writeCeiling(ceilings, record.key, record.module, record.measured);
24958
+ lowered.push({
24959
+ leaf: record.leaf,
24960
+ from: record.recorded,
24961
+ to: record.measured
24962
+ });
24963
+ break;
24964
+ case "dead-ceiling":
24965
+ dropCeiling(ceilings, record.key, record.module);
24966
+ removed.push({
24967
+ key: record.key,
24968
+ module: record.module,
24969
+ value: record.recorded
24970
+ });
24971
+ break;
24972
+ case "uncapped":
24973
+ writeCeiling(ceilings, record.key, record.module, record.measured);
24974
+ caps.push({
24975
+ key: record.key,
24976
+ module: record.module,
24977
+ value: record.measured
24978
+ });
24979
+ break;
24980
+ case "size":
24981
+ sizeBudgets[record.id] = record.to;
24982
+ lowered.push({
24983
+ leaf: record.leaf,
24984
+ from: record.recorded,
24985
+ to: record.to
24986
+ });
24987
+ }
24988
+ tightened.moduleCeilings = Object.keys(ceilings).length > 0 ? ceilings : void 0;
24989
+ tightened.sizeBudgets = Object.keys(sizeBudgets).length > 0 ? sizeBudgets : void 0;
24990
+ return {
24991
+ baseline: tightened,
24992
+ lowered,
24993
+ removed,
24994
+ caps
24995
+ };
24996
+ }
24997
+ function baselineUpdateRefusal(attribution) {
24998
+ if (attribution.newOutliers.length > 0) return "Skipped baseline update: an outlier crossed a limit for the first time this run. Record it with \"health:raise\", which writes the ceiling beside the reason it was earned.";
24999
+ if (attribution.unattributedOutliers.length > 0) {
25000
+ const base = attribution.outlierBase;
25001
+ return `Skipped baseline update: an outlier has no recorded ceiling and no merge-base measurement to clear it.${base.status === "unavailable" ? ` The merge base could not be measured: ${base.reason}.` : ""} Record it with "health:raise", which writes the ceiling beside the reason it was earned.`;
25002
+ }
25003
+ return null;
25004
+ }
25005
+ // src/codebase-health/base-checkout.ts
25006
+ const TEMP_PREFIX = "bst-health-base-";
25007
+ function withMergeBaseCheckout(executor, targetDir, mergeBase, use) {
25008
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), TEMP_PREFIX));
25009
+ const tree = path.join(tmp, "tree");
25010
+ const index = path.join(tmp, "index");
25011
+ try {
25012
+ fs.mkdirSync(tree, { recursive: true });
25013
+ const gitDir = gitOutput(executor.exec("git", ["rev-parse", "--absolute-git-dir"], { cwd: targetDir }), "git rev-parse --absolute-git-dir").trim();
25014
+ const workRoot = gitOutput(executor.exec("git", ["rev-parse", "--show-toplevel"], { cwd: targetDir }), "git rev-parse --show-toplevel").trim();
25015
+ const intoCheckout = (args) => executor.exec("git", [
25016
+ `--git-dir=${gitDir}`,
25017
+ `--work-tree=${tree}`,
25018
+ ...args
25019
+ ], {
25020
+ cwd: tree,
25021
+ env: { GIT_INDEX_FILE: index }
25022
+ });
25023
+ gitOutput(intoCheckout(["read-tree", mergeBase]), `git read-tree ${mergeBase.slice(0, 12)}`);
25024
+ gitOutput(intoCheckout(["checkout-index", "-a"]), "git checkout-index -a");
25025
+ mirrorNodeModules(workRoot, tree);
25026
+ return use(tree);
25027
+ } finally {
25028
+ fs.rmSync(tmp, {
25029
+ recursive: true,
25030
+ force: true
25031
+ });
25032
+ }
25033
+ }
25034
+ function gitOutput(result, command) {
25035
+ if (result.exitCode === 0) return result.stdout;
25036
+ const detail = result.stderr.trim().split("\n")[0] ?? "";
25037
+ throw new TransientError(`${command} failed: ${detail === "" ? `exit ${String(result.exitCode)}` : detail}`);
25038
+ }
25039
+ function mirrorNodeModules(workingRoot, checkoutRoot) {
25040
+ mirrorTree(workingRoot, checkoutRoot, "");
25041
+ }
25042
+ function mirrorTree(workingRoot, checkoutRoot, rel) {
25043
+ mirrorEntries(path.join(workingRoot, rel, "node_modules"), path.join(checkoutRoot, rel, "node_modules"));
25044
+ let entries;
25045
+ try {
25046
+ entries = fs.readdirSync(path.join(checkoutRoot, rel), { withFileTypes: true });
25047
+ } catch (_error) {
25048
+ return;
25049
+ }
25050
+ for (const entry of entries) {
25051
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
25052
+ if (entry.name === ".git" || entry.name === "node_modules") continue;
25053
+ mirrorTree(workingRoot, checkoutRoot, path.join(rel, entry.name));
25054
+ }
25055
+ }
25056
+ function mirrorEntries(source, dest) {
25057
+ let entries;
25058
+ try {
25059
+ entries = fs.readdirSync(source, { withFileTypes: true });
25060
+ } catch (_error) {
25061
+ return;
25062
+ }
25063
+ fs.mkdirSync(dest, { recursive: true });
25064
+ for (const entry of entries) {
25065
+ const src = path.join(source, entry.name);
25066
+ const target = path.join(dest, entry.name);
25067
+ if (entry.isSymbolicLink()) {
25068
+ const link = safeReadlink(src);
25069
+ if (link !== void 0 && !path.isAbsolute(link)) {
25070
+ linkRelative(link, target);
25071
+ continue;
25072
+ }
25073
+ } else if (entry.isDirectory() && entry.name.startsWith("@")) {
25074
+ mirrorEntries(src, target);
25075
+ continue;
25076
+ }
25077
+ try {
25078
+ fs.symlinkSync(src, target, entry.isDirectory() ? "dir" : "file");
25079
+ } catch (_error) {}
25080
+ }
25081
+ }
25082
+ function safeReadlink(file) {
25083
+ try {
25084
+ return fs.readlinkSync(file);
25085
+ } catch (_error) {
25086
+ return;
25087
+ }
25088
+ }
25089
+ function linkRelative(link, target) {
25090
+ try {
25091
+ fs.symlinkSync(link, target);
25092
+ } catch (_error) {}
25093
+ }
25094
+ // src/codebase-health/base-outliers.ts
25095
+ function unavailable(reason) {
25096
+ return {
25097
+ status: "unavailable",
25098
+ reason: firstLine(reason)
25099
+ };
25100
+ }
25101
+ function firstLine(text) {
25102
+ return text.trim().split("\n")[0] ?? "";
25103
+ }
25104
+ function measureBaseOutliers(opts) {
25105
+ const collect = opts.collect ?? collectDetails;
25106
+ try {
25107
+ return withMergeBaseCheckout(opts.executor, opts.targetDir, opts.mergeBase, (checkoutRoot) => {
25108
+ const baseTarget = path.join(checkoutRoot, opts.prefix);
25109
+ const collectConfig = buildCollectConfig(opts.config, { tsConfig: existsSync(path.join(baseTarget, "tsconfig.json")) ? "tsconfig.json" : void 0 });
25110
+ const details = collect(createRealHealthExecutor(baseTarget), collectConfig);
25111
+ const unresolved = details.unresolvedFirstParty;
25112
+ if (unresolved !== void 0 && unresolved.length > 0) return unavailable(`the base cruise could not resolve ${String(unresolved.length)} first-party imports`);
25113
+ if (opts.config.graphMetricsEnabled && details.circularDependencies === void 0) return unavailable("the base cruise produced no graph metrics");
25114
+ return {
25115
+ status: "measured",
25116
+ ceilings: ceilingsFromDetails(details)
25117
+ };
25118
+ });
25119
+ } catch (error) {
25120
+ return unavailable(describeError$1(error));
25121
+ }
25122
+ }
24698
25123
  // src/codebase-health/size.ts
24699
25124
  function byteLength(absolute) {
24700
25125
  try {
@@ -24772,7 +25197,7 @@ function measureOne(targetDir, id, budget, options) {
24772
25197
  };
24773
25198
  }
24774
25199
  // src/codebase-health/measure.ts
24775
- const BASELINE_FILE = "health-baseline.json";
25200
+ const BASELINE_FILE$1 = "health-baseline.json";
24776
25201
  function readTargetReference(executor, targetDir, out) {
24777
25202
  const context = detectHealthContext(targetDir);
24778
25203
  const read = readReference(executor, {
@@ -24794,7 +25219,7 @@ function assessRaises(executor, targetDir, current, out) {
24794
25219
  if (read.kind === "unavailable") throw new FatalError(read.reason);
24795
25220
  const reference = read.reference;
24796
25221
  if (reference.baseline === void 0) {
24797
- out.notice(`${BASELINE_FILE} has no counterpart on the default branch yet, so there is nothing to raise against.`);
25222
+ out.notice(`${BASELINE_FILE$1} has no counterpart on the default branch yet, so there is nothing to raise against.`);
24798
25223
  return {
24799
25224
  fields: {
24800
25225
  reference: {
@@ -24860,7 +25285,7 @@ function measureHealth(targetDir, config, out, opts = {}) {
24860
25285
  const ceilings = ceilingsFromDetails(details);
24861
25286
  refuseUnresolvedImports(details);
24862
25287
  refuseEmptyScope(details, config, opts.failOnEmptySrc, out);
24863
- const baselinePath = path.join(targetDir, BASELINE_FILE);
25288
+ const baselinePath = path.join(targetDir, BASELINE_FILE$1);
24864
25289
  const treeBaseline = existsSync(baselinePath) ? parseHealthBaseline(readFileSync(baselinePath, "utf-8")) : void 0;
24865
25290
  const raiseAssessment = assessRaises(executor, targetDir, {
24866
25291
  baseline: treeBaseline,
@@ -24952,7 +25377,7 @@ function assessSwitchOff(executor, targetDir, config, out) {
24952
25377
  if (read.kind === "unavailable") return void 0;
24953
25378
  const reference = read.reference;
24954
25379
  if (!reference.health.enabled || reference.baseline === void 0) return void 0;
24955
- const baselinePath = path.join(targetDir, BASELINE_FILE);
25380
+ const baselinePath = path.join(targetDir, BASELINE_FILE$1);
24956
25381
  const treeBaseline = existsSync(baselinePath) ? parseHealthBaseline(readFileSync(baselinePath, "utf-8")) : void 0;
24957
25382
  const named = healthOverridesAt(targetDir);
24958
25383
  const limitsOver = { ...config };
@@ -24978,10 +25403,10 @@ function sizeValuesToRecord(baseline, sizes, reset) {
24978
25403
  return Object.keys(recorded).length > 0 ? recorded : void 0;
24979
25404
  }
24980
25405
  function handleMissingBaseline(state, updateBaseline, failOnMissingBaseline) {
24981
- const { baselinePath, config, details, current, ceilings, sizes, out } = state;
25406
+ const { targetDir, config, details, current, ceilings, sizes, out } = state;
24982
25407
  if (updateBaseline === true) {
24983
25408
  if (config.graphMetricsEnabled && details.circularDependencies === void 0) {
24984
- out.notice(`Skipped baseline creation: graph metrics are unavailable this run. Fix the cruise before creating ${BASELINE_FILE}.`);
25409
+ out.notice(`Skipped baseline creation: graph metrics are unavailable this run. Fix the cruise before creating ${BASELINE_FILE$1}.`);
24985
25410
  out.json({
24986
25411
  status: "graph-unavailable",
24987
25412
  ...state.referenceFields,
@@ -24992,8 +25417,12 @@ function handleMissingBaseline(state, updateBaseline, failOnMissingBaseline) {
24992
25417
  process.exitCode = 1;
24993
25418
  return;
24994
25419
  }
24995
- writeFileSync(baselinePath, serializeHealthBaseline(current, ceilings, sizeValuesToRecord(void 0, sizes, false)));
24996
- out.notice(`Created ${BASELINE_FILE} (no prior baseline).`);
25420
+ writeHealthBaseline(targetDir, {
25421
+ ...current,
25422
+ moduleCeilings: ceilings,
25423
+ sizeBudgets: sizeValuesToRecord(void 0, sizes, false)
25424
+ });
25425
+ out.notice(`Created ${BASELINE_FILE$1} (no prior baseline).`);
24997
25426
  out.json({
24998
25427
  status: "baseline-created",
24999
25428
  ...state.referenceFields,
@@ -25003,7 +25432,7 @@ function handleMissingBaseline(state, updateBaseline, failOnMissingBaseline) {
25003
25432
  reportCarriedRaises(state.referenceFields.raises, out);
25004
25433
  return;
25005
25434
  }
25006
- const message = `${BASELINE_FILE} not found. Run with --update-baseline to create one from the current run.`;
25435
+ const message = `${BASELINE_FILE$1} not found. Run with --update-baseline to create one from the current run.`;
25007
25436
  if (failOnMissingBaseline === false) {
25008
25437
  out.notice(message);
25009
25438
  out.json({
@@ -25018,17 +25447,44 @@ function handleMissingBaseline(state, updateBaseline, failOnMissingBaseline) {
25018
25447
  reportCarriedRaises(state.referenceFields.raises, out);
25019
25448
  throw new FatalError(message);
25020
25449
  }
25021
- function applyBaselineUpdate(state, baseline, reset) {
25022
- const { baselinePath, config, details, current, ceilings, sizes, out } = state;
25450
+ function adoptUnrecorded(planned, recorded, current, ceilings) {
25451
+ const written = { ...planned };
25452
+ for (const key of METRIC_KEYS) {
25453
+ const measured = current[key];
25454
+ if (written[key] === void 0 && measured !== void 0) written[key] = measured;
25455
+ }
25456
+ if (recorded.moduleCeilings === void 0) written.moduleCeilings = ceilings;
25457
+ return written;
25458
+ }
25459
+ function applyBaselineUpdate(state, existing, reset) {
25460
+ const { targetDir, config, details, current, ceilings, sizes, out } = state;
25461
+ const { baseline, result, attribution } = existing;
25023
25462
  if (config.graphMetricsEnabled && details.circularDependencies === void 0) {
25024
25463
  out.notice(`Skipped baseline update: graph metrics are unavailable this run. Fix the cruise before updating.`);
25025
25464
  process.exitCode = 1;
25026
25465
  } else if (reset === true) {
25027
- writeFileSync(baselinePath, serializeHealthBaseline(current, ceilings, sizeValuesToRecord(baseline, sizes, true)));
25028
- out.notice(`Reset ${BASELINE_FILE} to the current run.`);
25466
+ writeHealthBaseline(targetDir, {
25467
+ ...current,
25468
+ moduleCeilings: ceilings,
25469
+ sizeBudgets: sizeValuesToRecord(baseline, sizes, true)
25470
+ });
25471
+ out.notice(`Reset ${BASELINE_FILE$1} to the current run.`);
25029
25472
  } else if (isFlatOrBetter(baseline, current, ceilings, sizes)) {
25030
- writeFileSync(baselinePath, serializeHealthBaseline(current, ceilings, sizeValuesToRecord(baseline, sizes, false)));
25031
- out.notice(`Updated ${BASELINE_FILE} (no regressions).`);
25473
+ const refusal = baselineUpdateRefusal(attribution);
25474
+ if (refusal !== null) out.notice(refusal);
25475
+ else {
25476
+ const plan = planHealthTighten({
25477
+ comparison: result,
25478
+ attribution,
25479
+ baseline,
25480
+ graphMeasured: config.graphMetricsEnabled
25481
+ });
25482
+ writeHealthBaseline(targetDir, {
25483
+ ...adoptUnrecorded(plan.baseline, baseline, current, ceilings),
25484
+ sizeBudgets: sizeValuesToRecord(plan.baseline, sizes, false)
25485
+ });
25486
+ out.notice(`Updated ${BASELINE_FILE$1} (no regressions).`);
25487
+ }
25032
25488
  } else out.notice(`Skipped baseline update: a metric or ceiling regressed. Fix the regression before updating.`);
25033
25489
  }
25034
25490
  function collectRegressions(result, details) {
@@ -25068,7 +25524,7 @@ const healthCheckCommand = defineCommand({
25068
25524
  },
25069
25525
  json: {
25070
25526
  type: "boolean",
25071
- description: "Emit one JSON document: status (compared | disabled | baseline-created | missing-baseline | graph-unavailable). disabled carries reference and raises only when the default branch has health enabled -- switching it off is a raise -- and nothing otherwise. Every other status carries reference ({status (read | no-baseline), mergeBase}) and raises ([{leaf, reference, current}]: every way this branch's two health files are higher than the default branch's, which it carries with its own code and a person merges). baseline-created, missing-baseline and graph-unavailable carry metrics ({crowdedDirectories, circularDependencies?, fanInOutliers?, fanOutOutliers?}) and sources. compared carries pass, tolerance, metrics (a list: [{key (crowdedDirectories | circularDependencies | fanInOutliers | fanOutOutliers), baseline?, current?, delta?, pass}]), ceilings ([{key (fanInOutliers | fanOutOutliers | crowdedDirectories), module, baseline, current, pass}]), sizeBudgets ([{id, ceiling?, measured?, pass, reason?}] -- every budget .tooling.json#health.sizeBudgets declares; reason is `unrecorded` for a declared budget with no recorded value, or the measurer's own explanation when it measured nothing), outlierBase ({status (measured | not-needed | unavailable), mergeBase?, reason?}), newOutliers ([{key, module, current}], outliers not on the merge base; empty unless measured), baseOutliers ([{key, module, base, current}]) and unattributedOutliers ([{key, module, current}], every outlier with no ceiling when the base was not measured), graphMetricsEnabled, graphMetricsMissing, staleEntries ([{kind (ceiling | exemption), metric, path, count?}]), regressions ({<failing metric key>: [{module, count} | {from, to}]}) and sources. sources is {entries ([{pattern, roots, status (resolved | unmatched | unrepresentable)}]), roots, fileCount}."
25527
+ description: "Emit one JSON document: status (compared | disabled | baseline-created | missing-baseline | graph-unavailable). disabled carries reference and raises only when the default branch has health enabled -- switching it off is a raise -- and nothing otherwise. Every other status carries reference ({status (read | no-baseline), mergeBase}) and raises ([{leaf, reference, current}]: every way this branch's two health files are higher than the default branch's, which it carries with its own code and a person merges). baseline-created, missing-baseline and graph-unavailable carry metrics ({crowdedDirectories, circularDependencies?, fanInOutliers?, fanOutOutliers?}) and sources. compared carries pass (false when newOutliers holds an entry, even with every count flat), tolerance, metrics (a list: [{key (crowdedDirectories | circularDependencies | fanInOutliers | fanOutOutliers), baseline?, current?, delta?, pass}]), ceilings ([{key (fanInOutliers | fanOutOutliers | crowdedDirectories), module, baseline, current, pass}]), sizeBudgets ([{id, ceiling?, measured?, pass, reason?}] -- every budget .tooling.json#health.sizeBudgets declares; reason is `unrecorded` for a declared budget with no recorded value, or the measurer's own explanation when it measured nothing), outlierBase ({status (measured | not-needed | unavailable), mergeBase?, reason?}), newOutliers ([{key, module, current}], outliers not on the merge base; empty unless measured), baseOutliers ([{key, module, base, current}]) and unattributedOutliers ([{key, module, current}], every outlier with no ceiling when the base was not measured), graphMetricsEnabled, graphMetricsMissing, slack ([{kind (count | ceiling | dead-ceiling | uncapped | size), leaf, recorded?, measured?}] -- every recorded value sitting above what this run measured, in the leaf spelling the failure lines print; information only, never a finding and never the verdict), staleEntries ([{kind (ceiling | exemption), metric, path, count?}]), regressions ({<failing metric key>: [{module, count} | {from, to}]}) and sources. sources is {entries ([{pattern, roots, status (resolved | unmatched | unrepresentable)}]), roots, fileCount}."
25072
25528
  }
25073
25529
  },
25074
25530
  run({ args }) {
@@ -25088,7 +25544,7 @@ const healthCheckCommand = defineCommand({
25088
25544
  if (!config.graphMetricsEnabled) out.notice("health: graph metrics disabled (no JS/TS source to cruise) -- crowdedDirectories only.");
25089
25545
  const run = measureHealth(targetDir, config, out, { failOnEmptySrc: args["fail-on-empty-src"] });
25090
25546
  const state = {
25091
- baselinePath: run.baselinePath,
25547
+ targetDir,
25092
25548
  config,
25093
25549
  details: run.details,
25094
25550
  current: run.current,
@@ -25097,22 +25553,31 @@ const healthCheckCommand = defineCommand({
25097
25553
  out,
25098
25554
  referenceFields: run.referenceFields
25099
25555
  };
25100
- if (run.existing === void 0) {
25556
+ const existing = run.existing;
25557
+ if (existing === void 0) {
25101
25558
  handleMissingBaseline(state, args["update-baseline"], args["fail-on-missing-baseline"]);
25102
25559
  return;
25103
25560
  }
25104
- const { baseline, result, attribution } = run.existing;
25561
+ const { baseline, result, attribution } = existing;
25105
25562
  out.text(formatCompareDiff(result, run.details, attribution));
25563
+ const slack = findSlack({
25564
+ comparison: result,
25565
+ attribution,
25566
+ baseline,
25567
+ graphMeasured: !(config.graphMetricsEnabled && run.details.circularDependencies === void 0)
25568
+ });
25569
+ for (const line of formatSlack(slack)) out.text(line);
25106
25570
  reportCarriedRaises(run.referenceFields.raises, out);
25107
25571
  const regressions = collectRegressions(result, run.details);
25108
25572
  const graphUnavailable = formatGraphUnavailable(baseline, run.details, config.graphMetricsEnabled, run.details.graphDiagnostic);
25109
25573
  if (graphUnavailable !== void 0) out.notice(graphUnavailable);
25110
25574
  const stale = findStaleEntries(baseline, run.details, config.exempt);
25111
25575
  for (const warning of formatStaleEntries(stale)) out.notice(warning);
25576
+ const verdictPasses = result.pass && attribution.newOutliers.length === 0;
25112
25577
  out.json({
25113
25578
  status: "compared",
25114
25579
  ...run.referenceFields,
25115
- pass: result.pass,
25580
+ pass: verdictPasses,
25116
25581
  tolerance: result.tolerance,
25117
25582
  metrics: result.metrics,
25118
25583
  ceilings: result.ceilings,
@@ -25123,191 +25588,15 @@ const healthCheckCommand = defineCommand({
25123
25588
  unattributedOutliers: attribution.unattributedOutliers,
25124
25589
  graphMetricsEnabled: config.graphMetricsEnabled,
25125
25590
  graphMetricsMissing: graphUnavailable !== void 0,
25591
+ slack,
25126
25592
  staleEntries: stale,
25127
25593
  regressions,
25128
25594
  sources: run.details.sources
25129
25595
  });
25130
- if (args["update-baseline"] === true) applyBaselineUpdate(state, baseline, args.reset);
25131
- if (!result.pass || graphUnavailable !== void 0) process.exitCode = 1;
25596
+ if (args["update-baseline"] === true) applyBaselineUpdate(state, existing, args.reset);
25597
+ if (!verdictPasses || graphUnavailable !== void 0) process.exitCode = 1;
25132
25598
  }
25133
25599
  });
25134
- // src/codebase-health/raise.ts
25135
- const SIZE_RAISE_FACTOR = 1.01;
25136
- function sizeRaiseValue(measured) {
25137
- return Math.floor(measured * SIZE_RAISE_FACTOR) + 1;
25138
- }
25139
- const JsonObjectSchema = z.record(z.string(), z.unknown());
25140
- const EXEMPT_LEAF_KEYS = [
25141
- {
25142
- prefix: "fan-in",
25143
- key: "fanInOutliers"
25144
- },
25145
- {
25146
- prefix: "fan-out",
25147
- key: "fanOutOutliers"
25148
- },
25149
- {
25150
- prefix: "crowding",
25151
- key: "crowdedDirectories"
25152
- }
25153
- ];
25154
- function refuseDeniableReason(leaf, reason) {
25155
- const fixed = fixText(`// ${reason}`, {
25156
- offenders: resolveOffenders(),
25157
- path: "health-raise.ts"
25158
- });
25159
- const refused = fixed.decisions.find((decision) => !decision.applied);
25160
- if (refused !== void 0) throw new FatalError(`health:raise: the reason for --exempt "${leaf}" carries ${refused.hit.offender.codepoint} (${refused.hit.offender.name}): ${refused.reason ?? "this gate denies it"}. Rewrite it in ASCII.`);
25161
- return fixed.text.slice(3);
25162
- }
25163
- function parseExemptLeaf(leaf) {
25164
- const separator = leaf.indexOf(":");
25165
- const prefix = separator < 0 ? "" : leaf.slice(0, separator).trim();
25166
- const path = separator < 0 ? "" : leaf.slice(separator + 1).trim();
25167
- if (prefix === "size") throw new FatalError(`health:raise: --exempt "${leaf}" names a size budget, which has no module to exempt. Run without --exempt: "health:raise" widens a grown size budget by measurement.`);
25168
- const named = EXEMPT_LEAF_KEYS.find((entry) => entry.prefix === prefix);
25169
- if (named === void 0 || path === "") throw new FatalError(`health:raise: --exempt "${leaf}" names no exemptable leaf. Pass one "health:check" printed: "fan-in: <path>", "fan-out: <path>", "crowding: <path>".`);
25170
- return {
25171
- key: named.key,
25172
- path
25173
- };
25174
- }
25175
- function copyCeilings(ceilings) {
25176
- const copy = {};
25177
- for (const key of RATCHETED_METRIC_KEYS) {
25178
- const byModule = ceilings?.[key];
25179
- if (byModule !== void 0) copy[key] = { ...byModule };
25180
- }
25181
- return copy;
25182
- }
25183
- function writeCeiling(ceilings, key, module, to) {
25184
- const byModule = ceilings[key] ?? {};
25185
- byModule[module] = to;
25186
- ceilings[key] = byModule;
25187
- }
25188
- function headlineFor(baseline, comparison, key, exemptCount) {
25189
- const measured = comparison.metrics.find((metric) => metric.key === key)?.current;
25190
- if (measured === void 0) return void 0;
25191
- const remaining = Math.max(0, measured - exemptCount);
25192
- return baseline[key] === void 0 ? remaining : Math.max(baseline[key] ?? 0, remaining);
25193
- }
25194
- function exemptionWrites(input) {
25195
- const writes = [];
25196
- const notes = [];
25197
- for (const request of input.exemptions) {
25198
- const parsed = parseExemptLeaf(request.leaf);
25199
- if (parsed === void 0) continue;
25200
- const recorded = input.config.exempt[parsed.key]?.[parsed.path];
25201
- if (recorded !== void 0) {
25202
- notes.push(`health.exempt.${parsed.key}.${parsed.path} already reads "${recorded}"; the reason was not overwritten.`);
25203
- continue;
25204
- }
25205
- writes.push({
25206
- key: parsed.key,
25207
- path: parsed.path,
25208
- reason: refuseDeniableReason(request.leaf, request.reason)
25209
- });
25210
- }
25211
- return {
25212
- writes,
25213
- notes
25214
- };
25215
- }
25216
- function objectAt(parent, key, where) {
25217
- const existing = parent[key];
25218
- if (existing === void 0) return {};
25219
- const parsed = JsonObjectSchema.safeParse(existing);
25220
- if (!parsed.success) throw new FatalError(`health:raise: ${where}#${key} is not an object, so an exemption cannot be written there.`);
25221
- return { ...parsed.data };
25222
- }
25223
- function applyExemptions(tooling, writes) {
25224
- if (writes.length === 0) return void 0;
25225
- const file = JsonObjectSchema.safeParse(tooling ?? {});
25226
- if (!file.success) throw new FatalError(`health:raise: .tooling.json is not a JSON object, so no exemption can be written.`);
25227
- const result = { ...file.data };
25228
- for (const write of writes) {
25229
- const health = objectAt(result, "health", ".tooling.json");
25230
- const exempt = objectAt(health, "exempt", ".tooling.json#health");
25231
- const table = objectAt(exempt, write.key, ".tooling.json#health.exempt");
25232
- table[write.path] = write.reason;
25233
- exempt[write.key] = table;
25234
- health["exempt"] = exempt;
25235
- result["health"] = health;
25236
- }
25237
- return result;
25238
- }
25239
- function planHealthRaise(input) {
25240
- const ceilings = copyCeilings(input.baseline.moduleCeilings);
25241
- const ceilingWrites = [];
25242
- const headlines = {};
25243
- const notes = [];
25244
- const exemptions = exemptionWrites(input);
25245
- notes.push(...exemptions.notes);
25246
- const isExcused = (key, module) => exemptions.writes.some((write) => write.key === key && exemptKeyMatcher(write.path)(module));
25247
- const exemptedCount = /* @__PURE__ */ new Map();
25248
- const countExcused = (key, module) => {
25249
- if (isExcused(key, module)) exemptedCount.set(key, (exemptedCount.get(key) ?? 0) + 1);
25250
- };
25251
- for (const outlier of input.attribution.newOutliers) countExcused(outlier.key, outlier.module);
25252
- for (const ceiling of input.comparison.ceilings) if (!ceiling.pass) countExcused(ceiling.key, ceiling.module);
25253
- const outlierBase = input.attribution.outlierBase;
25254
- if (outlierBase.status === "unavailable") notes.push(`no "(new)" ceiling was written: the merge base ${outlierBase.mergeBase} could not be measured (${outlierBase.reason}), so nothing could be called a first crossing.`);
25255
- for (const outlier of input.attribution.newOutliers) {
25256
- if (isExcused(outlier.key, outlier.module)) continue;
25257
- writeCeiling(ceilings, outlier.key, outlier.module, outlier.current);
25258
- const headline = headlineFor(input.baseline, input.comparison, outlier.key, exemptedCount.get(outlier.key) ?? 0);
25259
- if (headline !== void 0) headlines[outlier.key] = headline;
25260
- ceilingWrites.push({
25261
- key: outlier.key,
25262
- module: outlier.module,
25263
- value: outlier.current,
25264
- ...headline === void 0 ? {} : { headline }
25265
- });
25266
- }
25267
- for (const ceiling of input.comparison.ceilings) {
25268
- if (ceiling.pass) continue;
25269
- if (isExcused(ceiling.key, ceiling.module)) continue;
25270
- writeCeiling(ceilings, ceiling.key, ceiling.module, ceiling.current);
25271
- ceilingWrites.push({
25272
- key: ceiling.key,
25273
- module: ceiling.module,
25274
- value: ceiling.current
25275
- });
25276
- }
25277
- const sizeBudgets = { ...input.baseline.sizeBudgets };
25278
- const sizeWrites = [];
25279
- for (const size of input.comparison.sizeResults) {
25280
- if (size.pass || size.measured === void 0 || size.ceiling === void 0) continue;
25281
- if (size.measured <= size.ceiling) continue;
25282
- const value = sizeRaiseValue(size.measured);
25283
- sizeBudgets[size.id] = value;
25284
- sizeWrites.push({
25285
- id: size.id,
25286
- value
25287
- });
25288
- }
25289
- return {
25290
- baseline: widenedBaseline(input.baseline, headlines, ceilings, sizeBudgets),
25291
- tooling: applyExemptions(input.tooling, exemptions.writes),
25292
- ceilings: ceilingWrites,
25293
- sizes: sizeWrites,
25294
- exemptions: exemptions.writes,
25295
- notes
25296
- };
25297
- }
25298
- function widenedBaseline(baseline, headlines, ceilings, sizeBudgets) {
25299
- const widened = { ...baseline };
25300
- for (const key of METRIC_KEYS) {
25301
- const headline = headlines[key];
25302
- if (headline !== void 0) widened[key] = headline;
25303
- }
25304
- widened.moduleCeilings = Object.keys(ceilings).length > 0 ? ceilings : void 0;
25305
- widened.sizeBudgets = Object.keys(sizeBudgets).length > 0 ? sizeBudgets : void 0;
25306
- return widened;
25307
- }
25308
- function planHasWrites(plan) {
25309
- return plan.ceilings.length > 0 || plan.sizes.length > 0 || plan.exemptions.length > 0;
25310
- }
25311
25600
  // src/commands/health-raise.ts
25312
25601
  const JsonValueSchema = z.json();
25313
25602
  const TOOLING_FILE = ".tooling.json";
@@ -25321,13 +25610,6 @@ function collectExemptPairs(rawArgs) {
25321
25610
  reason: reasons[index] ?? ""
25322
25611
  }));
25323
25612
  }
25324
- function formatterFor(targetDir) {
25325
- const detected = computeDefaults(targetDir);
25326
- return createContentFormatter({
25327
- targetDir,
25328
- formatter: loadToolingConfig(targetDir)?.formatter ?? detected.formatter
25329
- });
25330
- }
25331
25613
  function readToolingFile(targetDir) {
25332
25614
  const full = path.join(targetDir, TOOLING_FILE);
25333
25615
  if (!existsSync(full)) return void 0;
@@ -25343,7 +25625,7 @@ function readToolingFile(targetDir) {
25343
25625
  if (!parsed.success) throw new FatalError(`health:raise: ${TOOLING_FILE} is not JSON: ${parsed.error.message}`);
25344
25626
  return parsed.data;
25345
25627
  }
25346
- function describePlan(plan) {
25628
+ function describePlan$1(plan) {
25347
25629
  const lines = [];
25348
25630
  for (const ceiling of plan.ceilings) {
25349
25631
  const headline = ceiling.headline === void 0 ? "" : `, ${ceiling.key} set to ${String(ceiling.headline)}`;
@@ -25407,7 +25689,7 @@ const healthRaiseCommand = defineCommand({
25407
25689
  });
25408
25690
  const dryRun = args["dry-run"] === true;
25409
25691
  const wrote = dryRun ? [] : writePlan(targetDir, plan);
25410
- for (const line of describePlan(plan)) out.text(line);
25692
+ for (const line of describePlan$1(plan)) out.text(line);
25411
25693
  out.json({
25412
25694
  status: planHasWrites(plan) ? "raised" : "nothing-to-raise",
25413
25695
  dryRun,
@@ -25421,18 +25703,97 @@ const healthRaiseCommand = defineCommand({
25421
25703
  }
25422
25704
  });
25423
25705
  function writePlan(targetDir, plan) {
25424
- const format = formatterFor(targetDir);
25425
25706
  const wrote = [];
25426
25707
  if (plan.ceilings.length > 0 || plan.sizes.length > 0) {
25427
- writeFileSync(path.join(targetDir, "health-baseline.json"), format("health-baseline.json", serializeHealthBaseline(plan.baseline, plan.baseline.moduleCeilings, plan.baseline.sizeBudgets)));
25708
+ writeHealthBaseline(targetDir, plan.baseline);
25428
25709
  wrote.push("health-baseline.json");
25429
25710
  }
25430
25711
  if (plan.tooling !== void 0) {
25712
+ const format = healthFileFormatter(targetDir);
25431
25713
  writeFileSync(path.join(targetDir, TOOLING_FILE), format(TOOLING_FILE, JSON.stringify(plan.tooling, null, 2)));
25432
25714
  wrote.push(TOOLING_FILE);
25433
25715
  }
25434
25716
  return wrote;
25435
25717
  }
25718
+ // src/commands/health-tighten.ts
25719
+ const BASELINE_FILE = "health-baseline.json";
25720
+ function describePlan(plan) {
25721
+ const lines = [];
25722
+ for (const lowering of plan.lowered) lines.push(`health-baseline: ${lowering.leaf} ${String(lowering.from)} -> ${String(lowering.to)}`);
25723
+ for (const removal of plan.removed) lines.push(`health-baseline: ${removal.key}: ${removal.module} ceiling ${String(removal.value)} removed`);
25724
+ for (const cap of plan.caps) lines.push(`health-baseline: ${cap.key}: ${cap.module} capped at ${String(cap.value)}`);
25725
+ return lines;
25726
+ }
25727
+ const healthTightenCommand = defineCommand({
25728
+ meta: {
25729
+ name: "health:tighten",
25730
+ description: "Shed the slack this branch's own measurement proved the baseline holds, by measurement: no number is an argument. Rewrites health-baseline.json with each recorded count and module ceiling lowered to what the run measured, dead ceilings removed, and current outliers capped; it never touches .tooling.json. Does nothing unless .tooling.json#health.enabled is true."
25731
+ },
25732
+ args: {
25733
+ dir: {
25734
+ type: "positional",
25735
+ valueHint: "dir",
25736
+ description: "Project directory (default: current directory)",
25737
+ required: false
25738
+ },
25739
+ "dry-run": {
25740
+ type: "boolean",
25741
+ description: "Print what would be written and write nothing"
25742
+ },
25743
+ json: {
25744
+ type: "boolean",
25745
+ description: "Emit one JSON document: status (tightened | nothing-to-tighten | disabled | graph-unavailable), dryRun, wrote ([path]), lowered ([{leaf, from, to}]), removed ([{key, module, value}]), caps ([{key, module, value}]), reference ({status (read | no-baseline), mergeBase}). disabled and graph-unavailable carry no writes."
25746
+ }
25747
+ },
25748
+ run({ args }) {
25749
+ const targetDir = path.resolve(args.dir ?? ".");
25750
+ const out = createCliOutput(args.json === true);
25751
+ const dryRun = args["dry-run"] === true;
25752
+ const config = resolveHealthConfig(targetDir);
25753
+ if (!config.enabled) {
25754
+ out.notice("health: disabled (set .tooling.json#health.enabled to true to enable).");
25755
+ out.json({
25756
+ status: "disabled",
25757
+ dryRun
25758
+ });
25759
+ return;
25760
+ }
25761
+ const run = measureHealth(targetDir, config, out);
25762
+ if (run.existing === void 0) throw new FatalError(`health:tighten: no ${BASELINE_FILE} to lower. Run "health:check --update-baseline" first: a tighten lowers a recorded number, and there is nothing recorded.`);
25763
+ if (config.graphMetricsEnabled && run.details.circularDependencies === void 0) {
25764
+ out.notice(`Skipped: graph metrics are unavailable this run. Fix the cruise before tightening ${BASELINE_FILE}.`);
25765
+ out.json({
25766
+ status: "graph-unavailable",
25767
+ dryRun,
25768
+ wrote: []
25769
+ });
25770
+ process.exitCode = 1;
25771
+ return;
25772
+ }
25773
+ const plan = planHealthTighten({
25774
+ comparison: run.existing.result,
25775
+ attribution: run.existing.attribution,
25776
+ baseline: run.existing.baseline,
25777
+ graphMeasured: config.graphMetricsEnabled
25778
+ });
25779
+ const hasWrites = plan.lowered.length > 0 || plan.removed.length > 0 || plan.caps.length > 0;
25780
+ const wrote = [];
25781
+ if (hasWrites && !dryRun) {
25782
+ writeHealthBaseline(targetDir, plan.baseline);
25783
+ wrote.push(BASELINE_FILE);
25784
+ }
25785
+ for (const line of describePlan(plan)) out.text(line);
25786
+ out.json({
25787
+ status: hasWrites ? "tightened" : "nothing-to-tighten",
25788
+ dryRun,
25789
+ wrote,
25790
+ lowered: plan.lowered,
25791
+ removed: plan.removed,
25792
+ caps: plan.caps,
25793
+ reference: run.referenceFields.reference
25794
+ });
25795
+ }
25796
+ });
25436
25797
  // src/codebase-health/module-report.ts
25437
25798
  function normalizeModulePath(raw) {
25438
25799
  let normalized = raw.replace(/\\/g, "/");
@@ -25518,7 +25879,7 @@ function formatModuleReports(reports) {
25518
25879
  }
25519
25880
  return lines.join("\n");
25520
25881
  }
25521
- // src/commands/health-coverage-note.ts
25882
+ // src/commands/health-summary.ts
25522
25883
  function readCoverageNote(targetDir) {
25523
25884
  const file = path.join(targetDir, "coverage-baseline.json");
25524
25885
  if (!existsSync(file)) return void 0;
@@ -25529,7 +25890,6 @@ function readCoverageNote(targetDir) {
25529
25890
  return;
25530
25891
  }
25531
25892
  }
25532
- // src/commands/health-summary.ts
25533
25893
  function readModuleCeilings(targetDir) {
25534
25894
  const file = path.join(targetDir, "health-baseline.json");
25535
25895
  if (!existsSync(file)) return void 0;
@@ -29767,7 +30127,7 @@ async function runCli(config) {
29767
30127
  // src/cli-main.ts
29768
30128
  setLogLevel(resolveLogLevel({}));
29769
30129
  setForgejoLogger(log$1);
29770
- const displayVersion = "0.102.0";
30130
+ const displayVersion = "0.104.0";
29771
30131
  const bstSubCommands = {
29772
30132
  "repo:sync": syncCommand,
29773
30133
  "checks:run": runChecksCommand,
@@ -29798,6 +30158,7 @@ const bstSubCommands = {
29798
30158
  "coverage:status": coverageStatusCommand,
29799
30159
  "health:check": healthCheckCommand,
29800
30160
  "health:raise": healthRaiseCommand,
30161
+ "health:tighten": healthTightenCommand,
29801
30162
  "health:summary": healthSummaryCommand,
29802
30163
  "health:record": healthRecordCommand,
29803
30164
  "health:status": healthStatusCommand,