@bensandee/tooling 0.101.0 → 0.103.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.101.0"
176
+ version: "0.103.0"
177
177
  });
178
178
  // ../cli-kit/src/logger.ts
179
179
  const RANK = {
@@ -1732,6 +1732,7 @@ const AgentConfigSchema = z.strictObject({
1732
1732
  preRunRebase: z.boolean().optional().meta({ description: "Merge the current default branch into the work branch before the container starts (default true) -- for an implement (execute) run, and for a spec or plan rerun on an existing branch. A clean merge or an already-up-to-date branch runs the container as is; a conflicting merge is aborted, recorded on the run's status comment, and the run proceeds on the un-synced branch -- a conflict, timeout or failed merge never fails the run, for any phase. Only the execute phase keeps the two-strike rule: two consecutive conflicting attempts hand the unit to agent/repair before any container runs, while a docs run just tries again on its next slice. Set false to skip the attempt entirely for this repo, in every phase: no fetch, no merge, no abort, and the branch is worked exactly as cloned." }),
1733
1733
  backlog: z.boolean().optional().meta({ description: "Whether the agent may self-trigger backlog runs consuming this repo's .agent/findings/ ledger (default: on wherever the ledger exists, which only happens in a repo whose own review loop wrote it). A backlog run opens a pull request that fixes or refutes the pending findings; false disarms it, leaving the ledger to accumulate for a human. A run starts only once at least three findings are pending or one is older than seven days." }),
1734
1734
  lintSweep: LintSweepConfigSchema.optional().meta({ description: "The lint-warning sweep: a periodic agent job that measures this repo's oxlint warnings on its default branch in a container and, past minWarnings, opens a pull request carrying a generated plan for an agent/implement run to work off. Expired @compat warnings leave that plan and each get their own issue instead (see compatIssues)." }),
1735
+ openDocs: z.boolean().optional().meta({ description: "Whether the agent reads this repo's open specs and plans on its default branch and classifies each one's next phase for the control panel's Inbox (default: on). On unless `false`: the sweep is advice only -- it writes nothing to this repo or the forge, and the only write a row can cause is an operator's click. `false` skips the repo in the sweep entirely, so it costs no classifier runs and contributes no rows." }),
1735
1736
  priority: z.record(z.string(), z.enum([
1736
1737
  "critical",
1737
1738
  "high",
@@ -5799,9 +5800,9 @@ function buildManagedDevDeps(ctx) {
5799
5800
  const devDeps = { ...rootDevDeps(ctx.config) };
5800
5801
  if (!isMonorepo) Object.assign(devDeps, perPackageDevDeps(ctx.config));
5801
5802
  if (ctx.config.stack !== "none") devDeps["@bensandee/config"] = isWorkspacePackage(ctx, "@bensandee/config") ? "workspace:*" : "0.15.1";
5802
- if (!isWorkspacePackage(ctx, "@bensandee/tooling")) devDeps["@bensandee/tooling"] = "0.101.0";
5803
+ if (!isWorkspacePackage(ctx, "@bensandee/tooling")) devDeps["@bensandee/tooling"] = "0.103.0";
5803
5804
  if (ctx.config.useEslintPlugin && ctx.config.stack !== "none") devDeps["@bensandee/eslint-plugin"] = isWorkspacePackage(ctx, "@bensandee/eslint-plugin") ? "workspace:*" : "0.18.0";
5804
- if (wantsAgentCli(ctx)) devDeps[AGENT_CLI_PACKAGE] = "0.3.0";
5805
+ if (wantsAgentCli(ctx)) devDeps[AGENT_CLI_PACKAGE] = "0.3.1";
5805
5806
  if (ctx.config.formatter === "oxfmt") devDeps["oxfmt"] = {
5806
5807
  "@changesets/cli": "3.0.3",
5807
5808
  "@release-it/bumper": "8.0.1",
@@ -9596,7 +9597,7 @@ const AGENT_RULES_HEAD = [
9596
9597
  "- Use pnpm, not npm/yarn/npx. Run binaries with `pnpm exec`.",
9597
9598
  "- `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)."
9598
9599
  ];
9599
- const TS_TYPECAST_RULE = "- No typecasts (`as`/`any`). Use zod schemas, type guards, or narrowing.";
9600
+ 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.";
9600
9601
  const AGENT_RULES_MID = [
9601
9602
  "- Fix lint violations; don't suppress them. For `no-empty-function`, use a `{ /* no-op */ }` body, not a disable comment.",
9602
9603
  "- 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.",
@@ -9647,7 +9648,7 @@ function agentRulesTail(agentWorked) {
9647
9648
  "",
9648
9649
  "**Small change** -- a fix, a doc edit, a one-file tweak: work on the default branch and leave it unstaged. Don't commit; surface the commit message as text for the user to run.",
9649
9650
  "",
9650
- "**Large effort** -- anything that warranted a written plan or spec (spec, then plan, then code, each approved before the next): start it in a worktree (see the Git guide), commit as you go, finish with `pnpm exec bst pr:create`. Push later commits with `pnpm exec bst pr:update`, which rewrites nothing unless given `--title`/`--body`. The one exception: a headless agent run (a spec, plan, execute, or review container) never starts a worktree -- it works and commits on the branch it was started on."
9651
+ "**Large effort** -- anything that warranted a written plan or spec (spec, then plan, then code, each approved before the next): start it in a worktree (see the Git guide), commit as you go, finish with `pnpm exec bst pr:create`. Push later commits with `pnpm exec bst pr:update`, which rewrites nothing unless given `--title`/`--body`; `--closes <n>` on either links an issue. The one exception: a headless agent run (a spec, plan, execute, or review container) never starts a worktree -- it works and commits on the branch it was started on."
9651
9652
  ];
9652
9653
  }
9653
9654
  const COMMENTS_GUIDE_BODY = [
@@ -9700,7 +9701,7 @@ const GIT_GUIDE_BODY = [
9700
9701
  "",
9701
9702
  "## Issue linking",
9702
9703
  "",
9703
- "An issue never becomes a pull request -- the two share a numbering sequence but are separate objects, and a branch named `fix/273-...` links nothing. **A closing keyword in the PR body is the only link:** `Closes #273` (or `Fixes` / `Resolves`) closes the issue on merge. `pr:create` derives the body from `git log <base>..HEAD`, so a keyword in a commit message carries through; `pr:update` does not -- pass `--body`.",
9704
+ "**A closing keyword in the PR body is the only link.** A branch name like `fix/273-...` links nothing. Link an issue with `pnpm exec bst pr:create --closes 273` or `pr:update --closes 273`; each adds the line only when the body does not already close the issue. Add it from the first push, on a spec or plan pull request too, because the agent uses the keyword to find an issue's open pull request. Without the CLI, put `Closes #273` (or `Fixes` / `Resolves`) on its own line in the body.",
9704
9705
  "",
9705
9706
  "It fails silently: an issue still open after its PR merged means the merger lacked permission to close it. The merge succeeds either way, so nothing reports it.",
9706
9707
  "",
@@ -9940,7 +9941,7 @@ const HEALTH_RULE_TAIL = [
9940
9941
  "",
9941
9942
  "**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.",
9942
9943
  "",
9943
- "**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.",
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. A lowering travels the same way: `pnpm exec bst health:tighten` writes it, from the measurement.",
9944
9945
  "",
9945
9946
  "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.",
9946
9947
  "",
@@ -10401,7 +10402,7 @@ function reportFailures(failed, command) {
10401
10402
  function generateMigratePrompt(results, config, detected) {
10402
10403
  const sections = [];
10403
10404
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
10404
- sections.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.101.0 repo:sync\` on ${timestamp}_\n`);
10405
+ sections.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.103.0 repo:sync\` on ${timestamp}_\n`);
10405
10406
  const changed = results.filter((r) => r.action === "created" || r.action === "updated" || r.action === "archived");
10406
10407
  if (changed.length > 0) {
10407
10408
  const items = changed.map((r) => {
@@ -11334,7 +11335,7 @@ function createRealHealthExecutor(rootDir) {
11334
11335
  };
11335
11336
  }
11336
11337
  // src/codebase-health/reference.ts
11337
- const BASELINE_FILE$2 = "health-baseline.json";
11338
+ const BASELINE_FILE$3 = "health-baseline.json";
11338
11339
  const TOOLING_FILE$1 = ".tooling.json";
11339
11340
  function repoPrefix(executor, cwd) {
11340
11341
  const result = executor.exec("git", ["rev-parse", "--show-prefix"], { cwd });
@@ -11415,7 +11416,7 @@ function readReference(executor, opts) {
11415
11416
  kind: "unavailable",
11416
11417
  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.`
11417
11418
  };
11418
- const baselineText = showAt(executor, opts.cwd, sha, `${prefix}${BASELINE_FILE$2}`);
11419
+ const baselineText = showAt(executor, opts.cwd, sha, `${prefix}${BASELINE_FILE$3}`);
11419
11420
  const toolingText = showAt(executor, opts.cwd, sha, `${prefix}${TOOLING_FILE$1}`);
11420
11421
  const health = resolveHealthConfigFromContext({
11421
11422
  exists: (rel) => rel === TOOLING_FILE$1 && toolingText !== void 0,
@@ -11568,7 +11569,7 @@ function baselineRaises(reference, current) {
11568
11569
  }
11569
11570
  }
11570
11571
  if (reference.baseline !== void 0 && current.baseline === void 0) raises.push({
11571
- leaf: BASELINE_FILE$2,
11572
+ leaf: BASELINE_FILE$3,
11572
11573
  reference: "present",
11573
11574
  current: "absent"
11574
11575
  });
@@ -13330,6 +13331,7 @@ const PullReviewCommentSchema = z.object({
13330
13331
  user: z.object({ login: z.string() }).nullish()
13331
13332
  });
13332
13333
  z.array(PullReviewCommentSchema);
13334
+ z.array(z.object({ id: z.number() }));
13333
13335
  // src/release/publish/child-output.ts
13334
13336
  function childOutput(result) {
13335
13337
  return [result.stdout, result.stderr].filter((stream) => stream.trim() !== "").join("\n");
@@ -14447,18 +14449,20 @@ function extractClosingRefs(messages) {
14447
14449
  return [...byIssue.values()];
14448
14450
  }
14449
14451
  function issuesClosedBy(body, repository) {
14452
+ return issuesInRepository(extractClosingRefs([body]).map((ref) => ref.issue), repository);
14453
+ }
14454
+ function issuesInRepository(refs, repository) {
14450
14455
  const numbers = /* @__PURE__ */ new Set();
14451
- for (const ref of extractClosingRefs([body])) {
14452
- const name = ref.issue.toLowerCase();
14456
+ for (const ref of refs) {
14457
+ const name = ref.toLowerCase();
14453
14458
  const hash = name.lastIndexOf("#");
14454
14459
  const repoPart = name.slice(0, hash);
14455
- const number = Number(name.slice(hash + 1));
14456
14460
  if (repoPart !== "" && repoPart !== repository.toLowerCase()) continue;
14457
- numbers.add(number);
14461
+ numbers.add(Number(name.slice(hash + 1)));
14458
14462
  }
14459
- const closed = [...numbers];
14460
- closed.sort((a, b) => a - b);
14461
- return closed;
14463
+ const sorted = [...numbers];
14464
+ sorted.sort((a, b) => a - b);
14465
+ return sorted;
14462
14466
  }
14463
14467
  function closedIssues(text) {
14464
14468
  return new Set(extractClosingRefs([text]).map((ref) => ref.issue.toLowerCase()));
@@ -14473,6 +14477,15 @@ function carryForwardClosingRefs(source, target) {
14473
14477
  const refLines = missing.map((ref) => ref.text).join("\n");
14474
14478
  return target.trim() === "" ? refLines : `${target}\n\n${refLines}`;
14475
14479
  }
14480
+ function parseIssueList(value) {
14481
+ const numbers = /* @__PURE__ */ new Set();
14482
+ for (const part of value.split(",")) {
14483
+ const match = /^#?([1-9]\d*)$/.exec(part.trim());
14484
+ if (match?.[1] === void 0) throw new FatalError(`--closes takes issue numbers separated by commas, such as 12 or 12,15; got ${JSON.stringify(value)}.`);
14485
+ numbers.add(Number(match[1]));
14486
+ }
14487
+ return [...numbers];
14488
+ }
14476
14489
  // ../forgejo/src/issues.ts
14477
14490
  function repositoryFromUrl(url) {
14478
14491
  if (!URL.canParse(url)) return null;
@@ -15397,6 +15410,7 @@ function branchNotFoundMessage(conn, branch) {
15397
15410
  return `Branch ${branch} not found in ${conn.repository}`;
15398
15411
  }
15399
15412
  const RepoFullNameSchema = z.object({ full_name: z.string() });
15413
+ z.object({ description: z.string().optional() });
15400
15414
  async function getRepoFullName(executor, conn) {
15401
15415
  const res = await executor.fetch(repoBase(conn), { headers: authHeaders(conn) });
15402
15416
  if (!res.ok) await throwForgejoFailure(res, {
@@ -20016,7 +20030,51 @@ function checkClosingLinks(messages, plan, allowUnlink) {
20016
20030
  unlinked
20017
20031
  };
20018
20032
  }
20033
+ function addClosingIssues(plan, issues) {
20034
+ const wanted = issues.map((issue) => `Closes #${String(issue)}`).join("\n");
20035
+ const added = droppedClosingRefs([wanted], plan.effective.body).map((ref) => Number(ref.issue.slice(1)));
20036
+ if (added.length === 0) return {
20037
+ plan,
20038
+ added
20039
+ };
20040
+ const body = carryForwardClosingRefs(wanted, plan.effective.body);
20041
+ return {
20042
+ plan: {
20043
+ ...plan,
20044
+ patch: {
20045
+ ...plan.patch,
20046
+ body
20047
+ },
20048
+ effective: {
20049
+ ...plan.effective,
20050
+ body
20051
+ }
20052
+ },
20053
+ added
20054
+ };
20055
+ }
20019
20056
  const ALWAYS_PROTECTED = /* @__PURE__ */ new Set(["main", "master"]);
20057
+ async function planUpsert(host, existing, derived, options) {
20058
+ let plan;
20059
+ if (existing === null) plan = {
20060
+ patch: {
20061
+ title: derived.title,
20062
+ body: derived.body
20063
+ },
20064
+ effective: derived,
20065
+ previousBody: null
20066
+ };
20067
+ else plan = planPrUpdate(options, derived, prUpdateNeedsLive(options) ? await host.readLive(existing, options.signal ?? null) : null, host.wipTitles);
20068
+ if (options.closes === void 0) return {
20069
+ plan,
20070
+ closesAdded: void 0
20071
+ };
20072
+ const linked = addClosingIssues(plan, options.closes);
20073
+ return {
20074
+ plan: linked.plan,
20075
+ closesAdded: linked.added
20076
+ };
20077
+ }
20020
20078
  async function runPrUpsert$1(git, host, options) {
20021
20079
  const { cwd } = options;
20022
20080
  const mode = options.mode ?? "upsert";
@@ -20049,22 +20107,14 @@ async function runPrUpsert$1(git, host, options) {
20049
20107
  const existing = open?.number ?? null;
20050
20108
  assertModeAllows(mode, existing, branch);
20051
20109
  if (!options.dryRun && options.skipPush !== true) await pushBranch(git, cwd, branch, options.pushEnv, options.forceWithLease);
20052
- let plan;
20053
- if (existing === null) plan = {
20054
- patch: {
20055
- title: derived.title,
20056
- body: derived.body
20057
- },
20058
- effective: derived,
20059
- previousBody: null
20060
- };
20061
- else plan = planPrUpdate(options, derived, prUpdateNeedsLive(options) ? await host.readLive(existing, signal) : null, host.wipTitles);
20110
+ const { plan, closesAdded } = await planUpsert(host, existing, derived, options);
20062
20111
  const report = checkClosingLinks(messages, plan, options.allowUnlink === true);
20063
20112
  options.onClosingLinks?.(report);
20064
20113
  const shape = {
20065
20114
  branch,
20066
20115
  base: open?.base ?? localBase,
20067
- ...plan.effective
20116
+ ...plan.effective,
20117
+ ...closesAdded === void 0 ? {} : { closesAdded }
20068
20118
  };
20069
20119
  if (options.dryRun) return {
20070
20120
  action: existing === null ? "would-create" : "would-update",
@@ -20100,7 +20150,7 @@ function describeClosingLinks(report, flags) {
20100
20150
  const lines = [];
20101
20151
  if (report.fromCommits.length > 0) {
20102
20152
  const said = report.fromCommits.map((dropped) => dropped.text).join(", ");
20103
- lines.push(`The commits say ${said}, but the PR body does not -- the issue may not close on merge. Add it to ${flags.body}.`);
20153
+ lines.push(`The commits say ${said}, but the PR body does not -- the issue may not close on merge. Link it with ${flags.closes}.`);
20104
20154
  }
20105
20155
  if (report.unlinked.length > 0) {
20106
20156
  const lost = report.unlinked.map((dropped) => dropped.text).join(", ");
@@ -20152,15 +20202,17 @@ function formatPrCreate(result) {
20152
20202
  };
20153
20203
  }
20154
20204
  function formatPrUpdate(result, rewrites, flags) {
20205
+ const added = result.closesAdded ?? [];
20155
20206
  if (isDryRun(result)) return {
20156
20207
  lines: [`[dry-run] Would push ${prTarget(result)} to ${prLabel(result)}`],
20157
20208
  body: {
20158
- heading: rewrites ? "[dry-run] Body" : "[dry-run] Body (unchanged)",
20209
+ heading: rewrites || added.length > 0 ? "[dry-run] Body" : "[dry-run] Body (unchanged)",
20159
20210
  text: result.body
20160
20211
  }
20161
20212
  };
20162
20213
  const lines = [`Updated ${prLabel(result)} (${prTarget(result)})`];
20163
- if (!rewrites) lines.push(`Title and body left as authored -- pass ${flags.title}/${flags.body} to change them.`);
20214
+ if (added.length > 0) lines.push(`Linked ${added.map((issue) => `#${String(issue)}`).join(", ")} with a Closes line.`);
20215
+ else if (!rewrites) lines.push(`Title and body left as authored -- pass ${flags.title}/${flags.body} to change them.`);
20164
20216
  if (result.url !== null) lines.push(result.url);
20165
20217
  return {
20166
20218
  lines,
@@ -20173,7 +20225,7 @@ const BST_COMMANDS = {
20173
20225
  update: "pnpm exec bst pr:update"
20174
20226
  };
20175
20227
  const BST_FLAGS = {
20176
- body: "--body",
20228
+ closes: "--closes",
20177
20229
  allowUnlink: "--allow-unlink"
20178
20230
  };
20179
20231
  function executorGit(executor) {
@@ -20332,13 +20384,17 @@ const prCreateCommand = defineCommand({
20332
20384
  type: "boolean",
20333
20385
  description: "With --upsert: permit a --body that drops a closing keyword the PR carries"
20334
20386
  },
20387
+ closes: {
20388
+ type: "string",
20389
+ description: "Issues the PR closes, comma-separated (12 or 12,15): adds a Closes #<n> line to the body for each one it does not already close"
20390
+ },
20335
20391
  "dry-run": {
20336
20392
  type: "boolean",
20337
20393
  description: "Show what would happen without pushing"
20338
20394
  },
20339
20395
  json: {
20340
20396
  type: "boolean",
20341
- description: "Emit one JSON document: action (created | updated | would-create | would-update), number (or null), url (or null), branch, base, title, body, droppedRefs? ([{text, issue}]), dryRun, claims? ([{issue, owner: unclaimed | agent | person | null, label?}]) -- present after a create in an agent-enabled Forgejo repo whose body closes an issue; owner null means the labels could not be read. bst pr:create is the one command that reports claims; bst-fj pr:create does not. A create or would-create carries droppedRefs; on a dry run, number and url are null."
20397
+ description: "Emit one JSON document: action (created | updated | would-create | would-update), number (or null), url (or null), branch, base, title, body, droppedRefs? ([{text, issue}]), closesAdded? (with --closes: the issues it added a Closes line for), dryRun, claims? ([{issue, owner: unclaimed | agent | person | null, label?}]) -- present after a create in an agent-enabled Forgejo repo whose body closes an issue; owner null means the labels could not be read. bst pr:create is the one command that reports claims; bst-fj pr:create does not. A create or would-create carries droppedRefs; on a dry run, number and url are null."
20342
20398
  },
20343
20399
  verbose: {
20344
20400
  type: "boolean",
@@ -20358,6 +20414,7 @@ const prCreateCommand = defineCommand({
20358
20414
  body,
20359
20415
  base: args.base ?? void 0,
20360
20416
  allowUnlink: args["allow-unlink"] === true,
20417
+ closes: args.closes === void 0 ? void 0 : parseIssueList(args.closes),
20361
20418
  draft: args.draft === true ? true : void 0,
20362
20419
  dryRun: args["dry-run"] === true,
20363
20420
  verbose: args.verbose === true || isEnvVerbose()
@@ -20636,13 +20693,17 @@ const prUpdateCommand = defineCommand({
20636
20693
  type: "boolean",
20637
20694
  description: "Permit a --body that drops a closing keyword the current body carries"
20638
20695
  },
20696
+ closes: {
20697
+ type: "string",
20698
+ description: "Issues the PR closes, comma-separated (12 or 12,15): adds a Closes #<n> line to the body for each one it does not already close"
20699
+ },
20639
20700
  "dry-run": {
20640
20701
  type: "boolean",
20641
20702
  description: "Show what would happen without pushing"
20642
20703
  },
20643
20704
  json: {
20644
20705
  type: "boolean",
20645
- description: "Emit one JSON document: action (updated | would-update), number (or null), url (or null), branch, base, title, body, dryRun, rewrites. On a dry run, number and url are null."
20706
+ description: "Emit one JSON document: action (updated | would-update), number (or null), url (or null), branch, base, title, body, closesAdded? (with --closes: the issues it added a Closes line for), dryRun, rewrites. On a dry run, number and url are null."
20646
20707
  },
20647
20708
  verbose: {
20648
20709
  type: "boolean",
@@ -20661,6 +20722,7 @@ const prUpdateCommand = defineCommand({
20661
20722
  body,
20662
20723
  base: args.base ?? void 0,
20663
20724
  allowUnlink: args["allow-unlink"] === true,
20725
+ closes: args.closes === void 0 ? void 0 : parseIssueList(args.closes),
20664
20726
  draft: void 0,
20665
20727
  dryRun: args["dry-run"] === true,
20666
20728
  verbose: args.verbose === true || isEnvVerbose()
@@ -23296,13 +23358,13 @@ function serializeBaseline(baseline) {
23296
23358
  }
23297
23359
  // src/commands/coverage-check.ts
23298
23360
  const COVERAGE_SUMMARY_FILE$1 = "coverage/coverage-summary.json";
23299
- const BASELINE_FILE$1 = "coverage-baseline.json";
23300
- 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.`;
23361
+ const BASELINE_FILE$2 = "coverage-baseline.json";
23362
+ 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.`;
23301
23363
  function applyBaselineUpdate$1(out, baselinePath, baseline, current, options) {
23302
23364
  const { reset, floorPp } = options;
23303
23365
  if (reset) {
23304
23366
  writeFileSync(baselinePath, serializeBaseline(current));
23305
- out.notice(`Updated ${BASELINE_FILE$1} (--reset: unconditional).`);
23367
+ out.notice(`Updated ${BASELINE_FILE$2} (--reset: unconditional).`);
23306
23368
  } else if (floorPp !== void 0) {
23307
23369
  const merged = mergeTotalsWithFloor(baseline.totals, current.totals, floorPp);
23308
23370
  writeFileSync(baselinePath, serializeBaseline({
@@ -23310,10 +23372,10 @@ function applyBaselineUpdate$1(out, baselinePath, baseline, current, options) {
23310
23372
  totals: merged
23311
23373
  }));
23312
23374
  const held = TOTAL_KEYS.filter((key) => merged[key] !== current.totals[key]);
23313
- 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(", ")}).`);
23375
+ 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(", ")}).`);
23314
23376
  } else if (isFlatOrUp(baseline.totals, current.totals)) {
23315
23377
  writeFileSync(baselinePath, serializeBaseline(current));
23316
- out.notice(`Updated ${BASELINE_FILE$1} (all four totals flat-or-up).`);
23378
+ out.notice(`Updated ${BASELINE_FILE$2} (all four totals flat-or-up).`);
23317
23379
  } else out.notice(`Skipped baseline update: at least one total dropped below baseline. Add tests or adjust coverage.exclude before updating.`);
23318
23380
  }
23319
23381
  const coverageCheckCommand = defineCommand({
@@ -23359,20 +23421,20 @@ const coverageCheckCommand = defineCommand({
23359
23421
  return;
23360
23422
  }
23361
23423
  const summaryPath = path.join(targetDir, COVERAGE_SUMMARY_FILE$1);
23362
- const baselinePath = path.join(targetDir, BASELINE_FILE$1);
23424
+ const baselinePath = path.join(targetDir, BASELINE_FILE$2);
23363
23425
  if (!existsSync(summaryPath)) throw new FatalError(missingSummaryMessage(targetDir));
23364
23426
  const current = deriveBaseline(parseV8Summary(readFileSync(summaryPath, "utf-8")), { rootDir: targetDir });
23365
23427
  if (!existsSync(baselinePath)) {
23366
23428
  if (args["update-baseline"] === true) {
23367
23429
  writeFileSync(baselinePath, serializeBaseline(current));
23368
- out.notice(`Created ${BASELINE_FILE$1} (no prior baseline).`);
23430
+ out.notice(`Created ${BASELINE_FILE$2} (no prior baseline).`);
23369
23431
  out.json({
23370
23432
  status: "baseline-created",
23371
23433
  totals: current.totals
23372
23434
  });
23373
23435
  return;
23374
23436
  }
23375
- const message = `${BASELINE_FILE$1} not found. Run with --update-baseline to create one from the current run.`;
23437
+ const message = `${BASELINE_FILE$2} not found. Run with --update-baseline to create one from the current run.`;
23376
23438
  if (args["fail-on-missing-baseline"] === false) {
23377
23439
  out.notice(message);
23378
23440
  out.json({
@@ -23526,6 +23588,17 @@ function serializeHealthBaseline(metrics, ceilings, sizeBudgets) {
23526
23588
  if (sizeBudgets !== void 0 && Object.keys(sizeBudgets).length > 0) ordered["sizeBudgets"] = sizeBudgets;
23527
23589
  return JSON.stringify(ordered, null, 2) + "\n";
23528
23590
  }
23591
+ function healthFileFormatter(targetDir) {
23592
+ const detected = computeDefaults(targetDir);
23593
+ return createContentFormatter({
23594
+ targetDir,
23595
+ formatter: loadToolingConfig(targetDir)?.formatter ?? detected.formatter
23596
+ });
23597
+ }
23598
+ function writeHealthBaseline(targetDir, baseline) {
23599
+ const format = healthFileFormatter(targetDir);
23600
+ writeFileSync(path.join(targetDir, "health-baseline.json"), format("health-baseline.json", serializeHealthBaseline(baseline, baseline.moduleCeilings, baseline.sizeBudgets)));
23601
+ }
23529
23602
  // src/codebase-health/exclude.ts
23530
23603
  function normalize(rel) {
23531
23604
  const posix = rel.replace(/\\/g, "/");
@@ -24255,8 +24328,7 @@ function compareMetrics(baseline, current, tolerance = DEFAULT_TOLERANCE, curren
24255
24328
  };
24256
24329
  }
24257
24330
  function needsBaseMeasurement(result) {
24258
- const failedKeys = new Set(result.metrics.filter((m) => m.pass === false).map((m) => m.key));
24259
- return RATCHETED_METRIC_KEYS.some((key) => failedKeys.has(key) && result.uncoveredOutliers.some((o) => o.key === key));
24331
+ return result.uncoveredOutliers.length > 0;
24260
24332
  }
24261
24333
  function attributeOutliers(uncovered, base) {
24262
24334
  if (base.status !== "measured") return {
@@ -24318,139 +24390,198 @@ function isFlatOrBetter(baseline, current, currentCeilings = {}, sizes = []) {
24318
24390
  });
24319
24391
  return metricsFlat && ceilingsFlat && sizesFlat;
24320
24392
  }
24321
- // src/codebase-health/base-checkout.ts
24322
- const TEMP_PREFIX = "bst-health-base-";
24323
- function withMergeBaseCheckout(executor, targetDir, mergeBase, use) {
24324
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), TEMP_PREFIX));
24325
- const tree = path.join(tmp, "tree");
24326
- const index = path.join(tmp, "index");
24327
- try {
24328
- fs.mkdirSync(tree, { recursive: true });
24329
- const gitDir = gitOutput(executor.exec("git", ["rev-parse", "--absolute-git-dir"], { cwd: targetDir }), "git rev-parse --absolute-git-dir").trim();
24330
- const workRoot = gitOutput(executor.exec("git", ["rev-parse", "--show-toplevel"], { cwd: targetDir }), "git rev-parse --show-toplevel").trim();
24331
- const intoCheckout = (args) => executor.exec("git", [
24332
- `--git-dir=${gitDir}`,
24333
- `--work-tree=${tree}`,
24334
- ...args
24335
- ], {
24336
- cwd: tree,
24337
- env: { GIT_INDEX_FILE: index }
24338
- });
24339
- gitOutput(intoCheckout(["read-tree", mergeBase]), `git read-tree ${mergeBase.slice(0, 12)}`);
24340
- gitOutput(intoCheckout(["checkout-index", "-a"]), "git checkout-index -a");
24341
- mirrorNodeModules(workRoot, tree);
24342
- return use(tree);
24343
- } finally {
24344
- fs.rmSync(tmp, {
24345
- recursive: true,
24346
- force: true
24347
- });
24348
- }
24393
+ // src/codebase-health/raise.ts
24394
+ const SIZE_RAISE_FACTOR = 1.01;
24395
+ function sizeRaiseValue(measured) {
24396
+ return Math.floor(measured * SIZE_RAISE_FACTOR) + 1;
24349
24397
  }
24350
- function gitOutput(result, command) {
24351
- if (result.exitCode === 0) return result.stdout;
24352
- const detail = result.stderr.trim().split("\n")[0] ?? "";
24353
- throw new TransientError(`${command} failed: ${detail === "" ? `exit ${String(result.exitCode)}` : detail}`);
24398
+ const JsonObjectSchema = z.record(z.string(), z.unknown());
24399
+ const EXEMPT_LEAF_KEYS = [
24400
+ {
24401
+ prefix: "fan-in",
24402
+ key: "fanInOutliers"
24403
+ },
24404
+ {
24405
+ prefix: "fan-out",
24406
+ key: "fanOutOutliers"
24407
+ },
24408
+ {
24409
+ prefix: "crowding",
24410
+ key: "crowdedDirectories"
24411
+ }
24412
+ ];
24413
+ function refuseDeniableReason(leaf, reason) {
24414
+ const fixed = fixText(`// ${reason}`, {
24415
+ offenders: resolveOffenders(),
24416
+ path: "health-raise.ts"
24417
+ });
24418
+ const refused = fixed.decisions.find((decision) => !decision.applied);
24419
+ 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.`);
24420
+ return fixed.text.slice(3);
24354
24421
  }
24355
- function mirrorNodeModules(workingRoot, checkoutRoot) {
24356
- mirrorTree(workingRoot, checkoutRoot, "");
24422
+ function parseExemptLeaf(leaf) {
24423
+ const separator = leaf.indexOf(":");
24424
+ const prefix = separator < 0 ? "" : leaf.slice(0, separator).trim();
24425
+ const path = separator < 0 ? "" : leaf.slice(separator + 1).trim();
24426
+ 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.`);
24427
+ const named = EXEMPT_LEAF_KEYS.find((entry) => entry.prefix === prefix);
24428
+ 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>".`);
24429
+ return {
24430
+ key: named.key,
24431
+ path
24432
+ };
24357
24433
  }
24358
- function mirrorTree(workingRoot, checkoutRoot, rel) {
24359
- mirrorEntries(path.join(workingRoot, rel, "node_modules"), path.join(checkoutRoot, rel, "node_modules"));
24360
- let entries;
24361
- try {
24362
- entries = fs.readdirSync(path.join(checkoutRoot, rel), { withFileTypes: true });
24363
- } catch (_error) {
24364
- return;
24365
- }
24366
- for (const entry of entries) {
24367
- if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
24368
- if (entry.name === ".git" || entry.name === "node_modules") continue;
24369
- mirrorTree(workingRoot, checkoutRoot, path.join(rel, entry.name));
24434
+ function copyCeilings$1(ceilings) {
24435
+ const copy = {};
24436
+ for (const key of RATCHETED_METRIC_KEYS) {
24437
+ const byModule = ceilings?.[key];
24438
+ if (byModule !== void 0) copy[key] = { ...byModule };
24370
24439
  }
24440
+ return copy;
24371
24441
  }
24372
- function mirrorEntries(source, dest) {
24373
- let entries;
24374
- try {
24375
- entries = fs.readdirSync(source, { withFileTypes: true });
24376
- } catch (_error) {
24377
- return;
24378
- }
24379
- fs.mkdirSync(dest, { recursive: true });
24380
- for (const entry of entries) {
24381
- const src = path.join(source, entry.name);
24382
- const target = path.join(dest, entry.name);
24383
- if (entry.isSymbolicLink()) {
24384
- const link = safeReadlink(src);
24385
- if (link !== void 0 && !path.isAbsolute(link)) {
24386
- linkRelative(link, target);
24387
- continue;
24388
- }
24389
- } else if (entry.isDirectory() && entry.name.startsWith("@")) {
24390
- mirrorEntries(src, target);
24442
+ function writeCeiling$1(ceilings, key, module, to) {
24443
+ const byModule = ceilings[key] ?? {};
24444
+ byModule[module] = to;
24445
+ ceilings[key] = byModule;
24446
+ }
24447
+ function headlineFor(baseline, comparison, key, exemptCount) {
24448
+ const measured = comparison.metrics.find((metric) => metric.key === key)?.current;
24449
+ if (measured === void 0) return void 0;
24450
+ const remaining = Math.max(0, measured - exemptCount);
24451
+ return baseline[key] === void 0 ? remaining : Math.max(baseline[key] ?? 0, remaining);
24452
+ }
24453
+ function exemptionWrites(input) {
24454
+ const writes = [];
24455
+ const notes = [];
24456
+ for (const request of input.exemptions) {
24457
+ const parsed = parseExemptLeaf(request.leaf);
24458
+ if (parsed === void 0) continue;
24459
+ const recorded = input.config.exempt[parsed.key]?.[parsed.path];
24460
+ if (recorded !== void 0) {
24461
+ notes.push(`health.exempt.${parsed.key}.${parsed.path} already reads "${recorded}"; the reason was not overwritten.`);
24391
24462
  continue;
24392
24463
  }
24393
- try {
24394
- fs.symlinkSync(src, target, entry.isDirectory() ? "dir" : "file");
24395
- } catch (_error) {}
24396
- }
24397
- }
24398
- function safeReadlink(file) {
24399
- try {
24400
- return fs.readlinkSync(file);
24401
- } catch (_error) {
24402
- return;
24464
+ writes.push({
24465
+ key: parsed.key,
24466
+ path: parsed.path,
24467
+ reason: refuseDeniableReason(request.leaf, request.reason)
24468
+ });
24403
24469
  }
24404
- }
24405
- function linkRelative(link, target) {
24406
- try {
24407
- fs.symlinkSync(link, target);
24408
- } catch (_error) {}
24409
- }
24410
- // src/codebase-health/base-outliers.ts
24411
- function unavailable(reason) {
24412
24470
  return {
24413
- status: "unavailable",
24414
- reason: firstLine(reason)
24471
+ writes,
24472
+ notes
24415
24473
  };
24416
24474
  }
24417
- function firstLine(text) {
24418
- return text.trim().split("\n")[0] ?? "";
24475
+ function objectAt(parent, key, where) {
24476
+ const existing = parent[key];
24477
+ if (existing === void 0) return {};
24478
+ const parsed = JsonObjectSchema.safeParse(existing);
24479
+ if (!parsed.success) throw new FatalError(`health:raise: ${where}#${key} is not an object, so an exemption cannot be written there.`);
24480
+ return { ...parsed.data };
24419
24481
  }
24420
- function measureBaseOutliers(opts) {
24421
- const collect = opts.collect ?? collectDetails;
24422
- try {
24423
- return withMergeBaseCheckout(opts.executor, opts.targetDir, opts.mergeBase, (checkoutRoot) => {
24424
- const baseTarget = path.join(checkoutRoot, opts.prefix);
24425
- const collectConfig = buildCollectConfig(opts.config, { tsConfig: existsSync(path.join(baseTarget, "tsconfig.json")) ? "tsconfig.json" : void 0 });
24426
- const details = collect(createRealHealthExecutor(baseTarget), collectConfig);
24427
- const unresolved = details.unresolvedFirstParty;
24428
- if (unresolved !== void 0 && unresolved.length > 0) return unavailable(`the base cruise could not resolve ${String(unresolved.length)} first-party imports`);
24429
- if (opts.config.graphMetricsEnabled && details.circularDependencies === void 0) return unavailable("the base cruise produced no graph metrics");
24430
- return {
24431
- status: "measured",
24432
- ceilings: ceilingsFromDetails(details)
24433
- };
24434
- });
24435
- } catch (error) {
24436
- return unavailable(describeError$1(error));
24482
+ function applyExemptions(tooling, writes) {
24483
+ if (writes.length === 0) return void 0;
24484
+ const file = JsonObjectSchema.safeParse(tooling ?? {});
24485
+ if (!file.success) throw new FatalError(`health:raise: .tooling.json is not a JSON object, so no exemption can be written.`);
24486
+ const result = { ...file.data };
24487
+ for (const write of writes) {
24488
+ const health = objectAt(result, "health", ".tooling.json");
24489
+ const exempt = objectAt(health, "exempt", ".tooling.json#health");
24490
+ const table = objectAt(exempt, write.key, ".tooling.json#health.exempt");
24491
+ table[write.path] = write.reason;
24492
+ exempt[write.key] = table;
24493
+ health["exempt"] = exempt;
24494
+ result["health"] = health;
24437
24495
  }
24496
+ return result;
24438
24497
  }
24439
- // src/codebase-health/render.ts
24440
- const GRAPH_METRIC_KEYS = METRIC_KEYS.filter((key) => key !== "crowdedDirectories");
24441
- const LABELS = {
24442
- crowdedDirectories: "crowded directories",
24443
- circularDependencies: "circular dependencies",
24444
- fanInOutliers: "fan-in outliers",
24445
- fanOutOutliers: "fan-out outliers",
24446
- linesOfCode: "lines of code"
24447
- };
24448
- const CEILING_LABELS = {
24449
- crowdedDirectories: "crowding",
24450
- fanInOutliers: "fan-in",
24451
- fanOutOutliers: "fan-out"
24452
- };
24453
- function formatMetricsSummary(metrics) {
24498
+ function planHealthRaise(input) {
24499
+ const ceilings = copyCeilings$1(input.baseline.moduleCeilings);
24500
+ const ceilingWrites = [];
24501
+ const headlines = {};
24502
+ const notes = [];
24503
+ const exemptions = exemptionWrites(input);
24504
+ notes.push(...exemptions.notes);
24505
+ const isExcused = (key, module) => exemptions.writes.some((write) => write.key === key && exemptKeyMatcher(write.path)(module));
24506
+ const exemptedCount = /* @__PURE__ */ new Map();
24507
+ const countExcused = (key, module) => {
24508
+ if (isExcused(key, module)) exemptedCount.set(key, (exemptedCount.get(key) ?? 0) + 1);
24509
+ };
24510
+ for (const outlier of input.attribution.newOutliers) countExcused(outlier.key, outlier.module);
24511
+ for (const ceiling of input.comparison.ceilings) if (!ceiling.pass) countExcused(ceiling.key, ceiling.module);
24512
+ const outlierBase = input.attribution.outlierBase;
24513
+ 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.`);
24514
+ for (const outlier of input.attribution.newOutliers) {
24515
+ if (isExcused(outlier.key, outlier.module)) continue;
24516
+ writeCeiling$1(ceilings, outlier.key, outlier.module, outlier.current);
24517
+ const headline = headlineFor(input.baseline, input.comparison, outlier.key, exemptedCount.get(outlier.key) ?? 0);
24518
+ if (headline !== void 0) headlines[outlier.key] = headline;
24519
+ ceilingWrites.push({
24520
+ key: outlier.key,
24521
+ module: outlier.module,
24522
+ value: outlier.current,
24523
+ ...headline === void 0 ? {} : { headline }
24524
+ });
24525
+ }
24526
+ for (const ceiling of input.comparison.ceilings) {
24527
+ if (ceiling.pass) continue;
24528
+ if (isExcused(ceiling.key, ceiling.module)) continue;
24529
+ writeCeiling$1(ceilings, ceiling.key, ceiling.module, ceiling.current);
24530
+ ceilingWrites.push({
24531
+ key: ceiling.key,
24532
+ module: ceiling.module,
24533
+ value: ceiling.current
24534
+ });
24535
+ }
24536
+ const sizeBudgets = { ...input.baseline.sizeBudgets };
24537
+ const sizeWrites = [];
24538
+ for (const size of input.comparison.sizeResults) {
24539
+ if (size.pass || size.measured === void 0 || size.ceiling === void 0) continue;
24540
+ if (size.measured <= size.ceiling) continue;
24541
+ const value = sizeRaiseValue(size.measured);
24542
+ sizeBudgets[size.id] = value;
24543
+ sizeWrites.push({
24544
+ id: size.id,
24545
+ value
24546
+ });
24547
+ }
24548
+ return {
24549
+ baseline: widenedBaseline(input.baseline, headlines, ceilings, sizeBudgets),
24550
+ tooling: applyExemptions(input.tooling, exemptions.writes),
24551
+ ceilings: ceilingWrites,
24552
+ sizes: sizeWrites,
24553
+ exemptions: exemptions.writes,
24554
+ notes
24555
+ };
24556
+ }
24557
+ function widenedBaseline(baseline, headlines, ceilings, sizeBudgets) {
24558
+ const widened = { ...baseline };
24559
+ for (const key of METRIC_KEYS) {
24560
+ const headline = headlines[key];
24561
+ if (headline !== void 0) widened[key] = headline;
24562
+ }
24563
+ widened.moduleCeilings = Object.keys(ceilings).length > 0 ? ceilings : void 0;
24564
+ widened.sizeBudgets = Object.keys(sizeBudgets).length > 0 ? sizeBudgets : void 0;
24565
+ return widened;
24566
+ }
24567
+ function planHasWrites(plan) {
24568
+ return plan.ceilings.length > 0 || plan.sizes.length > 0 || plan.exemptions.length > 0;
24569
+ }
24570
+ // src/codebase-health/render.ts
24571
+ const GRAPH_METRIC_KEYS$1 = METRIC_KEYS.filter((key) => key !== "crowdedDirectories");
24572
+ const LABELS = {
24573
+ crowdedDirectories: "crowded directories",
24574
+ circularDependencies: "circular dependencies",
24575
+ fanInOutliers: "fan-in outliers",
24576
+ fanOutOutliers: "fan-out outliers",
24577
+ linesOfCode: "lines of code"
24578
+ };
24579
+ const CEILING_LABELS = {
24580
+ crowdedDirectories: "crowding",
24581
+ fanInOutliers: "fan-in",
24582
+ fanOutOutliers: "fan-out"
24583
+ };
24584
+ function formatMetricsSummary(metrics) {
24454
24585
  const lines = ["codebase health"];
24455
24586
  for (const key of METRIC_KEYS) {
24456
24587
  const value = metrics[key];
@@ -24525,7 +24656,6 @@ function outlierAttributionLines(attribution, failedKeys) {
24525
24656
  const lines = [];
24526
24657
  let printedAttribution = false;
24527
24658
  for (const o of attribution.newOutliers) {
24528
- if (!failedKeys.has(o.key)) continue;
24529
24659
  lines.push(` ${CEILING_LABELS[o.key]}: ${o.module} -- -> ${o.current} (new)`);
24530
24660
  printedAttribution = true;
24531
24661
  }
@@ -24573,12 +24703,12 @@ function formatCompareDiff(result, details, attribution) {
24573
24703
  }
24574
24704
  const failedKeys = new Set(result.metrics.filter((m) => m.pass === false).map((m) => m.key));
24575
24705
  lines.push(...outlierAttributionLines(attribution, failedKeys));
24576
- lines.push(result.pass ? "health: PASS" : "health: FAIL");
24706
+ lines.push(result.pass && attribution.newOutliers.length === 0 ? "health: PASS" : "health: FAIL");
24577
24707
  return lines.join("\n");
24578
24708
  }
24579
24709
  function formatGraphUnavailable(baseline, details, graphMetricsEnabled, diagnostic) {
24580
24710
  if (!graphMetricsEnabled || details.circularDependencies !== void 0) return void 0;
24581
- const missing = GRAPH_METRIC_KEYS.filter((key) => baseline[key] !== void 0);
24711
+ const missing = GRAPH_METRIC_KEYS$1.filter((key) => baseline[key] !== void 0);
24582
24712
  if (missing.length === 0) return void 0;
24583
24713
  return [`health: the dependency graph was not measured this run, but the baseline records ${missing.map((key) => LABELS[key]).join(", ")}.`, ...diagnosticDetailLines(diagnostic)].join("\n");
24584
24714
  }
@@ -24588,7 +24718,7 @@ function diagnosticDetailLines(diagnostic) {
24588
24718
  }
24589
24719
  function formatGraphUnavailableForSummary(details, graphMetricsEnabled, diagnostic) {
24590
24720
  if (!graphMetricsEnabled || details.circularDependencies !== void 0) return void 0;
24591
- return [`health: graph metrics unavailable this run (${GRAPH_METRIC_KEYS.map((key) => LABELS[key]).join(", ")}).`, ...diagnosticDetailLines(diagnostic)].join("\n");
24721
+ return [`health: graph metrics unavailable this run (${GRAPH_METRIC_KEYS$1.map((key) => LABELS[key]).join(", ")}).`, ...diagnosticDetailLines(diagnostic)].join("\n");
24592
24722
  }
24593
24723
  function formatStaleEntries(stale) {
24594
24724
  return stale.map((entry) => {
@@ -24629,150 +24759,458 @@ function formatUnresolvedFirstParty(entries) {
24629
24759
  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.`);
24630
24760
  return lines.join("\n");
24631
24761
  }
24762
+ function formatSlack(entries) {
24763
+ if (entries.length === 0) return [];
24764
+ 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.`];
24765
+ for (const entry of entries) {
24766
+ const suffix = slackSuffix(entry.kind);
24767
+ const from = entry.recorded ?? "--";
24768
+ const to = entry.measured ?? "--";
24769
+ lines.push(` ${entry.leaf} ${String(from)} -> ${String(to)} ${suffix}`);
24770
+ }
24771
+ return lines;
24772
+ }
24773
+ function slackSuffix(kind) {
24774
+ if (kind === "dead-ceiling") return "(dead ceiling)";
24775
+ if (kind === "uncapped") return "(uncapped)";
24776
+ return "(slack)";
24777
+ }
24632
24778
  const CARRIED_RAISES_FIRST_LINE = "raises carried by this branch:";
24633
24779
  function formatCarriedRaises(raises) {
24634
24780
  return [CARRIED_RAISES_FIRST_LINE, ...raises.map((r) => ` ${r.leaf}: ${r.reference} -> ${r.current}`)].join("\n");
24635
24781
  }
24636
- // src/codebase-health/size.ts
24637
- function byteLength(absolute) {
24638
- try {
24639
- const stats = statSync(absolute);
24640
- return stats.isFile() ? stats.size : void 0;
24641
- } catch (_error) {
24642
- return;
24782
+ // src/codebase-health/tighten.ts
24783
+ const GRAPH_METRIC_KEYS = new Set(METRIC_KEYS.filter((key) => key !== "crowdedDirectories"));
24784
+ function isGraphMetric(key) {
24785
+ return GRAPH_METRIC_KEYS.has(key);
24786
+ }
24787
+ function ceilingLeaf(key, module) {
24788
+ return `${CEILING_LABELS[key]}: ${module}`;
24789
+ }
24790
+ function copyCeilings(ceilings) {
24791
+ const copy = {};
24792
+ for (const key of RATCHETED_METRIC_KEYS) {
24793
+ const byModule = ceilings?.[key];
24794
+ if (byModule !== void 0) copy[key] = { ...byModule };
24643
24795
  }
24796
+ return copy;
24644
24797
  }
24645
- function measurerChanged(budget, changedNames) {
24646
- const patterns = [...budget.files, "package.json"];
24647
- const matches = picomatch(patterns, { dot: true });
24648
- return changedNames.some((name) => matches(name));
24798
+ function writeCeiling(ceilings, key, module, to) {
24799
+ const byModule = ceilings[key] ?? {};
24800
+ byModule[module] = to;
24801
+ ceilings[key] = byModule;
24649
24802
  }
24650
- function measureSizeBudgets(targetDir, budgets, options) {
24651
- const measurements = [];
24652
- for (const [id, budget] of Object.entries(budgets).toSorted(([a], [b]) => a.localeCompare(b))) measurements.push(measureOne(targetDir, id, budget, options));
24653
- return measurements;
24803
+ function dropCeiling(ceilings, key, module) {
24804
+ const byModule = ceilings[key];
24805
+ if (byModule === void 0) return;
24806
+ delete byModule[module];
24807
+ if (Object.keys(byModule).length === 0) delete ceilings[key];
24654
24808
  }
24655
- function measureOne(targetDir, id, budget, options) {
24656
- if ("file" in budget) {
24657
- const bytes = byteLength(path.join(targetDir, budget.file));
24658
- if (bytes === void 0) return {
24659
- id,
24660
- unmeasured: `no file at ${budget.file}`
24661
- };
24662
- return {
24663
- id,
24664
- measured: bytes
24665
- };
24809
+ function slackRecords(input) {
24810
+ const { comparison, attribution, baseline, graphMeasured } = input;
24811
+ const records = [];
24812
+ for (const key of METRIC_KEYS) {
24813
+ if (!graphMeasured && isGraphMetric(key)) continue;
24814
+ const recorded = baseline[key];
24815
+ const measured = comparison.metrics.find((metric) => metric.key === key)?.current;
24816
+ if (recorded === void 0 || measured === void 0) continue;
24817
+ if (measured >= recorded) continue;
24818
+ records.push({
24819
+ kind: "count",
24820
+ key,
24821
+ leaf: key,
24822
+ recorded,
24823
+ measured
24824
+ });
24666
24825
  }
24667
- if ("glob" in budget) {
24668
- const sizes = [];
24669
- for (const match of globSync(budget.glob, { cwd: targetDir })) {
24670
- const bytes = byteLength(path.join(targetDir, match));
24671
- if (bytes !== void 0) sizes.push(bytes);
24672
- }
24673
- if (sizes.length === 0) return {
24674
- id,
24675
- unmeasured: `glob ${budget.glob} matched no files`
24676
- };
24677
- let total = 0;
24678
- let largest = 0;
24679
- for (const bytes of sizes) {
24680
- total += bytes;
24681
- if (bytes > largest) largest = bytes;
24826
+ const measuredLeaves = new Set(comparison.ceilings.map((ceiling) => ceilingLeaf(ceiling.key, ceiling.module)));
24827
+ for (const ceiling of comparison.ceilings) {
24828
+ if (!graphMeasured && isGraphMetric(ceiling.key)) continue;
24829
+ if (ceiling.current >= ceiling.baseline) continue;
24830
+ records.push({
24831
+ kind: "ceiling",
24832
+ key: ceiling.key,
24833
+ module: ceiling.module,
24834
+ leaf: ceilingLeaf(ceiling.key, ceiling.module),
24835
+ recorded: ceiling.baseline,
24836
+ measured: ceiling.current
24837
+ });
24838
+ }
24839
+ for (const key of RATCHETED_METRIC_KEYS) {
24840
+ if (!graphMeasured && isGraphMetric(key)) continue;
24841
+ for (const [module, recorded] of Object.entries(baseline.moduleCeilings?.[key] ?? {})) {
24842
+ if (measuredLeaves.has(ceilingLeaf(key, module))) continue;
24843
+ records.push({
24844
+ kind: "dead-ceiling",
24845
+ key,
24846
+ module,
24847
+ leaf: ceilingLeaf(key, module),
24848
+ recorded
24849
+ });
24682
24850
  }
24683
- return {
24684
- id,
24685
- measured: budget.aggregate === "largest" ? largest : total
24686
- };
24687
24851
  }
24688
- const result = options.executor.exec("pnpm", [
24689
- "run",
24690
- "--silent",
24691
- budget.script
24692
- ], { cwd: targetDir });
24693
- if (result.exitCode !== 0) return {
24694
- id,
24695
- unmeasured: `script ${budget.script} exited ${String(result.exitCode)}`
24696
- };
24697
- const reported = readMeasureMarker(result.stdout);
24698
- if (reported === void 0) return {
24699
- id,
24700
- unmeasured: `script ${budget.script} printed no measure marker`
24852
+ for (const outlier of [...attribution.baseOutliers, ...attribution.unattributedOutliers]) {
24853
+ if (!graphMeasured && isGraphMetric(outlier.key)) continue;
24854
+ records.push({
24855
+ kind: "uncapped",
24856
+ key: outlier.key,
24857
+ module: outlier.module,
24858
+ leaf: ceilingLeaf(outlier.key, outlier.module),
24859
+ measured: outlier.current
24860
+ });
24861
+ }
24862
+ for (const size of comparison.sizeResults) {
24863
+ const recorded = baseline.sizeBudgets?.[size.id];
24864
+ if (recorded === void 0 || size.measured === void 0) continue;
24865
+ const to = sizeRaiseValue(size.measured);
24866
+ if (recorded <= to) continue;
24867
+ records.push({
24868
+ kind: "size",
24869
+ id: size.id,
24870
+ leaf: `size: ${size.id}`,
24871
+ recorded,
24872
+ measured: size.measured,
24873
+ to
24874
+ });
24875
+ }
24876
+ return records;
24877
+ }
24878
+ function slackEntry(record) {
24879
+ if (record.kind === "uncapped") return {
24880
+ kind: record.kind,
24881
+ leaf: record.leaf,
24882
+ measured: record.measured
24701
24883
  };
24702
- if (!measurerChanged(budget, options.changedNames)) return {
24703
- id,
24704
- measured: reported
24884
+ if (record.kind === "dead-ceiling") return {
24885
+ kind: record.kind,
24886
+ leaf: record.leaf,
24887
+ recorded: record.recorded
24705
24888
  };
24706
24889
  return {
24707
- id,
24708
- measured: reported,
24709
- measurerChanged: true
24890
+ kind: record.kind,
24891
+ leaf: record.leaf,
24892
+ recorded: record.recorded,
24893
+ measured: record.measured
24710
24894
  };
24711
24895
  }
24712
- // src/codebase-health/measure.ts
24713
- const BASELINE_FILE = "health-baseline.json";
24714
- function readTargetReference(executor, targetDir, out) {
24715
- const context = detectHealthContext(targetDir);
24716
- const read = readReference(executor, {
24717
- cwd: targetDir,
24718
- stack: context.stack,
24719
- isMonorepo: context.isMonorepo,
24720
- ciEvent: processCiEventSource()
24721
- });
24722
- if (read.kind === "read" && read.warning !== void 0) out.notice(read.warning);
24723
- return read;
24724
- }
24725
- function reportCarriedRaises(raises, out) {
24726
- if (raises.length === 0) return;
24727
- out.text(formatCarriedRaises(raises));
24728
- out.text(formatWarnMarker(raises.length));
24896
+ function findSlack(input) {
24897
+ return slackRecords(input).map(slackEntry);
24729
24898
  }
24730
- function assessRaises(executor, targetDir, current, out) {
24731
- const read = readTargetReference(executor, targetDir, out);
24732
- if (read.kind === "unavailable") throw new FatalError(read.reason);
24733
- const reference = read.reference;
24734
- if (reference.baseline === void 0) {
24735
- out.notice(`${BASELINE_FILE} has no counterpart on the default branch yet, so there is nothing to raise against.`);
24736
- return {
24737
- fields: {
24738
- reference: {
24739
- status: "no-baseline",
24740
- mergeBase: reference.mergeBase
24741
- },
24742
- raises: []
24743
- },
24744
- prefix: reference.prefix
24745
- };
24899
+ function planHealthTighten(input) {
24900
+ const ceilings = copyCeilings(input.baseline.moduleCeilings);
24901
+ const sizeBudgets = { ...input.baseline.sizeBudgets };
24902
+ const tightened = { ...input.baseline };
24903
+ const lowered = [];
24904
+ const removed = [];
24905
+ const caps = [];
24906
+ for (const record of slackRecords(input)) switch (record.kind) {
24907
+ case "count":
24908
+ tightened[record.key] = record.measured;
24909
+ lowered.push({
24910
+ leaf: record.leaf,
24911
+ from: record.recorded,
24912
+ to: record.measured
24913
+ });
24914
+ break;
24915
+ case "ceiling":
24916
+ writeCeiling(ceilings, record.key, record.module, record.measured);
24917
+ lowered.push({
24918
+ leaf: record.leaf,
24919
+ from: record.recorded,
24920
+ to: record.measured
24921
+ });
24922
+ break;
24923
+ case "dead-ceiling":
24924
+ dropCeiling(ceilings, record.key, record.module);
24925
+ removed.push({
24926
+ key: record.key,
24927
+ module: record.module,
24928
+ value: record.recorded
24929
+ });
24930
+ break;
24931
+ case "uncapped":
24932
+ writeCeiling(ceilings, record.key, record.module, record.measured);
24933
+ caps.push({
24934
+ key: record.key,
24935
+ module: record.module,
24936
+ value: record.measured
24937
+ });
24938
+ break;
24939
+ case "size":
24940
+ sizeBudgets[record.id] = record.to;
24941
+ lowered.push({
24942
+ leaf: record.leaf,
24943
+ from: record.recorded,
24944
+ to: record.to
24945
+ });
24746
24946
  }
24947
+ tightened.moduleCeilings = Object.keys(ceilings).length > 0 ? ceilings : void 0;
24948
+ tightened.sizeBudgets = Object.keys(sizeBudgets).length > 0 ? sizeBudgets : void 0;
24747
24949
  return {
24748
- fields: {
24749
- reference: {
24750
- status: "read",
24751
- mergeBase: reference.mergeBase
24752
- },
24753
- raises: findRaises(reference, current)
24754
- },
24755
- prefix: reference.prefix
24950
+ baseline: tightened,
24951
+ lowered,
24952
+ removed,
24953
+ caps
24756
24954
  };
24757
24955
  }
24758
- function attributeRun(run) {
24759
- const { result, executor, targetDir, fields, prefix, config } = run;
24760
- if (!needsBaseMeasurement(result)) return attributeOutliers(result.uncoveredOutliers, { status: "not-needed" });
24761
- const mergeBase = fields.reference.mergeBase;
24762
- const measurement = measureBaseOutliers({
24763
- executor,
24764
- targetDir,
24765
- mergeBase,
24766
- prefix,
24767
- config
24768
- });
24769
- const base = measurement.status === "measured" ? {
24770
- status: "measured",
24771
- mergeBase,
24772
- ceilings: measurement.ceilings
24773
- } : {
24774
- status: "unavailable",
24775
- mergeBase,
24956
+ // src/codebase-health/base-checkout.ts
24957
+ const TEMP_PREFIX = "bst-health-base-";
24958
+ function withMergeBaseCheckout(executor, targetDir, mergeBase, use) {
24959
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), TEMP_PREFIX));
24960
+ const tree = path.join(tmp, "tree");
24961
+ const index = path.join(tmp, "index");
24962
+ try {
24963
+ fs.mkdirSync(tree, { recursive: true });
24964
+ const gitDir = gitOutput(executor.exec("git", ["rev-parse", "--absolute-git-dir"], { cwd: targetDir }), "git rev-parse --absolute-git-dir").trim();
24965
+ const workRoot = gitOutput(executor.exec("git", ["rev-parse", "--show-toplevel"], { cwd: targetDir }), "git rev-parse --show-toplevel").trim();
24966
+ const intoCheckout = (args) => executor.exec("git", [
24967
+ `--git-dir=${gitDir}`,
24968
+ `--work-tree=${tree}`,
24969
+ ...args
24970
+ ], {
24971
+ cwd: tree,
24972
+ env: { GIT_INDEX_FILE: index }
24973
+ });
24974
+ gitOutput(intoCheckout(["read-tree", mergeBase]), `git read-tree ${mergeBase.slice(0, 12)}`);
24975
+ gitOutput(intoCheckout(["checkout-index", "-a"]), "git checkout-index -a");
24976
+ mirrorNodeModules(workRoot, tree);
24977
+ return use(tree);
24978
+ } finally {
24979
+ fs.rmSync(tmp, {
24980
+ recursive: true,
24981
+ force: true
24982
+ });
24983
+ }
24984
+ }
24985
+ function gitOutput(result, command) {
24986
+ if (result.exitCode === 0) return result.stdout;
24987
+ const detail = result.stderr.trim().split("\n")[0] ?? "";
24988
+ throw new TransientError(`${command} failed: ${detail === "" ? `exit ${String(result.exitCode)}` : detail}`);
24989
+ }
24990
+ function mirrorNodeModules(workingRoot, checkoutRoot) {
24991
+ mirrorTree(workingRoot, checkoutRoot, "");
24992
+ }
24993
+ function mirrorTree(workingRoot, checkoutRoot, rel) {
24994
+ mirrorEntries(path.join(workingRoot, rel, "node_modules"), path.join(checkoutRoot, rel, "node_modules"));
24995
+ let entries;
24996
+ try {
24997
+ entries = fs.readdirSync(path.join(checkoutRoot, rel), { withFileTypes: true });
24998
+ } catch (_error) {
24999
+ return;
25000
+ }
25001
+ for (const entry of entries) {
25002
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
25003
+ if (entry.name === ".git" || entry.name === "node_modules") continue;
25004
+ mirrorTree(workingRoot, checkoutRoot, path.join(rel, entry.name));
25005
+ }
25006
+ }
25007
+ function mirrorEntries(source, dest) {
25008
+ let entries;
25009
+ try {
25010
+ entries = fs.readdirSync(source, { withFileTypes: true });
25011
+ } catch (_error) {
25012
+ return;
25013
+ }
25014
+ fs.mkdirSync(dest, { recursive: true });
25015
+ for (const entry of entries) {
25016
+ const src = path.join(source, entry.name);
25017
+ const target = path.join(dest, entry.name);
25018
+ if (entry.isSymbolicLink()) {
25019
+ const link = safeReadlink(src);
25020
+ if (link !== void 0 && !path.isAbsolute(link)) {
25021
+ linkRelative(link, target);
25022
+ continue;
25023
+ }
25024
+ } else if (entry.isDirectory() && entry.name.startsWith("@")) {
25025
+ mirrorEntries(src, target);
25026
+ continue;
25027
+ }
25028
+ try {
25029
+ fs.symlinkSync(src, target, entry.isDirectory() ? "dir" : "file");
25030
+ } catch (_error) {}
25031
+ }
25032
+ }
25033
+ function safeReadlink(file) {
25034
+ try {
25035
+ return fs.readlinkSync(file);
25036
+ } catch (_error) {
25037
+ return;
25038
+ }
25039
+ }
25040
+ function linkRelative(link, target) {
25041
+ try {
25042
+ fs.symlinkSync(link, target);
25043
+ } catch (_error) {}
25044
+ }
25045
+ // src/codebase-health/base-outliers.ts
25046
+ function unavailable(reason) {
25047
+ return {
25048
+ status: "unavailable",
25049
+ reason: firstLine(reason)
25050
+ };
25051
+ }
25052
+ function firstLine(text) {
25053
+ return text.trim().split("\n")[0] ?? "";
25054
+ }
25055
+ function measureBaseOutliers(opts) {
25056
+ const collect = opts.collect ?? collectDetails;
25057
+ try {
25058
+ return withMergeBaseCheckout(opts.executor, opts.targetDir, opts.mergeBase, (checkoutRoot) => {
25059
+ const baseTarget = path.join(checkoutRoot, opts.prefix);
25060
+ const collectConfig = buildCollectConfig(opts.config, { tsConfig: existsSync(path.join(baseTarget, "tsconfig.json")) ? "tsconfig.json" : void 0 });
25061
+ const details = collect(createRealHealthExecutor(baseTarget), collectConfig);
25062
+ const unresolved = details.unresolvedFirstParty;
25063
+ if (unresolved !== void 0 && unresolved.length > 0) return unavailable(`the base cruise could not resolve ${String(unresolved.length)} first-party imports`);
25064
+ if (opts.config.graphMetricsEnabled && details.circularDependencies === void 0) return unavailable("the base cruise produced no graph metrics");
25065
+ return {
25066
+ status: "measured",
25067
+ ceilings: ceilingsFromDetails(details)
25068
+ };
25069
+ });
25070
+ } catch (error) {
25071
+ return unavailable(describeError$1(error));
25072
+ }
25073
+ }
25074
+ // src/codebase-health/size.ts
25075
+ function byteLength(absolute) {
25076
+ try {
25077
+ const stats = statSync(absolute);
25078
+ return stats.isFile() ? stats.size : void 0;
25079
+ } catch (_error) {
25080
+ return;
25081
+ }
25082
+ }
25083
+ function measurerChanged(budget, changedNames) {
25084
+ const patterns = [...budget.files, "package.json"];
25085
+ const matches = picomatch(patterns, { dot: true });
25086
+ return changedNames.some((name) => matches(name));
25087
+ }
25088
+ function measureSizeBudgets(targetDir, budgets, options) {
25089
+ const measurements = [];
25090
+ for (const [id, budget] of Object.entries(budgets).toSorted(([a], [b]) => a.localeCompare(b))) measurements.push(measureOne(targetDir, id, budget, options));
25091
+ return measurements;
25092
+ }
25093
+ function measureOne(targetDir, id, budget, options) {
25094
+ if ("file" in budget) {
25095
+ const bytes = byteLength(path.join(targetDir, budget.file));
25096
+ if (bytes === void 0) return {
25097
+ id,
25098
+ unmeasured: `no file at ${budget.file}`
25099
+ };
25100
+ return {
25101
+ id,
25102
+ measured: bytes
25103
+ };
25104
+ }
25105
+ if ("glob" in budget) {
25106
+ const sizes = [];
25107
+ for (const match of globSync(budget.glob, { cwd: targetDir })) {
25108
+ const bytes = byteLength(path.join(targetDir, match));
25109
+ if (bytes !== void 0) sizes.push(bytes);
25110
+ }
25111
+ if (sizes.length === 0) return {
25112
+ id,
25113
+ unmeasured: `glob ${budget.glob} matched no files`
25114
+ };
25115
+ let total = 0;
25116
+ let largest = 0;
25117
+ for (const bytes of sizes) {
25118
+ total += bytes;
25119
+ if (bytes > largest) largest = bytes;
25120
+ }
25121
+ return {
25122
+ id,
25123
+ measured: budget.aggregate === "largest" ? largest : total
25124
+ };
25125
+ }
25126
+ const result = options.executor.exec("pnpm", [
25127
+ "run",
25128
+ "--silent",
25129
+ budget.script
25130
+ ], { cwd: targetDir });
25131
+ if (result.exitCode !== 0) return {
25132
+ id,
25133
+ unmeasured: `script ${budget.script} exited ${String(result.exitCode)}`
25134
+ };
25135
+ const reported = readMeasureMarker(result.stdout);
25136
+ if (reported === void 0) return {
25137
+ id,
25138
+ unmeasured: `script ${budget.script} printed no measure marker`
25139
+ };
25140
+ if (!measurerChanged(budget, options.changedNames)) return {
25141
+ id,
25142
+ measured: reported
25143
+ };
25144
+ return {
25145
+ id,
25146
+ measured: reported,
25147
+ measurerChanged: true
25148
+ };
25149
+ }
25150
+ // src/codebase-health/measure.ts
25151
+ const BASELINE_FILE$1 = "health-baseline.json";
25152
+ function readTargetReference(executor, targetDir, out) {
25153
+ const context = detectHealthContext(targetDir);
25154
+ const read = readReference(executor, {
25155
+ cwd: targetDir,
25156
+ stack: context.stack,
25157
+ isMonorepo: context.isMonorepo,
25158
+ ciEvent: processCiEventSource()
25159
+ });
25160
+ if (read.kind === "read" && read.warning !== void 0) out.notice(read.warning);
25161
+ return read;
25162
+ }
25163
+ function reportCarriedRaises(raises, out) {
25164
+ if (raises.length === 0) return;
25165
+ out.text(formatCarriedRaises(raises));
25166
+ out.text(formatWarnMarker(raises.length));
25167
+ }
25168
+ function assessRaises(executor, targetDir, current, out) {
25169
+ const read = readTargetReference(executor, targetDir, out);
25170
+ if (read.kind === "unavailable") throw new FatalError(read.reason);
25171
+ const reference = read.reference;
25172
+ if (reference.baseline === void 0) {
25173
+ out.notice(`${BASELINE_FILE$1} has no counterpart on the default branch yet, so there is nothing to raise against.`);
25174
+ return {
25175
+ fields: {
25176
+ reference: {
25177
+ status: "no-baseline",
25178
+ mergeBase: reference.mergeBase
25179
+ },
25180
+ raises: []
25181
+ },
25182
+ prefix: reference.prefix
25183
+ };
25184
+ }
25185
+ return {
25186
+ fields: {
25187
+ reference: {
25188
+ status: "read",
25189
+ mergeBase: reference.mergeBase
25190
+ },
25191
+ raises: findRaises(reference, current)
25192
+ },
25193
+ prefix: reference.prefix
25194
+ };
25195
+ }
25196
+ function attributeRun(run) {
25197
+ const { result, executor, targetDir, fields, prefix, config } = run;
25198
+ if (!needsBaseMeasurement(result)) return attributeOutliers(result.uncoveredOutliers, { status: "not-needed" });
25199
+ const mergeBase = fields.reference.mergeBase;
25200
+ const measurement = measureBaseOutliers({
25201
+ executor,
25202
+ targetDir,
25203
+ mergeBase,
25204
+ prefix,
25205
+ config
25206
+ });
25207
+ const base = measurement.status === "measured" ? {
25208
+ status: "measured",
25209
+ mergeBase,
25210
+ ceilings: measurement.ceilings
25211
+ } : {
25212
+ status: "unavailable",
25213
+ mergeBase,
24776
25214
  reason: measurement.reason
24777
25215
  };
24778
25216
  return attributeOutliers(result.uncoveredOutliers, base);
@@ -24798,7 +25236,7 @@ function measureHealth(targetDir, config, out, opts = {}) {
24798
25236
  const ceilings = ceilingsFromDetails(details);
24799
25237
  refuseUnresolvedImports(details);
24800
25238
  refuseEmptyScope(details, config, opts.failOnEmptySrc, out);
24801
- const baselinePath = path.join(targetDir, BASELINE_FILE);
25239
+ const baselinePath = path.join(targetDir, BASELINE_FILE$1);
24802
25240
  const treeBaseline = existsSync(baselinePath) ? parseHealthBaseline(readFileSync(baselinePath, "utf-8")) : void 0;
24803
25241
  const raiseAssessment = assessRaises(executor, targetDir, {
24804
25242
  baseline: treeBaseline,
@@ -24890,7 +25328,7 @@ function assessSwitchOff(executor, targetDir, config, out) {
24890
25328
  if (read.kind === "unavailable") return void 0;
24891
25329
  const reference = read.reference;
24892
25330
  if (!reference.health.enabled || reference.baseline === void 0) return void 0;
24893
- const baselinePath = path.join(targetDir, BASELINE_FILE);
25331
+ const baselinePath = path.join(targetDir, BASELINE_FILE$1);
24894
25332
  const treeBaseline = existsSync(baselinePath) ? parseHealthBaseline(readFileSync(baselinePath, "utf-8")) : void 0;
24895
25333
  const named = healthOverridesAt(targetDir);
24896
25334
  const limitsOver = { ...config };
@@ -24916,10 +25354,10 @@ function sizeValuesToRecord(baseline, sizes, reset) {
24916
25354
  return Object.keys(recorded).length > 0 ? recorded : void 0;
24917
25355
  }
24918
25356
  function handleMissingBaseline(state, updateBaseline, failOnMissingBaseline) {
24919
- const { baselinePath, config, details, current, ceilings, sizes, out } = state;
25357
+ const { targetDir, config, details, current, ceilings, sizes, out } = state;
24920
25358
  if (updateBaseline === true) {
24921
25359
  if (config.graphMetricsEnabled && details.circularDependencies === void 0) {
24922
- out.notice(`Skipped baseline creation: graph metrics are unavailable this run. Fix the cruise before creating ${BASELINE_FILE}.`);
25360
+ out.notice(`Skipped baseline creation: graph metrics are unavailable this run. Fix the cruise before creating ${BASELINE_FILE$1}.`);
24923
25361
  out.json({
24924
25362
  status: "graph-unavailable",
24925
25363
  ...state.referenceFields,
@@ -24930,322 +25368,185 @@ function handleMissingBaseline(state, updateBaseline, failOnMissingBaseline) {
24930
25368
  process.exitCode = 1;
24931
25369
  return;
24932
25370
  }
24933
- writeFileSync(baselinePath, serializeHealthBaseline(current, ceilings, sizeValuesToRecord(void 0, sizes, false)));
24934
- out.notice(`Created ${BASELINE_FILE} (no prior baseline).`);
24935
- out.json({
24936
- status: "baseline-created",
24937
- ...state.referenceFields,
24938
- metrics: current,
24939
- sources: details.sources
25371
+ writeHealthBaseline(targetDir, {
25372
+ ...current,
25373
+ moduleCeilings: ceilings,
25374
+ sizeBudgets: sizeValuesToRecord(void 0, sizes, false)
24940
25375
  });
24941
- reportCarriedRaises(state.referenceFields.raises, out);
24942
- return;
24943
- }
24944
- const message = `${BASELINE_FILE} not found. Run with --update-baseline to create one from the current run.`;
24945
- if (failOnMissingBaseline === false) {
24946
- out.notice(message);
25376
+ out.notice(`Created ${BASELINE_FILE$1} (no prior baseline).`);
24947
25377
  out.json({
24948
- status: "missing-baseline",
25378
+ status: "baseline-created",
24949
25379
  ...state.referenceFields,
24950
25380
  metrics: current,
24951
- sources: details.sources
24952
- });
24953
- reportCarriedRaises(state.referenceFields.raises, out);
24954
- return;
24955
- }
24956
- reportCarriedRaises(state.referenceFields.raises, out);
24957
- throw new FatalError(message);
24958
- }
24959
- function applyBaselineUpdate(state, baseline, reset) {
24960
- const { baselinePath, config, details, current, ceilings, sizes, out } = state;
24961
- if (config.graphMetricsEnabled && details.circularDependencies === void 0) {
24962
- out.notice(`Skipped baseline update: graph metrics are unavailable this run. Fix the cruise before updating.`);
24963
- process.exitCode = 1;
24964
- } else if (reset === true) {
24965
- writeFileSync(baselinePath, serializeHealthBaseline(current, ceilings, sizeValuesToRecord(baseline, sizes, true)));
24966
- out.notice(`Reset ${BASELINE_FILE} to the current run.`);
24967
- } else if (isFlatOrBetter(baseline, current, ceilings, sizes)) {
24968
- writeFileSync(baselinePath, serializeHealthBaseline(current, ceilings, sizeValuesToRecord(baseline, sizes, false)));
24969
- out.notice(`Updated ${BASELINE_FILE} (no regressions).`);
24970
- } else out.notice(`Skipped baseline update: a metric or ceiling regressed. Fix the regression before updating.`);
24971
- }
24972
- function collectRegressions(result, details) {
24973
- const regressions = {};
24974
- for (const m of result.metrics) if (!m.pass) regressions[m.key] = offenderEntries(details, m.key);
24975
- return regressions;
24976
- }
24977
- const healthCheckCommand = defineCommand({
24978
- meta: {
24979
- name: "health:check",
24980
- description: "Compare codebase-health metrics against health-baseline.json. Does nothing unless .tooling.json#health.enabled is true."
24981
- },
24982
- args: {
24983
- dir: {
24984
- type: "positional",
24985
- valueHint: "dir",
24986
- description: "Project directory (default: current directory)",
24987
- required: false
24988
- },
24989
- "update-baseline": {
24990
- type: "boolean",
24991
- description: "If no metric regressed, rewrite health-baseline.json"
24992
- },
24993
- reset: {
24994
- type: "boolean",
24995
- description: "With --update-baseline, rewrite health-baseline.json unconditionally, even when a metric regressed. For adopting a baseline after a deliberate measurement change, such as health.crossPackage changing what the cruise resolves. Still refused when graph metrics are enabled and this run measured no graph."
24996
- },
24997
- "fail-on-missing-baseline": {
24998
- type: "boolean",
24999
- default: true,
25000
- description: "Fail when no baseline exists (default). --no-fail-on-missing-baseline downgrades it to a notice."
25001
- },
25002
- "fail-on-empty-src": {
25003
- type: "boolean",
25004
- default: true,
25005
- description: "Fail when the configured health.src scope measured no source files (default). --no-fail-on-empty-src downgrades it to a notice."
25006
- },
25007
- json: {
25008
- type: "boolean",
25009
- 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}."
25010
- }
25011
- },
25012
- run({ args }) {
25013
- const targetDir = path.resolve(args.dir ?? ".");
25014
- const out = createCliOutput(args.json === true);
25015
- const config = resolveHealthConfig(targetDir);
25016
- if (!config.enabled) {
25017
- out.notice("health: disabled (set .tooling.json#health.enabled to true to enable).");
25018
- const switchOff = assessSwitchOff(createRealHealthExecutor(targetDir), targetDir, config, out);
25019
- out.json({
25020
- status: "disabled",
25021
- ...switchOff
25022
- });
25023
- reportCarriedRaises(switchOff?.raises ?? [], out);
25024
- return;
25025
- }
25026
- if (!config.graphMetricsEnabled) out.notice("health: graph metrics disabled (no JS/TS source to cruise) -- crowdedDirectories only.");
25027
- const run = measureHealth(targetDir, config, out, { failOnEmptySrc: args["fail-on-empty-src"] });
25028
- const state = {
25029
- baselinePath: run.baselinePath,
25030
- config,
25031
- details: run.details,
25032
- current: run.current,
25033
- ceilings: run.ceilings,
25034
- sizes: run.sizes,
25035
- out,
25036
- referenceFields: run.referenceFields
25037
- };
25038
- if (run.existing === void 0) {
25039
- handleMissingBaseline(state, args["update-baseline"], args["fail-on-missing-baseline"]);
25040
- return;
25041
- }
25042
- const { baseline, result, attribution } = run.existing;
25043
- out.text(formatCompareDiff(result, run.details, attribution));
25044
- reportCarriedRaises(run.referenceFields.raises, out);
25045
- const regressions = collectRegressions(result, run.details);
25046
- const graphUnavailable = formatGraphUnavailable(baseline, run.details, config.graphMetricsEnabled, run.details.graphDiagnostic);
25047
- if (graphUnavailable !== void 0) out.notice(graphUnavailable);
25048
- const stale = findStaleEntries(baseline, run.details, config.exempt);
25049
- for (const warning of formatStaleEntries(stale)) out.notice(warning);
25050
- out.json({
25051
- status: "compared",
25052
- ...run.referenceFields,
25053
- pass: result.pass,
25054
- tolerance: result.tolerance,
25055
- metrics: result.metrics,
25056
- ceilings: result.ceilings,
25057
- sizeBudgets: result.sizeResults,
25058
- outlierBase: attribution.outlierBase,
25059
- newOutliers: attribution.newOutliers,
25060
- baseOutliers: attribution.baseOutliers,
25061
- unattributedOutliers: attribution.unattributedOutliers,
25062
- graphMetricsEnabled: config.graphMetricsEnabled,
25063
- graphMetricsMissing: graphUnavailable !== void 0,
25064
- staleEntries: stale,
25065
- regressions,
25066
- sources: run.details.sources
25067
- });
25068
- if (args["update-baseline"] === true) applyBaselineUpdate(state, baseline, args.reset);
25069
- if (!result.pass || graphUnavailable !== void 0) process.exitCode = 1;
25070
- }
25071
- });
25072
- // src/codebase-health/raise.ts
25073
- const SIZE_RAISE_FACTOR = 1.01;
25074
- function sizeRaiseValue(measured) {
25075
- return Math.floor(measured * SIZE_RAISE_FACTOR) + 1;
25076
- }
25077
- const JsonObjectSchema = z.record(z.string(), z.unknown());
25078
- const EXEMPT_LEAF_KEYS = [
25079
- {
25080
- prefix: "fan-in",
25081
- key: "fanInOutliers"
25082
- },
25083
- {
25084
- prefix: "fan-out",
25085
- key: "fanOutOutliers"
25086
- },
25087
- {
25088
- prefix: "crowding",
25089
- key: "crowdedDirectories"
25090
- }
25091
- ];
25092
- function refuseDeniableReason(leaf, reason) {
25093
- const fixed = fixText(`// ${reason}`, {
25094
- offenders: resolveOffenders(),
25095
- path: "health-raise.ts"
25096
- });
25097
- const refused = fixed.decisions.find((decision) => !decision.applied);
25098
- 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.`);
25099
- return fixed.text.slice(3);
25100
- }
25101
- function parseExemptLeaf(leaf) {
25102
- const separator = leaf.indexOf(":");
25103
- const prefix = separator < 0 ? "" : leaf.slice(0, separator).trim();
25104
- const path = separator < 0 ? "" : leaf.slice(separator + 1).trim();
25105
- 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.`);
25106
- const named = EXEMPT_LEAF_KEYS.find((entry) => entry.prefix === prefix);
25107
- 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>".`);
25108
- return {
25109
- key: named.key,
25110
- path
25111
- };
25112
- }
25113
- function copyCeilings(ceilings) {
25114
- const copy = {};
25115
- for (const key of RATCHETED_METRIC_KEYS) {
25116
- const byModule = ceilings?.[key];
25117
- if (byModule !== void 0) copy[key] = { ...byModule };
25118
- }
25119
- return copy;
25120
- }
25121
- function writeCeiling(ceilings, key, module, to) {
25122
- const byModule = ceilings[key] ?? {};
25123
- byModule[module] = to;
25124
- ceilings[key] = byModule;
25125
- }
25126
- function headlineFor(baseline, comparison, key, exemptCount) {
25127
- const measured = comparison.metrics.find((metric) => metric.key === key)?.current;
25128
- if (measured === void 0) return void 0;
25129
- const remaining = Math.max(0, measured - exemptCount);
25130
- return baseline[key] === void 0 ? remaining : Math.max(baseline[key] ?? 0, remaining);
25131
- }
25132
- function exemptionWrites(input) {
25133
- const writes = [];
25134
- const notes = [];
25135
- for (const request of input.exemptions) {
25136
- const parsed = parseExemptLeaf(request.leaf);
25137
- if (parsed === void 0) continue;
25138
- const recorded = input.config.exempt[parsed.key]?.[parsed.path];
25139
- if (recorded !== void 0) {
25140
- notes.push(`health.exempt.${parsed.key}.${parsed.path} already reads "${recorded}"; the reason was not overwritten.`);
25141
- continue;
25142
- }
25143
- writes.push({
25144
- key: parsed.key,
25145
- path: parsed.path,
25146
- reason: refuseDeniableReason(request.leaf, request.reason)
25147
- });
25148
- }
25149
- return {
25150
- writes,
25151
- notes
25152
- };
25153
- }
25154
- function objectAt(parent, key, where) {
25155
- const existing = parent[key];
25156
- if (existing === void 0) return {};
25157
- const parsed = JsonObjectSchema.safeParse(existing);
25158
- if (!parsed.success) throw new FatalError(`health:raise: ${where}#${key} is not an object, so an exemption cannot be written there.`);
25159
- return { ...parsed.data };
25160
- }
25161
- function applyExemptions(tooling, writes) {
25162
- if (writes.length === 0) return void 0;
25163
- const file = JsonObjectSchema.safeParse(tooling ?? {});
25164
- if (!file.success) throw new FatalError(`health:raise: .tooling.json is not a JSON object, so no exemption can be written.`);
25165
- const result = { ...file.data };
25166
- for (const write of writes) {
25167
- const health = objectAt(result, "health", ".tooling.json");
25168
- const exempt = objectAt(health, "exempt", ".tooling.json#health");
25169
- const table = objectAt(exempt, write.key, ".tooling.json#health.exempt");
25170
- table[write.path] = write.reason;
25171
- exempt[write.key] = table;
25172
- health["exempt"] = exempt;
25173
- result["health"] = health;
25174
- }
25175
- return result;
25176
- }
25177
- function planHealthRaise(input) {
25178
- const ceilings = copyCeilings(input.baseline.moduleCeilings);
25179
- const ceilingWrites = [];
25180
- const headlines = {};
25181
- const notes = [];
25182
- const exemptions = exemptionWrites(input);
25183
- notes.push(...exemptions.notes);
25184
- const isExcused = (key, module) => exemptions.writes.some((write) => write.key === key && exemptKeyMatcher(write.path)(module));
25185
- const exemptedCount = /* @__PURE__ */ new Map();
25186
- const countExcused = (key, module) => {
25187
- if (isExcused(key, module)) exemptedCount.set(key, (exemptedCount.get(key) ?? 0) + 1);
25188
- };
25189
- for (const outlier of input.attribution.newOutliers) countExcused(outlier.key, outlier.module);
25190
- for (const ceiling of input.comparison.ceilings) if (!ceiling.pass) countExcused(ceiling.key, ceiling.module);
25191
- const outlierBase = input.attribution.outlierBase;
25192
- 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.`);
25193
- for (const outlier of input.attribution.newOutliers) {
25194
- if (isExcused(outlier.key, outlier.module)) continue;
25195
- writeCeiling(ceilings, outlier.key, outlier.module, outlier.current);
25196
- const headline = headlineFor(input.baseline, input.comparison, outlier.key, exemptedCount.get(outlier.key) ?? 0);
25197
- if (headline !== void 0) headlines[outlier.key] = headline;
25198
- ceilingWrites.push({
25199
- key: outlier.key,
25200
- module: outlier.module,
25201
- value: outlier.current,
25202
- ...headline === void 0 ? {} : { headline }
25203
- });
25204
- }
25205
- for (const ceiling of input.comparison.ceilings) {
25206
- if (ceiling.pass) continue;
25207
- if (isExcused(ceiling.key, ceiling.module)) continue;
25208
- writeCeiling(ceilings, ceiling.key, ceiling.module, ceiling.current);
25209
- ceilingWrites.push({
25210
- key: ceiling.key,
25211
- module: ceiling.module,
25212
- value: ceiling.current
25381
+ sources: details.sources
25213
25382
  });
25383
+ reportCarriedRaises(state.referenceFields.raises, out);
25384
+ return;
25214
25385
  }
25215
- const sizeBudgets = { ...input.baseline.sizeBudgets };
25216
- const sizeWrites = [];
25217
- for (const size of input.comparison.sizeResults) {
25218
- if (size.pass || size.measured === void 0 || size.ceiling === void 0) continue;
25219
- if (size.measured <= size.ceiling) continue;
25220
- const value = sizeRaiseValue(size.measured);
25221
- sizeBudgets[size.id] = value;
25222
- sizeWrites.push({
25223
- id: size.id,
25224
- value
25386
+ const message = `${BASELINE_FILE$1} not found. Run with --update-baseline to create one from the current run.`;
25387
+ if (failOnMissingBaseline === false) {
25388
+ out.notice(message);
25389
+ out.json({
25390
+ status: "missing-baseline",
25391
+ ...state.referenceFields,
25392
+ metrics: current,
25393
+ sources: details.sources
25225
25394
  });
25395
+ reportCarriedRaises(state.referenceFields.raises, out);
25396
+ return;
25226
25397
  }
25227
- return {
25228
- baseline: widenedBaseline(input.baseline, headlines, ceilings, sizeBudgets),
25229
- tooling: applyExemptions(input.tooling, exemptions.writes),
25230
- ceilings: ceilingWrites,
25231
- sizes: sizeWrites,
25232
- exemptions: exemptions.writes,
25233
- notes
25234
- };
25398
+ reportCarriedRaises(state.referenceFields.raises, out);
25399
+ throw new FatalError(message);
25235
25400
  }
25236
- function widenedBaseline(baseline, headlines, ceilings, sizeBudgets) {
25237
- const widened = { ...baseline };
25401
+ function adoptUnrecorded(planned, recorded, current, ceilings) {
25402
+ const written = { ...planned };
25238
25403
  for (const key of METRIC_KEYS) {
25239
- const headline = headlines[key];
25240
- if (headline !== void 0) widened[key] = headline;
25404
+ const measured = current[key];
25405
+ if (written[key] === void 0 && measured !== void 0) written[key] = measured;
25241
25406
  }
25242
- widened.moduleCeilings = Object.keys(ceilings).length > 0 ? ceilings : void 0;
25243
- widened.sizeBudgets = Object.keys(sizeBudgets).length > 0 ? sizeBudgets : void 0;
25244
- return widened;
25407
+ if (recorded.moduleCeilings === void 0) written.moduleCeilings = ceilings;
25408
+ return written;
25245
25409
  }
25246
- function planHasWrites(plan) {
25247
- return plan.ceilings.length > 0 || plan.sizes.length > 0 || plan.exemptions.length > 0;
25410
+ function applyBaselineUpdate(state, existing, reset) {
25411
+ const { targetDir, config, details, current, ceilings, sizes, out } = state;
25412
+ const { baseline, result, attribution } = existing;
25413
+ if (config.graphMetricsEnabled && details.circularDependencies === void 0) {
25414
+ out.notice(`Skipped baseline update: graph metrics are unavailable this run. Fix the cruise before updating.`);
25415
+ process.exitCode = 1;
25416
+ } else if (reset === true) {
25417
+ writeHealthBaseline(targetDir, {
25418
+ ...current,
25419
+ moduleCeilings: ceilings,
25420
+ sizeBudgets: sizeValuesToRecord(baseline, sizes, true)
25421
+ });
25422
+ out.notice(`Reset ${BASELINE_FILE$1} to the current run.`);
25423
+ } else if (isFlatOrBetter(baseline, current, ceilings, sizes)) {
25424
+ if (attribution.newOutliers.length > 0) out.notice("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.");
25425
+ else {
25426
+ const plan = planHealthTighten({
25427
+ comparison: result,
25428
+ attribution,
25429
+ baseline,
25430
+ graphMeasured: config.graphMetricsEnabled
25431
+ });
25432
+ writeHealthBaseline(targetDir, {
25433
+ ...adoptUnrecorded(plan.baseline, baseline, current, ceilings),
25434
+ sizeBudgets: sizeValuesToRecord(plan.baseline, sizes, false)
25435
+ });
25436
+ out.notice(`Updated ${BASELINE_FILE$1} (no regressions).`);
25437
+ }
25438
+ } else out.notice(`Skipped baseline update: a metric or ceiling regressed. Fix the regression before updating.`);
25439
+ }
25440
+ function collectRegressions(result, details) {
25441
+ const regressions = {};
25442
+ for (const m of result.metrics) if (!m.pass) regressions[m.key] = offenderEntries(details, m.key);
25443
+ return regressions;
25248
25444
  }
25445
+ const healthCheckCommand = defineCommand({
25446
+ meta: {
25447
+ name: "health:check",
25448
+ description: "Compare codebase-health metrics against health-baseline.json. Does nothing unless .tooling.json#health.enabled is true."
25449
+ },
25450
+ args: {
25451
+ dir: {
25452
+ type: "positional",
25453
+ valueHint: "dir",
25454
+ description: "Project directory (default: current directory)",
25455
+ required: false
25456
+ },
25457
+ "update-baseline": {
25458
+ type: "boolean",
25459
+ description: "If no metric regressed, rewrite health-baseline.json"
25460
+ },
25461
+ reset: {
25462
+ type: "boolean",
25463
+ description: "With --update-baseline, rewrite health-baseline.json unconditionally, even when a metric regressed. For adopting a baseline after a deliberate measurement change, such as health.crossPackage changing what the cruise resolves. Still refused when graph metrics are enabled and this run measured no graph."
25464
+ },
25465
+ "fail-on-missing-baseline": {
25466
+ type: "boolean",
25467
+ default: true,
25468
+ description: "Fail when no baseline exists (default). --no-fail-on-missing-baseline downgrades it to a notice."
25469
+ },
25470
+ "fail-on-empty-src": {
25471
+ type: "boolean",
25472
+ default: true,
25473
+ description: "Fail when the configured health.src scope measured no source files (default). --no-fail-on-empty-src downgrades it to a notice."
25474
+ },
25475
+ json: {
25476
+ type: "boolean",
25477
+ 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}."
25478
+ }
25479
+ },
25480
+ run({ args }) {
25481
+ const targetDir = path.resolve(args.dir ?? ".");
25482
+ const out = createCliOutput(args.json === true);
25483
+ const config = resolveHealthConfig(targetDir);
25484
+ if (!config.enabled) {
25485
+ out.notice("health: disabled (set .tooling.json#health.enabled to true to enable).");
25486
+ const switchOff = assessSwitchOff(createRealHealthExecutor(targetDir), targetDir, config, out);
25487
+ out.json({
25488
+ status: "disabled",
25489
+ ...switchOff
25490
+ });
25491
+ reportCarriedRaises(switchOff?.raises ?? [], out);
25492
+ return;
25493
+ }
25494
+ if (!config.graphMetricsEnabled) out.notice("health: graph metrics disabled (no JS/TS source to cruise) -- crowdedDirectories only.");
25495
+ const run = measureHealth(targetDir, config, out, { failOnEmptySrc: args["fail-on-empty-src"] });
25496
+ const state = {
25497
+ targetDir,
25498
+ config,
25499
+ details: run.details,
25500
+ current: run.current,
25501
+ ceilings: run.ceilings,
25502
+ sizes: run.sizes,
25503
+ out,
25504
+ referenceFields: run.referenceFields
25505
+ };
25506
+ const existing = run.existing;
25507
+ if (existing === void 0) {
25508
+ handleMissingBaseline(state, args["update-baseline"], args["fail-on-missing-baseline"]);
25509
+ return;
25510
+ }
25511
+ const { baseline, result, attribution } = existing;
25512
+ out.text(formatCompareDiff(result, run.details, attribution));
25513
+ const slack = findSlack({
25514
+ comparison: result,
25515
+ attribution,
25516
+ baseline,
25517
+ graphMeasured: !(config.graphMetricsEnabled && run.details.circularDependencies === void 0)
25518
+ });
25519
+ for (const line of formatSlack(slack)) out.text(line);
25520
+ reportCarriedRaises(run.referenceFields.raises, out);
25521
+ const regressions = collectRegressions(result, run.details);
25522
+ const graphUnavailable = formatGraphUnavailable(baseline, run.details, config.graphMetricsEnabled, run.details.graphDiagnostic);
25523
+ if (graphUnavailable !== void 0) out.notice(graphUnavailable);
25524
+ const stale = findStaleEntries(baseline, run.details, config.exempt);
25525
+ for (const warning of formatStaleEntries(stale)) out.notice(warning);
25526
+ const verdictPasses = result.pass && attribution.newOutliers.length === 0;
25527
+ out.json({
25528
+ status: "compared",
25529
+ ...run.referenceFields,
25530
+ pass: verdictPasses,
25531
+ tolerance: result.tolerance,
25532
+ metrics: result.metrics,
25533
+ ceilings: result.ceilings,
25534
+ sizeBudgets: result.sizeResults,
25535
+ outlierBase: attribution.outlierBase,
25536
+ newOutliers: attribution.newOutliers,
25537
+ baseOutliers: attribution.baseOutliers,
25538
+ unattributedOutliers: attribution.unattributedOutliers,
25539
+ graphMetricsEnabled: config.graphMetricsEnabled,
25540
+ graphMetricsMissing: graphUnavailable !== void 0,
25541
+ slack,
25542
+ staleEntries: stale,
25543
+ regressions,
25544
+ sources: run.details.sources
25545
+ });
25546
+ if (args["update-baseline"] === true) applyBaselineUpdate(state, existing, args.reset);
25547
+ if (!verdictPasses || graphUnavailable !== void 0) process.exitCode = 1;
25548
+ }
25549
+ });
25249
25550
  // src/commands/health-raise.ts
25250
25551
  const JsonValueSchema = z.json();
25251
25552
  const TOOLING_FILE = ".tooling.json";
@@ -25259,13 +25560,6 @@ function collectExemptPairs(rawArgs) {
25259
25560
  reason: reasons[index] ?? ""
25260
25561
  }));
25261
25562
  }
25262
- function formatterFor(targetDir) {
25263
- const detected = computeDefaults(targetDir);
25264
- return createContentFormatter({
25265
- targetDir,
25266
- formatter: loadToolingConfig(targetDir)?.formatter ?? detected.formatter
25267
- });
25268
- }
25269
25563
  function readToolingFile(targetDir) {
25270
25564
  const full = path.join(targetDir, TOOLING_FILE);
25271
25565
  if (!existsSync(full)) return void 0;
@@ -25281,7 +25575,7 @@ function readToolingFile(targetDir) {
25281
25575
  if (!parsed.success) throw new FatalError(`health:raise: ${TOOLING_FILE} is not JSON: ${parsed.error.message}`);
25282
25576
  return parsed.data;
25283
25577
  }
25284
- function describePlan(plan) {
25578
+ function describePlan$1(plan) {
25285
25579
  const lines = [];
25286
25580
  for (const ceiling of plan.ceilings) {
25287
25581
  const headline = ceiling.headline === void 0 ? "" : `, ${ceiling.key} set to ${String(ceiling.headline)}`;
@@ -25345,7 +25639,7 @@ const healthRaiseCommand = defineCommand({
25345
25639
  });
25346
25640
  const dryRun = args["dry-run"] === true;
25347
25641
  const wrote = dryRun ? [] : writePlan(targetDir, plan);
25348
- for (const line of describePlan(plan)) out.text(line);
25642
+ for (const line of describePlan$1(plan)) out.text(line);
25349
25643
  out.json({
25350
25644
  status: planHasWrites(plan) ? "raised" : "nothing-to-raise",
25351
25645
  dryRun,
@@ -25359,18 +25653,97 @@ const healthRaiseCommand = defineCommand({
25359
25653
  }
25360
25654
  });
25361
25655
  function writePlan(targetDir, plan) {
25362
- const format = formatterFor(targetDir);
25363
25656
  const wrote = [];
25364
25657
  if (plan.ceilings.length > 0 || plan.sizes.length > 0) {
25365
- writeFileSync(path.join(targetDir, "health-baseline.json"), format("health-baseline.json", serializeHealthBaseline(plan.baseline, plan.baseline.moduleCeilings, plan.baseline.sizeBudgets)));
25658
+ writeHealthBaseline(targetDir, plan.baseline);
25366
25659
  wrote.push("health-baseline.json");
25367
25660
  }
25368
25661
  if (plan.tooling !== void 0) {
25662
+ const format = healthFileFormatter(targetDir);
25369
25663
  writeFileSync(path.join(targetDir, TOOLING_FILE), format(TOOLING_FILE, JSON.stringify(plan.tooling, null, 2)));
25370
25664
  wrote.push(TOOLING_FILE);
25371
25665
  }
25372
25666
  return wrote;
25373
25667
  }
25668
+ // src/commands/health-tighten.ts
25669
+ const BASELINE_FILE = "health-baseline.json";
25670
+ function describePlan(plan) {
25671
+ const lines = [];
25672
+ for (const lowering of plan.lowered) lines.push(`health-baseline: ${lowering.leaf} ${String(lowering.from)} -> ${String(lowering.to)}`);
25673
+ for (const removal of plan.removed) lines.push(`health-baseline: ${removal.key}: ${removal.module} ceiling ${String(removal.value)} removed`);
25674
+ for (const cap of plan.caps) lines.push(`health-baseline: ${cap.key}: ${cap.module} capped at ${String(cap.value)}`);
25675
+ return lines;
25676
+ }
25677
+ const healthTightenCommand = defineCommand({
25678
+ meta: {
25679
+ name: "health:tighten",
25680
+ 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."
25681
+ },
25682
+ args: {
25683
+ dir: {
25684
+ type: "positional",
25685
+ valueHint: "dir",
25686
+ description: "Project directory (default: current directory)",
25687
+ required: false
25688
+ },
25689
+ "dry-run": {
25690
+ type: "boolean",
25691
+ description: "Print what would be written and write nothing"
25692
+ },
25693
+ json: {
25694
+ type: "boolean",
25695
+ 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."
25696
+ }
25697
+ },
25698
+ run({ args }) {
25699
+ const targetDir = path.resolve(args.dir ?? ".");
25700
+ const out = createCliOutput(args.json === true);
25701
+ const dryRun = args["dry-run"] === true;
25702
+ const config = resolveHealthConfig(targetDir);
25703
+ if (!config.enabled) {
25704
+ out.notice("health: disabled (set .tooling.json#health.enabled to true to enable).");
25705
+ out.json({
25706
+ status: "disabled",
25707
+ dryRun
25708
+ });
25709
+ return;
25710
+ }
25711
+ const run = measureHealth(targetDir, config, out);
25712
+ 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.`);
25713
+ if (config.graphMetricsEnabled && run.details.circularDependencies === void 0) {
25714
+ out.notice(`Skipped: graph metrics are unavailable this run. Fix the cruise before tightening ${BASELINE_FILE}.`);
25715
+ out.json({
25716
+ status: "graph-unavailable",
25717
+ dryRun,
25718
+ wrote: []
25719
+ });
25720
+ process.exitCode = 1;
25721
+ return;
25722
+ }
25723
+ const plan = planHealthTighten({
25724
+ comparison: run.existing.result,
25725
+ attribution: run.existing.attribution,
25726
+ baseline: run.existing.baseline,
25727
+ graphMeasured: config.graphMetricsEnabled
25728
+ });
25729
+ const hasWrites = plan.lowered.length > 0 || plan.removed.length > 0 || plan.caps.length > 0;
25730
+ const wrote = [];
25731
+ if (hasWrites && !dryRun) {
25732
+ writeHealthBaseline(targetDir, plan.baseline);
25733
+ wrote.push(BASELINE_FILE);
25734
+ }
25735
+ for (const line of describePlan(plan)) out.text(line);
25736
+ out.json({
25737
+ status: hasWrites ? "tightened" : "nothing-to-tighten",
25738
+ dryRun,
25739
+ wrote,
25740
+ lowered: plan.lowered,
25741
+ removed: plan.removed,
25742
+ caps: plan.caps,
25743
+ reference: run.referenceFields.reference
25744
+ });
25745
+ }
25746
+ });
25374
25747
  // src/codebase-health/module-report.ts
25375
25748
  function normalizeModulePath(raw) {
25376
25749
  let normalized = raw.replace(/\\/g, "/");
@@ -25456,7 +25829,7 @@ function formatModuleReports(reports) {
25456
25829
  }
25457
25830
  return lines.join("\n");
25458
25831
  }
25459
- // src/commands/health-coverage-note.ts
25832
+ // src/commands/health-summary.ts
25460
25833
  function readCoverageNote(targetDir) {
25461
25834
  const file = path.join(targetDir, "coverage-baseline.json");
25462
25835
  if (!existsSync(file)) return void 0;
@@ -25467,7 +25840,6 @@ function readCoverageNote(targetDir) {
25467
25840
  return;
25468
25841
  }
25469
25842
  }
25470
- // src/commands/health-summary.ts
25471
25843
  function readModuleCeilings(targetDir) {
25472
25844
  const file = path.join(targetDir, "health-baseline.json");
25473
25845
  if (!existsSync(file)) return void 0;
@@ -27081,6 +27453,128 @@ const docsCheckCommand = defineCommand({
27081
27453
  process.exitCode = exitCode;
27082
27454
  }
27083
27455
  });
27456
+ // src/docs-check/open-docs.ts
27457
+ const HASH_REF = /(?<![\w./#-])#([0-9]+)(?![0-9A-Za-z_-])/g;
27458
+ const WORD_REF = /\b(?:pull request|pr)\s+#?([0-9]+)\b/gi;
27459
+ const FORGE_REF = /\/(?:issues|pulls)\/([0-9]+)(?![0-9])/g;
27460
+ function forgeRefPattern(repoUrl) {
27461
+ const base = repoUrl?.replace(/\/+$/, "");
27462
+ if (base === void 0 || base === "") return FORGE_REF;
27463
+ return new RegExp(`${escapeRegex(base)}/(?:issues|pulls)/([0-9]+)(?![0-9])`, "g");
27464
+ }
27465
+ function titleOf(body) {
27466
+ return /^# +(.*\S)[ \t]*$/m.exec(stripCode(body))?.[1] ?? null;
27467
+ }
27468
+ function refsOf$1(body, repoUrl) {
27469
+ const scannable = stripCode(body);
27470
+ const found = /* @__PURE__ */ new Set();
27471
+ for (const re of [
27472
+ HASH_REF,
27473
+ WORD_REF,
27474
+ forgeRefPattern(repoUrl)
27475
+ ]) {
27476
+ re.lastIndex = 0;
27477
+ for (const match of scannable.matchAll(re)) {
27478
+ const digits = (match[1] ?? match[0]).replaceAll("#", "");
27479
+ const value = Number(digits);
27480
+ if (Number.isSafeInteger(value)) found.add(value);
27481
+ }
27482
+ }
27483
+ return [...found].toSorted((a, b) => a - b);
27484
+ }
27485
+ function linksOf(body, fileDir) {
27486
+ const found = /* @__PURE__ */ new Set();
27487
+ for (const link of relativeLinks(body, fileDir)) if (resolvesInsideDocs(link.target)) found.add(link.target);
27488
+ return [...found].toSorted();
27489
+ }
27490
+ function classOf(status) {
27491
+ if (status !== void 0 && PARTIAL_STATUS.test(status)) return "partial";
27492
+ if (status !== void 0 && OPEN_STATUS.test(status)) return "not-started";
27493
+ return "other";
27494
+ }
27495
+ function kindOf(docPath) {
27496
+ return classifyConventionalDoc(docPath)?.kind ?? "configured";
27497
+ }
27498
+ function readOpenDoc(exec, docPath, repoUrl) {
27499
+ const body = exec.readFile(docPath);
27500
+ if (body === void 0) return void 0;
27501
+ const status = statusOf(body);
27502
+ return {
27503
+ path: docPath,
27504
+ kind: kindOf(docPath),
27505
+ title: titleOf(body),
27506
+ status: status ?? null,
27507
+ statusClass: classOf(status),
27508
+ lastChangedISO: exec.lastContentChangeISO(docPath),
27509
+ refs: refsOf$1(body, repoUrl),
27510
+ links: linksOf(body, path.posix.dirname(docPath))
27511
+ };
27512
+ }
27513
+ function byPath(a, b) {
27514
+ if (a.path < b.path) return -1;
27515
+ if (a.path > b.path) return 1;
27516
+ return 0;
27517
+ }
27518
+ function listOpenDocs(exec, config, options = {}) {
27519
+ if (!config.enabled) return [];
27520
+ const docs = [];
27521
+ for (const pair of discoverPairs(exec, config)) for (const docPath of listDocs(exec, pair.active, pair.activePattern)) {
27522
+ const doc = readOpenDoc(exec, docPath, options.repoUrl);
27523
+ if (doc !== void 0) docs.push(doc);
27524
+ }
27525
+ return docs.toSorted(byPath);
27526
+ }
27527
+ // src/commands/docs-list.ts
27528
+ function dayOf(iso) {
27529
+ if (iso === void 0) return "unknown";
27530
+ const day = iso.slice(0, 10);
27531
+ return /^\d{4}-\d{2}-\d{2}$/.test(day) ? day : "unknown";
27532
+ }
27533
+ function refsOf(refs) {
27534
+ if (refs.length === 0) return "-";
27535
+ return refs.map((n) => `#${String(n)}`).join(",");
27536
+ }
27537
+ function runDocsList(exec, config) {
27538
+ const docs = listOpenDocs(exec, config);
27539
+ const lines = docs.map((doc) => `${doc.path} ${doc.statusClass} ${dayOf(doc.lastChangedISO)} ${refsOf(doc.refs)}`);
27540
+ return {
27541
+ payload: {
27542
+ ok: true,
27543
+ docs
27544
+ },
27545
+ text: lines.join("\n")
27546
+ };
27547
+ }
27548
+ const docsListCommand = defineCommand({
27549
+ meta: {
27550
+ name: "docs:list",
27551
+ description: "List the active specs and plans -- exactly the docs docs:check counts as active -- with what can be read mechanically from each: kind, title, raw Status value and its class (not-started, partial, other), the date its content last changed, the issue and pull request numbers it names, and the docs it links to. Reports and never writes; a Status line is data here, never a filter. Docs on a branch other than the default branch are not catalogued."
27552
+ },
27553
+ args: {
27554
+ dir: {
27555
+ type: "positional",
27556
+ valueHint: "dir",
27557
+ description: "Project directory (default: current directory)",
27558
+ required: false
27559
+ },
27560
+ json: {
27561
+ type: "boolean",
27562
+ description: "Emit one JSON document: ok, docs ([{path, kind (spec | plan | legacy-plan | configured), title, status, statusClass (not-started | partial | other), lastChangedISO, refs, links}])."
27563
+ },
27564
+ verbose: {
27565
+ type: "boolean",
27566
+ description: "Emit detailed debug logging"
27567
+ }
27568
+ },
27569
+ run({ args }) {
27570
+ const targetDir = path.resolve(args.dir ?? ".");
27571
+ const out = createCliOutput(args.json === true);
27572
+ const { payload, text } = runDocsList(createRealDocsExecutor(targetDir), resolveDocsConfig(targetDir));
27573
+ debug({ verbose: args.verbose === true || isEnvVerbose() }, `docs:list: ${String(payload.docs.length)} open doc(s)`);
27574
+ out.json(payload);
27575
+ if (text !== "") out.text(text);
27576
+ }
27577
+ });
27084
27578
  // src/docs-delink/engine.ts
27085
27579
  function textRestatesTarget(text, target) {
27086
27580
  const plain = text.replaceAll("`", "").trim();
@@ -29583,7 +30077,7 @@ async function runCli(config) {
29583
30077
  // src/cli-main.ts
29584
30078
  setLogLevel(resolveLogLevel({}));
29585
30079
  setForgejoLogger(log$1);
29586
- const displayVersion = "0.101.0";
30080
+ const displayVersion = "0.103.0";
29587
30081
  const bstSubCommands = {
29588
30082
  "repo:sync": syncCommand,
29589
30083
  "checks:run": runChecksCommand,
@@ -29614,6 +30108,7 @@ const bstSubCommands = {
29614
30108
  "coverage:status": coverageStatusCommand,
29615
30109
  "health:check": healthCheckCommand,
29616
30110
  "health:raise": healthRaiseCommand,
30111
+ "health:tighten": healthTightenCommand,
29617
30112
  "health:summary": healthSummaryCommand,
29618
30113
  "health:record": healthRecordCommand,
29619
30114
  "health:status": healthStatusCommand,
@@ -29621,6 +30116,7 @@ const bstSubCommands = {
29621
30116
  "ascii:check": asciiCheckAliasCommand,
29622
30117
  "branch:prune": branchPruneCommand,
29623
30118
  "docs:check": docsCheckCommand,
30119
+ "docs:list": docsListCommand,
29624
30120
  "docs:delink": docsDelinkCommand,
29625
30121
  "docs:relocate": docsRelocateCommand,
29626
30122
  "docs:retire": docsRetireCommand,