@bensandee/tooling 0.99.0 → 0.100.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
@@ -19,7 +19,7 @@ import { parse as parse$2 } from "smol-toml";
19
19
  import picomatch from "picomatch";
20
20
  import net from "node:net";
21
21
  import { fileURLToPath } from "node:url";
22
- //#region ../cli-kit/src/json.ts
22
+ // ../cli-kit/src/json.ts
23
23
  function resolveJsonMode(rawArgs) {
24
24
  if (!rawArgs.some(requestsJson)) return false;
25
25
  if (rawArgs.includes("--help") || rawArgs.includes("-h")) return false;
@@ -113,8 +113,7 @@ function classifyThrown(error, verbose) {
113
113
  detail
114
114
  };
115
115
  }
116
- //#endregion
117
- //#region ../cli-kit/src/env-file.ts
116
+ // ../cli-kit/src/env-file.ts
118
117
  const ENV_FILE_VAR = "BST_ENV_FILE";
119
118
  function loadEnvFileFromEnv() {
120
119
  const raw = process.env[ENV_FILE_VAR]?.trim();
@@ -171,14 +170,12 @@ function loadEnvFileForBin(rawArgs, bin, io = processIo) {
171
170
  return io.exit(1);
172
171
  }
173
172
  }
174
- //#endregion
175
- //#region src/env-file-preload.ts
173
+ // src/env-file-preload.ts
176
174
  const envFileLoad = loadEnvFileForBin(process.argv.slice(2), {
177
175
  name: "bst",
178
- version: "0.99.0"
176
+ version: "0.100.0"
179
177
  });
180
- //#endregion
181
- //#region ../cli-kit/src/logger.ts
178
+ // ../cli-kit/src/logger.ts
182
179
  const RANK = {
183
180
  error: 0,
184
181
  warn: 1,
@@ -282,11 +279,9 @@ function createLogger(options = {}) {
282
279
  });
283
280
  }
284
281
  const rootLogger = createLogger();
285
- //#endregion
286
- //#region src/utils/logger.ts
282
+ // src/utils/logger.ts
287
283
  setDefaultUserSink(clack.log);
288
- //#endregion
289
- //#region src/utils/log.ts
284
+ // src/utils/log.ts
290
285
  const isCI = Boolean(process.env["CI"]);
291
286
  const out = (msg) => console.log(msg);
292
287
  const log$1 = rootLogger;
@@ -297,8 +292,7 @@ function note(body, title) {
297
292
  out(body);
298
293
  } else clack.note(body, title);
299
294
  }
300
- //#endregion
301
- //#region ../cli-kit/src/output.ts
295
+ // ../cli-kit/src/output.ts
302
296
  const stdout = (msg) => console.log(msg);
303
297
  function initialState() {
304
298
  return {
@@ -361,8 +355,7 @@ function flushJsonOutput() {
361
355
  function jsonDocumentWritten() {
362
356
  return state.wrote;
363
357
  }
364
- //#endregion
365
- //#region ../cli-kit/src/git.ts
358
+ // ../cli-kit/src/git.ts
366
359
  const BRANCH_REF_PREFIX = "refs/heads/";
367
360
  const ORIGIN_READ_TIMEOUT_MS = 5e3;
368
361
  function defaultGitRunner(args, cwd, options) {
@@ -425,8 +418,7 @@ function readPackageRepositoryUrl(cwd) {
425
418
  if (!repo) return null;
426
419
  return typeof repo === "string" ? repo : repo.url;
427
420
  }
428
- //#endregion
429
- //#region ../forgejo/src/connection.ts
421
+ // ../forgejo/src/connection.ts
430
422
  function parseGitUrl(urlStr) {
431
423
  try {
432
424
  const url = new URL(urlStr);
@@ -568,8 +560,7 @@ function normalizeGitUrl(raw) {
568
560
  return null;
569
561
  }
570
562
  }
571
- //#endregion
572
- //#region src/types.ts
563
+ // src/types.ts
573
564
  const LEGACY_TOOLS = [
574
565
  "eslint",
575
566
  "prettier",
@@ -577,8 +568,7 @@ const LEGACY_TOOLS = [
577
568
  "webpack",
578
569
  "rollup"
579
570
  ];
580
- //#endregion
581
- //#region src/utils/json.ts
571
+ // src/utils/json.ts
582
572
  const StringRecord = z.record(z.string(), z.string());
583
573
  const DevEngineRuntimeSchema = z.looseObject({
584
574
  name: z.string(),
@@ -658,8 +648,7 @@ function describePackageJsonFailure(raw) {
658
648
  const issue = result.error.issues[0];
659
649
  return `${issue && issue.path.length > 0 ? issue.path.join(".") : "a managed field"} has the wrong type${issue ? ` (${issue.message})` : ""}`;
660
650
  }
661
- //#endregion
662
- //#region src/codebase-health/types.ts
651
+ // src/codebase-health/types.ts
663
652
  const METRIC_KEYS = [
664
653
  "crowdedDirectories",
665
654
  "circularDependencies",
@@ -715,8 +704,7 @@ function parseHealthHistoryLine(line) {
715
704
  const result = HealthRecordSchema.safeParse(json);
716
705
  return result.success ? result.data : void 0;
717
706
  }
718
- //#endregion
719
- //#region src/utils/tooling-schemas.ts
707
+ // src/utils/tooling-schemas.ts
720
708
  function parseToolingConfigSlice(raw, schema, context) {
721
709
  if (raw === void 0 || raw.trim() === "") return void 0;
722
710
  const displayPath = context.path ?? ".tooling.json";
@@ -866,8 +854,7 @@ function agentEnabledIn(raw) {
866
854
  return false;
867
855
  }
868
856
  }
869
- //#endregion
870
- //#region src/utils/stack.ts
857
+ // src/utils/stack.ts
871
858
  const IGNORED_DIRS = /* @__PURE__ */ new Set([
872
859
  "node_modules",
873
860
  "vendor",
@@ -978,8 +965,7 @@ function detectBuilder(targetDir, pkg) {
978
965
  }
979
966
  return builderFromConfigFiles(targetDir);
980
967
  }
981
- //#endregion
982
- //#region src/utils/detect.ts
968
+ // src/utils/detect.ts
983
969
  const LEGACY_PATTERNS = {
984
970
  eslint: [/^\.eslintrc/, /^eslint\.config\./],
985
971
  prettier: [/^\.prettierrc/, /^prettier\.config\./],
@@ -1162,8 +1148,7 @@ function getMonorepoPackages(targetDir) {
1162
1148
  } catch (_error) {}
1163
1149
  return results;
1164
1150
  }
1165
- //#endregion
1166
- //#region src/prompts/init-prompts.ts
1151
+ // src/prompts/init-prompts.ts
1167
1152
  function isCancelled$1(value) {
1168
1153
  return clack.isCancel(value);
1169
1154
  }
@@ -1381,8 +1366,7 @@ function buildDefaultConfig(targetDir, flags) {
1381
1366
  targetDir
1382
1367
  };
1383
1368
  }
1384
- //#endregion
1385
- //#region src/utils/win-command.ts
1369
+ // src/utils/win-command.ts
1386
1370
  const START_FAILURE_CODES = /* @__PURE__ */ new Set([
1387
1371
  "ENOENT",
1388
1372
  "EINVAL",
@@ -1396,8 +1380,7 @@ function shouldRetryViaShim(error, platform = process.platform) {
1396
1380
  }
1397
1381
  const spawnViaShim = spawn$1.sync;
1398
1382
  const spawnAsyncViaShim = spawn$1;
1399
- //#endregion
1400
- //#region src/utils/format.ts
1383
+ // src/utils/format.ts
1401
1384
  function runFormatter(targetDir, formatter, relativePath, content) {
1402
1385
  const bin = path.join(targetDir, "node_modules", ".bin", formatter);
1403
1386
  if (!existsSync(bin)) return void 0;
@@ -1435,8 +1418,7 @@ function isGeneratedTemplate(ctx, relativePath, template) {
1435
1418
  if (existing === template) return true;
1436
1419
  return existing === ctx.format(relativePath, template);
1437
1420
  }
1438
- //#endregion
1439
- //#region src/utils/fs.ts
1421
+ // src/utils/fs.ts
1440
1422
  function isContained(targetDir, rel) {
1441
1423
  const resolved = path.resolve(targetDir, rel);
1442
1424
  return resolved.startsWith(targetDir + path.sep) || resolved === targetDir;
@@ -1605,11 +1587,9 @@ function createDryRunContext(config, dockerDiscovery) {
1605
1587
  sawCrlf: () => sawCrlf
1606
1588
  };
1607
1589
  }
1608
- //#endregion
1609
- //#region src/repo-full-name.ts
1590
+ // src/repo-full-name.ts
1610
1591
  const REPO_FULL_NAME = /^(?!\.\.?\/)[\w.-]+\/(?!\.\.?$)[\w.-]+$/u;
1611
- //#endregion
1612
- //#region src/docs-check/config.ts
1592
+ // src/docs-check/config.ts
1613
1593
  const DEFAULT_STALE_DAYS = 30;
1614
1594
  const DocsConfigSchema = z.strictObject({
1615
1595
  enforced: z.union([z.boolean(), z.array(z.string())]).optional().meta({ description: "Which discovered pairs fail the build. true = all; an array names active dirs (e.g. [\"docs/plans\"]); default false = every violation is advisory." }),
@@ -1661,8 +1641,7 @@ function resolveDocsConfig(targetDir) {
1661
1641
  }
1662
1642
  } });
1663
1643
  }
1664
- //#endregion
1665
- //#region src/utils/tooling-config.ts
1644
+ // src/utils/tooling-config.ts
1666
1645
  const CONFIG_FILE = ".tooling.json";
1667
1646
  const ReleaseAssetSchema = z.strictObject({
1668
1647
  command: z.array(z.string()).nonempty().optional().meta({ description: "argv passed directly to the child process (no shell interpolation), e.g. [\"pnpm\",\"build\"]" }),
@@ -1745,7 +1724,7 @@ const LintSweepConfigSchema = z.strictObject({
1745
1724
  cooldownDays: z.number().int().nonnegative().optional().meta({ description: "Days after a lint-sweep pull request merged or closed before the sweep may open another (default 7): a merged sweep whose declined warnings survive must not re-file them the next morning." }),
1746
1725
  compatIssues: z.boolean().optional().meta({ description: "Whether the sweep splits expired @compat warnings out of its plan and files one issue per expired id (default: on). false keeps them in the bulk plan with the other warnings." })
1747
1726
  });
1748
- const AgentEgressConfigSchema = z.strictObject({ browseHosts: z.array(z.string().min(1)).optional().meta({ description: "Host patterns this repo's agent containers ask to fetch from, on top of the hosts every run needs: an exact host (`fastdl.mongodb.org`) or a wildcard over its leftmost label (`*.example.com`). No ports. This list is a request the deployment grants, not an opening: its grant mode decides whether a default branch's requests take effect on their own, an admin can refuse a host for this repo, and a host the product or the deployment known-denies is never opened whatever the declaration or the verdict says. What is granted joins the browse lane, which serves GET and HEAD only." }) });
1727
+ const AgentEgressConfigSchema = z.strictObject({ browseHosts: z.array(z.string().min(1)).optional().meta({ description: "Host patterns or path patterns this repo's agent containers ask to fetch from, on top of the hosts every run needs: an exact host (`fastdl.mongodb.org`), a wildcard over its leftmost label (`*.example.com`), or a path under one exact host (`raw.githubusercontent.com/owner/repo/`). No ports. This list is a request the deployment grants, not an opening: its grant mode decides whether a default branch's requests take effect on their own, an admin can refuse a host for this repo, and a host the product or the deployment known-denies is never opened whatever the declaration or the verdict says. A host the deployment has narrowed to its path patterns never takes a host-wide request automatically: that one waits for an admin, while a path pattern under it is granted as any other request. What is granted joins the browse lane, which serves GET and HEAD only." }) });
1749
1728
  const AgentConfigSchema = z.strictObject({
1750
1729
  enabled: z.boolean().optional().meta({ description: "The repo's explicit consent to the agent (default false). Only `true`, read from the repo's **default branch**, lets the agent work the repo: claim units, run sweeps, recover orphans, merge, act on a chat proposal or start a new spec. A missing key, `false`, a missing `.tooling.json` or a read that fails all mean not enabled, and the answer is re-read within about a minute. Every other `agent.*` key below has no effect without this one; `repo:sync` warns when the block sets one of them and this key is not `true`. Where this is `true`, `repo:sync` also installs `@bensandee/agent-cli`. `pnpm exec bst setup:agent` sets it to true and runs the sync. Provisioning the agent's labels is not consent, and is never gated by this key." }),
1751
1730
  autonomy: z.boolean().optional().meta({ description: "Retired and ignored -- it armed neither the advance rung nor the sweeps it once did. Advance is now the unit's own `agent-flags/advance` or `agent-flags/autopilot` label, and the trunk-red detector and world-changed retrigger sweep read `agent.trunkRed`. The key is still accepted so an existing config keeps syncing; the agent warns once per launch for a repo that still sets it." }),
@@ -1997,8 +1976,7 @@ function mergeWithSavedConfig(detected, saved) {
1997
1976
  detectPackageTypes: saved.detectPackageTypes ?? detected.detectPackageTypes
1998
1977
  };
1999
1978
  }
2000
- //#endregion
2001
- //#region src/release/connection.ts
1979
+ // src/release/connection.ts
2002
1980
  function resolveForgeToken(purpose) {
2003
1981
  const token = forgeTokenFromEnv(process.env);
2004
1982
  if (!token) throw new FatalError(`${purpose} needs a forge token -- set RELEASE_TOKEN (preferred) or FORGEJO_TOKEN.`);
@@ -2035,8 +2013,7 @@ function parseRepositoryUrl(cwd) {
2035
2013
  const urlStr = readPackageRepositoryUrl(cwd);
2036
2014
  return urlStr === null ? null : parseGitUrl(urlStr);
2037
2015
  }
2038
- //#endregion
2039
- //#region ../forgejo/src/errors.ts
2016
+ // ../forgejo/src/errors.ts
2040
2017
  var ForgeAccessError = class extends FatalError {};
2041
2018
  function authHeaders(conn) {
2042
2019
  return { Authorization: `token ${conn.token}` };
@@ -2203,8 +2180,7 @@ async function setUserActionSecret(executor, options) {
2203
2180
  resource: secretName
2204
2181
  });
2205
2182
  }
2206
- //#endregion
2207
- //#region src/utils/docker-secret-names.ts
2183
+ // src/utils/docker-secret-names.ts
2208
2184
  const HOST_BASE_OVERRIDES = {
2209
2185
  "code.orangebikelabs.com": "OBL_REGISTRY",
2210
2186
  "docker.io": "DOCKERHUB",
@@ -2250,8 +2226,7 @@ function loadRegistryHostOverride(cwd) {
2250
2226
  return;
2251
2227
  }
2252
2228
  }
2253
- //#endregion
2254
- //#region src/release/docker-bake.ts
2229
+ // src/release/docker-bake.ts
2255
2230
  function escapeBakeTemplate(value) {
2256
2231
  return value.replace(/\$\{/gu, () => "$${").replace(/%\{/gu, () => "%%{");
2257
2232
  }
@@ -2307,8 +2282,7 @@ function buildBakeDefinition(images) {
2307
2282
  target
2308
2283
  };
2309
2284
  }
2310
- //#endregion
2311
- //#region src/utils/debug.ts
2285
+ // src/utils/debug.ts
2312
2286
  const verboseLogger = createLogger({ level: "trace" });
2313
2287
  function isEnvVerbose() {
2314
2288
  return process.env["TOOLING_DEBUG"] === "true";
@@ -2323,13 +2297,11 @@ function debugExec(config, label, result) {
2323
2297
  if (result.stderr.trim()) lines.push(` stderr: ${redact$1(result.stderr.trim())}`);
2324
2298
  verboseLogger.debug(lines.join("\n"));
2325
2299
  }
2326
- //#endregion
2327
- //#region src/compose/yaml.ts
2300
+ // src/compose/yaml.ts
2328
2301
  function parseComposeYaml(content) {
2329
2302
  return parse$1(content, { logLevel: "silent" });
2330
2303
  }
2331
- //#endregion
2332
- //#region src/compose/services.ts
2304
+ // src/compose/services.ts
2333
2305
  const ComposeLongSyntaxPortSchema = z.looseObject({
2334
2306
  published: z.union([z.string(), z.number()]).optional(),
2335
2307
  target: z.union([z.string(), z.number()]).optional()
@@ -2569,8 +2541,7 @@ function extractComposeBuildDockerfiles(services) {
2569
2541
  for (const service of services) if (service.buildDockerfile) paths.add(service.buildDockerfile);
2570
2542
  return [...paths];
2571
2543
  }
2572
- //#endregion
2573
- //#region src/compose/file-set.ts
2544
+ // src/compose/file-set.ts
2574
2545
  const COMPOSE_FILE_CANDIDATES = [
2575
2546
  "docker-compose.yaml",
2576
2547
  "docker-compose.yml",
@@ -2672,8 +2643,7 @@ function resolveComposeFileSet(readFile, projectRoot, composeFiles) {
2672
2643
  sources
2673
2644
  };
2674
2645
  }
2675
- //#endregion
2676
- //#region ../forgejo/src/fetcher.ts
2646
+ // ../forgejo/src/fetcher.ts
2677
2647
  const LONG_FETCH_TIMEOUT_MS = 6e5;
2678
2648
  function morePagesFollow(res, pageLength, received, pageSize) {
2679
2649
  if (pageLength === 0) return false;
@@ -2682,8 +2652,7 @@ function morePagesFollow(res, pageLength, received, pageSize) {
2682
2652
  if (!Number.isSafeInteger(total) || total < 0) return pageLength >= pageSize;
2683
2653
  return received < total;
2684
2654
  }
2685
- //#endregion
2686
- //#region ../forgejo/src/fetch-retry.ts
2655
+ // ../forgejo/src/fetch-retry.ts
2687
2656
  const DEFAULT_RETRY_POLICY = {
2688
2657
  attempts: 5,
2689
2658
  baseDelayMs: 250,
@@ -2737,8 +2706,7 @@ function fetchWithRetry(fetchImpl, policy = DEFAULT_RETRY_POLICY, defaultTimeout
2737
2706
  }, callerSignal);
2738
2707
  };
2739
2708
  }
2740
- //#endregion
2741
- //#region src/utils/exec.ts
2709
+ // src/utils/exec.ts
2742
2710
  const EXEC_MAX_BUFFER = 67108864;
2743
2711
  function execCapture$2(file, args, options) {
2744
2712
  try {
@@ -2790,8 +2758,7 @@ function isExecSyncError(err) {
2790
2758
  function isKilledExecError(err) {
2791
2759
  return err instanceof Error && "stdout" in err && typeof err.stdout === "string" && "stderr" in err && typeof err.stderr === "string" && "signal" in err && typeof err.signal === "string";
2792
2760
  }
2793
- //#endregion
2794
- //#region src/release/executor.ts
2761
+ // src/release/executor.ts
2795
2762
  function captureSpawnOptions(options) {
2796
2763
  return {
2797
2764
  cwd: options?.cwd,
@@ -3248,16 +3215,11 @@ function resolveTagCommit(executor, cwd, tag) {
3248
3215
  const sha = result.stdout.trim();
3249
3216
  return result.exitCode === 0 && sha ? sha : void 0;
3250
3217
  }
3251
- function parseNewTags(output) {
3252
- const tags = [];
3253
- for (const line of output.split("\n")) {
3254
- const match = /New tag:\s+(\S+)/.exec(line);
3255
- if (match?.[1]) tags.push(match[1]);
3256
- }
3257
- return tags;
3218
+ function exactTag(name, version) {
3219
+ return `${name}@${version}`;
3258
3220
  }
3259
3221
  function computeExpectedTags(packages) {
3260
- return packages.map((p) => `${p.name}@${p.version}`);
3222
+ return packages.map((p) => exactTag(p.name, p.version));
3261
3223
  }
3262
3224
  function parseRemoteTags(output) {
3263
3225
  const tags = [];
@@ -3267,15 +3229,11 @@ function parseRemoteTags(output) {
3267
3229
  }
3268
3230
  return tags;
3269
3231
  }
3270
- function reconcileTags(expectedTags, remoteTags, stdoutTags) {
3232
+ function reconcileTags(expectedTags, remoteTags) {
3271
3233
  const remoteSet = new Set(remoteTags);
3272
- const result = /* @__PURE__ */ new Set();
3273
- for (const tag of expectedTags) if (!remoteSet.has(tag)) result.add(tag);
3274
- for (const tag of stdoutTags) result.add(tag);
3275
- return [...result];
3234
+ return expectedTags.filter((tag) => !remoteSet.has(tag));
3276
3235
  }
3277
- //#endregion
3278
- //#region src/release/publish/floating-tags.ts
3236
+ // src/release/publish/floating-tags.ts
3279
3237
  const VERSION_PATTERN = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
3280
3238
  function parseRemoteTagTargets(lsRemoteStdout) {
3281
3239
  const targets = /* @__PURE__ */ new Map();
@@ -3573,11 +3531,121 @@ function pushFloatingMove(call, move, targetSha, run) {
3573
3531
  function localTarget(call, entry) {
3574
3532
  return resolveTagCommit(call.executor, call.options.cwd, entry.family.exact(entry.version));
3575
3533
  }
3576
- //#endregion
3577
- //#region src/release/docker-check-only-phase.ts
3534
+ // src/release/docker-check-only-phase.ts
3578
3535
  const DOCKER_CHECK_ONLY_PHASE = "enforce";
3579
- //#endregion
3580
- //#region src/release/docker.ts
3536
+ // src/release/head-version-bump.ts
3537
+ const VersionFieldSchema = z.looseObject({ version: z.string().optional() });
3538
+ function hasHeadParent(executor, cwd) {
3539
+ const parent = executor.exec("git", [
3540
+ "rev-parse",
3541
+ "--verify",
3542
+ "--quiet",
3543
+ "HEAD~1"
3544
+ ], { cwd });
3545
+ return parent.exitCode === 0 && parent.stdout.trim() !== "";
3546
+ }
3547
+ function readAtRev(executor, cwd, rev, repoRelPath) {
3548
+ const shown = executor.exec("git", ["show", `${rev}:${repoRelPath}`], { cwd });
3549
+ if (shown.exitCode !== 0) return void 0;
3550
+ return shown.stdout;
3551
+ }
3552
+ function versionOf(raw) {
3553
+ if (raw === void 0) return void 0;
3554
+ let parsed;
3555
+ try {
3556
+ parsed = JSON.parse(raw);
3557
+ } catch (_error) {
3558
+ return;
3559
+ }
3560
+ const result = VersionFieldSchema.safeParse(parsed);
3561
+ return result.success ? result.data.version : void 0;
3562
+ }
3563
+ function headChangedVersion(executor, cwd, repoRelPath) {
3564
+ const before = versionOf(readAtRev(executor, cwd, "HEAD~1", repoRelPath));
3565
+ const after = versionOf(readAtRev(executor, cwd, "HEAD", repoRelPath));
3566
+ return before !== void 0 && after !== void 0 && before !== after;
3567
+ }
3568
+ // src/release/docker-publish-bound.ts
3569
+ function skipLine(pkg, versionSourcePath) {
3570
+ return `${pkg.imageName} v${pkg.version ?? "?"}: HEAD did not change the version in ${versionSourcePath}, so it is not pushed. Publish it by hand with --image ${pkg.imageName}.`;
3571
+ }
3572
+ function selectImagesToPush(executor, config, publishable) {
3573
+ const named = config.images ?? [];
3574
+ if (named.length > 0) return selectNamedImages(named, publishable);
3575
+ if (config.releaseStrategy !== "changesets") return {
3576
+ push: [...publishable],
3577
+ skipped: []
3578
+ };
3579
+ return selectBoundedImages(executor, config.cwd, publishable);
3580
+ }
3581
+ function selectNamedImages(images, publishable) {
3582
+ const publishableNames = publishable.map((pkg) => pkg.imageName);
3583
+ const known = new Set(publishableNames);
3584
+ const unknown = images.filter((name) => !known.has(name));
3585
+ if (unknown.length > 0) throw new FatalError(`--image names ${unknown.join(", ")}, which no publishable image carries. Publishable images: ${publishableNames.join(", ")}.`);
3586
+ const wanted = new Set(images);
3587
+ const push = [];
3588
+ const skipped = [];
3589
+ for (const pkg of publishable) {
3590
+ if (wanted.has(pkg.imageName)) {
3591
+ push.push(pkg);
3592
+ continue;
3593
+ }
3594
+ log$1.info(`${pkg.imageName}: not named by --image, so it is not pushed.`);
3595
+ skipped.push(pkg);
3596
+ }
3597
+ return {
3598
+ push,
3599
+ skipped
3600
+ };
3601
+ }
3602
+ function bumpedByPath(executor, cwd, path, memo) {
3603
+ const known = memo.get(path);
3604
+ if (known !== void 0) return known;
3605
+ const bumped = headChangedVersion(executor, cwd, path);
3606
+ memo.set(path, bumped);
3607
+ return bumped;
3608
+ }
3609
+ function selectBoundedImages(executor, cwd, publishable) {
3610
+ const overrides = /* @__PURE__ */ new Set();
3611
+ const bounded = [];
3612
+ for (const pkg of publishable) {
3613
+ if (pkg.versionSource.kind === "override") {
3614
+ overrides.add(pkg);
3615
+ continue;
3616
+ }
3617
+ bounded.push(pkg);
3618
+ }
3619
+ const push = new Set(overrides);
3620
+ if (bounded.length === 0) return {
3621
+ push: publishable.filter((pkg) => push.has(pkg)),
3622
+ skipped: []
3623
+ };
3624
+ if (!hasHeadParent(executor, cwd)) {
3625
+ log$1.info("HEAD has no parent commit to compare against, so no image that takes its version from a package.json is pushed. Publish one by hand with --image <name>.");
3626
+ return {
3627
+ push: publishable.filter((pkg) => push.has(pkg)),
3628
+ skipped: publishable.filter((pkg) => !push.has(pkg))
3629
+ };
3630
+ }
3631
+ const memo = /* @__PURE__ */ new Map();
3632
+ for (const pkg of bounded) {
3633
+ const source = pkg.versionSource;
3634
+ if (source.kind === "manifest") {
3635
+ if (bumpedByPath(executor, cwd, source.path, memo)) {
3636
+ push.add(pkg);
3637
+ continue;
3638
+ }
3639
+ log$1.info(skipLine(pkg, source.path));
3640
+ continue;
3641
+ }
3642
+ }
3643
+ return {
3644
+ push: publishable.filter((pkg) => push.has(pkg)),
3645
+ skipped: publishable.filter((pkg) => !push.has(pkg))
3646
+ };
3647
+ }
3648
+ // src/release/docker.ts
3581
3649
  function defaultPublish(checkOnlyIn, phase) {
3582
3650
  return !(checkOnlyIn !== void 0 && phase === "enforce");
3583
3651
  }
@@ -3639,16 +3707,40 @@ function findEnclosingPackage(executor, cwd, dockerfileRelPath) {
3639
3707
  while (true) {
3640
3708
  const segments = dir.split("/");
3641
3709
  if (segments[0] !== "packages" || segments.length < 2) return void 0;
3710
+ const relPath = `${segments.join("/")}/package.json`;
3642
3711
  const info = readPackageInfo(executor, path.join(cwd, ...segments, "package.json"));
3643
- if (info !== void 0) return info;
3712
+ if (info !== void 0) return {
3713
+ info,
3714
+ path: relPath
3715
+ };
3644
3716
  dir = segments.slice(0, -1).join("/");
3645
3717
  }
3646
3718
  }
3647
3719
  function resolveDockerVersion(executor, cwd, docker) {
3648
- if (docker.version !== void 0) return docker.version;
3720
+ if (docker.version !== void 0) return {
3721
+ version: docker.version,
3722
+ source: { kind: "override" }
3723
+ };
3649
3724
  const enclosing = findEnclosingPackage(executor, cwd, docker.dockerfile);
3650
- if (enclosing !== void 0) return enclosing.version;
3651
- return readPackageInfo(executor, path.join(cwd, "package.json"))?.version;
3725
+ if (enclosing !== void 0) return {
3726
+ version: enclosing.info.version,
3727
+ source: {
3728
+ kind: "manifest",
3729
+ path: enclosing.path
3730
+ }
3731
+ };
3732
+ const root = readPackageInfo(executor, path.join(cwd, "package.json"));
3733
+ if (root !== void 0) return {
3734
+ version: root.version,
3735
+ source: {
3736
+ kind: "manifest",
3737
+ path: "package.json"
3738
+ }
3739
+ };
3740
+ return {
3741
+ version: void 0,
3742
+ source: { kind: "none" }
3743
+ };
3652
3744
  }
3653
3745
  function stripScope(name) {
3654
3746
  const slashIndex = name.indexOf("/");
@@ -3678,10 +3770,13 @@ function createDockerPackage(executor, cwd, repoName, input) {
3678
3770
  const { dir, docker, origin } = input;
3679
3771
  const isRoot = dir === ".";
3680
3772
  const name = readPackageInfo(executor, isRoot ? path.join(cwd, "package.json") : path.join(cwd, "packages", dir, "package.json"))?.name;
3773
+ const imageName = docker.imageName ?? (isRoot ? stripScope(name ?? repoName) : `${repoName}-${stripScope(name ?? dir)}`);
3774
+ const { version, source } = resolveDockerVersion(executor, cwd, docker);
3681
3775
  return {
3682
3776
  dir,
3683
- imageName: docker.imageName ?? (isRoot ? stripScope(name ?? repoName) : `${repoName}-${stripScope(name ?? dir)}`),
3684
- version: resolveDockerVersion(executor, cwd, docker),
3777
+ imageName,
3778
+ version,
3779
+ versionSource: source,
3685
3780
  publish: docker.publish ?? defaultPublish(origin.checkOnlyIn, origin.phase),
3686
3781
  docker,
3687
3782
  checkOnlyIn: origin.checkOnlyIn
@@ -4252,21 +4347,27 @@ function runDockerPublish(executor, config) {
4252
4347
  packages: [],
4253
4348
  tags: [],
4254
4349
  skipped: [],
4255
- kept: []
4350
+ kept: [],
4351
+ skippedImages: []
4256
4352
  };
4257
4353
  const publishablePackages = packages.filter((pkg) => pkg.publish);
4258
4354
  if (publishablePackages.length === 0) return {
4259
4355
  packages,
4260
4356
  tags: [],
4261
4357
  skipped: [],
4262
- kept: []
4358
+ kept: [],
4359
+ skippedImages: []
4263
4360
  };
4264
4361
  for (const pkg of publishablePackages) {
4265
4362
  if (!pkg.version) throw new FatalError(`Docker image "${pkg.imageName}" (dockerfile ${pkg.docker.dockerfile}) has no version to publish. Checked: an explicit "version" override in .tooling.json#docker, the nearest enclosing packages/<name>/package.json walking up from the dockerfile, and the root package.json. Set an explicit version override for this image.`);
4266
4363
  const nameHost = imageRegistryHost(pkg.imageName);
4267
4364
  if (nameHost !== void 0 && nameHost.toLowerCase() !== config.registryHost.toLowerCase()) throw new FatalError(`Docker image "${pkg.imageName}" names registry "${nameHost}", but this run logs in to "${config.registryHost}". Fix one of the three: point the publish target at "${nameHost}" (registryHost/registryNamespace in .tooling.json, or DOCKER_REGISTRY_HOST/DOCKER_REGISTRY_NAMESPACE); override the name via .tooling.json#docker keyed by the discovered image name (e.g. {"docker": {"${pkg.imageName}": {"imageName": "<unqualified-name>"}}}); or exclude it with {"docker": {"${pkg.imageName}": {"publish": false}}}.`);
4268
4365
  }
4269
- if (!config.dryRun) {
4366
+ const selection = selectImagesToPush(executor, config, publishablePackages);
4367
+ const imagesToPush = selection.push;
4368
+ const skippedImages = selection.skipped.map((pkg) => pkg.imageName);
4369
+ if (imagesToPush.length === 0) log$1.info("No image to push, so this run neither logs in nor logs out.");
4370
+ else if (!config.dryRun) {
4270
4371
  log$1.info(`Logging in to ${config.registryHost}...`);
4271
4372
  const loginResult = executor.exec("docker", [
4272
4373
  "login",
@@ -4284,23 +4385,30 @@ function runDockerPublish(executor, config) {
4284
4385
  kept: []
4285
4386
  };
4286
4387
  try {
4287
- for (const pkg of publishablePackages) tagAndPushPackage(executor, config, pkg, outcome);
4388
+ for (const pkg of imagesToPush) tagAndPushPackage(executor, config, pkg, outcome);
4288
4389
  } finally {
4289
- if (!config.dryRun) {
4390
+ if (imagesToPush.length > 0 && !config.dryRun) {
4290
4391
  log$1.info(`Logging out from ${config.registryHost}...`);
4291
4392
  executor.exec("docker", ["logout", config.registryHost]);
4292
4393
  }
4293
4394
  }
4294
- log$1.info(`Published ${String(outcome.tags.length)} image tag(s)`);
4295
- if (outcome.skipped.length > 0) log$1.info(`Left ${String(outcome.skipped.length)} floating tag(s) alone: ${outcome.skipped.join(", ")}`);
4296
- if (outcome.kept.length > 0) log$1.info(`Kept ${String(outcome.kept.length)} record(s) already in the registry: ${outcome.kept.join(", ")}`);
4395
+ logPublishSummary(outcome, skippedImages, config);
4297
4396
  return {
4298
4397
  packages,
4299
- ...outcome
4398
+ ...outcome,
4399
+ skippedImages
4300
4400
  };
4301
4401
  }
4302
- //#endregion
4303
- //#region src/release/docker-discovery-memo.ts
4402
+ function logPublishSummary(outcome, skippedImages, config) {
4403
+ log$1.info(`Published ${String(outcome.tags.length)} image tag(s)`);
4404
+ if (outcome.skipped.length > 0) log$1.info(`Left ${String(outcome.skipped.length)} floating tag(s) alone: ${outcome.skipped.join(", ")}`);
4405
+ if (outcome.kept.length > 0) log$1.info(`Kept ${String(outcome.kept.length)} record(s) already in the registry: ${outcome.kept.join(", ")}`);
4406
+ if (skippedImages.length > 0) {
4407
+ const reason = config.images !== void 0 && config.images.length > 0 ? "not named by --image" : "whose version HEAD did not change";
4408
+ log$1.info(`Skipped ${String(skippedImages.length)} image(s) ${reason}: ${skippedImages.join(", ")}`);
4409
+ }
4410
+ }
4411
+ // src/release/docker-discovery-memo.ts
4304
4412
  function keysMatch(stored, cwd, repoName, phase) {
4305
4413
  return stored.cwd === cwd && stored.repoName === repoName && stored.phase === phase;
4306
4414
  }
@@ -4365,8 +4473,7 @@ function createDockerDiscoveryMemo() {
4365
4473
  }
4366
4474
  return { detect };
4367
4475
  }
4368
- //#endregion
4369
- //#region src/generators/docker-reader.ts
4476
+ // src/generators/docker-reader.ts
4370
4477
  const perContextMemos = /* @__PURE__ */ new WeakMap();
4371
4478
  function memoFor(ctx) {
4372
4479
  if (ctx.dockerDiscovery !== void 0) return ctx.dockerDiscovery;
@@ -4395,8 +4502,7 @@ function contextAsDockerReader(ctx) {
4395
4502
  }
4396
4503
  };
4397
4504
  }
4398
- //#endregion
4399
- //#region src/release/publish/publish-config-lint.ts
4505
+ // src/release/publish/publish-config-lint.ts
4400
4506
  const FIX = `add "publishConfig": { "registry": "<your registry URL>" } to its package.json`;
4401
4507
  function isUsableRegistry(value) {
4402
4508
  if (typeof value !== "string" || value.trim() === "") return false;
@@ -4447,8 +4553,7 @@ function declaredPublishRegistries(targetDir, structure, rootPackageJson) {
4447
4553
  }
4448
4554
  return registries;
4449
4555
  }
4450
- //#endregion
4451
- //#region src/utils/generated-header.ts
4556
+ // src/utils/generated-header.ts
4452
4557
  const MANAGED_HEADER_MARKER = "Managed by @bensandee/tooling --";
4453
4558
  function managedFileHeader(comment, lines) {
4454
4559
  return lines.map((line) => line === "" ? comment : `${comment} ${line}`).join("\n") + "\n";
@@ -4466,8 +4571,7 @@ const LEFTHOOK_MANAGED_HEADER = managedFileHeader("#", [
4466
4571
  "To stop managing this file, make `# @bensandee/tooling:ignore` the first line."
4467
4572
  ]);
4468
4573
  const GUIDE_MANAGED_HEADER = "<!-- Managed by @bensandee/tooling -- `bst repo:sync` rewrites this guide and archives local edits. To keep your own version, make the first line an HTML comment reading @bensandee/tooling:ignore. -->\n";
4469
- //#endregion
4470
- //#region src/utils/yaml-merge.ts
4574
+ // src/utils/yaml-merge.ts
4471
4575
  const IGNORE_PATTERN = "@bensandee/tooling:ignore";
4472
4576
  const CUSTOM_START = "# @tooling:custom";
4473
4577
  const CUSTOM_END = "# @tooling:endcustom";
@@ -4700,15 +4804,13 @@ function buildWorkflowYaml(options) {
4700
4804
  }).replace(/^(?=\S)/gm, (match, offset) => offset === 0 ? match : `\n${match}`);
4701
4805
  return ensureSchemaComment(WORKFLOW_MANAGED_HEADER + "\n" + readable, options.ci);
4702
4806
  }
4703
- //#endregion
4704
- //#region src/generators/mise-pin.ts
4705
- const MISE_VERSION = "2026.10.15";
4706
- const MISE_LINUX_X64_SHA256 = "e3b186d4c70627f27037be615becaf4acfb30e41fb6a1819486717dc94e4e2a9";
4807
+ // src/generators/mise-pin.ts
4808
+ const MISE_VERSION = "2026.10.19";
4809
+ const MISE_LINUX_X64_SHA256 = "3162760f40b6b5f706c60641e4ef5ee7322bc6c54f72fc26a7111b337aa18d9d";
4707
4810
  const SETUP_MISE_ACTION_URL = "https://code.orangebikelabs.com/bensandee/common/actions/setup-mise";
4708
4811
  const SETUP_MISE_ACTION_TAG = "setup-mise@latest";
4709
4812
  const SETUP_MISE_ACTION_SHA = "ebe622ef0d24c7efec4a5f6093ddb18500900e24";
4710
- //#endregion
4711
- //#region src/generators/ci-utils.ts
4813
+ // src/generators/ci-utils.ts
4712
4814
  function actionsExpr(expr) {
4713
4815
  return `\${{ ${expr} }}`;
4714
4816
  }
@@ -4852,8 +4954,7 @@ function retireManagedWorkflow(ctx, workflowPath, reason) {
4852
4954
  description
4853
4955
  };
4854
4956
  }
4855
- //#endregion
4856
- //#region src/generators/publish-ci.ts
4957
+ // src/generators/publish-ci.ts
4857
4958
  const RegistryHostSchema = z.object({ registryHost: z.string().optional() });
4858
4959
  function resolveGenTimeHost(ctx) {
4859
4960
  const toolingRaw = ctx.read(".tooling.json");
@@ -4984,8 +5085,7 @@ async function generateDeployCi(ctx) {
4984
5085
  description: "No publish workflow to retire"
4985
5086
  };
4986
5087
  }
4987
- //#endregion
4988
- //#region src/codebase-health/config.ts
5088
+ // src/codebase-health/config.ts
4989
5089
  const DEFAULT_HEALTH_HISTORY_BRANCH = "bst/health-metrics";
4990
5090
  const TS_EXTENSIONS = [".ts", ".tsx"];
4991
5091
  const JS_EXTENSIONS = [
@@ -5062,8 +5162,7 @@ function healthOverridesAt(targetDir) {
5062
5162
  }
5063
5163
  return parseToolingConfigSlice(raw, ToolingShallowSchema$2, { block: "health" })?.health;
5064
5164
  }
5065
- //#endregion
5066
- //#region src/utils/script-forwarding.ts
5165
+ // src/utils/script-forwarding.ts
5067
5166
  function commandSegments(script) {
5068
5167
  return script.split(/&&|\|\|?|;/).map((segment) => segment.trim());
5069
5168
  }
@@ -5130,8 +5229,7 @@ function diagnoseCheckScriptForwardingAt(targetDir) {
5130
5229
  }
5131
5230
  return diagnoseCheckScriptForwarding(scripts);
5132
5231
  }
5133
- //#endregion
5134
- //#region src/generators/agent-cli-dep.ts
5232
+ // src/generators/agent-cli-dep.ts
5135
5233
  const AGENT_CLI_PACKAGE = "@bensandee/agent-cli";
5136
5234
  function agentEnabled(ctx) {
5137
5235
  return agentEnabledIn(ctx.read(".tooling.json"));
@@ -5167,8 +5265,7 @@ function wantsCommitAndTagVersion(ctx) {
5167
5265
  if (ctx.config.releaseStrategy !== "simple") return false;
5168
5266
  return !readUnmanagedDevDepNames(ctx).has(COMMIT_AND_TAG_VERSION_PACKAGE);
5169
5267
  }
5170
- //#endregion
5171
- //#region src/generators/package-json.ts
5268
+ // src/generators/package-json.ts
5172
5269
  const NODE_ENGINES_FLOOR = "24.13.0";
5173
5270
  const ENGINES_NODE = `>=${NODE_ENGINES_FLOOR}`;
5174
5271
  function versionPart(s) {
@@ -5274,59 +5371,59 @@ function perPackageDevDeps(config) {
5274
5371
  "@changesets/cli": "3.0.3",
5275
5372
  "@release-it/bumper": "8.0.1",
5276
5373
  "@types/node": "24.19.2",
5277
- "@vitest/coverage-v8": "5.0.3",
5374
+ "@vitest/coverage-v8": "5.0.5",
5278
5375
  "commit-and-tag-version": "13.3.0",
5279
- "knip": "6.41.0",
5376
+ "knip": "6.42.1",
5280
5377
  "lefthook": "2.2.2",
5281
- "modern-web-guidance": "0.0.194",
5282
- "oxfmt": "0.73.0",
5283
- "oxlint": "1.87.0",
5284
- "oxlint-tsgolint": "7.0.2004",
5378
+ "modern-web-guidance": "0.0.195",
5379
+ "oxfmt": "0.74.0",
5380
+ "oxlint": "1.89.0",
5381
+ "oxlint-tsgolint": "7.0.2005",
5285
5382
  "prettier": "3.9.10",
5286
5383
  "release-it": "21.1.1",
5287
5384
  "tsdown": "0.23.1",
5288
5385
  "typescript": "6.0.3",
5289
- "vitest": "5.0.3",
5290
- "pnpm": "11.28.5"
5386
+ "vitest": "5.0.5",
5387
+ "pnpm": "11.28.8"
5291
5388
  }["typescript"];
5292
5389
  deps["@types/node"] = {
5293
5390
  "@changesets/cli": "3.0.3",
5294
5391
  "@release-it/bumper": "8.0.1",
5295
5392
  "@types/node": "24.19.2",
5296
- "@vitest/coverage-v8": "5.0.3",
5393
+ "@vitest/coverage-v8": "5.0.5",
5297
5394
  "commit-and-tag-version": "13.3.0",
5298
- "knip": "6.41.0",
5395
+ "knip": "6.42.1",
5299
5396
  "lefthook": "2.2.2",
5300
- "modern-web-guidance": "0.0.194",
5301
- "oxfmt": "0.73.0",
5302
- "oxlint": "1.87.0",
5303
- "oxlint-tsgolint": "7.0.2004",
5397
+ "modern-web-guidance": "0.0.195",
5398
+ "oxfmt": "0.74.0",
5399
+ "oxlint": "1.89.0",
5400
+ "oxlint-tsgolint": "7.0.2005",
5304
5401
  "prettier": "3.9.10",
5305
5402
  "release-it": "21.1.1",
5306
5403
  "tsdown": "0.23.1",
5307
5404
  "typescript": "6.0.3",
5308
- "vitest": "5.0.3",
5309
- "pnpm": "11.28.5"
5405
+ "vitest": "5.0.5",
5406
+ "pnpm": "11.28.8"
5310
5407
  }["@types/node"];
5311
5408
  }
5312
5409
  if (config.builder === "tsdown") deps["tsdown"] = {
5313
5410
  "@changesets/cli": "3.0.3",
5314
5411
  "@release-it/bumper": "8.0.1",
5315
5412
  "@types/node": "24.19.2",
5316
- "@vitest/coverage-v8": "5.0.3",
5413
+ "@vitest/coverage-v8": "5.0.5",
5317
5414
  "commit-and-tag-version": "13.3.0",
5318
- "knip": "6.41.0",
5415
+ "knip": "6.42.1",
5319
5416
  "lefthook": "2.2.2",
5320
- "modern-web-guidance": "0.0.194",
5321
- "oxfmt": "0.73.0",
5322
- "oxlint": "1.87.0",
5323
- "oxlint-tsgolint": "7.0.2004",
5417
+ "modern-web-guidance": "0.0.195",
5418
+ "oxfmt": "0.74.0",
5419
+ "oxlint": "1.89.0",
5420
+ "oxlint-tsgolint": "7.0.2005",
5324
5421
  "prettier": "3.9.10",
5325
5422
  "release-it": "21.1.1",
5326
5423
  "tsdown": "0.23.1",
5327
5424
  "typescript": "6.0.3",
5328
- "vitest": "5.0.3",
5329
- "pnpm": "11.28.5"
5425
+ "vitest": "5.0.5",
5426
+ "pnpm": "11.28.8"
5330
5427
  }["tsdown"];
5331
5428
  return deps;
5332
5429
  }
@@ -5336,39 +5433,39 @@ function vitestDevDeps() {
5336
5433
  "@changesets/cli": "3.0.3",
5337
5434
  "@release-it/bumper": "8.0.1",
5338
5435
  "@types/node": "24.19.2",
5339
- "@vitest/coverage-v8": "5.0.3",
5436
+ "@vitest/coverage-v8": "5.0.5",
5340
5437
  "commit-and-tag-version": "13.3.0",
5341
- "knip": "6.41.0",
5438
+ "knip": "6.42.1",
5342
5439
  "lefthook": "2.2.2",
5343
- "modern-web-guidance": "0.0.194",
5344
- "oxfmt": "0.73.0",
5345
- "oxlint": "1.87.0",
5346
- "oxlint-tsgolint": "7.0.2004",
5440
+ "modern-web-guidance": "0.0.195",
5441
+ "oxfmt": "0.74.0",
5442
+ "oxlint": "1.89.0",
5443
+ "oxlint-tsgolint": "7.0.2005",
5347
5444
  "prettier": "3.9.10",
5348
5445
  "release-it": "21.1.1",
5349
5446
  "tsdown": "0.23.1",
5350
5447
  "typescript": "6.0.3",
5351
- "vitest": "5.0.3",
5352
- "pnpm": "11.28.5"
5448
+ "vitest": "5.0.5",
5449
+ "pnpm": "11.28.8"
5353
5450
  }["vitest"],
5354
5451
  "@vitest/coverage-v8": {
5355
5452
  "@changesets/cli": "3.0.3",
5356
5453
  "@release-it/bumper": "8.0.1",
5357
5454
  "@types/node": "24.19.2",
5358
- "@vitest/coverage-v8": "5.0.3",
5455
+ "@vitest/coverage-v8": "5.0.5",
5359
5456
  "commit-and-tag-version": "13.3.0",
5360
- "knip": "6.41.0",
5457
+ "knip": "6.42.1",
5361
5458
  "lefthook": "2.2.2",
5362
- "modern-web-guidance": "0.0.194",
5363
- "oxfmt": "0.73.0",
5364
- "oxlint": "1.87.0",
5365
- "oxlint-tsgolint": "7.0.2004",
5459
+ "modern-web-guidance": "0.0.195",
5460
+ "oxfmt": "0.74.0",
5461
+ "oxlint": "1.89.0",
5462
+ "oxlint-tsgolint": "7.0.2005",
5366
5463
  "prettier": "3.9.10",
5367
5464
  "release-it": "21.1.1",
5368
5465
  "tsdown": "0.23.1",
5369
5466
  "typescript": "6.0.3",
5370
- "vitest": "5.0.3",
5371
- "pnpm": "11.28.5"
5467
+ "vitest": "5.0.5",
5468
+ "pnpm": "11.28.8"
5372
5469
  }["@vitest/coverage-v8"]
5373
5470
  };
5374
5471
  }
@@ -5377,59 +5474,59 @@ function rootDevDeps(config) {
5377
5474
  "@changesets/cli": "3.0.3",
5378
5475
  "@release-it/bumper": "8.0.1",
5379
5476
  "@types/node": "24.19.2",
5380
- "@vitest/coverage-v8": "5.0.3",
5477
+ "@vitest/coverage-v8": "5.0.5",
5381
5478
  "commit-and-tag-version": "13.3.0",
5382
- "knip": "6.41.0",
5479
+ "knip": "6.42.1",
5383
5480
  "lefthook": "2.2.2",
5384
- "modern-web-guidance": "0.0.194",
5385
- "oxfmt": "0.73.0",
5386
- "oxlint": "1.87.0",
5387
- "oxlint-tsgolint": "7.0.2004",
5481
+ "modern-web-guidance": "0.0.195",
5482
+ "oxfmt": "0.74.0",
5483
+ "oxlint": "1.89.0",
5484
+ "oxlint-tsgolint": "7.0.2005",
5388
5485
  "prettier": "3.9.10",
5389
5486
  "release-it": "21.1.1",
5390
5487
  "tsdown": "0.23.1",
5391
5488
  "typescript": "6.0.3",
5392
- "vitest": "5.0.3",
5393
- "pnpm": "11.28.5"
5489
+ "vitest": "5.0.5",
5490
+ "pnpm": "11.28.8"
5394
5491
  }["lefthook"] };
5395
5492
  if (config.stack !== "none") {
5396
5493
  deps["knip"] = {
5397
5494
  "@changesets/cli": "3.0.3",
5398
5495
  "@release-it/bumper": "8.0.1",
5399
5496
  "@types/node": "24.19.2",
5400
- "@vitest/coverage-v8": "5.0.3",
5497
+ "@vitest/coverage-v8": "5.0.5",
5401
5498
  "commit-and-tag-version": "13.3.0",
5402
- "knip": "6.41.0",
5499
+ "knip": "6.42.1",
5403
5500
  "lefthook": "2.2.2",
5404
- "modern-web-guidance": "0.0.194",
5405
- "oxfmt": "0.73.0",
5406
- "oxlint": "1.87.0",
5407
- "oxlint-tsgolint": "7.0.2004",
5501
+ "modern-web-guidance": "0.0.195",
5502
+ "oxfmt": "0.74.0",
5503
+ "oxlint": "1.89.0",
5504
+ "oxlint-tsgolint": "7.0.2005",
5408
5505
  "prettier": "3.9.10",
5409
5506
  "release-it": "21.1.1",
5410
5507
  "tsdown": "0.23.1",
5411
5508
  "typescript": "6.0.3",
5412
- "vitest": "5.0.3",
5413
- "pnpm": "11.28.5"
5509
+ "vitest": "5.0.5",
5510
+ "pnpm": "11.28.8"
5414
5511
  }["knip"];
5415
5512
  deps["oxlint"] = {
5416
5513
  "@changesets/cli": "3.0.3",
5417
5514
  "@release-it/bumper": "8.0.1",
5418
5515
  "@types/node": "24.19.2",
5419
- "@vitest/coverage-v8": "5.0.3",
5516
+ "@vitest/coverage-v8": "5.0.5",
5420
5517
  "commit-and-tag-version": "13.3.0",
5421
- "knip": "6.41.0",
5518
+ "knip": "6.42.1",
5422
5519
  "lefthook": "2.2.2",
5423
- "modern-web-guidance": "0.0.194",
5424
- "oxfmt": "0.73.0",
5425
- "oxlint": "1.87.0",
5426
- "oxlint-tsgolint": "7.0.2004",
5520
+ "modern-web-guidance": "0.0.195",
5521
+ "oxfmt": "0.74.0",
5522
+ "oxlint": "1.89.0",
5523
+ "oxlint-tsgolint": "7.0.2005",
5427
5524
  "prettier": "3.9.10",
5428
5525
  "release-it": "21.1.1",
5429
5526
  "tsdown": "0.23.1",
5430
5527
  "typescript": "6.0.3",
5431
- "vitest": "5.0.3",
5432
- "pnpm": "11.28.5"
5528
+ "vitest": "5.0.5",
5529
+ "pnpm": "11.28.8"
5433
5530
  }["oxlint"];
5434
5531
  Object.assign(deps, vitestDevDeps());
5435
5532
  }
@@ -5437,20 +5534,20 @@ function rootDevDeps(config) {
5437
5534
  "@changesets/cli": "3.0.3",
5438
5535
  "@release-it/bumper": "8.0.1",
5439
5536
  "@types/node": "24.19.2",
5440
- "@vitest/coverage-v8": "5.0.3",
5537
+ "@vitest/coverage-v8": "5.0.5",
5441
5538
  "commit-and-tag-version": "13.3.0",
5442
- "knip": "6.41.0",
5539
+ "knip": "6.42.1",
5443
5540
  "lefthook": "2.2.2",
5444
- "modern-web-guidance": "0.0.194",
5445
- "oxfmt": "0.73.0",
5446
- "oxlint": "1.87.0",
5447
- "oxlint-tsgolint": "7.0.2004",
5541
+ "modern-web-guidance": "0.0.195",
5542
+ "oxfmt": "0.74.0",
5543
+ "oxlint": "1.89.0",
5544
+ "oxlint-tsgolint": "7.0.2005",
5448
5545
  "prettier": "3.9.10",
5449
5546
  "release-it": "21.1.1",
5450
5547
  "tsdown": "0.23.1",
5451
5548
  "typescript": "6.0.3",
5452
- "vitest": "5.0.3",
5453
- "pnpm": "11.28.5"
5549
+ "vitest": "5.0.5",
5550
+ "pnpm": "11.28.8"
5454
5551
  }["oxlint-tsgolint"];
5455
5552
  return deps;
5456
5553
  }
@@ -5461,39 +5558,39 @@ function addReleaseDeps(deps, ctx) {
5461
5558
  "@changesets/cli": "3.0.3",
5462
5559
  "@release-it/bumper": "8.0.1",
5463
5560
  "@types/node": "24.19.2",
5464
- "@vitest/coverage-v8": "5.0.3",
5561
+ "@vitest/coverage-v8": "5.0.5",
5465
5562
  "commit-and-tag-version": "13.3.0",
5466
- "knip": "6.41.0",
5563
+ "knip": "6.42.1",
5467
5564
  "lefthook": "2.2.2",
5468
- "modern-web-guidance": "0.0.194",
5469
- "oxfmt": "0.73.0",
5470
- "oxlint": "1.87.0",
5471
- "oxlint-tsgolint": "7.0.2004",
5565
+ "modern-web-guidance": "0.0.195",
5566
+ "oxfmt": "0.74.0",
5567
+ "oxlint": "1.89.0",
5568
+ "oxlint-tsgolint": "7.0.2005",
5472
5569
  "prettier": "3.9.10",
5473
5570
  "release-it": "21.1.1",
5474
5571
  "tsdown": "0.23.1",
5475
5572
  "typescript": "6.0.3",
5476
- "vitest": "5.0.3",
5477
- "pnpm": "11.28.5"
5573
+ "vitest": "5.0.5",
5574
+ "pnpm": "11.28.8"
5478
5575
  }["release-it"];
5479
5576
  if (ctx.config.structure === "monorepo") deps["@release-it/bumper"] = {
5480
5577
  "@changesets/cli": "3.0.3",
5481
5578
  "@release-it/bumper": "8.0.1",
5482
5579
  "@types/node": "24.19.2",
5483
- "@vitest/coverage-v8": "5.0.3",
5580
+ "@vitest/coverage-v8": "5.0.5",
5484
5581
  "commit-and-tag-version": "13.3.0",
5485
- "knip": "6.41.0",
5582
+ "knip": "6.42.1",
5486
5583
  "lefthook": "2.2.2",
5487
- "modern-web-guidance": "0.0.194",
5488
- "oxfmt": "0.73.0",
5489
- "oxlint": "1.87.0",
5490
- "oxlint-tsgolint": "7.0.2004",
5584
+ "modern-web-guidance": "0.0.195",
5585
+ "oxfmt": "0.74.0",
5586
+ "oxlint": "1.89.0",
5587
+ "oxlint-tsgolint": "7.0.2005",
5491
5588
  "prettier": "3.9.10",
5492
5589
  "release-it": "21.1.1",
5493
5590
  "tsdown": "0.23.1",
5494
5591
  "typescript": "6.0.3",
5495
- "vitest": "5.0.3",
5496
- "pnpm": "11.28.5"
5592
+ "vitest": "5.0.5",
5593
+ "pnpm": "11.28.8"
5497
5594
  }["@release-it/bumper"];
5498
5595
  break;
5499
5596
  case "simple":
@@ -5501,40 +5598,40 @@ function addReleaseDeps(deps, ctx) {
5501
5598
  "@changesets/cli": "3.0.3",
5502
5599
  "@release-it/bumper": "8.0.1",
5503
5600
  "@types/node": "24.19.2",
5504
- "@vitest/coverage-v8": "5.0.3",
5601
+ "@vitest/coverage-v8": "5.0.5",
5505
5602
  "commit-and-tag-version": "13.3.0",
5506
- "knip": "6.41.0",
5603
+ "knip": "6.42.1",
5507
5604
  "lefthook": "2.2.2",
5508
- "modern-web-guidance": "0.0.194",
5509
- "oxfmt": "0.73.0",
5510
- "oxlint": "1.87.0",
5511
- "oxlint-tsgolint": "7.0.2004",
5605
+ "modern-web-guidance": "0.0.195",
5606
+ "oxfmt": "0.74.0",
5607
+ "oxlint": "1.89.0",
5608
+ "oxlint-tsgolint": "7.0.2005",
5512
5609
  "prettier": "3.9.10",
5513
5610
  "release-it": "21.1.1",
5514
5611
  "tsdown": "0.23.1",
5515
5612
  "typescript": "6.0.3",
5516
- "vitest": "5.0.3",
5517
- "pnpm": "11.28.5"
5613
+ "vitest": "5.0.5",
5614
+ "pnpm": "11.28.8"
5518
5615
  }["commit-and-tag-version"];
5519
5616
  break;
5520
5617
  case "changesets": deps["@changesets/cli"] = {
5521
5618
  "@changesets/cli": "3.0.3",
5522
5619
  "@release-it/bumper": "8.0.1",
5523
5620
  "@types/node": "24.19.2",
5524
- "@vitest/coverage-v8": "5.0.3",
5621
+ "@vitest/coverage-v8": "5.0.5",
5525
5622
  "commit-and-tag-version": "13.3.0",
5526
- "knip": "6.41.0",
5623
+ "knip": "6.42.1",
5527
5624
  "lefthook": "2.2.2",
5528
- "modern-web-guidance": "0.0.194",
5529
- "oxfmt": "0.73.0",
5530
- "oxlint": "1.87.0",
5531
- "oxlint-tsgolint": "7.0.2004",
5625
+ "modern-web-guidance": "0.0.195",
5626
+ "oxfmt": "0.74.0",
5627
+ "oxlint": "1.89.0",
5628
+ "oxlint-tsgolint": "7.0.2005",
5532
5629
  "prettier": "3.9.10",
5533
5630
  "release-it": "21.1.1",
5534
5631
  "tsdown": "0.23.1",
5535
5632
  "typescript": "6.0.3",
5536
- "vitest": "5.0.3",
5537
- "pnpm": "11.28.5"
5633
+ "vitest": "5.0.5",
5634
+ "pnpm": "11.28.8"
5538
5635
  }["@changesets/cli"];
5539
5636
  }
5540
5637
  }
@@ -5649,20 +5746,20 @@ function applyMetadataDefaults(pkg, ctx, changes) {
5649
5746
  "@changesets/cli": "3.0.3",
5650
5747
  "@release-it/bumper": "8.0.1",
5651
5748
  "@types/node": "24.19.2",
5652
- "@vitest/coverage-v8": "5.0.3",
5749
+ "@vitest/coverage-v8": "5.0.5",
5653
5750
  "commit-and-tag-version": "13.3.0",
5654
- "knip": "6.41.0",
5751
+ "knip": "6.42.1",
5655
5752
  "lefthook": "2.2.2",
5656
- "modern-web-guidance": "0.0.194",
5657
- "oxfmt": "0.73.0",
5658
- "oxlint": "1.87.0",
5659
- "oxlint-tsgolint": "7.0.2004",
5753
+ "modern-web-guidance": "0.0.195",
5754
+ "oxfmt": "0.74.0",
5755
+ "oxlint": "1.89.0",
5756
+ "oxlint-tsgolint": "7.0.2005",
5660
5757
  "prettier": "3.9.10",
5661
5758
  "release-it": "21.1.1",
5662
5759
  "tsdown": "0.23.1",
5663
5760
  "typescript": "6.0.3",
5664
- "vitest": "5.0.3",
5665
- "pnpm": "11.28.5"
5761
+ "vitest": "5.0.5",
5762
+ "pnpm": "11.28.8"
5666
5763
  }["pnpm"];
5667
5764
  const desiredPm = pinnedPnpm ? `pnpm@${pinnedPnpm}` : void 0;
5668
5765
  if (desiredPm) {
@@ -5700,47 +5797,47 @@ function buildManagedDevDeps(ctx) {
5700
5797
  const isMonorepo = ctx.config.structure === "monorepo";
5701
5798
  const devDeps = { ...rootDevDeps(ctx.config) };
5702
5799
  if (!isMonorepo) Object.assign(devDeps, perPackageDevDeps(ctx.config));
5703
- if (ctx.config.stack !== "none") devDeps["@bensandee/config"] = isWorkspacePackage(ctx, "@bensandee/config") ? "workspace:*" : "0.15.0";
5704
- if (!isWorkspacePackage(ctx, "@bensandee/tooling")) devDeps["@bensandee/tooling"] = "0.99.0";
5705
- if (ctx.config.useEslintPlugin && ctx.config.stack !== "none") devDeps["@bensandee/eslint-plugin"] = isWorkspacePackage(ctx, "@bensandee/eslint-plugin") ? "workspace:*" : "0.17.0";
5706
- if (wantsAgentCli(ctx)) devDeps[AGENT_CLI_PACKAGE] = "0.2.0";
5800
+ if (ctx.config.stack !== "none") devDeps["@bensandee/config"] = isWorkspacePackage(ctx, "@bensandee/config") ? "workspace:*" : "0.15.1";
5801
+ if (!isWorkspacePackage(ctx, "@bensandee/tooling")) devDeps["@bensandee/tooling"] = "0.100.0";
5802
+ if (ctx.config.useEslintPlugin && ctx.config.stack !== "none") devDeps["@bensandee/eslint-plugin"] = isWorkspacePackage(ctx, "@bensandee/eslint-plugin") ? "workspace:*" : "0.18.0";
5803
+ if (wantsAgentCli(ctx)) devDeps[AGENT_CLI_PACKAGE] = "0.3.0";
5707
5804
  if (ctx.config.formatter === "oxfmt") devDeps["oxfmt"] = {
5708
5805
  "@changesets/cli": "3.0.3",
5709
5806
  "@release-it/bumper": "8.0.1",
5710
5807
  "@types/node": "24.19.2",
5711
- "@vitest/coverage-v8": "5.0.3",
5808
+ "@vitest/coverage-v8": "5.0.5",
5712
5809
  "commit-and-tag-version": "13.3.0",
5713
- "knip": "6.41.0",
5810
+ "knip": "6.42.1",
5714
5811
  "lefthook": "2.2.2",
5715
- "modern-web-guidance": "0.0.194",
5716
- "oxfmt": "0.73.0",
5717
- "oxlint": "1.87.0",
5718
- "oxlint-tsgolint": "7.0.2004",
5812
+ "modern-web-guidance": "0.0.195",
5813
+ "oxfmt": "0.74.0",
5814
+ "oxlint": "1.89.0",
5815
+ "oxlint-tsgolint": "7.0.2005",
5719
5816
  "prettier": "3.9.10",
5720
5817
  "release-it": "21.1.1",
5721
5818
  "tsdown": "0.23.1",
5722
5819
  "typescript": "6.0.3",
5723
- "vitest": "5.0.3",
5724
- "pnpm": "11.28.5"
5820
+ "vitest": "5.0.5",
5821
+ "pnpm": "11.28.8"
5725
5822
  }["oxfmt"];
5726
5823
  if (ctx.config.formatter === "prettier") devDeps["prettier"] = {
5727
5824
  "@changesets/cli": "3.0.3",
5728
5825
  "@release-it/bumper": "8.0.1",
5729
5826
  "@types/node": "24.19.2",
5730
- "@vitest/coverage-v8": "5.0.3",
5827
+ "@vitest/coverage-v8": "5.0.5",
5731
5828
  "commit-and-tag-version": "13.3.0",
5732
- "knip": "6.41.0",
5829
+ "knip": "6.42.1",
5733
5830
  "lefthook": "2.2.2",
5734
- "modern-web-guidance": "0.0.194",
5735
- "oxfmt": "0.73.0",
5736
- "oxlint": "1.87.0",
5737
- "oxlint-tsgolint": "7.0.2004",
5831
+ "modern-web-guidance": "0.0.195",
5832
+ "oxfmt": "0.74.0",
5833
+ "oxlint": "1.89.0",
5834
+ "oxlint-tsgolint": "7.0.2005",
5738
5835
  "prettier": "3.9.10",
5739
5836
  "release-it": "21.1.1",
5740
5837
  "tsdown": "0.23.1",
5741
5838
  "typescript": "6.0.3",
5742
- "vitest": "5.0.3",
5743
- "pnpm": "11.28.5"
5839
+ "vitest": "5.0.5",
5840
+ "pnpm": "11.28.8"
5744
5841
  }["prettier"];
5745
5842
  addReleaseDeps(devDeps, ctx);
5746
5843
  return devDeps;
@@ -5798,20 +5895,20 @@ async function generatePackageJson(ctx) {
5798
5895
  "@changesets/cli": "3.0.3",
5799
5896
  "@release-it/bumper": "8.0.1",
5800
5897
  "@types/node": "24.19.2",
5801
- "@vitest/coverage-v8": "5.0.3",
5898
+ "@vitest/coverage-v8": "5.0.5",
5802
5899
  "commit-and-tag-version": "13.3.0",
5803
- "knip": "6.41.0",
5900
+ "knip": "6.42.1",
5804
5901
  "lefthook": "2.2.2",
5805
- "modern-web-guidance": "0.0.194",
5806
- "oxfmt": "0.73.0",
5807
- "oxlint": "1.87.0",
5808
- "oxlint-tsgolint": "7.0.2004",
5902
+ "modern-web-guidance": "0.0.195",
5903
+ "oxfmt": "0.74.0",
5904
+ "oxlint": "1.89.0",
5905
+ "oxlint-tsgolint": "7.0.2005",
5809
5906
  "prettier": "3.9.10",
5810
5907
  "release-it": "21.1.1",
5811
5908
  "tsdown": "0.23.1",
5812
5909
  "typescript": "6.0.3",
5813
- "vitest": "5.0.3",
5814
- "pnpm": "11.28.5"
5910
+ "vitest": "5.0.5",
5911
+ "pnpm": "11.28.8"
5815
5912
  }["pnpm"]}`
5816
5913
  };
5817
5914
  ctx.write(filePath, JSON.stringify(pkg, null, 2) + "\n");
@@ -5844,8 +5941,7 @@ function removeWorkspaceDevEnginesRuntime(ctx, relPath) {
5844
5941
  description: "removed devEngines.runtime (mise.toml declares the runtime)"
5845
5942
  };
5846
5943
  }
5847
- //#endregion
5848
- //#region src/generators/stale-config.ts
5944
+ // src/generators/stale-config.ts
5849
5945
  function reportStaleConfig(filePath, reason) {
5850
5946
  log$1.warn(`${filePath} is stale: ${reason}, so nothing reads it. bst does not delete it -- remove it yourself, or correct the stack/builder in .tooling.json if this is wrong.`);
5851
5947
  return {
@@ -5854,8 +5950,7 @@ function reportStaleConfig(filePath, reason) {
5854
5950
  description: `Stale (${reason}); left in place`
5855
5951
  };
5856
5952
  }
5857
- //#endregion
5858
- //#region src/generators/tsconfig.ts
5953
+ // src/generators/tsconfig.ts
5859
5954
  const DEFAULT_INCLUDE = [
5860
5955
  "src",
5861
5956
  "test",
@@ -6086,8 +6181,7 @@ function generateMonorepoPackageTsconfigs(ctx) {
6086
6181
  }
6087
6182
  return results;
6088
6183
  }
6089
- //#endregion
6090
- //#region src/coverage-tracking/compare.ts
6184
+ // src/coverage-tracking/compare.ts
6091
6185
  const TOTAL_KEYS = [
6092
6186
  "lines",
6093
6187
  "statements",
@@ -6130,8 +6224,7 @@ function mergeTotalsWithFloor(baseline, current, floorPp) {
6130
6224
  for (const key of TOTAL_KEYS) if (current[key] >= floorPp || current[key] >= baseline[key]) merged[key] = current[key];
6131
6225
  return merged;
6132
6226
  }
6133
- //#endregion
6134
- //#region src/coverage-tracking/parse.ts
6227
+ // src/coverage-tracking/parse.ts
6135
6228
  const TotalEntrySchema = z.object({
6136
6229
  total: z.number(),
6137
6230
  covered: z.number(),
@@ -6196,8 +6289,7 @@ function parseHistoryLine(line) {
6196
6289
  const result = CoverageRecordSchema.safeParse(json);
6197
6290
  return result.success ? result.data : void 0;
6198
6291
  }
6199
- //#endregion
6200
- //#region src/coverage-tracking/history.ts
6292
+ // src/coverage-tracking/history.ts
6201
6293
  const DEFAULT_HISTORY_BRANCH = "bst/coverage-metrics";
6202
6294
  const HISTORY_FILE = "coverage-history.jsonl";
6203
6295
  const MAX_PUSH_ATTEMPTS = 5;
@@ -6346,8 +6438,7 @@ function readRecordsGeneric(executor, config, parseLine) {
6346
6438
  }
6347
6439
  return records;
6348
6440
  }
6349
- //#endregion
6350
- //#region src/coverage-tracking/config.ts
6441
+ // src/coverage-tracking/config.ts
6351
6442
  const NO_SOURCE_REASON = "no JS/TS source";
6352
6443
  function resolveFromInputs(inputs) {
6353
6444
  if (inputs.coverage === false) return {
@@ -6403,8 +6494,7 @@ function resolveCoverageConfigFromContext(reader, fallbackSetupVitest) {
6403
6494
  stack: reader.config.stack
6404
6495
  });
6405
6496
  }
6406
- //#endregion
6407
- //#region src/generators/vitest.ts
6497
+ // src/generators/vitest.ts
6408
6498
  const DEFAULT_COVERAGE_INCLUDE = ["src/**"];
6409
6499
  function renderStringArray(items) {
6410
6500
  return `[${items.map((item) => JSON.stringify(item)).join(", ")}]`;
@@ -6559,8 +6649,7 @@ async function generateVitest(ctx) {
6559
6649
  warnIfMissingInclude(ctx);
6560
6650
  return results;
6561
6651
  }
6562
- //#endregion
6563
- //#region src/generators/oxlint.ts
6652
+ // src/generators/oxlint.ts
6564
6653
  const IGNORE_PATTERNS_SPREAD = "...(recommended.ignorePatterns ?? [])";
6565
6654
  const CONFIG_WITH_LINT_RULES = `import recommended from "@bensandee/config/oxlint/recommended";
6566
6655
  import bensandee from "@bensandee/eslint-plugin/recommended";
@@ -6738,8 +6827,7 @@ async function generateOxlint(ctx) {
6738
6827
  description: "Generated oxlint.config.ts"
6739
6828
  };
6740
6829
  }
6741
- //#endregion
6742
- //#region src/generators/formatter.ts
6830
+ // src/generators/formatter.ts
6743
6831
  const BASE_IGNORE_PATTERNS = [
6744
6832
  ".claude",
6745
6833
  ".agent/findings",
@@ -6855,8 +6943,7 @@ async function generatePrettier(ctx) {
6855
6943
  description: "Generated .prettierrc"
6856
6944
  };
6857
6945
  }
6858
- //#endregion
6859
- //#region src/generators/tsdown.ts
6946
+ // src/generators/tsdown.ts
6860
6947
  const TSDOWN_CONFIG = `import { defineConfig } from "tsdown";
6861
6948
 
6862
6949
  export default defineConfig({
@@ -6899,8 +6986,7 @@ async function generateTsdown(ctx) {
6899
6986
  description: "Generated tsdown.config.ts"
6900
6987
  };
6901
6988
  }
6902
- //#endregion
6903
- //#region src/generators/mise.ts
6989
+ // src/generators/mise.ts
6904
6990
  const TOOLS_HEADER_RE = /^\[tools\]\s*$/m;
6905
6991
  const TOP_LEVEL_HEADER_RE = /^\[{1,2}[^[].*\]{1,2}\s*$/m;
6906
6992
  const PNPM_LINE_RE = /^pnpm\s*=.*$/m;
@@ -7075,8 +7161,7 @@ const log = {
7075
7161
  current.debug(message);
7076
7162
  }
7077
7163
  };
7078
- //#endregion
7079
- //#region ../forgejo/src/releases.ts
7164
+ // ../forgejo/src/releases.ts
7080
7165
  const SETTLE_ATTEMPTS = 4;
7081
7166
  const SETTLE_BASE_DELAY_MS = 2e3;
7082
7167
  const SETTLE_MAX_DELAY_MS = 16e3;
@@ -7320,8 +7405,7 @@ z.looseObject({
7320
7405
  created: z.string().nullish()
7321
7406
  })
7322
7407
  });
7323
- //#endregion
7324
- //#region src/release/publish/version-of-record.ts
7408
+ // src/release/publish/version-of-record.ts
7325
7409
  const FOREIGN_VERSION_FILES = [{
7326
7410
  file: "Cargo.toml",
7327
7411
  sections: ["package"]
@@ -7361,8 +7445,7 @@ function releaseTargetConflict(stack, releaseStrategy, targetDir) {
7361
7445
  if (stack !== "none" || releaseStrategy !== "simple") return void 0;
7362
7446
  return detectForeignVersionOfRecord(targetDir);
7363
7447
  }
7364
- //#endregion
7365
- //#region src/release/publish/version-stamp.ts
7448
+ // src/release/publish/version-stamp.ts
7366
7449
  function splitLines(content) {
7367
7450
  const trailingNewline = content.endsWith("\n");
7368
7451
  return {
@@ -7406,8 +7489,7 @@ function stampContent(content, entry, version) {
7406
7489
  split.lines[index] = hasCr ? `${replacement}\r` : replacement;
7407
7490
  return joinLines(split);
7408
7491
  }
7409
- //#endregion
7410
- //#region src/release/publish/assets.ts
7492
+ // src/release/publish/assets.ts
7411
7493
  const CONVENTION_SCRIPT = "build:release-assets";
7412
7494
  const CONVENTION_OUTPUT_DIR = "release-assets";
7413
7495
  function configuredTargets(cwd, toolingConfig) {
@@ -7574,8 +7656,7 @@ async function releaseExists(executor, config, tag) {
7574
7656
  debugExec(config, `gh release view ${tag}`, result);
7575
7657
  return result.exitCode === 0;
7576
7658
  }
7577
- //#endregion
7578
- //#region src/generators/gitignore.ts
7659
+ // src/generators/gitignore.ts
7579
7660
  const REQUIRED_ENTRIES = [
7580
7661
  "node_modules/",
7581
7662
  ".pnpm-store/",
@@ -7640,8 +7721,7 @@ async function generateGitignore(ctx) {
7640
7721
  description: "Generated .gitignore"
7641
7722
  };
7642
7723
  }
7643
- //#endregion
7644
- //#region src/generators/gitattributes.ts
7724
+ // src/generators/gitattributes.ts
7645
7725
  const MANAGED_HEADER = ["# Managed by @bensandee/tooling: LF working tree on every platform, overriding", "# core.autocrlf/core.eol at checkout. Rules below this line win over it."].join("\n");
7646
7726
  const PREPEND_REASON = ["# Prepended above your existing rules: .gitattributes is last-match-wins, so a rule", "# placed below would override any binary/-text marks you already have."].join("\n");
7647
7727
  const RULE_LINE = "* text=auto eol=lf";
@@ -7679,8 +7759,7 @@ async function generateGitattributes(ctx) {
7679
7759
  description: "Prepended the LF rule"
7680
7760
  };
7681
7761
  }
7682
- //#endregion
7683
- //#region src/default-branch.ts
7762
+ // src/default-branch.ts
7684
7763
  const DEFAULT_BRANCH = "main";
7685
7764
  const DefaultBranchSliceSchema = z.object({ defaultBranch: z.union([z.literal(""), DefaultBranchNameSchema]).optional() });
7686
7765
  function configuredDefaultBranch(raw) {
@@ -7732,8 +7811,7 @@ function refuseForgeDefaultMismatch(configured, source, command) {
7732
7811
  if (reported === void 0 || reported === configured) return;
7733
7812
  throw new FatalError(`${command}: .tooling.json#defaultBranch is "${configured}", but the forge reports "${reported}" as this repository's default branch. Set .tooling.json#defaultBranch to "${reported}" and run pnpm exec bst repo:sync.`);
7734
7813
  }
7735
- //#endregion
7736
- //#region src/generators/release-ci.ts
7814
+ // src/generators/release-ci.ts
7737
7815
  const DEFAULT_POST_RELEASE_COMMAND = [
7738
7816
  "pnpm exec bst webhook:send",
7739
7817
  " \"$POST_RELEASE_HOOK_URL\"",
@@ -8006,13 +8084,11 @@ async function generateReleaseCi(ctx) {
8006
8084
  description: `Generated ${isGitHub ? "GitHub" : "Forgejo"} Actions release workflow`
8007
8085
  };
8008
8086
  }
8009
- //#endregion
8010
- //#region src/release/version-branch.ts
8087
+ // src/release/version-branch.ts
8011
8088
  function versionPrBranch(defaultBranch) {
8012
8089
  return `changeset-release/${defaultBranch}`;
8013
8090
  }
8014
- //#endregion
8015
- //#region src/generators/ci.ts
8091
+ // src/generators/ci.ts
8016
8092
  function coverageHistorySteps() {
8017
8093
  return [
8018
8094
  { step: {
@@ -8237,8 +8313,7 @@ async function generateCi(ctx) {
8237
8313
  description: `Generated ${isGitHub ? "GitHub" : "Forgejo"} Actions CI workflow`
8238
8314
  };
8239
8315
  }
8240
- //#endregion
8241
- //#region src/generators/knip.ts
8316
+ // src/generators/knip.ts
8242
8317
  const FOREIGN_OWNED = ["composer"];
8243
8318
  function scriptsInvoke(ctx, binary) {
8244
8319
  const invocation = new RegExp(String.raw`(?<![\w.-])${binary}(?![\w.-])`);
@@ -8486,8 +8561,7 @@ async function generateKnip(ctx) {
8486
8561
  description: createdDescription(filePath)
8487
8562
  };
8488
8563
  }
8489
- //#endregion
8490
- //#region src/generators/renovate.ts
8564
+ // src/generators/renovate.ts
8491
8565
  const SHARED_PRESET = "local>bensandee/tooling";
8492
8566
  const RENOVATE_CONFIG_PATHS = [
8493
8567
  "renovate.json",
@@ -8538,8 +8612,7 @@ async function generateRenovate(ctx) {
8538
8612
  description: "Generated renovate.json extending shared config"
8539
8613
  };
8540
8614
  }
8541
- //#endregion
8542
- //#region src/generators/pnpm-workspace.ts
8615
+ // src/generators/pnpm-workspace.ts
8543
8616
  const FILE_PATH = "pnpm-workspace.yaml";
8544
8617
  const DEFAULT_MIN_RELEASE_AGE = 1440;
8545
8618
  const BENSANDEE_EXCLUDE_PATTERN = "@bensandee/*";
@@ -8625,12 +8698,10 @@ async function generatePnpmWorkspace(ctx) {
8625
8698
  description: changes.join(", ")
8626
8699
  };
8627
8700
  }
8628
- //#endregion
8629
- //#region src/generators/claude-hooks-placeholder.ts
8701
+ // src/generators/claude-hooks-placeholder.ts
8630
8702
  const HOOK_NOT_BUILT_PLACEHOLDER = "/* bst-hook not built -- run pnpm build from packages/claude-hooks first */";
8631
8703
  const GUIDE_NOT_BUILT_PLACEHOLDER = "<!-- bst-hook guide not built -->";
8632
- //#endregion
8633
- //#region src/generators/claude-hooks.ts
8704
+ // src/generators/claude-hooks.ts
8634
8705
  const HOOK_PATH = ".claude/hooks/bst-hook.mjs";
8635
8706
  const GUIDE_PATH = ".claude/hooks/bst-hook-guide.md";
8636
8707
  const SETTINGS_PATH$1 = ".claude/hooks/bst-hook.settings.json";
@@ -8677,7 +8748,7 @@ function writeEmbedded(ctx, file) {
8677
8748
  }
8678
8749
  const NOT_BUILT = "run `pnpm build` from the repo root";
8679
8750
  async function generateClaudeHooks(ctx, embedded = {
8680
- hook: "/**\n * bst-hook -- Claude Code PreToolUse hook\n * @bensandee/claude-hooks\n * https://github.com/bensandee/tooling\n *\n * Auto-generated by @bensandee/tooling repo:sync -- do not edit manually.\n */\nimport * as fs from \"node:fs\";\nimport { existsSync, readFileSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { execFileSync } from \"node:child_process\";\n\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js\nfunction joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nfunction jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\") return value.toString();\n return value;\n}\nvar Cached = class {\n constructor(getter) {\n this._getter = getter;\n this._value = void 0;\n }\n get value() {\n const getter = this._getter;\n if (getter !== void 0) {\n this._value = getter();\n this._getter = void 0;\n }\n return this._value;\n }\n};\nfunction cached(getter) {\n return new Cached(getter);\n}\nfunction nullish(input) {\n return input === null || input === void 0;\n}\nfunction cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nfunction assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n}\nconst captureStackTrace = \"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => {};\nfunction isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nfunction isPlainObject(o) {\n if (isObject(o) === false) return false;\n const ctor = o.constructor;\n if (ctor === void 0) return true;\n if (typeof ctor !== \"function\") return true;\n const prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) return false;\n return true;\n}\nfunction shallowClone(o) {\n if (isPlainObject(o)) return { ...o };\n if (Array.isArray(o)) return [...o];\n if (o instanceof Map) return new Map(o);\n if (o instanceof Set) return new Set(o);\n return o;\n}\nfunction clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent) cl._zod.parent = inst;\n return cl;\n}\nfunction normalizeParams(_params) {\n const params = _params;\n if (!params) return {};\n if (typeof params === \"string\") return { error: () => params };\n if (params?.message !== void 0) {\n if (params?.error !== void 0) throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\") return {\n ...params,\n error: () => params.error\n };\n return params;\n}\nfunction stringifyPrimitive(value) {\n if (typeof value === \"bigint\") return value.toString() + \"n\";\n if (typeof value === \"string\") return `\"${value}\"`;\n return `${value}`;\n}\nfunction optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === \"optional\";\n });\n}\nfunction aborted(x, startIndex = 0) {\n if (x.aborted === true) return true;\n for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;\n return false;\n}\nfunction explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true) return true;\n for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true;\n return false;\n}\nfunction prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nfunction unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nfunction sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n if (!/_(length|size)$|_equals$/.test(d.check)) break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0) caps.push([max, ch]);\n }\n return caps;\n}\nfunction attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) (_a = issues[i]).schema ?? (_a.schema = inst);\n}\nfunction finalizeIssue(iss, ctx, config) {\n var _a;\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\")) (_a = iss).schema ?? (_a.schema = iss.inst);\n else iss.schema = iss.inst;\n }\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0;\n const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? \"Invalid input\";\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\") continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) full.input = iss.input;\n return full;\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\nfunction codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str)) return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {\n count--;\n i++;\n }\n return count;\n}\nfunction getLengthableOrigin(input) {\n if (Array.isArray(input)) return \"array\";\n if (typeof input === \"string\") return \"string\";\n return \"unknown\";\n}\nfunction parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"object\": {\n if (data === null) return \"null\";\n if (Array.isArray(data)) return \"array\";\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) return obj.constructor.name;\n }\n }\n return t;\n}\nfunction members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n if (desc.get) Object.defineProperty(proto, key, {\n ...desc,\n enumerable: false\n });\n else defineBound(proto, key, desc.value);\n }\n}\nfunction own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, {\n configurable: true,\n writable: true,\n enumerable,\n value\n });\n return value;\n}\nfunction hide(inst, key, value) {\n return own(inst, key, value, false);\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n }\n });\n}\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n return sentinel in proto ? void 0 : proto;\n}\nlet installing;\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n }\n};\nfunction defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n installing = void 0;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n if (broke) delete this[key];\n else Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n value\n });\n broke = broke || outer;\n return value;\n } catch (err) {\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n value\n });\n }\n });\n}\nfunction installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto) return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n const desc = {\n configurable: true,\n writable: true,\n enumerable,\n value: void 0\n };\n Object.defineProperty(this, key, desc);\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable,\n value\n });\n }\n });\n}\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/core.js\nvar _a;\nconst _zodDesc = {\n value: void 0,\n enumerable: false\n};\nlet _E = \"captureStackTrace\" in Error ? Error : null;\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n } catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n } finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\n/* @__NO_SIDE_EFFECTS__ */\nfunction $constructor(name, initializer, proto, params) {\n const zodProto = {};\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = /* @__PURE__ */ new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n const initialized = protoMembers && /* @__PURE__ */ new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n } finally {\n _zodDesc.value = void 0;\n }\n } else if (inst._zod.traits.has(name)) return;\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto) up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n members(target, protoMembers);\n }\n }\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k)) continue;\n if (!(k in inst)) inst[k] = proto[k].bind(inst);\n }\n }\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {}\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) fn();\n inst._zod.deferred = void 0;\n }\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp) pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent) return true;\n return inst?._zod?.traits?.has(name);\n } });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\nvar $ZodAsyncError = class extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n};\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nconst globalConfig = globalThis.__zod_globalConfig;\nfunction config(newConfig) {\n if (newConfig) Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/errors.js\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true\n};\nconst _issuesDesc = {\n value: void 0,\n enumerable: false\n};\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n _issuesDesc.value = void 0;\n Object.defineProperty(inst, \"message\", _messageDesc);\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", {\n value,\n configurable: true,\n writable: true\n });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", {\n value,\n configurable: true,\n writable: true\n });\n }\n });\n }\n};\nconst $ZodRealError = /* @__PURE__ */ $constructor(\"$ZodError\", initializer, void 0, { Parent: Error });\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/parse.js\nconst _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? {\n ..._ctx,\n async: false\n } : { async: false };\n const result = schema._zod.run({\n value,\n issues: []\n }, ctx);\n if (result instanceof Promise) throw new $ZodAsyncError();\n if (result.issues.length) {\n const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));\n captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nconst parse = /* @__PURE__*/ _parse($ZodRealError);\nconst _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? {\n ..._ctx,\n async: true\n } : { async: true };\n let result = schema._zod.run({\n value,\n issues: []\n }, ctx);\n if (result instanceof Promise) result = await result;\n if (result.issues.length) {\n const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));\n captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nconst parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError);\nconst _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? {\n ..._ctx,\n async: false\n } : { async: false };\n const result = schema._zod.run({\n value,\n issues: []\n }, ctx);\n if (result instanceof Promise) throw new $ZodAsyncError();\n return result.issues.length ? failure(_Err, result.issues, ctx) : {\n success: true,\n data: result.value\n };\n};\nconst safeParse = /* @__PURE__*/ _safeParse($ZodRealError);\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));\n issues = void 0;\n ctx = void 0;\n }\n return error;\n },\n set error(e) {\n error = e;\n issues = void 0;\n ctx = void 0;\n }\n };\n}\nconst _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? {\n ..._ctx,\n async: true\n } : { async: true };\n let result = schema._zod.run({\n value,\n issues: []\n }, ctx);\n if (result instanceof Promise) result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : {\n success: true,\n data: result.value\n };\n};\nconst safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError);\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/regexes.js\nconst anyString = /^[\\s\\S]{0,}$/;\nconst number = /^-?\\d+(?:\\.\\d+)?$/;\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/checks.js\nconst $ZodCheck = /*@__PURE__*/ $constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !nullish(val) && val.length !== void 0;\n};\nconst $ZodCheckMinLength = /*@__PURE__*/ $constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n if ((typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units) >= def.minimum) return;\n const origin = getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort\n });\n };\n});\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/versions.js\nconst version = {\n major: 4,\n minor: 6,\n patch: 7\n};\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/schemas.js\nconst $ZodType = /*@__PURE__*/ $constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def;\n inst._zod.bag = inst._zod.bag || {};\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n const checks = inst._zod.traits.has(\"$ZodCheck\") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : [];\n for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);\n if (checks.length === 0) {\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n } else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo) return payload;\n let isAborted = aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (explicitlyAborted(payload)) continue;\n if (!ch._zod.def.when(payload)) continue;\n } else if (isAborted) continue;\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();\n if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n if (payload.issues.length === currLen) return;\n attachSchema(payload.issues, currLen, inst);\n if (!isAborted) isAborted = aborted(payload, currLen);\n });\n else {\n if (payload.issues.length === currLen) continue;\n attachSchema(payload.issues, currLen, inst);\n if (!isAborted) isAborted = aborted(payload, currLen);\n }\n }\n if (asyncResult) return asyncResult.then(() => {\n return payload;\n });\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n if (aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false) throw new $ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) return inst._zod.parse(payload, ctx);\n if (ctx.direction === \"backward\") {\n const canary = inst._zod.parse({\n value: payload.value,\n issues: []\n }, {\n ...ctx,\n skipChecks: true\n });\n if (canary instanceof Promise) return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n return handleCanaryResult(canary, payload, ctx);\n }\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false) throw new $ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n get \"~standard\"() {\n return hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n own(this, \"~standard\", value);\n }\n});\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult(await inst._zod.run({\n value,\n issues: []\n }, ctx), ctx);\n}\nfunction standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({\n value,\n issues: []\n }, ctx);\n if (!(r instanceof Promise)) return toStandardResult(r, ctx);\n } catch (_) {}\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1\n };\n}\nconst $ZodString = /*@__PURE__*/ $constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = def.pattern ?? anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce) try {\n payload.value = String(payload.value);\n } catch (_) {}\n if (typeof payload.value === \"string\") return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst\n });\n return payload;\n };\n});\nconst $ZodUnknown = /*@__PURE__*/ $constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nfunction capSize(inst, size) {\n const caps = sizeCaps(inst._zod.def.checks);\n if (!caps.length) return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of sizeCaps(inst._zod.def.checks)) if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n payload.issues[start].continue = false;\n attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => Array.isArray(input) ? input.length : -1;\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));\n final.value[index] = result.value;\n}\nconst $ZodArray = /*@__PURE__*/ $constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: []\n }, ctx);\n if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n else {\n handleArrayResult(result, payload, i);\n if (abortEarly && result.issues.length !== 0 && aborted(result)) break;\n }\n }\n if (proms.length) return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n if (!isPresent && isOptionalOut && optin === \"optional\") return;\n if (result.issues.length) {\n if (optin !== void 0 && isOptionalOut && !isPresent) return;\n final.issues.push(...prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === void 0) {\n if (!result.issues.length) final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: void 0,\n path: [key]\n });\n return;\n }\n if (result.value === void 0) {\n if (isPresent || optin === \"defaulted\" && !isOptionalOut) final.value[key] = void 0;\n } else final.value[key] = result.value;\n}\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n const okeys = optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys)\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (aborted(payload, seen)) break;\n seen = payload.issues.length;\n }\n if (keySet.has(key)) continue;\n if (key === \"__proto__\") {\n if (t === \"never\") unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({\n value: input[key],\n issues: []\n }, ctx);\n if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n else handlePropertyResult(r, payload, key, input, optin, optout);\n }\n if (unrecognized.length) payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n continue: true\n });\n if (!proms.length) return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nconst $ZodObject = /*@__PURE__*/ $constructor(\"$ZodObject\", (inst, def) => {\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n const sh = desc?.get ? desc.get.raw : def.shape ?? {};\n if (sh) {\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = cached(() => normalizeDef(def));\n defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) assignProp(propValues, key, /* @__PURE__ */ new Set());\n for (const v of field.values) propValues[key].add(v);\n if (field.optin !== void 0) propValues[key].add(void 0);\n }\n }\n return propValues;\n });\n const isObject$1 = isObject;\n const catchall = def.catchall;\n let value;\n const memo = globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject$1(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (aborted(payload, seen)) break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\") continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({\n value: input[key],\n issues: []\n }, ctx);\n if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n else handlePropertyResult(r, payload, key, input, optin, optout);\n }\n if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nconst $ZodRecord = /*@__PURE__*/ $constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = /* @__PURE__ */ new Set();\n for (const key of values) if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n if (key === \"__proto__\") continue;\n const keyResult = def.keyType._zod.run({\n value: key,\n issues: []\n }, ctx);\n if (keyResult instanceof Promise) throw new Error(\"Async schemas not supported in object keys currently\");\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),\n input: key,\n path: [key],\n inst\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\") continue;\n const result = def.valueType._zod.run({\n value: input[key],\n issues: []\n }, ctx);\n if (result instanceof Promise) proms.push(result.then((result) => {\n if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));\n payload.value[outKey] = result.value;\n }));\n else {\n if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));\n payload.value[outKey] = result.value;\n }\n }\n let unrecognized;\n for (const key in input) if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n if (key === \"__proto__\") continue;\n payload.value[key] = input[key];\n } else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true\n });\n } else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n let unrecognized;\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\") continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue;\n let keyResult = def.keyType._zod.run({\n value: key,\n issues: []\n }, ctx);\n if (keyResult instanceof Promise) throw new Error(\"Async schemas not supported in object keys currently\");\n if (typeof key === \"string\" && number.test(key) && keyResult.issues.length) {\n const retryResult = def.keyType._zod.run({\n value: Number(key),\n issues: []\n }, ctx);\n if (retryResult instanceof Promise) throw new Error(\"Async schemas not supported in object keys currently\");\n if (retryResult.issues.length === 0) keyResult = retryResult;\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") payload.value[key] = input[key];\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n } else payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),\n input: key,\n path: [key],\n inst\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\") continue;\n const result = def.valueType._zod.run({\n value: input[key],\n issues: []\n }, ctx);\n if (result instanceof Promise) proms.push(result.then((result) => {\n if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));\n payload.value[outKey] = result.value;\n }));\n else {\n if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true\n });\n }\n if (proms.length) return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n payload.value = result.issues.length ? void 0 : result.value;\n return payload;\n}\nconst $ZodOptional = /*@__PURE__*/ $constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? /* @__PURE__ */ new Set([...values, void 0]) : void 0;\n });\n defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === void 0) {\n if (def.innerType._zod.optin !== \"defaulted\") return payload;\n const result = def.innerType._zod.run({\n value: payload.value,\n issues: []\n }, ctx);\n if (result instanceof Promise) return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nconst $ZodDefault = /*@__PURE__*/ $constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") return def.innerType._zod.run(payload, ctx);\n if (payload.value === void 0) {\n payload.value = def.defaultValue;\n return payload;\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === void 0) payload.value = def.defaultValue;\n return payload;\n}\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/en.js\nconst error = () => {\n const Sizable = {\n string: {\n unit: \"characters\",\n verb: \"to have\"\n },\n file: {\n unit: \"bytes\",\n verb: \"to have\"\n },\n array: {\n unit: \"items\",\n verb: \"to have\"\n },\n set: {\n unit: \"items\",\n verb: \"to have\"\n },\n map: {\n unit: \"entries\",\n verb: \"to have\"\n }\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\"\n };\n const TypeDictionary = { nan: \"NaN\" };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) return String(input);\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": return `Invalid input: expected ${getTypeName(issue.expected)}, received ${getTypeName(parsedType(issue.input), issue.input)}`;\n case \"invalid_value\":\n if (issue.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") return `Invalid string: must start with \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\") return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\") return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\") return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\": return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\": return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${joinValues(issue.keys, \", \")}`;\n case \"invalid_key\": return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) return `Invalid discriminator value. Expected ${issue.options.map((o) => `'${o}'`).join(\" | \")}`;\n if (issue.inclusive === false) return \"Invalid input: more than one option matched\";\n return \"Invalid input\";\n case \"invalid_element\": return `Invalid value in ${issue.origin}`;\n default: return `Invalid input`;\n }\n };\n};\nfunction en_default() {\n return { localeError: error() };\n}\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/api.js\nfunction snapshotChecks(def) {\n if (def.checks) def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nfunction _string(Class, params) {\n return new Class(snapshotChecks({\n type: \"string\",\n ...normalizeParams(params)\n }));\n}\n// @__NO_SIDE_EFFECTS__\nfunction _unknown(Class) {\n return new Class({ type: \"unknown\" });\n}\n// @__NO_SIDE_EFFECTS__\nfunction _minLength(minimum, params) {\n return new $ZodCheckMinLength({\n check: \"min_length\",\n ...normalizeParams(params),\n minimum\n });\n}\n\n//#endregion\n//#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/schemas.js\nconst ZodMiniType = /*@__PURE__*/ $constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod) throw new Error(\"Uninitialized schema in ZodMiniType.\");\n $ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n}, {\n get with() {\n return this.check;\n },\n set with(value) {\n own(this, \"with\", value);\n },\n parse(data, params) {\n return parse(this, data, params, { callee: this.parse });\n },\n parseAsync(data, params) {\n return parseAsync(this, data, params, { callee: this.parseAsync });\n },\n safeParse(data, params) {\n return safeParse(this, data, params);\n },\n safeParseAsync(data, params) {\n return safeParseAsync(this, data, params);\n },\n check(...checks) {\n const def = this.def;\n return this.clone({\n ...def,\n checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === \"function\" ? { _zod: {\n check: ch,\n def: { check: \"custom\" },\n onattach: []\n } } : ch)]\n }, { parent: true });\n },\n clone(_def, params) {\n return clone(this, _def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n }\n});\nconst ZodMiniString = /*@__PURE__*/ $constructor(\"ZodMiniString\", (inst, def) => {\n $ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction string(params) {\n return _string(ZodMiniString, params);\n}\nconst ZodMiniUnknown = /*@__PURE__*/ $constructor(\"ZodMiniUnknown\", (inst, def) => {\n $ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction unknown() {\n return _unknown(ZodMiniUnknown);\n}\nconst ZodMiniArray = /*@__PURE__*/ $constructor(\"ZodMiniArray\", (inst, def) => {\n $ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element,\n ...normalizeParams(params)\n });\n}\nconst ZodMiniObject = /*@__PURE__*/ $constructor(\"ZodMiniObject\", (inst, def) => {\n $ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n});\n// @__NO_SIDE_EFFECTS__\nfunction object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...normalizeParams(params)\n };\n return new ZodMiniObject(def);\n}\nconst ZodMiniRecord = /*@__PURE__*/ $constructor(\"ZodMiniRecord\", (inst, def) => {\n $ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction record(keyType, valueType, params) {\n if (!valueType || !valueType._zod) return new ZodMiniRecord({\n type: \"record\",\n keyType: /* @__PURE__ */ string(),\n valueType: keyType,\n ...normalizeParams(valueType)\n });\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType,\n ...normalizeParams(params)\n });\n}\nconst ZodMiniOptional = /*@__PURE__*/ $constructor(\"ZodMiniOptional\", (inst, def) => {\n $ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType\n });\n}\nconst ZodMiniDefault = /*@__PURE__*/ $constructor(\"ZodMiniDefault\", (inst, def) => {\n $ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : shallowClone(defaultValue);\n }\n });\n}\n\n//#endregion\n//#region src/lib/hook-io.ts\nconfig(en_default());\nconst HookInputSchema = object({\n session_id: string(),\n transcript_path: string(),\n cwd: string(),\n permission_mode: string(),\n hook_event_name: string(),\n tool_name: string(),\n tool_input: record(string(), unknown())\n});\nasync function readHookInput() {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(typeof chunk === \"string\" ? chunk : String(chunk));\n let parsed;\n try {\n parsed = JSON.parse(chunks.join(\"\"));\n } catch (_error) {\n return {\n ok: false,\n raw: chunks.join(\"\").slice(0, 200),\n error: \"invalid JSON\"\n };\n }\n const result = HookInputSchema.safeParse(parsed);\n if (!result.success) return {\n ok: false,\n raw: parsed,\n error: result.error.message\n };\n return {\n ok: true,\n data: result.data\n };\n}\nconst BashInputSchema = object({\n command: string(),\n description: optional(string())\n});\nconst FilePathInputSchema = object({ file_path: string() });\nconst SearchInputSchema = object({\n pattern: string(),\n path: optional(string())\n});\nfunction parseBashInput(toolInput) {\n const result = BashInputSchema.safeParse(toolInput);\n return result.success ? result.data : null;\n}\nfunction parseFilePathInput(toolInput) {\n const result = FilePathInputSchema.safeParse(toolInput);\n return result.success ? result.data : null;\n}\nfunction parseSearchInput(toolInput) {\n const result = SearchInputSchema.safeParse(toolInput);\n return result.success ? result.data : null;\n}\nfunction writeDeny(reason) {\n const decision = { hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n ...reason ? { permissionDecisionReason: reason } : {}\n } };\n process.stdout.write(JSON.stringify(decision));\n}\nfunction writeAdvice(advice) {\n const decision = { hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n additionalContext: advice\n } };\n process.stdout.write(JSON.stringify(decision));\n}\n\n//#endregion\n//#region src/lib/audit.ts\nconst MAX_LOG_SIZE = 1048576;\nfunction getLogPath() {\n const hookDir = path.dirname(fileURLToPath(import.meta.url));\n return path.join(hookDir, \"bst-hook.audit.local.jsonl\");\n}\nfunction rotateIfNeeded(logPath) {\n try {\n if (fs.statSync(logPath).size > MAX_LOG_SIZE) {\n const rotatedPath = `${logPath}.1`;\n fs.renameSync(logPath, rotatedPath);\n }\n } catch (_error) {}\n}\nlet rotationChecked = false;\nfunction audit(entry) {\n try {\n const logPath = getLogPath();\n if (!rotationChecked) {\n rotateIfNeeded(logPath);\n rotationChecked = true;\n }\n const record = {\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n ...entry\n };\n fs.appendFileSync(logPath, JSON.stringify(record) + \"\\n\");\n } catch (err) {\n process.stderr.write(`[bst-hook] audit write failed: ${err instanceof Error ? err.message : String(err)}\\n`);\n }\n}\n\n//#endregion\n//#region src/lib/shell-tokenizer.ts\nfunction scanDoubleQuoted(input, start) {\n let content = \"\";\n let i = start;\n while (i < input.length && input[i] !== \"\\\"\") {\n if (input[i] === \"\\\\\" && i + 1 < input.length) {\n const next = input[i + 1];\n if (next === \"\\\"\" || next === \"\\\\\" || next === \"$\" || next === \"`\") {\n content += next;\n i += 2;\n continue;\n }\n }\n content += input[i];\n i++;\n }\n if (i >= input.length) return null;\n return {\n content,\n next: i + 1\n };\n}\nfunction tokenize(input) {\n const tokens = [];\n let current = \"\";\n let i = 0;\n let inToken = false;\n while (i < input.length) {\n const ch = input[i];\n if (ch === \"'\") {\n inToken = true;\n i++;\n while (i < input.length && input[i] !== \"'\") {\n current += input[i];\n i++;\n }\n if (i >= input.length) return {\n ok: false,\n error: \"unterminated single quote\"\n };\n i++;\n } else if (ch === \"\\\"\") {\n inToken = true;\n const scanned = scanDoubleQuoted(input, i + 1);\n if (!scanned) return {\n ok: false,\n error: \"unterminated double quote\"\n };\n current += scanned.content;\n i = scanned.next;\n } else if (ch === \"\\\\\" && i + 1 < input.length) {\n inToken = true;\n current += input[i + 1];\n i += 2;\n } else if (ch === \" \" || ch === \" \") {\n if (inToken) {\n tokens.push(current);\n current = \"\";\n inToken = false;\n }\n i++;\n } else {\n inToken = true;\n current += ch;\n i++;\n }\n }\n if (inToken) tokens.push(current);\n return {\n ok: true,\n tokens\n };\n}\nconst SAFE_UNQUOTED_RE = /^[A-Za-z0-9_\\-./=:@%+,]+$/;\nfunction quoteToken(token) {\n if (token.length > 0 && SAFE_UNQUOTED_RE.test(token)) return token;\n return \"'\" + token.replace(/'/g, \"'\\\\''\") + \"'\";\n}\nfunction joinTokens(tokens) {\n return tokens.map(quoteToken).join(\" \");\n}\n\n//#endregion\n//#region src/lib/shell-splitter.ts\nfunction splitCommand(input) {\n if (!input || !input.trim()) return [];\n const segments = [];\n let current = \"\";\n let i = 0;\n let inSingleQuote = false;\n let inDoubleQuote = false;\n while (i < input.length) {\n const ch = input[i];\n if (ch === \"'\" && !inDoubleQuote) {\n inSingleQuote = !inSingleQuote;\n current += ch;\n i++;\n continue;\n }\n if (ch === \"\\\"\" && !inSingleQuote) {\n inDoubleQuote = !inDoubleQuote;\n current += ch;\n i++;\n continue;\n }\n if (ch === \"\\\\\" && !inSingleQuote && i + 1 < input.length) {\n current += ch + input[i + 1];\n i += 2;\n continue;\n }\n if (!inSingleQuote && !inDoubleQuote) {\n if (ch === \"&\" && i + 1 < input.length && input[i + 1] === \"&\") {\n pushSegment(segments, current, \"&&\");\n current = \"\";\n i += 2;\n continue;\n }\n if (ch === \"&\" && !(i + 1 < input.length && input[i + 1] === \">\") && !(i > 0 && (input[i - 1] === \">\" || input[i - 1] === \"<\"))) {\n pushSegment(segments, current, \"&\");\n current = \"\";\n i++;\n continue;\n }\n if (ch === \"|\" && i + 1 < input.length && input[i + 1] === \"|\") {\n pushSegment(segments, current, \"||\");\n current = \"\";\n i += 2;\n continue;\n }\n if (ch === \"|\") {\n pushSegment(segments, current, \"|\");\n current = \"\";\n i++;\n continue;\n }\n if (ch === \";\") {\n pushSegment(segments, current, \";\");\n current = \"\";\n i++;\n continue;\n }\n }\n current += ch;\n i++;\n }\n const trimmed = current.trim();\n if (trimmed) segments.push({\n command: trimmed,\n operator: null\n });\n return segments;\n}\nfunction pushSegment(segments, text, operator) {\n const trimmed = text.trim();\n if (trimmed) segments.push({\n command: trimmed,\n operator\n });\n}\n\n//#endregion\n//#region src/lib/injection-guard.ts\nfunction hasBraceExpansion(token) {\n let depth = 0;\n for (let i = 0; i < token.length; i++) {\n const ch = token[i];\n if (ch === \"{\") depth++;\n else if (ch === \"}\") {\n if (depth > 0) depth--;\n } else if (depth >= 1 && (ch === \",\" || ch === \".\" && token[i + 1] === \".\")) return true;\n }\n return false;\n}\nfunction checkInjection(tokens, rawSegment) {\n if (/[\\n\\r]/.test(rawSegment)) return {\n safe: false,\n reason: \"unquoted newline in command\"\n };\n for (const token of tokens) {\n if (token === \"`\") return {\n safe: false,\n reason: \"backtick command substitution\"\n };\n if (token.includes(\"`\")) return {\n safe: false,\n reason: \"backtick command substitution\"\n };\n if (token.includes(\"$\")) return {\n safe: false,\n reason: \"unresolved dollar-expansion\"\n };\n if (hasBraceExpansion(token)) return {\n safe: false,\n reason: \"brace expansion\"\n };\n if (token.includes(\"<(\")) return {\n safe: false,\n reason: \"process substitution\"\n };\n if (token.includes(\">(\")) return {\n safe: false,\n reason: \"process substitution\"\n };\n }\n return { safe: true };\n}\n\n//#endregion\n//#region src/lib/env-file.ts\nconst ENV_SAFE_SUFFIXES = [\n \".sample\",\n \".example\",\n \".template\"\n];\nconst ENV_TOOL_OWNED_SUFFIXES = [\".check.env\"];\nconst ENV_FILE_PATTERN = /(^|[/\\\\])(\\.env(\\..*)?|.*\\.env(\\..*)?|\\.env)$/;\nfunction isEnvSafeSuffix(filename) {\n return [...ENV_SAFE_SUFFIXES, ...ENV_TOOL_OWNED_SUFFIXES].some((suffix) => filename.endsWith(suffix));\n}\nfunction isEnvFile(filePath) {\n if (isEnvSafeSuffix(path.basename(filePath))) return false;\n return ENV_FILE_PATTERN.test(filePath);\n}\n\n//#endregion\n//#region src/lib/git-state.ts\nconst GIT_TIMEOUT_MS = 5e3;\nfunction getCurrentBranch(cwd) {\n try {\n const out = execFileSync(\"git\", [\n \"rev-parse\",\n \"--abbrev-ref\",\n \"HEAD\"\n ], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n if (!out || out === \"HEAD\") return null;\n return out;\n } catch {\n return null;\n }\n}\nfunction getRepoTopLevel(cwd) {\n try {\n const out = execFileSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n return out === \"\" ? null : out;\n } catch {\n return null;\n }\n}\nfunction getRemoteDefaultBranch(cwd) {\n try {\n const out = execFileSync(\"git\", [\n \"symbolic-ref\",\n \"--short\",\n \"refs/remotes/origin/HEAD\"\n ], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n if (!out) return null;\n return out.startsWith(\"origin/\") ? out.slice(7) : out;\n } catch {\n return null;\n }\n}\nconst DefaultBranchSchema = object({ defaultBranch: optional(string().check(_minLength(1))) });\nfunction getConfiguredDefaultBranch(topLevel) {\n let parsed;\n try {\n parsed = JSON.parse(readFileSync(join(topLevel, \".tooling.json\"), \"utf-8\"));\n } catch {\n return null;\n }\n const result = DefaultBranchSchema.safeParse(parsed);\n return result.success ? result.data.defaultBranch ?? null : null;\n}\nconst ALWAYS_PROTECTED = [\"main\", \"master\"];\nfunction getProtectedBranches(cwd, extra) {\n const set = new Set(ALWAYS_PROTECTED);\n const remote = getRemoteDefaultBranch(cwd);\n if (remote) set.add(remote);\n for (const b of extra) set.add(b);\n return set;\n}\nfunction getUpstream(cwd, branch) {\n try {\n return execFileSync(\"git\", [\n \"rev-parse\",\n \"--abbrev-ref\",\n `${branch}@{upstream}`\n ], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: 5e3\n }).toString().trim() || null;\n } catch {\n return null;\n }\n}\nfunction resolveCommit(cwd, rev) {\n try {\n return execFileSync(\"git\", [\n \"rev-parse\",\n \"--verify\",\n \"--quiet\",\n `${rev}^{commit}`\n ], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: 5e3\n }).toString().trim() || null;\n } catch {\n return null;\n }\n}\nfunction branchCarriesOtherFiles(cwd, allowed) {\n const toplevel = getRepoTopLevel(cwd);\n if (toplevel === null) return null;\n try {\n const defaultBranch = getConfiguredDefaultBranch(toplevel) ?? getRemoteDefaultBranch(toplevel) ?? \"main\";\n const mergeBase = execFileSync(\"git\", [\n \"merge-base\",\n \"HEAD\",\n `origin/${defaultBranch}`\n ], {\n cwd: toplevel,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n if (!mergeBase) return null;\n const names = (args) => execFileSync(\"git\", args, {\n cwd: toplevel,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().split(\"\\n\").filter((line) => line.length > 0);\n return [...names([\n \"diff\",\n \"--name-only\",\n mergeBase\n ]), ...names([\n \"ls-files\",\n \"--others\",\n \"--exclude-standard\"\n ])].some((name) => !allowed.includes(name));\n } catch {\n return null;\n }\n}\nfunction isPrimaryWorktree(cwd) {\n try {\n const gitDir = execFileSync(\"git\", [\"rev-parse\", \"--absolute-git-dir\"], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n const commonRaw = execFileSync(\"git\", [\"rev-parse\", \"--git-common-dir\"], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n if (!gitDir || !commonRaw) return false;\n const commonDir = resolve(cwd, commonRaw);\n return realpathSync(gitDir) === realpathSync(commonDir);\n } catch {\n return false;\n }\n}\n\n//#endregion\n//#region src/lib/git-short-options.ts\nconst VALUE_TAKING_LETTERS = {\n switch: /* @__PURE__ */ new Set([\"c\", \"C\"]),\n checkout: /* @__PURE__ */ new Set([\"b\", \"B\"]),\n branch: /* @__PURE__ */ new Set([\"u\"]),\n fetch: /* @__PURE__ */ new Set([\"o\", \"j\"])\n};\nfunction splitShortOptionCluster(token, sub) {\n if (!token.startsWith(\"-\") || token.startsWith(\"--\") || token.length <= 1) return;\n const valueLetters = VALUE_TAKING_LETTERS[sub];\n const letters = [];\n const chars = token.slice(1);\n for (let i = 0; i < chars.length; i++) {\n const ch = chars[i];\n letters.push(ch);\n if (valueLetters.has(ch)) return {\n letters,\n attachedValue: chars.slice(i + 1)\n };\n }\n return { letters };\n}\n\n//#endregion\n//#region src/lib/path-scope.ts\nfunction pathFlavorFor(base) {\n return /^[a-zA-Z]:[\\\\/]/.test(base) ? path.win32 : path.posix;\n}\nfunction resolveIn(base, target) {\n return pathFlavorFor(base).resolve(base, target);\n}\nfunction isWithin(dir, target) {\n const pp = pathFlavorFor(dir);\n const rel = pp.relative(dir, target);\n if (rel === \"\") return true;\n if (rel === \"..\" || rel.startsWith(\"..\" + pp.sep)) return false;\n return !pp.isAbsolute(rel);\n}\nfunction samePath(a, b) {\n return pathFlavorFor(a).relative(a, b) === \"\";\n}\nfunction targetsGitDir(filePath, cwd) {\n const pp = pathFlavorFor(cwd);\n const resolved = resolveIn(cwd, filePath);\n if (!isWithin(cwd, resolved)) return false;\n const rel = pp.relative(cwd, resolved);\n if (rel === \"\") return false;\n return rel.split(pp.sep).includes(\".git\");\n}\nfunction targetsNodeModules(filePath, cwd) {\n return resolveIn(cwd, filePath).split(/[/\\\\]/).includes(\"node_modules\");\n}\n\n//#endregion\n//#region src/rules.ts\nconst GIT_FLAGS_WITH_ARG = /* @__PURE__ */ new Set([\n \"-C\",\n \"-c\",\n \"--git-dir\",\n \"--work-tree\"\n]);\nfunction getGitSubcommand(tokens) {\n const args = tokens.slice(1);\n for (let i = 0; i < args.length; i++) {\n const t = args[i];\n if (GIT_FLAGS_WITH_ARG.has(t)) {\n i++;\n continue;\n }\n if (t.startsWith(\"-\")) continue;\n return t;\n }\n}\nconst WORKTREE_ADVICE = \"You're creating a feature branch in the primary worktree. An isolated worktree keeps this work independent of other windows, and with no commits on this branch yet, converting is cheap -- `git worktree add ../<dir> -b <branch>` (a sibling outside the repo, with its own dependency install). Claude Code keeps this session inside its own working tree, so the work continues in a new session opened in the sibling worktree. If you cannot open a session there, stay in the primary checkout on this branch and check `git branch --show-current` before each commit.\";\nfunction isGitBranchCreation(tokens) {\n const sub = getGitSubcommand(tokens);\n if (sub !== \"checkout\" && sub !== \"switch\") return false;\n const after = tokens.slice(tokens.indexOf(sub) + 1);\n const creationLetters = sub === \"checkout\" ? [\"b\", \"B\"] : [\"c\", \"C\"];\n return after.some((t) => {\n const cluster = splitShortOptionCluster(t, sub);\n return cluster !== void 0 && cluster.letters.some((l) => creationLetters.includes(l));\n });\n}\nfunction worktreeAdvice(tokens, ctx) {\n return isGitBranchCreation(tokens) && isPrimaryWorktree(ctx.cwd) ? WORKTREE_ADVICE : void 0;\n}\nconst GIT_FORCE_CREATE_LETTER = {\n switch: \"C\",\n checkout: \"B\"\n};\nconst GIT_FORCE_CREATE_LONG = {\n flag: \"--force-create\",\n shortest: \"--force-\"\n};\nfunction gitForceCreateTargets(after, letterSub) {\n const letter = GIT_FORCE_CREATE_LETTER[letterSub];\n const longFlag = GIT_FORCE_CREATE_LONG;\n const targets = [];\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (t === void 0) continue;\n if (letterSub === \"switch\") {\n const [flag, ...rest] = t.split(\"=\");\n if (flag !== void 0 && flag.length >= longFlag.shortest.length && longFlag.flag.startsWith(flag)) {\n const target = rest.length > 0 ? rest.join(\"=\") : after[i + 1];\n if (target !== void 0) targets.push(target);\n continue;\n }\n }\n const cluster = splitShortOptionCluster(t, letterSub);\n if (cluster === void 0 || !cluster.letters.includes(letter)) continue;\n if (cluster.attachedValue !== void 0 && cluster.attachedValue !== \"\") {\n targets.push(cluster.attachedValue);\n continue;\n }\n const next = after[i + 1];\n if (next !== void 0) targets.push(next);\n }\n return targets;\n}\nfunction gitCommandForceCreateTargets(tokens) {\n const sub = getGitSubcommand(tokens);\n if (sub === \"switch\" || sub === \"checkout\") return gitForceCreateTargets(tokens.slice(tokens.indexOf(sub) + 1), sub);\n if (sub === \"worktree\") {\n const worktreeIdx = tokens.indexOf(\"worktree\");\n if (tokens[worktreeIdx + 1] !== \"add\") return [];\n return gitForceCreateTargets(tokens.slice(worktreeIdx + 2), \"checkout\");\n }\n return [];\n}\nfunction isGitProtectedBranchForceCreate(tokens, ctx) {\n const targets = gitCommandForceCreateTargets(tokens);\n if (targets.length === 0) return false;\n const protectedSet = getProtectedBranches(ctx.cwd, ctx.repoProtectedBranches ?? []);\n return targets.some((t) => protectedSet.has(t));\n}\nfunction isGitProtectedBranchRefWrite(tokens, ctx) {\n const sub = getGitSubcommand(tokens);\n if (sub !== \"branch\") return false;\n const { flags, positionals } = splitGitBranchArgs(tokens.slice(tokens.indexOf(sub) + 1));\n if (positionals.length === 0) return false;\n let deleteMode = false;\n let renameMode = false;\n let copyMode = false;\n let forceMode = false;\n for (const flag of flags) {\n if (flag.letters !== void 0) {\n if (flag.letters.includes(\"d\") || flag.letters.includes(\"D\")) deleteMode = true;\n if (flag.letters.includes(\"m\") || flag.letters.includes(\"M\")) renameMode = true;\n if (flag.letters.includes(\"c\") || flag.letters.includes(\"C\")) copyMode = true;\n if (flag.letters.includes(\"f\") || flag.letters.includes(\"M\") || flag.letters.includes(\"C\")) forceMode = true;\n continue;\n }\n if (flag.name === \"delete\") deleteMode = true;\n if (flag.name === \"move\") renameMode = true;\n if (flag.name === \"copy\") copyMode = true;\n if (flag.name === \"force\") forceMode = true;\n }\n const protectedSet = getProtectedBranches(ctx.cwd, ctx.repoProtectedBranches ?? []);\n if (deleteMode && positionals.some((p) => protectedSet.has(p))) return true;\n if (renameMode && positionals.length >= 2 && protectedSet.has(positionals[0])) return true;\n if (forceMode) {\n const destination = renameMode || copyMode ? positionals[positionals.length - 1] : positionals[0];\n if (destination !== void 0 && protectedSet.has(destination)) return true;\n }\n return false;\n}\nfunction refspecDestination(refspec) {\n const spec = refspec.startsWith(\"+\") ? refspec.slice(1) : refspec;\n const colon = spec.lastIndexOf(\":\");\n return (colon === -1 ? spec : spec.slice(colon + 1)).replace(/^refs\\/heads\\//, \"\");\n}\nconst GIT_BRANCH_VALUE_FLAG_NAMES = /* @__PURE__ */ new Set([\n \"contains\",\n \"no-contains\",\n \"merged\",\n \"no-merged\",\n \"points-at\",\n \"sort\",\n \"format\",\n \"set-upstream-to\"\n]);\nfunction splitGitBranchArgs(after) {\n const flags = [];\n const positionals = [];\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (t === void 0) continue;\n if (!t.startsWith(\"-\")) {\n positionals.push(t);\n continue;\n }\n if (t.startsWith(\"--\") && t !== \"--\") {\n const eq = t.indexOf(\"=\");\n const name = eq > 0 ? t.slice(2, eq) : t.slice(2);\n flags.push({\n raw: t,\n name\n });\n if (eq < 0 && GIT_BRANCH_VALUE_FLAG_NAMES.has(name)) i++;\n continue;\n }\n const cluster = splitShortOptionCluster(t, \"branch\");\n if (cluster === void 0) {\n flags.push({ raw: t });\n continue;\n }\n flags.push({\n raw: t,\n letters: cluster.letters\n });\n if (cluster.attachedValue === \"\") i++;\n }\n return {\n flags,\n positionals\n };\n}\nconst GIT_FETCH_VALUE_FLAG_NAMES = /* @__PURE__ */ new Set([\n \"depth\",\n \"deepen\",\n \"shallow-since\",\n \"shallow-exclude\",\n \"negotiation-tip\",\n \"filter\",\n \"jobs\",\n \"server-option\",\n \"upload-pack\",\n \"refmap\",\n \"submodule-prefix\",\n \"recurse-submodules-default\"\n]);\nfunction splitGitFetchArgs(after) {\n const flags = [];\n const positionals = [];\n const refmaps = [];\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (t === void 0) continue;\n if (!t.startsWith(\"-\")) {\n positionals.push(t);\n continue;\n }\n if (t === \"--\") {\n flags.push({ raw: t });\n continue;\n }\n if (t.startsWith(\"--\")) {\n const eq = t.indexOf(\"=\");\n const name = eq > 0 ? t.slice(2, eq) : t.slice(2);\n flags.push({\n raw: t,\n name\n });\n if (name === \"refmap\") {\n if (eq > 0) refmaps.push(t.slice(eq + 1));\n else if (after[i + 1] !== void 0) refmaps.push(after[i + 1]);\n }\n if (eq < 0 && GIT_FETCH_VALUE_FLAG_NAMES.has(name)) i++;\n continue;\n }\n const cluster = splitShortOptionCluster(t, \"fetch\");\n if (cluster === void 0) {\n flags.push({ raw: t });\n continue;\n }\n flags.push({\n raw: t,\n letters: cluster.letters\n });\n if (cluster.attachedValue === \"\") i++;\n }\n return {\n flags,\n positionals,\n refmaps\n };\n}\nfunction fetchRefspecTarget(spec) {\n const body = spec.startsWith(\"+\") ? spec.slice(1) : spec;\n if (body.startsWith(\"^\")) return { kind: \"none\" };\n if (!body.includes(\":\")) return { kind: \"none\" };\n const destination = refspecDestination(body);\n if (destination === \"\") return { kind: \"none\" };\n if (destination.startsWith(\"refs/remotes/\")) return { kind: \"tracking\" };\n if (destination.startsWith(\"refs/\")) return { kind: \"other\" };\n return {\n kind: \"branch\",\n name: destination\n };\n}\nfunction globToAnchoredRegex(glob) {\n const escaped = glob.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`^${escaped.replace(/\\\\\\*/g, \".*\")}$`);\n}\nfunction isProtectedFetchBranch(name, protectedSet) {\n if (protectedSet.has(name)) return true;\n if (!name.includes(\"*\")) return false;\n const pattern = globToAnchoredRegex(name);\n for (const member of protectedSet) if (pattern.test(member)) return true;\n return false;\n}\nfunction isGitProtectedBranchFetchWrite(tokens, ctx) {\n const sub = getGitSubcommand(tokens);\n if (sub !== \"fetch\") return false;\n const { positionals, refmaps } = splitGitFetchArgs(tokens.slice(tokens.indexOf(sub) + 1));\n const protectedSet = getProtectedBranches(ctx.cwd, ctx.repoProtectedBranches ?? []);\n return [...positionals, ...refmaps].some((spec) => {\n const target = fetchRefspecTarget(spec);\n if (target.kind !== \"branch\" || target.name === void 0) return false;\n return isProtectedFetchBranch(target.name, protectedSet);\n });\n}\nfunction isGitProtectedUpdateRef(tokens, ctx) {\n const after = tokens.slice(tokens.indexOf(\"update-ref\") + 1);\n let ref;\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (t === \"-m\") {\n i++;\n continue;\n }\n if (t.startsWith(\"-\")) continue;\n ref = t;\n break;\n }\n if (ref === void 0) return false;\n return getProtectedBranches(ctx.cwd, ctx.repoProtectedBranches ?? []).has(ref.replace(/^refs\\/heads\\//, \"\"));\n}\nfunction gitEffectiveCwd(tokens, cwd) {\n let dir = cwd;\n const args = tokens.slice(1);\n for (let i = 0; i < args.length; i++) {\n const t = args[i];\n if (t === \"-C\") {\n const next = args[i + 1];\n if (next !== void 0) dir = path.resolve(dir, next);\n i++;\n continue;\n }\n if (GIT_FLAGS_WITH_ARG.has(t)) {\n i++;\n continue;\n }\n if (!t.startsWith(\"-\")) break;\n }\n return dir;\n}\nconst GIT_SWITCH_NEUTRAL_FLAGS = /* @__PURE__ */ new Set([\n \"-q\",\n \"--quiet\",\n \"-f\",\n \"--force\",\n \"--discard-changes\",\n \"-m\",\n \"--merge\",\n \"--no-track\",\n \"--progress\",\n \"--no-progress\",\n \"--guess\",\n \"--no-guess\",\n \"--ignore-other-worktrees\",\n \"--recurse-submodules\",\n \"--no-recurse-submodules\"\n]);\nconst GIT_SWITCH_CREATE_FLAGS = /* @__PURE__ */ new Set([\n \"--create\",\n \"--force-create\",\n \"--orphan\"\n]);\nconst GIT_CHECKOUT_PATH_FLAGS = /* @__PURE__ */ new Set([\n \"--ours\",\n \"--theirs\",\n \"-p\",\n \"--patch\",\n \"--conflict\",\n \"--pathspec-from-file\",\n \"--pathspec-file-nul\",\n \"--overlay\",\n \"--no-overlay\"\n]);\nconst GIT_SWITCH_NEUTRAL_LETTERS = /* @__PURE__ */ new Set([\n \"q\",\n \"f\",\n \"m\"\n]);\nfunction switchTarget(after, sub, isCheckoutBranch) {\n if (sub === \"checkout\" && after.includes(\"--\")) return void 0;\n const createLetters = sub === \"checkout\" ? [\"b\", \"B\"] : [\"c\", \"C\"];\n const known = (l) => GIT_SWITCH_NEUTRAL_LETTERS.has(l) || createLetters.includes(l);\n const positionals = [];\n let created;\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (!t.startsWith(\"-\")) {\n positionals.push(t);\n continue;\n }\n if (GIT_SWITCH_NEUTRAL_FLAGS.has(t)) continue;\n const eq = t.indexOf(\"=\");\n if (sub === \"checkout\" && GIT_CHECKOUT_PATH_FLAGS.has(eq === -1 ? t : t.slice(0, eq))) return;\n if (GIT_SWITCH_CREATE_FLAGS.has(eq === -1 ? t : t.slice(0, eq))) {\n created = eq === -1 ? after[++i] : t.slice(eq + 1);\n continue;\n }\n const cluster = splitShortOptionCluster(t, sub);\n if (cluster === void 0 || !cluster.letters.every(known)) return null;\n if (cluster.letters.some((l) => createLetters.includes(l))) created = cluster.attachedValue ? cluster.attachedValue : after[++i];\n }\n if (created !== void 0) return created;\n if (positionals.length !== 1) return void 0;\n const target = positionals[0];\n if (target === \"HEAD\" || target === \"@\") return void 0;\n if (sub === \"checkout\" && !isCheckoutBranch(target)) return void 0;\n return target;\n}\nfunction branchSwitch(tokens, ctx, resolved) {\n const sub = getGitSubcommand(tokens);\n if (sub !== \"switch\" && sub !== \"checkout\") return void 0;\n const dir = gitEffectiveCwd(tokens, ctx.cwd);\n const isCheckoutBranch = (name) => !resolved || getProtectedBranches(dir, ctx.repoProtectedBranches ?? []).has(name) || resolveCommit(dir, name) !== null;\n const target = switchTarget(tokens.slice(tokens.indexOf(sub) + 1), sub, isCheckoutBranch);\n if (!resolved) return target === void 0 ? void 0 : {\n dir,\n branch: null\n };\n return target === void 0 ? void 0 : {\n dir,\n branch: target\n };\n}\nconst GIT_CHECKED_OUT_WRITES = /* @__PURE__ */ new Set([\n \"commit\",\n \"merge\",\n \"rebase\",\n \"cherry-pick\",\n \"revert\",\n \"am\",\n \"pull\"\n]);\nfunction subcommandArgs(tokens, sub, valueFlags = /* @__PURE__ */ new Set()) {\n const after = tokens.slice(tokens.indexOf(sub) + 1);\n const flags = [];\n const positionals = [];\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (!t.startsWith(\"-\")) {\n positionals.push(t);\n continue;\n }\n flags.push(t);\n if (valueFlags.has(t)) i++;\n }\n return {\n flags,\n positionals\n };\n}\nconst GIT_PUSH_VALUE_FLAGS = /* @__PURE__ */ new Set([\n \"-o\",\n \"--push-option\",\n \"--repo\",\n \"--receive-pack\",\n \"--exec\"\n]);\nfunction isMergeFastForwardFromUpstream(tokens, upstream) {\n const { flags, positionals } = subcommandArgs(tokens, \"merge\");\n if (!flags.includes(\"--ff-only\") || positionals.length !== 1) return false;\n const ref = positionals[0];\n return ref === \"@{u}\" || ref === \"@{upstream}\" || upstream !== null && ref === upstream;\n}\nconst GIT_PULL_NO_REBASE = /* @__PURE__ */ new Set([\n \"--rebase=false\",\n \"--rebase=no\",\n \"--rebase=off\",\n \"--rebase=0\"\n]);\nfunction isPullFromUpstream(tokens, upstream) {\n const { flags, positionals } = subcommandArgs(tokens, \"pull\");\n if (flags.some((t) => t.startsWith(\"--rebase\") && !GIT_PULL_NO_REBASE.has(t) || t === \"--no-ff\" || !t.startsWith(\"--\") && t.slice(1).includes(\"r\"))) return false;\n if (positionals.length === 0) return true;\n if (positionals.length !== 2 || upstream === null) return false;\n const [remote, branch] = positionals;\n return `${remote}/${branch.replace(/^refs\\/heads\\//, \"\")}` === upstream;\n}\nfunction isRefMovingReset(tokens, cwd, head) {\n if (tokens.slice(tokens.indexOf(\"reset\") + 1).includes(\"--\")) return false;\n const { positionals } = subcommandArgs(tokens, \"reset\");\n if (positionals.length !== 1) return false;\n if (head !== \"HEAD\" && /^(HEAD|@)/.test(positionals[0])) return false;\n const target = resolveCommit(cwd, positionals[0]);\n if (target === null) return false;\n return target !== resolveCommit(cwd, head);\n}\nfunction pushDestinations(tokens, current) {\n const { positionals } = subcommandArgs(tokens, \"push\", GIT_PUSH_VALUE_FLAGS);\n const refspecs = positionals.slice(1);\n if (refspecs.length === 0) return null;\n const names = [];\n for (const spec of refspecs) {\n const dst = refspecDestination(spec);\n if (dst === \"HEAD\" || dst === \"@\") {\n if (current !== null) names.push(current);\n continue;\n }\n names.push(dst);\n }\n return names;\n}\nconst GIT_PUSH_EVERY_BRANCH = /* @__PURE__ */ new Set([\n \"--all\",\n \"--branches\",\n \"--mirror\"\n]);\nfunction leavesRefInPlace(tokens, sub) {\n const { flags } = subcommandArgs(tokens, sub);\n if (flags.includes(\"--abort\") || flags.includes(\"--quit\")) return true;\n return sub === \"commit\" && flags.includes(\"--dry-run\");\n}\nfunction movesProtectedRef(tokens, ctx) {\n const sub = getGitSubcommand(tokens);\n if (sub === void 0) return false;\n if (sub === \"switch\" || sub === \"checkout\" || sub === \"worktree\") return isGitProtectedBranchForceCreate(tokens, ctx);\n if (sub === \"branch\") return isGitProtectedBranchRefWrite(tokens, ctx);\n if (sub === \"fetch\") return isGitProtectedBranchFetchWrite(tokens, ctx);\n if (sub === \"update-ref\") return isGitProtectedUpdateRef(tokens, ctx);\n if (sub !== \"push\" && sub !== \"reset\" && !GIT_CHECKED_OUT_WRITES.has(sub)) return false;\n const cwd = gitEffectiveCwd(tokens, ctx.cwd);\n const pending = ctx.pendingBranches?.[cwd];\n const current = pending ? pending.branch : getCurrentBranch(cwd);\n const protectedSet = getProtectedBranches(cwd, ctx.repoProtectedBranches ?? []);\n const onProtected = current !== null && protectedSet.has(current);\n if (sub === \"push\") {\n const { flags } = subcommandArgs(tokens, \"push\", GIT_PUSH_VALUE_FLAGS);\n if (flags.some((f) => GIT_PUSH_EVERY_BRANCH.has(f))) return true;\n const destinations = pushDestinations(tokens, current);\n if (destinations === null) {\n if (flags.includes(\"--tags\")) return false;\n return onProtected;\n }\n return destinations.some((d) => protectedSet.has(d));\n }\n if (!onProtected) return false;\n if (leavesRefInPlace(tokens, sub)) return false;\n if (sub === \"reset\") return isRefMovingReset(tokens, cwd, pending ? current : \"HEAD\");\n if (sub === \"merge\" || sub === \"pull\") {\n const upstream = getUpstream(cwd, current);\n if (sub === \"merge\" && isMergeFastForwardFromUpstream(tokens, upstream)) return false;\n if (sub === \"pull\" && isPullFromUpstream(tokens, upstream)) return false;\n }\n return true;\n}\nconst PNPM_BUILTINS = /* @__PURE__ */ new Set([\n \"install\",\n \"i\",\n \"add\",\n \"remove\",\n \"rm\",\n \"uninstall\",\n \"un\",\n \"update\",\n \"up\",\n \"upgrade\",\n \"list\",\n \"ls\",\n \"ll\",\n \"la\",\n \"why\",\n \"view\",\n \"info\",\n \"show\",\n \"outdated\",\n \"audit\",\n \"licenses\",\n \"init\",\n \"create\",\n \"link\",\n \"unlink\",\n \"pack\",\n \"publish\",\n \"config\",\n \"set\",\n \"get\",\n \"store\",\n \"cache\",\n \"rebuild\",\n \"rb\",\n \"prune\",\n \"dedupe\",\n \"dlx\",\n \"exec\",\n \"run\",\n \"patch\",\n \"patch-commit\",\n \"recursive\",\n \"-r\"\n]);\nconst NPM_READ_OPS = /* @__PURE__ */ new Set([\n \"view\",\n \"info\",\n \"show\"\n]);\nfunction isNpmReadOp(tokens) {\n const sub = tokens[1];\n return sub !== void 0 && NPM_READ_OPS.has(sub);\n}\nfunction getNpmRedirectReason(tokens) {\n const sub = tokens[1];\n const BASE = \"This project uses pnpm.\";\n if (!sub) return `${BASE} Use \\`pnpm\\` instead of npm.`;\n if (sub === \"install\" || sub === \"i\" || sub === \"ci\") {\n if (tokens.slice(2).some((t) => !t.startsWith(\"-\"))) return `${BASE} Use \\`pnpm add <pkg>\\` instead of \\`npm install <pkg>\\`.`;\n return `${BASE} Use \\`pnpm install\\` instead of npm.`;\n }\n if (sub === \"add\") return `${BASE} Use \\`pnpm add <pkg>\\` instead of npm.`;\n if (sub === \"uninstall\" || sub === \"remove\" || sub === \"rm\" || sub === \"un\" || sub === \"r\") return `${BASE} Use \\`pnpm remove <pkg>\\` instead of npm.`;\n if (sub === \"run\" || sub === \"run-script\") return `${BASE} Use \\`pnpm run <script>\\` or \\`pnpm <script>\\` instead of npm.`;\n if (sub === \"test\" || sub === \"t\" || sub === \"tst\") return `${BASE} Use \\`pnpm test\\` instead of npm.`;\n if (sub === \"start\") return `${BASE} Use \\`pnpm start\\` instead of npm.`;\n if (sub === \"stop\") return `${BASE} Use \\`pnpm stop\\` instead of npm.`;\n if (sub === \"restart\") return `${BASE} Use \\`pnpm restart\\` instead of npm.`;\n if (sub === \"exec\") return `${BASE} Use \\`pnpm exec <cmd>\\` instead of npm.`;\n if (sub === \"list\" || sub === \"ls\" || sub === \"ll\" || sub === \"la\") return `${BASE} Use \\`pnpm list\\` instead of npm.`;\n if (sub === \"why\") return `${BASE} Use \\`pnpm why\\` instead of npm.`;\n if (sub === \"outdated\") return `${BASE} Use \\`pnpm outdated\\` instead of npm.`;\n if (sub === \"audit\") return `${BASE} Use \\`pnpm audit\\` instead of npm.`;\n if (sub === \"update\" || sub === \"up\" || sub === \"upgrade\") return `${BASE} Use \\`pnpm update\\` instead of npm.`;\n if (sub === \"init\") return `${BASE} Use \\`pnpm init\\` instead of npm.`;\n if (sub === \"publish\") return `${BASE} Use \\`pnpm publish\\` instead of npm.`;\n if (sub === \"link\") return `${BASE} Use \\`pnpm link\\` instead of npm.`;\n if (sub === \"unlink\") return `${BASE} Use \\`pnpm unlink\\` instead of npm.`;\n if (sub === \"pack\") return `${BASE} Use \\`pnpm pack\\` instead of npm.`;\n if (sub === \"cache\") return `${BASE} Use \\`pnpm store\\` instead of \\`npm cache\\`.`;\n if (sub === \"config\" || sub === \"set\" || sub === \"get\") return `${BASE} Use \\`pnpm config\\` instead of npm.`;\n return `${BASE} Use the equivalent pnpm command instead of npm.`;\n}\nconst LAST_POSITIONAL_DEST = /* @__PURE__ */ new Set([\n \"cp\",\n \"mv\",\n \"rsync\",\n \"install\",\n \"ln\"\n]);\nconst ALL_POSITIONAL_DEST = /* @__PURE__ */ new Set([\"tee\", \"truncate\"]);\nfunction explicitTargetDirectory(rest) {\n for (const [i, t] of rest.entries()) {\n if (t === \"-t\" || t === \"--target-directory\") return rest[i + 1] ?? null;\n if (t.startsWith(\"--target-directory=\")) return t.slice(19);\n }\n return null;\n}\nconst OUTPUT_REDIRECT = /^(?:\\d*|&)>{1,2}$/;\nconst OUTPUT_REDIRECT_ATTACHED = /^(?:\\d*|&)>{1,2}(.+)$/;\nconst INPUT_REDIRECT = /^\\d*<$/;\nconst INPUT_REDIRECT_ATTACHED = /^\\d*<([^<].*)$/;\nfunction spacedRedirectDirection(token) {\n if (OUTPUT_REDIRECT.test(token)) return \"out\";\n if (INPUT_REDIRECT.test(token)) return \"in\";\n return null;\n}\nfunction splitRedirects(tokens) {\n const redirects = [];\n const rest = [];\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i];\n const spaced = spacedRedirectDirection(t);\n if (spaced !== null) {\n const next = tokens[i + 1];\n if (next !== void 0) redirects.push({\n direction: spaced,\n target: next\n });\n i++;\n continue;\n }\n const out = OUTPUT_REDIRECT_ATTACHED.exec(t);\n if (out) {\n redirects.push({\n direction: \"out\",\n target: out[1]\n });\n continue;\n }\n const input = INPUT_REDIRECT_ATTACHED.exec(t);\n if (input) {\n redirects.push({\n direction: \"in\",\n target: input[1]\n });\n continue;\n }\n rest.push(t);\n }\n return {\n redirects,\n rest\n };\n}\nfunction redirectTargets(tokens, direction) {\n return splitRedirects(tokens).redirects.filter((r) => r.direction === direction).map((r) => r.target);\n}\nfunction writeDestinations(tokens) {\n const cmd = path.basename(tokens[0] ?? \"\");\n const rest = tokens.slice(1);\n const dests = redirectTargets(tokens, \"out\");\n if (cmd === \"dd\") dests.push(...rest.filter((t) => t.startsWith(\"of=\")).map((t) => t.slice(3)));\n else if (cmd === \"sed\") {\n if (rest.some((t) => t === \"--in-place\" || /^-[a-zA-Z]*i/.test(t))) dests.push(...rest.filter((t) => !t.startsWith(\"-\")));\n } else if (ALL_POSITIONAL_DEST.has(cmd)) dests.push(...rest.filter((t) => !t.startsWith(\"-\")));\n else if (LAST_POSITIONAL_DEST.has(cmd)) {\n if (cmd === \"cp\" && rest.includes(\"--remove-destination\")) return dests;\n const targetDir = explicitTargetDirectory(rest);\n if (targetDir !== null) dests.push(targetDir);\n else {\n const last = rest.findLast((t) => !t.startsWith(\"-\"));\n if (last !== void 0) dests.push(last);\n }\n }\n return dests;\n}\nfunction writesIntoNodeModules(tokens, ctx) {\n return writeDestinations(tokens).some((d) => targetsNodeModules(d, ctx.cwd));\n}\nconst NODE_MODULES_WRITE_REASON = \"Don't write into node_modules/. Its files are hardlinks into pnpm's global store, so overwriting one in place (plain `cp`, `>` redirect, `sed -i`, ...) writes through the link and corrupts that package for every project on this machine -- silently, since the directory you wrote into ends up fine. To test a local build as an installed dependency, run it directly (`node packages/<pkg>/dist/bin.mjs <cmd>`), or install into a scratch tree with an isolated store (`pnpm add --store-dir <scratch> <pkg>`). If you must replace a file in place, `cp --remove-destination` is safe -- it unlinks the target first. Run `pnpm store status` to check whether the store is already damaged.\";\nfunction isChmod777(tokens) {\n return tokens.some((t) => t === \"777\" || t === \"0777\");\n}\nfunction isGitForcePush(tokens) {\n const pushIdx = tokens.indexOf(\"push\");\n if (pushIdx === -1) return false;\n return tokens.slice(pushIdx + 1).some((t) => t === \"--force\" || t === \"-f\");\n}\nconst ENV_READ_FILE_COMMANDS = /* @__PURE__ */ new Set([\n \"cat\",\n \"head\",\n \"tail\",\n \"less\",\n \"more\",\n \"source\",\n \".\"\n]);\nconst GREP_FAMILY_COMMANDS = /* @__PURE__ */ new Set([\n \"grep\",\n \"rg\",\n \"ag\"\n]);\nfunction grepFileOperands(rest) {\n const files = [];\n let patternAccountedFor = false;\n let optionsEnded = false;\n for (let i = 0; i < rest.length; i++) {\n const t = rest[i];\n if (!optionsEnded && t === \"--\") {\n optionsEnded = true;\n continue;\n }\n if (!optionsEnded) {\n if (t === \"-f\" || t === \"--file\") {\n const value = rest[i + 1];\n if (value !== void 0) {\n files.push(value);\n i++;\n }\n patternAccountedFor = true;\n continue;\n }\n if (t.startsWith(\"--file=\")) {\n files.push(t.slice(7));\n patternAccountedFor = true;\n continue;\n }\n if (t.startsWith(\"-f\") && t !== \"-f\" && !t.startsWith(\"--\")) {\n files.push(t.slice(2));\n patternAccountedFor = true;\n continue;\n }\n if (t === \"-e\" || t === \"--regexp\") {\n i++;\n patternAccountedFor = true;\n continue;\n }\n if (t.startsWith(\"--regexp=\") || t.startsWith(\"-e\") && t !== \"-e\" && !t.startsWith(\"--\")) {\n patternAccountedFor = true;\n continue;\n }\n if (t.startsWith(\"-\")) continue;\n }\n if (!patternAccountedFor) {\n patternAccountedFor = true;\n continue;\n }\n files.push(t);\n }\n return files;\n}\nfunction envFileOperands(tokens) {\n const cmd = path.basename(tokens[0] ?? \"\");\n const { redirects, rest } = splitRedirects(tokens.slice(1));\n const operands = redirects.filter((r) => r.direction === \"in\").map((r) => r.target);\n if (GREP_FAMILY_COMMANDS.has(cmd)) operands.push(...grepFileOperands(rest));\n else if (ENV_READ_FILE_COMMANDS.has(cmd)) operands.push(...rest.filter((t) => !t.startsWith(\"-\")));\n return operands;\n}\nconst HEALTH_CEILING_FILES = [\"health-baseline.json\", \".tooling.json\"];\nconst HEALTH_RAISE_REASON = \"Run `pnpm exec bst health:raise` to raise only what this branch crossed. `--update-baseline --reset` records every outlier, including the ones already on the default branch.\";\nfunction isHealthBaselineReset(tokens) {\n return tokens.includes(\"health:check\") && tokens.includes(\"--update-baseline\") && tokens.includes(\"--reset\");\n}\nfunction raiseTravelsWithCode(cwd) {\n return branchCarriesOtherFiles(cwd, HEALTH_CEILING_FILES) === true;\n}\nconst denyRules = [\n {\n name: \"sudo\",\n match: /^sudo$/,\n action: \"deny\",\n reason: \"Don't use sudo. If you need elevated permissions, ask me to do it manually.\"\n },\n {\n name: \"git-force-push\",\n match: /^git$/,\n action: \"deny\",\n when: (tokens) => isGitForcePush(tokens),\n reason: \"Use `git push --force-with-lease` instead of `--force`.\"\n },\n {\n name: \"git-protected-branch-write\",\n match: /^git$/,\n action: \"deny\",\n when: (tokens, ctx) => movesProtectedRef(tokens, ctx),\n reason: \"This would move a protected branch (main, master, the remote's default branch, or one listed in .claude/hooks/bst-hook.settings.json#protectedBranches). Work on a feature branch in a worktree: `git worktree add ../<repo>-<topic> -b feat/<topic>`, then commit and push there. To bring `main` up to date, use `git pull --ff-only`.\"\n },\n {\n name: \"chmod-777\",\n match: /^chmod$/,\n action: \"deny\",\n when: (tokens) => isChmod777(tokens),\n reason: \"Don't use 777 permissions. Use more restrictive permissions.\"\n },\n {\n name: \"node-modules-write\",\n match: /./,\n action: \"deny\",\n when: (tokens, ctx) => writesIntoNodeModules(tokens, ctx),\n reason: NODE_MODULES_WRITE_REASON\n },\n {\n name: \"env-file-read\",\n match: /./,\n action: \"deny\",\n when: (tokens) => envFileOperands(tokens).some(isEnvFile),\n reason: \"Don't read .env files. These contain secrets that should not appear in the conversation.\"\n },\n {\n name: \"env-file-write\",\n match: /./,\n action: \"deny\",\n when: (tokens) => redirectTargets(tokens, \"out\").some(isEnvFile),\n reason: \"Don't write to .env files. These contain secrets.\"\n },\n {\n name: \"health-baseline-reset\",\n match: /^bst$/,\n action: \"deny\",\n when: (tokens, ctx) => isHealthBaselineReset(tokens) && raiseTravelsWithCode(ctx.cwd),\n reason: HEALTH_RAISE_REASON\n },\n {\n name: \"npx-redirect\",\n match: /^npx$/,\n action: \"deny\",\n reason: \"This project uses pnpm. Use `pnpm dlx <pkg>` or `pnpm exec <cmd>` instead of npx.\"\n },\n {\n name: \"mise-self-update\",\n match: /^mise$/,\n action: \"deny\",\n when: (tokens) => tokens[1] === \"self-update\",\n reason: \"Don't self-update mise. The version is Renovate-managed; ask a human to bump the pin.\"\n }\n];\n\n//#endregion\n//#region src/lib/script-resolver.ts\nconst PackageJsonSchema = object({ scripts: record(string(), unknown()) });\nfunction resolveScript(scriptName, cwd) {\n const scripts = readScripts(cwd);\n if (!scripts) return null;\n const main = scripts[scriptName];\n if (typeof main !== \"string\") return null;\n const pre = scripts[`pre${scriptName}`];\n const post = scripts[`post${scriptName}`];\n return {\n pre: typeof pre === \"string\" ? pre : null,\n main,\n post: typeof post === \"string\" ? post : null\n };\n}\nfunction resolveFilteredScript(scriptName, filterPkg, cwd) {\n const pkgDir = findWorkspacePackageDir(filterPkg, cwd);\n if (!pkgDir) return null;\n const script = resolveScript(scriptName, pkgDir);\n if (!script) return null;\n return {\n ...script,\n pkgDir\n };\n}\nfunction resolveRecursiveScripts(scriptName, rootDir) {\n const pkgDirs = listWorkspacePackageDirs(rootDir);\n if (!pkgDirs) return null;\n const results = [];\n for (const pkgDir of pkgDirs) {\n const resolved = resolveScript(scriptName, pkgDir);\n if (resolved) results.push({\n ...resolved,\n pkgDir\n });\n }\n return results;\n}\nfunction listWorkspacePackageDirs(rootDir) {\n const patterns = readWorkspacePatterns(rootDir);\n if (!patterns) return null;\n const dirs = [];\n for (const pattern of patterns) {\n if (!pattern.endsWith(\"/*\")) continue;\n const baseDir = pattern.slice(0, -2);\n const parentDir = resolve(rootDir, baseDir);\n let entries;\n try {\n entries = readdirSync(parentDir);\n } catch {\n continue;\n }\n for (const entry of entries) {\n const entryDir = join(parentDir, entry);\n try {\n if (!statSync(entryDir).isDirectory()) continue;\n } catch {\n continue;\n }\n dirs.push(entryDir);\n }\n }\n return dirs.length > 0 ? dirs : null;\n}\nfunction findWorkspacePackageDir(pkgName, rootDir) {\n const pkgDirs = listWorkspacePackageDirs(rootDir);\n if (!pkgDirs) return null;\n for (const entryDir of pkgDirs) {\n const name = readPackageName(entryDir);\n if (name === pkgName || name === `@${pkgName}`) return entryDir;\n if (entryDir.split(\"/\").pop() === pkgName) return entryDir;\n if (name) {\n if ((name.startsWith(\"@\") ? name.split(\"/\")[1] : name) === pkgName) return entryDir;\n }\n }\n return null;\n}\nfunction readWorkspacePatterns(rootDir) {\n try {\n const lines = readFileSync(join(rootDir, \"pnpm-workspace.yaml\"), \"utf-8\").split(\"\\n\");\n const packagesIdx = lines.findIndex((l) => /^packages\\s*:/.test(l));\n if (packagesIdx === -1) return null;\n const patterns = [];\n for (let i = packagesIdx + 1; i < lines.length; i++) {\n const line = lines[i];\n const match = /^\\s+-\\s+(.+)$/.exec(line);\n if (!match) break;\n patterns.push(match[1].trim().replace(/['\"`]/g, \"\"));\n }\n return patterns.length > 0 ? patterns : null;\n } catch {\n return null;\n }\n}\nconst PackageNameSchema = object({ name: string() });\nfunction readPackageName(dir) {\n try {\n const raw = readFileSync(join(dir, \"package.json\"), \"utf-8\");\n const result = PackageNameSchema.safeParse(JSON.parse(raw));\n if (!result.success) return null;\n return result.data.name;\n } catch {\n return null;\n }\n}\nfunction readScripts(cwd) {\n try {\n const raw = readFileSync(join(cwd, \"package.json\"), \"utf-8\");\n const result = PackageJsonSchema.safeParse(JSON.parse(raw));\n if (!result.success) return null;\n return result.data.scripts;\n } catch {\n return null;\n }\n}\n\n//#endregion\n//#region src/lib/workspace-root.ts\nfunction findWorkspaceRoot(cwd) {\n let dir = resolve(cwd);\n while (true) {\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return dir;\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n//#endregion\n//#region src/evaluate.ts\nconst MAX_EVAL_DEPTH = 5;\nfunction subshellBody(command) {\n if (!command.startsWith(\"(\") || !command.endsWith(\")\")) return null;\n let depth = 0;\n let quote = null;\n for (let i = 0; i < command.length; i++) {\n const ch = command[i];\n if (quote !== null) {\n if (ch === quote) quote = null;\n else if (ch === \"\\\\\" && quote === \"\\\"\") i++;\n continue;\n }\n if (ch === \"\\\\\") i++;\n else if (ch === \"'\" || ch === \"\\\"\") quote = ch;\n else if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n if (depth === 0) return i === command.length - 1 ? command.slice(1, -1) : null;\n }\n }\n return null;\n}\nfunction extractCdDir(segment, ctx) {\n const tokenResult = tokenize(segment);\n if (!tokenResult.ok || tokenResult.tokens.length !== 2) return null;\n const tokens = tokenResult.tokens;\n if (tokens[0] !== \"cd\") return null;\n const dir = tokens[1];\n if (path.isAbsolute(dir)) return dir;\n return path.resolve(ctx.cwd, dir);\n}\nfunction extractBranchSwitch(segment, ctx) {\n const tokenResult = tokenize(segment);\n if (!tokenResult.ok) return void 0;\n let tokens = tokenResult.tokens;\n let envSkipped = 0;\n while (envSkipped < tokens.length && /^\\w+=/.test(tokens[envSkipped])) envSkipped++;\n tokens = tokens.slice(envSkipped);\n if (tokens.length === 0 || path.basename(tokens[0]) !== \"git\") return void 0;\n return branchSwitch(tokens, ctx, checkInjection(tokens, segment).safe);\n}\nfunction evaluateCommand(command, ctx) {\n if (ctx.depth >= MAX_EVAL_DEPTH) return {\n action: \"none\",\n rule: null,\n reason: \"max evaluation depth exceeded\"\n };\n const trimmed = command.trim();\n if (!trimmed) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n const body = subshellBody(trimmed);\n if (body !== null) return evaluateCommand(body, {\n ...ctx,\n depth: ctx.depth + 1\n });\n const segments = splitCommand(trimmed);\n if (segments.length === 0) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n let firstNone = null;\n const currentCtx = { ...ctx };\n let unknownAfterNext;\n for (const segment of segments) {\n if (segment.operator === \"&&\") {\n const cdDir = extractCdDir(segment.command, currentCtx);\n if (cdDir) currentCtx.cwd = cdDir;\n }\n const result = evaluateSegment(segment.command, currentCtx);\n if (result.action === \"deny\") return result;\n if (!firstNone) firstNone = result;\n if (unknownAfterNext) {\n currentCtx.pendingBranches = {\n ...currentCtx.pendingBranches,\n [unknownAfterNext.dir]: unknownAfterNext\n };\n unknownAfterNext = void 0;\n }\n const switched = extractBranchSwitch(segment.command, currentCtx);\n if (switched) {\n const unknown = {\n dir: switched.dir,\n branch: null\n };\n if (segment.operator === \"&&\") currentCtx.pendingBranches = {\n ...currentCtx.pendingBranches,\n [switched.dir]: switched\n };\n else if (segment.operator === \"||\") unknownAfterNext = unknown;\n else currentCtx.pendingBranches = {\n ...currentCtx.pendingBranches,\n [switched.dir]: unknown\n };\n }\n }\n return firstNone ?? {\n action: \"none\",\n rule: null,\n reason: null\n };\n}\nfunction evaluateResolvedScript(resolved, ctx) {\n if (resolved.pre) {\n const preResult = evaluateCommand(resolved.pre, ctx);\n if (preResult.action === \"deny\") return preResult;\n }\n const mainResult = evaluateCommand(resolved.main, ctx);\n if (mainResult.action === \"deny\") return mainResult;\n if (resolved.post) {\n const postResult = evaluateCommand(resolved.post, ctx);\n if (postResult.action === \"deny\") return postResult;\n }\n return {\n action: \"none\",\n rule: null,\n reason: null\n };\n}\nfunction evaluateSegment(rawSegment, ctx) {\n const trimmed = rawSegment.trim();\n const body = subshellBody(trimmed);\n if (body !== null) return evaluateCommand(body, {\n ...ctx,\n depth: ctx.depth + 1\n });\n if (trimmed.startsWith(\"(\") && trimmed.endsWith(\")\")) return {\n action: \"none\",\n rule: null,\n reason: \"subshell\"\n };\n const tokenResult = tokenize(rawSegment);\n if (!tokenResult.ok) return {\n action: \"none\",\n rule: null,\n reason: tokenResult.error\n };\n let tokens = tokenResult.tokens;\n if (tokens.length === 0) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n let envSkipped = 0;\n while (envSkipped < tokens.length && /^\\w+=/.test(tokens[envSkipped])) envSkipped++;\n if (envSkipped >= tokens.length) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n tokens = tokens.slice(envSkipped);\n if (writesIntoNodeModules(tokens, ctx)) return {\n action: \"deny\",\n rule: \"node-modules-write\",\n reason: NODE_MODULES_WRITE_REASON\n };\n const injection = checkInjection(tokens, rawSegment);\n if (!injection.safe) return {\n action: \"none\",\n rule: null,\n reason: injection.reason\n };\n const SAFE_REDIRECT_TOKENS = /* @__PURE__ */ new Set([\n \"2>&1\",\n \"2>/dev/null\",\n \">/dev/null\",\n \"1>/dev/null\"\n ]);\n tokens = tokens.filter((t, i) => {\n if (SAFE_REDIRECT_TOKENS.has(t)) return false;\n if ((t === \">\" || t === \">>\") && tokens[i + 1] === \"/dev/null\") return false;\n if (t === \"/dev/null\" && i > 0 && (tokens[i - 1] === \">\" || tokens[i - 1] === \">>\")) return false;\n return true;\n });\n const cmdName = path.basename(tokens[0]);\n if (cmdName === \"command\" && tokens.length > 1) return evaluateCommand(joinTokens(tokens.slice(1)), {\n ...ctx,\n depth: ctx.depth + 1\n });\n if (cmdName === \"env\") {\n let envIdx = 1;\n while (envIdx < tokens.length && /^\\w+=/.test(tokens[envIdx])) envIdx++;\n if (envIdx >= tokens.length) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n return evaluateCommand(joinTokens(tokens.slice(envIdx)), {\n ...ctx,\n depth: ctx.depth + 1\n });\n }\n if (cmdName === \"pnpm\") return evaluatePnpm(tokens, ctx);\n if (cmdName === \"npm\") return evaluateNpm(tokens);\n if (cmdName === \"mise\" && tokens[1] === \"exec\") {\n const inner = miseExecInner(tokens);\n if (!inner) return {\n action: \"none\",\n rule: null,\n reason: \"bare mise exec\"\n };\n return evaluateCommand(joinTokens(inner), {\n ...ctx,\n depth: ctx.depth + 1\n });\n }\n if (cmdName === \"bash\" || cmdName === \"sh\" || cmdName === \"zsh\") return evaluateShellC(tokens, ctx);\n if (cmdName === \"xargs\") return evaluateXargs(tokens, ctx);\n if (cmdName === \"node\" && (tokens.includes(\"-e\") || tokens.includes(\"-p\") || tokens.includes(\"--eval\") || tokens.includes(\"--print\"))) return {\n action: \"none\",\n rule: null,\n reason: \"node eval\"\n };\n for (const rule of denyRules) if (rule.match.test(cmdName)) {\n if (!rule.when || rule.when(tokens, ctx)) return {\n action: \"deny\",\n rule: rule.name,\n reason: rule.reason ?? null\n };\n }\n const advice = cmdName === \"git\" ? worktreeAdvice(tokens, ctx) : void 0;\n return {\n action: \"none\",\n rule: null,\n reason: `no rule matched: ${cmdName}`,\n ...advice ? { advice } : {}\n };\n}\nfunction miseExecInner(tokens) {\n const dashIdx = tokens.indexOf(\"--\");\n if (dashIdx === -1) return void 0;\n const inner = tokens.slice(dashIdx + 1);\n return inner.length > 0 ? inner : void 0;\n}\nfunction scanPnpmFlags(subTokens, from, state) {\n for (let i = from; i < subTokens.length; i++) {\n const t = subTokens[i];\n if (t === \"--filter\" || t.startsWith(\"--filter=\") || t === \"-F\" || t.startsWith(\"-F=\")) return {\n name: void 0,\n filterIdx: i\n };\n if (t === \"-r\" || t === \"--recursive\") {\n state.isRecursive = true;\n continue;\n }\n if (t === \"-w\" || t === \"--workspace-root\") {\n state.isWorkspaceRoot = true;\n continue;\n }\n if (t === \"-C\" || t === \"--dir\") {\n state.dirOverride = subTokens[++i];\n continue;\n }\n if (t.startsWith(\"-C=\") || t.startsWith(\"--dir=\")) {\n state.dirOverride = t.split(\"=\", 2)[1];\n continue;\n }\n if (t.startsWith(\"-\") && !PNPM_BUILTINS.has(t)) continue;\n return { name: t };\n }\n return { name: void 0 };\n}\nfunction evaluatePnpm(tokens, ctx) {\n const subTokens = tokens.slice(1);\n const state = {\n isRecursive: false,\n isWorkspaceRoot: false,\n dirOverride: void 0\n };\n const scan = scanPnpmFlags(subTokens, 0, state);\n if (scan.filterIdx !== void 0) return evaluatePnpmFilter(tokens, subTokens, scan.filterIdx, ctx, state.dirOverride);\n const subcommand = scan.name;\n const subcommandIdx = subcommand ? subTokens.indexOf(subcommand) : -1;\n if (!subcommand) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n if (subcommand === \"dlx\") return {\n action: \"none\",\n rule: null,\n reason: \"pnpm dlx\"\n };\n if (subcommand === \"add\") return {\n action: \"none\",\n rule: null,\n reason: \"pnpm add\"\n };\n if (subcommand === \"exec\") {\n const execArgs = subTokens.slice(subcommandIdx + 1);\n if (execArgs.length === 0) return {\n action: \"none\",\n rule: null,\n reason: \"bare pnpm exec\"\n };\n return evaluateCommand(joinTokens(execArgs), {\n ...ctx,\n depth: ctx.depth + 1\n });\n }\n let scriptName;\n let { isRecursive, isWorkspaceRoot, dirOverride } = state;\n if (subcommand === \"run\") {\n const runScan = scanPnpmFlags(subTokens, subcommandIdx + 1, state);\n ({isRecursive, isWorkspaceRoot, dirOverride} = state);\n if (runScan.filterIdx !== void 0) return evaluatePnpmFilter(tokens, subTokens, runScan.filterIdx, ctx, state.dirOverride);\n if (!runScan.name) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm run without script name\"\n };\n scriptName = runScan.name;\n } else if (!PNPM_BUILTINS.has(subcommand)) scriptName = subcommand;\n else return {\n action: \"none\",\n rule: null,\n reason: null\n };\n if (isRecursive) return evaluatePnpmRecursive(scriptName, ctx);\n if (isWorkspaceRoot) {\n const root = findWorkspaceRoot(ctx.cwd);\n if (!root) return {\n action: \"none\",\n rule: null,\n reason: \"workspace root not found\"\n };\n return evaluatePnpmScript(scriptName, {\n ...ctx,\n cwd: root\n });\n }\n if (dirOverride) {\n const resolved = path.resolve(ctx.cwd, dirOverride);\n return evaluatePnpmScript(scriptName, {\n ...ctx,\n cwd: resolved\n });\n }\n return evaluatePnpmScript(scriptName, ctx);\n}\nfunction evaluatePnpmScript(scriptName, ctx) {\n const resolved = resolveScript(scriptName, ctx.cwd);\n if (!resolved) return {\n action: \"none\",\n rule: null,\n reason: \"script resolution failed\"\n };\n const res = evaluateResolvedScript(resolved, {\n ...ctx,\n depth: ctx.depth + 1\n });\n if (res.action === \"deny\") return res;\n return {\n action: \"none\",\n rule: `pnpm-script:${scriptName}`,\n reason: null\n };\n}\nfunction evaluatePnpmRecursive(scriptName, ctx) {\n const resolved = resolveRecursiveScripts(scriptName, ctx.cwd);\n if (!resolved || resolved.length === 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm recursive\"\n };\n for (const pkg of resolved) {\n const res = evaluateResolvedScript(pkg, {\n ...ctx,\n depth: ctx.depth + 1,\n cwd: pkg.pkgDir ?? ctx.cwd\n });\n if (res.action === \"deny\") return res;\n }\n return {\n action: \"none\",\n rule: `pnpm-recursive:${scriptName}`,\n reason: null\n };\n}\nfunction evaluateNpm(tokens) {\n if (isNpmReadOp(tokens)) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n return {\n action: \"deny\",\n rule: \"npm-redirect\",\n reason: getNpmRedirectReason(tokens)\n };\n}\nfunction collectFiltersAndScan(subTokens, from, filterPkgs) {\n let dirOverride;\n for (let i = from; i < subTokens.length; i += 1) {\n const t = subTokens[i];\n if (t === \"--filter\" || t === \"-F\") {\n const pkg = subTokens[i + 1];\n if (pkg === void 0 || pkg.startsWith(\"-\")) return void 0;\n filterPkgs.push(pkg);\n i += 1;\n continue;\n }\n if (t.startsWith(\"--filter=\") || t.startsWith(\"-F=\")) {\n const pkg = t.startsWith(\"-F=\") ? t.slice(3) : t.slice(9);\n if (pkg === \"\") return void 0;\n filterPkgs.push(pkg);\n continue;\n }\n if (t === \"-r\" || t === \"--recursive\" || t === \"-w\" || t === \"--workspace-root\") continue;\n if (t === \"-C\" || t === \"--dir\") {\n dirOverride = subTokens[i + 1];\n i += 1;\n continue;\n }\n if (t.startsWith(\"-C=\") || t.startsWith(\"--dir=\")) {\n dirOverride = t.split(\"=\", 2)[1];\n continue;\n }\n if (t.startsWith(\"-\")) continue;\n return {\n name: t,\n index: i,\n dirOverride\n };\n }\n return {\n name: void 0,\n index: -1,\n dirOverride\n };\n}\nfunction evaluatePnpmFilter(_tokens, subTokens, filterIdx, ctx, stateDir) {\n const filterPkgs = [];\n const scan = collectFiltersAndScan(subTokens, filterIdx, filterPkgs);\n if (scan === void 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter without package\"\n };\n let dirOverride = scan.dirOverride ?? stateDir;\n if (filterPkgs.length === 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter without package\"\n };\n const filterSubcommand = scan.name;\n const subcmdIdx = scan.index;\n if (filterSubcommand === void 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter without subcommand\"\n };\n if (PNPM_BUILTINS.has(filterSubcommand) && filterSubcommand !== \"run\" && filterSubcommand !== \"exec\") return {\n action: \"none\",\n rule: null,\n reason: null\n };\n if (filterSubcommand === \"exec\") {\n const execArgs = subTokens.slice(subcmdIdx + 1);\n if (execArgs.length === 0) return {\n action: \"none\",\n rule: null,\n reason: \"bare pnpm exec\"\n };\n return evaluateCommand(joinTokens(execArgs), {\n ...ctx,\n depth: ctx.depth + 1\n });\n }\n let scriptName = filterSubcommand;\n if (filterSubcommand === \"run\") {\n const runScan = collectFiltersAndScan(subTokens, subcmdIdx + 1, filterPkgs);\n if (runScan === void 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter without package\"\n };\n scriptName = runScan.name;\n if (runScan.dirOverride !== void 0) dirOverride = runScan.dirOverride;\n }\n if (scriptName === void 0 || scriptName.startsWith(\"-\")) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter run without script name\"\n };\n if (PNPM_BUILTINS.has(scriptName) && scriptName !== \"run\") return {\n action: \"none\",\n rule: null,\n reason: null\n };\n const baseDir = dirOverride ? path.resolve(ctx.cwd, dirOverride) : ctx.cwd;\n for (const pkg of filterPkgs) {\n const resolved = resolveFilteredScript(scriptName, pkg, baseDir);\n if (!resolved) return {\n action: \"none\",\n rule: null,\n reason: \"filtered script resolution failed\"\n };\n const res = evaluateResolvedScript(resolved, {\n ...ctx,\n depth: ctx.depth + 1,\n cwd: resolved.pkgDir ?? baseDir\n });\n if (res.action === \"deny\") return res;\n }\n return {\n action: \"none\",\n rule: `pnpm-filter:${filterPkgs.join(\",\")}:${scriptName}`,\n reason: null\n };\n}\nconst SHELL_LOGIN_FLAGS = /* @__PURE__ */ new Set([\"-l\", \"--login\"]);\nfunction evaluateShellC(tokens, ctx) {\n let i = 1;\n while (i < tokens.length && SHELL_LOGIN_FLAGS.has(tokens[i])) i++;\n const flag = tokens[i];\n if (flag === void 0 || !/^-[lc]+$/.test(flag) || !flag.includes(\"c\")) return {\n action: \"none\",\n rule: null,\n reason: \"shell without a plain -c\"\n };\n const cmdArg = tokens[i + 1];\n if (!cmdArg) return {\n action: \"none\",\n rule: null,\n reason: \"shell -c without command\"\n };\n if (tokens.length > i + 2) return {\n action: \"none\",\n rule: null,\n reason: \"shell -c with positional args\"\n };\n return evaluateCommand(cmdArg, {\n ...ctx,\n depth: ctx.depth + 1\n });\n}\nconst XARGS_ARG_FLAGS = /* @__PURE__ */ new Set([\n \"-I\",\n \"-d\",\n \"-n\",\n \"-P\",\n \"-s\",\n \"-L\",\n \"-E\",\n \"-a\",\n \"--max-args\",\n \"--max-procs\",\n \"--delimiter\",\n \"--replace\",\n \"--max-lines\",\n \"--max-chars\",\n \"--arg-file\",\n \"--process-slot-var\"\n]);\nconst XARGS_BOOL_FLAGS = /* @__PURE__ */ new Set([\n \"-0\",\n \"--null\",\n \"-t\",\n \"--verbose\",\n \"-r\",\n \"--no-run-if-empty\",\n \"-p\",\n \"--interactive\",\n \"-x\",\n \"--exit\",\n \"--show-limits\"\n]);\nfunction evaluateXargs(tokens, ctx) {\n let i = 1;\n while (i < tokens.length) {\n const t = tokens[i];\n if (!t.startsWith(\"-\")) break;\n if (XARGS_ARG_FLAGS.has(t)) {\n i += 2;\n continue;\n }\n const eqIdx = t.indexOf(\"=\");\n if (eqIdx !== -1) {\n const flagName = t.slice(0, eqIdx);\n if (XARGS_ARG_FLAGS.has(flagName)) {\n i++;\n continue;\n }\n }\n if (t.length > 2 && XARGS_ARG_FLAGS.has(t.slice(0, 2))) {\n i++;\n continue;\n }\n if (XARGS_BOOL_FLAGS.has(t)) {\n i++;\n continue;\n }\n return {\n action: \"none\",\n rule: null,\n reason: \"xargs with unrecognised flags\"\n };\n }\n if (i >= tokens.length) return {\n action: \"none\",\n rule: null,\n reason: \"xargs without command\"\n };\n return evaluateCommand(joinTokens(tokens.slice(i)), {\n ...ctx,\n depth: ctx.depth + 1\n });\n}\n\n//#endregion\n//#region src/file-rules.ts\nconst READ_TOOLS = /* @__PURE__ */ new Set([\n \"Read\",\n \"Glob\",\n \"Grep\"\n]);\nconst WRITE_TOOLS = /* @__PURE__ */ new Set([\"Write\", \"Edit\"]);\nconst fileDenyRules = [\n {\n name: \"env-file-read\",\n tools: READ_TOOLS,\n action: \"deny\",\n when: (filePath) => isEnvFile(filePath),\n reason: \"Don't read .env files. These contain secrets that should not appear in the conversation.\"\n },\n {\n name: \"env-file-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath) => isEnvFile(filePath),\n reason: \"Don't write to .env files. These contain secrets.\"\n },\n {\n name: \"hooks-folder-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath, ctx) => {\n const resolved = resolveIn(ctx.cwd, filePath);\n const hooksDir = path.join(ctx.cwd, \".claude\", \"hooks\");\n return isWithin(hooksDir, resolved);\n },\n reason: \"Don't write to .claude/hooks/. These files are managed by the project and should not be modified directly.\"\n },\n {\n name: \"git-dir-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath, ctx) => targetsGitDir(filePath, ctx.cwd),\n reason: \"Don't write into .git/ directly. Its internals (config, hooks, refs) are not plain project files -- a config edit can redirect remotes or push destinations that other rules trust, and a hooks/ script runs automatically on the next commit/push. Use git subcommands instead, or ask the user.\"\n },\n {\n name: \"node-modules-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath, ctx) => targetsNodeModules(filePath, ctx.cwd),\n reason: \"Don't write into node_modules/. Its files are hardlinks into pnpm's global store -- editing one in place corrupts that package for every project on this machine. Edit the source package and rebuild, or install into a scratch tree with an isolated store (`pnpm add --store-dir <scratch> <pkg>`).\"\n },\n {\n name: \"claude-settings-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath, ctx) => {\n const resolved = resolveIn(ctx.cwd, filePath);\n return samePath(resolved, path.join(ctx.cwd, \".claude\", \"settings.json\"));\n },\n reason: \"Don't write to .claude/settings.json. This file is managed by the project and should not be modified directly.\"\n }\n];\n\n//#endregion\n//#region src/evaluate-tool.ts\nconst FILE_PATH_TOOLS = /* @__PURE__ */ new Set([\n \"Read\",\n \"Write\",\n \"Edit\"\n]);\nconst SEARCH_TOOLS = /* @__PURE__ */ new Set([\"Glob\", \"Grep\"]);\nfunction extractPath(toolName, toolInput, cwd) {\n if (FILE_PATH_TOOLS.has(toolName)) return parseFilePathInput(toolInput)?.file_path ?? null;\n if (SEARCH_TOOLS.has(toolName)) return parseSearchInput(toolInput)?.path ?? cwd;\n return null;\n}\nfunction evaluateToolUse(toolName, toolInput, ctx) {\n const filePath = extractPath(toolName, toolInput, ctx.cwd);\n if (filePath === null) return {\n action: \"none\",\n rule: null,\n reason: \"unknown tool input shape\"\n };\n for (const rule of fileDenyRules) if (rule.tools.has(toolName) && rule.when(filePath, ctx, toolInput)) return {\n action: \"deny\",\n rule: rule.name,\n reason: rule.reason ?? null\n };\n return {\n action: \"none\",\n rule: null,\n reason: \"no file rule matched\"\n };\n}\n\n//#endregion\n//#region src/lib/settings.ts\nconst SETTINGS_PATH = \".claude/hooks/bst-hook.settings.json\";\nconst BstHookSettingsSchema = object({ protectedBranches: _default(array(string().check(_minLength(1))), []) });\nfunction isFileClean(cwd, relativePath) {\n try {\n execFileSync(\"git\", [\n \"ls-files\",\n \"--error-unmatch\",\n relativePath\n ], {\n cwd,\n stdio: \"ignore\",\n timeout: GIT_TIMEOUT_MS\n });\n execFileSync(\"git\", [\n \"diff\",\n \"--quiet\",\n \"HEAD\",\n \"--\",\n relativePath\n ], {\n cwd,\n stdio: \"ignore\",\n timeout: GIT_TIMEOUT_MS\n });\n return true;\n } catch {\n return false;\n }\n}\nfunction loadRepoSettings(cwd) {\n const root = findWorkspaceRoot(cwd) ?? cwd;\n const settingsFile = join(root, SETTINGS_PATH);\n const empty = { protectedBranches: [] };\n if (!existsSync(settingsFile)) return empty;\n if (!isFileClean(root, SETTINGS_PATH)) return empty;\n try {\n const raw = readFileSync(settingsFile, \"utf-8\");\n const parsed = JSON.parse(raw);\n const result = BstHookSettingsSchema.safeParse(parsed);\n if (!result.success) return empty;\n return { protectedBranches: result.data.protectedBranches };\n } catch {\n return empty;\n }\n}\n\n//#endregion\n//#region src/index.ts\nconst inputResult = await readHookInput();\nif (!inputResult.ok) {\n process.stderr.write(`[bst-hook] invalid hook input: ${inputResult.error}\\n`);\n audit({\n sessionId: \"unknown\",\n cwd: \"unknown\",\n command: `<invalid input: ${inputResult.error}>`,\n decision: \"none\",\n rule: null,\n reason: `validation failed: ${inputResult.error}`,\n permissionMode: void 0\n });\n process.exit(0);\n}\nconst input = inputResult.data;\nif (input.hook_event_name !== \"PreToolUse\") process.exit(0);\nif (!(/* @__PURE__ */ new Set([\n \"Bash\",\n \"Read\",\n \"Write\",\n \"Edit\",\n \"Glob\",\n \"Grep\"\n])).has(input.tool_name)) process.exit(0);\nconst repoSettings = loadRepoSettings(input.cwd);\nlet decision;\nlet auditCommand;\nif (input.tool_name === \"Bash\") {\n const bashInput = parseBashInput(input.tool_input);\n if (!bashInput) {\n audit({\n sessionId: input.session_id,\n cwd: input.cwd,\n toolName: input.tool_name,\n command: `<invalid Bash input: ${JSON.stringify(input.tool_input).slice(0, 200)}>`,\n decision: \"none\",\n rule: null,\n reason: \"Bash tool_input missing or invalid 'command' field\",\n permissionMode: input.permission_mode\n });\n process.exit(0);\n }\n decision = evaluateCommand(bashInput.command, {\n cwd: input.cwd,\n depth: 0,\n repoProtectedBranches: repoSettings.protectedBranches\n });\n auditCommand = bashInput.command;\n} else {\n const projectDir = findWorkspaceRoot(input.cwd) ?? process.env[\"CLAUDE_PROJECT_DIR\"] ?? input.cwd;\n decision = evaluateToolUse(input.tool_name, input.tool_input, {\n cwd: projectDir,\n sessionId: input.session_id\n });\n const filePath = String(input.tool_input[\"file_path\"] ?? input.tool_input[\"path\"] ?? \"\");\n auditCommand = `${input.tool_name} ${filePath}`;\n}\naudit({\n sessionId: input.session_id,\n cwd: input.cwd,\n toolName: input.tool_name,\n command: auditCommand,\n decision: decision.action,\n rule: decision.rule,\n reason: decision.reason,\n permissionMode: input.permission_mode\n});\nif (decision.action === \"deny\") writeDeny(decision.reason);\nelse if (decision.advice) writeAdvice(decision.advice);\n\n//#endregion\nexport { };",
8751
+ hook: "/**\n * bst-hook -- Claude Code PreToolUse hook\n * @bensandee/claude-hooks\n * https://github.com/bensandee/tooling\n *\n * Auto-generated by @bensandee/tooling repo:sync -- do not edit manually.\n */\nimport * as fs from \"node:fs\";\nimport { existsSync, readFileSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { execFileSync } from \"node:child_process\";\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js\nfunction joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nfunction jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\") return value.toString();\n return value;\n}\nvar Cached = class {\n constructor(getter) {\n this._getter = getter;\n this._value = void 0;\n }\n get value() {\n const getter = this._getter;\n if (getter !== void 0) {\n this._value = getter();\n this._getter = void 0;\n }\n return this._value;\n }\n};\nfunction cached(getter) {\n return new Cached(getter);\n}\nfunction nullish(input) {\n return input === null || input === void 0;\n}\nfunction cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nfunction assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n}\nconst captureStackTrace = \"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => {};\nfunction isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nfunction isPlainObject(o) {\n if (isObject(o) === false) return false;\n const ctor = o.constructor;\n if (ctor === void 0) return true;\n if (typeof ctor !== \"function\") return true;\n const prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) return false;\n return true;\n}\nfunction shallowClone(o) {\n if (isPlainObject(o)) return { ...o };\n if (Array.isArray(o)) return [...o];\n if (o instanceof Map) return new Map(o);\n if (o instanceof Set) return new Set(o);\n return o;\n}\nfunction clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent) cl._zod.parent = inst;\n return cl;\n}\nfunction normalizeParams(_params) {\n const params = _params;\n if (!params) return {};\n if (typeof params === \"string\") return { error: () => params };\n if (params?.message !== void 0) {\n if (params?.error !== void 0) throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\") return {\n ...params,\n error: () => params.error\n };\n return params;\n}\nfunction stringifyPrimitive(value) {\n if (typeof value === \"bigint\") return value.toString() + \"n\";\n if (typeof value === \"string\") return `\"${value}\"`;\n return `${value}`;\n}\nfunction optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === \"optional\";\n });\n}\nfunction aborted(x, startIndex = 0) {\n if (x.aborted === true) return true;\n for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;\n return false;\n}\nfunction explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true) return true;\n for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true;\n return false;\n}\nfunction prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nfunction unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nfunction sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n if (!/_(length|size)$|_equals$/.test(d.check)) break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0) caps.push([max, ch]);\n }\n return caps;\n}\nfunction attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) (_a = issues[i]).schema ?? (_a.schema = inst);\n}\nfunction finalizeIssue(iss, ctx, config) {\n var _a;\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\")) (_a = iss).schema ?? (_a.schema = iss.inst);\n else iss.schema = iss.inst;\n }\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0;\n const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? \"Invalid input\";\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\") continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) full.input = iss.input;\n return full;\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\nfunction codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str)) return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {\n count--;\n i++;\n }\n return count;\n}\nfunction getLengthableOrigin(input) {\n if (Array.isArray(input)) return \"array\";\n if (typeof input === \"string\") return \"string\";\n return \"unknown\";\n}\nfunction parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"object\": {\n if (data === null) return \"null\";\n if (Array.isArray(data)) return \"array\";\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) return obj.constructor.name;\n }\n }\n return t;\n}\nfunction members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n if (desc.get) Object.defineProperty(proto, key, {\n ...desc,\n enumerable: false\n });\n else defineBound(proto, key, desc.value);\n }\n}\nfunction own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, {\n configurable: true,\n writable: true,\n enumerable,\n value\n });\n return value;\n}\nfunction hide(inst, key, value) {\n return own(inst, key, value, false);\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n }\n });\n}\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n return sentinel in proto ? void 0 : proto;\n}\nlet installing;\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n }\n};\nfunction defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n installing = void 0;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n if (broke) delete this[key];\n else Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n value\n });\n broke = broke || outer;\n return value;\n } catch (err) {\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n value\n });\n }\n });\n}\nfunction installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto) return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n const desc = {\n configurable: true,\n writable: true,\n enumerable,\n value: void 0\n };\n Object.defineProperty(this, key, desc);\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable,\n value\n });\n }\n });\n}\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/core.js\nvar _a;\nconst _zodDesc = {\n value: void 0,\n enumerable: false\n};\nlet _E = \"captureStackTrace\" in Error ? Error : null;\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n } catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n } finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\n/* @__NO_SIDE_EFFECTS__ */\nfunction $constructor(name, initializer, proto, params) {\n const zodProto = {};\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = /* @__PURE__ */ new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n const initialized = protoMembers && /* @__PURE__ */ new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n } finally {\n _zodDesc.value = void 0;\n }\n } else if (inst._zod.traits.has(name)) return;\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto) up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n members(target, protoMembers);\n }\n }\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k)) continue;\n if (!(k in inst)) inst[k] = proto[k].bind(inst);\n }\n }\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {}\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) fn();\n inst._zod.deferred = void 0;\n }\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp) pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent) return true;\n return inst?._zod?.traits?.has(name);\n } });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\nvar $ZodAsyncError = class extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n};\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nconst globalConfig = globalThis.__zod_globalConfig;\nfunction config(newConfig) {\n if (newConfig) Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/errors.js\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true\n};\nconst _issuesDesc = {\n value: void 0,\n enumerable: false\n};\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n _issuesDesc.value = void 0;\n Object.defineProperty(inst, \"message\", _messageDesc);\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", {\n value,\n configurable: true,\n writable: true\n });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", {\n value,\n configurable: true,\n writable: true\n });\n }\n });\n }\n};\nconst $ZodRealError = /* @__PURE__ */ $constructor(\"$ZodError\", initializer, void 0, { Parent: Error });\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/parse.js\nconst _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? {\n ..._ctx,\n async: false\n } : { async: false };\n const result = schema._zod.run({\n value,\n issues: []\n }, ctx);\n if (result instanceof Promise) throw new $ZodAsyncError();\n if (result.issues.length) {\n const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));\n captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nconst parse = /* @__PURE__*/ _parse($ZodRealError);\nconst _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? {\n ..._ctx,\n async: true\n } : { async: true };\n let result = schema._zod.run({\n value,\n issues: []\n }, ctx);\n if (result instanceof Promise) result = await result;\n if (result.issues.length) {\n const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));\n captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nconst parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError);\nconst _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? {\n ..._ctx,\n async: false\n } : { async: false };\n const result = schema._zod.run({\n value,\n issues: []\n }, ctx);\n if (result instanceof Promise) throw new $ZodAsyncError();\n return result.issues.length ? failure(_Err, result.issues, ctx) : {\n success: true,\n data: result.value\n };\n};\nconst safeParse = /* @__PURE__*/ _safeParse($ZodRealError);\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));\n issues = void 0;\n ctx = void 0;\n }\n return error;\n },\n set error(e) {\n error = e;\n issues = void 0;\n ctx = void 0;\n }\n };\n}\nconst _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? {\n ..._ctx,\n async: true\n } : { async: true };\n let result = schema._zod.run({\n value,\n issues: []\n }, ctx);\n if (result instanceof Promise) result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : {\n success: true,\n data: result.value\n };\n};\nconst safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError);\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/regexes.js\nconst anyString = /^[\\s\\S]{0,}$/;\nconst number = /^-?\\d+(?:\\.\\d+)?$/;\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/checks.js\nconst $ZodCheck = /*@__PURE__*/ $constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !nullish(val) && val.length !== void 0;\n};\nconst $ZodCheckMinLength = /*@__PURE__*/ $constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n if ((typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units) >= def.minimum) return;\n const origin = getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort\n });\n };\n});\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/versions.js\nconst version = {\n major: 4,\n minor: 6,\n patch: 7\n};\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/schemas.js\nconst $ZodType = /*@__PURE__*/ $constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def;\n inst._zod.bag = inst._zod.bag || {};\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n const checks = inst._zod.traits.has(\"$ZodCheck\") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : [];\n for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);\n if (checks.length === 0) {\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n } else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo) return payload;\n let isAborted = aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (explicitlyAborted(payload)) continue;\n if (!ch._zod.def.when(payload)) continue;\n } else if (isAborted) continue;\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();\n if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n if (payload.issues.length === currLen) return;\n attachSchema(payload.issues, currLen, inst);\n if (!isAborted) isAborted = aborted(payload, currLen);\n });\n else {\n if (payload.issues.length === currLen) continue;\n attachSchema(payload.issues, currLen, inst);\n if (!isAborted) isAborted = aborted(payload, currLen);\n }\n }\n if (asyncResult) return asyncResult.then(() => {\n return payload;\n });\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n if (aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false) throw new $ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) return inst._zod.parse(payload, ctx);\n if (ctx.direction === \"backward\") {\n const canary = inst._zod.parse({\n value: payload.value,\n issues: []\n }, {\n ...ctx,\n skipChecks: true\n });\n if (canary instanceof Promise) return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n return handleCanaryResult(canary, payload, ctx);\n }\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false) throw new $ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n get \"~standard\"() {\n return hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n own(this, \"~standard\", value);\n }\n});\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult(await inst._zod.run({\n value,\n issues: []\n }, ctx), ctx);\n}\nfunction standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({\n value,\n issues: []\n }, ctx);\n if (!(r instanceof Promise)) return toStandardResult(r, ctx);\n } catch (_) {}\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1\n };\n}\nconst $ZodString = /*@__PURE__*/ $constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = def.pattern ?? anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce) try {\n payload.value = String(payload.value);\n } catch (_) {}\n if (typeof payload.value === \"string\") return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst\n });\n return payload;\n };\n});\nconst $ZodUnknown = /*@__PURE__*/ $constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nfunction capSize(inst, size) {\n const caps = sizeCaps(inst._zod.def.checks);\n if (!caps.length) return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of sizeCaps(inst._zod.def.checks)) if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n payload.issues[start].continue = false;\n attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => Array.isArray(input) ? input.length : -1;\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));\n final.value[index] = result.value;\n}\nconst $ZodArray = /*@__PURE__*/ $constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: []\n }, ctx);\n if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n else {\n handleArrayResult(result, payload, i);\n if (abortEarly && result.issues.length !== 0 && aborted(result)) break;\n }\n }\n if (proms.length) return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n if (!isPresent && isOptionalOut && optin === \"optional\") return;\n if (result.issues.length) {\n if (optin !== void 0 && isOptionalOut && !isPresent) return;\n final.issues.push(...prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === void 0) {\n if (!result.issues.length) final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: void 0,\n path: [key]\n });\n return;\n }\n if (result.value === void 0) {\n if (isPresent || optin === \"defaulted\" && !isOptionalOut) final.value[key] = void 0;\n } else final.value[key] = result.value;\n}\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n const okeys = optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys)\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (aborted(payload, seen)) break;\n seen = payload.issues.length;\n }\n if (keySet.has(key)) continue;\n if (key === \"__proto__\") {\n if (t === \"never\") unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({\n value: input[key],\n issues: []\n }, ctx);\n if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n else handlePropertyResult(r, payload, key, input, optin, optout);\n }\n if (unrecognized.length) payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n continue: true\n });\n if (!proms.length) return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nconst $ZodObject = /*@__PURE__*/ $constructor(\"$ZodObject\", (inst, def) => {\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n const sh = desc?.get ? desc.get.raw : def.shape ?? {};\n if (sh) {\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = cached(() => normalizeDef(def));\n defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) assignProp(propValues, key, /* @__PURE__ */ new Set());\n for (const v of field.values) propValues[key].add(v);\n if (field.optin !== void 0) propValues[key].add(void 0);\n }\n }\n return propValues;\n });\n const isObject$1 = isObject;\n const catchall = def.catchall;\n let value;\n const memo = globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject$1(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (aborted(payload, seen)) break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\") continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({\n value: input[key],\n issues: []\n }, ctx);\n if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n else handlePropertyResult(r, payload, key, input, optin, optout);\n }\n if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nconst $ZodRecord = /*@__PURE__*/ $constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = /* @__PURE__ */ new Set();\n for (const key of values) if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n if (key === \"__proto__\") continue;\n const keyResult = def.keyType._zod.run({\n value: key,\n issues: []\n }, ctx);\n if (keyResult instanceof Promise) throw new Error(\"Async schemas not supported in object keys currently\");\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),\n input: key,\n path: [key],\n inst\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\") continue;\n const result = def.valueType._zod.run({\n value: input[key],\n issues: []\n }, ctx);\n if (result instanceof Promise) proms.push(result.then((result) => {\n if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));\n payload.value[outKey] = result.value;\n }));\n else {\n if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));\n payload.value[outKey] = result.value;\n }\n }\n let unrecognized;\n for (const key in input) if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n if (key === \"__proto__\") continue;\n payload.value[key] = input[key];\n } else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true\n });\n } else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n let unrecognized;\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\") continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue;\n let keyResult = def.keyType._zod.run({\n value: key,\n issues: []\n }, ctx);\n if (keyResult instanceof Promise) throw new Error(\"Async schemas not supported in object keys currently\");\n if (typeof key === \"string\" && number.test(key) && keyResult.issues.length) {\n const retryResult = def.keyType._zod.run({\n value: Number(key),\n issues: []\n }, ctx);\n if (retryResult instanceof Promise) throw new Error(\"Async schemas not supported in object keys currently\");\n if (retryResult.issues.length === 0) keyResult = retryResult;\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") payload.value[key] = input[key];\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n } else payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),\n input: key,\n path: [key],\n inst\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\") continue;\n const result = def.valueType._zod.run({\n value: input[key],\n issues: []\n }, ctx);\n if (result instanceof Promise) proms.push(result.then((result) => {\n if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));\n payload.value[outKey] = result.value;\n }));\n else {\n if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true\n });\n }\n if (proms.length) return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n payload.value = result.issues.length ? void 0 : result.value;\n return payload;\n}\nconst $ZodOptional = /*@__PURE__*/ $constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? /* @__PURE__ */ new Set([...values, void 0]) : void 0;\n });\n defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === void 0) {\n if (def.innerType._zod.optin !== \"defaulted\") return payload;\n const result = def.innerType._zod.run({\n value: payload.value,\n issues: []\n }, ctx);\n if (result instanceof Promise) return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nconst $ZodDefault = /*@__PURE__*/ $constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") return def.innerType._zod.run(payload, ctx);\n if (payload.value === void 0) {\n payload.value = def.defaultValue;\n return payload;\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === void 0) payload.value = def.defaultValue;\n return payload;\n}\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/en.js\nconst error = () => {\n const Sizable = {\n string: {\n unit: \"characters\",\n verb: \"to have\"\n },\n file: {\n unit: \"bytes\",\n verb: \"to have\"\n },\n array: {\n unit: \"items\",\n verb: \"to have\"\n },\n set: {\n unit: \"items\",\n verb: \"to have\"\n },\n map: {\n unit: \"entries\",\n verb: \"to have\"\n }\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\"\n };\n const TypeDictionary = { nan: \"NaN\" };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) return String(input);\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": return `Invalid input: expected ${getTypeName(issue.expected)}, received ${getTypeName(parsedType(issue.input), issue.input)}`;\n case \"invalid_value\":\n if (issue.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing) return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") return `Invalid string: must start with \"${_issue.prefix}\"`;\n if (_issue.format === \"ends_with\") return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\") return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\") return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\": return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\": return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${joinValues(issue.keys, \", \")}`;\n case \"invalid_key\": return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) return `Invalid discriminator value. Expected ${issue.options.map((o) => `'${o}'`).join(\" | \")}`;\n if (issue.inclusive === false) return \"Invalid input: more than one option matched\";\n return \"Invalid input\";\n case \"invalid_element\": return `Invalid value in ${issue.origin}`;\n default: return `Invalid input`;\n }\n };\n};\nfunction en_default() {\n return { localeError: error() };\n}\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/api.js\nfunction snapshotChecks(def) {\n if (def.checks) def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nfunction _string(Class, params) {\n return new Class(snapshotChecks({\n type: \"string\",\n ...normalizeParams(params)\n }));\n}\n// @__NO_SIDE_EFFECTS__\nfunction _unknown(Class) {\n return new Class({ type: \"unknown\" });\n}\n// @__NO_SIDE_EFFECTS__\nfunction _minLength(minimum, params) {\n return new $ZodCheckMinLength({\n check: \"min_length\",\n ...normalizeParams(params),\n minimum\n });\n}\n\n// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/schemas.js\nconst ZodMiniType = /*@__PURE__*/ $constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod) throw new Error(\"Uninitialized schema in ZodMiniType.\");\n $ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n}, {\n get with() {\n return this.check;\n },\n set with(value) {\n own(this, \"with\", value);\n },\n parse(data, params) {\n return parse(this, data, params, { callee: this.parse });\n },\n parseAsync(data, params) {\n return parseAsync(this, data, params, { callee: this.parseAsync });\n },\n safeParse(data, params) {\n return safeParse(this, data, params);\n },\n safeParseAsync(data, params) {\n return safeParseAsync(this, data, params);\n },\n check(...checks) {\n const def = this.def;\n return this.clone({\n ...def,\n checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === \"function\" ? { _zod: {\n check: ch,\n def: { check: \"custom\" },\n onattach: []\n } } : ch)]\n }, { parent: true });\n },\n clone(_def, params) {\n return clone(this, _def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n }\n});\nconst ZodMiniString = /*@__PURE__*/ $constructor(\"ZodMiniString\", (inst, def) => {\n $ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction string(params) {\n return _string(ZodMiniString, params);\n}\nconst ZodMiniUnknown = /*@__PURE__*/ $constructor(\"ZodMiniUnknown\", (inst, def) => {\n $ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction unknown() {\n return _unknown(ZodMiniUnknown);\n}\nconst ZodMiniArray = /*@__PURE__*/ $constructor(\"ZodMiniArray\", (inst, def) => {\n $ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element,\n ...normalizeParams(params)\n });\n}\nconst ZodMiniObject = /*@__PURE__*/ $constructor(\"ZodMiniObject\", (inst, def) => {\n $ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n});\n// @__NO_SIDE_EFFECTS__\nfunction object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...normalizeParams(params)\n };\n return new ZodMiniObject(def);\n}\nconst ZodMiniRecord = /*@__PURE__*/ $constructor(\"ZodMiniRecord\", (inst, def) => {\n $ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction record(keyType, valueType, params) {\n if (!valueType || !valueType._zod) return new ZodMiniRecord({\n type: \"record\",\n keyType: /* @__PURE__ */ string(),\n valueType: keyType,\n ...normalizeParams(valueType)\n });\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType,\n ...normalizeParams(params)\n });\n}\nconst ZodMiniOptional = /*@__PURE__*/ $constructor(\"ZodMiniOptional\", (inst, def) => {\n $ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType\n });\n}\nconst ZodMiniDefault = /*@__PURE__*/ $constructor(\"ZodMiniDefault\", (inst, def) => {\n $ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : shallowClone(defaultValue);\n }\n });\n}\n\n// src/lib/hook-io.ts\nconfig(en_default());\nconst HookInputSchema = object({\n session_id: string(),\n transcript_path: string(),\n cwd: string(),\n permission_mode: string(),\n hook_event_name: string(),\n tool_name: string(),\n tool_input: record(string(), unknown())\n});\nasync function readHookInput() {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(typeof chunk === \"string\" ? chunk : String(chunk));\n let parsed;\n try {\n parsed = JSON.parse(chunks.join(\"\"));\n } catch (_error) {\n return {\n ok: false,\n raw: chunks.join(\"\").slice(0, 200),\n error: \"invalid JSON\"\n };\n }\n const result = HookInputSchema.safeParse(parsed);\n if (!result.success) return {\n ok: false,\n raw: parsed,\n error: result.error.message\n };\n return {\n ok: true,\n data: result.data\n };\n}\nconst BashInputSchema = object({\n command: string(),\n description: optional(string())\n});\nconst FilePathInputSchema = object({ file_path: string() });\nconst SearchInputSchema = object({\n pattern: string(),\n path: optional(string())\n});\nfunction parseBashInput(toolInput) {\n const result = BashInputSchema.safeParse(toolInput);\n return result.success ? result.data : null;\n}\nfunction parseFilePathInput(toolInput) {\n const result = FilePathInputSchema.safeParse(toolInput);\n return result.success ? result.data : null;\n}\nfunction parseSearchInput(toolInput) {\n const result = SearchInputSchema.safeParse(toolInput);\n return result.success ? result.data : null;\n}\nfunction writeDeny(reason) {\n const decision = { hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n ...reason ? { permissionDecisionReason: reason } : {}\n } };\n process.stdout.write(JSON.stringify(decision));\n}\nfunction writeAdvice(advice) {\n const decision = { hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n additionalContext: advice\n } };\n process.stdout.write(JSON.stringify(decision));\n}\n\n// src/lib/audit.ts\nconst MAX_LOG_SIZE = 1048576;\nfunction getLogPath() {\n const hookDir = path.dirname(fileURLToPath(import.meta.url));\n return path.join(hookDir, \"bst-hook.audit.local.jsonl\");\n}\nfunction rotateIfNeeded(logPath) {\n try {\n if (fs.statSync(logPath).size > MAX_LOG_SIZE) {\n const rotatedPath = `${logPath}.1`;\n fs.renameSync(logPath, rotatedPath);\n }\n } catch (_error) {}\n}\nlet rotationChecked = false;\nfunction audit(entry) {\n try {\n const logPath = getLogPath();\n if (!rotationChecked) {\n rotateIfNeeded(logPath);\n rotationChecked = true;\n }\n const record = {\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n ...entry\n };\n fs.appendFileSync(logPath, JSON.stringify(record) + \"\\n\");\n } catch (err) {\n process.stderr.write(`[bst-hook] audit write failed: ${err instanceof Error ? err.message : String(err)}\\n`);\n }\n}\n\n// src/lib/shell-tokenizer.ts\nfunction scanDoubleQuoted(input, start) {\n let content = \"\";\n let i = start;\n while (i < input.length && input[i] !== \"\\\"\") {\n if (input[i] === \"\\\\\" && i + 1 < input.length) {\n const next = input[i + 1];\n if (next === \"\\\"\" || next === \"\\\\\" || next === \"$\" || next === \"`\") {\n content += next;\n i += 2;\n continue;\n }\n }\n content += input[i];\n i++;\n }\n if (i >= input.length) return null;\n return {\n content,\n next: i + 1\n };\n}\nfunction tokenize(input) {\n const tokens = [];\n let current = \"\";\n let i = 0;\n let inToken = false;\n while (i < input.length) {\n const ch = input[i];\n if (ch === \"'\") {\n inToken = true;\n i++;\n while (i < input.length && input[i] !== \"'\") {\n current += input[i];\n i++;\n }\n if (i >= input.length) return {\n ok: false,\n error: \"unterminated single quote\"\n };\n i++;\n } else if (ch === \"\\\"\") {\n inToken = true;\n const scanned = scanDoubleQuoted(input, i + 1);\n if (!scanned) return {\n ok: false,\n error: \"unterminated double quote\"\n };\n current += scanned.content;\n i = scanned.next;\n } else if (ch === \"\\\\\" && i + 1 < input.length) {\n inToken = true;\n current += input[i + 1];\n i += 2;\n } else if (ch === \" \" || ch === \" \") {\n if (inToken) {\n tokens.push(current);\n current = \"\";\n inToken = false;\n }\n i++;\n } else {\n inToken = true;\n current += ch;\n i++;\n }\n }\n if (inToken) tokens.push(current);\n return {\n ok: true,\n tokens\n };\n}\nconst SAFE_UNQUOTED_RE = /^[A-Za-z0-9_\\-./=:@%+,]+$/;\nfunction quoteToken(token) {\n if (token.length > 0 && SAFE_UNQUOTED_RE.test(token)) return token;\n return \"'\" + token.replace(/'/g, \"'\\\\''\") + \"'\";\n}\nfunction joinTokens(tokens) {\n return tokens.map(quoteToken).join(\" \");\n}\n\n// src/lib/shell-splitter.ts\nfunction splitCommand(input) {\n if (!input || !input.trim()) return [];\n const segments = [];\n let current = \"\";\n let i = 0;\n let inSingleQuote = false;\n let inDoubleQuote = false;\n while (i < input.length) {\n const ch = input[i];\n if (ch === \"'\" && !inDoubleQuote) {\n inSingleQuote = !inSingleQuote;\n current += ch;\n i++;\n continue;\n }\n if (ch === \"\\\"\" && !inSingleQuote) {\n inDoubleQuote = !inDoubleQuote;\n current += ch;\n i++;\n continue;\n }\n if (ch === \"\\\\\" && !inSingleQuote && i + 1 < input.length) {\n current += ch + input[i + 1];\n i += 2;\n continue;\n }\n if (!inSingleQuote && !inDoubleQuote) {\n if (ch === \"&\" && i + 1 < input.length && input[i + 1] === \"&\") {\n pushSegment(segments, current, \"&&\");\n current = \"\";\n i += 2;\n continue;\n }\n if (ch === \"&\" && !(i + 1 < input.length && input[i + 1] === \">\") && !(i > 0 && (input[i - 1] === \">\" || input[i - 1] === \"<\"))) {\n pushSegment(segments, current, \"&\");\n current = \"\";\n i++;\n continue;\n }\n if (ch === \"|\" && i + 1 < input.length && input[i + 1] === \"|\") {\n pushSegment(segments, current, \"||\");\n current = \"\";\n i += 2;\n continue;\n }\n if (ch === \"|\") {\n pushSegment(segments, current, \"|\");\n current = \"\";\n i++;\n continue;\n }\n if (ch === \";\") {\n pushSegment(segments, current, \";\");\n current = \"\";\n i++;\n continue;\n }\n }\n current += ch;\n i++;\n }\n const trimmed = current.trim();\n if (trimmed) segments.push({\n command: trimmed,\n operator: null\n });\n return segments;\n}\nfunction pushSegment(segments, text, operator) {\n const trimmed = text.trim();\n if (trimmed) segments.push({\n command: trimmed,\n operator\n });\n}\n\n// src/lib/injection-guard.ts\nfunction hasBraceExpansion(token) {\n let depth = 0;\n for (let i = 0; i < token.length; i++) {\n const ch = token[i];\n if (ch === \"{\") depth++;\n else if (ch === \"}\") {\n if (depth > 0) depth--;\n } else if (depth >= 1 && (ch === \",\" || ch === \".\" && token[i + 1] === \".\")) return true;\n }\n return false;\n}\nfunction checkInjection(tokens, rawSegment) {\n if (/[\\n\\r]/.test(rawSegment)) return {\n safe: false,\n reason: \"unquoted newline in command\"\n };\n for (const token of tokens) {\n if (token === \"`\") return {\n safe: false,\n reason: \"backtick command substitution\"\n };\n if (token.includes(\"`\")) return {\n safe: false,\n reason: \"backtick command substitution\"\n };\n if (token.includes(\"$\")) return {\n safe: false,\n reason: \"unresolved dollar-expansion\"\n };\n if (hasBraceExpansion(token)) return {\n safe: false,\n reason: \"brace expansion\"\n };\n if (token.includes(\"<(\")) return {\n safe: false,\n reason: \"process substitution\"\n };\n if (token.includes(\">(\")) return {\n safe: false,\n reason: \"process substitution\"\n };\n }\n return { safe: true };\n}\n\n// src/lib/env-file.ts\nconst ENV_SAFE_SUFFIXES = [\n \".sample\",\n \".example\",\n \".template\"\n];\nconst ENV_TOOL_OWNED_SUFFIXES = [\".check.env\"];\nconst ENV_FILE_PATTERN = /(^|[/\\\\])(\\.env(\\..*)?|.*\\.env(\\..*)?|\\.env)$/;\nfunction isEnvSafeSuffix(filename) {\n return [...ENV_SAFE_SUFFIXES, ...ENV_TOOL_OWNED_SUFFIXES].some((suffix) => filename.endsWith(suffix));\n}\nfunction isEnvFile(filePath) {\n if (isEnvSafeSuffix(path.basename(filePath))) return false;\n return ENV_FILE_PATTERN.test(filePath);\n}\n\n// src/lib/git-state.ts\nconst GIT_TIMEOUT_MS = 5e3;\nfunction getCurrentBranch(cwd) {\n try {\n const out = execFileSync(\"git\", [\n \"rev-parse\",\n \"--abbrev-ref\",\n \"HEAD\"\n ], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n if (!out || out === \"HEAD\") return null;\n return out;\n } catch {\n return null;\n }\n}\nfunction getRepoTopLevel(cwd) {\n try {\n const out = execFileSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n return out === \"\" ? null : out;\n } catch {\n return null;\n }\n}\nfunction getRemoteDefaultBranch(cwd) {\n try {\n const out = execFileSync(\"git\", [\n \"symbolic-ref\",\n \"--short\",\n \"refs/remotes/origin/HEAD\"\n ], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n if (!out) return null;\n return out.startsWith(\"origin/\") ? out.slice(7) : out;\n } catch {\n return null;\n }\n}\nconst DefaultBranchSchema = object({ defaultBranch: optional(string().check(_minLength(1))) });\nfunction getConfiguredDefaultBranch(topLevel) {\n let parsed;\n try {\n parsed = JSON.parse(readFileSync(join(topLevel, \".tooling.json\"), \"utf-8\"));\n } catch {\n return null;\n }\n const result = DefaultBranchSchema.safeParse(parsed);\n return result.success ? result.data.defaultBranch ?? null : null;\n}\nconst ALWAYS_PROTECTED = [\"main\", \"master\"];\nfunction getProtectedBranches(cwd, extra) {\n const set = new Set(ALWAYS_PROTECTED);\n const remote = getRemoteDefaultBranch(cwd);\n if (remote) set.add(remote);\n for (const b of extra) set.add(b);\n return set;\n}\nfunction getUpstream(cwd, branch) {\n try {\n return execFileSync(\"git\", [\n \"rev-parse\",\n \"--abbrev-ref\",\n `${branch}@{upstream}`\n ], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: 5e3\n }).toString().trim() || null;\n } catch {\n return null;\n }\n}\nfunction resolveCommit(cwd, rev) {\n try {\n return execFileSync(\"git\", [\n \"rev-parse\",\n \"--verify\",\n \"--quiet\",\n `${rev}^{commit}`\n ], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: 5e3\n }).toString().trim() || null;\n } catch {\n return null;\n }\n}\nfunction branchCarriesOtherFiles(cwd, allowed) {\n const toplevel = getRepoTopLevel(cwd);\n if (toplevel === null) return null;\n try {\n const defaultBranch = getConfiguredDefaultBranch(toplevel) ?? getRemoteDefaultBranch(toplevel) ?? \"main\";\n const mergeBase = execFileSync(\"git\", [\n \"merge-base\",\n \"HEAD\",\n `origin/${defaultBranch}`\n ], {\n cwd: toplevel,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n if (!mergeBase) return null;\n const names = (args) => execFileSync(\"git\", args, {\n cwd: toplevel,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().split(\"\\n\").filter((line) => line.length > 0);\n return [...names([\n \"diff\",\n \"--name-only\",\n mergeBase\n ]), ...names([\n \"ls-files\",\n \"--others\",\n \"--exclude-standard\"\n ])].some((name) => !allowed.includes(name));\n } catch {\n return null;\n }\n}\nfunction isPrimaryWorktree(cwd) {\n try {\n const gitDir = execFileSync(\"git\", [\"rev-parse\", \"--absolute-git-dir\"], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n const commonRaw = execFileSync(\"git\", [\"rev-parse\", \"--git-common-dir\"], {\n cwd,\n stdio: [\n \"ignore\",\n \"pipe\",\n \"ignore\"\n ],\n timeout: GIT_TIMEOUT_MS\n }).toString().trim();\n if (!gitDir || !commonRaw) return false;\n const commonDir = resolve(cwd, commonRaw);\n return realpathSync(gitDir) === realpathSync(commonDir);\n } catch {\n return false;\n }\n}\n\n// src/lib/git-short-options.ts\nconst VALUE_TAKING_LETTERS = {\n switch: /* @__PURE__ */ new Set([\"c\", \"C\"]),\n checkout: /* @__PURE__ */ new Set([\"b\", \"B\"]),\n branch: /* @__PURE__ */ new Set([\"u\"]),\n fetch: /* @__PURE__ */ new Set([\"o\", \"j\"])\n};\nfunction splitShortOptionCluster(token, sub) {\n if (!token.startsWith(\"-\") || token.startsWith(\"--\") || token.length <= 1) return;\n const valueLetters = VALUE_TAKING_LETTERS[sub];\n const letters = [];\n const chars = token.slice(1);\n for (let i = 0; i < chars.length; i++) {\n const ch = chars[i];\n letters.push(ch);\n if (valueLetters.has(ch)) return {\n letters,\n attachedValue: chars.slice(i + 1)\n };\n }\n return { letters };\n}\n\n// src/lib/path-scope.ts\nfunction pathFlavorFor(base) {\n return /^[a-zA-Z]:[\\\\/]/.test(base) ? path.win32 : path.posix;\n}\nfunction resolveIn(base, target) {\n return pathFlavorFor(base).resolve(base, target);\n}\nfunction isWithin(dir, target) {\n const pp = pathFlavorFor(dir);\n const rel = pp.relative(dir, target);\n if (rel === \"\") return true;\n if (rel === \"..\" || rel.startsWith(\"..\" + pp.sep)) return false;\n return !pp.isAbsolute(rel);\n}\nfunction samePath(a, b) {\n return pathFlavorFor(a).relative(a, b) === \"\";\n}\nfunction targetsGitDir(filePath, cwd) {\n const pp = pathFlavorFor(cwd);\n const resolved = resolveIn(cwd, filePath);\n if (!isWithin(cwd, resolved)) return false;\n const rel = pp.relative(cwd, resolved);\n if (rel === \"\") return false;\n return rel.split(pp.sep).includes(\".git\");\n}\nfunction targetsNodeModules(filePath, cwd) {\n return resolveIn(cwd, filePath).split(/[/\\\\]/).includes(\"node_modules\");\n}\n\n// src/rules.ts\nconst GIT_FLAGS_WITH_ARG = /* @__PURE__ */ new Set([\n \"-C\",\n \"-c\",\n \"--git-dir\",\n \"--work-tree\"\n]);\nfunction getGitSubcommand(tokens) {\n const args = tokens.slice(1);\n for (let i = 0; i < args.length; i++) {\n const t = args[i];\n if (GIT_FLAGS_WITH_ARG.has(t)) {\n i++;\n continue;\n }\n if (t.startsWith(\"-\")) continue;\n return t;\n }\n}\nconst WORKTREE_ADVICE = \"You're creating a feature branch in the primary worktree. An isolated worktree keeps this work independent of other windows, and with no commits on this branch yet, converting is cheap -- `git worktree add ../<dir> -b <branch>` (a sibling outside the repo, with its own dependency install). Claude Code keeps this session inside its own working tree, so the work continues in a new session opened in the sibling worktree. If you cannot open a session there, stay in the primary checkout on this branch and check `git branch --show-current` before each commit.\";\nfunction isGitBranchCreation(tokens) {\n const sub = getGitSubcommand(tokens);\n if (sub !== \"checkout\" && sub !== \"switch\") return false;\n const after = tokens.slice(tokens.indexOf(sub) + 1);\n const creationLetters = sub === \"checkout\" ? [\"b\", \"B\"] : [\"c\", \"C\"];\n return after.some((t) => {\n const cluster = splitShortOptionCluster(t, sub);\n return cluster !== void 0 && cluster.letters.some((l) => creationLetters.includes(l));\n });\n}\nfunction worktreeAdvice(tokens, ctx) {\n return isGitBranchCreation(tokens) && isPrimaryWorktree(ctx.cwd) ? WORKTREE_ADVICE : void 0;\n}\nconst GIT_FORCE_CREATE_LETTER = {\n switch: \"C\",\n checkout: \"B\"\n};\nconst GIT_FORCE_CREATE_LONG = {\n flag: \"--force-create\",\n shortest: \"--force-\"\n};\nfunction gitForceCreateTargets(after, letterSub) {\n const letter = GIT_FORCE_CREATE_LETTER[letterSub];\n const longFlag = GIT_FORCE_CREATE_LONG;\n const targets = [];\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (t === void 0) continue;\n if (letterSub === \"switch\") {\n const [flag, ...rest] = t.split(\"=\");\n if (flag !== void 0 && flag.length >= longFlag.shortest.length && longFlag.flag.startsWith(flag)) {\n const target = rest.length > 0 ? rest.join(\"=\") : after[i + 1];\n if (target !== void 0) targets.push(target);\n continue;\n }\n }\n const cluster = splitShortOptionCluster(t, letterSub);\n if (cluster === void 0 || !cluster.letters.includes(letter)) continue;\n if (cluster.attachedValue !== void 0 && cluster.attachedValue !== \"\") {\n targets.push(cluster.attachedValue);\n continue;\n }\n const next = after[i + 1];\n if (next !== void 0) targets.push(next);\n }\n return targets;\n}\nfunction gitCommandForceCreateTargets(tokens) {\n const sub = getGitSubcommand(tokens);\n if (sub === \"switch\" || sub === \"checkout\") return gitForceCreateTargets(tokens.slice(tokens.indexOf(sub) + 1), sub);\n if (sub === \"worktree\") {\n const worktreeIdx = tokens.indexOf(\"worktree\");\n if (tokens[worktreeIdx + 1] !== \"add\") return [];\n return gitForceCreateTargets(tokens.slice(worktreeIdx + 2), \"checkout\");\n }\n return [];\n}\nfunction isGitProtectedBranchForceCreate(tokens, ctx) {\n const targets = gitCommandForceCreateTargets(tokens);\n if (targets.length === 0) return false;\n const protectedSet = getProtectedBranches(ctx.cwd, ctx.repoProtectedBranches ?? []);\n return targets.some((t) => protectedSet.has(t));\n}\nfunction isGitProtectedBranchRefWrite(tokens, ctx) {\n const sub = getGitSubcommand(tokens);\n if (sub !== \"branch\") return false;\n const { flags, positionals } = splitGitBranchArgs(tokens.slice(tokens.indexOf(sub) + 1));\n if (positionals.length === 0) return false;\n let deleteMode = false;\n let renameMode = false;\n let copyMode = false;\n let forceMode = false;\n for (const flag of flags) {\n if (flag.letters !== void 0) {\n if (flag.letters.includes(\"d\") || flag.letters.includes(\"D\")) deleteMode = true;\n if (flag.letters.includes(\"m\") || flag.letters.includes(\"M\")) renameMode = true;\n if (flag.letters.includes(\"c\") || flag.letters.includes(\"C\")) copyMode = true;\n if (flag.letters.includes(\"f\") || flag.letters.includes(\"M\") || flag.letters.includes(\"C\")) forceMode = true;\n continue;\n }\n if (flag.name === \"delete\") deleteMode = true;\n if (flag.name === \"move\") renameMode = true;\n if (flag.name === \"copy\") copyMode = true;\n if (flag.name === \"force\") forceMode = true;\n }\n const protectedSet = getProtectedBranches(ctx.cwd, ctx.repoProtectedBranches ?? []);\n if (deleteMode && positionals.some((p) => protectedSet.has(p))) return true;\n if (renameMode && positionals.length >= 2 && protectedSet.has(positionals[0])) return true;\n if (forceMode) {\n const destination = renameMode || copyMode ? positionals[positionals.length - 1] : positionals[0];\n if (destination !== void 0 && protectedSet.has(destination)) return true;\n }\n return false;\n}\nfunction refspecDestination(refspec) {\n const spec = refspec.startsWith(\"+\") ? refspec.slice(1) : refspec;\n const colon = spec.lastIndexOf(\":\");\n return (colon === -1 ? spec : spec.slice(colon + 1)).replace(/^refs\\/heads\\//, \"\");\n}\nconst GIT_BRANCH_VALUE_FLAG_NAMES = /* @__PURE__ */ new Set([\n \"contains\",\n \"no-contains\",\n \"merged\",\n \"no-merged\",\n \"points-at\",\n \"sort\",\n \"format\",\n \"set-upstream-to\"\n]);\nfunction splitGitBranchArgs(after) {\n const flags = [];\n const positionals = [];\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (t === void 0) continue;\n if (!t.startsWith(\"-\")) {\n positionals.push(t);\n continue;\n }\n if (t.startsWith(\"--\") && t !== \"--\") {\n const eq = t.indexOf(\"=\");\n const name = eq > 0 ? t.slice(2, eq) : t.slice(2);\n flags.push({\n raw: t,\n name\n });\n if (eq < 0 && GIT_BRANCH_VALUE_FLAG_NAMES.has(name)) i++;\n continue;\n }\n const cluster = splitShortOptionCluster(t, \"branch\");\n if (cluster === void 0) {\n flags.push({ raw: t });\n continue;\n }\n flags.push({\n raw: t,\n letters: cluster.letters\n });\n if (cluster.attachedValue === \"\") i++;\n }\n return {\n flags,\n positionals\n };\n}\nconst GIT_FETCH_VALUE_FLAG_NAMES = /* @__PURE__ */ new Set([\n \"depth\",\n \"deepen\",\n \"shallow-since\",\n \"shallow-exclude\",\n \"negotiation-tip\",\n \"filter\",\n \"jobs\",\n \"server-option\",\n \"upload-pack\",\n \"refmap\",\n \"submodule-prefix\",\n \"recurse-submodules-default\"\n]);\nfunction splitGitFetchArgs(after) {\n const flags = [];\n const positionals = [];\n const refmaps = [];\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (t === void 0) continue;\n if (!t.startsWith(\"-\")) {\n positionals.push(t);\n continue;\n }\n if (t === \"--\") {\n flags.push({ raw: t });\n continue;\n }\n if (t.startsWith(\"--\")) {\n const eq = t.indexOf(\"=\");\n const name = eq > 0 ? t.slice(2, eq) : t.slice(2);\n flags.push({\n raw: t,\n name\n });\n if (name === \"refmap\") {\n if (eq > 0) refmaps.push(t.slice(eq + 1));\n else if (after[i + 1] !== void 0) refmaps.push(after[i + 1]);\n }\n if (eq < 0 && GIT_FETCH_VALUE_FLAG_NAMES.has(name)) i++;\n continue;\n }\n const cluster = splitShortOptionCluster(t, \"fetch\");\n if (cluster === void 0) {\n flags.push({ raw: t });\n continue;\n }\n flags.push({\n raw: t,\n letters: cluster.letters\n });\n if (cluster.attachedValue === \"\") i++;\n }\n return {\n flags,\n positionals,\n refmaps\n };\n}\nfunction fetchRefspecTarget(spec) {\n const body = spec.startsWith(\"+\") ? spec.slice(1) : spec;\n if (body.startsWith(\"^\")) return { kind: \"none\" };\n if (!body.includes(\":\")) return { kind: \"none\" };\n const destination = refspecDestination(body);\n if (destination === \"\") return { kind: \"none\" };\n if (destination.startsWith(\"refs/remotes/\")) return { kind: \"tracking\" };\n if (destination.startsWith(\"refs/\")) return { kind: \"other\" };\n return {\n kind: \"branch\",\n name: destination\n };\n}\nfunction globToAnchoredRegex(glob) {\n const escaped = glob.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`^${escaped.replace(/\\\\\\*/g, \".*\")}$`);\n}\nfunction isProtectedFetchBranch(name, protectedSet) {\n if (protectedSet.has(name)) return true;\n if (!name.includes(\"*\")) return false;\n const pattern = globToAnchoredRegex(name);\n for (const member of protectedSet) if (pattern.test(member)) return true;\n return false;\n}\nfunction isGitProtectedBranchFetchWrite(tokens, ctx) {\n const sub = getGitSubcommand(tokens);\n if (sub !== \"fetch\") return false;\n const { positionals, refmaps } = splitGitFetchArgs(tokens.slice(tokens.indexOf(sub) + 1));\n const protectedSet = getProtectedBranches(ctx.cwd, ctx.repoProtectedBranches ?? []);\n return [...positionals, ...refmaps].some((spec) => {\n const target = fetchRefspecTarget(spec);\n if (target.kind !== \"branch\" || target.name === void 0) return false;\n return isProtectedFetchBranch(target.name, protectedSet);\n });\n}\nfunction isGitProtectedUpdateRef(tokens, ctx) {\n const after = tokens.slice(tokens.indexOf(\"update-ref\") + 1);\n let ref;\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (t === \"-m\") {\n i++;\n continue;\n }\n if (t.startsWith(\"-\")) continue;\n ref = t;\n break;\n }\n if (ref === void 0) return false;\n return getProtectedBranches(ctx.cwd, ctx.repoProtectedBranches ?? []).has(ref.replace(/^refs\\/heads\\//, \"\"));\n}\nfunction gitEffectiveCwd(tokens, cwd) {\n let dir = cwd;\n const args = tokens.slice(1);\n for (let i = 0; i < args.length; i++) {\n const t = args[i];\n if (t === \"-C\") {\n const next = args[i + 1];\n if (next !== void 0) dir = path.resolve(dir, next);\n i++;\n continue;\n }\n if (GIT_FLAGS_WITH_ARG.has(t)) {\n i++;\n continue;\n }\n if (!t.startsWith(\"-\")) break;\n }\n return dir;\n}\nconst GIT_SWITCH_NEUTRAL_FLAGS = /* @__PURE__ */ new Set([\n \"-q\",\n \"--quiet\",\n \"-f\",\n \"--force\",\n \"--discard-changes\",\n \"-m\",\n \"--merge\",\n \"--no-track\",\n \"--progress\",\n \"--no-progress\",\n \"--guess\",\n \"--no-guess\",\n \"--ignore-other-worktrees\",\n \"--recurse-submodules\",\n \"--no-recurse-submodules\"\n]);\nconst GIT_SWITCH_CREATE_FLAGS = /* @__PURE__ */ new Set([\n \"--create\",\n \"--force-create\",\n \"--orphan\"\n]);\nconst GIT_CHECKOUT_PATH_FLAGS = /* @__PURE__ */ new Set([\n \"--ours\",\n \"--theirs\",\n \"-p\",\n \"--patch\",\n \"--conflict\",\n \"--pathspec-from-file\",\n \"--pathspec-file-nul\",\n \"--overlay\",\n \"--no-overlay\"\n]);\nconst GIT_SWITCH_NEUTRAL_LETTERS = /* @__PURE__ */ new Set([\n \"q\",\n \"f\",\n \"m\"\n]);\nfunction switchTarget(after, sub, isCheckoutBranch) {\n if (sub === \"checkout\" && after.includes(\"--\")) return void 0;\n const createLetters = sub === \"checkout\" ? [\"b\", \"B\"] : [\"c\", \"C\"];\n const known = (l) => GIT_SWITCH_NEUTRAL_LETTERS.has(l) || createLetters.includes(l);\n const positionals = [];\n let created;\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (!t.startsWith(\"-\")) {\n positionals.push(t);\n continue;\n }\n if (GIT_SWITCH_NEUTRAL_FLAGS.has(t)) continue;\n const eq = t.indexOf(\"=\");\n if (sub === \"checkout\" && GIT_CHECKOUT_PATH_FLAGS.has(eq === -1 ? t : t.slice(0, eq))) return;\n if (GIT_SWITCH_CREATE_FLAGS.has(eq === -1 ? t : t.slice(0, eq))) {\n created = eq === -1 ? after[++i] : t.slice(eq + 1);\n continue;\n }\n const cluster = splitShortOptionCluster(t, sub);\n if (cluster === void 0 || !cluster.letters.every(known)) return null;\n if (cluster.letters.some((l) => createLetters.includes(l))) created = cluster.attachedValue ? cluster.attachedValue : after[++i];\n }\n if (created !== void 0) return created;\n if (positionals.length !== 1) return void 0;\n const target = positionals[0];\n if (target === \"HEAD\" || target === \"@\") return void 0;\n if (sub === \"checkout\" && !isCheckoutBranch(target)) return void 0;\n return target;\n}\nfunction branchSwitch(tokens, ctx, resolved) {\n const sub = getGitSubcommand(tokens);\n if (sub !== \"switch\" && sub !== \"checkout\") return void 0;\n const dir = gitEffectiveCwd(tokens, ctx.cwd);\n const isCheckoutBranch = (name) => !resolved || getProtectedBranches(dir, ctx.repoProtectedBranches ?? []).has(name) || resolveCommit(dir, name) !== null;\n const target = switchTarget(tokens.slice(tokens.indexOf(sub) + 1), sub, isCheckoutBranch);\n if (!resolved) return target === void 0 ? void 0 : {\n dir,\n branch: null\n };\n return target === void 0 ? void 0 : {\n dir,\n branch: target\n };\n}\nconst GIT_CHECKED_OUT_WRITES = /* @__PURE__ */ new Set([\n \"commit\",\n \"merge\",\n \"rebase\",\n \"cherry-pick\",\n \"revert\",\n \"am\",\n \"pull\"\n]);\nfunction subcommandArgs(tokens, sub, valueFlags = /* @__PURE__ */ new Set()) {\n const after = tokens.slice(tokens.indexOf(sub) + 1);\n const flags = [];\n const positionals = [];\n for (let i = 0; i < after.length; i++) {\n const t = after[i];\n if (!t.startsWith(\"-\")) {\n positionals.push(t);\n continue;\n }\n flags.push(t);\n if (valueFlags.has(t)) i++;\n }\n return {\n flags,\n positionals\n };\n}\nconst GIT_PUSH_VALUE_FLAGS = /* @__PURE__ */ new Set([\n \"-o\",\n \"--push-option\",\n \"--repo\",\n \"--receive-pack\",\n \"--exec\"\n]);\nfunction isMergeFastForwardFromUpstream(tokens, upstream) {\n const { flags, positionals } = subcommandArgs(tokens, \"merge\");\n if (!flags.includes(\"--ff-only\") || positionals.length !== 1) return false;\n const ref = positionals[0];\n return ref === \"@{u}\" || ref === \"@{upstream}\" || upstream !== null && ref === upstream;\n}\nconst GIT_PULL_NO_REBASE = /* @__PURE__ */ new Set([\n \"--rebase=false\",\n \"--rebase=no\",\n \"--rebase=off\",\n \"--rebase=0\"\n]);\nfunction isPullFromUpstream(tokens, upstream) {\n const { flags, positionals } = subcommandArgs(tokens, \"pull\");\n if (flags.some((t) => t.startsWith(\"--rebase\") && !GIT_PULL_NO_REBASE.has(t) || t === \"--no-ff\" || !t.startsWith(\"--\") && t.slice(1).includes(\"r\"))) return false;\n if (positionals.length === 0) return true;\n if (positionals.length !== 2 || upstream === null) return false;\n const [remote, branch] = positionals;\n return `${remote}/${branch.replace(/^refs\\/heads\\//, \"\")}` === upstream;\n}\nfunction isRefMovingReset(tokens, cwd, head) {\n if (tokens.slice(tokens.indexOf(\"reset\") + 1).includes(\"--\")) return false;\n const { positionals } = subcommandArgs(tokens, \"reset\");\n if (positionals.length !== 1) return false;\n if (head !== \"HEAD\" && /^(HEAD|@)/.test(positionals[0])) return false;\n const target = resolveCommit(cwd, positionals[0]);\n if (target === null) return false;\n return target !== resolveCommit(cwd, head);\n}\nfunction pushDestinations(tokens, current) {\n const { positionals } = subcommandArgs(tokens, \"push\", GIT_PUSH_VALUE_FLAGS);\n const refspecs = positionals.slice(1);\n if (refspecs.length === 0) return null;\n const names = [];\n for (const spec of refspecs) {\n const dst = refspecDestination(spec);\n if (dst === \"HEAD\" || dst === \"@\") {\n if (current !== null) names.push(current);\n continue;\n }\n names.push(dst);\n }\n return names;\n}\nconst GIT_PUSH_EVERY_BRANCH = /* @__PURE__ */ new Set([\n \"--all\",\n \"--branches\",\n \"--mirror\"\n]);\nfunction leavesRefInPlace(tokens, sub) {\n const { flags } = subcommandArgs(tokens, sub);\n if (flags.includes(\"--abort\") || flags.includes(\"--quit\")) return true;\n return sub === \"commit\" && flags.includes(\"--dry-run\");\n}\nfunction movesProtectedRef(tokens, ctx) {\n const sub = getGitSubcommand(tokens);\n if (sub === void 0) return false;\n if (sub === \"switch\" || sub === \"checkout\" || sub === \"worktree\") return isGitProtectedBranchForceCreate(tokens, ctx);\n if (sub === \"branch\") return isGitProtectedBranchRefWrite(tokens, ctx);\n if (sub === \"fetch\") return isGitProtectedBranchFetchWrite(tokens, ctx);\n if (sub === \"update-ref\") return isGitProtectedUpdateRef(tokens, ctx);\n if (sub !== \"push\" && sub !== \"reset\" && !GIT_CHECKED_OUT_WRITES.has(sub)) return false;\n const cwd = gitEffectiveCwd(tokens, ctx.cwd);\n const pending = ctx.pendingBranches?.[cwd];\n const current = pending ? pending.branch : getCurrentBranch(cwd);\n const protectedSet = getProtectedBranches(cwd, ctx.repoProtectedBranches ?? []);\n const onProtected = current !== null && protectedSet.has(current);\n if (sub === \"push\") {\n const { flags } = subcommandArgs(tokens, \"push\", GIT_PUSH_VALUE_FLAGS);\n if (flags.some((f) => GIT_PUSH_EVERY_BRANCH.has(f))) return true;\n const destinations = pushDestinations(tokens, current);\n if (destinations === null) {\n if (flags.includes(\"--tags\")) return false;\n return onProtected;\n }\n return destinations.some((d) => protectedSet.has(d));\n }\n if (!onProtected) return false;\n if (leavesRefInPlace(tokens, sub)) return false;\n if (sub === \"reset\") return isRefMovingReset(tokens, cwd, pending ? current : \"HEAD\");\n if (sub === \"merge\" || sub === \"pull\") {\n const upstream = getUpstream(cwd, current);\n if (sub === \"merge\" && isMergeFastForwardFromUpstream(tokens, upstream)) return false;\n if (sub === \"pull\" && isPullFromUpstream(tokens, upstream)) return false;\n }\n return true;\n}\nconst PNPM_BUILTINS = /* @__PURE__ */ new Set([\n \"install\",\n \"i\",\n \"add\",\n \"remove\",\n \"rm\",\n \"uninstall\",\n \"un\",\n \"update\",\n \"up\",\n \"upgrade\",\n \"list\",\n \"ls\",\n \"ll\",\n \"la\",\n \"why\",\n \"view\",\n \"info\",\n \"show\",\n \"outdated\",\n \"audit\",\n \"licenses\",\n \"init\",\n \"create\",\n \"link\",\n \"unlink\",\n \"pack\",\n \"publish\",\n \"config\",\n \"set\",\n \"get\",\n \"store\",\n \"cache\",\n \"rebuild\",\n \"rb\",\n \"prune\",\n \"dedupe\",\n \"dlx\",\n \"exec\",\n \"run\",\n \"patch\",\n \"patch-commit\",\n \"recursive\",\n \"-r\"\n]);\nconst NPM_READ_OPS = /* @__PURE__ */ new Set([\n \"view\",\n \"info\",\n \"show\"\n]);\nfunction isNpmReadOp(tokens) {\n const sub = tokens[1];\n return sub !== void 0 && NPM_READ_OPS.has(sub);\n}\nfunction getNpmRedirectReason(tokens) {\n const sub = tokens[1];\n const BASE = \"This project uses pnpm.\";\n if (!sub) return `${BASE} Use \\`pnpm\\` instead of npm.`;\n if (sub === \"install\" || sub === \"i\" || sub === \"ci\") {\n if (tokens.slice(2).some((t) => !t.startsWith(\"-\"))) return `${BASE} Use \\`pnpm add <pkg>\\` instead of \\`npm install <pkg>\\`.`;\n return `${BASE} Use \\`pnpm install\\` instead of npm.`;\n }\n if (sub === \"add\") return `${BASE} Use \\`pnpm add <pkg>\\` instead of npm.`;\n if (sub === \"uninstall\" || sub === \"remove\" || sub === \"rm\" || sub === \"un\" || sub === \"r\") return `${BASE} Use \\`pnpm remove <pkg>\\` instead of npm.`;\n if (sub === \"run\" || sub === \"run-script\") return `${BASE} Use \\`pnpm run <script>\\` or \\`pnpm <script>\\` instead of npm.`;\n if (sub === \"test\" || sub === \"t\" || sub === \"tst\") return `${BASE} Use \\`pnpm test\\` instead of npm.`;\n if (sub === \"start\") return `${BASE} Use \\`pnpm start\\` instead of npm.`;\n if (sub === \"stop\") return `${BASE} Use \\`pnpm stop\\` instead of npm.`;\n if (sub === \"restart\") return `${BASE} Use \\`pnpm restart\\` instead of npm.`;\n if (sub === \"exec\") return `${BASE} Use \\`pnpm exec <cmd>\\` instead of npm.`;\n if (sub === \"list\" || sub === \"ls\" || sub === \"ll\" || sub === \"la\") return `${BASE} Use \\`pnpm list\\` instead of npm.`;\n if (sub === \"why\") return `${BASE} Use \\`pnpm why\\` instead of npm.`;\n if (sub === \"outdated\") return `${BASE} Use \\`pnpm outdated\\` instead of npm.`;\n if (sub === \"audit\") return `${BASE} Use \\`pnpm audit\\` instead of npm.`;\n if (sub === \"update\" || sub === \"up\" || sub === \"upgrade\") return `${BASE} Use \\`pnpm update\\` instead of npm.`;\n if (sub === \"init\") return `${BASE} Use \\`pnpm init\\` instead of npm.`;\n if (sub === \"publish\") return `${BASE} Use \\`pnpm publish\\` instead of npm.`;\n if (sub === \"link\") return `${BASE} Use \\`pnpm link\\` instead of npm.`;\n if (sub === \"unlink\") return `${BASE} Use \\`pnpm unlink\\` instead of npm.`;\n if (sub === \"pack\") return `${BASE} Use \\`pnpm pack\\` instead of npm.`;\n if (sub === \"cache\") return `${BASE} Use \\`pnpm store\\` instead of \\`npm cache\\`.`;\n if (sub === \"config\" || sub === \"set\" || sub === \"get\") return `${BASE} Use \\`pnpm config\\` instead of npm.`;\n return `${BASE} Use the equivalent pnpm command instead of npm.`;\n}\nconst LAST_POSITIONAL_DEST = /* @__PURE__ */ new Set([\n \"cp\",\n \"mv\",\n \"rsync\",\n \"install\",\n \"ln\"\n]);\nconst ALL_POSITIONAL_DEST = /* @__PURE__ */ new Set([\"tee\", \"truncate\"]);\nfunction explicitTargetDirectory(rest) {\n for (const [i, t] of rest.entries()) {\n if (t === \"-t\" || t === \"--target-directory\") return rest[i + 1] ?? null;\n if (t.startsWith(\"--target-directory=\")) return t.slice(19);\n }\n return null;\n}\nconst OUTPUT_REDIRECT = /^(?:\\d*|&)>{1,2}$/;\nconst OUTPUT_REDIRECT_ATTACHED = /^(?:\\d*|&)>{1,2}(.+)$/;\nconst INPUT_REDIRECT = /^\\d*<$/;\nconst INPUT_REDIRECT_ATTACHED = /^\\d*<([^<].*)$/;\nfunction spacedRedirectDirection(token) {\n if (OUTPUT_REDIRECT.test(token)) return \"out\";\n if (INPUT_REDIRECT.test(token)) return \"in\";\n return null;\n}\nfunction splitRedirects(tokens) {\n const redirects = [];\n const rest = [];\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i];\n const spaced = spacedRedirectDirection(t);\n if (spaced !== null) {\n const next = tokens[i + 1];\n if (next !== void 0) redirects.push({\n direction: spaced,\n target: next\n });\n i++;\n continue;\n }\n const out = OUTPUT_REDIRECT_ATTACHED.exec(t);\n if (out) {\n redirects.push({\n direction: \"out\",\n target: out[1]\n });\n continue;\n }\n const input = INPUT_REDIRECT_ATTACHED.exec(t);\n if (input) {\n redirects.push({\n direction: \"in\",\n target: input[1]\n });\n continue;\n }\n rest.push(t);\n }\n return {\n redirects,\n rest\n };\n}\nfunction redirectTargets(tokens, direction) {\n return splitRedirects(tokens).redirects.filter((r) => r.direction === direction).map((r) => r.target);\n}\nfunction writeDestinations(tokens) {\n const cmd = path.basename(tokens[0] ?? \"\");\n const rest = tokens.slice(1);\n const dests = redirectTargets(tokens, \"out\");\n if (cmd === \"dd\") dests.push(...rest.filter((t) => t.startsWith(\"of=\")).map((t) => t.slice(3)));\n else if (cmd === \"sed\") {\n if (rest.some((t) => t === \"--in-place\" || /^-[a-zA-Z]*i/.test(t))) dests.push(...rest.filter((t) => !t.startsWith(\"-\")));\n } else if (ALL_POSITIONAL_DEST.has(cmd)) dests.push(...rest.filter((t) => !t.startsWith(\"-\")));\n else if (LAST_POSITIONAL_DEST.has(cmd)) {\n if (cmd === \"cp\" && rest.includes(\"--remove-destination\")) return dests;\n const targetDir = explicitTargetDirectory(rest);\n if (targetDir !== null) dests.push(targetDir);\n else {\n const last = rest.findLast((t) => !t.startsWith(\"-\"));\n if (last !== void 0) dests.push(last);\n }\n }\n return dests;\n}\nfunction writesIntoNodeModules(tokens, ctx) {\n return writeDestinations(tokens).some((d) => targetsNodeModules(d, ctx.cwd));\n}\nconst NODE_MODULES_WRITE_REASON = \"Don't write into node_modules/. Its files are hardlinks into pnpm's global store, so overwriting one in place (plain `cp`, `>` redirect, `sed -i`, ...) writes through the link and corrupts that package for every project on this machine -- silently, since the directory you wrote into ends up fine. To test a local build as an installed dependency, run it directly (`node packages/<pkg>/dist/bin.mjs <cmd>`), or install into a scratch tree with an isolated store (`pnpm add --store-dir <scratch> <pkg>`). If you must replace a file in place, `cp --remove-destination` is safe -- it unlinks the target first. Run `pnpm store status` to check whether the store is already damaged.\";\nfunction isChmod777(tokens) {\n return tokens.some((t) => t === \"777\" || t === \"0777\");\n}\nfunction isGitForcePush(tokens) {\n const pushIdx = tokens.indexOf(\"push\");\n if (pushIdx === -1) return false;\n return tokens.slice(pushIdx + 1).some((t) => t === \"--force\" || t === \"-f\");\n}\nconst ENV_READ_FILE_COMMANDS = /* @__PURE__ */ new Set([\n \"cat\",\n \"head\",\n \"tail\",\n \"less\",\n \"more\",\n \"source\",\n \".\"\n]);\nconst GREP_FAMILY_COMMANDS = /* @__PURE__ */ new Set([\n \"grep\",\n \"rg\",\n \"ag\"\n]);\nfunction grepFileOperands(rest) {\n const files = [];\n let patternAccountedFor = false;\n let optionsEnded = false;\n for (let i = 0; i < rest.length; i++) {\n const t = rest[i];\n if (!optionsEnded && t === \"--\") {\n optionsEnded = true;\n continue;\n }\n if (!optionsEnded) {\n if (t === \"-f\" || t === \"--file\") {\n const value = rest[i + 1];\n if (value !== void 0) {\n files.push(value);\n i++;\n }\n patternAccountedFor = true;\n continue;\n }\n if (t.startsWith(\"--file=\")) {\n files.push(t.slice(7));\n patternAccountedFor = true;\n continue;\n }\n if (t.startsWith(\"-f\") && t !== \"-f\" && !t.startsWith(\"--\")) {\n files.push(t.slice(2));\n patternAccountedFor = true;\n continue;\n }\n if (t === \"-e\" || t === \"--regexp\") {\n i++;\n patternAccountedFor = true;\n continue;\n }\n if (t.startsWith(\"--regexp=\") || t.startsWith(\"-e\") && t !== \"-e\" && !t.startsWith(\"--\")) {\n patternAccountedFor = true;\n continue;\n }\n if (t.startsWith(\"-\")) continue;\n }\n if (!patternAccountedFor) {\n patternAccountedFor = true;\n continue;\n }\n files.push(t);\n }\n return files;\n}\nfunction envFileOperands(tokens) {\n const cmd = path.basename(tokens[0] ?? \"\");\n const { redirects, rest } = splitRedirects(tokens.slice(1));\n const operands = redirects.filter((r) => r.direction === \"in\").map((r) => r.target);\n if (GREP_FAMILY_COMMANDS.has(cmd)) operands.push(...grepFileOperands(rest));\n else if (ENV_READ_FILE_COMMANDS.has(cmd)) operands.push(...rest.filter((t) => !t.startsWith(\"-\")));\n return operands;\n}\nconst HEALTH_CEILING_FILES = [\"health-baseline.json\", \".tooling.json\"];\nconst HEALTH_RAISE_REASON = \"Run `pnpm exec bst health:raise` to raise only what this branch crossed. `--update-baseline --reset` records every outlier, including the ones already on the default branch.\";\nfunction isHealthBaselineReset(tokens) {\n return tokens.includes(\"health:check\") && tokens.includes(\"--update-baseline\") && tokens.includes(\"--reset\");\n}\nfunction raiseTravelsWithCode(cwd) {\n return branchCarriesOtherFiles(cwd, HEALTH_CEILING_FILES) === true;\n}\nconst denyRules = [\n {\n name: \"sudo\",\n match: /^sudo$/,\n action: \"deny\",\n reason: \"Don't use sudo. If you need elevated permissions, ask me to do it manually.\"\n },\n {\n name: \"git-force-push\",\n match: /^git$/,\n action: \"deny\",\n when: (tokens) => isGitForcePush(tokens),\n reason: \"Use `git push --force-with-lease` instead of `--force`.\"\n },\n {\n name: \"git-protected-branch-write\",\n match: /^git$/,\n action: \"deny\",\n when: (tokens, ctx) => movesProtectedRef(tokens, ctx),\n reason: \"This would move a protected branch (main, master, the remote's default branch, or one listed in .claude/hooks/bst-hook.settings.json#protectedBranches). Work on a feature branch in a worktree: `git worktree add ../<repo>-<topic> -b feat/<topic>`, then commit and push there. To bring `main` up to date, use `git pull --ff-only`.\"\n },\n {\n name: \"chmod-777\",\n match: /^chmod$/,\n action: \"deny\",\n when: (tokens) => isChmod777(tokens),\n reason: \"Don't use 777 permissions. Use more restrictive permissions.\"\n },\n {\n name: \"node-modules-write\",\n match: /./,\n action: \"deny\",\n when: (tokens, ctx) => writesIntoNodeModules(tokens, ctx),\n reason: NODE_MODULES_WRITE_REASON\n },\n {\n name: \"env-file-read\",\n match: /./,\n action: \"deny\",\n when: (tokens) => envFileOperands(tokens).some(isEnvFile),\n reason: \"Don't read .env files. These contain secrets that should not appear in the conversation.\"\n },\n {\n name: \"env-file-write\",\n match: /./,\n action: \"deny\",\n when: (tokens) => redirectTargets(tokens, \"out\").some(isEnvFile),\n reason: \"Don't write to .env files. These contain secrets.\"\n },\n {\n name: \"health-baseline-reset\",\n match: /^bst$/,\n action: \"deny\",\n when: (tokens, ctx) => isHealthBaselineReset(tokens) && raiseTravelsWithCode(ctx.cwd),\n reason: HEALTH_RAISE_REASON\n },\n {\n name: \"npx-redirect\",\n match: /^npx$/,\n action: \"deny\",\n reason: \"This project uses pnpm. Use `pnpm dlx <pkg>` or `pnpm exec <cmd>` instead of npx.\"\n },\n {\n name: \"mise-self-update\",\n match: /^mise$/,\n action: \"deny\",\n when: (tokens) => tokens[1] === \"self-update\",\n reason: \"Don't self-update mise. The version is Renovate-managed; ask a human to bump the pin.\"\n }\n];\n\n// src/lib/script-resolver.ts\nconst PackageJsonSchema = object({ scripts: record(string(), unknown()) });\nfunction resolveScript(scriptName, cwd) {\n const scripts = readScripts(cwd);\n if (!scripts) return null;\n const main = scripts[scriptName];\n if (typeof main !== \"string\") return null;\n const pre = scripts[`pre${scriptName}`];\n const post = scripts[`post${scriptName}`];\n return {\n pre: typeof pre === \"string\" ? pre : null,\n main,\n post: typeof post === \"string\" ? post : null\n };\n}\nfunction resolveFilteredScript(scriptName, filterPkg, cwd) {\n const pkgDir = findWorkspacePackageDir(filterPkg, cwd);\n if (!pkgDir) return null;\n const script = resolveScript(scriptName, pkgDir);\n if (!script) return null;\n return {\n ...script,\n pkgDir\n };\n}\nfunction resolveRecursiveScripts(scriptName, rootDir) {\n const pkgDirs = listWorkspacePackageDirs(rootDir);\n if (!pkgDirs) return null;\n const results = [];\n for (const pkgDir of pkgDirs) {\n const resolved = resolveScript(scriptName, pkgDir);\n if (resolved) results.push({\n ...resolved,\n pkgDir\n });\n }\n return results;\n}\nfunction listWorkspacePackageDirs(rootDir) {\n const patterns = readWorkspacePatterns(rootDir);\n if (!patterns) return null;\n const dirs = [];\n for (const pattern of patterns) {\n if (!pattern.endsWith(\"/*\")) continue;\n const baseDir = pattern.slice(0, -2);\n const parentDir = resolve(rootDir, baseDir);\n let entries;\n try {\n entries = readdirSync(parentDir);\n } catch {\n continue;\n }\n for (const entry of entries) {\n const entryDir = join(parentDir, entry);\n try {\n if (!statSync(entryDir).isDirectory()) continue;\n } catch {\n continue;\n }\n dirs.push(entryDir);\n }\n }\n return dirs.length > 0 ? dirs : null;\n}\nfunction findWorkspacePackageDir(pkgName, rootDir) {\n const pkgDirs = listWorkspacePackageDirs(rootDir);\n if (!pkgDirs) return null;\n for (const entryDir of pkgDirs) {\n const name = readPackageName(entryDir);\n if (name === pkgName || name === `@${pkgName}`) return entryDir;\n if (entryDir.split(\"/\").pop() === pkgName) return entryDir;\n if (name) {\n if ((name.startsWith(\"@\") ? name.split(\"/\")[1] : name) === pkgName) return entryDir;\n }\n }\n return null;\n}\nfunction readWorkspacePatterns(rootDir) {\n try {\n const lines = readFileSync(join(rootDir, \"pnpm-workspace.yaml\"), \"utf-8\").split(\"\\n\");\n const packagesIdx = lines.findIndex((l) => /^packages\\s*:/.test(l));\n if (packagesIdx === -1) return null;\n const patterns = [];\n for (let i = packagesIdx + 1; i < lines.length; i++) {\n const line = lines[i];\n const match = /^\\s+-\\s+(.+)$/.exec(line);\n if (!match) break;\n patterns.push(match[1].trim().replace(/['\"`]/g, \"\"));\n }\n return patterns.length > 0 ? patterns : null;\n } catch {\n return null;\n }\n}\nconst PackageNameSchema = object({ name: string() });\nfunction readPackageName(dir) {\n try {\n const raw = readFileSync(join(dir, \"package.json\"), \"utf-8\");\n const result = PackageNameSchema.safeParse(JSON.parse(raw));\n if (!result.success) return null;\n return result.data.name;\n } catch {\n return null;\n }\n}\nfunction readScripts(cwd) {\n try {\n const raw = readFileSync(join(cwd, \"package.json\"), \"utf-8\");\n const result = PackageJsonSchema.safeParse(JSON.parse(raw));\n if (!result.success) return null;\n return result.data.scripts;\n } catch {\n return null;\n }\n}\n\n// src/lib/workspace-root.ts\nfunction findWorkspaceRoot(cwd) {\n let dir = resolve(cwd);\n while (true) {\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return dir;\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n// src/evaluate.ts\nconst MAX_EVAL_DEPTH = 5;\nfunction subshellBody(command) {\n if (!command.startsWith(\"(\") || !command.endsWith(\")\")) return null;\n let depth = 0;\n let quote = null;\n for (let i = 0; i < command.length; i++) {\n const ch = command[i];\n if (quote !== null) {\n if (ch === quote) quote = null;\n else if (ch === \"\\\\\" && quote === \"\\\"\") i++;\n continue;\n }\n if (ch === \"\\\\\") i++;\n else if (ch === \"'\" || ch === \"\\\"\") quote = ch;\n else if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n if (depth === 0) return i === command.length - 1 ? command.slice(1, -1) : null;\n }\n }\n return null;\n}\nfunction extractCdDir(segment, ctx) {\n const tokenResult = tokenize(segment);\n if (!tokenResult.ok || tokenResult.tokens.length !== 2) return null;\n const tokens = tokenResult.tokens;\n if (tokens[0] !== \"cd\") return null;\n const dir = tokens[1];\n if (path.isAbsolute(dir)) return dir;\n return path.resolve(ctx.cwd, dir);\n}\nfunction extractBranchSwitch(segment, ctx) {\n const tokenResult = tokenize(segment);\n if (!tokenResult.ok) return void 0;\n let tokens = tokenResult.tokens;\n let envSkipped = 0;\n while (envSkipped < tokens.length && /^\\w+=/.test(tokens[envSkipped])) envSkipped++;\n tokens = tokens.slice(envSkipped);\n if (tokens.length === 0 || path.basename(tokens[0]) !== \"git\") return void 0;\n return branchSwitch(tokens, ctx, checkInjection(tokens, segment).safe);\n}\nfunction evaluateCommand(command, ctx) {\n if (ctx.depth >= MAX_EVAL_DEPTH) return {\n action: \"none\",\n rule: null,\n reason: \"max evaluation depth exceeded\"\n };\n const trimmed = command.trim();\n if (!trimmed) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n const body = subshellBody(trimmed);\n if (body !== null) return evaluateCommand(body, {\n ...ctx,\n depth: ctx.depth + 1\n });\n const segments = splitCommand(trimmed);\n if (segments.length === 0) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n let firstNone = null;\n const currentCtx = { ...ctx };\n let unknownAfterNext;\n for (const segment of segments) {\n if (segment.operator === \"&&\") {\n const cdDir = extractCdDir(segment.command, currentCtx);\n if (cdDir) currentCtx.cwd = cdDir;\n }\n const result = evaluateSegment(segment.command, currentCtx);\n if (result.action === \"deny\") return result;\n if (!firstNone) firstNone = result;\n if (unknownAfterNext) {\n currentCtx.pendingBranches = {\n ...currentCtx.pendingBranches,\n [unknownAfterNext.dir]: unknownAfterNext\n };\n unknownAfterNext = void 0;\n }\n const switched = extractBranchSwitch(segment.command, currentCtx);\n if (switched) {\n const unknown = {\n dir: switched.dir,\n branch: null\n };\n if (segment.operator === \"&&\") currentCtx.pendingBranches = {\n ...currentCtx.pendingBranches,\n [switched.dir]: switched\n };\n else if (segment.operator === \"||\") unknownAfterNext = unknown;\n else currentCtx.pendingBranches = {\n ...currentCtx.pendingBranches,\n [switched.dir]: unknown\n };\n }\n }\n return firstNone ?? {\n action: \"none\",\n rule: null,\n reason: null\n };\n}\nfunction evaluateResolvedScript(resolved, ctx) {\n if (resolved.pre) {\n const preResult = evaluateCommand(resolved.pre, ctx);\n if (preResult.action === \"deny\") return preResult;\n }\n const mainResult = evaluateCommand(resolved.main, ctx);\n if (mainResult.action === \"deny\") return mainResult;\n if (resolved.post) {\n const postResult = evaluateCommand(resolved.post, ctx);\n if (postResult.action === \"deny\") return postResult;\n }\n return {\n action: \"none\",\n rule: null,\n reason: null\n };\n}\nfunction evaluateSegment(rawSegment, ctx) {\n const trimmed = rawSegment.trim();\n const body = subshellBody(trimmed);\n if (body !== null) return evaluateCommand(body, {\n ...ctx,\n depth: ctx.depth + 1\n });\n if (trimmed.startsWith(\"(\") && trimmed.endsWith(\")\")) return {\n action: \"none\",\n rule: null,\n reason: \"subshell\"\n };\n const tokenResult = tokenize(rawSegment);\n if (!tokenResult.ok) return {\n action: \"none\",\n rule: null,\n reason: tokenResult.error\n };\n let tokens = tokenResult.tokens;\n if (tokens.length === 0) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n let envSkipped = 0;\n while (envSkipped < tokens.length && /^\\w+=/.test(tokens[envSkipped])) envSkipped++;\n if (envSkipped >= tokens.length) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n tokens = tokens.slice(envSkipped);\n if (writesIntoNodeModules(tokens, ctx)) return {\n action: \"deny\",\n rule: \"node-modules-write\",\n reason: NODE_MODULES_WRITE_REASON\n };\n const injection = checkInjection(tokens, rawSegment);\n if (!injection.safe) return {\n action: \"none\",\n rule: null,\n reason: injection.reason\n };\n const SAFE_REDIRECT_TOKENS = /* @__PURE__ */ new Set([\n \"2>&1\",\n \"2>/dev/null\",\n \">/dev/null\",\n \"1>/dev/null\"\n ]);\n tokens = tokens.filter((t, i) => {\n if (SAFE_REDIRECT_TOKENS.has(t)) return false;\n if ((t === \">\" || t === \">>\") && tokens[i + 1] === \"/dev/null\") return false;\n if (t === \"/dev/null\" && i > 0 && (tokens[i - 1] === \">\" || tokens[i - 1] === \">>\")) return false;\n return true;\n });\n const cmdName = path.basename(tokens[0]);\n if (cmdName === \"command\" && tokens.length > 1) return evaluateCommand(joinTokens(tokens.slice(1)), {\n ...ctx,\n depth: ctx.depth + 1\n });\n if (cmdName === \"env\") {\n let envIdx = 1;\n while (envIdx < tokens.length && /^\\w+=/.test(tokens[envIdx])) envIdx++;\n if (envIdx >= tokens.length) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n return evaluateCommand(joinTokens(tokens.slice(envIdx)), {\n ...ctx,\n depth: ctx.depth + 1\n });\n }\n if (cmdName === \"pnpm\") return evaluatePnpm(tokens, ctx);\n if (cmdName === \"npm\") return evaluateNpm(tokens);\n if (cmdName === \"mise\" && tokens[1] === \"exec\") {\n const inner = miseExecInner(tokens);\n if (!inner) return {\n action: \"none\",\n rule: null,\n reason: \"bare mise exec\"\n };\n return evaluateCommand(joinTokens(inner), {\n ...ctx,\n depth: ctx.depth + 1\n });\n }\n if (cmdName === \"bash\" || cmdName === \"sh\" || cmdName === \"zsh\") return evaluateShellC(tokens, ctx);\n if (cmdName === \"xargs\") return evaluateXargs(tokens, ctx);\n if (cmdName === \"node\" && (tokens.includes(\"-e\") || tokens.includes(\"-p\") || tokens.includes(\"--eval\") || tokens.includes(\"--print\"))) return {\n action: \"none\",\n rule: null,\n reason: \"node eval\"\n };\n for (const rule of denyRules) if (rule.match.test(cmdName)) {\n if (!rule.when || rule.when(tokens, ctx)) return {\n action: \"deny\",\n rule: rule.name,\n reason: rule.reason ?? null\n };\n }\n const advice = cmdName === \"git\" ? worktreeAdvice(tokens, ctx) : void 0;\n return {\n action: \"none\",\n rule: null,\n reason: `no rule matched: ${cmdName}`,\n ...advice ? { advice } : {}\n };\n}\nfunction miseExecInner(tokens) {\n const dashIdx = tokens.indexOf(\"--\");\n if (dashIdx === -1) return void 0;\n const inner = tokens.slice(dashIdx + 1);\n return inner.length > 0 ? inner : void 0;\n}\nfunction scanPnpmFlags(subTokens, from, state) {\n for (let i = from; i < subTokens.length; i++) {\n const t = subTokens[i];\n if (t === \"--filter\" || t.startsWith(\"--filter=\") || t === \"-F\" || t.startsWith(\"-F=\")) return {\n name: void 0,\n filterIdx: i\n };\n if (t === \"-r\" || t === \"--recursive\") {\n state.isRecursive = true;\n continue;\n }\n if (t === \"-w\" || t === \"--workspace-root\") {\n state.isWorkspaceRoot = true;\n continue;\n }\n if (t === \"-C\" || t === \"--dir\") {\n state.dirOverride = subTokens[++i];\n continue;\n }\n if (t.startsWith(\"-C=\") || t.startsWith(\"--dir=\")) {\n state.dirOverride = t.split(\"=\", 2)[1];\n continue;\n }\n if (t.startsWith(\"-\") && !PNPM_BUILTINS.has(t)) continue;\n return { name: t };\n }\n return { name: void 0 };\n}\nfunction evaluatePnpm(tokens, ctx) {\n const subTokens = tokens.slice(1);\n const state = {\n isRecursive: false,\n isWorkspaceRoot: false,\n dirOverride: void 0\n };\n const scan = scanPnpmFlags(subTokens, 0, state);\n if (scan.filterIdx !== void 0) return evaluatePnpmFilter(tokens, subTokens, scan.filterIdx, ctx, state.dirOverride);\n const subcommand = scan.name;\n const subcommandIdx = subcommand ? subTokens.indexOf(subcommand) : -1;\n if (!subcommand) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n if (subcommand === \"dlx\") return {\n action: \"none\",\n rule: null,\n reason: \"pnpm dlx\"\n };\n if (subcommand === \"add\") return {\n action: \"none\",\n rule: null,\n reason: \"pnpm add\"\n };\n if (subcommand === \"exec\") {\n const execArgs = subTokens.slice(subcommandIdx + 1);\n if (execArgs.length === 0) return {\n action: \"none\",\n rule: null,\n reason: \"bare pnpm exec\"\n };\n return evaluateCommand(joinTokens(execArgs), {\n ...ctx,\n depth: ctx.depth + 1\n });\n }\n let scriptName;\n let { isRecursive, isWorkspaceRoot, dirOverride } = state;\n if (subcommand === \"run\") {\n const runScan = scanPnpmFlags(subTokens, subcommandIdx + 1, state);\n ({isRecursive, isWorkspaceRoot, dirOverride} = state);\n if (runScan.filterIdx !== void 0) return evaluatePnpmFilter(tokens, subTokens, runScan.filterIdx, ctx, state.dirOverride);\n if (!runScan.name) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm run without script name\"\n };\n scriptName = runScan.name;\n } else if (!PNPM_BUILTINS.has(subcommand)) scriptName = subcommand;\n else return {\n action: \"none\",\n rule: null,\n reason: null\n };\n if (isRecursive) return evaluatePnpmRecursive(scriptName, ctx);\n if (isWorkspaceRoot) {\n const root = findWorkspaceRoot(ctx.cwd);\n if (!root) return {\n action: \"none\",\n rule: null,\n reason: \"workspace root not found\"\n };\n return evaluatePnpmScript(scriptName, {\n ...ctx,\n cwd: root\n });\n }\n if (dirOverride) {\n const resolved = path.resolve(ctx.cwd, dirOverride);\n return evaluatePnpmScript(scriptName, {\n ...ctx,\n cwd: resolved\n });\n }\n return evaluatePnpmScript(scriptName, ctx);\n}\nfunction evaluatePnpmScript(scriptName, ctx) {\n const resolved = resolveScript(scriptName, ctx.cwd);\n if (!resolved) return {\n action: \"none\",\n rule: null,\n reason: \"script resolution failed\"\n };\n const res = evaluateResolvedScript(resolved, {\n ...ctx,\n depth: ctx.depth + 1\n });\n if (res.action === \"deny\") return res;\n return {\n action: \"none\",\n rule: `pnpm-script:${scriptName}`,\n reason: null\n };\n}\nfunction evaluatePnpmRecursive(scriptName, ctx) {\n const resolved = resolveRecursiveScripts(scriptName, ctx.cwd);\n if (!resolved || resolved.length === 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm recursive\"\n };\n for (const pkg of resolved) {\n const res = evaluateResolvedScript(pkg, {\n ...ctx,\n depth: ctx.depth + 1,\n cwd: pkg.pkgDir ?? ctx.cwd\n });\n if (res.action === \"deny\") return res;\n }\n return {\n action: \"none\",\n rule: `pnpm-recursive:${scriptName}`,\n reason: null\n };\n}\nfunction evaluateNpm(tokens) {\n if (isNpmReadOp(tokens)) return {\n action: \"none\",\n rule: null,\n reason: null\n };\n return {\n action: \"deny\",\n rule: \"npm-redirect\",\n reason: getNpmRedirectReason(tokens)\n };\n}\nfunction collectFiltersAndScan(subTokens, from, filterPkgs) {\n let dirOverride;\n for (let i = from; i < subTokens.length; i += 1) {\n const t = subTokens[i];\n if (t === \"--filter\" || t === \"-F\") {\n const pkg = subTokens[i + 1];\n if (pkg === void 0 || pkg.startsWith(\"-\")) return void 0;\n filterPkgs.push(pkg);\n i += 1;\n continue;\n }\n if (t.startsWith(\"--filter=\") || t.startsWith(\"-F=\")) {\n const pkg = t.startsWith(\"-F=\") ? t.slice(3) : t.slice(9);\n if (pkg === \"\") return void 0;\n filterPkgs.push(pkg);\n continue;\n }\n if (t === \"-r\" || t === \"--recursive\" || t === \"-w\" || t === \"--workspace-root\") continue;\n if (t === \"-C\" || t === \"--dir\") {\n dirOverride = subTokens[i + 1];\n i += 1;\n continue;\n }\n if (t.startsWith(\"-C=\") || t.startsWith(\"--dir=\")) {\n dirOverride = t.split(\"=\", 2)[1];\n continue;\n }\n if (t.startsWith(\"-\")) continue;\n return {\n name: t,\n index: i,\n dirOverride\n };\n }\n return {\n name: void 0,\n index: -1,\n dirOverride\n };\n}\nfunction evaluatePnpmFilter(_tokens, subTokens, filterIdx, ctx, stateDir) {\n const filterPkgs = [];\n const scan = collectFiltersAndScan(subTokens, filterIdx, filterPkgs);\n if (scan === void 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter without package\"\n };\n let dirOverride = scan.dirOverride ?? stateDir;\n if (filterPkgs.length === 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter without package\"\n };\n const filterSubcommand = scan.name;\n const subcmdIdx = scan.index;\n if (filterSubcommand === void 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter without subcommand\"\n };\n if (PNPM_BUILTINS.has(filterSubcommand) && filterSubcommand !== \"run\" && filterSubcommand !== \"exec\") return {\n action: \"none\",\n rule: null,\n reason: null\n };\n if (filterSubcommand === \"exec\") {\n const execArgs = subTokens.slice(subcmdIdx + 1);\n if (execArgs.length === 0) return {\n action: \"none\",\n rule: null,\n reason: \"bare pnpm exec\"\n };\n return evaluateCommand(joinTokens(execArgs), {\n ...ctx,\n depth: ctx.depth + 1\n });\n }\n let scriptName = filterSubcommand;\n if (filterSubcommand === \"run\") {\n const runScan = collectFiltersAndScan(subTokens, subcmdIdx + 1, filterPkgs);\n if (runScan === void 0) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter without package\"\n };\n scriptName = runScan.name;\n if (runScan.dirOverride !== void 0) dirOverride = runScan.dirOverride;\n }\n if (scriptName === void 0 || scriptName.startsWith(\"-\")) return {\n action: \"none\",\n rule: null,\n reason: \"pnpm --filter run without script name\"\n };\n if (PNPM_BUILTINS.has(scriptName) && scriptName !== \"run\") return {\n action: \"none\",\n rule: null,\n reason: null\n };\n const baseDir = dirOverride ? path.resolve(ctx.cwd, dirOverride) : ctx.cwd;\n for (const pkg of filterPkgs) {\n const resolved = resolveFilteredScript(scriptName, pkg, baseDir);\n if (!resolved) return {\n action: \"none\",\n rule: null,\n reason: \"filtered script resolution failed\"\n };\n const res = evaluateResolvedScript(resolved, {\n ...ctx,\n depth: ctx.depth + 1,\n cwd: resolved.pkgDir ?? baseDir\n });\n if (res.action === \"deny\") return res;\n }\n return {\n action: \"none\",\n rule: `pnpm-filter:${filterPkgs.join(\",\")}:${scriptName}`,\n reason: null\n };\n}\nconst SHELL_LOGIN_FLAGS = /* @__PURE__ */ new Set([\"-l\", \"--login\"]);\nfunction evaluateShellC(tokens, ctx) {\n let i = 1;\n while (i < tokens.length && SHELL_LOGIN_FLAGS.has(tokens[i])) i++;\n const flag = tokens[i];\n if (flag === void 0 || !/^-[lc]+$/.test(flag) || !flag.includes(\"c\")) return {\n action: \"none\",\n rule: null,\n reason: \"shell without a plain -c\"\n };\n const cmdArg = tokens[i + 1];\n if (!cmdArg) return {\n action: \"none\",\n rule: null,\n reason: \"shell -c without command\"\n };\n if (tokens.length > i + 2) return {\n action: \"none\",\n rule: null,\n reason: \"shell -c with positional args\"\n };\n return evaluateCommand(cmdArg, {\n ...ctx,\n depth: ctx.depth + 1\n });\n}\nconst XARGS_ARG_FLAGS = /* @__PURE__ */ new Set([\n \"-I\",\n \"-d\",\n \"-n\",\n \"-P\",\n \"-s\",\n \"-L\",\n \"-E\",\n \"-a\",\n \"--max-args\",\n \"--max-procs\",\n \"--delimiter\",\n \"--replace\",\n \"--max-lines\",\n \"--max-chars\",\n \"--arg-file\",\n \"--process-slot-var\"\n]);\nconst XARGS_BOOL_FLAGS = /* @__PURE__ */ new Set([\n \"-0\",\n \"--null\",\n \"-t\",\n \"--verbose\",\n \"-r\",\n \"--no-run-if-empty\",\n \"-p\",\n \"--interactive\",\n \"-x\",\n \"--exit\",\n \"--show-limits\"\n]);\nfunction evaluateXargs(tokens, ctx) {\n let i = 1;\n while (i < tokens.length) {\n const t = tokens[i];\n if (!t.startsWith(\"-\")) break;\n if (XARGS_ARG_FLAGS.has(t)) {\n i += 2;\n continue;\n }\n const eqIdx = t.indexOf(\"=\");\n if (eqIdx !== -1) {\n const flagName = t.slice(0, eqIdx);\n if (XARGS_ARG_FLAGS.has(flagName)) {\n i++;\n continue;\n }\n }\n if (t.length > 2 && XARGS_ARG_FLAGS.has(t.slice(0, 2))) {\n i++;\n continue;\n }\n if (XARGS_BOOL_FLAGS.has(t)) {\n i++;\n continue;\n }\n return {\n action: \"none\",\n rule: null,\n reason: \"xargs with unrecognised flags\"\n };\n }\n if (i >= tokens.length) return {\n action: \"none\",\n rule: null,\n reason: \"xargs without command\"\n };\n return evaluateCommand(joinTokens(tokens.slice(i)), {\n ...ctx,\n depth: ctx.depth + 1\n });\n}\n\n// src/file-rules.ts\nconst READ_TOOLS = /* @__PURE__ */ new Set([\n \"Read\",\n \"Glob\",\n \"Grep\"\n]);\nconst WRITE_TOOLS = /* @__PURE__ */ new Set([\"Write\", \"Edit\"]);\nconst fileDenyRules = [\n {\n name: \"env-file-read\",\n tools: READ_TOOLS,\n action: \"deny\",\n when: (filePath) => isEnvFile(filePath),\n reason: \"Don't read .env files. These contain secrets that should not appear in the conversation.\"\n },\n {\n name: \"env-file-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath) => isEnvFile(filePath),\n reason: \"Don't write to .env files. These contain secrets.\"\n },\n {\n name: \"hooks-folder-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath, ctx) => {\n const resolved = resolveIn(ctx.cwd, filePath);\n const hooksDir = path.join(ctx.cwd, \".claude\", \"hooks\");\n return isWithin(hooksDir, resolved);\n },\n reason: \"Don't write to .claude/hooks/. These files are managed by the project and should not be modified directly.\"\n },\n {\n name: \"git-dir-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath, ctx) => targetsGitDir(filePath, ctx.cwd),\n reason: \"Don't write into .git/ directly. Its internals (config, hooks, refs) are not plain project files -- a config edit can redirect remotes or push destinations that other rules trust, and a hooks/ script runs automatically on the next commit/push. Use git subcommands instead, or ask the user.\"\n },\n {\n name: \"node-modules-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath, ctx) => targetsNodeModules(filePath, ctx.cwd),\n reason: \"Don't write into node_modules/. Its files are hardlinks into pnpm's global store -- editing one in place corrupts that package for every project on this machine. Edit the source package and rebuild, or install into a scratch tree with an isolated store (`pnpm add --store-dir <scratch> <pkg>`).\"\n },\n {\n name: \"claude-settings-write\",\n tools: WRITE_TOOLS,\n action: \"deny\",\n when: (filePath, ctx) => {\n const resolved = resolveIn(ctx.cwd, filePath);\n return samePath(resolved, path.join(ctx.cwd, \".claude\", \"settings.json\"));\n },\n reason: \"Don't write to .claude/settings.json. This file is managed by the project and should not be modified directly.\"\n }\n];\n\n// src/evaluate-tool.ts\nconst FILE_PATH_TOOLS = /* @__PURE__ */ new Set([\n \"Read\",\n \"Write\",\n \"Edit\"\n]);\nconst SEARCH_TOOLS = /* @__PURE__ */ new Set([\"Glob\", \"Grep\"]);\nfunction extractPath(toolName, toolInput, cwd) {\n if (FILE_PATH_TOOLS.has(toolName)) return parseFilePathInput(toolInput)?.file_path ?? null;\n if (SEARCH_TOOLS.has(toolName)) return parseSearchInput(toolInput)?.path ?? cwd;\n return null;\n}\nfunction evaluateToolUse(toolName, toolInput, ctx) {\n const filePath = extractPath(toolName, toolInput, ctx.cwd);\n if (filePath === null) return {\n action: \"none\",\n rule: null,\n reason: \"unknown tool input shape\"\n };\n for (const rule of fileDenyRules) if (rule.tools.has(toolName) && rule.when(filePath, ctx, toolInput)) return {\n action: \"deny\",\n rule: rule.name,\n reason: rule.reason ?? null\n };\n return {\n action: \"none\",\n rule: null,\n reason: \"no file rule matched\"\n };\n}\n\n// src/lib/settings.ts\nconst SETTINGS_PATH = \".claude/hooks/bst-hook.settings.json\";\nconst BstHookSettingsSchema = object({ protectedBranches: _default(array(string().check(_minLength(1))), []) });\nfunction isFileClean(cwd, relativePath) {\n try {\n execFileSync(\"git\", [\n \"ls-files\",\n \"--error-unmatch\",\n relativePath\n ], {\n cwd,\n stdio: \"ignore\",\n timeout: GIT_TIMEOUT_MS\n });\n execFileSync(\"git\", [\n \"diff\",\n \"--quiet\",\n \"HEAD\",\n \"--\",\n relativePath\n ], {\n cwd,\n stdio: \"ignore\",\n timeout: GIT_TIMEOUT_MS\n });\n return true;\n } catch {\n return false;\n }\n}\nfunction loadRepoSettings(cwd) {\n const root = findWorkspaceRoot(cwd) ?? cwd;\n const settingsFile = join(root, SETTINGS_PATH);\n const empty = { protectedBranches: [] };\n if (!existsSync(settingsFile)) return empty;\n if (!isFileClean(root, SETTINGS_PATH)) return empty;\n try {\n const raw = readFileSync(settingsFile, \"utf-8\");\n const parsed = JSON.parse(raw);\n const result = BstHookSettingsSchema.safeParse(parsed);\n if (!result.success) return empty;\n return { protectedBranches: result.data.protectedBranches };\n } catch {\n return empty;\n }\n}\n\n// src/index.ts\nconst inputResult = await readHookInput();\nif (!inputResult.ok) {\n process.stderr.write(`[bst-hook] invalid hook input: ${inputResult.error}\\n`);\n audit({\n sessionId: \"unknown\",\n cwd: \"unknown\",\n command: `<invalid input: ${inputResult.error}>`,\n decision: \"none\",\n rule: null,\n reason: `validation failed: ${inputResult.error}`,\n permissionMode: void 0\n });\n process.exit(0);\n}\nconst input = inputResult.data;\nif (input.hook_event_name !== \"PreToolUse\") process.exit(0);\nif (!(/* @__PURE__ */ new Set([\n \"Bash\",\n \"Read\",\n \"Write\",\n \"Edit\",\n \"Glob\",\n \"Grep\"\n])).has(input.tool_name)) process.exit(0);\nconst repoSettings = loadRepoSettings(input.cwd);\nlet decision;\nlet auditCommand;\nif (input.tool_name === \"Bash\") {\n const bashInput = parseBashInput(input.tool_input);\n if (!bashInput) {\n audit({\n sessionId: input.session_id,\n cwd: input.cwd,\n toolName: input.tool_name,\n command: `<invalid Bash input: ${JSON.stringify(input.tool_input).slice(0, 200)}>`,\n decision: \"none\",\n rule: null,\n reason: \"Bash tool_input missing or invalid 'command' field\",\n permissionMode: input.permission_mode\n });\n process.exit(0);\n }\n decision = evaluateCommand(bashInput.command, {\n cwd: input.cwd,\n depth: 0,\n repoProtectedBranches: repoSettings.protectedBranches\n });\n auditCommand = bashInput.command;\n} else {\n const projectDir = findWorkspaceRoot(input.cwd) ?? process.env[\"CLAUDE_PROJECT_DIR\"] ?? input.cwd;\n decision = evaluateToolUse(input.tool_name, input.tool_input, {\n cwd: projectDir,\n sessionId: input.session_id\n });\n const filePath = String(input.tool_input[\"file_path\"] ?? input.tool_input[\"path\"] ?? \"\");\n auditCommand = `${input.tool_name} ${filePath}`;\n}\naudit({\n sessionId: input.session_id,\n cwd: input.cwd,\n toolName: input.tool_name,\n command: auditCommand,\n decision: decision.action,\n rule: decision.rule,\n reason: decision.reason,\n permissionMode: input.permission_mode\n});\nif (decision.action === \"deny\") writeDeny(decision.reason);\nelse if (decision.advice) writeAdvice(decision.advice);\n\nexport { };",
8681
8752
  guide: "# bst-hook Permission Guide\n\nThis project uses a PreToolUse hook (`bst-hook`) that checks each Bash command\nand file tool call before it runs. The hook only ever blocks a command; it does\nnot approve anything on its own. A command that matches a rule below is denied,\nwith a message that says what to do instead.\n\n## Denied commands\n\nThese are blocked. The hook tells you what to do instead.\n\n### Bash\n\n- **sudo**: Don't use sudo. If you need elevated permissions, ask me to do it manually.\n- **git-force-push**: Use `git push --force-with-lease` instead of `--force`.\n- **git-protected-branch-write**: This would move a protected branch (main, master, the remote's default branch, or one listed in .claude/hooks/bst-hook.settings.json#protectedBranches). Work on a feature branch in a worktree: `git worktree add ../<repo>-<topic> -b feat/<topic>`, then commit and push there. To bring `main` up to date, use `git pull --ff-only`.\n- **chmod-777**: Don't use 777 permissions. Use more restrictive permissions.\n- **node-modules-write**: Don't write into node_modules/. Its files are hardlinks into pnpm's global store, so overwriting one in place (plain `cp`, `>` redirect, `sed -i`, ...) writes through the link and corrupts that package for every project on this machine -- silently, since the directory you wrote into ends up fine. To test a local build as an installed dependency, run it directly (`node packages/<pkg>/dist/bin.mjs <cmd>`), or install into a scratch tree with an isolated store (`pnpm add --store-dir <scratch> <pkg>`). If you must replace a file in place, `cp --remove-destination` is safe -- it unlinks the target first. Run `pnpm store status` to check whether the store is already damaged.\n- **env-file-read**: Don't read .env files. These contain secrets that should not appear in the conversation.\n- **env-file-write**: Don't write to .env files. These contain secrets.\n- **health-baseline-reset**: Run `pnpm exec bst health:raise` to raise only what this branch crossed. `--update-baseline --reset` records every outlier, including the ones already on the default branch.\n- **npx-redirect**: This project uses pnpm. Use `pnpm dlx <pkg>` or `pnpm exec <cmd>` instead of npx.\n- **mise-self-update**: Don't self-update mise. The version is Renovate-managed; ask a human to bump the pin.\n\n### File tools (Read, Write, Edit, Glob, Grep)\n\n- **env-file-read**: Don't read .env files. These contain secrets that should not appear in the conversation.\n- **env-file-write**: Don't write to .env files. These contain secrets.\n- **hooks-folder-write**: Don't write to .claude/hooks/. These files are managed by the project and should not be modified directly.\n- **git-dir-write**: Don't write into .git/ directly. Its internals (config, hooks, refs) are not plain project files -- a config edit can redirect remotes or push destinations that other rules trust, and a hooks/ script runs automatically on the next commit/push. Use git subcommands instead, or ask the user.\n- **node-modules-write**: Don't write into node_modules/. Its files are hardlinks into pnpm's global store -- editing one in place corrupts that package for every project on this machine. Edit the source package and rebuild, or install into a scratch tree with an isolated store (`pnpm add --store-dir <scratch> <pkg>`).\n- **claude-settings-write**: Don't write to .claude/settings.json. This file is managed by the project and should not be modified directly.\n\n## How commands are evaluated\n\n- **Pipelines and chains**: every segment is checked; a deny on any segment blocks the whole command.\n- **pnpm scripts**: `pnpm <script>` resolves against `package.json` (including pre/post hooks and `--filter` workspaces) and evaluates the resolved command recursively.\n- **cd propagation**: `cd dir && cmd` evaluates `cmd` relative to the new directory.\n- **Branch switch propagation**: `git switch <branch> && cmd` (or `git checkout <branch>`) evaluates a git write in `cmd` against the branch it switched to, not the one checked out before. This holds only across `&&` and only in the same directory.\n- **Audit log**: all decisions are logged to `.claude/hooks/bst-hook.audit.local.jsonl`.\n\n## Everything else\n\nA command that matches none of the rules above is judged by Claude Code's own\nauto mode, not by this hook.\n"
8682
8753
  }) {
8683
8754
  const results = [{
@@ -8697,8 +8768,7 @@ async function generateClaudeHooks(ctx, embedded = {
8697
8768
  if (legacyAllowResult) results.push(legacyAllowResult);
8698
8769
  return results;
8699
8770
  }
8700
- //#endregion
8701
- //#region src/generators/claude-settings.ts
8771
+ // src/generators/claude-settings.ts
8702
8772
  const HookEntrySchema = z.object({
8703
8773
  type: z.string().optional(),
8704
8774
  command: z.string().optional()
@@ -8855,8 +8925,7 @@ async function generateClaudeSettings(ctx) {
8855
8925
  }
8856
8926
  return results;
8857
8927
  }
8858
- //#endregion
8859
- //#region src/generators/release-it.ts
8928
+ // src/generators/release-it.ts
8860
8929
  function buildConfig$3(ci, isMonorepo) {
8861
8930
  const config = {
8862
8931
  $schema: "https://unpkg.com/release-it/schema/release-it.json",
@@ -8906,8 +8975,7 @@ async function generateReleaseIt(ctx) {
8906
8975
  description: "Generated .release-it.json"
8907
8976
  };
8908
8977
  }
8909
- //#endregion
8910
- //#region src/generators/changesets.ts
8978
+ // src/generators/changesets.ts
8911
8979
  function buildConfig$2(defaultBranch) {
8912
8980
  return {
8913
8981
  $schema: "https://unpkg.com/@changesets/config@3.1.1/schema.json",
@@ -8942,8 +9010,7 @@ async function generateChangesets(ctx) {
8942
9010
  description: "Generated .changeset/config.json"
8943
9011
  };
8944
9012
  }
8945
- //#endregion
8946
- //#region src/generators/lefthook.ts
9013
+ // src/generators/lefthook.ts
8947
9014
  const LINT_COMMAND = "pnpm exec oxlint --no-error-on-unmatched-pattern {staged_files}";
8948
9015
  function formatCommandFor(formatter) {
8949
9016
  return formatter === "prettier" ? "pnpm exec prettier --ignore-unknown --no-error-on-unmatched-pattern --write {staged_files}" : "pnpm exec oxfmt --no-error-on-unmatched-pattern {staged_files}";
@@ -9111,8 +9178,7 @@ async function generateLefthook(ctx) {
9111
9178
  });
9112
9179
  return results;
9113
9180
  }
9114
- //#endregion
9115
- //#region src/generators/vscode-settings.ts
9181
+ // src/generators/vscode-settings.ts
9116
9182
  const SCHEMA_LOCAL_PATH = ".vscode/forgejo-workflow.schema.json";
9117
9183
  const SETTINGS_PATH = ".vscode/settings.json";
9118
9184
  const SCHEMA_GLOB = ".forgejo/workflows/*.{yml,yaml}";
@@ -9201,8 +9267,7 @@ async function generateVscodeSettings(ctx) {
9201
9267
  results.push(writeSchemaToSettings(ctx));
9202
9268
  return results;
9203
9269
  }
9204
- //#endregion
9205
- //#region src/docs-check/blocks.ts
9270
+ // src/docs-check/blocks.ts
9206
9271
  const KEY_METADATA_LINE = /^[ \t]*(?:\*\*)?[A-Z][A-Za-z]*(?: [A-Za-z][A-Za-z]*)*(?:\*\*)?:(?:\*\*)?(?:\s|$)/;
9207
9272
  const HEADING_LINE = /^#{1,6}(?:\s|$)/;
9208
9273
  const LIST_BULLET_LINE = /^(?:[-*+]|\d+[.)])\s/;
@@ -9271,8 +9336,7 @@ function insertBlockAtBoundary(content, anchor, block) {
9271
9336
  const rest = content.slice(anchor).replace(/^\n+/, "");
9272
9337
  return `${before}\n\n${block}${rest === "" ? "\n" : `\n\n${rest}`}`;
9273
9338
  }
9274
- //#endregion
9275
- //#region src/docs-check/links.ts
9339
+ // src/docs-check/links.ts
9276
9340
  const LINK_RE = /\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g;
9277
9341
  const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
9278
9342
  const FENCE_OPEN_RE = /^ {0,3}((?:>[ \t]?)+ {0,3})?(`{3,}|~{3,})/;
@@ -9419,8 +9483,7 @@ const DOCS_ROOT$1 = "docs";
9419
9483
  function resolvesInsideDocs(target) {
9420
9484
  return target === DOCS_ROOT$1 || target.startsWith(`${DOCS_ROOT$1}/`);
9421
9485
  }
9422
- //#endregion
9423
- //#region src/docs-check/status.ts
9486
+ // src/docs-check/status.ts
9424
9487
  const TERMINAL_STATUS_WORDS = [
9425
9488
  "completed",
9426
9489
  "shipped",
@@ -9521,8 +9584,7 @@ function matchStatusBlock(content) {
9521
9584
  quoted: statusQuoted
9522
9585
  };
9523
9586
  }
9524
- //#endregion
9525
- //#region src/generators/claude-md.ts
9587
+ // src/generators/claude-md.ts
9526
9588
  const FILE = "CLAUDE.md";
9527
9589
  function codeList(words) {
9528
9590
  return words.map((word) => `\`${word}\``).join(", ");
@@ -9766,20 +9828,20 @@ function webUiGuideBody() {
9766
9828
  "@changesets/cli": "3.0.3",
9767
9829
  "@release-it/bumper": "8.0.1",
9768
9830
  "@types/node": "24.19.2",
9769
- "@vitest/coverage-v8": "5.0.3",
9831
+ "@vitest/coverage-v8": "5.0.5",
9770
9832
  "commit-and-tag-version": "13.3.0",
9771
- "knip": "6.41.0",
9833
+ "knip": "6.42.1",
9772
9834
  "lefthook": "2.2.2",
9773
- "modern-web-guidance": "0.0.194",
9774
- "oxfmt": "0.73.0",
9775
- "oxlint": "1.87.0",
9776
- "oxlint-tsgolint": "7.0.2004",
9835
+ "modern-web-guidance": "0.0.195",
9836
+ "oxfmt": "0.74.0",
9837
+ "oxlint": "1.89.0",
9838
+ "oxlint-tsgolint": "7.0.2005",
9777
9839
  "prettier": "3.9.10",
9778
9840
  "release-it": "21.1.1",
9779
9841
  "tsdown": "0.23.1",
9780
9842
  "typescript": "6.0.3",
9781
- "vitest": "5.0.3",
9782
- "pnpm": "11.28.5"
9843
+ "vitest": "5.0.5",
9844
+ "pnpm": "11.28.8"
9783
9845
  }["modern-web-guidance"]}`;
9784
9846
  return [
9785
9847
  "# Web UI",
@@ -10177,8 +10239,7 @@ async function generateClaudeMd(ctx) {
10177
10239
  syncAgentsMdLink(ctx)
10178
10240
  ];
10179
10241
  }
10180
- //#endregion
10181
- //#region src/generators/versionrc.ts
10242
+ // src/generators/versionrc.ts
10182
10243
  function buildConfig() {
10183
10244
  return {
10184
10245
  header: "# Changelog\n\nAll notable changes to this project will be documented in this file.\n",
@@ -10243,8 +10304,7 @@ async function generateVersionrc(ctx) {
10243
10304
  description: "Generated .versionrc.json"
10244
10305
  };
10245
10306
  }
10246
- //#endregion
10247
- //#region src/generators/stale-ci-workflows.ts
10307
+ // src/generators/stale-ci-workflows.ts
10248
10308
  async function generateStaleCiWorkflows(ctx) {
10249
10309
  const ci = ctx.config.ci;
10250
10310
  if (ci === "none") return [];
@@ -10293,8 +10353,7 @@ function retireReason(strategy, retiredPath, keptCiPath, ci) {
10293
10353
  if (keptCiPath === ciWorkflowPath(ci, "changesets")) return `${prefix} releases from ${keptCiBaseName}`;
10294
10354
  return `${prefix} has no release workflow`;
10295
10355
  }
10296
- //#endregion
10297
- //#region src/generators/pipeline.ts
10356
+ // src/generators/pipeline.ts
10298
10357
  async function runGenerators(ctx) {
10299
10358
  const results = [];
10300
10359
  const priorDevEngines = ctx.packageJson?.devEngines;
@@ -10326,8 +10385,7 @@ async function runGenerators(ctx) {
10326
10385
  results.push(saveToolingConfig(ctx, ctx.config));
10327
10386
  return results;
10328
10387
  }
10329
- //#endregion
10330
- //#region src/utils/generator-failures.ts
10388
+ // src/utils/generator-failures.ts
10331
10389
  function failedResults(results) {
10332
10390
  return results.filter((r) => r.action === "failed");
10333
10391
  }
@@ -10336,12 +10394,11 @@ function reportFailures(failed, command) {
10336
10394
  log$1.error(`${String(failed.length)} file(s) could not be synced by ${command} -- fix them by hand:`);
10337
10395
  for (const r of failed) log$1.info(` ${r.filePath} -- ${r.description}`);
10338
10396
  }
10339
- //#endregion
10340
- //#region src/generators/migrate-prompt.ts
10397
+ // src/generators/migrate-prompt.ts
10341
10398
  function generateMigratePrompt(results, config, detected) {
10342
10399
  const sections = [];
10343
10400
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
10344
- sections.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.99.0 repo:sync\` on ${timestamp}_\n`);
10401
+ sections.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.100.0 repo:sync\` on ${timestamp}_\n`);
10345
10402
  const changed = results.filter((r) => r.action === "created" || r.action === "updated" || r.action === "archived");
10346
10403
  if (changed.length > 0) {
10347
10404
  const items = changed.map((r) => {
@@ -10452,8 +10509,7 @@ function addTestGenerationTasks(tasks, results) {
10452
10509
  A starter test was created at \`test/example.test.ts\`. Review \`src/\` and create additional tests covering exported functions and edge cases.
10453
10510
  `);
10454
10511
  }
10455
- //#endregion
10456
- //#region src/commands/repo-init.ts
10512
+ // src/commands/repo-init.ts
10457
10513
  function logDetectionSummary(ctx) {
10458
10514
  if (ctx.config.publishDocker) {
10459
10515
  const publishablePackages = detectContextDockerPackages(ctx).filter((pkg) => pkg.publish);
@@ -10563,8 +10619,7 @@ async function runInitReport(config, options = {}) {
10563
10619
  async function runInit(config, options = {}) {
10564
10620
  return (await runInitReport(config, options)).results;
10565
10621
  }
10566
- //#endregion
10567
- //#region src/docker-check/compose-lint.ts
10622
+ // src/docker-check/compose-lint.ts
10568
10623
  const ComposeFileShape = z.looseObject({ name: z.unknown().optional() });
10569
10624
  const BASE_COMPOSE_FILES = new Set(COMPOSE_FILE_CANDIDATES);
10570
10625
  const COMPOSE_FILENAME_PATTERN = /^(?:docker-compose|compose).*\.(?:yml|yaml)$/;
@@ -10681,8 +10736,7 @@ function readTopLevelName(absPath) {
10681
10736
  if (typeof value !== "string") return void 0;
10682
10737
  return value;
10683
10738
  }
10684
- //#endregion
10685
- //#region src/docker-check/sweep.ts
10739
+ // src/docker-check/sweep.ts
10686
10740
  const CI_LABEL = "com.bensandee.ci";
10687
10741
  const DEFAULT_MAX_AGE_MS = 144e5;
10688
10742
  const OVERLAY_FINGERPRINT = /(?:^|\/)tooling-check-[^/]+\/overlay\.ya?ml$/;
@@ -10907,8 +10961,7 @@ function recordFailure(executor, report, kind, ref, result) {
10907
10961
  });
10908
10962
  executor.log(`Could not reclaim ${kind} ${ref}: ${error}`);
10909
10963
  }
10910
- //#endregion
10911
- //#region src/docker-check/detect.ts
10964
+ // src/docker-check/detect.ts
10912
10965
  function readFileOrNull(absPath) {
10913
10966
  try {
10914
10967
  return readFileSync(absPath, "utf-8");
@@ -11128,8 +11181,7 @@ function createFileReader() {
11128
11181
  }
11129
11182
  };
11130
11183
  }
11131
- //#endregion
11132
- //#region src/checks/marker.ts
11184
+ // src/checks/marker.ts
11133
11185
  const CHECKS_MARKER = "::bst-checks::";
11134
11186
  const WARN_LINE = new RegExp(`^${CHECKS_MARKER} warn (\\d+)\\s*$`);
11135
11187
  function formatWarnMarker(count) {
@@ -11156,8 +11208,7 @@ function readMeasureMarker(stdout) {
11156
11208
  }
11157
11209
  return found;
11158
11210
  }
11159
- //#endregion
11160
- //#region src/checks/step-exec.ts
11211
+ // src/checks/step-exec.ts
11161
11212
  function execStep(cmd, cwd, sink = process.stdout) {
11162
11213
  return new Promise((resolve) => {
11163
11214
  const child = spawn(cmd, {
@@ -11200,8 +11251,7 @@ function execStep(cmd, cwd, sink = process.stdout) {
11200
11251
  });
11201
11252
  });
11202
11253
  }
11203
- //#endregion
11204
- //#region src/checks/skip-report.ts
11254
+ // src/checks/skip-report.ts
11205
11255
  function matches(name, patterns) {
11206
11256
  return patterns.size > 0 && picomatch.isMatch(name, [...patterns]);
11207
11257
  }
@@ -11220,8 +11270,7 @@ function groupSkippedSteps(steps, defined, flagSkip, configSkip) {
11220
11270
  steps: bySource[source]
11221
11271
  }));
11222
11272
  }
11223
- //#endregion
11224
- //#region src/codebase-health/executor.ts
11273
+ // src/codebase-health/executor.ts
11225
11274
  function createRealHealthExecutor(rootDir) {
11226
11275
  return {
11227
11276
  exec(file, args, options) {
@@ -11281,8 +11330,7 @@ function createRealHealthExecutor(rootDir) {
11281
11330
  }
11282
11331
  };
11283
11332
  }
11284
- //#endregion
11285
- //#region src/codebase-health/reference.ts
11333
+ // src/codebase-health/reference.ts
11286
11334
  const BASELINE_FILE$2 = "health-baseline.json";
11287
11335
  const TOOLING_FILE$1 = ".tooling.json";
11288
11336
  function repoPrefix(executor, cwd) {
@@ -11576,8 +11624,7 @@ function branchDiffNames(executor, cwd, mergeBase) {
11576
11624
  }
11577
11625
  return [...names].toSorted();
11578
11626
  }
11579
- //#endregion
11580
- //#region ../forgejo/src/git.ts
11627
+ // ../forgejo/src/git.ts
11581
11628
  const GIT_LOCAL_TIMEOUT_MS = 6e4;
11582
11629
  const GIT_WRITE_TIMEOUT_MS = 3e5;
11583
11630
  function pickDefaultBranch(override, originHead) {
@@ -11688,8 +11735,7 @@ async function pushBranch(git, cwd, branch, env, forceWithLease = false) {
11688
11735
  });
11689
11736
  if (result.exitCode !== 0) throw new FatalError(`Failed to push ${branch}: ${result.stderr || result.stdout}`);
11690
11737
  }
11691
- //#endregion
11692
- //#region src/utils/branch.ts
11738
+ // src/utils/branch.ts
11693
11739
  function resolveDefaultBranch(options) {
11694
11740
  const override = options.configOverride;
11695
11741
  if (override !== void 0 && override !== "") return pickDefaultBranch(override, void 0);
@@ -11699,8 +11745,7 @@ function resolveDefaultBranch(options) {
11699
11745
  "refs/remotes/origin/HEAD"
11700
11746
  ], options.cwd));
11701
11747
  }
11702
- //#endregion
11703
- //#region ../cli-kit/src/flags.ts
11748
+ // ../cli-kit/src/flags.ts
11704
11749
  const UNIVERSAL_FLAGS = [
11705
11750
  "--help",
11706
11751
  "-h",
@@ -12015,8 +12060,7 @@ function parseListFlag(rawArgs, flag) {
12015
12060
  }
12016
12061
  return values.flatMap((value) => value.split(",")).map((value) => value.trim()).filter((value) => value.length > 0);
12017
12062
  }
12018
- //#endregion
12019
- //#region src/commands/repo-run-checks.ts
12063
+ // src/commands/repo-run-checks.ts
12020
12064
  const CHECKS = [
12021
12065
  { name: "build" },
12022
12066
  { name: "typecheck" },
@@ -12398,14 +12442,12 @@ const runChecksCommand = defineCommand({
12398
12442
  process.exitCode = exitCode;
12399
12443
  }
12400
12444
  });
12401
- //#endregion
12402
- //#region src/utils/workflow-paths.ts
12445
+ // src/utils/workflow-paths.ts
12403
12446
  const WORKFLOW_DIR_PREFIXES = [".forgejo/workflows/", ".github/workflows/"];
12404
12447
  function isWorkflowDirPath(filePath) {
12405
12448
  return WORKFLOW_DIR_PREFIXES.some((prefix) => filePath.startsWith(prefix));
12406
12449
  }
12407
- //#endregion
12408
- //#region src/commands/workflow-apt-steps.ts
12450
+ // src/commands/workflow-apt-steps.ts
12409
12451
  const APT_INSTALL = /\bapt(?:-get)?(?:\s+-\S+)*\s+install\b/g;
12410
12452
  const COMMAND_END = /&&|\|\||;|\|/;
12411
12453
  function workflowFiles(targetDir) {
@@ -12488,8 +12530,7 @@ function findWorkflowAptSteps(targetDir) {
12488
12530
  }
12489
12531
  return steps.toSorted((a, b) => a.file.localeCompare(b.file));
12490
12532
  }
12491
- //#endregion
12492
- //#region src/commands/sync-gates.ts
12533
+ // src/commands/sync-gates.ts
12493
12534
  function runReleaseTargetGate(config, targetDir) {
12494
12535
  const file = releaseTargetConflict(config.stack, config.releaseStrategy, targetDir);
12495
12536
  if (!file) return false;
@@ -12716,8 +12757,7 @@ function runToolchainGate(targetDir) {
12716
12757
  if (!declared) return 0;
12717
12758
  return checkDeclaredToolsActive(targetDir, declared);
12718
12759
  }
12719
- //#endregion
12720
- //#region src/commands/repo-sync.ts
12760
+ // src/commands/repo-sync.ts
12721
12761
  const rawLog$1 = (msg) => console.log(msg);
12722
12762
  const syncCommand = defineCommand({
12723
12763
  meta: {
@@ -12986,8 +13026,7 @@ function lineDiff(oldText, newText) {
12986
13026
  for (const l of added) lines.push(`+ ${l.trim()}`);
12987
13027
  return lines;
12988
13028
  }
12989
- //#endregion
12990
- //#region ../forgejo/src/git-auth.ts
13029
+ // ../forgejo/src/git-auth.ts
12991
13030
  function buildGitAuth(coords) {
12992
13031
  const host = coords.serverUrl.replace(/^https?:\/\//, "");
12993
13032
  return {
@@ -12995,8 +13034,7 @@ function buildGitAuth(coords) {
12995
13034
  url: `https://x-access-token:${coords.token}@${host}/${coords.repository}`
12996
13035
  };
12997
13036
  }
12998
- //#endregion
12999
- //#region ../forgejo/src/pr-title.ts
13037
+ // ../forgejo/src/pr-title.ts
13000
13038
  const WIP_PREFIXES = ["WIP:", "[WIP]"];
13001
13039
  function hasWipPrefix(title) {
13002
13040
  return matchedWipPrefix(title) !== void 0;
@@ -13010,8 +13048,7 @@ function stripWipPrefix(title) {
13010
13048
  if (prefix === void 0) return title;
13011
13049
  return title.slice(prefix.length).trimStart();
13012
13050
  }
13013
- //#endregion
13014
- //#region ../forgejo/src/pr.ts
13051
+ // ../forgejo/src/pr.ts
13015
13052
  const CreatedPrSchema = z.object({
13016
13053
  number: z.number(),
13017
13054
  html_url: z.string().optional()
@@ -13062,9 +13099,12 @@ function updatedBefore(since) {
13062
13099
  return (pr) => pr.updatedAt !== null && Date.parse(pr.updatedAt) < since;
13063
13100
  }
13064
13101
  async function listPulls(executor, conn, options = {}) {
13102
+ const startPage = options.startPage ?? 1;
13103
+ if (!Number.isInteger(startPage) || startPage < 1) throw new FatalError(`Cannot list PRs on ${conn.repository}: startPage must be an integer of at least 1, got ${String(startPage)}`);
13104
+ const lastPage = startPage + PULLS_MAX_PAGES - 1;
13065
13105
  const headers = { Authorization: `token ${conn.token}` };
13066
13106
  const pulls = [];
13067
- for (let page = 1; page <= PULLS_MAX_PAGES; page++) {
13107
+ for (let page = startPage; page <= lastPage; page++) {
13068
13108
  options.signal?.throwIfAborted();
13069
13109
  const params = new URLSearchParams({
13070
13110
  state: options.state ?? "all",
@@ -13104,9 +13144,9 @@ async function listPulls(executor, conn, options = {}) {
13104
13144
  if (options.stopWhen !== void 0 && items.some(options.stopWhen)) break;
13105
13145
  if (options.updatedSince !== void 0 && items.some(updatedBefore(options.updatedSince))) break;
13106
13146
  if (options.limit !== void 0 && pulls.length >= options.limit) break;
13107
- if (page === PULLS_MAX_PAGES) {
13147
+ if (page === lastPage) {
13108
13148
  log.warn(`PR listing on ${conn.repository} hit the ${String(PULLS_MAX_PAGES)}-page cap without an empty page; results may be truncated`);
13109
- options.onPageCap?.();
13149
+ options.onPageCap?.(lastPage);
13110
13150
  }
13111
13151
  }
13112
13152
  return pulls;
@@ -13283,13 +13323,11 @@ const PullReviewCommentSchema = z.object({
13283
13323
  user: z.object({ login: z.string() }).nullish()
13284
13324
  });
13285
13325
  z.array(PullReviewCommentSchema);
13286
- //#endregion
13287
- //#region src/release/publish/child-output.ts
13326
+ // src/release/publish/child-output.ts
13288
13327
  function childOutput(result) {
13289
13328
  return [result.stdout, result.stderr].filter((stream) => stream.trim() !== "").join("\n");
13290
13329
  }
13291
- //#endregion
13292
- //#region src/release/publish/version.ts
13330
+ // src/release/publish/version.ts
13293
13331
  function defaultBranchRef(config) {
13294
13332
  return `refs/heads/${config.defaultBranch}`;
13295
13333
  }
@@ -13521,9 +13559,83 @@ async function runVersionMode(executor, config) {
13521
13559
  pr: "updated"
13522
13560
  };
13523
13561
  }
13524
- //#endregion
13525
- //#region src/release/publish/publish.ts
13526
- function moveAllFloatingTags(executor, config, auth, packages, dryRun) {
13562
+ // src/release/publish/npm-publish.ts
13563
+ const DEFAULT_ACCESS = "restricted";
13564
+ const PreStateSchema = z.looseObject({ tag: z.string().optional() });
13565
+ const ChangesetAccessSchema = z.looseObject({ access: z.string().optional() });
13566
+ function refuseAccessRead(configPath, cause) {
13567
+ return new FatalError(`Could not read the npm access from ${configPath}: ${cause}. Refusing to publish, because falling back to \`restricted\` would change the access of a package the config declares public.`);
13568
+ }
13569
+ function changesetFallbackAccess(executor, config) {
13570
+ const configPath = path.join(config.cwd, ".changeset", "config.json");
13571
+ const raw = executor.readFile(configPath);
13572
+ if (raw === null) return void 0;
13573
+ let data;
13574
+ try {
13575
+ data = JSON.parse(raw);
13576
+ } catch (error) {
13577
+ throw refuseAccessRead(configPath, describeError$1(error));
13578
+ }
13579
+ const result = ChangesetAccessSchema.safeParse(data);
13580
+ if (!result.success) {
13581
+ const issue = result.error.issues[0];
13582
+ throw refuseAccessRead(configPath, `${issue && issue.path.length > 0 ? issue.path.join(".") : "the config"} has the wrong type`);
13583
+ }
13584
+ return result.data.access;
13585
+ }
13586
+ function distTag(executor, config) {
13587
+ const prePath = path.join(config.cwd, ".changeset", "pre.json");
13588
+ const raw = executor.readFile(prePath);
13589
+ if (raw === null) return "latest";
13590
+ let data;
13591
+ try {
13592
+ data = JSON.parse(raw);
13593
+ } catch (error) {
13594
+ throw new FatalError(`Could not read the dist-tag from ${prePath}: ${describeError$1(error)}. Refusing to publish, because a prerelease published to \`latest\` moves the public dist-tag.`);
13595
+ }
13596
+ const result = PreStateSchema.safeParse(data);
13597
+ const tag = result.success ? result.data.tag : void 0;
13598
+ if (tag === void 0 || tag === "") throw new FatalError(`${prePath} carries no dist-tag. Refusing to publish, because a prerelease published to \`latest\` moves the public dist-tag.`);
13599
+ return tag;
13600
+ }
13601
+ function accessOf(bumped, changesetAccess) {
13602
+ const access = bumped.access ?? changesetAccess ?? DEFAULT_ACCESS;
13603
+ if (access !== "public" && access !== "restricted") throw new FatalError(`Unknown npm access "${access}" for ${bumped.name}. Expected "public" or "restricted".`);
13604
+ return access;
13605
+ }
13606
+ function publishBumpedPackages(executor, config, bumped) {
13607
+ const publishable = bumped.filter((p) => !p.private);
13608
+ if (publishable.length === 0) {
13609
+ log$1.info("Nothing to publish: every bumped package is private");
13610
+ return;
13611
+ }
13612
+ const changesetAccess = changesetFallbackAccess(executor, config);
13613
+ const tag = distTag(executor, config);
13614
+ for (const access of ["restricted", "public"]) {
13615
+ const group = publishable.filter((p) => accessOf(p, changesetAccess) === access);
13616
+ if (group.length === 0) continue;
13617
+ const args = [
13618
+ "-r",
13619
+ "publish",
13620
+ ...group.flatMap((p) => ["--filter", p.name]),
13621
+ "--access",
13622
+ access,
13623
+ "--tag",
13624
+ tag,
13625
+ "--no-git-checks"
13626
+ ];
13627
+ const command = ["pnpm", ...args].join(" ");
13628
+ if (config.dryRun) {
13629
+ log$1.info(`[dry-run] Would run ${command}`);
13630
+ continue;
13631
+ }
13632
+ const result = executor.exec("pnpm", args, { cwd: config.cwd });
13633
+ debugExec(config, command, result);
13634
+ if (result.exitCode !== 0) throw new FatalError(`pnpm publish failed (exit code ${String(result.exitCode)}):\n${childOutput(result)}`);
13635
+ }
13636
+ }
13637
+ // src/release/publish/publish.ts
13638
+ function moveBoundedFloatingTags(executor, config, auth, families, dryRun) {
13527
13639
  return moveFloatingTags(executor, {
13528
13640
  cwd: config.cwd,
13529
13641
  git: {
@@ -13532,7 +13644,19 @@ function moveAllFloatingTags(executor, config, auth, packages, dryRun) {
13532
13644
  },
13533
13645
  dryRun,
13534
13646
  verbose: config.verbose
13535
- }, packages);
13647
+ }, families);
13648
+ }
13649
+ function floatingFamilies(packages, remoteSet, pushedTags) {
13650
+ const existing = /* @__PURE__ */ new Set([...remoteSet, ...pushedTags]);
13651
+ const families = [];
13652
+ for (const p of packages) {
13653
+ if (!existing.has(exactTag(p.name, p.version))) continue;
13654
+ families.push({
13655
+ family: changesetsTagFamily(p.name),
13656
+ version: p.version
13657
+ });
13658
+ }
13659
+ return families;
13536
13660
  }
13537
13661
  function prereleaseTag(families, tag) {
13538
13662
  for (const entry of families) {
@@ -13571,22 +13695,12 @@ function pushTagToRemote(executor, config, auth, tag, remoteSet) {
13571
13695
  ], { cwd: config.cwd });
13572
13696
  if (pushTagResult.exitCode !== 0) throw new FatalError(`Failed to push tag ${tag}: ${pushTagResult.stderr || pushTagResult.stdout}`);
13573
13697
  }
13574
- async function runPublishMode(executor, config) {
13575
- log$1.info("Publishing packages whose versions are not yet on the registry");
13576
- let stdoutTags;
13577
- if (config.dryRun) {
13578
- log$1.info("[dry-run] Would run pnpm changeset publish");
13579
- stdoutTags = [];
13580
- } else {
13581
- const publishResult = executor.exec("pnpm", ["changeset", "publish"], { cwd: config.cwd });
13582
- debugExec(config, "pnpm changeset publish", publishResult);
13583
- if (publishResult.exitCode !== 0) throw new FatalError(`pnpm changeset publish failed (exit code ${String(publishResult.exitCode)}):\n${childOutput(publishResult)}`);
13584
- stdoutTags = parseNewTags(publishResult.stdout + "\n" + publishResult.stderr);
13585
- }
13586
- debug(config, `Tags from publish stdout: ${stdoutTags.length > 0 ? stdoutTags.join(", ") : "(none)"}`);
13698
+ async function runPublishMode(executor, config, bumped) {
13699
+ log$1.info("Publishing the packages HEAD bumped that are not yet on the registry");
13700
+ publishBumpedPackages(executor, config, bumped);
13701
+ const expectedTags = bumped.map((p) => p.tag);
13702
+ debug(config, `Expected tags from the bumped set: ${expectedTags.length > 0 ? expectedTags.join(", ") : "(none)"}`);
13587
13703
  const packages = executor.listWorkspacePackages(config.cwd);
13588
- const expectedTags = computeExpectedTags(packages);
13589
- debug(config, `Expected tags from workspace packages: ${expectedTags.length > 0 ? expectedTags.join(", ") : "(none)"}`);
13590
13704
  const auth = buildGitAuth(config);
13591
13705
  const remoteTags = parseRemoteTags(executor.exec("git", [
13592
13706
  ...auth.args,
@@ -13596,14 +13710,20 @@ async function runPublishMode(executor, config) {
13596
13710
  ], { cwd: config.cwd }).stdout);
13597
13711
  debug(config, `Remote tags: ${remoteTags.length > 0 ? remoteTags.join(", ") : "(none)"}`);
13598
13712
  const remoteSet = new Set(remoteTags);
13599
- const tagsToPush = reconcileTags(expectedTags, remoteTags, stdoutTags);
13713
+ const tagsToPush = reconcileTags(expectedTags, remoteTags);
13600
13714
  debug(config, `Reconciled tags to push: ${tagsToPush.length > 0 ? tagsToPush.join(", ") : "(none)"}`);
13601
13715
  const families = packages.map((p) => ({
13602
13716
  family: changesetsTagFamily(p.name),
13603
13717
  version: p.version
13604
13718
  }));
13719
+ const bumpedPrerelease = new Map(bumped.map((p) => [p.tag, isPrerelease(p.version)]));
13720
+ function prereleaseFor(tag) {
13721
+ const own = bumpedPrerelease.get(tag);
13722
+ if (own !== void 0) return own;
13723
+ return prereleaseTag(families, tag);
13724
+ }
13605
13725
  if (config.dryRun) {
13606
- reportFloatingTagOutcome(moveAllFloatingTags(executor, config, auth, families, true), true);
13726
+ reportFloatingTagOutcome(moveBoundedFloatingTags(executor, config, auth, floatingFamilies(packages, remoteSet, tagsToPush), true), true);
13607
13727
  if (tagsToPush.length === 0) {
13608
13728
  log$1.info("No packages were published");
13609
13729
  return { mode: "none" };
@@ -13620,17 +13740,19 @@ async function runPublishMode(executor, config) {
13620
13740
  repository: config.repository,
13621
13741
  token: config.token
13622
13742
  };
13623
- const remoteExpectedTags = expectedTags.filter((t) => remoteSet.has(t) && !tagsToPush.includes(t));
13743
+ const remoteExpectedTags = [.../* @__PURE__ */ new Set([...computeExpectedTags(packages), ...expectedTags])].filter((t) => remoteSet.has(t) && !tagsToPush.includes(t));
13624
13744
  debug(config, `Expected tags already on remote: ${remoteExpectedTags.length > 0 ? remoteExpectedTags.join(", ") : "(none)"}`);
13625
13745
  const tagsWithMissingReleases = [];
13626
- for (const tag of remoteExpectedTags) if (!(prereleaseTag(families, tag) ? await prereleaseReleaseExists(executor, conn, tag) : await findRelease(executor, conn, tag))) {
13746
+ for (const tag of remoteExpectedTags) if (!(prereleaseFor(tag) ? await prereleaseReleaseExists(executor, conn, tag) : await findRelease(executor, conn, tag))) {
13627
13747
  debug(config, `Tag ${tag} exists on remote but has no release -- will create`);
13628
13748
  tagsWithMissingReleases.push(tag);
13629
13749
  }
13630
13750
  const allTags = [...tagsToPush, ...tagsWithMissingReleases];
13751
+ const bumpedTagSet = new Set(expectedTags);
13752
+ const repairedOwnTag = tagsWithMissingReleases.some((t) => bumpedTagSet.has(t));
13631
13753
  if (allTags.length === 0) {
13632
13754
  log$1.info("No packages were published");
13633
- reportFloatingTagOutcome(moveAllFloatingTags(executor, config, auth, families, false), false);
13755
+ reportFloatingTagOutcome(moveBoundedFloatingTags(executor, config, auth, floatingFamilies(packages, remoteSet, []), false), false);
13634
13756
  return { mode: "none" };
13635
13757
  }
13636
13758
  log$1.info(`Tags to process: ${allTags.join(", ")}`);
@@ -13640,7 +13762,7 @@ async function runPublishMode(executor, config) {
13640
13762
  debug(config, `Ensuring Forgejo release for ${tag}`);
13641
13763
  const { status: releaseStatus } = await ensureRelease(executor, conn, tag, {
13642
13764
  target: resolveTagCommit(executor, config.cwd, tag),
13643
- prerelease: prereleaseTag(families, tag)
13765
+ prerelease: prereleaseFor(tag)
13644
13766
  });
13645
13767
  if (releaseStatus === "exists") log$1.warn(`Release for ${tag} already exists -- skipping`);
13646
13768
  else log$1.info(`Created release for ${tag}`);
@@ -13655,14 +13777,97 @@ async function runPublishMode(executor, config) {
13655
13777
  const failedTags = errors.map((e) => e.tag).join(", ");
13656
13778
  throw new TransientError(`Failed to create releases for: ${failedTags}`);
13657
13779
  }
13658
- reportFloatingTagOutcome(moveAllFloatingTags(executor, config, auth, families, false), false);
13780
+ reportFloatingTagOutcome(moveBoundedFloatingTags(executor, config, auth, floatingFamilies(packages, remoteSet, allTags), false), false);
13781
+ if (tagsToPush.length === 0 && !repairedOwnTag) {
13782
+ log$1.info("No packages were published");
13783
+ return { mode: "none" };
13784
+ }
13659
13785
  return {
13660
13786
  mode: "publish",
13661
13787
  tags: allTags
13662
13788
  };
13663
13789
  }
13664
- //#endregion
13665
- //#region ../forgejo/src/user.ts
13790
+ // src/release/publish/bumped-set.ts
13791
+ const BumpedManifestSchema = z.looseObject({
13792
+ name: z.string().optional(),
13793
+ version: z.string().optional(),
13794
+ private: z.boolean().optional(),
13795
+ publishConfig: z.unknown().optional()
13796
+ });
13797
+ const PublishAccessSchema = z.looseObject({ access: z.string().optional() });
13798
+ function parseManifest(stdout) {
13799
+ let json;
13800
+ try {
13801
+ json = JSON.parse(stdout);
13802
+ } catch {
13803
+ return;
13804
+ }
13805
+ const result = BumpedManifestSchema.safeParse(json);
13806
+ return result.success ? result.data : void 0;
13807
+ }
13808
+ function candidates(executor, cwd) {
13809
+ const packages = executor.listWorkspacePackages(cwd);
13810
+ if (packages.length > 0) return packages.map((p) => ({
13811
+ path: `packages/${p.dir}/package.json`,
13812
+ root: false
13813
+ }));
13814
+ return [{
13815
+ path: "package.json",
13816
+ root: true
13817
+ }];
13818
+ }
13819
+ function showManifest(executor, cwd, revision, path) {
13820
+ const result = executor.exec("git", ["show", `${revision}:${path}`], { cwd });
13821
+ if (result.exitCode !== 0) return void 0;
13822
+ return parseManifest(result.stdout);
13823
+ }
13824
+ function readBumpedSet(executor, config) {
13825
+ const parent = executor.exec("git", [
13826
+ "rev-parse",
13827
+ "--verify",
13828
+ "--quiet",
13829
+ "HEAD~1"
13830
+ ], { cwd: config.cwd });
13831
+ if (parent.exitCode !== 0 || parent.stdout.trim() === "") return [];
13832
+ const candidateList = candidates(executor, config.cwd);
13833
+ const changed = executor.exec("git", [
13834
+ "-c",
13835
+ "core.quotePath=false",
13836
+ "diff",
13837
+ "--name-only",
13838
+ "HEAD~1",
13839
+ "HEAD",
13840
+ "--",
13841
+ ...candidateList.map((c) => c.path)
13842
+ ], { cwd: config.cwd });
13843
+ const changedPaths = new Set(changed.stdout.split("\n").filter((line) => line.trim() !== ""));
13844
+ const bumped = [];
13845
+ for (const candidate of candidateList) {
13846
+ if (!changedPaths.has(candidate.path)) continue;
13847
+ const before = showManifest(executor, config.cwd, "HEAD~1", candidate.path);
13848
+ const after = showManifest(executor, config.cwd, "HEAD", candidate.path);
13849
+ if (before === void 0 || after === void 0) continue;
13850
+ const previousVersion = before.version;
13851
+ const version = after.version;
13852
+ if (previousVersion === void 0 || version === void 0) continue;
13853
+ if (previousVersion === version) continue;
13854
+ if (after.name === void 0) continue;
13855
+ bumped.push({
13856
+ name: after.name,
13857
+ version,
13858
+ tag: candidate.root ? `v${version}` : `${after.name}@${version}`,
13859
+ private: after.private ?? false,
13860
+ access: readAccess(after.publishConfig)
13861
+ });
13862
+ }
13863
+ return bumped;
13864
+ }
13865
+ function readAccess(publishConfig) {
13866
+ if (publishConfig === void 0) return void 0;
13867
+ const result = PublishAccessSchema.safeParse(publishConfig);
13868
+ return result.success ? result.data.access : void 0;
13869
+ }
13870
+ // ../forgejo/src/user.ts
13666
13871
  const AuthenticatedUserSchema = z.object({
13667
13872
  login: z.string(),
13668
13873
  email: z.string().nullish()
@@ -13688,16 +13893,14 @@ async function getAuthenticatedUser(executor, conn, signal = null) {
13688
13893
  function noreplyEmail(serverUrl, login) {
13689
13894
  return `${login}@noreply.${serverUrl.replace(/^https?:\/\//, "")}`;
13690
13895
  }
13691
- //#endregion
13692
- //#region src/release/types.ts
13896
+ // src/release/types.ts
13693
13897
  const GIT_READ_TIMEOUT_MS = 12e4;
13694
13898
  function sleep(ms) {
13695
13899
  return new Promise((resolve) => {
13696
13900
  setTimeout(resolve, ms);
13697
13901
  });
13698
13902
  }
13699
- //#endregion
13700
- //#region src/release/git-identity.ts
13903
+ // src/release/git-identity.ts
13701
13904
  function ciActorName(platform) {
13702
13905
  return platform === "github" ? "github-actions[bot]" : "forgejo-actions[bot]";
13703
13906
  }
@@ -13757,8 +13960,7 @@ async function configureGitIdentity(executor, platform, cwd, conn, signal = null
13757
13960
  email
13758
13961
  };
13759
13962
  }
13760
- //#endregion
13761
- //#region src/commands/release-changesets.ts
13963
+ // src/commands/release-changesets.ts
13762
13964
  const releaseForgejoCommand = defineCommand({
13763
13965
  meta: {
13764
13966
  name: "release:changesets",
@@ -13853,11 +14055,12 @@ async function runRelease(config, executor, ciEvent) {
13853
14055
  log$1.info(`Git identity: ${identity.name} <${identity.email}>`);
13854
14056
  const changesetFiles = executor.listChangesetFiles(config.cwd);
13855
14057
  debug(config, `Changeset files found: ${changesetFiles.length > 0 ? changesetFiles.join(", ") : "(none)"}`);
13856
- const bumped = headBumpedVersion(executor, config);
14058
+ const bumpedSet = readBumpedSet(executor, config);
14059
+ const bumped = headBumpedVersion(bumpedSet);
13857
14060
  if (bumped && changesetFiles.length > 0) {
13858
14061
  log$1.info(`HEAD bumped a version and changesets are still pending (${changesetFiles.join(", ")}) -- publishing the merged version first, then versioning the rest.`);
13859
14062
  debug(config, "Entering publish mode, then version mode");
13860
- return publishThenVersion(executor, config);
14063
+ return publishThenVersion(executor, config, bumpedSet);
13861
14064
  }
13862
14065
  if (changesetFiles.length > 0) {
13863
14066
  debug(config, "Entering version mode");
@@ -13869,10 +14072,10 @@ async function runRelease(config, executor, ciEvent) {
13869
14072
  return { mode: "none" };
13870
14073
  }
13871
14074
  debug(config, "Entering publish mode");
13872
- return runPublishMode(executor, config);
14075
+ return runPublishMode(executor, config, bumpedSet);
13873
14076
  }
13874
- async function publishThenVersion(executor, config) {
13875
- const published = await runPublishMode(executor, config);
14077
+ async function publishThenVersion(executor, config, bumpedSet) {
14078
+ const published = await runPublishMode(executor, config, bumpedSet);
13876
14079
  if (published.mode !== "publish") return runVersionMode(executor, config);
13877
14080
  const head = executor.exec("git", ["rev-parse", "HEAD"], { cwd: config.cwd });
13878
14081
  const publishedHead = head.exitCode === 0 ? head.stdout.trim() : "";
@@ -13903,30 +14106,8 @@ async function publishThenVersion(executor, config) {
13903
14106
  restorePublishedCheckout(executor, config, publishedHead);
13904
14107
  }
13905
14108
  }
13906
- function headBumpedVersion(executor, config) {
13907
- const parent = executor.exec("git", [
13908
- "rev-parse",
13909
- "--verify",
13910
- "--quiet",
13911
- "HEAD~1"
13912
- ], { cwd: config.cwd });
13913
- if (parent.exitCode !== 0 || parent.stdout.trim() === "") {
13914
- debug(config, "Publish guard: HEAD has no parent (root commit)");
13915
- return false;
13916
- }
13917
- const diff = executor.exec("git", [
13918
- "diff",
13919
- "HEAD~1",
13920
- "HEAD",
13921
- "--",
13922
- "package.json",
13923
- "packages/*/package.json"
13924
- ], { cwd: config.cwd });
13925
- const removedVersion = /^-\s+"version":\s*"/m.test(diff.stdout);
13926
- const addedVersion = /^\+\s+"version":\s*"/m.test(diff.stdout);
13927
- const bumped = removedVersion && addedVersion;
13928
- debug(config, `Publish guard: HEAD bumped an existing version = ${String(bumped)}`);
13929
- return bumped;
14109
+ function headBumpedVersion(bumpedSet) {
14110
+ return bumpedSet.length > 0;
13930
14111
  }
13931
14112
  function restorePublishedCheckout(executor, config, publishedHead) {
13932
14113
  debug(config, `Restoring the checkout to the published commit ${publishedHead}`);
@@ -13937,8 +14118,7 @@ function restorePublishedCheckout(executor, config, publishedHead) {
13937
14118
  ], { cwd: config.cwd });
13938
14119
  if (reset.exitCode !== 0) throw new FatalError(`Could not restore the checkout to the published commit ${publishedHead}: ${reset.stderr || reset.stdout}`);
13939
14120
  }
13940
- //#endregion
13941
- //#region ../forgejo/src/actions.ts
14121
+ // ../forgejo/src/actions.ts
13942
14122
  const ActionsRunRecordSchema = z.object({
13943
14123
  id: z.number(),
13944
14124
  index_in_repo: z.number().nullish(),
@@ -13983,8 +14163,7 @@ async function dispatchWorkflow$1(executor, conn, options) {
13983
14163
  inputs: options.inputs
13984
14164
  };
13985
14165
  }
13986
- //#endregion
13987
- //#region src/release/publish/dispatch.ts
14166
+ // src/release/publish/dispatch.ts
13988
14167
  async function dispatchWorkflow(resolved, options, executor) {
13989
14168
  if (resolved.type === "forgejo") return dispatchForgejo(resolved.conn, options, executor);
13990
14169
  return dispatchGitHub(options, executor);
@@ -14028,8 +14207,7 @@ function dispatchGitHub(options, executor) {
14028
14207
  inputs: options.inputs
14029
14208
  };
14030
14209
  }
14031
- //#endregion
14032
- //#region src/commands/release-trigger.ts
14210
+ // src/commands/release-trigger.ts
14033
14211
  const releaseTriggerCommand = defineCommand({
14034
14212
  meta: {
14035
14213
  name: "release:trigger",
@@ -14074,8 +14252,7 @@ const releaseTriggerCommand = defineCommand({
14074
14252
  });
14075
14253
  }
14076
14254
  });
14077
- //#endregion
14078
- //#region ../forgejo/src/label-provisioning.ts
14255
+ // ../forgejo/src/label-provisioning.ts
14079
14256
  const LabelSchema$1 = z.object({
14080
14257
  id: z.number(),
14081
14258
  name: z.string(),
@@ -14120,8 +14297,7 @@ const LabelSpecSchema = z.strictObject({
14120
14297
  exclusive: z.boolean().optional()
14121
14298
  });
14122
14299
  z.record(z.string(), z.array(LabelSpecSchema));
14123
- //#endregion
14124
- //#region ../forgejo/src/issue-labels.ts
14300
+ // ../forgejo/src/issue-labels.ts
14125
14301
  const TimelineEntrySchema = z.object({
14126
14302
  id: z.number(),
14127
14303
  type: z.string(),
@@ -14172,8 +14348,7 @@ async function replaceForgejoIssueLabels(executor, conn, number, labelIds) {
14172
14348
  resource: `#${String(number)}`
14173
14349
  }, issueNotFoundMessage(conn, number));
14174
14350
  }
14175
- //#endregion
14176
- //#region ../forgejo/src/issue-comments.ts
14351
+ // ../forgejo/src/issue-comments.ts
14177
14352
  const CommentResponseSchema = z.object({
14178
14353
  id: z.number(),
14179
14354
  body: z.string().nullish(),
@@ -14247,8 +14422,7 @@ async function addForgejoComment(executor, conn, number, body) {
14247
14422
  }, issueNotFoundMessage(conn, number));
14248
14423
  return normalizeComment(parseCommentOrThrow(await res.json()));
14249
14424
  }
14250
- //#endregion
14251
- //#region ../forgejo/src/issues.ts
14425
+ // ../forgejo/src/issues.ts
14252
14426
  const IssueResponseSchema = z.object({
14253
14427
  number: z.number(),
14254
14428
  title: z.string(),
@@ -14322,13 +14496,15 @@ const DependencyResponseSchema = z.object({
14322
14496
  });
14323
14497
  z.array(DependencyResponseSchema);
14324
14498
  function issueListParams(type, query) {
14325
- const params = new URLSearchParams(type === "all" ? {} : { type });
14499
+ const kind = query.type ?? type;
14500
+ const params = new URLSearchParams(kind === "all" ? {} : { type: kind });
14326
14501
  params.set("state", query.state);
14327
14502
  params.set("limit", String(query.limit));
14328
14503
  if (query.label !== void 0) params.set("labels", query.label);
14329
14504
  if (query.page !== void 0) params.set("page", String(query.page));
14330
14505
  if (query.since !== void 0) params.set("since", query.since);
14331
14506
  if (query.sort !== void 0) params.set("sort", query.sort);
14507
+ if (query.q !== void 0) params.set("q", query.q);
14332
14508
  return params;
14333
14509
  }
14334
14510
  async function fetchIssueListPage(executor, conn, params) {
@@ -14429,8 +14605,7 @@ async function setForgejoIssueState(executor, conn, number, state) {
14429
14605
  }, issueNotFoundMessage(conn, number));
14430
14606
  return normalizeIssue(parseIssueOrThrow(await res.json()));
14431
14607
  }
14432
- //#endregion
14433
- //#region ../forgejo/src/issue-api.ts
14608
+ // ../forgejo/src/issue-api.ts
14434
14609
  var IssueNumberRequiredError = class extends FatalError {
14435
14610
  constructor() {
14436
14611
  super("An issue number or issue URL is required.");
@@ -14457,11 +14632,9 @@ function forgejoIssueApi(fetcher, conn) {
14457
14632
  pullRequest: (number) => getForgejoPrDetail(fetcher, conn, number)
14458
14633
  };
14459
14634
  }
14460
- //#endregion
14461
- //#region src/release/forge-timeout.ts
14635
+ // src/release/forge-timeout.ts
14462
14636
  const FORGE_API_TIMEOUT_MS = 12e4;
14463
- //#endregion
14464
- //#region src/release/issue-ref.ts
14637
+ // src/release/issue-ref.ts
14465
14638
  async function ghJson(parse, executor, cwd, args, options) {
14466
14639
  const { notFoundMessage, input, signal } = options;
14467
14640
  const bound = {
@@ -14695,8 +14868,7 @@ function resolveIssueTransport(executor, cwd, target, injectedToken, signal = nu
14695
14868
  conn
14696
14869
  };
14697
14870
  }
14698
- //#endregion
14699
- //#region src/work-status/labels.ts
14871
+ // src/work-status/labels.ts
14700
14872
  const SCOPE_ORDER = [
14701
14873
  "agent",
14702
14874
  "agent-flags",
@@ -14767,8 +14939,7 @@ function ownerOf(names) {
14767
14939
  };
14768
14940
  return { owner: "unclaimed" };
14769
14941
  }
14770
- //#endregion
14771
- //#region src/work-status/claim.ts
14942
+ // src/work-status/claim.ts
14772
14943
  const HANDOVER_ROUTES = "Claim it from the control panel's \"Claim for hand work\", which strips the trigger, or remove the agent label by hand and run pnpm exec bst work:start again.";
14773
14944
  function decideClaim(report, enabled) {
14774
14945
  if (!enabled) return {
@@ -14868,8 +15039,7 @@ async function writeClaim(executor, cwd, target, number) {
14868
15039
  };
14869
15040
  }
14870
15041
  }
14871
- //#endregion
14872
- //#region src/work-status/consent.ts
15042
+ // src/work-status/consent.ts
14873
15043
  async function readAgentConsent(git, defaultBranch) {
14874
15044
  const base = await git.resolveBase(defaultBranch);
14875
15045
  if (base !== `origin/${defaultBranch}`) return {
@@ -14893,8 +15063,7 @@ function readWorkingTree(topLevel) {
14893
15063
  return;
14894
15064
  }
14895
15065
  }
14896
- //#endregion
14897
- //#region ../forgejo/src/issue-run.ts
15066
+ // ../forgejo/src/issue-run.ts
14898
15067
  var NothingToUpdateError = class extends FatalError {
14899
15068
  constructor() {
14900
15069
  super("Nothing to change: neither a title nor a body was given.");
@@ -15175,8 +15344,7 @@ async function branchExists(executor, conn, branch) {
15175
15344
  }, branchNotFoundMessage(conn, branch));
15176
15345
  return true;
15177
15346
  }
15178
- //#endregion
15179
- //#region ../forgejo/src/pr-host.ts
15347
+ // ../forgejo/src/pr-host.ts
15180
15348
  function forgejoPrHost(fetcher, conn) {
15181
15349
  return {
15182
15350
  wipTitles: true,
@@ -15209,8 +15377,7 @@ function forgejoPrEditHost(fetcher, conn) {
15209
15377
  ready: (number, write) => updatePr(fetcher, conn, number, { title: write.title })
15210
15378
  };
15211
15379
  }
15212
- //#endregion
15213
- //#region src/release/github-pr-host.ts
15380
+ // src/release/github-pr-host.ts
15214
15381
  function githubPrHost(executor, cwd, signal) {
15215
15382
  return {
15216
15383
  wipTitles: false,
@@ -15483,8 +15650,7 @@ function githubPrEditHost(executor, cwd, repository) {
15483
15650
  }
15484
15651
  };
15485
15652
  }
15486
- //#endregion
15487
- //#region ../forgejo/src/closing-refs.ts
15653
+ // ../forgejo/src/closing-refs.ts
15488
15654
  const CLOSING_REF = /(?:^|[\s([])(clos(?:e|es|ed)|fix(?:es|ed)?|resolv(?:e|es|ed))(?::[ \t]*|[ \t]+)((?:[\w.-]+\/[\w.-]+)?#\d+)(?![\w-])/gim;
15489
15655
  function capitalize(word) {
15490
15656
  return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
@@ -15514,8 +15680,7 @@ function carryForwardClosingRefs(source, target) {
15514
15680
  const refLines = missing.map((ref) => ref.text).join("\n");
15515
15681
  return target.trim() === "" ? refLines : `${target}\n\n${refLines}`;
15516
15682
  }
15517
- //#endregion
15518
- //#region src/work-status/matching.ts
15683
+ // src/work-status/matching.ts
15519
15684
  function prsClosingIssue(pulls, issue, repository) {
15520
15685
  const bare = `#${String(issue)}`;
15521
15686
  const scoped = `${repository}#${String(issue)}`;
@@ -15535,8 +15700,7 @@ function descriptionsOf(labels) {
15535
15700
  }
15536
15701
  return descriptions;
15537
15702
  }
15538
- //#endregion
15539
- //#region src/work-status/forge-github.ts
15703
+ // src/work-status/forge-github.ts
15540
15704
  const OPEN_PULL_SCAN_LIMIT$1 = 200;
15541
15705
  const GitHubPullListSchema = z.array(z.object({
15542
15706
  number: z.number(),
@@ -15600,8 +15764,7 @@ async function githubLabelDescriptions(executor, cwd, repository) {
15600
15764
  description: label.description ?? void 0
15601
15765
  })));
15602
15766
  }
15603
- //#endregion
15604
- //#region src/work-status/forge.ts
15767
+ // src/work-status/forge.ts
15605
15768
  const OPEN_PULL_SCAN_LIMIT = 200;
15606
15769
  function viewNumber(resolver, number) {
15607
15770
  return viewIssue(resolver, { ref: String(number) });
@@ -15651,8 +15814,7 @@ function resolveWorkForge(executor, cwd, target) {
15651
15814
  labelDescriptions: () => githubLabelDescriptions(executor, cwd, repository)
15652
15815
  };
15653
15816
  }
15654
- //#endregion
15655
- //#region src/work-status/git.ts
15817
+ // src/work-status/git.ts
15656
15818
  const FIELD_SEPARATOR = "";
15657
15819
  function failed(command, stderr) {
15658
15820
  const detail = stderr.trim();
@@ -15789,8 +15951,7 @@ async function createWorkGit(executor, cwd) {
15789
15951
  }
15790
15952
  };
15791
15953
  }
15792
- //#endregion
15793
- //#region src/work-status/prepare.ts
15954
+ // src/work-status/prepare.ts
15794
15955
  function tryResolveWorkForge(executor, topLevel, target) {
15795
15956
  try {
15796
15957
  return resolveWorkForge(executor, topLevel, target);
@@ -15825,8 +15986,7 @@ async function prepareWorkStatus(refText, cwd) {
15825
15986
  forge
15826
15987
  };
15827
15988
  }
15828
- //#endregion
15829
- //#region src/docs-check/discover.ts
15989
+ // src/docs-check/discover.ts
15830
15990
  const DOCS_ROOT = "docs";
15831
15991
  const RETIRED_DIR = "retired";
15832
15992
  const RETIRED_DIR_NAMES$1 = [RETIRED_DIR, "completed"];
@@ -15946,14 +16106,12 @@ function discoverPairs(exec, config) {
15946
16106
  return true;
15947
16107
  });
15948
16108
  }
15949
- //#endregion
15950
- //#region src/describe-forge-error.ts
16109
+ // src/describe-forge-error.ts
15951
16110
  function describeForgeError(error) {
15952
16111
  if (error instanceof RepoTargetEmptyError) return "--repo was given with no repository URL (expected e.g. https://host/owner/repo).";
15953
16112
  if (error instanceof RepoTargetMismatchError) return `--repo disagrees with the issue URL: --repo names ${error.given}, the issue URL names ${error.fromReference}.`;
15954
16113
  }
15955
- //#endregion
15956
- //#region src/chars-check/offenders.ts
16114
+ // src/chars-check/offenders.ts
15957
16115
  const TIER1_OFFENDERS = [
15958
16116
  {
15959
16117
  codepoint: "U+2018",
@@ -16659,8 +16817,7 @@ const nameByCodepoint = new Map([...DEFAULT_OFFENDERS, ...Object.values(OFFENDER
16659
16817
  function offenderNameByCodepoint(codepoint) {
16660
16818
  return nameByCodepoint.get(codepoint);
16661
16819
  }
16662
- //#endregion
16663
- //#region src/chars-check/span-lexer.ts
16820
+ // src/chars-check/span-lexer.ts
16664
16821
  var SpanLexer = class {
16665
16822
  spans = [];
16666
16823
  spanStart = 0;
@@ -16687,8 +16844,7 @@ var SpanLexer = class {
16687
16844
  return this.spans;
16688
16845
  }
16689
16846
  };
16690
- //#endregion
16691
- //#region src/chars-check/context-js-ts.ts
16847
+ // src/chars-check/context-js-ts.ts
16692
16848
  const EXPRESSION_START_PUNCTUATION = /* @__PURE__ */ new Set([
16693
16849
  "(",
16694
16850
  "[",
@@ -17062,8 +17218,7 @@ const jsxFamily = {
17062
17218
  extensions: [".jsx", ".tsx"],
17063
17219
  definition: { classify: (text) => classifyJsTs(text, true) }
17064
17220
  };
17065
- //#endregion
17066
- //#region src/chars-check/context-kt-java.ts
17221
+ // src/chars-check/context-kt-java.ts
17067
17222
  var KtJavaLexer = class extends SpanLexer {
17068
17223
  text;
17069
17224
  kotlin;
@@ -17202,8 +17357,7 @@ const javaFamily = {
17202
17357
  extensions: [".java"],
17203
17358
  definition: { classify: (text) => classifyKtJava(text, false) }
17204
17359
  };
17205
- //#endregion
17206
- //#region src/chars-check/context-markup.ts
17360
+ // src/chars-check/context-markup.ts
17207
17361
  const TAG_START = /[A-Za-z!?]/;
17208
17362
  const TAG_NAME_CHAR = /[A-Za-z0-9:_-]/;
17209
17363
  var MarkupLexer = class extends SpanLexer {
@@ -17378,8 +17532,7 @@ const htmlFamily = {
17378
17532
  extensions: [".html", ".htm"],
17379
17533
  definition: { classify: (text) => classifyMarkup(text, true) }
17380
17534
  };
17381
- //#endregion
17382
- //#region src/chars-check/context-structured.ts
17535
+ // src/chars-check/context-structured.ts
17383
17536
  function triesJsonParse(text) {
17384
17537
  try {
17385
17538
  JSON.parse(text);
@@ -17508,8 +17661,7 @@ function classifyAsProse(text) {
17508
17661
  context: "prose"
17509
17662
  }];
17510
17663
  }
17511
- //#endregion
17512
- //#region src/chars-check/families.ts
17664
+ // src/chars-check/families.ts
17513
17665
  const FAMILIES = [
17514
17666
  jsTsFamily,
17515
17667
  jsxFamily,
@@ -17546,8 +17698,7 @@ const FAMILIES = [
17546
17698
  }
17547
17699
  }
17548
17700
  ];
17549
- //#endregion
17550
- //#region src/chars-check/context.ts
17701
+ // src/chars-check/context.ts
17551
17702
  const proseSpan = (text) => [{
17552
17703
  start: 0,
17553
17704
  end: text.length,
@@ -17584,8 +17735,7 @@ function contextAt(spans, offset) {
17584
17735
  function spanCovering(spans, offset) {
17585
17736
  for (const span of spans) if (offset >= span.start && offset < span.end) return span;
17586
17737
  }
17587
- //#endregion
17588
- //#region src/chars-check/scan.ts
17738
+ // src/chars-check/scan.ts
17589
17739
  const IGNORE_LINE_MARKERS = ["chars-ignore-line", "ascii-ignore-line"];
17590
17740
  function hasIgnoreMarker(line) {
17591
17741
  return IGNORE_LINE_MARKERS.some((marker) => line.includes(marker));
@@ -17673,8 +17823,7 @@ function createRealScanExecutor(rootDir) {
17673
17823
  }
17674
17824
  };
17675
17825
  }
17676
- //#endregion
17677
- //#region src/chars-check/placement.ts
17826
+ // src/chars-check/placement.ts
17678
17827
  const ESCAPE_TOKEN_RE = /\\u\{[0-9a-fA-F]{1,6}\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g;
17679
17828
  const ENTITY_TOKEN_RE = /&#(?:[xX][0-9a-fA-F]{1,6}|[0-9]{1,7});/g;
17680
17829
  const MARKUP_CONTEXTS = /* @__PURE__ */ new Set([
@@ -17833,8 +17982,7 @@ function finishFinding(site, parts, rule) {
17833
17982
  name: offenderNameByCodepoint(codepoint)
17834
17983
  };
17835
17984
  }
17836
- //#endregion
17837
- //#region src/chars-check/rewrite.ts
17985
+ // src/chars-check/rewrite.ts
17838
17986
  function unicodeEscape(offender) {
17839
17987
  let out = "";
17840
17988
  for (let i = 0; i < offender.char.length; i += 1) {
@@ -17919,8 +18067,7 @@ function isFixedNow(offender, decision, fixAmbiguous) {
17919
18067
  function violatesXmlCommentInvariant(commentBody) {
17920
18068
  return commentBody.includes("--") || commentBody.endsWith("-");
17921
18069
  }
17922
- //#endregion
17923
- //#region src/chars-check/fix.ts
18070
+ // src/chars-check/fix.ts
17924
18071
  function precedingBackslashRun(text, offset) {
17925
18072
  let count = 0;
17926
18073
  for (let i = offset - 1; i >= 0 && text[i] === "\\"; i -= 1) count += 1;
@@ -18141,8 +18288,7 @@ function createRealFixExecutor(rootDir) {
18141
18288
  }
18142
18289
  };
18143
18290
  }
18144
- //#endregion
18145
- //#region src/findings/format.ts
18291
+ // src/findings/format.ts
18146
18292
  const FINDINGS_DIR = ".agent/findings";
18147
18293
  const MAX_SLUG_LENGTH = 60;
18148
18294
  const SLUG_FALLBACK = "finding";
@@ -18209,8 +18355,7 @@ function parseFindingHeader(text) {
18209
18355
  function countDeferralNotes(content) {
18210
18356
  return content.split(/\r?\n/).filter((line) => line.startsWith("**Deferred")).length;
18211
18357
  }
18212
- //#endregion
18213
- //#region src/plan-workspace/task-label.ts
18358
+ // src/plan-workspace/task-label.ts
18214
18359
  const HEADING = /^(#{1,6})[ \t]+(.*)$/;
18215
18360
  const BOX = /^([ \t]*)[-*] \[[ xX]\][ \t]*(.*)$/;
18216
18361
  const LABEL = /^Task[ \t]+([0-9]+)([a-z]?)(?![0-9A-Za-z])/;
@@ -18252,8 +18397,7 @@ function taskLabelId(text) {
18252
18397
  if (digits === void 0 || String(Number(digits)) !== digits) return null;
18253
18398
  return `${digits}${match?.[2] ?? ""}`;
18254
18399
  }
18255
- //#endregion
18256
- //#region src/plan-workspace/plan-units.ts
18400
+ // src/plan-workspace/plan-units.ts
18257
18401
  const AFTER_LABEL = /^[ \t]*(?::|\.|--?)?[ \t]*/;
18258
18402
  function planTask(headingText, label) {
18259
18403
  const unwrapped = headingText.replace(/^(\*\*|__)/, "").replace(/(\*\*|__)$/, "");
@@ -18262,52 +18406,81 @@ function planTask(headingText, label) {
18262
18406
  title: unwrapped.slice(unwrapped.indexOf(label) + label.length).replace(AFTER_LABEL, "").trim()
18263
18407
  };
18264
18408
  }
18265
- function groupPlanUnits(text, boxes) {
18409
+ function walkUnits(text, boxes) {
18266
18410
  const lines = text.split("\n");
18267
18411
  const fenced = fencedLines(lines);
18268
18412
  const boxAtLine = /* @__PURE__ */ new Map();
18269
18413
  for (const box of boxes) boxAtLine.set(box.line, box);
18270
18414
  const units = [];
18271
18415
  const open = [];
18416
+ const unitAtLine = lines.map(() => null);
18417
+ let loneBoxUnit = null;
18418
+ const inEffect = () => {
18419
+ const section = open[open.length - 1];
18420
+ if (section !== void 0) return section.index;
18421
+ return loneBoxUnit;
18422
+ };
18272
18423
  for (const [index, rawLine] of lines.entries()) {
18273
- if (fenced[index] === true) continue;
18274
18424
  const line = rawLine ?? "";
18425
+ if (fenced[index] === true) {
18426
+ unitAtLine[index] = inEffect();
18427
+ continue;
18428
+ }
18275
18429
  const heading = HEADING.exec(line);
18276
18430
  if (heading !== null) {
18277
18431
  const level = (heading[1] ?? "").length;
18278
18432
  while (open.length > 0 && (open[open.length - 1]?.level ?? 0) >= level) open.pop();
18433
+ loneBoxUnit = null;
18279
18434
  const headingText = (heading[2] ?? "").trim();
18280
18435
  const label = taskLabelId(headingText);
18281
- if (label === null) continue;
18436
+ if (label === null) {
18437
+ unitAtLine[index] = inEffect();
18438
+ continue;
18439
+ }
18282
18440
  const unit = {
18283
18441
  key: headingText,
18284
18442
  task: planTask(headingText, label),
18285
18443
  boxes: []
18286
18444
  };
18445
+ const unitIndex = units.length;
18287
18446
  units.push(unit);
18288
18447
  open.push({
18289
18448
  level,
18290
- unit
18449
+ unit,
18450
+ index: unitIndex
18291
18451
  });
18452
+ unitAtLine[index] = unitIndex;
18292
18453
  continue;
18293
18454
  }
18294
18455
  const box = boxAtLine.get(index);
18295
- if (box === void 0) continue;
18456
+ if (box === void 0) {
18457
+ unitAtLine[index] = inEffect();
18458
+ continue;
18459
+ }
18296
18460
  const section = open[open.length - 1];
18297
18461
  if (section !== void 0) {
18298
18462
  section.unit.boxes.push(box);
18463
+ unitAtLine[index] = section.index;
18299
18464
  continue;
18300
18465
  }
18466
+ const unitIndex = units.length;
18301
18467
  units.push({
18302
18468
  key: box.title,
18303
18469
  task: null,
18304
18470
  boxes: [box]
18305
18471
  });
18472
+ unitAtLine[index] = unitIndex;
18473
+ loneBoxUnit = unitIndex;
18306
18474
  }
18307
- return units;
18475
+ return {
18476
+ units,
18477
+ unitAtLine
18478
+ };
18479
+ }
18480
+ function groupPlanUnits(text, boxes) {
18481
+ return walkUnits(text, boxes).units;
18308
18482
  }
18309
- //#endregion
18310
- //#region src/plan-workspace/plan-boxes.ts
18483
+ // src/plan-workspace/plan-boxes.ts
18311
18484
  const BOX_LINE_REGEX = /^[ \t]*[-*] \[([ xX])\][ \t]*(.*)$/;
18312
18485
  const HEADING_REGEX = /^#{1,6} /;
18313
18486
  const DECLINED_LINE_REGEX = /^[ \t]*(?:[-*][ \t]+)?\*\*Declined:\*\*[ \t]*(.*)$/;
@@ -18375,7 +18548,7 @@ function deferredLineOf(lines, fenced, start, blockEnd) {
18375
18548
  if (fenced[index] === true) continue;
18376
18549
  const match = DEFERRED_LINE_REGEX.exec(lines[index] ?? "");
18377
18550
  if (match === null) continue;
18378
- return (match[1] ?? "").trim();
18551
+ return boxParagraph(lines, fenced, index, blockEnd, (match[1] ?? "").trim());
18379
18552
  }
18380
18553
  return null;
18381
18554
  }
@@ -18509,7 +18682,7 @@ function parsePlanBoxes(planText) {
18509
18682
  if (fenced[index] === true) continue;
18510
18683
  const noteMatch = NOTE_LINE_REGEX.exec(lines[index] ?? "");
18511
18684
  if (noteMatch === null) continue;
18512
- const text = (noteMatch[2] ?? "").trim();
18685
+ const text = boxParagraph(lines, fenced, index, blockEnd, (noteMatch[2] ?? "").trim());
18513
18686
  if (text !== "") notes.push({
18514
18687
  kind: noteKind(noteMatch[1] ?? ""),
18515
18688
  text
@@ -18520,7 +18693,7 @@ function parsePlanBoxes(planText) {
18520
18693
  if (fenced[index] === true) continue;
18521
18694
  const declinedMatch = DECLINED_LINE_REGEX.exec(lines[index] ?? "");
18522
18695
  if (declinedMatch === null) continue;
18523
- const remainder = (declinedMatch[1] ?? "").trim();
18696
+ const remainder = boxParagraph(lines, fenced, index, blockEnd, (declinedMatch[1] ?? "").trim());
18524
18697
  if (remainder !== "") {
18525
18698
  reason = remainder;
18526
18699
  break;
@@ -18547,8 +18720,7 @@ function parsePlanBoxes(planText) {
18547
18720
  function countOutstandingBoxes(planText, options) {
18548
18721
  return parsePlanBoxes(planText).filter((box) => isOutstanding(box, options)).length;
18549
18722
  }
18550
- //#endregion
18551
- //#region src/plan-workspace/status.ts
18723
+ // src/plan-workspace/status.ts
18552
18724
  const RETIRED_SEGMENT = /(^|\/)retired\//;
18553
18725
  function enclosingTaskLabel(planText, line) {
18554
18726
  const lines = planText.split("\n");
@@ -18593,8 +18765,7 @@ function planStatus(planText, planPath) {
18593
18765
  notes
18594
18766
  };
18595
18767
  }
18596
- //#endregion
18597
- //#region ../cli-kit/src/agent-markers.ts
18768
+ // ../cli-kit/src/agent-markers.ts
18598
18769
  const RUN_COMMENT_MARKER = "**agent:run**";
18599
18770
  const REVIEW_COMMENT_MARKER = "**agent:review**";
18600
18771
  const AGENT_NOTE_MARKER = "**bst agent**";
@@ -18621,8 +18792,7 @@ const AGENT_MARKERS = [
18621
18792
  function hasAgentMarker(body) {
18622
18793
  return AGENT_MARKERS.some((marker) => body.startsWith(marker));
18623
18794
  }
18624
- //#endregion
18625
- //#region src/work-status/feedback.ts
18795
+ // src/work-status/feedback.ts
18626
18796
  const EXCERPT_LINES = 5;
18627
18797
  function excerpt(body) {
18628
18798
  const kept = [];
@@ -18669,8 +18839,7 @@ function feedbackSince(comments, headCommitDate, cap, agentLogin) {
18669
18839
  truncated
18670
18840
  };
18671
18841
  }
18672
- //#endregion
18673
- //#region src/work-status/report.ts
18842
+ // src/work-status/report.ts
18674
18843
  const COMMIT_CAP = 20;
18675
18844
  const FEEDBACK_CAP = 20;
18676
18845
  function ok(value) {
@@ -19039,8 +19208,7 @@ async function buildWorkStatus(deps, ref) {
19039
19208
  commits: await section(() => commitsSection(inputs))
19040
19209
  };
19041
19210
  }
19042
- //#endregion
19043
- //#region src/work-status/render.ts
19211
+ // src/work-status/render.ts
19044
19212
  const FOOTER = "Advice, not a gate: this is what the reads found, not a verdict.";
19045
19213
  const FEEDBACK_CAVEAT = "The feedback cutoff is the newest agent run or review comment on the pull request and is approximate, and review comments pinned to diff lines are not in the thread this reads.";
19046
19214
  function short(sha) {
@@ -19137,8 +19305,7 @@ function renderWorkStatus(report, options) {
19137
19305
  lines.push(report.feedback.state === "ok" ? `${FOOTER} ${FEEDBACK_CAVEAT}` : FOOTER);
19138
19306
  return lines.join("\n");
19139
19307
  }
19140
- //#endregion
19141
- //#region src/commands/work-start.ts
19308
+ // src/commands/work-start.ts
19142
19309
  function claimLine(result) {
19143
19310
  if (result.outcome === "claimed") return `claim: claimed -- ${result.label ?? "agent-flags/human-driven"} is on this object.`;
19144
19311
  if (result.outcome === "already-claimed") return "claim: already-claimed -- the flag is already on it; nothing was written.";
@@ -19207,8 +19374,7 @@ const workStartCommand = defineCommand({
19207
19374
  if (exitCode !== 0) process.exitCode = exitCode;
19208
19375
  }
19209
19376
  });
19210
- //#endregion
19211
- //#region src/commands/work-status.ts
19377
+ // src/commands/work-status.ts
19212
19378
  const workStatusCommand = defineCommand({
19213
19379
  meta: {
19214
19380
  name: "work:status",
@@ -19248,8 +19414,7 @@ const workStatusCommand = defineCommand({
19248
19414
  out.text(renderWorkStatus(report, { agentEnabled: consent.enabled }));
19249
19415
  }
19250
19416
  });
19251
- //#endregion
19252
- //#region ../cli-kit/src/workflow-inputs.ts
19417
+ // ../cli-kit/src/workflow-inputs.ts
19253
19418
  const INPUT_FLAG = "--input";
19254
19419
  const INPUT_FLAG_EQ = "--input=";
19255
19420
  function collectInputArgs(rawArgs) {
@@ -19276,8 +19441,7 @@ function parseInputs(raw) {
19276
19441
  }
19277
19442
  return inputs;
19278
19443
  }
19279
- //#endregion
19280
- //#region src/commands/workflow-dispatch.ts
19444
+ // src/commands/workflow-dispatch.ts
19281
19445
  const workflowDispatchCommand = defineCommand({
19282
19446
  meta: {
19283
19447
  name: "workflow:dispatch",
@@ -19326,8 +19490,7 @@ const workflowDispatchCommand = defineCommand({
19326
19490
  });
19327
19491
  }
19328
19492
  });
19329
- //#endregion
19330
- //#region ../forgejo/src/pr-merge.ts
19493
+ // ../forgejo/src/pr-merge.ts
19331
19494
  async function mergePr(executor, conn, prNumber, options) {
19332
19495
  const url = `${conn.serverUrl}/api/v1/repos/${conn.repository}/pulls/${String(prNumber)}/merge`;
19333
19496
  const body = {
@@ -19430,16 +19593,14 @@ z.object({
19430
19593
  sha: z.string()
19431
19594
  })
19432
19595
  });
19433
- //#endregion
19434
- //#region ../cli-kit/src/env-override.ts
19596
+ // ../cli-kit/src/env-override.ts
19435
19597
  function envMsOverride(raw, productionMs) {
19436
19598
  if (raw === void 0) return productionMs;
19437
19599
  const parsed = Number(raw.trim());
19438
19600
  if (!Number.isSafeInteger(parsed) || parsed <= 0) return productionMs;
19439
19601
  return Math.min(parsed, productionMs);
19440
19602
  }
19441
- //#endregion
19442
- //#region src/release/publish/version-merge.ts
19603
+ // src/release/publish/version-merge.ts
19443
19604
  function evaluateVersionPr(state) {
19444
19605
  const label = `PR #${String(state.prNumber)}`;
19445
19606
  if (!state.open) return {
@@ -19620,8 +19781,7 @@ function mergeVersionPrGitHub(executor, options) {
19620
19781
  status: "merged"
19621
19782
  };
19622
19783
  }
19623
- //#endregion
19624
- //#region src/commands/changesets-merge.ts
19784
+ // src/commands/changesets-merge.ts
19625
19785
  const releaseMergeCommand = defineCommand({
19626
19786
  meta: {
19627
19787
  name: "changesets:merge",
@@ -19653,8 +19813,7 @@ const releaseMergeCommand = defineCommand({
19653
19813
  out.json(result);
19654
19814
  }
19655
19815
  });
19656
- //#endregion
19657
- //#region ../forgejo/src/pr-upsert.ts
19816
+ // ../forgejo/src/pr-upsert.ts
19658
19817
  const COMMIT_TYPES = /* @__PURE__ */ new Set([
19659
19818
  "feat",
19660
19819
  "fix",
@@ -19862,8 +20021,7 @@ async function runPrUpsert$1(git, host, options) {
19862
20021
  ...shape
19863
20022
  };
19864
20023
  }
19865
- //#endregion
19866
- //#region ../forgejo/src/pr-upsert-messages.ts
20024
+ // ../forgejo/src/pr-upsert-messages.ts
19867
20025
  function describePrModeError(error, commands) {
19868
20026
  if (error.reason === "already-open") {
19869
20027
  const createVerb = commands.create.split(" ").at(-1) ?? commands.create;
@@ -19942,8 +20100,7 @@ function formatPrUpdate(result, rewrites, flags) {
19942
20100
  body: null
19943
20101
  };
19944
20102
  }
19945
- //#endregion
19946
- //#region src/release/pull-request.ts
20103
+ // src/release/pull-request.ts
19947
20104
  const BST_COMMANDS = {
19948
20105
  create: "pnpm exec bst pr:create",
19949
20106
  update: "pnpm exec bst pr:update"
@@ -19990,8 +20147,7 @@ async function runPrUpsert(executor, options) {
19990
20147
  function warnClosingLinks(report) {
19991
20148
  for (const line of describeClosingLinks(report, BST_FLAGS)) log$1.warn(line);
19992
20149
  }
19993
- //#endregion
19994
- //#region ../cli-kit/src/body-source.ts
20150
+ // ../cli-kit/src/body-source.ts
19995
20151
  function tryRead(read, label) {
19996
20152
  try {
19997
20153
  return read();
@@ -20011,8 +20167,7 @@ function readBodySource(body, bodyFile, options = {}) {
20011
20167
  if (!existsSync(bodyFile)) throw new FatalError(`${flags.file} not found: ${bodyFile}`);
20012
20168
  return tryRead(() => readFileSync(bodyFile, "utf-8"), `${flags.file} "${bodyFile}"`);
20013
20169
  }
20014
- //#endregion
20015
- //#region src/commands/pr-create.ts
20170
+ // src/commands/pr-create.ts
20016
20171
  const prCreateCommand = defineCommand({
20017
20172
  meta: {
20018
20173
  name: "pr:create",
@@ -20084,8 +20239,7 @@ const prCreateCommand = defineCommand({
20084
20239
  if (summary.body !== null) note(summary.body.text, summary.body.heading);
20085
20240
  }
20086
20241
  });
20087
- //#endregion
20088
- //#region ../forgejo/src/pr-edit.ts
20242
+ // ../forgejo/src/pr-edit.ts
20089
20243
  const MERGEABLE_RECHECK_DELAY_MS = 2e3;
20090
20244
  function isOpen(live) {
20091
20245
  return live.state === "open" && live.merged === false;
@@ -20212,23 +20366,20 @@ function renderPrReady(result) {
20212
20366
  if (result.action === "would-ready") return `Dry run: pull request ${number} would stop being a draft, reading "${result.title}".`;
20213
20367
  return `Dry run: pull request ${number} would read "${result.title}".`;
20214
20368
  }
20215
- //#endregion
20216
- //#region ../forgejo/src/pr-number.ts
20369
+ // ../forgejo/src/pr-number.ts
20217
20370
  function parsePrNumber(raw) {
20218
20371
  const value = Number(raw);
20219
20372
  if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < 1) throw new FatalError(`Invalid pull request number "${raw}" (expected a positive integer).`);
20220
20373
  return value;
20221
20374
  }
20222
- //#endregion
20223
- //#region src/release/pr-edit-host.ts
20375
+ // src/release/pr-edit-host.ts
20224
20376
  function resolvePrEditHost(executor, cwd, repo) {
20225
20377
  const resolved = resolveIssueTransport(executor, cwd, parseRepoTarget(repo));
20226
20378
  if (resolved.target.hostname === "github.com") return githubPrEditHost(executor, cwd, resolved.target.repository);
20227
20379
  if (resolved.conn === void 0) throw new UnexpectedError(`Resolved a non-github.com target (${resolved.target.hostname}) with no Forgejo connection.`);
20228
20380
  return forgejoPrEditHost(executor, resolved.conn);
20229
20381
  }
20230
- //#endregion
20231
- //#region src/commands/pr-ready.ts
20382
+ // src/commands/pr-ready.ts
20232
20383
  const prReadyCommand = defineCommand({
20233
20384
  meta: {
20234
20385
  name: "pr:ready",
@@ -20272,8 +20423,7 @@ const prReadyCommand = defineCommand({
20272
20423
  out.text(renderPrReady(result));
20273
20424
  }
20274
20425
  });
20275
- //#endregion
20276
- //#region src/commands/pr-retarget.ts
20426
+ // src/commands/pr-retarget.ts
20277
20427
  const prRetargetCommand = defineCommand({
20278
20428
  meta: {
20279
20429
  name: "pr:retarget",
@@ -20320,8 +20470,7 @@ const prRetargetCommand = defineCommand({
20320
20470
  out.text(renderPrRetarget(result));
20321
20471
  }
20322
20472
  });
20323
- //#endregion
20324
- //#region src/commands/pr-update.ts
20473
+ // src/commands/pr-update.ts
20325
20474
  const prUpdateCommand = defineCommand({
20326
20475
  meta: {
20327
20476
  name: "pr:update",
@@ -20390,8 +20539,7 @@ const prUpdateCommand = defineCommand({
20390
20539
  if (summary.body !== null) note(summary.body.text, summary.body.heading);
20391
20540
  }
20392
20541
  });
20393
- //#endregion
20394
- //#region src/release/publish/simple.ts
20542
+ // src/release/publish/simple.ts
20395
20543
  function observedTagPrefix(tag, version) {
20396
20544
  if (tag.endsWith(version)) {
20397
20545
  const prefix = tag.slice(0, tag.length - version.length);
@@ -20617,8 +20765,7 @@ async function createPlatformRelease(executor, config, tag, version) {
20617
20765
  log$1.info(`Created GitHub release for ${tag}`);
20618
20766
  return true;
20619
20767
  }
20620
- //#endregion
20621
- //#region src/commands/release-simple.ts
20768
+ // src/commands/release-simple.ts
20622
20769
  const releaseSimpleCommand = defineCommand({
20623
20770
  meta: {
20624
20771
  name: "release:simple",
@@ -20706,8 +20853,7 @@ const releaseSimpleCommand = defineCommand({
20706
20853
  }
20707
20854
  }
20708
20855
  });
20709
- //#endregion
20710
- //#region src/commands/release-assets.ts
20856
+ // src/commands/release-assets.ts
20711
20857
  const releaseAssetsCommand = defineCommand({
20712
20858
  meta: {
20713
20859
  name: "release:assets",
@@ -20744,8 +20890,7 @@ const releaseAssetsCommand = defineCommand({
20744
20890
  await runReleaseAssets(createRealExecutor$1(), config);
20745
20891
  }
20746
20892
  });
20747
- //#endregion
20748
- //#region src/lint-types/executor.ts
20893
+ // src/lint-types/executor.ts
20749
20894
  function runViaShim(args, cwd) {
20750
20895
  const result = spawnViaShim("pnpm", args, {
20751
20896
  cwd,
@@ -20784,11 +20929,9 @@ function createRealLintTypesExecutor() {
20784
20929
  };
20785
20930
  } };
20786
20931
  }
20787
- //#endregion
20788
- //#region src/lint-types/phase.ts
20932
+ // src/lint-types/phase.ts
20789
20933
  const LINT_TYPES_PHASE = "enforce";
20790
- //#endregion
20791
- //#region src/lint-types/report.ts
20934
+ // src/lint-types/report.ts
20792
20935
  function formatRuleCode(code) {
20793
20936
  if (code === void 0) return "(no rule code)";
20794
20937
  const match = /^([^()]+)\(([^()]+)\)$/.exec(code);
@@ -20851,8 +20994,7 @@ function buildLintTypesResult(run, phase, strictTypeAware) {
20851
20994
  marker: run.findings.length > 0 && exitCode === 0 ? formatWarnMarker(run.findings.length) : null
20852
20995
  };
20853
20996
  }
20854
- //#endregion
20855
- //#region src/lint-types/schema.ts
20997
+ // src/lint-types/schema.ts
20856
20998
  const SpanSchema = z.object({
20857
20999
  offset: z.number(),
20858
21000
  length: z.number(),
@@ -20883,8 +21025,7 @@ function parseOxlintJson(raw) {
20883
21025
  if (!result.success) throw new FatalError(`oxlint -f json output doesn't match the expected shape: ${result.error.message}\nOutput: ${rawSnippet(raw)}`);
20884
21026
  return result.data;
20885
21027
  }
20886
- //#endregion
20887
- //#region src/lint-types/subtract.ts
21028
+ // src/lint-types/subtract.ts
20888
21029
  function diagnosticKey(diagnostic) {
20889
21030
  const span = diagnostic.labels[0]?.span;
20890
21031
  return JSON.stringify([
@@ -20899,8 +21040,7 @@ function subtractDiagnostics(typeAware, plain) {
20899
21040
  const plainKeys = new Set(plain.map(diagnosticKey));
20900
21041
  return typeAware.filter((diagnostic) => !plainKeys.has(diagnosticKey(diagnostic)));
20901
21042
  }
20902
- //#endregion
20903
- //#region src/lint-types/run.ts
21043
+ // src/lint-types/run.ts
20904
21044
  const MISSING_BINARY_MARKER = "Failed to find tsgolint executable";
20905
21045
  function oxlintArgs(typeAware, extraArgs) {
20906
21046
  const base = [
@@ -20941,8 +21081,7 @@ function runLintTypes(executor, targetDir, extraArgs = []) {
20941
21081
  findings: subtractDiagnostics(typeAwareDoc.diagnostics, plainDoc.diagnostics)
20942
21082
  };
20943
21083
  }
20944
- //#endregion
20945
- //#region src/commands/lint-types.ts
21084
+ // src/commands/lint-types.ts
20946
21085
  const lintTypesCommand = defineCommand({
20947
21086
  meta: {
20948
21087
  name: "lint:types",
@@ -20974,8 +21113,7 @@ const lintTypesCommand = defineCommand({
20974
21113
  process.exitCode = exitCode;
20975
21114
  }
20976
21115
  });
20977
- //#endregion
20978
- //#region src/checks/lint-report.ts
21116
+ // src/checks/lint-report.ts
20979
21117
  function buildLintReportResult(doc, oxlintExitCode) {
20980
21118
  const warnings = doc.diagnostics.filter((d) => d.severity === "warning").length;
20981
21119
  const errors = doc.diagnostics.length - warnings;
@@ -20991,8 +21129,7 @@ function buildLintReportResult(doc, oxlintExitCode) {
20991
21129
  marker: oxlintExitCode === 0 && warnings > 0 ? formatWarnMarker(warnings) : null
20992
21130
  };
20993
21131
  }
20994
- //#endregion
20995
- //#region src/commands/lint-report.ts
21132
+ // src/commands/lint-report.ts
20996
21133
  const lintReportCommand = defineCommand({
20997
21134
  meta: {
20998
21135
  name: "lint:report",
@@ -21031,8 +21168,7 @@ const lintReportCommand = defineCommand({
21031
21168
  process.exitCode = exitCode;
21032
21169
  }
21033
21170
  });
21034
- //#endregion
21035
- //#region src/commands/publish-docker.ts
21171
+ // src/commands/publish-docker.ts
21036
21172
  function requireDockerCredentials(registryHost) {
21037
21173
  const username = process.env["DOCKER_USERNAME"];
21038
21174
  const password = process.env["DOCKER_PASSWORD"];
@@ -21080,12 +21216,16 @@ const publishDockerCommand = defineCommand({
21080
21216
  type: "boolean",
21081
21217
  description: "Build and tag images but skip login, push, and logout"
21082
21218
  },
21219
+ image: {
21220
+ type: "string",
21221
+ description: "Publish only this image, by its final image name, without the release bound (repeatable)"
21222
+ },
21083
21223
  verbose: {
21084
21224
  type: "boolean",
21085
21225
  description: "Emit detailed debug logging"
21086
21226
  }
21087
21227
  },
21088
- async run({ args }) {
21228
+ async run({ args, rawArgs }) {
21089
21229
  const cwd = process.cwd();
21090
21230
  const { registryHost, registryNamespace } = resolveRegistryConfig(cwd);
21091
21231
  const { username, password } = requireDockerCredentials(registryHost);
@@ -21096,13 +21236,14 @@ const publishDockerCommand = defineCommand({
21096
21236
  username,
21097
21237
  password,
21098
21238
  dryRun: args["dry-run"] === true,
21099
- verbose: args.verbose === true || isEnvVerbose()
21239
+ verbose: args.verbose === true || isEnvVerbose(),
21240
+ releaseStrategy: loadToolingConfig(cwd)?.releaseStrategy ?? "none",
21241
+ images: collectFlagValues(rawArgs, "--image")
21100
21242
  };
21101
21243
  runDockerPublish(createRealExecutor$1(), config);
21102
21244
  }
21103
21245
  });
21104
- //#endregion
21105
- //#region src/commands/docker-build.ts
21246
+ // src/commands/docker-build.ts
21106
21247
  function detectSubpackage(cwd) {
21107
21248
  const parent = path.dirname(cwd);
21108
21249
  if (path.basename(parent) === "packages" && existsSync(path.join(parent, "..", "package.json"))) return {
@@ -21154,8 +21295,7 @@ const dockerBuildCommand = defineCommand({
21154
21295
  });
21155
21296
  }
21156
21297
  });
21157
- //#endregion
21158
- //#region src/docker-check/executor.ts
21298
+ // src/docker-check/executor.ts
21159
21299
  function execCapture(file, args, options) {
21160
21300
  const spawnOptions = {
21161
21301
  cwd: options?.cwd,
@@ -21228,8 +21368,7 @@ function createRealExecutor() {
21228
21368
  logError: (msg) => console.error(msg)
21229
21369
  };
21230
21370
  }
21231
- //#endregion
21232
- //#region src/docker-check/free-port.ts
21371
+ // src/docker-check/free-port.ts
21233
21372
  function findFreePort() {
21234
21373
  return new Promise((resolve, reject) => {
21235
21374
  const server = net.createServer();
@@ -21249,8 +21388,7 @@ function findFreePort() {
21249
21388
  });
21250
21389
  });
21251
21390
  }
21252
- //#endregion
21253
- //#region src/docker-check/compose.ts
21391
+ // src/docker-check/compose.ts
21254
21392
  const ContainerInfoSchema = z.object({
21255
21393
  Service: z.string(),
21256
21394
  Health: z.string(),
@@ -21455,11 +21593,10 @@ function composePs(executor, config) {
21455
21593
  return [];
21456
21594
  }
21457
21595
  }
21458
- //#endregion
21459
- //#region src/docker-check/health.ts
21596
+ // src/docker-check/health.ts
21460
21597
  const DOCKER_RUN_START_FAILURE_EXIT_CODE = 125;
21461
21598
  const PROBE_TIMEOUT_SECONDS = "5";
21462
- const PROBE_IMAGE = "curlimages/curl:8.23.0@sha256:a134550be58ab783810e613ae96fd253c38f7bdd16d9bf9be350700c7a29ac06";
21599
+ const PROBE_IMAGE = "curlimages/curl:8.23.0@sha256:11e64e28c5f58c8d93ee95fcf22ac055f48b0bc440e0ce7d8013bbb5ad6aa8ac";
21463
21600
  function getContainerHealth(containers, serviceName) {
21464
21601
  return containers.find((c) => c.Service === serviceName)?.Health ?? "unknown";
21465
21602
  }
@@ -21512,8 +21649,7 @@ async function checkHttpHealth(executor, compose, check, containers) {
21512
21649
  return false;
21513
21650
  }
21514
21651
  }
21515
- //#endregion
21516
- //#region src/docker-check/check.ts
21652
+ // src/docker-check/check.ts
21517
21653
  const DEFAULT_TIMEOUT_MS = 12e4;
21518
21654
  const DEFAULT_POLL_INTERVAL_MS = 5e3;
21519
21655
  function withFilledVariables(executor, config) {
@@ -21709,16 +21845,14 @@ async function runDockerCheck(executor, rawConfig) {
21709
21845
  disposeExit();
21710
21846
  }
21711
21847
  }
21712
- //#endregion
21713
- //#region src/docker-check/project-name.ts
21848
+ // src/docker-check/project-name.ts
21714
21849
  function deriveProjectName(repoName, env = process.env) {
21715
21850
  return `${sanitize(repoName)}-check-${sanitize(env["GITHUB_RUN_ID"] ?? env["CI_RUN_ID"] ?? String(process.pid))}`;
21716
21851
  }
21717
21852
  function sanitize(name) {
21718
21853
  return name.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "repo";
21719
21854
  }
21720
- //#endregion
21721
- //#region src/commands/docker-check.ts
21855
+ // src/commands/docker-check.ts
21722
21856
  function toHttpHealthChecks(checks) {
21723
21857
  return checks.map((check) => ({
21724
21858
  name: check.name,
@@ -21843,8 +21977,7 @@ const dockerCheckCommand = defineCommand({
21843
21977
  }
21844
21978
  }
21845
21979
  });
21846
- //#endregion
21847
- //#region src/commands/docker-sweep.ts
21980
+ // src/commands/docker-sweep.ts
21848
21981
  function parseMaxAgeHours(raw) {
21849
21982
  const value = Number(raw);
21850
21983
  if (raw.trim() === "" || !Number.isFinite(value) || value < 0) throw new FatalError(`--max-age must be a non-negative number of hours, got "${raw}"`);
@@ -21885,8 +22018,7 @@ const dockerSweepCommand = defineCommand({
21885
22018
  out.text(`${verb} ${String(report.containers.length)} container(s), ${String(report.networks.length)} network(s), ${String(report.volumes.length)} volume(s).${failed}`);
21886
22019
  }
21887
22020
  });
21888
- //#endregion
21889
- //#region src/commands/hooks-audit.ts
22021
+ // src/commands/hooks-audit.ts
21890
22022
  function findProjectRoot(cwd) {
21891
22023
  let dir = path.resolve(cwd);
21892
22024
  while (true) {
@@ -22033,8 +22165,7 @@ const hooksAuditCommand = defineCommand({
22033
22165
  printSection(out, "None commands:", none, 10);
22034
22166
  }
22035
22167
  });
22036
- //#endregion
22037
- //#region src/commands/hooks-sync.ts
22168
+ // src/commands/hooks-sync.ts
22038
22169
  function buildMinimalConfig(targetDir) {
22039
22170
  const isMonorepo = existsSync(path.join(targetDir, "pnpm-workspace.yaml"));
22040
22171
  return {
@@ -22165,8 +22296,7 @@ async function runHooksCheck(config) {
22165
22296
  exitCode: 1
22166
22297
  };
22167
22298
  }
22168
- //#endregion
22169
- //#region src/commands/setup-agent.ts
22299
+ // src/commands/setup-agent.ts
22170
22300
  const RawToolingConfigSchema = z.record(z.string(), z.unknown());
22171
22301
  function previousState(saved) {
22172
22302
  const enabled = saved.agent?.enabled;
@@ -22261,8 +22391,7 @@ const setupAgentCommand = defineCommand({
22261
22391
  process.exitCode = report.exitCode;
22262
22392
  }
22263
22393
  });
22264
- //#endregion
22265
- //#region src/commands/setup-secrets.ts
22394
+ // src/commands/setup-secrets.ts
22266
22395
  function isCancelled(value) {
22267
22396
  return clack.isCancel(value);
22268
22397
  }
@@ -22578,8 +22707,7 @@ const setupSecretsCommand = defineCommand({
22578
22707
  clack.outro(`Done! ${String(result.secrets.length)} ${levelLabel} secret(s) on ${platform}:${tokenLine}\n${secretLines}`);
22579
22708
  }
22580
22709
  });
22581
- //#endregion
22582
- //#region src/release/publish/webhook.ts
22710
+ // src/release/publish/webhook.ts
22583
22711
  function buildSimplePayload(options) {
22584
22712
  const repository = options.repository ?? "";
22585
22713
  const serverUrl = options.serverUrl ?? "https://github.com";
@@ -22680,8 +22808,7 @@ async function sendWebhookWithLogging(url, secret, payload) {
22680
22808
  }
22681
22809
  return result;
22682
22810
  }
22683
- //#endregion
22684
- //#region src/commands/webhook-send.ts
22811
+ // src/commands/webhook-send.ts
22685
22812
  function resolveWebhookPayload(args, env = process.env) {
22686
22813
  if (args.tag || args.repository) return buildSimplePayload({
22687
22814
  tag: args.tag ?? "",
@@ -22765,8 +22892,7 @@ const webhookSendCommand = defineCommand({
22765
22892
  if (!result.ok && strict) process.exitCode = 1;
22766
22893
  }
22767
22894
  });
22768
- //#endregion
22769
- //#region src/coverage-tracking/derive.ts
22895
+ // src/coverage-tracking/derive.ts
22770
22896
  function emptySums() {
22771
22897
  return {
22772
22898
  linesTotal: 0,
@@ -22838,8 +22964,7 @@ function deriveRecord(summary, options) {
22838
22964
  ...baseline
22839
22965
  };
22840
22966
  }
22841
- //#endregion
22842
- //#region src/coverage-tracking/executor.ts
22967
+ // src/coverage-tracking/executor.ts
22843
22968
  function createRealCoverageExecutor() {
22844
22969
  return { exec(file, args, options) {
22845
22970
  const result = execCapture$2(file, args, {
@@ -22855,8 +22980,7 @@ function createRealCoverageExecutor() {
22855
22980
  };
22856
22981
  } };
22857
22982
  }
22858
- //#endregion
22859
- //#region src/coverage-tracking/render.ts
22983
+ // src/coverage-tracking/render.ts
22860
22984
  const PCT_WIDTH = 7;
22861
22985
  function pad(value, width) {
22862
22986
  if (value.length >= width) return value;
@@ -22960,16 +23084,14 @@ function formatTimestamp(iso) {
22960
23084
  if (Number.isNaN(date.getTime())) return iso;
22961
23085
  return `${String(date.getUTCFullYear())}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(date.getUTCDate()).padStart(2, "0")}`;
22962
23086
  }
22963
- //#endregion
22964
- //#region src/commands/coverage-missing-summary.ts
23087
+ // src/commands/coverage-missing-summary.ts
22965
23088
  const COVERAGE_SUMMARY_FILE$3 = "coverage/coverage-summary.json";
22966
23089
  function missingSummaryMessage(targetDir) {
22967
23090
  const base = `${COVERAGE_SUMMARY_FILE$3} not found. Run \`pnpm test:coverage\` first, or add "json-summary" to your vitest reporters.`;
22968
23091
  const hint = diagnoseCheckScriptForwardingAt(targetDir);
22969
23092
  return hint ? `${base}\n\n${hint}` : base;
22970
23093
  }
22971
- //#endregion
22972
- //#region src/commands/coverage-summary.ts
23094
+ // src/commands/coverage-summary.ts
22973
23095
  const COVERAGE_SUMMARY_FILE$2 = "coverage/coverage-summary.json";
22974
23096
  function readSummary(targetDir) {
22975
23097
  const summaryPath = path.join(targetDir, COVERAGE_SUMMARY_FILE$2);
@@ -23029,13 +23151,11 @@ const coverageSummaryCommand = defineCommand({
23029
23151
  }));
23030
23152
  }
23031
23153
  });
23032
- //#endregion
23033
- //#region src/coverage-tracking/baseline.ts
23154
+ // src/coverage-tracking/baseline.ts
23034
23155
  function serializeBaseline(baseline) {
23035
23156
  return JSON.stringify(baseline, null, 2) + "\n";
23036
23157
  }
23037
- //#endregion
23038
- //#region src/commands/coverage-check.ts
23158
+ // src/commands/coverage-check.ts
23039
23159
  const COVERAGE_SUMMARY_FILE$1 = "coverage/coverage-summary.json";
23040
23160
  const BASELINE_FILE$1 = "coverage-baseline.json";
23041
23161
  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.`;
@@ -23140,8 +23260,7 @@ const coverageCheckCommand = defineCommand({
23140
23260
  if (!result.pass && !isLegacyBaseline) process.exitCode = 1;
23141
23261
  }
23142
23262
  });
23143
- //#endregion
23144
- //#region src/commands/coverage-record.ts
23263
+ // src/commands/coverage-record.ts
23145
23264
  const COVERAGE_SUMMARY_FILE = "coverage/coverage-summary.json";
23146
23265
  const coverageRecordCommand = defineCommand({
23147
23266
  meta: {
@@ -23211,8 +23330,7 @@ const coverageRecordCommand = defineCommand({
23211
23330
  });
23212
23331
  }
23213
23332
  });
23214
- //#endregion
23215
- //#region src/commands/coverage-status.ts
23333
+ // src/commands/coverage-status.ts
23216
23334
  const coverageStatusCommand = defineCommand({
23217
23335
  meta: {
23218
23336
  name: "coverage:status",
@@ -23258,8 +23376,7 @@ const coverageStatusCommand = defineCommand({
23258
23376
  out.text(formatTrendTable(trailing));
23259
23377
  }
23260
23378
  });
23261
- //#endregion
23262
- //#region src/codebase-health/baseline.ts
23379
+ // src/codebase-health/baseline.ts
23263
23380
  function serializeHealthBaseline(metrics, ceilings, sizeBudgets) {
23264
23381
  const ordered = {};
23265
23382
  for (const key of METRIC_KEYS) {
@@ -23270,8 +23387,7 @@ function serializeHealthBaseline(metrics, ceilings, sizeBudgets) {
23270
23387
  if (sizeBudgets !== void 0 && Object.keys(sizeBudgets).length > 0) ordered["sizeBudgets"] = sizeBudgets;
23271
23388
  return JSON.stringify(ordered, null, 2) + "\n";
23272
23389
  }
23273
- //#endregion
23274
- //#region src/codebase-health/exclude.ts
23390
+ // src/codebase-health/exclude.ts
23275
23391
  function normalize(rel) {
23276
23392
  const posix = rel.replace(/\\/g, "/");
23277
23393
  return posix.startsWith("./") ? posix.slice(2) : posix;
@@ -23296,8 +23412,7 @@ function createExcludeMatcher(patterns) {
23296
23412
  return ancestors(normalized).some((dir) => isMatch(dir));
23297
23413
  };
23298
23414
  }
23299
- //#endregion
23300
- //#region src/codebase-health/exempt-match.ts
23415
+ // src/codebase-health/exempt-match.ts
23301
23416
  function exemptKeyMatcher(key) {
23302
23417
  if (!picomatch.scan(key).isGlob) return (path) => path === key;
23303
23418
  const isMatch = picomatch(key, { dot: true });
@@ -23310,8 +23425,7 @@ function createExemptLookup(reasons) {
23310
23425
  }));
23311
23426
  return (path) => reasons[path] ?? globs.find((glob) => glob.matches(path))?.reason;
23312
23427
  }
23313
- //#endregion
23314
- //#region src/codebase-health/depcruise.ts
23428
+ // src/codebase-health/depcruise.ts
23315
23429
  const DependencySchema = z.object({
23316
23430
  module: z.string(),
23317
23431
  resolved: z.string(),
@@ -23571,8 +23685,7 @@ function collectGraphDetails(executor, config, isExcluded = () => false, sourceL
23571
23685
  workspacePackages
23572
23686
  }) };
23573
23687
  }
23574
- //#endregion
23575
- //#region src/codebase-health/workspace-packages.ts
23688
+ // src/codebase-health/workspace-packages.ts
23576
23689
  const PnpmWorkspaceSchema = z.object({ packages: z.array(z.string()).optional() });
23577
23690
  const RootManifestSchema = z.object({ workspaces: z.union([z.array(z.string()), z.object({ packages: z.array(z.string()) })]).optional() });
23578
23691
  const PackageNameSchema = z.object({ name: z.string() });
@@ -23666,8 +23779,7 @@ function listWorkspacePackageNames(executor) {
23666
23779
  }
23667
23780
  return names;
23668
23781
  }
23669
- //#endregion
23670
- //#region src/codebase-health/collect.ts
23782
+ // src/codebase-health/collect.ts
23671
23783
  function buildCollectConfig(config, opts) {
23672
23784
  return {
23673
23785
  src: config.src,
@@ -23915,8 +24027,7 @@ function offenderEntries(details, key) {
23915
24027
  case "fanOutOutliers": return details.fanOutOutliers ?? [];
23916
24028
  }
23917
24029
  }
23918
- //#endregion
23919
- //#region src/codebase-health/compare.ts
24030
+ // src/codebase-health/compare.ts
23920
24031
  const DEFAULT_TOLERANCE = 0;
23921
24032
  function compareSizeBudgets(baseline, measurements) {
23922
24033
  const results = [];
@@ -24068,8 +24179,7 @@ function isFlatOrBetter(baseline, current, currentCeilings = {}, sizes = []) {
24068
24179
  });
24069
24180
  return metricsFlat && ceilingsFlat && sizesFlat;
24070
24181
  }
24071
- //#endregion
24072
- //#region src/codebase-health/base-checkout.ts
24182
+ // src/codebase-health/base-checkout.ts
24073
24183
  const TEMP_PREFIX = "bst-health-base-";
24074
24184
  function withMergeBaseCheckout(executor, targetDir, mergeBase, use) {
24075
24185
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), TEMP_PREFIX));
@@ -24158,8 +24268,7 @@ function linkRelative(link, target) {
24158
24268
  fs.symlinkSync(link, target);
24159
24269
  } catch (_error) {}
24160
24270
  }
24161
- //#endregion
24162
- //#region src/codebase-health/base-outliers.ts
24271
+ // src/codebase-health/base-outliers.ts
24163
24272
  function unavailable(reason) {
24164
24273
  return {
24165
24274
  status: "unavailable",
@@ -24188,8 +24297,7 @@ function measureBaseOutliers(opts) {
24188
24297
  return unavailable(describeError$1(error));
24189
24298
  }
24190
24299
  }
24191
- //#endregion
24192
- //#region src/codebase-health/render.ts
24300
+ // src/codebase-health/render.ts
24193
24301
  const GRAPH_METRIC_KEYS = METRIC_KEYS.filter((key) => key !== "crowdedDirectories");
24194
24302
  const LABELS = {
24195
24303
  crowdedDirectories: "crowded directories",
@@ -24274,6 +24382,30 @@ function formatExplain(details) {
24274
24382
  }
24275
24383
  return lines.join("\n");
24276
24384
  }
24385
+ function outlierAttributionLines(attribution, failedKeys) {
24386
+ const lines = [];
24387
+ let printedAttribution = false;
24388
+ for (const o of attribution.newOutliers) {
24389
+ if (!failedKeys.has(o.key)) continue;
24390
+ lines.push(` ${CEILING_LABELS[o.key]}: ${o.module} -- -> ${o.current} (new)`);
24391
+ printedAttribution = true;
24392
+ }
24393
+ for (const o of attribution.baseOutliers) {
24394
+ if (!failedKeys.has(o.key)) continue;
24395
+ lines.push(` ${CEILING_LABELS[o.key]}: ${o.module} ${o.base} -> ${o.current} (on base)`);
24396
+ printedAttribution = true;
24397
+ }
24398
+ for (const o of attribution.unattributedOutliers) {
24399
+ if (!failedKeys.has(o.key)) continue;
24400
+ lines.push(` ${CEILING_LABELS[o.key]}: ${o.module} -- -> ${o.current} (no ceiling)`);
24401
+ printedAttribution = true;
24402
+ }
24403
+ if (printedAttribution) {
24404
+ if (attribution.outlierBase.status === "measured") lines.push(` outliers attributed against the merge base ${attribution.outlierBase.mergeBase}`);
24405
+ else if (attribution.outlierBase.status === "unavailable") lines.push(` outliers not attributed: the merge base ${attribution.outlierBase.mergeBase} could not be measured (${attribution.outlierBase.reason})`);
24406
+ }
24407
+ return lines;
24408
+ }
24277
24409
  function formatCompareDiff(result, details, attribution) {
24278
24410
  const lines = [];
24279
24411
  for (const m of result.metrics) {
@@ -24301,26 +24433,7 @@ function formatCompareDiff(result, details, attribution) {
24301
24433
  if (s.measurerChanged === true) lines.push(` size: ${s.id} measured by code this branch changed`);
24302
24434
  }
24303
24435
  const failedKeys = new Set(result.metrics.filter((m) => m.pass === false).map((m) => m.key));
24304
- let printedAttribution = false;
24305
- for (const o of attribution.newOutliers) {
24306
- if (!failedKeys.has(o.key)) continue;
24307
- lines.push(` ${CEILING_LABELS[o.key]}: ${o.module} -- -> ${o.current} (new)`);
24308
- printedAttribution = true;
24309
- }
24310
- for (const o of attribution.baseOutliers) {
24311
- if (!failedKeys.has(o.key)) continue;
24312
- lines.push(` ${CEILING_LABELS[o.key]}: ${o.module} ${o.base} -> ${o.current} (on base)`);
24313
- printedAttribution = true;
24314
- }
24315
- for (const o of attribution.unattributedOutliers) {
24316
- if (!failedKeys.has(o.key)) continue;
24317
- lines.push(` ${CEILING_LABELS[o.key]}: ${o.module} -- -> ${o.current} (no ceiling)`);
24318
- printedAttribution = true;
24319
- }
24320
- if (printedAttribution) {
24321
- if (attribution.outlierBase.status === "measured") lines.push(` outliers attributed against the merge base ${attribution.outlierBase.mergeBase}`);
24322
- else if (attribution.outlierBase.status === "unavailable") lines.push(` outliers not attributed: the merge base ${attribution.outlierBase.mergeBase} could not be measured (${attribution.outlierBase.reason})`);
24323
- }
24436
+ lines.push(...outlierAttributionLines(attribution, failedKeys));
24324
24437
  lines.push(result.pass ? "health: PASS" : "health: FAIL");
24325
24438
  return lines.join("\n");
24326
24439
  }
@@ -24381,8 +24494,7 @@ const CARRIED_RAISES_FIRST_LINE = "raises carried by this branch:";
24381
24494
  function formatCarriedRaises(raises) {
24382
24495
  return [CARRIED_RAISES_FIRST_LINE, ...raises.map((r) => ` ${r.leaf}: ${r.reference} -> ${r.current}`)].join("\n");
24383
24496
  }
24384
- //#endregion
24385
- //#region src/codebase-health/size.ts
24497
+ // src/codebase-health/size.ts
24386
24498
  function byteLength(absolute) {
24387
24499
  try {
24388
24500
  const stats = statSync(absolute);
@@ -24458,8 +24570,7 @@ function measureOne(targetDir, id, budget, options) {
24458
24570
  measurerChanged: true
24459
24571
  };
24460
24572
  }
24461
- //#endregion
24462
- //#region src/codebase-health/measure.ts
24573
+ // src/codebase-health/measure.ts
24463
24574
  const BASELINE_FILE = "health-baseline.json";
24464
24575
  function readTargetReference(executor, targetDir, out) {
24465
24576
  const context = detectHealthContext(targetDir);
@@ -24598,8 +24709,7 @@ function measureHealth(targetDir, config, out, opts = {}) {
24598
24709
  }
24599
24710
  };
24600
24711
  }
24601
- //#endregion
24602
- //#region src/codebase-health/staleness.ts
24712
+ // src/codebase-health/staleness.ts
24603
24713
  function wasMeasured(metric, path, details) {
24604
24714
  if (metric === "crowdedDirectories") return details.directories.has(path);
24605
24715
  return details.graphModules?.has(path) ?? true;
@@ -24635,8 +24745,7 @@ function findStaleEntries(baseline, details, exempt) {
24635
24745
  }
24636
24746
  return stale;
24637
24747
  }
24638
- //#endregion
24639
- //#region src/commands/health-check.ts
24748
+ // src/commands/health-check.ts
24640
24749
  function assessSwitchOff(executor, targetDir, config, out) {
24641
24750
  const read = readTargetReference(executor, targetDir, out);
24642
24751
  if (read.kind === "unavailable") return void 0;
@@ -24821,8 +24930,7 @@ const healthCheckCommand = defineCommand({
24821
24930
  if (!result.pass || graphUnavailable !== void 0) process.exitCode = 1;
24822
24931
  }
24823
24932
  });
24824
- //#endregion
24825
- //#region src/codebase-health/raise.ts
24933
+ // src/codebase-health/raise.ts
24826
24934
  const SIZE_RAISE_FACTOR = 1.01;
24827
24935
  function sizeRaiseValue(measured) {
24828
24936
  return Math.floor(measured * SIZE_RAISE_FACTOR) + 1;
@@ -24999,8 +25107,7 @@ function widenedBaseline(baseline, headlines, ceilings, sizeBudgets) {
24999
25107
  function planHasWrites(plan) {
25000
25108
  return plan.ceilings.length > 0 || plan.sizes.length > 0 || plan.exemptions.length > 0;
25001
25109
  }
25002
- //#endregion
25003
- //#region src/commands/health-raise.ts
25110
+ // src/commands/health-raise.ts
25004
25111
  const JsonValueSchema = z.json();
25005
25112
  const TOOLING_FILE = ".tooling.json";
25006
25113
  function collectExemptPairs(rawArgs) {
@@ -25125,8 +25232,7 @@ function writePlan(targetDir, plan) {
25125
25232
  }
25126
25233
  return wrote;
25127
25234
  }
25128
- //#endregion
25129
- //#region src/codebase-health/module-report.ts
25235
+ // src/codebase-health/module-report.ts
25130
25236
  function normalizeModulePath(raw) {
25131
25237
  let normalized = raw.replace(/\\/g, "/");
25132
25238
  while (normalized.startsWith("./")) normalized = normalized.slice(2);
@@ -25211,8 +25317,7 @@ function formatModuleReports(reports) {
25211
25317
  }
25212
25318
  return lines.join("\n");
25213
25319
  }
25214
- //#endregion
25215
- //#region src/commands/health-coverage-note.ts
25320
+ // src/commands/health-coverage-note.ts
25216
25321
  function readCoverageNote(targetDir) {
25217
25322
  const file = path.join(targetDir, "coverage-baseline.json");
25218
25323
  if (!existsSync(file)) return void 0;
@@ -25223,8 +25328,7 @@ function readCoverageNote(targetDir) {
25223
25328
  return;
25224
25329
  }
25225
25330
  }
25226
- //#endregion
25227
- //#region src/commands/health-summary.ts
25331
+ // src/commands/health-summary.ts
25228
25332
  function readModuleCeilings(targetDir) {
25229
25333
  const file = path.join(targetDir, "health-baseline.json");
25230
25334
  if (!existsSync(file)) return void 0;
@@ -25319,8 +25423,7 @@ const healthSummaryCommand = defineCommand({
25319
25423
  if (moduleReports !== void 0) out.text(formatModuleReports(moduleReports));
25320
25424
  }
25321
25425
  });
25322
- //#endregion
25323
- //#region src/codebase-health/history.ts
25426
+ // src/codebase-health/history.ts
25324
25427
  const HEALTH_HISTORY_FILE = "health-history.jsonl";
25325
25428
  function appendHealthRecord(executor, config, record) {
25326
25429
  return appendRecord(executor, {
@@ -25335,8 +25438,7 @@ function readHealthRecords(executor, config) {
25335
25438
  historyFile: HEALTH_HISTORY_FILE
25336
25439
  }, parseHealthHistoryLine);
25337
25440
  }
25338
- //#endregion
25339
- //#region src/commands/health-record.ts
25441
+ // src/commands/health-record.ts
25340
25442
  const healthRecordCommand = defineCommand({
25341
25443
  meta: {
25342
25444
  name: "health:record",
@@ -25411,8 +25513,7 @@ const healthRecordCommand = defineCommand({
25411
25513
  });
25412
25514
  }
25413
25515
  });
25414
- //#endregion
25415
- //#region src/commands/health-status.ts
25516
+ // src/commands/health-status.ts
25416
25517
  const healthStatusCommand = defineCommand({
25417
25518
  meta: {
25418
25519
  name: "health:status",
@@ -25453,8 +25554,7 @@ const healthStatusCommand = defineCommand({
25453
25554
  out.text(formatStatus(trailing));
25454
25555
  }
25455
25556
  });
25456
- //#endregion
25457
- //#region src/chars-check/config.ts
25557
+ // src/chars-check/config.ts
25458
25558
  const ToolingShallowSchema = z.object({
25459
25559
  chars: tolerantBlock(CharsConfigSchema).optional(),
25460
25560
  ascii: tolerantBlock(CharsConfigSchema).optional()
@@ -25482,8 +25582,7 @@ function resolveCharsConfig(targetDir) {
25482
25582
  const full = path.join(targetDir, ".tooling.json");
25483
25583
  return parseCharsConfig(existsSync(full) ? readFileSync(full, "utf-8") : void 0, path.relative(process.cwd(), full) || full);
25484
25584
  }
25485
- //#endregion
25486
- //#region src/chars-check/report.ts
25585
+ // src/chars-check/report.ts
25487
25586
  function displayChar(offender) {
25488
25587
  if (offender.group === void 0) return offender.char;
25489
25588
  return `<${offender.codepoint}>`;
@@ -25535,8 +25634,7 @@ function toJsonReport(decisions, placement = []) {
25535
25634
  })
25536
25635
  };
25537
25636
  }
25538
- //#endregion
25539
- //#region src/commands/chars-check.ts
25637
+ // src/commands/chars-check.ts
25540
25638
  function reportDecisions(decisions, placement = []) {
25541
25639
  return {
25542
25640
  payload: toJsonReport(decisions, placement),
@@ -25655,8 +25753,7 @@ const DirEntrySchema = z.looseObject({
25655
25753
  type: z.string()
25656
25754
  });
25657
25755
  z.array(DirEntrySchema);
25658
- //#endregion
25659
- //#region src/release/forgejo/branch-prune-reads.ts
25756
+ // src/release/forgejo/branch-prune-reads.ts
25660
25757
  const ToolingConfigBranchPruneShapeSchema = z.looseObject({ branchPrune: BranchPruneConfigSchema.optional() });
25661
25758
  function readBranchPruneBlockFromDisk(targetDir) {
25662
25759
  const fullPath = path.join(targetDir, ".tooling.json");
@@ -25696,6 +25793,14 @@ function del(entry) {
25696
25793
  function daysSince(iso, now) {
25697
25794
  return (now - Date.parse(iso)) / 864e5;
25698
25795
  }
25796
+ const MERGE_SKEW_MS = 36e5;
25797
+ function pushedAfterMerge(commitDate, mergedAt) {
25798
+ if (commitDate === null || mergedAt === null) return false;
25799
+ const commit = Date.parse(commitDate);
25800
+ const merged = Date.parse(mergedAt);
25801
+ if (Number.isNaN(commit) || Number.isNaN(merged)) return false;
25802
+ return commit > merged + MERGE_SKEW_MS;
25803
+ }
25699
25804
  function hardNeverTouchReason(branch, defaultBranch) {
25700
25805
  if (branch === defaultBranch) return "the default branch";
25701
25806
  if (HARD_NEVER_TOUCH_NAMES.has(branch)) return "orphan data branch (never merges to default)";
@@ -25722,13 +25827,15 @@ function resolveBranchPr(branch, prsByHead) {
25722
25827
  };
25723
25828
  return { status: "none" };
25724
25829
  }
25725
- function classifyWorkBranch(branch, prsByHead, now, rules) {
25830
+ function classifyWorkBranch(remote, prsByHead, now, rules) {
25831
+ const branch = remote.name;
25726
25832
  const resolved = resolveBranchPr(branch, prsByHead);
25727
- if (resolved.status === "none") return keep(branch, "no PR found for this branch");
25833
+ if (resolved.status === "none") return keep(branch, "no PR found for this branch in the listing");
25728
25834
  if (resolved.status === "open") return keep(branch, `open PR #${String(resolved.pr.number)}`);
25729
25835
  if (resolved.status === "closed-unmerged") return keep(branch, `PR #${String(resolved.pr.number)} closed without merging`);
25730
- const age = daysSince(resolved.pr.mergedAt ?? "", now);
25731
25836
  const prLabel = `PR #${String(resolved.pr.number)}`;
25837
+ if (pushedAfterMerge(remote.commitDate, resolved.pr.mergedAt)) return keep(branch, `has commits after ${prLabel} merged`);
25838
+ const age = daysSince(resolved.pr.mergedAt ?? "", now);
25732
25839
  if (age >= rules.mergedDays) return del({
25733
25840
  branch,
25734
25841
  reason: `${prLabel} merged ${age.toFixed(1)}d ago (>= ${String(rules.mergedDays)}d)`,
@@ -25737,11 +25844,27 @@ function classifyWorkBranch(branch, prsByHead, now, rules) {
25737
25844
  });
25738
25845
  return keep(branch, `${prLabel} merged only ${age.toFixed(1)}d ago (< ${String(rules.mergedDays)}d)`);
25739
25846
  }
25847
+ function backupAgeFallback(remote, prefix, now, rules, pr) {
25848
+ const branch = remote.name;
25849
+ if (remote.commitDate === null) return keep(branch, `${prefix}, and this ref's commit date is unknown`);
25850
+ const age = daysSince(remote.commitDate, now);
25851
+ if (age >= rules.backupDays) return del({
25852
+ branch,
25853
+ reason: `${prefix}, and this ref is ${age.toFixed(1)}d old (>= ${String(rules.backupDays)}d)`,
25854
+ prNumber: pr?.prNumber,
25855
+ mergedAt: pr?.mergedAt
25856
+ });
25857
+ return keep(branch, `${prefix}, and this ref is only ${age.toFixed(1)}d old (< ${String(rules.backupDays)}d)`);
25858
+ }
25740
25859
  function classifyBackupRef(remote, parent, prsByHead, now, rules) {
25741
25860
  const branch = remote.name;
25742
25861
  const resolved = resolveBranchPr(parent, prsByHead);
25743
25862
  if (resolved.status === "open") return keep(branch, `parent branch ${parent} has an open PR #${String(resolved.pr.number)}`);
25744
25863
  if (resolved.status === "merged") {
25864
+ if (pushedAfterMerge(remote.commitDate, resolved.pr.mergedAt) && daysSince(resolved.pr.mergedAt ?? "", now) >= rules.mergedDays) return backupAgeFallback(remote, `parent branch ${parent}'s PR #${String(resolved.pr.number)} merged before this ref's last commit`, now, rules, {
25865
+ prNumber: resolved.pr.number,
25866
+ mergedAt: resolved.pr.mergedAt ?? void 0
25867
+ });
25745
25868
  const age = daysSince(resolved.pr.mergedAt ?? "", now);
25746
25869
  const prLabel = `parent branch ${parent}'s PR #${String(resolved.pr.number)}`;
25747
25870
  if (age >= rules.mergedDays) return del({
@@ -25752,14 +25875,7 @@ function classifyBackupRef(remote, parent, prsByHead, now, rules) {
25752
25875
  });
25753
25876
  return keep(branch, `${prLabel} merged only ${age.toFixed(1)}d ago (< ${String(rules.mergedDays)}d)`);
25754
25877
  }
25755
- const noMergedParent = `parent branch ${parent} has no merged PR`;
25756
- if (remote.commitDate === null) return keep(branch, `${noMergedParent}, and this ref's commit date is unknown`);
25757
- const age = daysSince(remote.commitDate, now);
25758
- if (age >= rules.backupDays) return del({
25759
- branch,
25760
- reason: `${noMergedParent}, and this ref is ${age.toFixed(1)}d old (>= ${String(rules.backupDays)}d)`
25761
- });
25762
- return keep(branch, `${noMergedParent}, and this ref is only ${age.toFixed(1)}d old (< ${String(rules.backupDays)}d)`);
25878
+ return backupAgeFallback(remote, `parent branch ${parent} has no merged PR`, now, rules);
25763
25879
  }
25764
25880
  function classifyBranch(remote, prsByHead, isConfigExcluded, now, rules) {
25765
25881
  const hard = hardNeverTouchReason(remote.name, rules.defaultBranch);
@@ -25768,7 +25884,7 @@ function classifyBranch(remote, prsByHead, isConfigExcluded, now, rules) {
25768
25884
  if (isConfigExcluded(remote.name)) return keep(remote.name, "matches a config-added exclusion");
25769
25885
  const parent = parseBackupParent(remote.name);
25770
25886
  if (parent !== null) return classifyBackupRef(remote, parent, prsByHead, now, rules);
25771
- return classifyWorkBranch(remote.name, prsByHead, now, rules);
25887
+ return classifyWorkBranch(remote, prsByHead, now, rules);
25772
25888
  }
25773
25889
  function selectBranchesToPrune(branches, prs, now, rules) {
25774
25890
  const prsByHead = /* @__PURE__ */ new Map();
@@ -25797,8 +25913,7 @@ function selectBranchesToPrune(branches, prs, now, rules) {
25797
25913
  truncated
25798
25914
  };
25799
25915
  }
25800
- //#endregion
25801
- //#region ../forgejo/src/branches.ts
25916
+ // ../forgejo/src/branches.ts
25802
25917
  const BranchEntrySchema = z.object({
25803
25918
  name: z.string(),
25804
25919
  protected: z.boolean().optional(),
@@ -25877,8 +25992,7 @@ async function deleteBranch(executor, conn, branch) {
25877
25992
  resource: `${conn.repository}/${branch}`
25878
25993
  });
25879
25994
  }
25880
- //#endregion
25881
- //#region src/branch-prune/shell.ts
25995
+ // src/branch-prune/shell.ts
25882
25996
  const BRANCH_LIST_MAX_PAGES = 20;
25883
25997
  const HEADS_PREFIX = "refs/heads/";
25884
25998
  function parseLsRemoteHeadNames(stdout) {
@@ -25889,6 +26003,29 @@ function parseLsRemoteHeadNames(stdout) {
25889
26003
  }
25890
26004
  return names;
25891
26005
  }
26006
+ const DAY_MS = 864e5;
26007
+ const CLOSED_PR_SLACK_DAYS = 14;
26008
+ function closedPrWindowMs(rules) {
26009
+ return (rules.mergedDays + CLOSED_PR_SLACK_DAYS) * DAY_MS;
26010
+ }
26011
+ async function listPrunePulls(executor, conn, closedSince, knownClosedPulls, signal) {
26012
+ let openCapped = false;
26013
+ const [open, closed] = await Promise.all([listPulls(executor, conn, {
26014
+ state: "open",
26015
+ signal,
26016
+ onPageCap: () => {
26017
+ openCapped = true;
26018
+ }
26019
+ }), listPulls(executor, conn, {
26020
+ state: "closed",
26021
+ updatedSince: closedSince,
26022
+ signal
26023
+ })]);
26024
+ if (openCapped) throw new FatalError(`Open PR listing on ${conn.repository} hit its page cap; refusing to prune, since a missed open PR could delete its branch`);
26025
+ const live = [...open, ...closed];
26026
+ const liveNumbers = new Set(live.map((pr) => pr.number));
26027
+ return [...live, ...knownClosedPulls.filter((pr) => !liveNumbers.has(pr.number))];
26028
+ }
25892
26029
  async function runBranchPrune(executor, conn, now, options) {
25893
26030
  const repoLog = log$1.child({ repo: conn.repository });
25894
26031
  const auth = buildGitAuth(conn);
@@ -25904,7 +26041,13 @@ async function runBranchPrune(executor, conn, now, options) {
25904
26041
  });
25905
26042
  if (lsRemote.exitCode !== 0) throw new FatalError(`git ls-remote --heads failed: ${lsRemote.stderr || lsRemote.stdout}`);
25906
26043
  const branchNames = parseLsRemoteHeadNames(lsRemote.stdout);
25907
- const [pulls, forgeListing] = await Promise.all([listPulls(executor, conn, { signal }), listBranches(executor, conn, {
26044
+ const rules = {
26045
+ defaultBranch: options.defaultBranch,
26046
+ mergedDays: options.mergedDays ?? 7,
26047
+ backupDays: options.backupDays ?? 30,
26048
+ exclude: options.exclude
26049
+ };
26050
+ const [pulls, forgeListing] = await Promise.all([listPrunePulls(executor, conn, now - closedPrWindowMs(rules), options.knownClosedPulls ?? [], signal), listBranches(executor, conn, {
25908
26051
  signal: signal ?? void 0,
25909
26052
  maxPages: BRANCH_LIST_MAX_PAGES
25910
26053
  })]);
@@ -25917,12 +26060,7 @@ async function runBranchPrune(executor, conn, now, options) {
25917
26060
  protected: info?.protected ?? false,
25918
26061
  commitDate: info?.commitDate ?? null
25919
26062
  };
25920
- }), pulls, now, {
25921
- defaultBranch: options.defaultBranch,
25922
- mergedDays: options.mergedDays ?? 7,
25923
- backupDays: options.backupDays ?? 30,
25924
- exclude: options.exclude
25925
- });
26063
+ }), pulls, now, rules);
25926
26064
  if (selection.truncated) repoLog.warn(`branch:prune: per-run deletion cap (${String(50)}) reached -- some eligible branches were deferred to the next run rather than deleted in one pass`);
25927
26065
  const deleted = [];
25928
26066
  const failed = [];
@@ -25963,8 +26101,7 @@ async function deleteOneBranch(executor, conn, entry, repoLog) {
25963
26101
  error
25964
26102
  };
25965
26103
  }
25966
- //#endregion
25967
- //#region src/commands/branch-prune.ts
26104
+ // src/commands/branch-prune.ts
25968
26105
  function parseDaysFlag(flagName, raw) {
25969
26106
  const value = Number(raw);
25970
26107
  if (!Number.isInteger(value) || value < 0) throw new FatalError(`--${flagName} must be a non-negative integer, got "${raw}"`);
@@ -26038,8 +26175,7 @@ const branchPruneCommand = defineCommand({
26038
26175
  if (report.failed.length > 0) log$1.warn(`branch:prune: ${String(report.failed.length)} deletion(s) failed`);
26039
26176
  }
26040
26177
  });
26041
- //#endregion
26042
- //#region src/docs-check/plan-locate.ts
26178
+ // src/docs-check/plan-locate.ts
26043
26179
  const SCORED_STATUS = /^[A-Z][0-9]+$/;
26044
26180
  const RENAME_STATUS = /^R[0-9]*$/;
26045
26181
  const COPY_STATUS = /^C[0-9]*$/;
@@ -26176,8 +26312,7 @@ function locatePlan(input) {
26176
26312
  };
26177
26313
  return { kind: "none" };
26178
26314
  }
26179
- //#endregion
26180
- //#region src/docs-check/rules.ts
26315
+ // src/docs-check/rules.ts
26181
26316
  function claimsPartialDelivery(body) {
26182
26317
  const status = statusOf(body);
26183
26318
  return status !== void 0 && PARTIAL_STATUS.test(status);
@@ -26266,8 +26401,7 @@ function checkDoc(input) {
26266
26401
  });
26267
26402
  return violations;
26268
26403
  }
26269
- //#endregion
26270
- //#region src/docs-check/collect.ts
26404
+ // src/docs-check/collect.ts
26271
26405
  const MS_PER_DAY$1 = 864e5;
26272
26406
  const SPEC_DIR_BASENAME = "specs";
26273
26407
  const PLAN_DIR_BASENAME = "plans";
@@ -26438,8 +26572,7 @@ function collectViolations(exec, config, opts) {
26438
26572
  unmatchedEnforced
26439
26573
  };
26440
26574
  }
26441
- //#endregion
26442
- //#region src/docs-check/content-age.ts
26575
+ // src/docs-check/content-age.ts
26443
26576
  const HEX_HASH = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
26444
26577
  function parseIgnoreRevs(text) {
26445
26578
  const hashes = /* @__PURE__ */ new Set();
@@ -26540,8 +26673,7 @@ function lastContentChange(git, rel, context) {
26540
26673
  maxCount *= WINDOW_GROWTH;
26541
26674
  }
26542
26675
  }
26543
- //#endregion
26544
- //#region src/docs-check/executor.ts
26676
+ // src/docs-check/executor.ts
26545
26677
  function gitOut$1(rootDir, args) {
26546
26678
  try {
26547
26679
  return execFileSync("git", args, {
@@ -26699,8 +26831,7 @@ function createRealDocsExecutor(rootDir) {
26699
26831
  branchNameStatus: () => branchNameStatus(rootDir)
26700
26832
  };
26701
26833
  }
26702
- //#endregion
26703
- //#region src/docs-check/render.ts
26834
+ // src/docs-check/render.ts
26704
26835
  function group(violations) {
26705
26836
  const byFile = /* @__PURE__ */ new Map();
26706
26837
  for (const violation of violations) {
@@ -26735,8 +26866,7 @@ function formatReport(result) {
26735
26866
  lines.push(`[x] docs: ${String(fatal.length)} violation(s).`, "", ...group(fatal), "The plan-lifecycle guide (`.agent/guides/plan-lifecycle.md`) is the spec for all of this.", "Reminder: a doc's DIRECTORY is the source of truth for done-ness -- not its Status line, not its checkboxes.");
26736
26867
  return lines.join("\n");
26737
26868
  }
26738
- //#endregion
26739
- //#region src/commands/docs-check.ts
26869
+ // src/commands/docs-check.ts
26740
26870
  function runDocsCheck(exec, config, opts) {
26741
26871
  const vc = { verbose: opts.verbose ?? false };
26742
26872
  if (!config.enabled) {
@@ -26806,8 +26936,7 @@ const docsCheckCommand = defineCommand({
26806
26936
  process.exitCode = exitCode;
26807
26937
  }
26808
26938
  });
26809
- //#endregion
26810
- //#region src/docs-delink/engine.ts
26939
+ // src/docs-delink/engine.ts
26811
26940
  function textRestatesTarget(text, target) {
26812
26941
  const plain = text.replaceAll("`", "").trim();
26813
26942
  if (plain === "") return true;
@@ -26898,8 +27027,7 @@ function applyDelinkPlan(exec, plan) {
26898
27027
  exec.writeFile(file.file, file.content);
26899
27028
  }
26900
27029
  }
26901
- //#endregion
26902
- //#region src/docs-relocate/executor.ts
27030
+ // src/docs-relocate/executor.ts
26903
27031
  const PRUNED_DIRS = /* @__PURE__ */ new Set([
26904
27032
  "node_modules",
26905
27033
  "dist",
@@ -27004,8 +27132,7 @@ function createRealRelocateExecutor(rootDir) {
27004
27132
  }
27005
27133
  };
27006
27134
  }
27007
- //#endregion
27008
- //#region src/commands/docs-delink.ts
27135
+ // src/commands/docs-delink.ts
27009
27136
  const RETIRED_DIR_NAMES = /* @__PURE__ */ new Set(["retired", "completed"]);
27010
27137
  function assertRetiredDirs(dirs) {
27011
27138
  if (dirs.length === 0) throw new FatalError("docs:delink: at least one retired/ directory is required");
@@ -27090,8 +27217,7 @@ const docsDelinkCommand = defineCommand({
27090
27217
  process.exitCode = exitCode;
27091
27218
  }
27092
27219
  });
27093
- //#endregion
27094
- //#region src/docs-relocate/engine.ts
27220
+ // src/docs-relocate/engine.ts
27095
27221
  function lineOf(body, index) {
27096
27222
  let line = 1;
27097
27223
  for (let i = 0; i < index; i++) if (body[i] === "\n") line++;
@@ -27202,8 +27328,7 @@ function applyRelocatePlan(exec, plan) {
27202
27328
  for (const move of plan.moves) if (move.status === "pending") exec.move(move.from, move.to);
27203
27329
  for (const rewrite of plan.rewrites) exec.writeFile(rewrite.file, rewrite.content);
27204
27330
  }
27205
- //#endregion
27206
- //#region src/commands/docs-relocate.ts
27331
+ // src/commands/docs-relocate.ts
27207
27332
  function isExistingDirectory(exec, rel) {
27208
27333
  return exec.exists(rel) && exec.readFile(rel) === void 0;
27209
27334
  }
@@ -27298,13 +27423,11 @@ const docsRelocateCommand = defineCommand({
27298
27423
  process.exitCode = exitCode;
27299
27424
  }
27300
27425
  });
27301
- //#endregion
27302
- //#region src/local-today.ts
27426
+ // src/local-today.ts
27303
27427
  function localToday(now) {
27304
27428
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
27305
27429
  }
27306
- //#endregion
27307
- //#region src/commands/docs-retire.ts
27430
+ // src/commands/docs-retire.ts
27308
27431
  const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
27309
27432
  function validateRetireArgs(exec, src, opts) {
27310
27433
  if (!isRetireVerb(opts.status)) throw new FatalError(`docs:retire: unrecognized --status "${opts.status}" (expected one of: ${RETIRE_VERBS.join(", ")})`);
@@ -27526,8 +27649,7 @@ const docsRetireCommand = defineCommand({
27526
27649
  process.exitCode = exitCode;
27527
27650
  }
27528
27651
  });
27529
- //#endregion
27530
- //#region ../forgejo/src/issue-messages.ts
27652
+ // ../forgejo/src/issue-messages.ts
27531
27653
  const ISSUE_LIST_JSON_HELP = "Emit one JSON document: issues ([{number, title, state, url, author, labels, createdAt, updatedAt, closedAt (null while open), isPullRequest, assignees, attachments ([{id, name, size, createdAt, downloadUrl}])}]), truncated.";
27532
27654
  const ISSUE_CREATE_JSON_HELP = "Emit one JSON document: number, url, assignees. A dry run reports number 0 and an empty url.";
27533
27655
  const ISSUE_STATE_JSON_HELP = "Emit one JSON document: number, url, action (close | reopen), state ({previous, current}), changed, comment? ({posted}; present only when a comment was given).";
@@ -27558,8 +27680,7 @@ function describeNoLabelsGiven(error, clearFlag) {
27558
27680
  function describeAttachmentExists(error, forceFlag) {
27559
27681
  return `"${error.filePath}" already exists -- pass ${forceFlag} to overwrite it.`;
27560
27682
  }
27561
- //#endregion
27562
- //#region src/release/issue/issue.ts
27683
+ // src/release/issue/issue.ts
27563
27684
  function resolverFor(executor, cwd, log) {
27564
27685
  return (target) => {
27565
27686
  const transport = resolveIssueTransport(executor, cwd, target);
@@ -27656,8 +27777,7 @@ async function runIssueCreate(executor, options) {
27656
27777
  throw error;
27657
27778
  }
27658
27779
  }
27659
- //#endregion
27660
- //#region src/commands/issue-view.ts
27780
+ // src/commands/issue-view.ts
27661
27781
  const issueViewCommand = defineCommand({
27662
27782
  meta: {
27663
27783
  name: "issue:view",
@@ -27696,8 +27816,7 @@ const issueViewCommand = defineCommand({
27696
27816
  log$1.info(formatIssue(view));
27697
27817
  }
27698
27818
  });
27699
- //#endregion
27700
- //#region src/commands/issue-list.ts
27819
+ // src/commands/issue-list.ts
27701
27820
  const issueListCommand = defineCommand({
27702
27821
  meta: {
27703
27822
  name: "issue:list",
@@ -27750,8 +27869,7 @@ const issueListCommand = defineCommand({
27750
27869
  log$1.info(formatIssueList(result));
27751
27870
  }
27752
27871
  });
27753
- //#endregion
27754
- //#region src/commands/issue-comment.ts
27872
+ // src/commands/issue-comment.ts
27755
27873
  const issueCommentCommand = defineCommand({
27756
27874
  meta: {
27757
27875
  name: "issue:comment",
@@ -27806,8 +27924,7 @@ const issueCommentCommand = defineCommand({
27806
27924
  log$1.info(formatIssueComment(result, args["dry-run"] === true));
27807
27925
  }
27808
27926
  });
27809
- //#endregion
27810
- //#region src/commands/issue-create.ts
27927
+ // src/commands/issue-create.ts
27811
27928
  function collectLabelArgs(rawArgs) {
27812
27929
  return collectFlagValues(rawArgs, "--label");
27813
27930
  }
@@ -27888,8 +28005,7 @@ const issueCreateCommand = defineCommand({
27888
28005
  for (const line of formatIssueCreate(result, args.title, args["dry-run"] === true)) log$1.info(line);
27889
28006
  }
27890
28007
  });
27891
- //#endregion
27892
- //#region src/commands/issue-update.ts
28008
+ // src/commands/issue-update.ts
27893
28009
  const issueUpdateCommand = defineCommand({
27894
28010
  meta: {
27895
28011
  name: "issue:update",
@@ -27949,8 +28065,7 @@ const issueUpdateCommand = defineCommand({
27949
28065
  if (args["dry-run"] === true && result.changed.includes("body")) note(result.previous.body === "" ? "(empty)" : result.previous.body, "[dry-run] Current body");
27950
28066
  }
27951
28067
  });
27952
- //#endregion
27953
- //#region ../forgejo/src/issue-run-download.ts
28068
+ // ../forgejo/src/issue-run-download.ts
27954
28069
  function isReadableFile(filePath) {
27955
28070
  try {
27956
28071
  readFileSync(filePath);
@@ -28043,8 +28158,7 @@ function formatDownload(result, dryRun) {
28043
28158
  for (const file of result.files) lines.push(` ${file.name} (${String(file.size)} bytes)`);
28044
28159
  return lines.join("\n");
28045
28160
  }
28046
- //#endregion
28047
- //#region src/release/issue/issue-download.ts
28161
+ // src/release/issue/issue-download.ts
28048
28162
  async function runIssueDownload(executor, options) {
28049
28163
  try {
28050
28164
  return await downloadIssueAttachments((target) => {
@@ -28074,8 +28188,7 @@ async function runIssueDownload(executor, options) {
28074
28188
  throw error;
28075
28189
  }
28076
28190
  }
28077
- //#endregion
28078
- //#region src/commands/issue-download.ts
28191
+ // src/commands/issue-download.ts
28079
28192
  const issueDownloadCommand = defineCommand({
28080
28193
  meta: {
28081
28194
  name: "issue:download",
@@ -28130,8 +28243,7 @@ const issueDownloadCommand = defineCommand({
28130
28243
  log$1.info(formatDownload(result, args["dry-run"] === true));
28131
28244
  }
28132
28245
  });
28133
- //#endregion
28134
- //#region ../forgejo/src/issue-run-labels.ts
28246
+ // ../forgejo/src/issue-run-labels.ts
28135
28247
  async function labelIssue(resolve, request) {
28136
28248
  const ref = parseIssueRef(request.ref);
28137
28249
  const number = requireIssueNumber(ref);
@@ -28200,8 +28312,7 @@ function formatIssueSetLabels(result, dryRun) {
28200
28312
  if (result.added.length > 0) lines.push(` ${dryRun ? "would add" : "added"}: ${result.added.join(", ")}`);
28201
28313
  return lines.join("\n");
28202
28314
  }
28203
- //#endregion
28204
- //#region src/release/issue/issue-label.ts
28315
+ // src/release/issue/issue-label.ts
28205
28316
  async function runIssueLabel(executor, options) {
28206
28317
  try {
28207
28318
  return await labelIssue((target) => {
@@ -28227,8 +28338,7 @@ async function runIssueLabel(executor, options) {
28227
28338
  throw error;
28228
28339
  }
28229
28340
  }
28230
- //#endregion
28231
- //#region src/commands/issue-label.ts
28341
+ // src/commands/issue-label.ts
28232
28342
  function defineIssueLabelCommand(action) {
28233
28343
  return defineCommand({
28234
28344
  meta: {
@@ -28283,8 +28393,7 @@ function defineIssueLabelCommand(action) {
28283
28393
  }
28284
28394
  const issueLabelCommand = defineIssueLabelCommand("add");
28285
28395
  const issueUnlabelCommand = defineIssueLabelCommand("remove");
28286
- //#endregion
28287
- //#region src/release/issue/issue-set-labels.ts
28396
+ // src/release/issue/issue-set-labels.ts
28288
28397
  async function runIssueSetLabels(executor, options) {
28289
28398
  try {
28290
28399
  return await setIssueLabels((target) => {
@@ -28308,8 +28417,7 @@ async function runIssueSetLabels(executor, options) {
28308
28417
  throw error;
28309
28418
  }
28310
28419
  }
28311
- //#endregion
28312
- //#region src/commands/issue-set-labels.ts
28420
+ // src/commands/issue-set-labels.ts
28313
28421
  const issueSetLabelsCommand = defineCommand({
28314
28422
  meta: {
28315
28423
  name: "issue:set-labels",
@@ -28365,8 +28473,7 @@ const issueSetLabelsCommand = defineCommand({
28365
28473
  log$1.info(formatIssueSetLabels(result, args["dry-run"] === true));
28366
28474
  }
28367
28475
  });
28368
- //#endregion
28369
- //#region ../forgejo/src/issue-run-state.ts
28476
+ // ../forgejo/src/issue-run-state.ts
28370
28477
  var EmptyCommentError = class extends FatalError {
28371
28478
  constructor() {
28372
28479
  super("The comment resolved to empty text.");
@@ -28462,8 +28569,7 @@ function formatIssueState(result, dryRun) {
28462
28569
  }
28463
28570
  return lines.join("\n");
28464
28571
  }
28465
- //#endregion
28466
- //#region src/release/issue/issue-state.ts
28572
+ // src/release/issue/issue-state.ts
28467
28573
  async function runIssueState(executor, options) {
28468
28574
  try {
28469
28575
  return await setIssueState((target) => {
@@ -28493,8 +28599,7 @@ async function runIssueState(executor, options) {
28493
28599
  throw error;
28494
28600
  }
28495
28601
  }
28496
- //#endregion
28497
- //#region src/commands/issue-state.ts
28602
+ // src/commands/issue-state.ts
28498
28603
  function defineIssueStateCommand(action) {
28499
28604
  return defineCommand({
28500
28605
  meta: {
@@ -28557,8 +28662,7 @@ function defineIssueStateCommand(action) {
28557
28662
  }
28558
28663
  const issueCloseCommand = defineIssueStateCommand("close");
28559
28664
  const issueReopenCommand = defineIssueStateCommand("reopen");
28560
- //#endregion
28561
- //#region src/commands/findings-add.ts
28665
+ // src/commands/findings-add.ts
28562
28666
  const SOURCE_RE = /^(pr|issue)#(\d+)$/;
28563
28667
  const ALLOWED_CLASSES = ["nit", "pre-existing"];
28564
28668
  function parseSource(source) {
@@ -28675,8 +28779,7 @@ const findingsAddCommand = defineCommand({
28675
28779
  if (result.createdLedgerDir) out.notice(`Created ${FINDINGS_DIR}/ -- the backlog sweep is now armed for this repo.`);
28676
28780
  }
28677
28781
  });
28678
- //#endregion
28679
- //#region src/commands/findings-list.ts
28782
+ // src/commands/findings-list.ts
28680
28783
  const MS_PER_DAY = 864e5;
28681
28784
  function readFindingSummary(fullPath) {
28682
28785
  let body;
@@ -28759,8 +28862,7 @@ const findingsListCommand = defineCommand({
28759
28862
  out.text(renderText(result));
28760
28863
  }
28761
28864
  });
28762
- //#endregion
28763
- //#region src/commands/findings-resolve.ts
28865
+ // src/commands/findings-resolve.ts
28764
28866
  function resolveFindingPath(rootDir, name) {
28765
28867
  const ledgerDir = path.join(rootDir, FINDINGS_DIR);
28766
28868
  const relative = name.includes("/") ? name : `${FINDINGS_DIR}/${name}`;
@@ -28837,8 +28939,7 @@ const findingsResolveCommand = defineCommand({
28837
28939
  for (const file of result.files) out.text(`${verb} ${file}`);
28838
28940
  }
28839
28941
  });
28840
- //#endregion
28841
- //#region src/plan-workspace/git.ts
28942
+ // src/plan-workspace/git.ts
28842
28943
  function runGit(args, cwd) {
28843
28944
  try {
28844
28945
  return {
@@ -28861,8 +28962,7 @@ function runGit(args, cwd) {
28861
28962
  };
28862
28963
  }
28863
28964
  }
28864
- //#endregion
28865
- //#region src/plan-workspace/workspace.ts
28965
+ // src/plan-workspace/workspace.ts
28866
28966
  const WORKSPACE_ROOT = ".superpowers/sdd";
28867
28967
  const MARKER = "plan-path";
28868
28968
  function unretiredId(planId) {
@@ -28912,8 +29012,7 @@ function resolveOutPath(out, cwd) {
28912
29012
  if (!existsSync(parent)) throw new FatalError(`--out directory does not exist: ${parent}`);
28913
29013
  return target;
28914
29014
  }
28915
- //#endregion
28916
- //#region src/plan-workspace/review-package.ts
29015
+ // src/plan-workspace/review-package.ts
28917
29016
  function resolveCommit(ref, label, cwd) {
28918
29017
  const result = runGit([
28919
29018
  "rev-parse",
@@ -28989,8 +29088,7 @@ function writeReviewPackage(planPath, base, head, cwd, out) {
28989
29088
  bytes: Buffer.byteLength(body)
28990
29089
  };
28991
29090
  }
28992
- //#endregion
28993
- //#region src/plan-workspace/task-brief.ts
29091
+ // src/plan-workspace/task-brief.ts
28994
29092
  function isTaskLabel(text, label) {
28995
29093
  return taskLabelId(text) === label;
28996
29094
  }
@@ -29047,8 +29145,7 @@ function writeTaskBrief(planPath, label, cwd, out) {
29047
29145
  lines: task.split("\n").length - 1
29048
29146
  };
29049
29147
  }
29050
- //#endregion
29051
- //#region src/commands/plan.ts
29148
+ // src/commands/plan.ts
29052
29149
  const PLAN_ARG = {
29053
29150
  type: "positional",
29054
29151
  required: true,
@@ -29191,8 +29288,7 @@ const planStatusCommand = defineCommand({
29191
29288
  out.text(renderStatus(report));
29192
29289
  }
29193
29290
  });
29194
- //#endregion
29195
- //#region ../cli-kit/src/path-probe.ts
29291
+ // ../cli-kit/src/path-probe.ts
29196
29292
  function probeCliPath(value) {
29197
29293
  try {
29198
29294
  const stat = statSync(value, { throwIfNoEntry: false });
@@ -29202,8 +29298,7 @@ function probeCliPath(value) {
29202
29298
  return "missing";
29203
29299
  }
29204
29300
  }
29205
- //#endregion
29206
- //#region ../cli-kit/src/run.ts
29301
+ // ../cli-kit/src/run.ts
29207
29302
  function classifyWithHook(error, verbose, hook) {
29208
29303
  const classified = classifyThrown(error, verbose);
29209
29304
  const worded = hook?.(error);
@@ -29340,11 +29435,10 @@ async function runCli(config) {
29340
29435
  await Promise.all([drain(process.stdout), drain(process.stderr)]);
29341
29436
  process.exit(process.exitCode ?? 0);
29342
29437
  }
29343
- //#endregion
29344
- //#region src/cli-main.ts
29438
+ // src/cli-main.ts
29345
29439
  setLogLevel(resolveLogLevel({}));
29346
29440
  setForgejoLogger(log$1);
29347
- const displayVersion = "0.99.0";
29441
+ const displayVersion = "0.100.0";
29348
29442
  const bstSubCommands = {
29349
29443
  "repo:sync": syncCommand,
29350
29444
  "checks:run": runChecksCommand,
@@ -29419,10 +29513,8 @@ async function runBstCli(extraSubCommands = {}) {
29419
29513
  describeError: describeForgeError
29420
29514
  });
29421
29515
  }
29422
- //#endregion
29423
- //#region src/bin.ts
29516
+ // src/bin.ts
29424
29517
  applyVerbosityFromArgs(process.argv.slice(2));
29425
29518
  log$1.debug(describeEnvFileLoad(envFileLoad));
29426
29519
  await runBstCli();
29427
- //#endregion
29428
29520
  export {};