@patronage/software-factory 1.0.0-alpha.45 → 1.0.0-alpha.47

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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as __exportAll } from "./chunk-pbuEa-1d.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
2
  import path from "node:path";
3
3
  import { Command, InvalidArgumentError } from "commander";
4
4
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
@@ -8,10 +8,10 @@ import { accessSync, appendFileSync, closeSync, constants, cpSync, existsSync, f
8
8
  import { FACTORY_APP_BROKER_ORIGIN, FACTORY_APP_BROKER_PATH, FACTORY_CURSOR_OIDC_AUDIENCE, FACTORY_PROOF_GATE_APP_ID, FACTORY_PROOF_GATE_STEP_NAME, FACTORY_PR_STATUS_HUD_JOB_NAME, GitHubApiError, assertPreviewCleanupStackPolicy, assertPreviewCleanupTargetsAbsent, discoverOrphanedPreviewCleanupTargets, discoverPreviewCleanupTargets, mintInstallationToken, parsePreviewCleanupResidue, parsePreviewCleanupTargets, previewCleanupGithubOutput, previewCleanupResiduePullRequests, previewProofInventory, productionImpactTargetOutput, readPullRequestStates, readVitestProfileDocument, recordPreviewCleanupOutcome } from "@patronage/factory-ci";
9
9
  import http from "node:http";
10
10
  import { isDeepStrictEqual, promisify } from "node:util";
11
- import os, { homedir, tmpdir } from "node:os";
11
+ import os, { availableParallelism, homedir, tmpdir } from "node:os";
12
12
  import { z } from "zod";
13
13
  import picomatch from "picomatch";
14
- import { parse } from "yaml";
14
+ import { parse, parseAllDocuments } from "yaml";
15
15
  import crypto, { createHash, randomBytes, randomUUID } from "node:crypto";
16
16
  import { Buffer as Buffer$1 } from "node:buffer";
17
17
  import { link, lstat, mkdir, open, readFile, readdir, realpath, rename, stat, unlink } from "node:fs/promises";
@@ -20,12 +20,11 @@ import { setImmediate as setImmediate$1, setTimeout as setTimeout$1 } from "node
20
20
  import { Worker } from "node:worker_threads";
21
21
  import { AsyncLocalStorage } from "node:async_hooks";
22
22
  import { pathToFileURL } from "node:url";
23
- //#region package.json
23
+ // package.json
24
24
  var name = "@patronage/software-factory";
25
- var version = "1.0.0-alpha.45";
26
- //#endregion
27
- //#region src/git-globals-parse.ts
28
- const VALUE_TAKING_GIT_OPTIONS = new Set([
25
+ var version = "1.0.0-alpha.47";
26
+ // src/git-globals-parse.ts
27
+ const VALUE_TAKING_GIT_OPTIONS = /* @__PURE__ */ new Set([
29
28
  "-C",
30
29
  "-c",
31
30
  "--git-dir",
@@ -57,8 +56,7 @@ function parseGitGlobalsAndSubcommand(args) {
57
56
  }
58
57
  return { globals: args };
59
58
  }
60
- //#endregion
61
- //#region src/worker-checkout-guard.ts
59
+ // src/worker-checkout-guard.ts
62
60
  function normalizeGitPath(dir) {
63
61
  const resolved = path.resolve(dir).replace(/\/+$/u, "");
64
62
  try {
@@ -151,7 +149,7 @@ function assertWorkerCheckoutAllowed({ cwd, operation, probe = defaultCheckoutDi
151
149
  operation
152
150
  }));
153
151
  }
154
- const GIT_TRACKED_MUTATION_SUBCOMMANDS = new Set([
152
+ const GIT_TRACKED_MUTATION_SUBCOMMANDS = /* @__PURE__ */ new Set([
155
153
  "add",
156
154
  "am",
157
155
  "cherry-pick",
@@ -166,13 +164,13 @@ const GIT_TRACKED_MUTATION_SUBCOMMANDS = new Set([
166
164
  "rm",
167
165
  "switch"
168
166
  ]);
169
- const APPLY_READ_ONLY_FLAGS = new Set([
167
+ const APPLY_READ_ONLY_FLAGS = /* @__PURE__ */ new Set([
170
168
  "--check",
171
169
  "--stat",
172
170
  "--numstat",
173
171
  "--summary"
174
172
  ]);
175
- const BRANCH_MUTATING_FLAGS = new Set([
173
+ const BRANCH_MUTATING_FLAGS = /* @__PURE__ */ new Set([
176
174
  "-d",
177
175
  "-D",
178
176
  "--delete",
@@ -189,7 +187,7 @@ const BRANCH_MUTATING_FLAGS = new Set([
189
187
  "--unset-upstream",
190
188
  "--edit-description"
191
189
  ]);
192
- const BRANCH_LIST_SELECTOR_FLAGS = new Set([
190
+ const BRANCH_LIST_SELECTOR_FLAGS = /* @__PURE__ */ new Set([
193
191
  "-l",
194
192
  "--list",
195
193
  "-a",
@@ -215,7 +213,7 @@ function isBranchMutation(rest) {
215
213
  if (rest.some((token) => !token.startsWith("-"))) return true;
216
214
  return false;
217
215
  }
218
- const TAG_MUTATING_FLAGS = new Set([
216
+ const TAG_MUTATING_FLAGS = /* @__PURE__ */ new Set([
219
217
  "-a",
220
218
  "--annotate",
221
219
  "-s",
@@ -234,7 +232,7 @@ const TAG_MUTATING_FLAGS = new Set([
234
232
  "--local-user",
235
233
  "--create-reflog"
236
234
  ]);
237
- const TAG_READ_MODE_FLAGS = new Set([
235
+ const TAG_READ_MODE_FLAGS = /* @__PURE__ */ new Set([
238
236
  "-l",
239
237
  "--list",
240
238
  "--contains",
@@ -326,8 +324,7 @@ function assertNoWorkerControlCheckoutMutation({ command, args, cwd, env, probe
326
324
  }));
327
325
  }
328
326
  }
329
- //#endregion
330
- //#region src/stash-guard.ts
327
+ // src/stash-guard.ts
331
328
  var StashGuardError = class extends Error {
332
329
  constructor(message) {
333
330
  super(message);
@@ -390,8 +387,7 @@ function assertNoSharedStash({ args, command, cwd, env, probe = defaultStashRole
390
387
  if (workTreeRole === "linked") throw new StashGuardError(stashGuardMessage({ cwd: dirs.topLevel }));
391
388
  }
392
389
  }
393
- //#endregion
394
- //#region src/git.ts
390
+ // src/git.ts
395
391
  const REPOSITORY_LOCAL_GIT_ENV = [
396
392
  "GIT_COMMON_DIR",
397
393
  "GIT_DIR",
@@ -590,7 +586,7 @@ function listDirtyTrackedFiles(cwd) {
590
586
  "--cached",
591
587
  "--name-status"
592
588
  ], cwd).stdout);
593
- return [...new Set([...unstaged, ...staged])];
589
+ return [.../* @__PURE__ */ new Set([...unstaged, ...staged])];
594
590
  }
595
591
  /**
596
592
  * Tracked, changed files considered "in scope" for verification gates
@@ -610,7 +606,7 @@ function changedFiles(cwd, base) {
610
606
  "--name-status",
611
607
  `${resolveDiffBase(cwd, base)}...HEAD`
612
608
  ], cwd).stdout);
613
- return [...new Set([...committed, ...listDirtyTrackedFiles(cwd)])].toSorted();
609
+ return [.../* @__PURE__ */ new Set([...committed, ...listDirtyTrackedFiles(cwd)])].toSorted();
614
610
  }
615
611
  /**
616
612
  * The heads this branch actually had on top of `base`, newest first. Used to
@@ -731,8 +727,7 @@ function remoteDefaultBranchRef(cwd) {
731
727
  const ref = result.stdout.trim();
732
728
  return ref.length > 0 ? ref : void 0;
733
729
  }
734
- //#endregion
735
- //#region src/checkout-repository.ts
730
+ // src/checkout-repository.ts
736
731
  function normalizeRepositoryIdentity(repository) {
737
732
  return {
738
733
  name: repository.name.replace(/\.git$/iu, "").toLowerCase(),
@@ -800,8 +795,7 @@ const repositorySlug = (repository) => {
800
795
  const normalized = normalizeRepositoryIdentity(repository);
801
796
  return `${normalized.owner}/${normalized.name}`;
802
797
  };
803
- //#endregion
804
- //#region src/cursor-oidc-mint.ts
798
+ // src/cursor-oidc-mint.ts
805
799
  const DEFAULT_CURSOR_AGENT_SOCKET = "/run/cursor/api.sock";
806
800
  const DEFAULT_TIMEOUT_MS = 5e3;
807
801
  const cursorAgentSocketPath = (env = process.env) => {
@@ -888,8 +882,7 @@ const mintCursorOidcToken = (options = {}) => new Promise((resolve, reject) => {
888
882
  req.write(body);
889
883
  req.end();
890
884
  });
891
- //#endregion
892
- //#region src/pr-verify-status.ts
885
+ // src/pr-verify-status.ts
893
886
  const PR_VERIFY_STATUS_CONTEXT = "patronage-factory/pr-verify";
894
887
  const GITHUB_PUBLISH_TIMEOUT_MS = 5e3;
895
888
  /**
@@ -946,8 +939,7 @@ function createGhCommitStatusPoster(output, run = runGhStatus) {
946
939
  runDetachedBestEffort(publish);
947
940
  };
948
941
  }
949
- //#endregion
950
- //#region src/factory-app-broker-client.ts
942
+ // src/factory-app-broker-client.ts
951
943
  const FACTORY_APP_BROKER_URL = `${FACTORY_APP_BROKER_ORIGIN}${FACTORY_APP_BROKER_PATH}`;
952
944
  /**
953
945
  * The opt-in broker permission set (#1360): `actions: read`, `checks: read`,
@@ -1020,8 +1012,7 @@ const exchangeFactoryAppInstallationToken = async (input) => {
1020
1012
  if (body === null || typeof body !== "object" || typeof body.token !== "string" || body.token.length === 0) throw new FactoryAppBrokerError("Factory App broker exchange omitted token");
1021
1013
  return body.token;
1022
1014
  };
1023
- //#endregion
1024
- //#region src/user-config.ts
1015
+ // src/user-config.ts
1025
1016
  const FACTORY_USER_CONFIG_SCHEMA_VERSION = 2;
1026
1017
  const githubAppConfigSchema = z.object({
1027
1018
  appId: z.union([z.string().min(1), z.number().int().positive()]),
@@ -1120,8 +1111,7 @@ function tryUserConfig(input = {}) {
1120
1111
  function formatUserConfigError(configPath, error) {
1121
1112
  return `User config is invalid: ${configPath}: ${formatZodIssues(error)}`;
1122
1113
  }
1123
- //#endregion
1124
- //#region src/github-app-access.ts
1114
+ // src/github-app-access.ts
1125
1115
  const NO_APP_SKIP_MESSAGE = "no factory GitHub App configured; skipping durable check-run republish.\n";
1126
1116
  /**
1127
1117
  * Fail-closed App credential mint/exchange that never completed. Distinct from
@@ -1265,8 +1255,7 @@ const resolveFactoryAppAccess = async (repository, dependencies = {}) => {
1265
1255
  message: NO_APP_SKIP_MESSAGE
1266
1256
  };
1267
1257
  };
1268
- //#endregion
1269
- //#region src/app-token-exec.ts
1258
+ // src/app-token-exec.ts
1270
1259
  /**
1271
1260
  * `app-token:exec` (#1426): run one child command with a fresh Factory App
1272
1261
  * installation token in `FACTORY_GITHUB_APP_TOKEN`.
@@ -1280,12 +1269,13 @@ const resolveFactoryAppAccess = async (repository, dependencies = {}) => {
1280
1269
  */
1281
1270
  /** The child's exit status; a child killed by a signal reads as 1. */
1282
1271
  const runInheritedChild = async ({ args, command, cwd, env }) => {
1283
- const [code] = await once(spawn(command, args, {
1272
+ const child = spawn(command, args, {
1284
1273
  cwd,
1285
1274
  env,
1286
1275
  shell: false,
1287
1276
  stdio: "inherit"
1288
- }), "close");
1277
+ });
1278
+ const [code] = await once(child, "close");
1289
1279
  return code ?? 1;
1290
1280
  };
1291
1281
  /**
@@ -1324,8 +1314,7 @@ async function runAppTokenExec(args, dependencies = {}) {
1324
1314
  }
1325
1315
  });
1326
1316
  }
1327
- //#endregion
1328
- //#region src/command-options.ts
1317
+ // src/command-options.ts
1329
1318
  function positiveInteger$1(name) {
1330
1319
  return (value) => {
1331
1320
  const parsed = Number(value);
@@ -1362,8 +1351,7 @@ function resolveProofOutputPaths(cwd, defaultPath, requested) {
1362
1351
  canonical: resolveCheckoutPath(cwd, defaultPath)
1363
1352
  };
1364
1353
  }
1365
- //#endregion
1366
- //#region src/app-token-exec-command.ts
1354
+ // src/app-token-exec-command.ts
1367
1355
  function createAppTokenExecCommand(action = runAppTokenExec) {
1368
1356
  return markCwdOptionDefault(new Command("app-token:exec").description("Run a command with a fresh Factory App installation token for this checkout's repository in FACTORY_GITHUB_APP_TOKEN; exits 1 without running it when no token resolves, else with the command's exit code").usage("[options] -- <command> [args...]").argument("<command...>", "the command to run, after `--`").option("--cwd <path>", "checkout to scope the token to and run in", collectCwdOption).action(async (command, options) => {
1369
1357
  const exitCode = await action({
@@ -1373,8 +1361,7 @@ function createAppTokenExecCommand(action = runAppTokenExec) {
1373
1361
  if (exitCode !== 0) process.exitCode = exitCode;
1374
1362
  }));
1375
1363
  }
1376
- //#endregion
1377
- //#region src/cli-entry.ts
1364
+ // src/cli-entry.ts
1378
1365
  /**
1379
1366
  * The path of the module that runs a factory command.
1380
1367
  *
@@ -1389,8 +1376,7 @@ function createAppTokenExecCommand(action = runAppTokenExec) {
1389
1376
  * development, `cli.js` in the built package.
1390
1377
  */
1391
1378
  const factoryCliEntry = () => path.join(import.meta.dirname, `cli${path.extname(import.meta.filename)}`);
1392
- //#endregion
1393
- //#region src/glob-match.ts
1379
+ // src/glob-match.ts
1394
1380
  function isValidGlob(pattern) {
1395
1381
  try {
1396
1382
  picomatch(pattern, { strictBrackets: true });
@@ -1409,8 +1395,7 @@ function isValidRepoRelativeGlob(pattern) {
1409
1395
  function matchesAnyGlob(patterns, file) {
1410
1396
  return patterns.length > 0 && picomatch.isMatch(file, [...patterns]);
1411
1397
  }
1412
- //#endregion
1413
- //#region src/impact-stamp.ts
1398
+ // src/impact-stamp.ts
1414
1399
  const LOCKFILE_PATH = "pnpm-lock.yaml";
1415
1400
  const SUPPORTED_LOCKFILE_VERSION = "9.0";
1416
1401
  const impactStampTargetSchema = z.object({
@@ -1588,11 +1573,25 @@ const canonical = (value) => {
1588
1573
  return value;
1589
1574
  };
1590
1575
  const stableStringify$1 = (value) => JSON.stringify(canonical(value));
1576
+ const PACKAGE_MANAGER_IMPORTER_KEYS = /* @__PURE__ */ new Set(["configDependencies", "packageManagerDependencies"]);
1577
+ const isPackageManagerLockfile = (value) => {
1578
+ if (!isRecord$2(value) || !isRecord$2(value.importers)) return false;
1579
+ const importerPaths = Object.keys(value.importers);
1580
+ const root = value.importers["."];
1581
+ return importerPaths.length === 1 && isRecord$2(root) && Object.keys(root).every((key) => PACKAGE_MANAGER_IMPORTER_KEYS.has(key));
1582
+ };
1591
1583
  const parseLockfile = (content) => {
1592
1584
  try {
1593
- const parsed = parse(content);
1594
- if (!isRecord$2(parsed)) return;
1595
- const validated = pnpmLockfileSchema.safeParse(parsed);
1585
+ const documents = parseAllDocuments(content);
1586
+ if (!Array.isArray(documents) || documents.some((document) => document.errors.length > 0)) return;
1587
+ const values = documents.map((document) => document.toJS());
1588
+ const [first, second] = values;
1589
+ const project = values.length === 2 ? second : first;
1590
+ if (values.length === 0 || values.length > 2 || values.length === 2 && !isPackageManagerLockfile(first) || !isRecord$2(project)) return;
1591
+ const validated = pnpmLockfileSchema.safeParse(values.length === 2 ? {
1592
+ ...project,
1593
+ packageManagerLockfile: first
1594
+ } : project);
1596
1595
  return validated.success ? validated.data : void 0;
1597
1596
  } catch {
1598
1597
  return;
@@ -1600,7 +1599,7 @@ const parseLockfile = (content) => {
1600
1599
  };
1601
1600
  const nonGraphSections = ({ importers: _importers, packages: _packages, snapshots: _snapshots, ...rest }) => rest;
1602
1601
  const changedSectionKeys = (before, after) => {
1603
- return [...new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})])].filter((key) => stableStringify$1(before?.[key]) !== stableStringify$1(after?.[key]));
1602
+ return [.../* @__PURE__ */ new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})])].filter((key) => stableStringify$1(before?.[key]) !== stableStringify$1(after?.[key]));
1604
1603
  };
1605
1604
  const linkTarget = (importerPath, version) => {
1606
1605
  if (!version.startsWith("link:")) return;
@@ -1619,7 +1618,7 @@ const linkTarget = (importerPath, version) => {
1619
1618
  };
1620
1619
  const importerMatchesTarget = (importerPath, importerRoots) => importerRoots.some((root) => importerPath === root || importerPath.startsWith(`${root}/`));
1621
1620
  const workspaceClosure = (lockfile, importerRoots) => {
1622
- const closure = new Set(["."]);
1621
+ const closure = /* @__PURE__ */ new Set(["."]);
1623
1622
  const queue = Object.keys(lockfile.importers ?? {}).filter((importerPath) => importerMatchesTarget(importerPath, importerRoots));
1624
1623
  while (queue.length > 0) {
1625
1624
  const importerPath = queue.pop();
@@ -1859,7 +1858,8 @@ const unionTargetImpact = (source, lockfile) => {
1859
1858
  const computeImpactStampOrThrow = ({ changedFiles, profile, profilePath = "software-factory.profile.json", readLockfile }, targets) => {
1860
1859
  const { dependencyLocalGlobs, inertGlobs } = declaredOwnershipGlobs(profile);
1861
1860
  if (targets.length === 0) {
1862
- const { inertPaths, unsubscribedPaths } = partitionUnownedSourcePaths(changedFiles.filter((file) => file !== "pnpm-lock.yaml" && isRepoRelativePath(file)), [], inertGlobs);
1861
+ const sourceFiles = changedFiles.filter((file) => file !== "pnpm-lock.yaml" && isRepoRelativePath(file));
1862
+ const { inertPaths, unsubscribedPaths } = partitionUnownedSourcePaths(sourceFiles, [], inertGlobs);
1863
1863
  return {
1864
1864
  basis: "conservative",
1865
1865
  inertPaths,
@@ -1939,7 +1939,7 @@ const lockfileImporterScope = (readLockfile) => {
1939
1939
  reason: `${LOCKFILE_PATH} changes the root importer's dependencies`
1940
1940
  };
1941
1941
  const resolvedBy = [...new Set(sides.parsed.flatMap((lockfile) => Object.keys(lockfile.importers)))].map((importerPath) => {
1942
- const keys = new Set(sides.parsed.flatMap((lockfile) => [...snapshotClosure(lockfile, new Set([importerPath]))]));
1942
+ const keys = new Set(sides.parsed.flatMap((lockfile) => [...snapshotClosure(lockfile, /* @__PURE__ */ new Set([importerPath]))]));
1943
1943
  return {
1944
1944
  bare: new Set([...keys].map(withoutPeerSuffix)),
1945
1945
  importerPath,
@@ -1965,16 +1965,15 @@ const lockfileImporterScope = (readLockfile) => {
1965
1965
  kind: "scoped"
1966
1966
  };
1967
1967
  };
1968
- //#endregion
1969
- //#region src/diff-classification.ts
1968
+ // src/diff-classification.ts
1970
1969
  const DIFF_CLASSIFICATIONS = [
1971
1970
  "docs/process-only",
1972
1971
  "trivial",
1973
1972
  "non-trivial"
1974
1973
  ];
1975
- //#endregion
1976
- //#region src/required-check-policy.ts
1974
+ // src/required-check-policy.ts
1977
1975
  const EVIDENCE_CHECK_TYPES = ["review", "verify"];
1976
+ const evidenceCheckTypeSchema = z.enum(EVIDENCE_CHECK_TYPES);
1978
1977
  const requiredCheckScopeSchema = z.object({ classifications: z.array(z.enum(DIFF_CLASSIFICATIONS)).min(1) }).strict();
1979
1978
  const requiredCheckInScope = ({ context, scope }) => {
1980
1979
  if (!scope) return {
@@ -1994,8 +1993,7 @@ const requiredCheckInScope = ({ context, scope }) => {
1994
1993
  reason: `out of scope — classification "${context.classification}" is not one of: ${scope.classifications.join(", ")}`
1995
1994
  };
1996
1995
  };
1997
- //#endregion
1998
- //#region src/profile.ts
1996
+ // src/profile.ts
1999
1997
  const DEFAULT_FACTORY_REPOSITORY = "unknown/unknown";
2000
1998
  /**
2001
1999
  * The shapes v6 replaced. Not loadable — {@link legacyProfileMigration} turns
@@ -2336,8 +2334,7 @@ function formatProfileError(profilePath, error) {
2336
2334
  return `${issue.path.length > 0 ? issue.path.join(".") : "root"}: ${issue.message}`;
2337
2335
  }).join("; ")}`;
2338
2336
  }
2339
- //#endregion
2340
- //#region src/verification-run-context.ts
2337
+ // src/verification-run-context.ts
2341
2338
  const FACTORY_BASE_REF_ENV = "FACTORY_BASE_REF";
2342
2339
  const FACTORY_CHANGED_FILES_ENV = "FACTORY_CHANGED_FILES";
2343
2340
  const FACTORY_CHANGED_FILES_FILE_ENV = "FACTORY_CHANGED_FILES_FILE";
@@ -2420,9 +2417,8 @@ function createVerificationRunContext(input) {
2420
2417
  }
2421
2418
  };
2422
2419
  }
2423
- //#endregion
2424
- //#region src/affected.ts
2425
- const JS_MODULE_EXTENSIONS = new Set([
2420
+ // src/affected.ts
2421
+ const JS_MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
2426
2422
  ".cjs",
2427
2423
  ".cts",
2428
2424
  ".js",
@@ -2495,7 +2491,7 @@ const listPnpmProjects = (cwd, selection, env) => {
2495
2491
  cwd,
2496
2492
  encoding: "utf-8",
2497
2493
  env,
2498
- maxBuffer: 64 * 1024 * 1024,
2494
+ maxBuffer: 67108864,
2499
2495
  shell: false
2500
2496
  });
2501
2497
  if (result.error || result.status !== 0) throw new Error(`pnpm ls ${selection.join(" ")} failed in ${cwd}: ${result.error?.message ?? result.stderr.trim()}`);
@@ -2706,12 +2702,13 @@ const resolveVitestBin = (cwd) => {
2706
2702
  return path.join(root, bin);
2707
2703
  };
2708
2704
  const runInherited = async (invocation, env) => {
2709
- const [code] = await once(spawn(invocation.command, invocation.args, {
2705
+ const child = spawn(invocation.command, invocation.args, {
2710
2706
  cwd: invocation.cwd,
2711
2707
  env,
2712
2708
  shell: false,
2713
2709
  stdio: "inherit"
2714
- }), "close");
2710
+ });
2711
+ const [code] = await once(child, "close");
2715
2712
  return code ?? 1;
2716
2713
  };
2717
2714
  /**
@@ -2818,8 +2815,7 @@ const runAffected = async (args, dependencies) => {
2818
2815
  }
2819
2816
  return 0;
2820
2817
  };
2821
- //#endregion
2822
- //#region src/commands/affected.ts
2818
+ // src/commands/affected.ts
2823
2819
  const selectedRunner = (options) => {
2824
2820
  if (options.pnpm === options.vitest) throw new Error("psf affected needs exactly one runner: --pnpm or --vitest");
2825
2821
  return options.pnpm ? "pnpm" : "vitest";
@@ -2840,8 +2836,7 @@ function createAffectedCommand(output) {
2840
2836
  }, { write: (text) => output.stdout.write(text) });
2841
2837
  }));
2842
2838
  }
2843
- //#endregion
2844
- //#region src/admission-credential.ts
2839
+ // src/admission-credential.ts
2845
2840
  const OPERATION_LABELS = {
2846
2841
  "create-pull-request": "creating the pull request",
2847
2842
  "edit-pull-request-body": "editing the pull request body",
@@ -2921,16 +2916,14 @@ const createAdmissionCredential = (dependencies = {}) => {
2921
2916
  };
2922
2917
  /** The admission credential this process mints once, when first needed. */
2923
2918
  const processAdmissionCredential = createAdmissionCredential();
2924
- //#endregion
2925
- //#region src/review-rungs.ts
2919
+ // src/review-rungs.ts
2926
2920
  const EVIDENCE_REVIEW_RUNGS = [
2927
2921
  "independent-model",
2928
2922
  "oracle",
2929
2923
  "human"
2930
2924
  ];
2931
2925
  const RUNG_ORDER = Object.fromEntries(EVIDENCE_REVIEW_RUNGS.map((rung, index) => [rung, index]));
2932
- //#endregion
2933
- //#region src/boundary-manifest.ts
2926
+ // src/boundary-manifest.ts
2934
2927
  var boundary_manifest_exports = /* @__PURE__ */ __exportAll({
2935
2928
  BOUNDARY_CLOSEOUT_DEFAULT_RUNG: () => BOUNDARY_CLOSEOUT_DEFAULT_RUNG,
2936
2929
  BOUNDARY_MANIFEST_SCHEMA_VERSION: () => 1,
@@ -3042,8 +3035,7 @@ const parseBoundaryManifest = (issueBody) => {
3042
3035
  };
3043
3036
  };
3044
3037
  const closeoutRungFor = (manifest) => manifest.closeout?.review ?? "oracle";
3045
- //#endregion
3046
- //#region src/comment-provenance.ts
3038
+ // src/comment-provenance.ts
3047
3039
  var comment_provenance_exports = /* @__PURE__ */ __exportAll({
3048
3040
  SHA_MATCH_MIN_LENGTH: () => 7,
3049
3041
  isBotLogin: () => isBotLogin,
@@ -3055,8 +3047,7 @@ const sameHeadSha = (left, right) => {
3055
3047
  if (Math.min(left.length, right.length) < 7) return false;
3056
3048
  return left.startsWith(right) || right.startsWith(left);
3057
3049
  };
3058
- //#endregion
3059
- //#region src/boundary-membership-graph.ts
3050
+ // src/boundary-membership-graph.ts
3060
3051
  const DEFAULT_TERMINAL_BASE = "main";
3061
3052
  /** Every child issue the manifest declares, across waves. */
3062
3053
  const declaredIssueSet = (manifest) => new Set(manifest.waves.flatMap((wave) => wave.issues));
@@ -3224,8 +3215,7 @@ const coveredSetDivergences = (computed, proof) => {
3224
3215
  for (const reviewed of proof.coveredSet) if (!liveKeys.has(membershipKey(reviewed))) divergences.push(`${membershipLabel(reviewed)} was covered by the proof but is no longer in the delivery boundary's live covered set`);
3225
3216
  return divergences;
3226
3217
  };
3227
- //#endregion
3228
- //#region src/boundary-review-proof.ts
3218
+ // src/boundary-review-proof.ts
3229
3219
  var boundary_review_proof_exports = /* @__PURE__ */ __exportAll({
3230
3220
  BOUNDARY_REVIEW_PROOF_KIND: () => BOUNDARY_REVIEW_PROOF_KIND$1,
3231
3221
  boundaryReviewProofAuthorsSeen: () => boundaryReviewProofAuthorsSeen,
@@ -3342,8 +3332,7 @@ const boundaryReviewProofAuthorsSeen = (comments, boundary) => {
3342
3332
  };
3343
3333
  const boundaryReviewProofParseFailures = (comments, boundary) => scanBoundaryReviewProofs(comments, boundary).failed;
3344
3334
  const undispositionedBlockingFindings = (proof) => proof.findings.filter((finding) => (finding.category !== "maintainability" || finding.blockingAfterCap === true) && finding.disposition === void 0).map((finding) => `boundary finding "${finding.title}" (category ${finding.category ?? "unknown"}) has no disposition; fix it or record waived / follow-up-filed`);
3345
- //#endregion
3346
- //#region src/boundary-topology.ts
3335
+ // src/boundary-topology.ts
3347
3336
  const eachToEpicBranch = (manifest) => manifest.topology === "each-to-epic" ? manifest.integrationBranch : void 0;
3348
3337
  /**
3349
3338
  * Validate only the current member during admission. This deliberately does
@@ -3462,8 +3451,7 @@ const boundaryTopologyReasons = ({ manifest, pullRequests, terminalBase = DEFAUL
3462
3451
  if (admittedReleaseMembers.length > 1) reasons.push(`each-to-epic admits at most one post-terminal release member targeting ${terminalBase}; found ${admittedReleaseMembers.length}: ${admittedReleaseMembers.map((member) => `PR #${member.number}`).join(", ")}.`);
3463
3452
  return reasons;
3464
3453
  };
3465
- //#endregion
3466
- //#region src/closing-keywords.ts
3454
+ // src/closing-keywords.ts
3467
3455
  const CLOSING_KEYWORD = new RegExp(`(?<![A-Za-z0-9#/-])(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)(?::\\s*|\\s+)(?:(?<owner>[\\w.-]+)/(?<repo>[\\w.-]+)#|#)(?<number>\\d+)(?![A-Za-z0-9])`, "giu");
3468
3456
  const blankNonNewlines = (text) => text.replaceAll(/[^\n]/gu, " ");
3469
3457
  const FENCE_LINE = /^(?:[ \t>]*(?:(?:[-+*]|\d{1,9}[.)])[ \t]+)?)(?<fence>`{3,}|~{3,})(?<rest>[^\r\n]*)(?:\r?\n|$)/gmu;
@@ -3551,8 +3539,7 @@ const issuesNamedByClosingKeywords = (body, delivery) => {
3551
3539
  };
3552
3540
  /** Body-named issues that sit in the boundary's declared child set. */
3553
3541
  const declaredChildrenNamedInBody = (body, delivery, declaredIssues) => issuesNamedByClosingKeywords(body, delivery).filter((issue) => declaredIssues.has(issue));
3554
- //#endregion
3555
- //#region src/demand-keys.ts
3542
+ // src/demand-keys.ts
3556
3543
  /** The demands that exist at most once per candidate. */
3557
3544
  const DEMAND_KEYS = {
3558
3545
  /**
@@ -3718,8 +3705,7 @@ const demandKeySchema = z.string().refine((value) => {
3718
3705
  * reports it as an unapplied waiver — so nothing is admitted by accepting it.
3719
3706
  */
3720
3707
  const waiverDemandKeySchema = z.string().regex(/^[a-z][a-z0-9-]*(?::[A-Za-z0-9._%/-]+)?$/u, "A demand key is a lowercase family, optionally qualified by its resolved value (e.g. review-rung:human).");
3721
- //#endregion
3722
- //#region src/factory-session.ts
3708
+ // src/factory-session.ts
3723
3709
  const FACTORY_SESSION_ID_ENV = "FACTORY_SESSION_ID";
3724
3710
  const UNKNOWN_AUTHORING_SESSION = "unknown";
3725
3711
  const normalizeSessionId = (value) => {
@@ -3736,8 +3722,7 @@ const resolveAuthoringSessionIds = ({ override, recorded }) => {
3736
3722
  const normalizedRecorded = normalizeSessionId(recorded);
3737
3723
  return normalizedRecorded && normalizedRecorded !== "unknown" ? [normalizedRecorded] : [];
3738
3724
  };
3739
- //#endregion
3740
- //#region src/demand-waiver.ts
3725
+ // src/demand-waiver.ts
3741
3726
  const DEMAND_WAIVER_SCHEMA_VERSION$1 = 1;
3742
3727
  const DEFAULT_DEMAND_WAIVER_PATH = ".factory-memory/demand-waivers.json";
3743
3728
  const shaSchema$5 = z.string().regex(/^[0-9a-f]{40}$/u);
@@ -3849,8 +3834,7 @@ const authorizeDemandWaiver = ({ authenticatedLogin, session }) => {
3849
3834
  ...normalizedSession && normalizedSession !== "unknown" ? { session: normalizedSession } : {}
3850
3835
  } };
3851
3836
  };
3852
- //#endregion
3853
- //#region src/sha256-hex.ts
3837
+ // src/sha256-hex.ts
3854
3838
  const ROUND_CONSTANTS = new Uint32Array([
3855
3839
  1116352408,
3856
3840
  1899447441,
@@ -3995,10 +3979,9 @@ const sha256Hex = (input) => {
3995
3979
  for (let offset = 0; offset < padded.length; offset += BLOCK_BYTES) compress(state, view, offset);
3996
3980
  return toHex(state);
3997
3981
  };
3998
- //#endregion
3999
- //#region src/review-finding-identity.ts
3982
+ // src/review-finding-identity.ts
4000
3983
  const normalizeCitedSpan = (text) => text.split(/\r?\n/u).map((line) => line.trim().replaceAll(/\s+/gu, " ")).filter((line) => line.length > 0).join("\n");
4001
- const PRESCRIBED_ACTION_STOPWORDS = new Set([
3984
+ const PRESCRIBED_ACTION_STOPWORDS = /* @__PURE__ */ new Set([
4002
3985
  "a",
4003
3986
  "an",
4004
3987
  "the",
@@ -4065,11 +4048,12 @@ const findingKey = (finding) => {
4065
4048
  const normalizedSpan = normalizeCitedSpan(finding.citedSpan ?? "");
4066
4049
  const actionTokens = tokenizePrescribedAction(finding.prescribedAction ?? "");
4067
4050
  const legacyDiscriminator = normalizedSpan.length > 0 || actionTokens.length > 0 ? "" : normalizeTitle(finding.title ?? "");
4068
- return sha256Hex(`${path}\0${sha256Hex(normalizedSpan)}\0${actionTokens.join(" ")}\0${legacyDiscriminator}`);
4051
+ const spanDigest = sha256Hex(normalizedSpan);
4052
+ const actionJoined = actionTokens.join(" ");
4053
+ return sha256Hex(`${path}\0${spanDigest}\0${actionJoined}\0${legacyDiscriminator}`);
4069
4054
  };
4070
4055
  const declarationMatchesEntry = (entry, target) => normalizeTitle(entry.title) === normalizeTitle(target.title) && (target.file === void 0 || entry.file !== void 0 && normalizeFile(entry.file) === normalizeFile(target.file));
4071
- //#endregion
4072
- //#region src/review-ladder-policy.ts
4056
+ // src/review-ladder-policy.ts
4073
4057
  const REVIEW_SEVERITIES = [
4074
4058
  "critical",
4075
4059
  "high",
@@ -4145,8 +4129,7 @@ const FACTORY_REVIEW_CYCLE_CAP = 5;
4145
4129
  */
4146
4130
  const reviewRoundCount = (cycles) => new Set(cycles.map((cycle, index) => cycle.identity?.patchId ?? `unidentified:${index}`)).size;
4147
4131
  const resolveReviewLadderPolicy = () => ({ gate: { cap: FACTORY_REVIEW_CYCLE_CAP } });
4148
- //#endregion
4149
- //#region src/review-ladder-ledger.ts
4132
+ // src/review-ladder-ledger.ts
4150
4133
  const OCCURRENCE_ADDRESS_PATTERN = /^c[1-9][0-9]*f[1-9][0-9]*$/u;
4151
4134
  const occurrenceAddress = (cycle, finding) => `c${cycle}f${finding}`;
4152
4135
  /** The 1-based recording position an address names. */
@@ -4273,8 +4256,7 @@ const openLadderFindings = (ledger) => ledger.filter((entry) => entry.dispositio
4273
4256
  const occurrenceBlocks = (occurrence) => occurrence.disposition === "open" && resolveFindingBlocking(occurrence.finding, "open");
4274
4257
  const blockingLadderFindings = (ledger) => ledger.filter((entry) => entry.occurrences.some(occurrenceBlocks));
4275
4258
  const staleRepeatLadderFindings = (ledger) => ledger.filter((entry) => entry.disposition === "stale-repeat");
4276
- //#endregion
4277
- //#region src/review-recording-schema.ts
4259
+ // src/review-recording-schema.ts
4278
4260
  const ABSENT_PROOF_DIGEST = "absent";
4279
4261
  const sha256Pattern = /^[0-9a-f]{64}$/u;
4280
4262
  const occurrenceAddressSchema$1 = z.string().regex(OCCURRENCE_ADDRESS_PATTERN);
@@ -4312,8 +4294,7 @@ const reviewCycleRecordingSchema = z.object({
4312
4294
  findingsDigest: z.string().regex(sha256Pattern),
4313
4295
  recordingId: z.string().regex(sha256Pattern)
4314
4296
  }).strict();
4315
- //#endregion
4316
- //#region src/review-recording.ts
4297
+ // src/review-recording.ts
4317
4298
  /**
4318
4299
  * The occurrences of the cycles already on the ladder, in recording order,
4319
4300
  * with the write-time key each carries for grouping the next cycle. A cycle
@@ -4430,8 +4411,7 @@ const resolveDeclaredDispositions = ({ declarations, index, resolutions }) => {
4430
4411
  }
4431
4412
  return records;
4432
4413
  };
4433
- //#endregion
4434
- //#region src/pr-proof-io.ts
4414
+ // src/pr-proof-io.ts
4435
4415
  const proofPathFor = (descriptor, cwd, filePath = descriptor.defaultPath) => path.resolve(cwd, filePath);
4436
4416
  const readProofFromPath = (parse, filePath) => parse(JSON.parse(readFileSync(filePath, "utf-8")));
4437
4417
  const readProofFor = (descriptor, cwd, filePath) => readProofFromPath(descriptor.parse, proofPathFor(descriptor, cwd, filePath));
@@ -4706,8 +4686,7 @@ function assertCleanWorktreeForProof({ cwd, dirtyMessage, statusPorcelain }) {
4706
4686
  const status = statusPorcelain(cwd);
4707
4687
  if (status.trim().length > 0) throw new Error(`${dirtyMessage}\n${status}`);
4708
4688
  }
4709
- //#endregion
4710
- //#region src/battery-shell-command.ts
4689
+ // src/battery-shell-command.ts
4711
4690
  /** Quotes one argument for a POSIX shell, including embedded single quotes. */
4712
4691
  function singleQuote(value) {
4713
4692
  return `'${value.replaceAll("'", String.raw`'\''`)}'`;
@@ -4724,8 +4703,7 @@ function singleQuote(value) {
4724
4703
  function withPinnedNodeOnPath(command, nodeBinDir) {
4725
4704
  return `export PATH=${singleQuote(nodeBinDir)}:"$PATH"\n${command}`;
4726
4705
  }
4727
- //#endregion
4728
- //#region src/github-issue-comments.ts
4706
+ // src/github-issue-comments.ts
4729
4707
  const isCommentPage = (value) => Array.isArray(value[0]);
4730
4708
  const normalizeIssueComments = (value) => {
4731
4709
  return (isCommentPage(value) ? value.flat() : value).map((comment) => ({
@@ -4737,8 +4715,7 @@ const normalizeIssueComments = (value) => {
4737
4715
  url: comment.html_url
4738
4716
  }));
4739
4717
  };
4740
- //#endregion
4741
- //#region src/github-client.ts
4718
+ // src/github-client.ts
4742
4719
  /**
4743
4720
  * Shared `gh` CLI client for the factory.
4744
4721
  *
@@ -5044,8 +5021,7 @@ const describeCandidateBase = (binding) => {
5044
5021
  const pullRequest = binding.source.pullRequest.status === "none" ? "no pull request is open for this branch" : `the pull request lookup was unavailable, so no live PR base could be read (${binding.source.pullRequest.reason})`;
5045
5022
  return `base ${binding.ref} at ${binding.sha}, ${fetched}; ${pullRequest}`;
5046
5023
  };
5047
- //#endregion
5048
- //#region src/candidate-identity.ts
5024
+ // src/candidate-identity.ts
5049
5025
  /**
5050
5026
  * The same fallback for a patch id taken at an explicit ref rather than at
5051
5027
  * `HEAD`. It exists so the historical-cycle walk (#943) reads a past patch
@@ -5201,8 +5177,7 @@ function createCandidateIdentityResolver({ cwd, git }) {
5201
5177
  return identity;
5202
5178
  };
5203
5179
  }
5204
- //#endregion
5205
- //#region src/catch-up-recognition.ts
5180
+ // src/catch-up-recognition.ts
5206
5181
  const refused = (reason) => ({
5207
5182
  reasons: [reason],
5208
5183
  recognized: false
@@ -5241,8 +5216,7 @@ const recognizeCatchUpCandidate = ({ base, cwd }) => {
5241
5216
  return refused(`catch-up recognition refused: ${error instanceof Error ? error.message : String(error)}`);
5242
5217
  }
5243
5218
  };
5244
- //#endregion
5245
- //#region src/demand-resolution.ts
5219
+ // src/demand-resolution.ts
5246
5220
  /**
5247
5221
  * Resolve the review modes demanded by a candidate's changed files.
5248
5222
  *
@@ -5295,7 +5269,7 @@ const resolveAuthoritativeReviewDemand = ({ basePolicy, candidatePolicy, changed
5295
5269
  const candidateCanonical = canonicalReviewPolicy(candidatePolicy);
5296
5270
  const reviewPolicyChanged = baseCanonical !== candidateCanonical;
5297
5271
  const candidatePaths = reviewPolicyPaths(candidatePolicy);
5298
- const effectivePaths = [...new Set([...reviewPolicyPaths(basePolicy), ...candidatePaths])].toSorted(compareStrings);
5272
+ const effectivePaths = [.../* @__PURE__ */ new Set([...reviewPolicyPaths(basePolicy), ...candidatePaths])].toSorted(compareStrings);
5299
5273
  const candidateOwned = new Set(candidatePaths);
5300
5274
  const baseOnlyMatchedPaths = effectivePaths.filter((protectedPath) => !candidateOwned.has(protectedPath) && changedFiles.some((file) => matchesAnyGlob([protectedPath], file)));
5301
5275
  const candidateAloneDemandsSecurity = changedFiles.some((file) => matchesAnyGlob(candidatePaths, file));
@@ -5756,8 +5730,9 @@ const gateTimingRecordSchema = z.object({
5756
5730
  /** Wall-clock start of this gate invocation (ISO 8601). */
5757
5731
  startedAt: z.iso.datetime()
5758
5732
  }).strict();
5733
+ const CLAUDE_CODE_SESSION_ID_ENV$1 = "CLAUDE_CODE_SESSION_ID";
5759
5734
  const GATE_TIMING_LEDGER_DIR = ".factory-memory/gate-timing";
5760
- const resolveGateTimingAgentRunId = (env = process.env) => normalizeSessionId(env["FACTORY_AGENT_RUN_ID"]) ?? discoverFactorySessionId(env);
5735
+ const resolveGateTimingAgentRunId = (env = process.env) => normalizeSessionId(env["FACTORY_AGENT_RUN_ID"]) ?? discoverFactorySessionId(env) ?? normalizeSessionId(env[CLAUDE_CODE_SESSION_ID_ENV$1]);
5761
5736
  const safeLedgerName = (agentRunId) => agentRunId.replaceAll(/[^\w.-]/gu, "-").slice(0, 120);
5762
5737
  const gateTimingLedgerPath = (root, agentRunId) => path.join(root, GATE_TIMING_LEDGER_DIR, `${safeLedgerName(agentRunId)}.jsonl`);
5763
5738
  /**
@@ -5780,8 +5755,7 @@ const parseGateTimingLedgerText = (text) => {
5780
5755
  }
5781
5756
  return records;
5782
5757
  };
5783
- //#endregion
5784
- //#region src/hq-access.ts
5758
+ // src/hq-access.ts
5785
5759
  /**
5786
5760
  * The environment variables that carry the HQ Cloudflare Access service token.
5787
5761
  * Both names are shell identifiers, so `/bin/sh` passes them through on every
@@ -5816,8 +5790,7 @@ const buildCloudflareAccessRequestInit = (token, init) => ({
5816
5790
  },
5817
5791
  redirect: "error"
5818
5792
  });
5819
- //#endregion
5820
- //#region src/hq-credentials.ts
5793
+ // src/hq-credentials.ts
5821
5794
  /**
5822
5795
  * Resolving the HQ Access credentials, and saying *why* when that fails.
5823
5796
  *
@@ -5995,8 +5968,7 @@ const FAILURE_SENTENCE = {
5995
5968
  * read, so nothing here can quote a secret.
5996
5969
  */
5997
5970
  const describeHqCredentialFailure = (resolution) => `HQ Access credentials are unavailable: ${FAILURE_SENTENCE[resolution.failure](resolution.reference ?? "the configured reference")}`;
5998
- //#endregion
5999
- //#region src/hq-origin-policy.ts
5971
+ // src/hq-origin-policy.ts
6000
5972
  /**
6001
5973
  * Where the HQ Access service token may be sent, decided once.
6002
5974
  *
@@ -6017,7 +5989,7 @@ const describeHqCredentialFailure = (resolution) => `HQ Access credentials are u
6017
5989
  * touch the filesystem, so it still applies when the file does not answer.
6018
5990
  */
6019
5991
  /** Largest operator config or profile file the HQ readers will open. */
6020
- const MAX_HQ_CONFIG_BYTES = 1024 * 1024;
5992
+ const MAX_HQ_CONFIG_BYTES = 1048576;
6021
5993
  const remainingMs = (deadline) => Math.max(0, deadline - performance.now());
6022
5994
  const settleWithin = async (operation, budgetMs) => {
6023
5995
  const settleOperation = async () => {
@@ -6133,7 +6105,8 @@ const resolveHqAllowedOrigins = (env, configOrigins) => {
6133
6105
  const loadHqAllowedOrigins = async (env, deadline) => {
6134
6106
  let configOrigins = [];
6135
6107
  try {
6136
- const contents = await readBoundedTextFile(defaultUserConfigPath(env), deadline);
6108
+ const configPath = defaultUserConfigPath(env);
6109
+ const contents = await readBoundedTextFile(configPath, deadline);
6137
6110
  if (contents !== void 0) configOrigins = hqAllowedOriginsFromConfigText(contents);
6138
6111
  } catch {
6139
6112
  configOrigins = [];
@@ -6145,8 +6118,7 @@ const loadHqAllowedOrigins = async (env, deadline) => {
6145
6118
  * No prefix, wildcard, or host-only match.
6146
6119
  */
6147
6120
  const isHqOriginAuthorized = (allowedOrigins, endpoint) => allowedOrigins.includes(endpoint.origin);
6148
- //#endregion
6149
- //#region src/hq-user-agent.ts
6121
+ // src/hq-user-agent.ts
6150
6122
  /**
6151
6123
  * The `User-Agent` every HQ ingest sink request carries (#1343). Without it
6152
6124
  * the sink sends fetch's default, `node`. HQ stores the header in
@@ -6178,7 +6150,7 @@ const SPOOL_REPOSITORY_MARKER = ".repository-identity";
6178
6150
  */
6179
6151
  const HQ_SPOOL_SWEEP_MAX_DEPTH = 4;
6180
6152
  const HQ_SPOOL_STATE_SEGMENTS = ["patronage-factory", "hq-spool"];
6181
- const MAX_HQ_INGEST_PAYLOAD_BYTES = 256 * 1024;
6153
+ const MAX_HQ_INGEST_PAYLOAD_BYTES = 262144;
6182
6154
  const MAX_HQ_REPLAY_ENTRIES = 32;
6183
6155
  const STALE_SPOOL_ARTIFACT_MS = 6e4;
6184
6156
  const HQ_JOURNAL_FLUSH_BUDGET_MS = 250;
@@ -6472,7 +6444,7 @@ const persistRetrySpool = async (layout, entry, deadline) => {
6472
6444
  status: "failed"
6473
6445
  };
6474
6446
  }
6475
- if (Buffer.byteLength(body, "utf-8") > MAX_HQ_INGEST_PAYLOAD_BYTES + 16 * 1024) return {
6447
+ if (Buffer.byteLength(body, "utf-8") > 278528) return {
6476
6448
  failure: "failed",
6477
6449
  status: "failed"
6478
6450
  };
@@ -6530,10 +6502,6 @@ const persistRetrySpool = async (layout, entry, deadline) => {
6530
6502
  status: "failed"
6531
6503
  };
6532
6504
  };
6533
- const appendCloseoutSpool = async (layout, entry, deadline) => {
6534
- const result = await persistRetrySpool(layout, entry, deadline);
6535
- return result.status === "failed" ? result.failure : void 0;
6536
- };
6537
6505
  const positiveBudget = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
6538
6506
  const MAX_WIDENED_BUDGET_MS = 6e4;
6539
6507
  const envBudget = (env, name) => {
@@ -6697,14 +6665,12 @@ const loadBoundedPayload = async (input, deadline) => {
6697
6665
  * gate. Nothing else carries that record: re-emitting an earlier proof event
6698
6666
  * to carry it would duplicate proof facts on the board.
6699
6667
  */
6700
- const GATE_TIMED_PROOF_KINDS = new Set([
6668
+ const GATE_TIMED_PROOF_KINDS = /* @__PURE__ */ new Set([
6701
6669
  "boundary-check-proof",
6702
6670
  "pr-ready-proof",
6703
6671
  "pr-review-proof",
6704
6672
  "pr-verify-proof"
6705
6673
  ]);
6706
- /** The newest ledger records one proof event carries. */
6707
- const MAX_GATE_TIMINGS_PER_EVENT = 50;
6708
6674
  /**
6709
6675
  * The gate-timing records a proof event carries to HQ (#1316): the newest
6710
6676
  * records in this lane's ledger in the emitting checkout, keyed the way
@@ -6726,7 +6692,7 @@ const emissionGateTimings = async (input, env, deadline, payloadBytes) => {
6726
6692
  if (agentRunId === void 0) return [];
6727
6693
  const ledger = await readBoundedTextFile(gateTimingLedgerPath(path.resolve(input.cwd), agentRunId), deadline, MAX_HQ_CONFIG_BYTES);
6728
6694
  if (ledger === void 0) return [];
6729
- const records = parseGateTimingLedgerText(ledger).slice(-MAX_GATE_TIMINGS_PER_EVENT);
6695
+ const records = parseGateTimingLedgerText(ledger).slice(-50);
6730
6696
  return payloadBytes + Buffer.byteLength(JSON.stringify({ gateTimings: records }), "utf-8") <= MAX_HQ_INGEST_PAYLOAD_BYTES ? records : [];
6731
6697
  } catch {
6732
6698
  return [];
@@ -6744,27 +6710,6 @@ const validatedIngestEndpoint = (value) => {
6744
6710
  const origin = validatedHqOrigin(value);
6745
6711
  return origin === void 0 ? void 0 : new URL(HQ_INGEST_PATH$1, origin.origin);
6746
6712
  };
6747
- const retainRetryEntry = async (layout, entry, dependencies, deadline) => {
6748
- let customAppend;
6749
- try {
6750
- customAppend = dependencies.appendJournal;
6751
- } catch {
6752
- return "failed";
6753
- }
6754
- if (customAppend === void 0) return appendCloseoutSpool(layout, entry, deadline);
6755
- let row;
6756
- try {
6757
- row = JSON.stringify(entry);
6758
- } catch {
6759
- return "failed";
6760
- }
6761
- const target = path.join(path.resolve(layout.root, ...layout.segments), `${randomUUID()}-${spoolFileName(entry)}`);
6762
- setImmediate(async () => {
6763
- try {
6764
- await customAppend(target, row);
6765
- } catch {}
6766
- }).unref();
6767
- };
6768
6713
  /** The checkout's profile, read within `deadline`; unusable reads as absent. */
6769
6714
  const readProjectHqProfile = async (cwd, profilePath, deadline) => {
6770
6715
  let resolvedPath;
@@ -6942,7 +6887,7 @@ const isReplayableEntry = (value) => {
6942
6887
  * automation stops retrying: 401/403 (Access refusing expired or wrong
6943
6888
  * service-token credentials), 408 (request timeout), 429 (rate limit).
6944
6889
  */
6945
- const NON_CONTENT_CLIENT_STATUSES = new Set([
6890
+ const NON_CONTENT_CLIENT_STATUSES = /* @__PURE__ */ new Set([
6946
6891
  401,
6947
6892
  403,
6948
6893
  408,
@@ -6978,7 +6923,7 @@ const replayCloseoutSpool = async (layout, endpoint, clientId, clientSecret, req
6978
6923
  const metadata = await settleWithin(lstat(artifactPath), remainingMs(setupDeadline));
6979
6924
  if (metadata.status !== "fulfilled" || !metadata.value.isFile() || metadata.value.isSymbolicLink() || !isTemporary && !isClaim || now - (isTemporary ? metadata.value.mtimeMs : Math.max(metadata.value.mtimeMs, metadata.value.ctimeMs)) < STALE_SPOOL_ARTIFACT_MS) continue;
6980
6925
  if (isTemporary) {
6981
- const file = await readBoundedTextFileNoFollow(artifactPath, setupDeadline, MAX_HQ_INGEST_PAYLOAD_BYTES + 16 * 1024);
6926
+ const file = await readBoundedTextFileNoFollow(artifactPath, setupDeadline, 278528);
6982
6927
  let parsed;
6983
6928
  try {
6984
6929
  parsed = file === void 0 ? void 0 : JSON.parse(file.contents);
@@ -6990,7 +6935,8 @@ const replayCloseoutSpool = async (layout, endpoint, clientId, clientSecret, req
6990
6935
  if (!await mutateBoundDirectory(spool, spoolIdentity, setupDeadline, async () => unlink(artifactPath))) return;
6991
6936
  continue;
6992
6937
  }
6993
- if (!await publishImmutableFile(spool, spoolIdentity, artifactPath, path.join(spool, finalName), setupDeadline)) return;
6938
+ const finalPath = path.join(spool, finalName);
6939
+ if (!await publishImmutableFile(spool, spoolIdentity, artifactPath, finalPath, setupDeadline)) return;
6994
6940
  continue;
6995
6941
  }
6996
6942
  const markerIndex = name.indexOf(".json.draining-");
@@ -7007,10 +6953,10 @@ const replayCloseoutSpool = async (layout, endpoint, clientId, clientSecret, req
7007
6953
  if (!await directoryIdentityMatches(spool, spoolIdentity, setupDeadline)) return;
7008
6954
  if (attempted >= maxEntries || remainingMs(replayDeadline) <= 0) break;
7009
6955
  const metadata = await settleWithin(lstat(eventPath), remainingMs(setupDeadline));
7010
- if (metadata.status !== "fulfilled" || !metadata.value.isFile() || metadata.value.isSymbolicLink() || metadata.value.size > MAX_HQ_INGEST_PAYLOAD_BYTES + 16 * 1024) continue;
6956
+ if (metadata.status !== "fulfilled" || !metadata.value.isFile() || metadata.value.isSymbolicLink() || metadata.value.size > 278528) continue;
7011
6957
  const claimPath = `${eventPath}.draining-${randomUUID()}`;
7012
6958
  if (!await mutateBoundDirectory(spool, spoolIdentity, setupDeadline, async () => rename(eventPath, claimPath))) continue;
7013
- const file = await readBoundedTextFileNoFollow(claimPath, setupDeadline, MAX_HQ_INGEST_PAYLOAD_BYTES + 16 * 1024);
6959
+ const file = await readBoundedTextFileNoFollow(claimPath, setupDeadline, 278528);
7014
6960
  let entry;
7015
6961
  try {
7016
6962
  entry = file === void 0 ? void 0 : JSON.parse(file.contents);
@@ -7023,7 +6969,8 @@ const replayCloseoutSpool = async (layout, endpoint, clientId, clientSecret, req
7023
6969
  }
7024
6970
  const entryEndpoint = validatedHqOrigin(entry.endpoint);
7025
6971
  if (!entryEndpoint || entryEndpoint.origin !== endpoint.origin) {
7026
- if (!await mutateBoundDirectory(spool, spoolIdentity, performance.now() + flushBudgetMs, async () => rename(claimPath, `${eventPath}${UNDELIVERABLE_SUFFIX}`))) return;
6972
+ const claimCompletionDeadline = performance.now() + flushBudgetMs;
6973
+ if (!await mutateBoundDirectory(spool, spoolIdentity, claimCompletionDeadline, async () => rename(claimPath, `${eventPath}${UNDELIVERABLE_SUFFIX}`))) return;
7027
6974
  report?.({
7028
6975
  detail: `recorded endpoint ${entryEndpoint?.origin ?? "(unusable)"} is not this repository's authorized HQ origin ${endpoint.origin}; dispositioned as ${path.basename(eventPath)}${UNDELIVERABLE_SUFFIX}`,
7029
6976
  eventId: entry.event.eventId,
@@ -7044,7 +6991,8 @@ const replayCloseoutSpool = async (layout, endpoint, clientId, clientSecret, req
7044
6991
  const outcome = await attemptTransport(request, endpoint, clientId, clientSecret, body, Math.min(transportBudgetMs, remainingMs(replayDeadline)), report !== void 0);
7045
6992
  const permanent = !outcome.ok && isPermanentRejection(outcome.reason);
7046
6993
  if (permanent && options.evictPermanentRejections === true) {
7047
- if (!await mutateBoundDirectory(spool, spoolIdentity, performance.now() + flushBudgetMs, async () => rename(claimPath, `${eventPath}${UNDELIVERABLE_SUFFIX}`))) return;
6994
+ const claimCompletionDeadline = performance.now() + flushBudgetMs;
6995
+ if (!await mutateBoundDirectory(spool, spoolIdentity, claimCompletionDeadline, async () => rename(claimPath, `${eventPath}${UNDELIVERABLE_SUFFIX}`))) return;
7048
6996
  report?.({
7049
6997
  detail: `${outcome.detail === void 0 ? outcome.reason : `${outcome.reason}: ${outcome.detail}`}; HQ refuses these bytes on every retry under its current ingest schema; dispositioned as ${path.basename(eventPath)}${UNDELIVERABLE_SUFFIX}`,
7050
6998
  eventId: entry.event.eventId,
@@ -7070,10 +7018,13 @@ const replayCloseoutSpool = async (layout, endpoint, clientId, clientSecret, req
7070
7018
  status: drainFailureStatus(outcome.reason)
7071
7019
  });
7072
7020
  }
7073
- if (!await mutateBoundDirectory(spool, spoolIdentity, performance.now() + flushBudgetMs, () => outcome.ok ? unlink(claimPath) : rename(claimPath, eventPath))) return;
7021
+ const claimCompletionDeadline = performance.now() + flushBudgetMs;
7022
+ if (!await mutateBoundDirectory(spool, spoolIdentity, claimCompletionDeadline, () => outcome.ok ? unlink(claimPath) : rename(claimPath, eventPath))) return;
7074
7023
  }
7075
7024
  };
7076
- async function deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, transportBudgetMs) {
7025
+ async function deliverHqIngest(input, dependencies, anchoredSetupDeadline, timeoutMs, transportBudgetMs, lateStart) {
7026
+ let setupDeadline = anchoredSetupDeadline;
7027
+ let persistOnly = lateStart;
7077
7028
  let config;
7078
7029
  try {
7079
7030
  if (!input.profile.hq?.enabled) return "skipped";
@@ -7093,7 +7044,8 @@ async function deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, tr
7093
7044
  await reportDiagnostic(dependencies, setupDeadline, "operator configuration is unavailable", "HQ ingest skipped");
7094
7045
  return "skipped";
7095
7046
  }
7096
- if (!isHqOriginAuthorized(await loadHqAllowedOrigins(env, setupDeadline), endpoint)) {
7047
+ const allowedOrigins = await loadHqAllowedOrigins(env, setupDeadline);
7048
+ if (!isHqOriginAuthorized(allowedOrigins, endpoint)) {
7097
7049
  await reportDiagnostic(dependencies, setupDeadline, `endpoint origin ${endpoint.origin} is not authorized by hqAllowedOrigins in the operator user config`, "HQ ingest skipped");
7098
7050
  return "skipped";
7099
7051
  }
@@ -7126,7 +7078,10 @@ async function deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, tr
7126
7078
  let unconfirmed = false;
7127
7079
  try {
7128
7080
  await setImmediate$1();
7129
- if (remainingMs(setupDeadline) <= 0) return "deferred";
7081
+ if (remainingMs(setupDeadline) <= 0) {
7082
+ setupDeadline = performance.now() + timeoutMs;
7083
+ persistOnly = true;
7084
+ }
7130
7085
  const projectedPayload = await loadBoundedPayload(input, setupDeadline);
7131
7086
  const eventId = makeEventId();
7132
7087
  const observedAt = now().toISOString();
@@ -7153,27 +7108,24 @@ async function deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, tr
7153
7108
  schemaVersion: projectedPayload.value.schemaVersion,
7154
7109
  ...subject === void 0 ? {} : { subject }
7155
7110
  };
7156
- let customJournal = false;
7111
+ let failedAt;
7157
7112
  try {
7158
- customJournal = dependencies.appendJournal !== void 0;
7113
+ failedAt = now().toISOString();
7159
7114
  } catch {
7160
- customJournal = false;
7115
+ failedAt = "unknown";
7161
7116
  }
7162
- if (!customJournal) {
7163
- let failedAt;
7164
- try {
7165
- failedAt = now().toISOString();
7166
- } catch {
7167
- failedAt = "unknown";
7168
- }
7169
- const persisted = await persistRetrySpool(writeLayout, {
7170
- endpoint: endpoint.href,
7171
- event,
7172
- failedAt,
7173
- reason: "tracked-advisory-pending"
7174
- }, performance.now() + journalFlushBudgetFor(dependencies));
7175
- if (persisted.status === "persisted") persistedEventPath = persisted.eventPath;
7176
- else prePersistFailure = persisted.failure;
7117
+ const persisted = await persistRetrySpool(writeLayout, {
7118
+ endpoint: endpoint.href,
7119
+ event,
7120
+ failedAt,
7121
+ reason: persistOnly ? "setup-budget-elapsed" : "tracked-advisory-pending"
7122
+ }, performance.now() + journalFlushBudgetFor(dependencies));
7123
+ if (persisted.status === "persisted") persistedEventPath = persisted.eventPath;
7124
+ else prePersistFailure = persisted.failure;
7125
+ if (persistOnly) {
7126
+ if (persistedEventPath !== void 0) return "deferred";
7127
+ reason = "setup-budget-elapsed";
7128
+ throw new Error(reason);
7177
7129
  }
7178
7130
  if (!clientId || !clientSecret) {
7179
7131
  if (persistedEventPath === void 0) {
@@ -7217,12 +7169,6 @@ async function deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, tr
7217
7169
  } catch {
7218
7170
  failedAt = "unknown";
7219
7171
  }
7220
- let customJournal = false;
7221
- try {
7222
- customJournal = dependencies.appendJournal !== void 0;
7223
- } catch {
7224
- customJournal = false;
7225
- }
7226
7172
  const retryEntry = {
7227
7173
  endpoint: endpoint.href,
7228
7174
  event,
@@ -7230,15 +7176,12 @@ async function deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, tr
7230
7176
  reason,
7231
7177
  ...unconfirmed ? { unconfirmed: true } : {}
7232
7178
  };
7233
- if (customJournal && persistedEventPath === void 0) journalFailure = await retainRetryEntry(writeLayout, retryEntry, dependencies, flushDeadline);
7234
- else if (!customJournal) {
7235
- const updated = await persistRetrySpool(writeLayout, retryEntry, flushDeadline);
7236
- if (updated.status === "persisted") {
7237
- if (persistedEventPath !== void 0) await removeRetrySpoolEvent(writeLayout, persistedEventPath, flushDeadline);
7238
- persistedEventPath = updated.eventPath;
7239
- journalFailure = void 0;
7240
- } else journalFailure = updated.failure;
7241
- }
7179
+ const updated = await persistRetrySpool(writeLayout, retryEntry, flushDeadline);
7180
+ if (updated.status === "persisted") {
7181
+ if (persistedEventPath !== void 0) await removeRetrySpoolEvent(writeLayout, persistedEventPath, flushDeadline);
7182
+ persistedEventPath = updated.eventPath;
7183
+ journalFailure = void 0;
7184
+ } else journalFailure = updated.failure;
7242
7185
  }
7243
7186
  if (!unconfirmed && journalFailure === void 0 && persistedEventPath !== void 0) return "deferred";
7244
7187
  const journalSuffix = journalFailure ? `; retry spool ${journalFailure}` : "";
@@ -7248,12 +7191,13 @@ async function deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, tr
7248
7191
  async function dispatchBounded(dependencies, gateStartedAt, work) {
7249
7192
  await setImmediate$1();
7250
7193
  const timeoutMs = timeoutFor(dependencies);
7251
- const setupDeadline = gateStartedAt + timeoutMs;
7252
- if (remainingMs(setupDeadline) <= 0) return "deferred";
7194
+ const lateStart = remainingMs(gateStartedAt + timeoutMs) <= 0;
7195
+ const anchoredAt = lateStart ? performance.now() : gateStartedAt;
7196
+ const setupDeadline = anchoredAt + timeoutMs;
7253
7197
  const transportBudgetMs = transportTimeoutFor(dependencies);
7254
- const outerDeadline = gateStartedAt + timeoutMs + 2 * transportBudgetMs + HQ_JOURNAL_FLUSH_BUDGET_MS + 500;
7198
+ const outerDeadline = anchoredAt + timeoutMs + 2 * transportBudgetMs + HQ_JOURNAL_FLUSH_BUDGET_MS + 500;
7255
7199
  try {
7256
- const result = await settleWithin(work(setupDeadline, timeoutMs, transportBudgetMs), remainingMs(outerDeadline));
7200
+ const result = await settleWithin(work(setupDeadline, timeoutMs, transportBudgetMs, lateStart), remainingMs(outerDeadline));
7257
7201
  return result.status === "fulfilled" ? result.value : "deferred";
7258
7202
  } catch {
7259
7203
  return "deferred";
@@ -7280,7 +7224,8 @@ async function drainRepositorySpool(input, dependencies, setupDeadline, timeoutM
7280
7224
  const endpoint = validatedIngestEndpoint(profile.hq.endpoint);
7281
7225
  if (!endpoint) return "skipped";
7282
7226
  const env = dependencies.env ?? process.env;
7283
- if (!isHqOriginAuthorized(await loadHqAllowedOrigins(env, setupDeadline), endpoint)) return "skipped";
7227
+ const allowedOrigins = await loadHqAllowedOrigins(env, setupDeadline);
7228
+ if (!isHqOriginAuthorized(allowedOrigins, endpoint)) return "skipped";
7284
7229
  const layout = repositorySpoolLayout({
7285
7230
  owner: profile.repository.owner,
7286
7231
  repo: profile.repository.name
@@ -7310,14 +7255,14 @@ async function drainHqSpoolOnExit(input, dependencies = {}) {
7310
7255
  } catch {}
7311
7256
  }
7312
7257
  /** Wall-clock ceiling for one explicit drain. Flush is not a gate; it may wait. */
7313
- const DEFAULT_HQ_FLUSH_BUDGET_MS = 600 * 1e3;
7258
+ const DEFAULT_HQ_FLUSH_BUDGET_MS = 6e5;
7314
7259
  /** ENOENT is the only filesystem answer that means "this location is absent". */
7315
7260
  const isMissingEntryError = (error) => typeof error === "object" && error !== null && error.code === "ENOENT";
7316
7261
  const countRemainingSpoolWork = async (spools, deadline, options = {}) => {
7317
7262
  let remaining = 0;
7318
7263
  const reasons = /* @__PURE__ */ new Map();
7319
7264
  const noteReason = async (file, listed) => {
7320
- const read = await readBoundedTextFileNoFollow(file, deadline, MAX_HQ_INGEST_PAYLOAD_BYTES + 16 * 1024);
7265
+ const read = await readBoundedTextFileNoFollow(file, deadline, 278528);
7321
7266
  if (read !== void 0 && (read.identity.dev !== listed.dev || read.identity.ino !== listed.ino)) return;
7322
7267
  let entry;
7323
7268
  try {
@@ -7592,17 +7537,19 @@ async function flushHqSpool(input, dependencies = {}) {
7592
7537
  */
7593
7538
  function enqueueHqIngest(input, dependencies = {}) {
7594
7539
  try {
7595
- return trackPendingHqIngest(dispatchBounded(dependencies, performance.now(), (setupDeadline, timeoutMs, transportBudgetMs) => deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, transportBudgetMs)));
7540
+ const gateStartedAt = performance.now();
7541
+ return trackPendingHqIngest(dispatchBounded(dependencies, gateStartedAt, (setupDeadline, timeoutMs, transportBudgetMs, lateStart) => deliverHqIngest(input, dependencies, setupDeadline, timeoutMs, transportBudgetMs, lateStart)));
7596
7542
  } catch {
7597
7543
  return Promise.resolve("skipped");
7598
7544
  }
7599
7545
  }
7600
7546
  function enqueueProjectHqIngest(input, dependencies = {}) {
7601
7547
  try {
7602
- return trackPendingHqIngest(dispatchBounded(dependencies, performance.now(), async (setupDeadline, timeoutMs, transportBudgetMs) => {
7548
+ const gateStartedAt = performance.now();
7549
+ return trackPendingHqIngest(dispatchBounded(dependencies, gateStartedAt, async (setupDeadline, timeoutMs, transportBudgetMs, lateStart) => {
7603
7550
  const projectInput = await projectInputForHqIngest(input, setupDeadline);
7604
7551
  if (projectInput === void 0) return "skipped";
7605
- return deliverHqIngest(projectInput, dependencies, setupDeadline, timeoutMs, transportBudgetMs);
7552
+ return deliverHqIngest(projectInput, dependencies, setupDeadline, timeoutMs, transportBudgetMs, lateStart);
7606
7553
  }));
7607
7554
  } catch {
7608
7555
  return Promise.resolve("skipped");
@@ -7925,7 +7872,8 @@ const deferProjectHqIngestIsolated = async (input, env) => {
7925
7872
  if (!isIsolatedReadResult(sourcesRead)) return "held";
7926
7873
  const configOrigins = isolatedConfigOrigins(sourcesRead.results.config);
7927
7874
  if (configOrigins === void 0) return "skipped";
7928
- if (!isHqOriginAuthorized(resolveHqAllowedOrigins(env, configOrigins), endpoint)) return "skipped";
7875
+ const allowedOrigins = resolveHqAllowedOrigins(env, configOrigins);
7876
+ if (!isHqOriginAuthorized(allowedOrigins, endpoint)) return "skipped";
7929
7877
  const payloadSource = input.payloadJson ?? (sourcesRead.results.payload?.status === "ok" ? sourcesRead.results.payload.source : void 0);
7930
7878
  if (payloadSource === void 0) return "held";
7931
7879
  const projectedPayload = parseBoundedPayloadText(payloadSource);
@@ -7987,8 +7935,7 @@ async function deferProjectHqIngest(input, dependencies = {}) {
7987
7935
  }
7988
7936
  return deferProjectHqIngestIsolated(input, env);
7989
7937
  }
7990
- //#endregion
7991
- //#region src/evidence-freshness.ts
7938
+ // src/evidence-freshness.ts
7992
7939
  const patchIdMatches = (recorded, candidate) => Boolean(recorded.patchId) && recorded.patchId === candidate.patchId;
7993
7940
  const headShaMatches = (recorded, candidate) => Boolean(recorded.headSha && candidate.headSha && sameHeadSha(candidate.headSha, recorded.headSha));
7994
7941
  /**
@@ -8002,8 +7949,7 @@ function evidenceFresh({ candidate, recorded, rule }) {
8002
7949
  if (patchIdMatches(recorded, candidate)) return true;
8003
7950
  return rule === "patch-id-or-head-sha" && headShaMatches(recorded, candidate);
8004
7951
  }
8005
- //#endregion
8006
- //#region src/pr-readiness/external-evidence.ts
7952
+ // src/pr-readiness/external-evidence.ts
8007
7953
  var external_evidence_exports = /* @__PURE__ */ __exportAll({
8008
7954
  EVIDENCE_CHECK_TYPES: () => EVIDENCE_CHECK_TYPES,
8009
7955
  EVIDENCE_DIR: () => EVIDENCE_DIR,
@@ -8338,8 +8284,7 @@ function independenceRefusalReason(name, independence) {
8338
8284
  default: return `Required review check "${name}" independence could not be confirmed; fail closed (ADR 0014).`;
8339
8285
  }
8340
8286
  }
8341
- //#endregion
8342
- //#region src/evidence-emit.ts
8287
+ // src/evidence-emit.ts
8343
8288
  const defaultGit = () => ({
8344
8289
  currentHeadSha,
8345
8290
  mergeBaseSha,
@@ -8368,7 +8313,7 @@ function buildEvidenceEnvelope(args, dependencies = {}) {
8368
8313
  git
8369
8314
  });
8370
8315
  const sessionId = resolveEmitSessionId(args.sessionId, env);
8371
- const parsed = parseEvidenceEnvelope({
8316
+ const candidate = {
8372
8317
  check: args.check,
8373
8318
  checkType: "verify",
8374
8319
  headSha,
@@ -8382,7 +8327,8 @@ function buildEvidenceEnvelope(args, dependencies = {}) {
8382
8327
  ...args.policyVersion ? { policyVersion: args.policyVersion } : {},
8383
8328
  ...sessionId ? { sessionId } : {},
8384
8329
  ...args.requestId ? { requestId: args.requestId } : {}
8385
- });
8330
+ };
8331
+ const parsed = parseEvidenceEnvelope(candidate);
8386
8332
  if (!parsed.ok) throw new Error(`Refusing to emit an invalid evidence envelope: ${parsed.error}`);
8387
8333
  return parsed.envelope;
8388
8334
  }
@@ -8406,8 +8352,7 @@ function runEvidenceEmit(args, dependencies = {}) {
8406
8352
  path: target
8407
8353
  };
8408
8354
  }
8409
- //#endregion
8410
- //#region src/gate-timing-finalize.ts
8355
+ // src/gate-timing-finalize.ts
8411
8356
  /**
8412
8357
  * A gate's hook to write its own timing record before its final proof event
8413
8358
  * (#1316).
@@ -8446,8 +8391,7 @@ const finalizeGateTiming = (gate, { passed }) => {
8446
8391
  if (scope?.gate === gate) scope.finalize(passed ? "pass" : "fail");
8447
8392
  } catch {}
8448
8393
  };
8449
- //#endregion
8450
- //#region src/advisory-line.ts
8394
+ // src/advisory-line.ts
8451
8395
  const absorbStreamError = () => {};
8452
8396
  /**
8453
8397
  * One best-effort line, on stderr unless another stream is named. A closed
@@ -8468,8 +8412,7 @@ const writeAdvisoryLine = (line, stream = process.stderr) => {
8468
8412
  if (error === null || error === void 0) stream.removeListener("error", absorbStreamError);
8469
8413
  });
8470
8414
  };
8471
- //#endregion
8472
- //#region src/check-run-generations.ts
8415
+ // src/check-run-generations.ts
8473
8416
  /**
8474
8417
  * Select the newest generation, or say why there is no single authority.
8475
8418
  *
@@ -8501,8 +8444,7 @@ function generationOrderMs(value) {
8501
8444
  const parsed = value ? Date.parse(value) : NaN;
8502
8445
  return Number.isFinite(parsed) ? parsed : Number.NEGATIVE_INFINITY;
8503
8446
  }
8504
- //#endregion
8505
- //#region src/check-run-relay.ts
8447
+ // src/check-run-relay.ts
8506
8448
  /**
8507
8449
  * The CLI side of HQ's Factory check-run relay (#1535, #1567).
8508
8450
  *
@@ -8599,8 +8541,7 @@ async function postCheckRunThroughRelay(relay, body, request, timeoutMs) {
8599
8541
  if (!response.ok) throw new GitHubApiError(response.status, response.statusText);
8600
8542
  return await response.json();
8601
8543
  }
8602
- //#endregion
8603
- //#region src/github-app-client.ts
8544
+ // src/github-app-client.ts
8604
8545
  const readExchange = async (request, url, init, timeoutMs) => {
8605
8546
  const response = await request(url, {
8606
8547
  ...init,
@@ -8667,16 +8608,14 @@ async function requestFactoryApp(input, dependencies = {}) {
8667
8608
  const token = await resolveFactoryAppToken(input, dependencies, request, timeoutMs);
8668
8609
  return readExchange(request, `https://api.github.com/repos/${input.owner}/${input.repo}/${input.path}`, factoryAppInit(input, token), timeoutMs);
8669
8610
  }
8670
- //#endregion
8671
- //#region src/pr-verify-mode.ts
8672
- const RESOLVED_PR_VERIFY_MODES = new Set([
8611
+ // src/pr-verify-mode.ts
8612
+ const RESOLVED_PR_VERIFY_MODES = /* @__PURE__ */ new Set([
8673
8613
  "docs-only",
8674
8614
  "trivial",
8675
8615
  "full"
8676
8616
  ]);
8677
8617
  const isResolvedPrVerifyMode = (value) => RESOLVED_PR_VERIFY_MODES.has(value);
8678
- //#endregion
8679
- //#region src/catch-up-recognition-record.ts
8618
+ // src/catch-up-recognition-record.ts
8680
8619
  const objectShaSchema = z.string().regex(/^[0-9a-f]{40}$/u);
8681
8620
  const catchUpRecognitionSchema = z.object({
8682
8621
  baseRef: z.string().min(1),
@@ -8685,8 +8624,7 @@ const catchUpRecognitionSchema = z.object({
8685
8624
  mergedTreeSha: objectShaSchema,
8686
8625
  upstreamRef: z.string().min(1)
8687
8626
  }).strict();
8688
- //#endregion
8689
- //#region src/policy-resolution.ts
8627
+ // src/policy-resolution.ts
8690
8628
  const COMMIT_SHA_PATTERN$3 = /^[0-9a-f]{40}$/u;
8691
8629
  const digestSchema = z.string().regex(/^[0-9a-f]{64}$/u);
8692
8630
  /**
@@ -8744,8 +8682,7 @@ const unresolvedPolicyResolutionSchema = z.object({
8744
8682
  const policyResolutionSchema = z.discriminatedUnion("status", [authoritativePolicyResolutionSchema, unresolvedPolicyResolutionSchema]);
8745
8683
  /** Only the ordinary pre-PR unresolved policy permits proof reuse (#1459). */
8746
8684
  const policyResolutionAllowsProofReuse = (resolution) => resolution?.status !== "unresolved" || resolution.cause === "no-pull-request";
8747
- //#endregion
8748
- //#region src/verification-battery.ts
8685
+ // src/verification-battery.ts
8749
8686
  const UNCONDITIONAL_BASIS = "unconditional: the profile declares no impactTarget for this command";
8750
8687
  /**
8751
8688
  * The `vetoedTargets` contract, enforced at RUNTIME as well as at the type
@@ -8878,7 +8815,7 @@ const assertBatteryCompleteness = (proof, context) => {
8878
8815
  seen.add(entry.name);
8879
8816
  }
8880
8817
  if (proof.outcome !== "passed") return;
8881
- const disposed = new Set([...executed, ...seen]);
8818
+ const disposed = /* @__PURE__ */ new Set([...executed, ...seen]);
8882
8819
  const undisposed = selected.filter((name) => !disposed.has(name));
8883
8820
  if (undisposed.length > 0) context.addIssue({
8884
8821
  code: "custom",
@@ -8976,8 +8913,7 @@ const batteryScopeSummaryLines = (plan) => {
8976
8913
  if (plan.notRequired.length === 0) return [];
8977
8914
  return ["Verification battery scoped by the impact stamp (not-required):", ...plan.notRequired.map((entry) => `- ${entry.name} (${entry.impactTarget}): ${entry.basis}`)];
8978
8915
  };
8979
- //#endregion
8980
- //#region src/pr-verify-proof-rules.ts
8916
+ // src/pr-verify-proof-rules.ts
8981
8917
  const assertPrVerifyProofRules = (proof, context) => {
8982
8918
  if (proof.notDemandedRecords !== void 0 && proof.impactStamp === void 0) context.addIssue({
8983
8919
  code: "custom",
@@ -8996,6 +8932,12 @@ const assertPrVerifyProofRules = (proof, context) => {
8996
8932
  * factory must adopt this release before HQ ingests its pr:verify proofs.
8997
8933
  */
8998
8934
  const SUPPORTED_PR_VERIFY_SCHEMA_VERSIONS = [4];
8935
+ /** Where a verification battery ran (#1570). */
8936
+ const PR_VERIFY_RUNNER_KINDS = [
8937
+ "ci",
8938
+ "cloud",
8939
+ "local"
8940
+ ];
8999
8941
  const prVerifyTestFailureSchema = z.object({
9000
8942
  file: z.string().min(1),
9001
8943
  kind: z.enum([
@@ -9030,6 +8972,17 @@ const notDemandedRecordSchema = z.object({
9030
8972
  basis: z.string().min(1),
9031
8973
  name: z.string().min(1)
9032
8974
  });
8975
+ const runnerSchema = z.object({
8976
+ arch: z.string().min(1).max(32),
8977
+ cpuCount: z.number().int().positive(),
8978
+ kind: z.enum(PR_VERIFY_RUNNER_KINDS),
8979
+ os: z.string().min(1).max(32),
8980
+ provider: z.enum([
8981
+ "claude-code",
8982
+ "cursor",
8983
+ "github-actions"
8984
+ ]).optional()
8985
+ });
9033
8986
  const prVerifySchemaVersionSchema = z.literal(4);
9034
8987
  const prVerifyProofSchema = z.object({
9035
8988
  authoringSession: z.string().trim().min(1),
@@ -9071,6 +9024,7 @@ const prVerifyProofSchema = z.object({
9071
9024
  profilePath: z.string().min(1),
9072
9025
  projectKey: z.string().min(1),
9073
9026
  repository: z.string().min(1),
9027
+ runner: runnerSchema.optional(),
9074
9028
  schemaVersion: prVerifySchemaVersionSchema,
9075
9029
  startedAt: z.iso.datetime(),
9076
9030
  verificationCommands: z.array(z.object({
@@ -9088,8 +9042,7 @@ const prVerifyProofSchema = z.object({
9088
9042
  function validatePrVerifyProof(value) {
9089
9043
  return prVerifyProofSchema.parse(value);
9090
9044
  }
9091
- //#endregion
9092
- //#region src/pr-verify-check-payload.ts
9045
+ // src/pr-verify-check-payload.ts
9093
9046
  /**
9094
9047
  * Machine-readable binding carried on the `patronage-factory/pr-verify` check
9095
9048
  * run (#247), alongside the human-readable prose summary.
@@ -9179,8 +9132,7 @@ const parsePrVerifyCheckPayload = (text) => {
9179
9132
  } catch {}
9180
9133
  };
9181
9134
  const renderPrVerifyCheckPayloadText = (payload) => `\`\`\`json\n${JSON.stringify(payload, null, 2)}\n\`\`\``;
9182
- //#endregion
9183
- //#region src/github-check-runs.ts
9135
+ // src/github-check-runs.ts
9184
9136
  const FACTORY_CHECK_NAMES = {
9185
9137
  "pr-ready": "patronage-factory/pr-ready",
9186
9138
  "pr-review": "patronage-factory/pr-review",
@@ -9785,25 +9737,13 @@ async function ensureFactoryCheckRunPublished(input, dependencies = {}) {
9785
9737
  return false;
9786
9738
  }
9787
9739
  }
9788
- /**
9789
- * The detached publication's budget, stated once (#1322, #1394). Each stage
9790
- * enforces its own share in per-call timeouts (`timeoutMs`, 5 s by default):
9791
- * the Details lookup (`gh pr view`) one call; the App credential two (a PEM
9792
- * mint's installation lookup and token POST, one attempt each, or a Cursor
9793
- * VM's OIDC mint and broker exchange); the check-run POST one per attempt,
9794
- * with its retry delays between. A publication that finishes inside its stage
9795
- * budgets therefore finishes inside their sum, plus a margin for the work
9796
- * between stages. By default that is 4 × 5 s + 1 s = 21 s.
9797
- */
9798
- const DETAILS_URL_CALLS = 1;
9799
- const CREDENTIAL_CALLS = 2;
9800
9740
  const STAGE_HANDOFF_MARGIN_MS = 1e3;
9801
9741
  const publicationBudgetMs = (dependencies) => {
9802
9742
  const timeoutMs = dependencies.timeoutMs ?? 5e3;
9803
9743
  const { attempts, delayMs } = dependencies.retry ?? DEFAULT_CHECK_RUN_RETRY;
9804
9744
  const posts = Math.max(1, attempts);
9805
9745
  const postTimeoutMs = checkRunRelayOptedIn(dependencies.env ?? process.env) ? Math.max(timeoutMs, CHECK_RUN_RELAY_TIMEOUT_MS) : timeoutMs;
9806
- return (DETAILS_URL_CALLS + CREDENTIAL_CALLS) * timeoutMs + posts * postTimeoutMs + (posts - 1) * delayMs + STAGE_HANDOFF_MARGIN_MS;
9746
+ return 3 * timeoutMs + posts * postTimeoutMs + (posts - 1) * delayMs + STAGE_HANDOFF_MARGIN_MS;
9807
9747
  };
9808
9748
  /** `request` with `signal` joined to each call's own signal, never in its place. */
9809
9749
  const fetchCancelledBy = (request, signal) => async (resource, init) => request(resource, {
@@ -10307,8 +10247,7 @@ function readExactHeadFactoryRunFrom(source, input) {
10307
10247
  }
10308
10248
  /** One line naming a run: its id or link, its status and its conclusion. */
10309
10249
  const describeExactHeadFactoryRun = (gate, run) => `${FACTORY_CHECK_NAMES[gate]} run ${run.url ?? (run.id === void 0 ? "with no id" : String(run.id))} (${run.status === "completed" ? `completed, ${run.conclusion || "no conclusion"}` : run.status || "no status"})`;
10310
- //#endregion
10311
- //#region src/repository-profile-path.ts
10250
+ // src/repository-profile-path.ts
10312
10251
  /**
10313
10252
  * `git rev-parse --show-toplevel` answers with a real path, while a caller's
10314
10253
  * `cwd` may reach the same directory through a symlink (every macOS temporary
@@ -10378,8 +10317,7 @@ const repositoryContainedProfilePath = ({ cwd, profilePath, readRepositoryRoot =
10378
10317
  if (escapesRoot(relativePath)) throw new Error("The readiness profile must be inside the trusted checkout.");
10379
10318
  return relativePath;
10380
10319
  };
10381
- //#endregion
10382
- //#region src/pr-classification.ts
10320
+ // src/pr-classification.ts
10383
10321
  const MISSING_STAMP_REASON = "impact stamp is missing; fail closed to non-trivial";
10384
10322
  function ownershipFromStamp(stamp, file) {
10385
10323
  if (stamp.inertPaths.includes(file)) return { kind: "inert" };
@@ -10487,8 +10425,7 @@ function classifyDiffForRun(profile, files, options) {
10487
10425
  });
10488
10426
  return applyProfileEditGuard(files, relativeProfile, options.profilePath, classifyDiff(files, stamp));
10489
10427
  }
10490
- //#endregion
10491
- //#region src/pr-readiness/verification-proof.ts
10428
+ // src/pr-readiness/verification-proof.ts
10492
10429
  var verification_proof_exports = /* @__PURE__ */ __exportAll({
10493
10430
  SUPPORTED_PR_VERIFY_SCHEMA_VERSIONS: () => SUPPORTED_PR_VERIFY_SCHEMA_VERSIONS,
10494
10431
  prVerifyFullHeadShasForDiff: () => prVerifyFullHeadShasForDiff,
@@ -10738,8 +10675,56 @@ const verificationProofBlockingReason = (state) => {
10738
10675
  return "Typed pr:verify proof shows verification aborted; verification did not pass. Re-run patronage-factory pr:verify.";
10739
10676
  }
10740
10677
  };
10741
- //#endregion
10742
- //#region src/workspace-install-resolution.ts
10678
+ // src/verify-runner.ts
10679
+ const currentHost = () => ({
10680
+ arch: process.arch,
10681
+ cpuCount: availableParallelism(),
10682
+ os: process.platform
10683
+ });
10684
+ const present = (value) => value !== void 0 && value.length > 0;
10685
+ /**
10686
+ * Classifies the machine a pr:verify battery runs on (#1570). It reads only
10687
+ * documented environment markers, never a hostname or path:
10688
+ *
10689
+ * - `GITHUB_ACTIONS` or `CI` marks a hosted CI runner (the same test as
10690
+ * `isHostedRunner`).
10691
+ * - `CLAUDE_CODE_REMOTE=true` marks a Claude Code cloud session.
10692
+ * - `CURSOR_AGENT_SOCKET` marks a Cursor-managed VM (the same marker
10693
+ * `doctor` reads).
10694
+ *
10695
+ * Everything else is `local`. CI wins over a cloud marker, because an agent
10696
+ * that dispatches to CI runs the battery on the CI machine.
10697
+ */
10698
+ const describeVerifyRunner = (env, host = currentHost()) => {
10699
+ const base = {
10700
+ arch: host.arch,
10701
+ cpuCount: Math.max(1, Math.trunc(host.cpuCount)),
10702
+ os: host.os
10703
+ };
10704
+ if (isHostedRunner(env)) return env.GITHUB_ACTIONS === "true" ? {
10705
+ ...base,
10706
+ kind: "ci",
10707
+ provider: "github-actions"
10708
+ } : {
10709
+ ...base,
10710
+ kind: "ci"
10711
+ };
10712
+ if (env.CLAUDE_CODE_REMOTE === "true") return {
10713
+ ...base,
10714
+ kind: "cloud",
10715
+ provider: "claude-code"
10716
+ };
10717
+ if (present(env.CURSOR_AGENT_SOCKET)) return {
10718
+ ...base,
10719
+ kind: "cloud",
10720
+ provider: "cursor"
10721
+ };
10722
+ return {
10723
+ ...base,
10724
+ kind: "local"
10725
+ };
10726
+ };
10727
+ // src/workspace-install-resolution.ts
10743
10728
  const readJson = (filePath, read) => {
10744
10729
  if (!existsSync(filePath)) return null;
10745
10730
  try {
@@ -10765,7 +10750,10 @@ const packageDirForName = (repoRoot, name, read) => {
10765
10750
  "software-factory",
10766
10751
  "software-factory-hq",
10767
10752
  "software-factory-docs"
10768
- ]) if (readJson(path.join(repoRoot, dir, "package.json"), read)?.name === name) return path.join(repoRoot, dir);
10753
+ ]) {
10754
+ const pkgPath = path.join(repoRoot, dir, "package.json");
10755
+ if (readJson(pkgPath, read)?.name === name) return path.join(repoRoot, dir);
10756
+ }
10769
10757
  return null;
10770
10758
  };
10771
10759
  /** Workspace packages HQ depends on whose Node default export is under dist/. */
@@ -10860,8 +10848,7 @@ const assertCleanInstallResolution = (repoRoot, dependencies = {}) => {
10860
10848
  skipped: false
10861
10849
  };
10862
10850
  };
10863
- //#endregion
10864
- //#region src/pr-verify.ts
10851
+ // src/pr-verify.ts
10865
10852
  const DEFAULT_PR_VERIFY_PROOF_PATH = ".factory-memory/pr-verify.json";
10866
10853
  const PR_VERIFY_PROOF_DESCRIPTOR$1 = {
10867
10854
  defaultPath: DEFAULT_PR_VERIFY_PROOF_PATH,
@@ -10947,7 +10934,7 @@ const classifyVitestFailure = (errorLine) => {
10947
10934
  * run that crashes while writing why it failed.
10948
10935
  */
10949
10936
  function parseVitestFailures(stdout) {
10950
- const lines = stdout.replace(ANSI_ESCAPE_PATTERN, "").split(/\r?\n/u);
10937
+ const lines = stdout.replaceAll(ANSI_ESCAPE_PATTERN, "").split(/\r?\n/u);
10951
10938
  const failures = [];
10952
10939
  const seen = /* @__PURE__ */ new Set();
10953
10940
  for (const [index, line] of lines.entries()) {
@@ -11031,7 +11018,7 @@ function baselineFullProofsForDocsOnly({ previousProof, profilePath, projectKey,
11031
11018
  seedFilter: matchesProfile
11032
11019
  });
11033
11020
  }
11034
- function buildPrVerifyProof({ authoringSession, base, baseSha, baselineFullProofs, catchUpRecognition, classification, commands, endedAt, executedCommands, files, headSha, impactStamp, mode, mergeBaseSha: proofMergeBaseSha, notRequiredCommands, outcome, patchId, policyResolution, profilePath, projectKey, repository, startedAt }) {
11021
+ function buildPrVerifyProof({ authoringSession, base, baseSha, baselineFullProofs, catchUpRecognition, classification, commands, endedAt, executedCommands, files, headSha, impactStamp, mode, mergeBaseSha: proofMergeBaseSha, notRequiredCommands, outcome, patchId, policyResolution, profilePath, projectKey, repository, runner, startedAt }) {
11035
11022
  return {
11036
11023
  authoringSession,
11037
11024
  base,
@@ -11056,6 +11043,7 @@ function buildPrVerifyProof({ authoringSession, base, baseSha, baselineFullProof
11056
11043
  profilePath,
11057
11044
  projectKey,
11058
11045
  repository,
11046
+ ...runner ? { runner } : {},
11059
11047
  schemaVersion: 4,
11060
11048
  startedAt: startedAt.toISOString(),
11061
11049
  verificationCommands: commands
@@ -11292,6 +11280,7 @@ function runPrVerify(args, dependencies = {}) {
11292
11280
  profilePath,
11293
11281
  projectKey: profile.repository.name,
11294
11282
  repository,
11283
+ runner: (dependencies.describeRunner ?? describeVerifyRunner)(dependencies.env ?? process.env),
11295
11284
  startedAt
11296
11285
  };
11297
11286
  const writePartialProof = (outcome) => {
@@ -11451,8 +11440,7 @@ const runPrVerifyWithAdmission = async (args, dependencies = {}) => {
11451
11440
  lookupPullRequestBase: () => lookup
11452
11441
  });
11453
11442
  };
11454
- //#endregion
11455
- //#region src/demand-waive.ts
11443
+ // src/demand-waive.ts
11456
11444
  const DEMAND_WAIVER_SCHEMA_VERSION = 1;
11457
11445
  const shaSchema$3 = z.string().regex(/^[0-9a-f]{40}$/u);
11458
11446
  const demandWaiverStorePath = (cwd, filePath) => path.resolve(cwd, filePath ?? ".factory-memory/demand-waivers.json");
@@ -11574,16 +11562,24 @@ const runDemandWaive = (args, dependencies = {}) => {
11574
11562
  ...authorization.authorization.session ? { session: authorization.authorization.session } : {}
11575
11563
  };
11576
11564
  const storePath = demandWaiverStorePath(cwd, args.output);
11577
- writeProofJson(validateDemandWaiverStore({
11565
+ const existing = readDemandWaivers(cwd, args.output).filter((candidate) => !(candidate.demand === waiver.demand && candidate.candidate.pr === waiver.candidate.pr && candidate.candidate.headSha === waiver.candidate.headSha));
11566
+ const store = {
11578
11567
  command: "patronage-factory demand:waive",
11579
11568
  schemaVersion: DEMAND_WAIVER_SCHEMA_VERSION,
11580
- waivers: [...readDemandWaivers(cwd, args.output).filter((candidate) => !(candidate.demand === waiver.demand && candidate.candidate.pr === waiver.candidate.pr && candidate.candidate.headSha === waiver.candidate.headSha)), waiver]
11581
- }), storePath);
11569
+ waivers: [...existing, waiver]
11570
+ };
11571
+ writeProofJson(validateDemandWaiverStore(store), storePath);
11582
11572
  console.log(`demand:waive recorded a waiver of "${waiver.demand}" for PR #${waiver.candidate.pr} at ${waiver.candidate.headSha} by ${waiver.operator}. The demand is waived, not met.`);
11583
11573
  console.log(`demand:waive record written to ${storePath}`);
11584
11574
  if (args.json) console.log(JSON.stringify(waiver, null, 2));
11585
11575
  return waiver;
11586
11576
  };
11577
+ // src/arming-outcome.ts
11578
+ const ARMING_OUTCOMES = [
11579
+ "armed",
11580
+ "merged",
11581
+ "not-armed"
11582
+ ];
11587
11583
  /** One refusal sentence: single line, trimmed, bounded. */
11588
11584
  const blockedReasonDetailSchema = z.string().min(1).max(280).refine((value) => value.trim().length > 0, { message: "must not be blank" }).refine((value) => !/[\r\n]/u.test(value), { message: "must be one line, not a multi-line payload" });
11589
11585
  const blockedReasonSchema = z.object({
@@ -11622,8 +11618,7 @@ const blockedReasonIssues = (proof) => {
11622
11618
  const drifted = named.findIndex((reason, index) => reason.detail !== blockedReasonDetail(reasons[index]));
11623
11619
  return drifted === -1 ? [] : blockedReasonIssue(`blockedReasons[${drifted}] does not carry blocking reason ${drifted}; the two projections must tell one story`);
11624
11620
  };
11625
- //#endregion
11626
- //#region src/packages/review-prompt-sections/schema.ts
11621
+ // src/packages/review-prompt-sections/schema.ts
11627
11622
  const REVIEW_PROMPT_SECTION_PROVENANCES = [
11628
11623
  "coding-standards",
11629
11624
  "prior-review-ledger",
@@ -11805,8 +11800,7 @@ const renderReviewFindingsFileExample = (waveRung) => JSON.stringify(exampleForS
11805
11800
  "resolutions",
11806
11801
  "rung"
11807
11802
  ] : [])), null, 2);
11808
- //#endregion
11809
- //#region src/review-ladder.ts
11803
+ // src/review-ladder.ts
11810
11804
  const LADDER_NEXT_ACTION_KINDS = [
11811
11805
  "run-interior-cycle",
11812
11806
  "advance-to-gate",
@@ -11935,8 +11929,7 @@ const evaluateReviewLadder = ({ cycles, policy }) => {
11935
11929
  occurrences
11936
11930
  };
11937
11931
  };
11938
- //#endregion
11939
- //#region src/pr-readiness/ladder-proof-state.ts
11932
+ // src/pr-readiness/ladder-proof-state.ts
11940
11933
  const persistedCycleSchema = z.custom((cycle) => typeof cycle === "object" && cycle !== null, "ladder cycle must be an object").superRefine((cycle, context) => {
11941
11934
  const parsed = reviewCycleRecordingSchema.safeParse(cycle.recording);
11942
11935
  if (!parsed.success) context.addIssue({
@@ -12002,8 +11995,7 @@ const reviewAcceptedThroughSnapshot = (snapshot) => {
12002
11995
  if (snapshot.evaluation.nextAction.kind === "accept-nonblocking-findings") return snapshot.cycleState.autoBlockingFindings === 0;
12003
11996
  return false;
12004
11997
  };
12005
- //#endregion
12006
- //#region src/pr-readiness/review-epoch.ts
11998
+ // src/pr-readiness/review-epoch.ts
12007
11999
  const openStateFromReviews = (reviews) => {
12008
12000
  const openEntries = reviews.flatMap((review) => review.findings);
12009
12001
  const blockingEntries = openEntries.filter((finding) => resolveFindingBlocking(finding, "open"));
@@ -12104,8 +12096,7 @@ const reviewProofForEpoch = (proof, kind, epoch, current) => {
12104
12096
  return {};
12105
12097
  };
12106
12098
  const reviewProofFor = (proof, kind, policy, current) => reviewProofForEpoch(proof, kind, reviewEpochModeFor(proof ?? {}, policy), current);
12107
- //#endregion
12108
- //#region src/pr-readiness/review-proof.ts
12099
+ // src/pr-readiness/review-proof.ts
12109
12100
  var review_proof_exports = /* @__PURE__ */ __exportAll({
12110
12101
  DEFAULT_PR_REVIEW_MAX_CYCLES: () => 5,
12111
12102
  DEFAULT_PR_REVIEW_PROOF_PATH: () => DEFAULT_PR_REVIEW_PROOF_PATH,
@@ -12269,8 +12260,7 @@ const PR_REVIEW_PROOF_DESCRIPTOR = {
12269
12260
  parse: validatePrReviewProof,
12270
12261
  schemaVersion: 3
12271
12262
  };
12272
- //#endregion
12273
- //#region src/review-proof-applicability.ts
12263
+ // src/review-proof-applicability.ts
12274
12264
  const REVIEW_STATUS_VALUES = [
12275
12265
  "not-required",
12276
12266
  "current",
@@ -12310,8 +12300,7 @@ const reviewStatus = ({ blocked, required, reviewedHeadSha, reviewedPatchId, hea
12310
12300
  })) return "current";
12311
12301
  return "stale";
12312
12302
  };
12313
- //#endregion
12314
- //#region src/review-state.ts
12303
+ // src/review-state.ts
12315
12304
  const reviewStateIssue = (message, field) => [{
12316
12305
  code: "custom",
12317
12306
  message,
@@ -12381,9 +12370,7 @@ const closeoutArtifactSchema = z.object({
12381
12370
  repo: RepoSchema,
12382
12371
  schemaVersion: z.literal(5)
12383
12372
  }).strict();
12384
- //#endregion
12385
- //#region src/schemas.ts
12386
- const evidenceCheckTypeSchema = z.enum(EVIDENCE_CHECK_TYPES);
12373
+ // src/schemas.ts
12387
12374
  const evidenceReviewRungSchema = z.enum(EVIDENCE_REVIEW_RUNGS);
12388
12375
  const diffClassificationSchema = z.enum(DIFF_CLASSIFICATIONS);
12389
12376
  const ladderStageSchema = z.enum(LADDER_STAGES);
@@ -12646,15 +12633,11 @@ const managedReadinessLedgerSchema$1 = z.object({
12646
12633
  ])
12647
12634
  });
12648
12635
  const prReadySchemaVersionSchema = z.literal(3);
12649
- z.object({
12636
+ const prReadyProofSchema = z.object({
12650
12637
  arming: z.object({
12651
12638
  detail: z.string().min(1).optional(),
12652
12639
  headSha: z.string().regex(/^[0-9a-f]{40}$/u),
12653
- outcome: z.enum([
12654
- "armed",
12655
- "merged",
12656
- "not-armed"
12657
- ])
12640
+ outcome: z.enum(ARMING_OUTCOMES)
12658
12641
  }).optional(),
12659
12642
  authoringSession: z.string().min(1).optional(),
12660
12643
  blockedReasons: blockedReasonsSchema.optional(),
@@ -12675,8 +12658,7 @@ z.object({
12675
12658
  }).superRefine((proof, context) => {
12676
12659
  for (const issue of blockedReasonIssues({ ...proof })) context.addIssue(issue);
12677
12660
  });
12678
- //#endregion
12679
- //#region src/boundary-check.ts
12661
+ // src/boundary-check.ts
12680
12662
  const DEFAULT_BOUNDARY_CHECK_PROOF_PATH = ".factory-memory/boundary-check.json";
12681
12663
  const CLOSING_PRS_QUERY = `query($owner: String!, $repo: String!, $issue: Int!) {
12682
12664
  repository(owner: $owner, name: $repo) {
@@ -12737,12 +12719,14 @@ const closingFetcherWithBodyKeywords = (manifest, repo, github) => {
12737
12719
  const listInput = manifest.integrationBranch === void 0 ? {} : { integrationBranch: manifest.integrationBranch };
12738
12720
  const candidates = github.listCandidatePullRequests(repo, listInput);
12739
12721
  return (issue) => {
12740
- return mergeClosingRefs(github.fetchClosingPullRequests(repo, issue), candidates.flatMap((candidate) => {
12722
+ const graphql = github.fetchClosingPullRequests(repo, issue);
12723
+ const extra = candidates.flatMap((candidate) => {
12741
12724
  return new Set(declaredChildrenNamedInBody(candidate.body, {
12742
12725
  owner,
12743
12726
  repo: name
12744
12727
  }, declared)).has(issue) ? [withoutBody(candidate)] : [];
12745
- }));
12728
+ });
12729
+ return mergeClosingRefs(graphql, extra);
12746
12730
  };
12747
12731
  };
12748
12732
  const closeGateForMemberships = ({ final, github, memberships, repo, waivers }) => {
@@ -12963,8 +12947,7 @@ async function runBoundaryCheckWithAdmission(args, dependencies = {}) {
12963
12947
  function validateBoundaryCheckProof(value) {
12964
12948
  return boundaryCheckProofSchema.parse(value);
12965
12949
  }
12966
- //#endregion
12967
- //#region src/interior-telemetry/pricing-snapshot.ts
12950
+ // src/interior-telemetry/pricing-snapshot.ts
12968
12951
  /** Human-readable provenance tag, embedded in data-gap messages so an unpriced
12969
12952
  * block names the exact snapshot that lacked its model. */
12970
12953
  const PRICING_SNAPSHOT_PROVENANCE = "litellm model_prices_and_context_window.json @ d966122 (fetched 2026-07-20)";
@@ -13044,8 +13027,7 @@ const LITELLM_PRICING_SNAPSHOT = {
13044
13027
  * must degrade to a null cost plus a data gap, never approximate.
13045
13028
  */
13046
13029
  const resolveModelPricing = (model) => LITELLM_PRICING_SNAPSHOT[model] ?? LITELLM_PRICING_SNAPSHOT[model.replace(/-20\d{6}$/u, "")];
13047
- //#endregion
13048
- //#region src/interior-telemetry/harvest-adapter.ts
13030
+ // src/interior-telemetry/harvest-adapter.ts
13049
13031
  const nonNegInt = (value) => typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value >= 0 ? value : void 0;
13050
13032
  const asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
13051
13033
  /** First non-empty string among the candidates, or undefined. */
@@ -13161,7 +13143,8 @@ const addTotals = (target, delta) => {
13161
13143
  };
13162
13144
  /** The cumulative `total_token_usage` on an at-rest `token_count` event. */
13163
13145
  const cumulativeFromTokenCount = (payload) => {
13164
- const total = asRecord(asRecord(payload.info)?.total_token_usage);
13146
+ const info = asRecord(payload.info);
13147
+ const total = asRecord(info?.total_token_usage);
13165
13148
  return total ? totalsFromUsage(total) : void 0;
13166
13149
  };
13167
13150
  /** Fold one rollout line into the accumulator (model + cumulative + per-turn). */
@@ -13481,8 +13464,7 @@ const harvestTokenFamilies = (input) => {
13481
13464
  };
13482
13465
  }
13483
13466
  };
13484
- //#endregion
13485
- //#region src/interior-telemetry/gate-timing.ts
13467
+ // src/interior-telemetry/gate-timing.ts
13486
13468
  const readGateTimingLedger = (ledgerPath) => {
13487
13469
  let content;
13488
13470
  try {
@@ -13562,8 +13544,7 @@ function withGateTiming(spec, action) {
13562
13544
  }
13563
13545
  };
13564
13546
  }
13565
- //#endregion
13566
- //#region src/commands/boundary-check.ts
13547
+ // src/commands/boundary-check.ts
13567
13548
  const renderReport = (record) => {
13568
13549
  const lines = [`boundary:check ${record.status === "ready" ? "READY" : "BLOCKED"} — ${record.boundary ?? "(no manifest)"} (epic #${record.epicIssue}, ${record.repo})`];
13569
13550
  if (record.manifestHash) lines.push(`manifest sha256 ${record.manifestHash.value}`);
@@ -13592,8 +13573,7 @@ function createBoundaryCheckCommand(output, action) {
13592
13573
  if (record.status !== "ready") throw new Error(`boundary:check refused: ${record.blockingReasons.join("; ")}`);
13593
13574
  })));
13594
13575
  }
13595
- //#endregion
13596
- //#region src/candidate-impact.ts
13576
+ // src/candidate-impact.ts
13597
13577
  const CANDIDATE_IMPACT_DECISION_SCHEMA_VERSION = 1;
13598
13578
  const COMMIT_SHA_PATTERN$2 = /^[0-9a-f]{40}$/iu;
13599
13579
  const ZERO_SHA_PATTERN$1 = /^0{40}$/u;
@@ -13821,8 +13801,7 @@ const candidateImpactSummaryLines = (decision) => decision.basis.classification
13821
13801
  inertPathsLine(decision.inertPaths),
13822
13802
  unsubscribedPathsLine(decision.unsubscribedPaths)
13823
13803
  ];
13824
- //#endregion
13825
- //#region src/commands/candidate-impact.ts
13804
+ // src/commands/candidate-impact.ts
13826
13805
  function createCandidateImpactCommand(output) {
13827
13806
  return markCwdOptionDefault(new Command("candidate:impact").description("Classify candidate targets from an exact pull-request base/head identity").option("--base <sha>", "candidate base commit SHA").option("--head <sha>", "candidate head commit SHA").option("--cwd <path>", "repository working directory", collectCwdOption).option("--profile <path>", "path to the project profile JSON file").option("--github-output <path>", "append stable decision outputs to a GitHub Actions output file").option("--github-summary <path>", "append a human-readable decision to a GitHub Actions summary file").option("--json", "print the complete decision as JSON").option("--emit-run-context", "emit the FACTORY_BASE_REF / FACTORY_CHANGED_FILES run-context contract").action((options) => {
13828
13807
  const decision = runCandidateImpact({
@@ -13846,8 +13825,7 @@ function createCandidateImpactCommand(output) {
13846
13825
  } else output.stdout.write(`${candidateImpactSummaryLines(decision).join("\n")}\n`);
13847
13826
  }));
13848
13827
  }
13849
- //#endregion
13850
- //#region src/ci-analyze.ts
13828
+ // src/ci-analyze.ts
13851
13829
  /**
13852
13830
  * `ci:analyze` — read-only GitHub Actions run lifecycle analysis (#647).
13853
13831
  *
@@ -14320,8 +14298,7 @@ const renderCiAnalyzeReport = (report) => {
14320
14298
  }
14321
14299
  return `${lines.join("\n")}\n`;
14322
14300
  };
14323
- //#endregion
14324
- //#region src/commands/ci-analyze.ts
14301
+ // src/commands/ci-analyze.ts
14325
14302
  /**
14326
14303
  * `ci:analyze` command wiring (#647).
14327
14304
  *
@@ -14394,7 +14371,7 @@ const assembleRunRequests = (input) => {
14394
14371
  }
14395
14372
  return ordered;
14396
14373
  };
14397
- const GH_ARTIFACT_MAX_BYTES = 256 * 1024 * 1024;
14374
+ const GH_ARTIFACT_MAX_BYTES = 268435456;
14398
14375
  const PAGE_SIZE = 100;
14399
14376
  const MAX_PAGES = 50;
14400
14377
  /**
@@ -14484,7 +14461,7 @@ const parseZipInfoListing = (text) => {
14484
14461
  }
14485
14462
  return members;
14486
14463
  };
14487
- const MAX_ARTIFACT_DECOMPRESSED_BYTES = 256 * 1024 * 1024;
14464
+ const MAX_ARTIFACT_DECOMPRESSED_BYTES = 268435456;
14488
14465
  const UNSAFE_MEMBER_CHARACTERS = /[*?[\]]/u;
14489
14466
  /**
14490
14467
  * The member policy for artifact zips, as a pure function so the security
@@ -14527,10 +14504,11 @@ const createGhCiAnalyzeClient = (repository) => ({
14527
14504
  const zip = execFileSync("gh", ["api", `/repos/${repository}/actions/artifacts/${artifactId}/zip`], { maxBuffer: GH_ARTIFACT_MAX_BYTES });
14528
14505
  const zipPath = path.join(scratch, "artifact.zip");
14529
14506
  writeFileSync(zipPath, zip);
14530
- const selected = selectProfileZipMembers(parseZipInfoListing(execFileSync("unzip", ["-Z", zipPath], {
14507
+ const listing = execFileSync("unzip", ["-Z", zipPath], {
14531
14508
  encoding: "utf-8",
14532
14509
  maxBuffer: GH_ARTIFACT_MAX_BYTES
14533
- })));
14510
+ });
14511
+ const selected = selectProfileZipMembers(parseZipInfoListing(listing));
14534
14512
  if (selected.length === 0) return Promise.resolve([]);
14535
14513
  const extracted = path.join(scratch, "extracted");
14536
14514
  execFileSync("unzip", [
@@ -14619,8 +14597,7 @@ const UnknownFactoryTraceEventSchema = FactoryTraceEventCoreSchema.extend({
14619
14597
  payload: z.unknown(),
14620
14598
  unknownTraceEvent: z.literal(true)
14621
14599
  }).strict();
14622
- //#endregion
14623
- //#region src/packages/trace/implementation/review-gate.ts
14600
+ // src/packages/trace/implementation/review-gate.ts
14624
14601
  const ReviewGateTracePayloadShape = z.object({
14625
14602
  base: nonEmptyString$1,
14626
14603
  changedFiles: z.array(nonEmptyString$1).min(1),
@@ -14639,8 +14616,7 @@ const ReviewGateTraceEventSchema = FactoryTraceEventCoreSchema.extend({
14639
14616
  typeVersion: z.literal(1)
14640
14617
  }).strict();
14641
14618
  const reviewGatePayloadFor = (event) => ReviewGateTracePayloadSchema.parse(Object.fromEntries(Object.keys(ReviewGateTracePayloadShape.shape).map((key) => [key, event[key]]).filter(([, value]) => value !== void 0)));
14642
- //#endregion
14643
- //#region src/packages/trace/implementation/review-ladder-stage.ts
14619
+ // src/packages/trace/implementation/review-ladder-stage.ts
14644
14620
  const LadderSessionAttributionSchema = z.object({
14645
14621
  orchestrationMode: z.enum(["autonomous", "manual"]).optional(),
14646
14622
  resumedSession: z.boolean().optional(),
@@ -14685,8 +14661,7 @@ const ReviewLadderStageTraceEventSchema = FactoryTraceEventCoreSchema.extend({
14685
14661
  typeVersion: z.literal(1)
14686
14662
  }).strict();
14687
14663
  const reviewLadderStagePayloadFor = (event) => ReviewLadderStageTracePayloadSchema.parse(Object.fromEntries(Object.keys(ReviewLadderStageTracePayloadShape.shape).map((key) => [key, event[key]]).filter(([, value]) => value !== void 0)));
14688
- //#endregion
14689
- //#region src/packages/trace/implementation/definitions.ts
14664
+ // src/packages/trace/implementation/definitions.ts
14690
14665
  const defineTraceEvent = (definition) => definition;
14691
14666
  const FACTORY_TRACE_EVENT_DEFINITIONS = [defineTraceEvent({
14692
14667
  appendEventSchema: ReviewGateTraceEventSchema,
@@ -14723,7 +14698,8 @@ const deriveTraceRegistry = (definitions) => {
14723
14698
  const factoryTraceEventSchema = z.union(readUnionSchemas);
14724
14699
  const appendFactoryTraceEventSchema = z.union(appendUnionSchemas);
14725
14700
  const wirePayloadFor = (event) => {
14726
- return definitionByKind[event.eventType].emit(event);
14701
+ const kind = event.eventType;
14702
+ return definitionByKind[kind].emit(event);
14727
14703
  };
14728
14704
  return {
14729
14705
  appendFactoryTraceEventSchema,
@@ -14737,8 +14713,7 @@ const deriveTraceRegistry = (definitions) => {
14737
14713
  };
14738
14714
  };
14739
14715
  const { appendFactoryTraceEventSchema: AppendFactoryTraceEventSchema, factoryTraceEventSchema: FactoryTraceEventSchema, payloadSchemaRegistry, payloadVersions: FACTORY_TRACE_PAYLOAD_VERSIONS, wirePayloadFor } = deriveTraceRegistry(FACTORY_TRACE_EVENT_DEFINITIONS);
14740
- //#endregion
14741
- //#region src/packages/trace/implementation/trace-shard.ts
14716
+ // src/packages/trace/implementation/trace-shard.ts
14742
14717
  const FACTORY_TRACE_DIR = ".factory-memory/factory-trace";
14743
14718
  const shardDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/u, "must be YYYY-MM-DD");
14744
14719
  const validateFactoryTraceShardDate = (date) => {
@@ -14748,8 +14723,7 @@ const validateFactoryTraceShardDate = (date) => {
14748
14723
  };
14749
14724
  const factoryTraceEventDate = (event) => new Date(event.createdAt).toISOString().slice(0, 10);
14750
14725
  const factoryTraceShardPath = (repoRoot, date) => path.join(repoRoot, FACTORY_TRACE_DIR, `${validateFactoryTraceShardDate(date)}.jsonl`);
14751
- //#endregion
14752
- //#region src/packages/trace/implementation/trace-sinks.ts
14726
+ // src/packages/trace/implementation/trace-sinks.ts
14753
14727
  const createLocalJsonlTraceSink = (repoRoot) => ({ append: (envelope) => {
14754
14728
  const filePath = factoryTraceShardPath(repoRoot, factoryTraceEventDate({ createdAt: envelope.createdAt }));
14755
14729
  mkdirSync(path.dirname(filePath), { recursive: true });
@@ -14775,8 +14749,7 @@ const resolveTraceWriteSinks = (repoRoot, options = {}) => {
14775
14749
  ...options.mirror ? { mirror: options.mirror } : {}
14776
14750
  };
14777
14751
  };
14778
- //#endregion
14779
- //#region src/packages/trace/implementation/facade.ts
14752
+ // src/packages/trace/implementation/facade.ts
14780
14753
  var FactoryTraceJsonlError = class extends Error {
14781
14754
  diagnostic;
14782
14755
  constructor(diagnostic) {
@@ -15017,8 +14990,7 @@ const scanFactoryTraceDiagnostics = ({ filters, from, repoRoot, to }) => scanFac
15017
14990
  repoRoot,
15018
14991
  to
15019
14992
  }).diagnostics;
15020
- //#endregion
15021
- //#region src/epic-closeout/gather.ts
14993
+ // src/epic-closeout/gather.ts
15022
14994
  const BUDGET_NOTE = "bounded closeout report: trace diagnostics scan plus the lane token harvest; no per-commit forensic dig";
15023
14995
  function gatherCloseoutInputs(opts) {
15024
14996
  const diagnostics = scanFactoryTraceDiagnostics({
@@ -15039,16 +15011,14 @@ function gatherCloseoutInputs(opts) {
15039
15011
  diagnostics
15040
15012
  };
15041
15013
  }
15042
- //#endregion
15043
- //#region src/epic-closeout/types.ts
15014
+ // src/epic-closeout/types.ts
15044
15015
  var CloseoutValidationError = class extends Error {
15045
15016
  constructor(message) {
15046
15017
  super(message);
15047
15018
  this.name = "CloseoutValidationError";
15048
15019
  }
15049
15020
  };
15050
- //#endregion
15051
- //#region src/epic-closeout/report.ts
15021
+ // src/epic-closeout/report.ts
15052
15022
  const ROW_LIMIT_BLINDSPOT_ID = "closeout-row-limit";
15053
15023
  const BASELINE_BLINDSPOT = {
15054
15024
  id: "bounded-standing-step",
@@ -15068,7 +15038,7 @@ const assertMetricSources = (metrics) => {
15068
15038
  */
15069
15039
  const boundCloseoutRows = (input) => {
15070
15040
  const sourceBlindspots = input.blindspots.filter((blindspot) => blindspot.id !== ROW_LIMIT_BLINDSPOT_ID);
15071
- let remaining = Math.max(0, MAX_CLOSEOUT_ROWS - 1);
15041
+ let remaining = Math.max(0, 999);
15072
15042
  const blindspots = sourceBlindspots.slice(0, remaining);
15073
15043
  remaining -= blindspots.length;
15074
15044
  const metrics = input.metrics.slice(0, remaining);
@@ -15108,8 +15078,7 @@ function buildEpicCloseoutReport(input) {
15108
15078
  schemaVersion: 5
15109
15079
  });
15110
15080
  }
15111
- //#endregion
15112
- //#region src/epic-closeout/token-harvest.ts
15081
+ // src/epic-closeout/token-harvest.ts
15113
15082
  /**
15114
15083
  * The closeout token harvest.
15115
15084
  *
@@ -15251,7 +15220,7 @@ const gptMetrics = (gpt) => gpt.roles.flatMap((role) => {
15251
15220
  const harvestCloseoutTokens = (input) => {
15252
15221
  const env = input.env ?? process.env;
15253
15222
  const dataGaps = [];
15254
- const laneIdentity = resolveGateTimingAgentRunId(env) ?? resolveNativeSessionId(env);
15223
+ const laneIdentity = resolveGateTimingAgentRunId(env);
15255
15224
  const agentRunId = laneIdentity ?? `closeout-${safeRunName(input.epic)}`;
15256
15225
  if (laneIdentity === void 0) dataGaps.push("agentRunId is synthetic (no lane run identity exported): the closeout is keyed to the epic, not to a run.");
15257
15226
  const claudeSessionId = discoverFactorySessionId(env) ?? resolveNativeSessionId(env);
@@ -15311,13 +15280,11 @@ const harvestCloseoutTokens = (input) => {
15311
15280
  metrics
15312
15281
  };
15313
15282
  };
15314
- //#endregion
15315
- //#region src/epic-closeout/epic-filename.ts
15283
+ // src/epic-closeout/epic-filename.ts
15316
15284
  function sanitizeEpicFilename(epic) {
15317
15285
  return epic.replaceAll(/[^A-Za-z0-9._-]/gu, "-");
15318
15286
  }
15319
- //#endregion
15320
- //#region src/epic-closeout/render.ts
15287
+ // src/epic-closeout/render.ts
15321
15288
  const formatValue = (value) => {
15322
15289
  if (value === null) return "_null_";
15323
15290
  if (typeof value === "boolean") return value ? "true" : "false";
@@ -15356,8 +15323,7 @@ function renderCloseoutMarkdown(artifact) {
15356
15323
  ""
15357
15324
  ].join("\n");
15358
15325
  }
15359
- //#endregion
15360
- //#region src/epic-closeout/write-artifact.ts
15326
+ // src/epic-closeout/write-artifact.ts
15361
15327
  /** The closeout artifact directory, relative to repoRoot. */
15362
15328
  const DEFAULT_OUT_DIR = ".factory-memory/closeouts";
15363
15329
  function closeoutArtifactPaths(opts) {
@@ -15382,8 +15348,7 @@ function writeCloseoutArtifact(opts) {
15382
15348
  writeFileSync(markdownPath, renderCloseoutMarkdown(artifact), "utf-8");
15383
15349
  return { markdownPath };
15384
15350
  }
15385
- //#endregion
15386
- //#region src/proof-archive.ts
15351
+ // src/proof-archive.ts
15387
15352
  const FACTORY_MEMORY_DIR = ".factory-memory";
15388
15353
  const PROOF_ARCHIVE_DIR_ENV = "FACTORY_PROOF_ARCHIVE_DIR";
15389
15354
  const DEFAULT_PROOF_ARCHIVE_SUBPATH = path.join(".factory", "proof-archive");
@@ -15441,7 +15406,8 @@ function archiveProofResidue(input) {
15441
15406
  entryCount: 0
15442
15407
  };
15443
15408
  }
15444
- const archiveRoot = resolveProofArchiveRoot(env, input.homeDir ?? homedir());
15409
+ const homeDir = input.homeDir ?? homedir();
15410
+ const archiveRoot = resolveProofArchiveRoot(env, homeDir);
15445
15411
  const repoSlug = `${safeSegment(input.repo.owner)}-${safeSegment(input.repo.name)}`;
15446
15412
  const archiveDir = path.join(archiveRoot, repoSlug, safeSegment(input.agentRunId), archiveTimestamp(now));
15447
15413
  const residueDir = path.join(archiveDir, "factory-memory");
@@ -15481,8 +15447,7 @@ function archiveProofResidue(input) {
15481
15447
  };
15482
15448
  }
15483
15449
  }
15484
- //#endregion
15485
- //#region src/commands/closeout.ts
15450
+ // src/commands/closeout.ts
15486
15451
  const formatUtcDate = (date) => date.toISOString().slice(0, 10);
15487
15452
  const nonEmptyRepoRoot = (value) => {
15488
15453
  if (value.trim() === "") throw new InvalidArgumentError("--repo-root requires a non-empty path");
@@ -15637,8 +15602,7 @@ function createCloseoutCommand(output, dependencies = {}) {
15637
15602
  output.stdout.write(`wrote ${written.markdownPath}\n`);
15638
15603
  }));
15639
15604
  }
15640
- //#endregion
15641
- //#region src/commands/config.ts
15605
+ // src/commands/config.ts
15642
15606
  function resolveConfigPath(deps) {
15643
15607
  return deps.configPath ?? defaultUserConfigPath(deps.env ?? process.env);
15644
15608
  }
@@ -15699,8 +15663,7 @@ function createConfigCommand(output, deps = {}) {
15699
15663
  });
15700
15664
  return config;
15701
15665
  }
15702
- //#endregion
15703
- //#region src/commands/demand-waive.ts
15666
+ // src/commands/demand-waive.ts
15704
15667
  /**
15705
15668
  * The one override verb (#354). It takes a resolved demand key, never a
15706
15669
  * control name, so no control ever needs a skip flag of its own — and it
@@ -15718,8 +15681,7 @@ function createDemandWaiveCommand(_output, action = runDemandWaive) {
15718
15681
  });
15719
15682
  }));
15720
15683
  }
15721
- //#endregion
15722
- //#region src/hq-ingest-preflight.ts
15684
+ // src/hq-ingest-preflight.ts
15723
15685
  /**
15724
15686
  * Whether the HQ ingest credentials resolve (#312).
15725
15687
  *
@@ -15776,7 +15738,8 @@ function hqIngestCredentialCheck({ env, resolve = defaultSecretReferenceProbe, r
15776
15738
  })).filter(({ resolution }) => resolution.status !== "resolved");
15777
15739
  if (unresolved.length > 0) return {
15778
15740
  message: `HQ ingest credentials are absent and did not resolve from the operator's secret store: ${unresolved.map(({ reference, resolution }) => {
15779
- return `${reference} (${RESOLUTION_HINT[resolution.status]})`;
15741
+ const status = resolution.status;
15742
+ return `${reference} (${RESOLUTION_HINT[status]})`;
15780
15743
  }).join("; ")}. Warm the reference (\`op-fast read '<ref>' >/dev/null\`) or correct it in the operator user config. ${REMEDY_SHAPE}`,
15781
15744
  name: HQ_INGEST_PREFLIGHT_CHECK_NAME,
15782
15745
  status: "warning"
@@ -15787,8 +15750,7 @@ function hqIngestCredentialCheck({ env, resolve = defaultSecretReferenceProbe, r
15787
15750
  status: "ok"
15788
15751
  };
15789
15752
  }
15790
- //#endregion
15791
- //#region src/admission-preflight.ts
15753
+ // src/admission-preflight.ts
15792
15754
  const errorMessage$1 = (error) => error instanceof Error ? error.message : String(error);
15793
15755
  /**
15794
15756
  * The base every row below measures against (#1131, #1121). Bound the same
@@ -16133,8 +16095,7 @@ const admissionPreflightChecks = ({ base, candidateBase, cwd, env = process.env,
16133
16095
  })
16134
16096
  ];
16135
16097
  };
16136
- //#endregion
16137
- //#region src/doctor-hq-checks.ts
16098
+ // src/doctor-hq-checks.ts
16138
16099
  const HQ_SPOOL_CHECK_NAME = "hq-spool";
16139
16100
  const FLUSH_REMEDY = "Run `psf hq:flush` to drain them.";
16140
16101
  /** One sentence per orphaned location, with the `--dir` recovery it needs. */
@@ -16358,8 +16319,7 @@ async function hqReadinessDoctorChecks(input, dependencies = {}) {
16358
16319
  reachable
16359
16320
  ];
16360
16321
  }
16361
- //#endregion
16362
- //#region src/hq-last-stored.ts
16322
+ // src/hq-last-stored.ts
16363
16323
  /**
16364
16324
  * The HQ client for `GET /api/ingest/last-stored` (#1339): when HQ last stored
16365
16325
  * an event for a repository. Doctor's `hq-webhook` row asks it when GitHub
@@ -16448,8 +16408,7 @@ async function fetchHqLastStored(input, dependencies = {}) {
16448
16408
  return unknown("unexpected-response", `HQ at ${origin.origin} answered 200 with a reply that is not a last-stored answer.`);
16449
16409
  }
16450
16410
  }
16451
- //#endregion
16452
- //#region src/doctor-hq-last-stored.ts
16411
+ // src/doctor-hq-last-stored.ts
16453
16412
  /**
16454
16413
  * The `hq-last-stored` doctor row (#1342): the silent-spool alarm. A machine
16455
16414
  * whose gates stop reaching HQ looks, from HQ, like a machine that stopped
@@ -16479,7 +16438,6 @@ const PR_VERIFY_PROOF_PATH = path.join(".factory-memory", "pr-verify.json");
16479
16438
  * most, and how far a coarse filesystem clock may put the write before it.
16480
16439
  */
16481
16440
  const PROOF_WRITE_WINDOW_MS = 6e4;
16482
- const MTIME_GRANULARITY_MS = 2e3;
16483
16441
  /**
16484
16442
  * This checkout's pr:verify proof, and whether a pr:verify run here wrote it.
16485
16443
  * Only such a run handed the proof to the HQ sink, at `endedAt`.
@@ -16505,7 +16463,7 @@ const readLocalProof = (input) => {
16505
16463
  }
16506
16464
  const { name, owner } = input.profile.repository;
16507
16465
  const writeLag = writtenAtMs - Date.parse(proof.endedAt);
16508
- return proof.profilePath === input.profilePath && proof.repository === `${owner}/${name}` && writeLag >= -MTIME_GRANULARITY_MS && writeLag <= PROOF_WRITE_WINDOW_MS ? {
16466
+ return proof.profilePath === input.profilePath && proof.repository === `${owner}/${name}` && writeLag >= -2e3 && writeLag <= PROOF_WRITE_WINDOW_MS ? {
16509
16467
  endedAt: proof.endedAt,
16510
16468
  status: "local"
16511
16469
  } : { status: "unattributed" };
@@ -16590,8 +16548,7 @@ async function hqLastStoredDoctorCheck(input, dependencies = {}) {
16590
16548
  status: behind || spool.pending > 0 || spool.unlistable > 0 ? "warning" : "ok"
16591
16549
  };
16592
16550
  }
16593
- //#endregion
16594
- //#region src/doctor-hq-webhook.ts
16551
+ // src/doctor-hq-webhook.ts
16595
16552
  /**
16596
16553
  * The `hq-webhook` doctor row (#1341): whether GitHub's webhook deliveries
16597
16554
  * from this repository reach HQ. paitronage and firedup answered 401 from
@@ -16735,8 +16692,7 @@ async function hqWebhookDoctorCheck(input, dependencies = {}) {
16735
16692
  return unreadableCheck(input, hq, error, dependencies);
16736
16693
  }
16737
16694
  }
16738
- //#endregion
16739
- //#region src/doctor-machine-checks.ts
16695
+ // src/doctor-machine-checks.ts
16740
16696
  /**
16741
16697
  * Machine readiness rows for `doctor` (#1315): facts about this machine, not
16742
16698
  * about the profile, that decide whether factory work can run here.
@@ -16910,8 +16866,7 @@ function machineDoctorChecks(input, dependencies = {}) {
16910
16866
  previewProducerCheck(input, dependencies.isOnPath ?? isExecutableOnPath)
16911
16867
  ];
16912
16868
  }
16913
- //#endregion
16914
- //#region src/doctor.ts
16869
+ // src/doctor.ts
16915
16870
  async function doctorProjectProfile(input = {}) {
16916
16871
  const { path, profile } = loadProjectProfile(input);
16917
16872
  const env = input.env ?? process.env;
@@ -17145,8 +17100,7 @@ const ambientGhAuthCheck = async (cwd, env, check = (root, ghEnv) => {
17145
17100
  };
17146
17101
  }
17147
17102
  };
17148
- //#endregion
17149
- //#region src/commands/doctor.ts
17103
+ // src/commands/doctor.ts
17150
17104
  function createDoctorCommand(output) {
17151
17105
  return markCwdOptionDefault(new Command("doctor").description("Validate a project profile without mutating GitHub or local files").option("--base <ref>", "base ref to assert for --preflight. With a pull request open for this branch its live base is the base and a disagreeing value is reported; without one, this ref (default origin/main) is fetched fresh").option("--cwd <path>", "working directory to validate", collectCwdOption).option("--json", "print the doctor report as JSON").option("--preflight", "also list the pre-checkable admission requirements for the current candidate (read-only; never blocks); each required check states whether this candidate is demanded to satisfy it, resolved by candidate:impact; findings-file shape and wave membership have no read-only pre-check").option("--profile <path>", "path to the project profile JSON file").action(async (options) => {
17152
17106
  const report = await doctorProjectProfile({
@@ -17170,8 +17124,7 @@ function formatHumanReport(report) {
17170
17124
  ""
17171
17125
  ].join("\n");
17172
17126
  }
17173
- //#endregion
17174
- //#region src/epic-structure.ts
17127
+ // src/epic-structure.ts
17175
17128
  /**
17176
17129
  * Producer-side `epic-structure` v1 emitter (epic #132, lane #135).
17177
17130
  *
@@ -17352,7 +17305,8 @@ const validateDagDocument = (input) => {
17352
17305
  const rawNodes = Array.isArray(doc.nodes) ? doc.nodes : void 0;
17353
17306
  if (rawNodes === void 0 || rawNodes.length === 0) diagnostics.push("dag document requires a non-empty `nodes` array");
17354
17307
  const { nodes, slugs } = validateNodes(rawNodes ?? [], diagnostics);
17355
- const edges = validateEdges(Array.isArray(doc.edges) ? doc.edges : [], slugs, diagnostics);
17308
+ const rawEdges = Array.isArray(doc.edges) ? doc.edges : [];
17309
+ const edges = validateEdges(rawEdges, slugs, diagnostics);
17356
17310
  const cycle = findCycle(slugs, edges);
17357
17311
  if (cycle) diagnostics.push(`dependency cycle detected: ${cycle.join(" -> ")}`);
17358
17312
  if (diagnostics.length > 0 || epicId === void 0 || repo === void 0) throw new EpicStructureValidationError(diagnostics);
@@ -17476,8 +17430,7 @@ const publishEpicStructure = async (args) => {
17476
17430
  status: response.status
17477
17431
  };
17478
17432
  };
17479
- //#endregion
17480
- //#region src/commands/epic-publish-structure.ts
17433
+ // src/commands/epic-publish-structure.ts
17481
17434
  const STDIN = "-";
17482
17435
  /** Reads a dag.yml source path, or stdin when `source` is `-`. */
17483
17436
  const readSource = (source) => {
@@ -17505,7 +17458,8 @@ const parseDocument = (raw, source) => {
17505
17458
  * document; the command does not patch authored structure with override flags.
17506
17459
  */
17507
17460
  const buildEvent = (source) => {
17508
- return buildEpicStructureEvent({ document: parseDocument(readSource(source), source) });
17461
+ const document = parseDocument(readSource(source), source);
17462
+ return buildEpicStructureEvent({ document });
17509
17463
  };
17510
17464
  function createEpicPublishStructureCommand(output, deps = {}) {
17511
17465
  const env = deps.env ?? process.env;
@@ -17531,8 +17485,7 @@ function createEpicPublishStructureCommand(output, deps = {}) {
17531
17485
  output.stdout.write(options.json ? `${JSON.stringify(result, null, 2)}\n` : `epic:publish-structure ${result.duplicate ? "no-op (duplicate)" : "accepted"} — eventId ${result.eventId} [HTTP ${result.status}]\n`);
17532
17486
  });
17533
17487
  }
17534
- //#endregion
17535
- //#region src/commands/evidence-emit.ts
17488
+ // src/commands/evidence-emit.ts
17536
17489
  const readStdin = () => {
17537
17490
  let raw = "";
17538
17491
  try {
@@ -17601,8 +17554,7 @@ function createEvidenceEmitCommand(output, action = runEvidenceEmit, readInput =
17601
17554
  if (options.json && "envelope" in result) output.stdout.write(`${JSON.stringify(result.envelope, null, 2)}\n`);
17602
17555
  }));
17603
17556
  }
17604
- //#endregion
17605
- //#region src/hq-flush.ts
17557
+ // src/hq-flush.ts
17606
17558
  /**
17607
17559
  * Spools holding this repository's evidence under an earlier key of its own
17608
17560
  * (#420) — a question the drain itself cannot answer, because it resolves
@@ -17761,8 +17713,7 @@ const hqFlushExitCode = (result) => {
17761
17713
  if (result.unreachableFiles > 0) return HQ_FLUSH_TRANSPORT_EXIT_CODE;
17762
17714
  return result.incomplete ? HQ_FLUSH_INCOMPLETE_EXIT_CODE : 0;
17763
17715
  };
17764
- //#endregion
17765
- //#region src/commands/hq-flush.ts
17716
+ // src/commands/hq-flush.ts
17766
17717
  function createHqFlushCommand(output, action = runHqFlush) {
17767
17718
  return markCwdOptionDefault(new Command("hq:flush").description("Drain this repository's spooled HQ evidence and report every event; exits 1 when transport failed and 2 when the drain did not finish").option("--cwd <path>", "working directory to evaluate", collectCwdOption).option("--dir <path>", "drain an explicit spool directory instead of the default locations; repeatable", (value, previous = []) => [...previous, value]).option("--evict-permanent", "disposition schema-permanent rejections (HTTP 422) in place with `.undeliverable` instead of retaining them").option("--json", "print the flush result as JSON").option("--profile <path>", "path to the project profile JSON file").action(async (options) => {
17768
17719
  const result = await action({
@@ -17777,8 +17728,7 @@ function createHqFlushCommand(output, action = runHqFlush) {
17777
17728
  if (exitCode !== 0) process.exitCode = exitCode;
17778
17729
  }));
17779
17730
  }
17780
- //#endregion
17781
- //#region src/follow-up.ts
17731
+ // src/follow-up.ts
17782
17732
  const FACTORY_CLI_EXECUTABLE = "patronage-factory";
17783
17733
  const FactoryCliInvocationSchema = z.object({
17784
17734
  argvPrefix: z.array(z.string().min(1)).min(1),
@@ -17823,8 +17773,28 @@ const FollowUpActionSchema = z.object({
17823
17773
  argv: z.array(z.string()),
17824
17774
  command: z.string()
17825
17775
  }).strict();
17826
- //#endregion
17827
- //#region src/pr-publish-transaction-error.ts
17776
+ // src/hold-label.ts
17777
+ /** The label that keeps an admitted pull request attended (#1299). */
17778
+ const FACTORY_HOLD_LABEL = "factory:hold";
17779
+ /**
17780
+ * `--hold` on pr:publish and pr:ready (#1513): put `factory:hold` on the pull
17781
+ * request before anything can arm it, so readiness admits it and leaves the
17782
+ * merge to a person. A REST call, so it works where GraphQL is refused, and
17783
+ * on the operator's own credential, like every other write that is not a
17784
+ * pull request create or body edit.
17785
+ */
17786
+ const ghApiArgsForHoldLabel = ({ owner, pr, repo }) => [
17787
+ "api",
17788
+ "--method",
17789
+ "POST",
17790
+ `/repos/${owner}/${repo}/issues/${pr}/labels`,
17791
+ "-f",
17792
+ `labels[]=${FACTORY_HOLD_LABEL}`
17793
+ ];
17794
+ const holdPullRequest = (input) => {
17795
+ runCapture("gh", ghApiArgsForHoldLabel(input), input.cwd);
17796
+ };
17797
+ // src/pr-publish-transaction-error.ts
17828
17798
  /**
17829
17799
  * Publish's admission read is a bounded transaction (#348): undraft, await the
17830
17800
  * newest hosted run for this head, re-evaluate, and return the current
@@ -17837,8 +17807,7 @@ var PrPublishTransactionAbortedError = class extends Error {
17837
17807
  this.name = "PrPublishTransactionAbortedError";
17838
17808
  }
17839
17809
  };
17840
- //#endregion
17841
- //#region src/pr-readiness/pr-body-sections.ts
17810
+ // src/pr-readiness/pr-body-sections.ts
17842
17811
  const MANAGED_SECTION_NAMES = [
17843
17812
  "Verification",
17844
17813
  "Review proof",
@@ -17894,8 +17863,7 @@ const findSectionBounds = (body, heading) => {
17894
17863
  headingStart
17895
17864
  };
17896
17865
  };
17897
- //#endregion
17898
- //#region src/pr-readiness/pr-body-patch.ts
17866
+ // src/pr-readiness/pr-body-patch.ts
17899
17867
  const markerSlug = (heading) => heading.toLowerCase().replaceAll(/[^a-z0-9]+/gu, "-");
17900
17868
  const markerFor = (heading, edge) => `<!-- patronage-factory:${markerSlug(heading)}:${edge} -->`;
17901
17869
  const renderManagedPrBodyBlock = (heading, content) => `${markerFor(heading, "start")}\n${content.trim()}\n${markerFor(heading, "end")}`;
@@ -17940,8 +17908,7 @@ const patchPrBodySections = (body, parts) => {
17940
17908
  }
17941
17909
  return result;
17942
17910
  };
17943
- //#endregion
17944
- //#region src/pr-readiness/pr-body-renderer.ts
17911
+ // src/pr-readiness/pr-body-renderer.ts
17945
17912
  var pr_body_renderer_exports = /* @__PURE__ */ __exportAll({
17946
17913
  PR_BODY_MANAGED_SECTIONS: () => MANAGED_SECTION_NAMES,
17947
17914
  renderPrBodySectionParts: () => renderPrBodySectionParts,
@@ -17981,8 +17948,7 @@ const renderPrBodySections = ({ reviewProof, verifyProof }) => `${renderPrBodySe
17981
17948
  reviewProof,
17982
17949
  verifyProof
17983
17950
  }).map((part) => `## ${part.heading}\n\n${renderManagedPrBodyBlock(part.heading, part.content)}`).join("\n\n")}\n`;
17984
- //#endregion
17985
- //#region src/pr-readiness/status-check-rollup.ts
17951
+ // src/pr-readiness/status-check-rollup.ts
17986
17952
  var status_check_rollup_exports = /* @__PURE__ */ __exportAll({
17987
17953
  HOSTED_VERIFY_CHECK_NAME: () => HOSTED_VERIFY_CHECK_NAME,
17988
17954
  HOSTED_VERIFY_DRAFT_CHECK_NAME: () => HOSTED_VERIFY_DRAFT_CHECK_NAME,
@@ -18002,19 +17968,19 @@ var status_check_rollup_exports = /* @__PURE__ */ __exportAll({
18002
17968
  statusCheckState: () => statusCheckState,
18003
17969
  unsettledNonRequiredCheckNames: () => unsettledNonRequiredCheckNames
18004
17970
  });
18005
- const PASSED_STATES = new Set([
17971
+ const PASSED_STATES = /* @__PURE__ */ new Set([
18006
17972
  "SUCCESS",
18007
17973
  "SKIPPED",
18008
17974
  "NEUTRAL"
18009
17975
  ]);
18010
- const FAILED_STATES = new Set([
17976
+ const FAILED_STATES = /* @__PURE__ */ new Set([
18011
17977
  "FAILURE",
18012
17978
  "ERROR",
18013
17979
  "CANCELLED",
18014
17980
  "TIMED_OUT",
18015
17981
  "ACTION_REQUIRED"
18016
17982
  ]);
18017
- const PENDING_STATES = new Set([
17983
+ const PENDING_STATES = /* @__PURE__ */ new Set([
18018
17984
  "PENDING",
18019
17985
  "QUEUED",
18020
17986
  "IN_PROGRESS",
@@ -18066,7 +18032,7 @@ const HOSTED_VERIFY_DRAFT_CHECK_NAME = `${HOSTED_VERIFY_CHECK_NAME} (draft)`;
18066
18032
  * clear it. The draft run is a superseded generation of the summary job the
18067
18033
  * `verify` row already answers for, so admission does not judge it.
18068
18034
  */
18069
- const isDraftHostedVerifyCheck = (check) => check.name === HOSTED_VERIFY_DRAFT_CHECK_NAME && Boolean(check.workflowName);
18035
+ const isDraftHostedVerifyCheck = (check) => check.name === "verify (draft)" && Boolean(check.workflowName);
18070
18036
  /**
18071
18037
  * Is this a cancelled run of the PR status HUD job (#1056)?
18072
18038
  *
@@ -18136,7 +18102,7 @@ const checkTimestampMs = (check) => {
18136
18102
  const effectiveChecks = (rollup) => {
18137
18103
  const checksByContext = /* @__PURE__ */ new Map();
18138
18104
  const unkeyed = [];
18139
- for (const [index, check] of rollup.entries()) {
18105
+ for (const check of rollup) {
18140
18106
  const context = checkContext(check);
18141
18107
  if (!context) {
18142
18108
  unkeyed.push(check);
@@ -18145,7 +18111,6 @@ const effectiveChecks = (rollup) => {
18145
18111
  const checks = checksByContext.get(context) ?? [];
18146
18112
  checks.push({
18147
18113
  check,
18148
- index,
18149
18114
  timestampMs: checkTimestampMs(check)
18150
18115
  });
18151
18116
  checksByContext.set(context, checks);
@@ -18158,20 +18123,17 @@ const effectiveChecks = (rollup) => {
18158
18123
  currentChecks.push(firstCheck.check);
18159
18124
  continue;
18160
18125
  }
18161
- if (checks.some((check) => check.timestampMs === void 0)) {
18126
+ const orderable = checks.flatMap((check) => check.timestampMs === void 0 ? [] : [{
18127
+ check: check.check,
18128
+ orderMs: check.timestampMs
18129
+ }]);
18130
+ if (orderable.length !== checks.length) {
18162
18131
  currentChecks.push(...checks.map((check) => check.check));
18163
18132
  continue;
18164
18133
  }
18165
- let latest = firstCheck;
18166
- for (const candidate of checks.slice(1)) {
18167
- if (latest.timestampMs === void 0 || candidate.timestampMs === void 0) continue;
18168
- if (candidate.timestampMs > latest.timestampMs) {
18169
- latest = candidate;
18170
- continue;
18171
- }
18172
- if (candidate.timestampMs === latest.timestampMs && candidate.index > latest.index) latest = candidate;
18173
- }
18174
- currentChecks.push(latest.check);
18134
+ const newest = selectNewestGeneration(orderable);
18135
+ if (newest.kind === "newest") currentChecks.push(newest.generation.check);
18136
+ else if (newest.kind === "ambiguous") currentChecks.push(...newest.tied.map((generation) => generation.check));
18175
18137
  }
18176
18138
  return currentChecks;
18177
18139
  };
@@ -18303,8 +18265,7 @@ const admissionCheckSetDescription = (requiredContexts) => {
18303
18265
  if (requiredContexts === void 0) return "every hosted run (the base branch's required checks could not be read)";
18304
18266
  return requiredContexts.length === 0 ? "every hosted run (the base branch requires no checks)" : `the base branch's required checks (${requiredContexts.join(", ")})`;
18305
18267
  };
18306
- //#endregion
18307
- //#region src/arm-auto-merge.ts
18268
+ // src/arm-auto-merge.ts
18308
18269
  /**
18309
18270
  * The read-back, parsed rather than asserted. `state` is read loosely so a
18310
18271
  * merged pull request is still recognised as merged even when the enablement
@@ -18388,8 +18349,7 @@ function armAutoMerge(input, dependencies = {}) {
18388
18349
  outcome: "not-armed"
18389
18350
  };
18390
18351
  }
18391
- //#endregion
18392
- //#region src/merge-freeze.ts
18352
+ // src/merge-freeze.ts
18393
18353
  const MERGE_FREEZE_CHECK_NAME = "patronage-factory/merge-freeze";
18394
18354
  /**
18395
18355
  * The Factory App's slug, as GitHub serves it on the runs the writer posts.
@@ -18867,8 +18827,7 @@ function armingMergeFreezeOutcome(input, authority) {
18867
18827
  notices: []
18868
18828
  };
18869
18829
  }
18870
- //#endregion
18871
- //#region src/pr-readiness/proof-identity.ts
18830
+ // src/pr-readiness/proof-identity.ts
18872
18831
  var proof_identity_exports = /* @__PURE__ */ __exportAll({
18873
18832
  REVIEW_STATUS_VALUES: () => REVIEW_STATUS_VALUES,
18874
18833
  explicitFailureIdentity: () => explicitFailureIdentity,
@@ -18981,13 +18940,9 @@ const readinessRepairSchema = z.object({
18981
18940
  const managedReadinessLedgerSchema = z.object({
18982
18941
  baseSha: shaSchema$1,
18983
18942
  blockingReasons: z.array(z.string()),
18984
- classification: z.enum([
18985
- "docs/process-only",
18986
- "trivial",
18987
- "non-trivial"
18988
- ]),
18943
+ classification: z.enum(DIFF_CLASSIFICATIONS),
18989
18944
  externalChecks: z.array(z.object({
18990
- checkType: z.enum(EVIDENCE_CHECK_TYPES),
18945
+ checkType: evidenceCheckTypeSchema,
18991
18946
  name: z.string().min(1),
18992
18947
  reason: z.string().optional(),
18993
18948
  scope: requiredCheckScopeSchema.optional(),
@@ -19046,8 +19001,7 @@ const managedReadinessLedgerSchema = z.object({
19046
19001
  function validateManagedReadinessLedger(value) {
19047
19002
  return managedReadinessLedgerSchema.parse(value);
19048
19003
  }
19049
- //#endregion
19050
- //#region src/pr-readiness/review-requiredness.ts
19004
+ // src/pr-readiness/review-requiredness.ts
19051
19005
  const proofInputs = (input, epoch) => {
19052
19006
  const current = {
19053
19007
  headSha: input.headSha,
@@ -19121,8 +19075,7 @@ const resolveReviewRequiredness = (input) => {
19121
19075
  gateCapMismatchBlockers: gateCapMismatchBlockers(evaluation)
19122
19076
  };
19123
19077
  };
19124
- //#endregion
19125
- //#region src/pr-readiness/readiness-evaluation.ts
19078
+ // src/pr-readiness/readiness-evaluation.ts
19126
19079
  var readiness_evaluation_exports = /* @__PURE__ */ __exportAll({
19127
19080
  CORRECTNESS_UNTYPED_REVIEW_BLOCKER_REASON: () => CORRECTNESS_UNTYPED_REVIEW_BLOCKER_REASON,
19128
19081
  DRAFT_BLOCKER_REASON: () => DRAFT_BLOCKER_REASON,
@@ -19465,12 +19418,13 @@ const waveRungBlockers = (input) => {
19465
19418
  if (!demanded) return [];
19466
19419
  return demandedRungSatisfactionReasons({
19467
19420
  demandedRung: demanded.review,
19468
- reviewRuns: input.reviewProof?.reviews
19421
+ reviewRuns: currentRoundReviewRuns(input.reviewProof)
19469
19422
  }).map((reason) => ({
19470
19423
  demand: reviewRungDemand(demanded.review),
19471
19424
  reason
19472
19425
  }));
19473
19426
  };
19427
+ const currentRoundReviewRuns = (proof) => proof && [...proof.reviews, ...(proof.ladder?.cycles ?? []).filter((cycle) => cycle.historical !== true && cycle.identity?.patchId === proof.patchId).flatMap((cycle) => cycle.verdicts ?? [])];
19474
19428
  const mergeFreezeBlockers = (input) => (input.mergeFreeze?.blockingReasons ?? []).map((reason) => ({
19475
19429
  demand: DEMAND_KEYS.mergeFreeze,
19476
19430
  reason
@@ -19577,34 +19531,35 @@ const evaluateReadiness = (input) => {
19577
19531
  });
19578
19532
  const { ledgerVerification, prVerifyStatus } = verifyGate;
19579
19533
  const requiredChecks = requiredChecksEvaluation(input);
19534
+ const resolvedBlockers = [
19535
+ ...collectBlockers({
19536
+ correctnessRequired,
19537
+ correctnessStatus,
19538
+ correctnessUntyped,
19539
+ input,
19540
+ prVerifyStatus,
19541
+ securityRequired,
19542
+ securityStatus,
19543
+ securityUntyped,
19544
+ verificationProof: verifyGate.verification.verificationProof
19545
+ }),
19546
+ ...requiredChecks.blockers,
19547
+ ...(catchUpRecognition ? [] : input.policyIdentityRefusals ?? []).map((reason) => ({
19548
+ demand: DEMAND_KEYS.policyIdentity,
19549
+ reason
19550
+ })),
19551
+ ...catchUpRecognition ? [] : reviewRoundLimitBlockers(input),
19552
+ ...gateCapMismatchBlockers.map((blocker) => ({
19553
+ demand: DEMAND_KEYS.reviewLadder,
19554
+ reason: blocker.reason
19555
+ })),
19556
+ ...waveRungBlockers(input),
19557
+ ...armedWithoutBoundaryBlockers(input),
19558
+ ...mergeFreezeBlockers(input),
19559
+ ...exactHeadRunBlockers(input)
19560
+ ];
19580
19561
  const { blockers, waivedDemands } = foldWaivers({
19581
- blockers: [
19582
- ...collectBlockers({
19583
- correctnessRequired,
19584
- correctnessStatus,
19585
- correctnessUntyped,
19586
- input,
19587
- prVerifyStatus,
19588
- securityRequired,
19589
- securityStatus,
19590
- securityUntyped,
19591
- verificationProof: verifyGate.verification.verificationProof
19592
- }),
19593
- ...requiredChecks.blockers,
19594
- ...(catchUpRecognition ? [] : input.policyIdentityRefusals ?? []).map((reason) => ({
19595
- demand: DEMAND_KEYS.policyIdentity,
19596
- reason
19597
- })),
19598
- ...catchUpRecognition ? [] : reviewRoundLimitBlockers(input),
19599
- ...gateCapMismatchBlockers.map((blocker) => ({
19600
- demand: DEMAND_KEYS.reviewLadder,
19601
- reason: blocker.reason
19602
- })),
19603
- ...waveRungBlockers(input),
19604
- ...armedWithoutBoundaryBlockers(input),
19605
- ...mergeFreezeBlockers(input),
19606
- ...exactHeadRunBlockers(input)
19607
- ],
19562
+ blockers: resolvedBlockers,
19608
19563
  waivers: input.waivers ?? []
19609
19564
  });
19610
19565
  const notices = [
@@ -19696,8 +19651,7 @@ const evaluateReadiness = (input) => {
19696
19651
  waivedDemands
19697
19652
  };
19698
19653
  };
19699
- //#endregion
19700
- //#region src/github-pr-status-comment.ts
19654
+ // src/github-pr-status-comment.ts
19701
19655
  const FACTORY_PR_STATUS_COMMENT_MARKER = "<!-- patronage-factory-pr-status-hud -->";
19702
19656
  const OBSERVED_MARKER_PREFIX = "<!-- patronage-factory-pr-status-observed:";
19703
19657
  const OBSERVED_MARKER_SUFFIX = " -->";
@@ -19827,12 +19781,16 @@ const reconcileManagedComments = async (exchange, input, comments, incomingBody)
19827
19781
  const attemptUpsert = async (exchange, input, writtenBody, attempt) => {
19828
19782
  if (attempt >= UPSERT_ATTEMPT_LIMIT) throw new Error("PR status HUD upsert exhausted attempts without a single current comment.");
19829
19783
  const managed = await listManagedComments(exchange, input);
19830
- if (managed.length > 1) return resultFrom("updated", await reconcileManagedComments(exchange, input, managed, writtenBody));
19784
+ if (managed.length > 1) {
19785
+ const keeper = await reconcileManagedComments(exchange, input, managed, writtenBody);
19786
+ return resultFrom("updated", keeper);
19787
+ }
19831
19788
  const [existing] = managed;
19832
19789
  if (existing) try {
19833
19790
  const fresh = await readComment(exchange, input, existing.id);
19834
19791
  if (existingIsCurrentOrNewer(fresh.body, input.observedAt)) return resultFrom("updated", fresh);
19835
- return resultFrom("updated", await patchManaged(exchange, input, existing.id, writtenBody));
19792
+ const updated = await patchManaged(exchange, input, existing.id, writtenBody);
19793
+ return resultFrom("updated", updated);
19836
19794
  } catch (error) {
19837
19795
  if (isRetryableMutation(error)) return attemptUpsert(exchange, input, writtenBody, attempt + 1);
19838
19796
  throw error;
@@ -19858,10 +19816,11 @@ const attemptUpsert = async (exchange, input, writtenBody, attempt) => {
19858
19816
  }
19859
19817
  };
19860
19818
  async function upsertFactoryPrStatusComment(input, dependencies = {}) {
19861
- return attemptUpsert(exchangeFor(dependencies), input, managedBody(input.body, input.observedAt), 0);
19819
+ const exchange = exchangeFor(dependencies);
19820
+ const writtenBody = managedBody(input.body, input.observedAt);
19821
+ return attemptUpsert(exchange, input, writtenBody, 0);
19862
19822
  }
19863
- //#endregion
19864
- //#region src/preview-lifecycle.ts
19823
+ // src/preview-lifecycle.ts
19865
19824
  const previewTargetPlanSchema = z.object({
19866
19825
  basis: z.string(),
19867
19826
  disposition: z.enum(["deploy", "not-required"]),
@@ -19940,8 +19899,7 @@ const planPreviewLifecycle = ({ candidate, profile, proof, vetoedTargets }) => {
19940
19899
  targets
19941
19900
  };
19942
19901
  };
19943
- //#endregion
19944
- //#region src/pr-status-hud.ts
19902
+ // src/pr-status-hud.ts
19945
19903
  const statusLabel = (status) => {
19946
19904
  return `${{
19947
19905
  Failed: "❌",
@@ -20206,6 +20164,19 @@ const newestSnapshot = (name, generations) => {
20206
20164
  };
20207
20165
  const completedSnapshot = (name, sha, runs) => newestSnapshot(name, factoryGenerations(name, sha, runs));
20208
20166
  const MERGE_FREEZE_CHECK = "patronage-factory/merge-freeze";
20167
+ /** A red freeze row for a run readiness refuses to read. */
20168
+ const refusedFreezeSnapshot = (run, sha, refusal) => {
20169
+ const at = run.completed_at ?? run.started_at;
20170
+ if (!at) throw new Error(`${MERGE_FREEZE_CHECK} presentation snapshot has a refused run with no usable timestamp.`);
20171
+ return {
20172
+ completedAt: at,
20173
+ conclusion: run.conclusion ?? run.status,
20174
+ ...run.details_url ? { detailsUrl: run.details_url } : {},
20175
+ headSha: sha,
20176
+ name: MERGE_FREEZE_CHECK,
20177
+ refusal
20178
+ };
20179
+ };
20209
20180
  /**
20210
20181
  * The merge-freeze row shows the generation readiness reads (#1501), chosen by
20211
20182
  * the freeze's own selection rather than a second copy of it. That selection
@@ -20218,11 +20189,12 @@ const MERGE_FREEZE_CHECK = "patronage-factory/merge-freeze";
20218
20189
  * pinned Factory App did not write refuses the whole read, as it does in the
20219
20190
  * reader (#1393): filtering it out could let an older generation win. So does
20220
20191
  * any listed run the reader cannot parse, such as an older one concluded
20221
- * `cancelled` (#1550). A newest payload the selection cannot parse, or one
20222
- * that contradicts its own check run, is unreadable.
20192
+ * `cancelled` (#1550). A newest payload the selection cannot parse, one
20193
+ * that contradicts its own check run, or two newest generations that share a
20194
+ * start (#1557) is unreadable.
20223
20195
  *
20224
20196
  * Otherwise the row is the newest completed snapshot, as for every other check:
20225
- * running, missing and ambiguous generations present as before. Every case
20197
+ * running and missing generations present as before. Every case
20226
20198
  * where the freeze stays fail-closed keeps the row red. The HUD is advisory and
20227
20199
  * never gates.
20228
20200
  */
@@ -20230,19 +20202,12 @@ const mergeFreezeSnapshot = (sha, runs) => {
20230
20202
  const foreign = runs.find((run) => !writtenByFactoryApp(run));
20231
20203
  const unparseable = runs.find((run) => !isReadableMergeFreezeListedRun(run));
20232
20204
  const refusing = foreign ?? unparseable;
20233
- if (refusing) {
20234
- const at = refusing.completed_at ?? refusing.started_at;
20235
- if (!at) throw new Error(`${MERGE_FREEZE_CHECK} presentation snapshot has a refused run with no usable timestamp.`);
20236
- return {
20237
- completedAt: at,
20238
- conclusion: refusing.conclusion ?? refusing.status,
20239
- ...refusing.details_url ? { detailsUrl: refusing.details_url } : {},
20240
- headSha: sha,
20241
- name: MERGE_FREEZE_CHECK,
20242
- refusal: foreign ? `refused: run ${String(foreign.id)} was not written by the Factory App` : `refused: run ${String(refusing.id)} cannot be read`
20243
- };
20244
- }
20205
+ if (refusing) return refusedFreezeSnapshot(refusing, sha, foreign ? `refused: run ${String(foreign.id)} was not written by the Factory App` : `refused: run ${String(refusing.id)} cannot be read`);
20245
20206
  const generations = factoryGenerations(MERGE_FREEZE_CHECK, sha, runs);
20207
+ const newestStart = Math.max(...generations.map((run) => generationOrderMs(run.started_at)));
20208
+ const tied = generations.filter((run) => generationOrderMs(run.started_at) === newestStart).toSorted((a, b) => b.id - a.id);
20209
+ const [highestTied] = tied;
20210
+ if (tied.length > 1 && highestTied) return refusedFreezeSnapshot(highestTied, sha, "unreadable newest payload");
20246
20211
  const newest = newestSnapshot(MERGE_FREEZE_CHECK, generations);
20247
20212
  if (!newest) return newest;
20248
20213
  const unreadable = {
@@ -20261,7 +20226,7 @@ const mergeFreezeSnapshot = (sha, runs) => {
20261
20226
  return unreadable;
20262
20227
  }
20263
20228
  };
20264
- const FAILED_PREVIEW_CONCLUSIONS = new Set([
20229
+ const FAILED_PREVIEW_CONCLUSIONS = /* @__PURE__ */ new Set([
20265
20230
  "action_required",
20266
20231
  "cancelled",
20267
20232
  "failure",
@@ -20439,12 +20404,18 @@ async function refreshFactoryPrStatusHudSafely(input, onNotice = (message) => {
20439
20404
  onNotice(`PR status HUD refresh failed without affecting the gate: ${error instanceof Error ? error.message : String(error)}`);
20440
20405
  }
20441
20406
  }
20442
- //#endregion
20443
- //#region src/pr-ready.ts
20407
+ // src/pr-ready.ts
20444
20408
  const CHECK_CONCLUSION_BY_READINESS_STATUS = {
20445
20409
  blocked: "failure",
20446
20410
  ready: "success"
20447
20411
  };
20412
+ /**
20413
+ * Blocked on nothing but a required check that has not settled: the one
20414
+ * refusal time alone clears. `pr:ready` withholds a follow-up for exactly this
20415
+ * state, and `pr:publish` waits on exactly this state. Both read it from the
20416
+ * recorded verdict, so publish never infers it from a missing follow-up.
20417
+ */
20418
+ const isAwaitingRequiredChecksOnly = (verdict) => verdict.status === "blocked" && verdict.ledger.github.requiredChecks === "pending" && verdict.blockingReasons.length === 1;
20448
20419
  function defaultPrReadyGit() {
20449
20420
  return {
20450
20421
  canResolveCommit,
@@ -20518,35 +20489,6 @@ async function fetchPullRequestWithMergeablePoll({ fetch, sleep = setTimeout$1 }
20518
20489
  function defaultPrReadyGithub() {
20519
20490
  return { fetchPullRequest };
20520
20491
  }
20521
- const prReadyProofSchema = z.object({
20522
- arming: z.object({
20523
- detail: z.string().min(1).optional(),
20524
- headSha: z.string().regex(/^[0-9a-f]{40}$/u),
20525
- outcome: z.enum([
20526
- "armed",
20527
- "merged",
20528
- "not-armed"
20529
- ])
20530
- }).optional(),
20531
- authoringSession: z.string().min(1).optional(),
20532
- blockedReasons: blockedReasonsSchema.optional(),
20533
- blockingReasons: z.array(z.string()),
20534
- command: z.literal("patronage-factory pr:ready"),
20535
- followUp: FollowUpActionSchema.optional(),
20536
- humanBlockingReasons: z.array(z.string()).default([]),
20537
- ledger: managedReadinessLedgerSchema,
20538
- notices: z.array(z.string().min(1)).optional(),
20539
- policyResolution: policyResolutionSchema.optional(),
20540
- profileBlobSha: z.string().regex(/^[0-9a-f]{40}$/u).optional(),
20541
- profilePath: z.string().min(1).optional(),
20542
- repairs: z.array(readinessRepairSchema).default([]),
20543
- repository: z.string().regex(/^[^/\s]+\/[^/\s]+$/u).optional(),
20544
- schemaVersion: z.literal(3),
20545
- status: z.enum(["ready", "blocked"]),
20546
- waivedDemands: z.array(waivedDemandSchema).optional()
20547
- }).superRefine((proof, context) => {
20548
- for (const issue of blockedReasonIssues({ ...proof })) context.addIssue(issue);
20549
- });
20550
20492
  function validatePrReadyProof(value) {
20551
20493
  return prReadyProofSchema.parse(value);
20552
20494
  }
@@ -20678,8 +20620,6 @@ function canResolveCommit(cwd, sha) {
20678
20620
  return false;
20679
20621
  }
20680
20622
  }
20681
- /** The label that keeps an admitted pull request attended (#1299). */
20682
- const FACTORY_HOLD_LABEL = "factory:hold";
20683
20623
  const EPIC_LABEL = "epic";
20684
20624
  const labelNamesSchema = z.object({ nodes: z.array(z.object({ name: z.string() })) }).transform(({ nodes }) => nodes.map((node) => node.name));
20685
20625
  const issueParentSchema = z.object({
@@ -20869,7 +20809,7 @@ const standaloneMembership = async ({ bodyIssues, readFacts, readParent }) => {
20869
20809
  const armingWithheldNotice = ({ facts, liveEnablement, membership }) => {
20870
20810
  if (!facts.ok) return `Native auto-merge was not armed: pr:ready could not read the repository's auto-merge setting or the labels and closing issues of this pull request. ${facts.detail} Re-run pr:ready when GitHub answers.`;
20871
20811
  if (!facts.value.autoMergeAllowed) return "Native auto-merge was not armed: this repository does not allow auto-merge (GitHub's \"Allow auto-merge\" setting is off). The candidate is admitted and stays attended by repository policy. This is not a failure.";
20872
- if (hasLabel(facts.value.labels, FACTORY_HOLD_LABEL)) return liveEnablement ? `This pull request carries the ${FACTORY_HOLD_LABEL} label, so pr:ready did not arm it, but GitHub already has auto-merge on for it. The label does not turn auto-merge off: GitHub still merges it when its required checks are green. To hold it for a person, turn off auto-merge on the pull request.` : `Native auto-merge was not armed: this pull request carries the ${FACTORY_HOLD_LABEL} label, so it is admitted and held for a person. To arm it, remove the label and re-run pr:ready.`;
20812
+ if (hasLabel(facts.value.labels, "factory:hold")) return liveEnablement ? `This pull request carries the ${FACTORY_HOLD_LABEL} label, so pr:ready did not arm it, but GitHub already has auto-merge on for it. The label does not turn auto-merge off: GitHub still merges it when its required checks are green. To hold it for a person, turn off auto-merge on the pull request.` : `Native auto-merge was not armed: this pull request carries the ${FACTORY_HOLD_LABEL} label, so it is admitted and held for a person. To arm it, remove the label and re-run pr:ready.`;
20873
20813
  if (membership?.kind === "member") return `Native auto-merge was not armed: this pull request closes #${membership.issue}, a sub-issue of open epic #${membership.parent}, and the boundary manifest of that epic governs its members. Re-run pr:ready --epic ${membership.parent} so its wave decides.`;
20874
20814
  if (membership?.kind === "unreadable") return `Native auto-merge was not armed: pr:ready could not read the sub-issue parent of ${membership.issue === void 0 ? "the issues this pull request closes" : `#${membership.issue}`}, so it cannot tell whether a boundary manifest governs this pull request. ${membership.detail} Re-run pr:ready when GitHub answers, or with --epic <issue> when an epic governs it.`;
20875
20815
  };
@@ -21064,6 +21004,12 @@ async function runPrReady(args, dependencies = {}) {
21064
21004
  });
21065
21005
  };
21066
21006
  try {
21007
+ if (args.hold) await (dependencies.holdPullRequest ?? holdPullRequest)({
21008
+ cwd,
21009
+ owner: repository.owner,
21010
+ pr: args.pr,
21011
+ repo: repository.name
21012
+ });
21067
21013
  const pr = await withAdmissionReadRetry((extraEnv) => fetchPullRequestWithMergeablePoll({
21068
21014
  fetch: () => github.fetchPullRequest({
21069
21015
  owner: repository.owner,
@@ -21272,7 +21218,7 @@ async function runPrReady(args, dependencies = {}) {
21272
21218
  recorded: verifyProofRead.proof?.authoringSession
21273
21219
  });
21274
21220
  const undraftRepair = evaluation.repairs.find((repair) => repair.code === "undraft-pr");
21275
- const pendingExternalChecksOnly = externalCheckState === "pending" && evaluation.blockingReasons.length === 1;
21221
+ const pendingExternalChecksOnly = isAwaitingRequiredChecksOnly(evaluation);
21276
21222
  const routeOwnedNotYetOnly = evaluation.status === "blocked" && evaluation.humanBlockingReasons.length === 0;
21277
21223
  const boundary = waveDemand?.kind === "demanded" ? waveDemand.demand : void 0;
21278
21224
  const armingConsidered = evaluation.status === "ready" && boundary?.autoMerge !== false;
@@ -21389,8 +21335,7 @@ async function runPrReady(args, dependencies = {}) {
21389
21335
  throw error;
21390
21336
  }
21391
21337
  }
21392
- //#endregion
21393
- //#region src/pr-review-gate-trace.ts
21338
+ // src/pr-review-gate-trace.ts
21394
21339
  const eventTime$1 = () => (/* @__PURE__ */ new Date()).toISOString();
21395
21340
  const buildReviewGateNotRequiredTraceEvent = ({ createdAt = eventTime$1(), identity, proof }) => ReviewGateTraceEventSchema.parse({
21396
21341
  base: proof.base,
@@ -21426,8 +21371,7 @@ const tryAppendReviewGateNotRequiredTraceEvent = ({ identity, proof, repoRoot })
21426
21371
  };
21427
21372
  }
21428
21373
  };
21429
- //#endregion
21430
- //#region src/review-fault-injection.ts
21374
+ // src/review-fault-injection.ts
21431
21375
  const REVIEW_FAULT_ENV = "FACTORY_REVIEW_FAULT";
21432
21376
  const REVIEW_FAULT_POINTS = [
21433
21377
  "after-retain",
@@ -21458,8 +21402,7 @@ const resolveReviewFault = ({ allowFaultInjection = false, env = process.env } =
21458
21402
  const faultAt = (injected, point) => {
21459
21403
  if (injected === point) throw new InjectedReviewFaultError(point);
21460
21404
  };
21461
- //#endregion
21462
- //#region src/review-findings-retention.ts
21405
+ // src/review-findings-retention.ts
21463
21406
  const REVIEW_FINDINGS_RETENTION_DIR = ".factory-memory/review-findings";
21464
21407
  const retainReviewBytes = ({ bytes, cwd, directory: relativeDirectory = REVIEW_FINDINGS_RETENTION_DIR }) => {
21465
21408
  const digest = sha256Hex(bytes);
@@ -21491,8 +21434,7 @@ const retainReviewBytes = ({ bytes, cwd, directory: relativeDirectory = REVIEW_F
21491
21434
  path: target
21492
21435
  };
21493
21436
  };
21494
- //#endregion
21495
- //#region src/issue-body-sections.ts
21437
+ // src/issue-body-sections.ts
21496
21438
  const HEADING_PATTERN = /^#{2,6}\s+(?<title>.+?)\s*$/u;
21497
21439
  const FENCE_PATTERN = /^\s*(?<fence>`{3,}|~{3,})(?<rest>.*)$/u;
21498
21440
  /**
@@ -21537,14 +21479,12 @@ const sectionBody = (body, heading) => {
21537
21479
  if (startIndex === -1) return;
21538
21480
  return lines.slice(startIndex + 1).join("\n").trim();
21539
21481
  };
21540
- //#endregion
21541
- //#region src/review-focus.ts
21482
+ // src/review-focus.ts
21542
21483
  const REVIEW_FOCUS_SECTION = "Review focus";
21543
21484
  const reviewFocusFromIssueBody = (body) => {
21544
21485
  return sectionBody(body, "Review focus") || void 0;
21545
21486
  };
21546
- //#endregion
21547
- //#region src/review-ladder-trace.ts
21487
+ // src/review-ladder-trace.ts
21548
21488
  const eventTime = () => (/* @__PURE__ */ new Date()).toISOString();
21549
21489
  const buildReviewLadderStageTraceEvent = ({ createdAt = eventTime(), event, headSha, identity, patchId }) => {
21550
21490
  const trace = {
@@ -21596,14 +21536,13 @@ const tryAppendReviewLadderStageTraceEvent = (input) => {
21596
21536
  };
21597
21537
  }
21598
21538
  };
21599
- //#endregion
21600
- //#region src/review-lineage.ts
21539
+ // src/review-lineage.ts
21601
21540
  const isReviewLineageContinuous = (prior, current, isAncestor) => prior.base === current.base && (prior.headSha === current.headSha || isAncestor(prior.headSha, current.headSha));
21602
- //#endregion
21603
- //#region src/review-policy-declarations.ts
21541
+ // src/review-policy-declarations.ts
21604
21542
  const identityRepeatDeclarations = (occurrences, cycleIndex) => occurrences.flatMap((occurrence) => {
21605
21543
  if (cycleOfAddress(occurrence.address) !== cycleIndex || occurrence.root === occurrence.address) return [];
21606
- const disposition = IDENTITY_REPEAT_DISPOSITION[projectedGroupDisposition(occurrences.filter((member) => member.root === occurrence.root && cycleOfAddress(member.address) < cycleIndex))];
21544
+ const earlier = occurrences.filter((member) => member.root === occurrence.root && cycleOfAddress(member.address) < cycleIndex);
21545
+ const disposition = IDENTITY_REPEAT_DISPOSITION[projectedGroupDisposition(earlier)];
21607
21546
  return disposition === void 0 ? [] : [{
21608
21547
  authority: "policy",
21609
21548
  disposition,
@@ -21623,8 +21562,7 @@ const severityFloorDeclarations = (occurrences, liveCycleCount) => {
21623
21562
  }] : [];
21624
21563
  });
21625
21564
  };
21626
- //#endregion
21627
- //#region src/review-ladder-proof.ts
21565
+ // src/review-ladder-proof.ts
21628
21566
  const priorLadderStateFor = ({ base, headSha, isAncestor, prior }) => {
21629
21567
  if (!prior?.ladder) return;
21630
21568
  return isReviewLineageContinuous({
@@ -21688,7 +21626,11 @@ function ladderStateForRun({ historical, identity, model, policy, priorLadder, r
21688
21626
  model,
21689
21627
  recording: record,
21690
21628
  stage: "gate",
21691
- ...Object.keys(session).length > 0 ? { session } : {}
21629
+ ...Object.keys(session).length > 0 ? { session } : {},
21630
+ verdicts: runs.map(({ review }) => ({
21631
+ outcome: review.outcome,
21632
+ ...review.rung === void 0 ? {} : { rung: review.rung }
21633
+ }))
21692
21634
  };
21693
21635
  };
21694
21636
  const explicit = recording.declarations;
@@ -21723,8 +21665,7 @@ function emitLadderStageTrace({ cwd, evaluation, headSha, issue, patchId, profil
21723
21665
  if (traceResult.ok) console.error(`review-ladder-stage trace event appended to ${traceResult.filePath}`);
21724
21666
  else console.error(`review-ladder-stage trace event not written: ${traceResult.errorMessage}`);
21725
21667
  }
21726
- //#endregion
21727
- //#region src/review-contract.ts
21668
+ // src/review-contract.ts
21728
21669
  const SESSION_ID_RULE = `"sessionId" is this review session's own id. It must differ from the authoring session id the candidate was verified under (FACTORY_SESSION_ID): pr:review --findings refuses a findings file whose sessionId equals the authoring session.`;
21729
21670
  const authorityRule = (waveRung) => waveRung === void 0 ? `Emit schemaVersion 1 and omit "producer" and "rung": this candidate resolves no boundary-wave review rung. If your dispatch instructions do name a rung, emit schemaVersion 3 with that rung and with "producer" instead. "resolutions" is accepted at every schemaVersion: when the prior-review ledger below shows an open occurrence you verified fixed, add "resolutions": [{"target": "<its address, for example c1f1>", "reference": "<the commit or the verified fix>"}]; silence is not resolution, and an occurrence you do not name stays open.` : `This candidate belongs to a boundary wave that demands the ${waveRung} review rung, so schemaVersion 3 is required. Record "rung": "${waveRung}" exactly as shown, and set "producer" to the engine and model that ran this review (for example "codex-cli/gpt-5.6-sol"). Findings without both fields are recorded without authority, and pr:publish then refuses with "no passing review at that authority". "resolutions" is optional: when the prior-review ledger below shows an open occurrence you verified fixed, name it by its address (for example "c1f1") with a reference; silence is not resolution, and an occurrence you do not name stays open.`;
21730
21671
  /**
@@ -21741,8 +21682,7 @@ ${authorityRule(waveRung)}
21741
21682
  ${SESSION_ID_RULE}
21742
21683
  Use category "correctness", "safety", "coordination", or "maintainability"; set blockingAfterCap true for correctness, safety, or coordination findings. citedSpan must be the exact code text the finding is about, quoted verbatim from the diff (identity is derived from this, not from the title, so quote precisely). prescribedAction must be a concise, standalone statement of the required fix (identity is derived from this text too).`;
21743
21684
  };
21744
- //#endregion
21745
- //#region src/review-prompt.ts
21685
+ // src/review-prompt.ts
21746
21686
  const reviewScope = ({ base, changedFiles: files, headSha, patchId, profile, waveRung }) => `Review scope:
21747
21687
  - Repository: ${profile.repository.owner}/${profile.repository.name}
21748
21688
  - Base ref: ${base}
@@ -21840,13 +21780,14 @@ Open occurrences above are unadjudicated: each still needs a disposition. If you
21840
21780
  });
21841
21781
  const assembleReviewPrompt = ({ base, changedFiles, cwd = process.cwd(), headSha, issueFocus, kind, patchId, priorLedgerEntries, profile, waveRung }, dependencies = {}) => {
21842
21782
  const priorLedger = priorLedgerEntries ?? [];
21783
+ const codingStandards = kind === "correctness" ? readCodingStandardsAtHead({
21784
+ cwd,
21785
+ git: dependencies.git,
21786
+ headSha
21787
+ }) : void 0;
21843
21788
  const optionalSegments = {
21844
21789
  "coding-standards": codingStandardsSegment({
21845
- contents: kind === "correctness" ? readCodingStandardsAtHead({
21846
- cwd,
21847
- git: dependencies.git,
21848
- headSha
21849
- }) : void 0,
21790
+ contents: codingStandards,
21850
21791
  headSha
21851
21792
  }),
21852
21793
  "issue-review-focus": issueFocus ? issueFocusSegment(issueFocus) : void 0,
@@ -21872,8 +21813,7 @@ const assembleReviewPrompt = ({ base, changedFiles, cwd = process.cwd(), headSha
21872
21813
  sections: segments.flatMap((segment) => segment.section ? [segment.section] : [])
21873
21814
  };
21874
21815
  };
21875
- //#endregion
21876
- //#region src/review-recording-id.ts
21816
+ // src/review-recording-id.ts
21877
21817
  const lengthPrefixed = (field) => `${Buffer.byteLength(field, "utf-8")}:${field}`;
21878
21818
  const reviewRecordingId = ({ baseSha, dispositionsBytes, findingsBytes, historical, model, patchId, producer, rung, sessionId }) => sha256Hex([
21879
21819
  patchId,
@@ -21886,8 +21826,7 @@ const reviewRecordingId = ({ baseSha, dispositionsBytes, findingsBytes, historic
21886
21826
  sha256Hex(findingsBytes),
21887
21827
  sha256Hex(dispositionsBytes ?? "")
21888
21828
  ].map((field) => lengthPrefixed(field)).join(""));
21889
- //#endregion
21890
- //#region src/pr-review.ts
21829
+ // src/pr-review.ts
21891
21830
  const DEFAULT_ASSEMBLED_REVIEW_PROMPT_PATH = ".factory-memory/pr-review-prompt.json";
21892
21831
  const MISSING_ASSEMBLED_PROMPT_NOTICE = "pr:review notice: assembled review prompt not found at .factory-memory/pr-review-prompt.json; accepting findings without promptSections.";
21893
21832
  const STALE_ASSEMBLED_PROMPT_NOTICE = "pr:review notice: assembled review prompt patch-id does not match the candidate; accepting findings without promptSections.";
@@ -21926,7 +21865,8 @@ const defaultPrReviewGit = () => ({
21926
21865
  * a real reader will run; off a Cursor VM `gh` is unchanged.
21927
21866
  */
21928
21867
  const assembleIssueReads = async ({ args, dependencies, profile }) => {
21929
- const real = githubWaveDemandReads((args.issue !== void 0 || args.epic !== void 0) && (dependencies.fetchIssueBody === void 0 || args.epic !== void 0 && dependencies.fetchClosingPullRequests === void 0) ? await (dependencies.admission ?? processAdmissionCredential).ghEnv("read-issue", {
21868
+ const needsRealRead = (args.issue !== void 0 || args.epic !== void 0) && (dependencies.fetchIssueBody === void 0 || args.epic !== void 0 && dependencies.fetchClosingPullRequests === void 0);
21869
+ const real = githubWaveDemandReads(needsRealRead ? await (dependencies.admission ?? processAdmissionCredential).ghEnv("read-issue", {
21930
21870
  owner: profile.repository.owner,
21931
21871
  repo: profile.repository.name
21932
21872
  }) : void 0);
@@ -22003,10 +21943,10 @@ const assertReviewCycleInWindow = (cycle, maxCycles) => {
22003
21943
  */
22004
21944
  function enabledKinds(profile, mode, files = [], suppliedFindingsKinds = [], demandedKinds = []) {
22005
21945
  const demanded = new Set(demandedKinds);
22006
- const profileModes = new Set(["correctness", ...(profile.review?.conditional?.length ?? 0) > 0 || demanded.has("security") ? ["security"] : []]);
21946
+ const profileModes = /* @__PURE__ */ new Set(["correctness", ...(profile.review?.conditional?.length ?? 0) > 0 || demanded.has("security") ? ["security"] : []]);
22007
21947
  const configuredKinds = (mode === "all" ? [...profileModes] : [mode]).filter((kind) => profileModes.has(kind));
22008
21948
  if (configuredKinds.length === 0) throw new Error(`No configured review mode matches ${mode}.`);
22009
- const applicableKinds = new Set([...resolveApplicableReviewModes(profile, files), ...demanded]);
21949
+ const applicableKinds = /* @__PURE__ */ new Set([...resolveApplicableReviewModes(profile, files), ...demanded]);
22010
21950
  const suppliedKinds = new Set(suppliedFindingsKinds);
22011
21951
  return configuredKinds.filter((kind) => applicableKinds.has(kind) || suppliedKinds.has(kind));
22012
21952
  }
@@ -22273,7 +22213,8 @@ const assertAssembleMayPrepareReview = ({ args, base, cwd, git, headSha, output,
22273
22213
  };
22274
22214
  };
22275
22215
  const promptSectionsFromAssembledArtifact = ({ cwd, patchId }) => {
22276
- const read = readAssembledReviewPrompt(path.resolve(cwd, DEFAULT_ASSEMBLED_REVIEW_PROMPT_PATH));
22216
+ const artifactPath = path.resolve(cwd, DEFAULT_ASSEMBLED_REVIEW_PROMPT_PATH);
22217
+ const read = readAssembledReviewPrompt(artifactPath);
22277
22218
  if (read.status === "missing") {
22278
22219
  console.error(MISSING_ASSEMBLED_PROMPT_NOTICE);
22279
22220
  return;
@@ -22902,8 +22843,7 @@ async function runPrReview(args, dependencies = {}) {
22902
22843
  assertReviewOutcomes(recorded.proof, ladderPolicy, args.cycle, maxCycles);
22903
22844
  return recorded.proof;
22904
22845
  }
22905
- //#endregion
22906
- //#region src/pull-request-fill.ts
22846
+ // src/pull-request-fill.ts
22907
22847
  const FIELD_SEPARATOR = "";
22908
22848
  const RECORD_SEPARATOR = "";
22909
22849
  /**
@@ -22946,8 +22886,7 @@ const pullRequestFill = (commits) => {
22946
22886
  title: oldest.subject
22947
22887
  };
22948
22888
  };
22949
- //#endregion
22950
- //#region src/pr-publish.ts
22889
+ // src/pr-publish.ts
22951
22890
  const defaultNow = () => /* @__PURE__ */ new Date();
22952
22891
  var PrPublishFollowUpError = class extends Error {
22953
22892
  result;
@@ -23274,6 +23213,7 @@ const producerPostStatus = async (post) => {
23274
23213
  async function ensureVerifyProof({ args, cwd, dependencies, headSha, pr, verifyProofPath }) {
23275
23214
  let declineReason = "no pr:verify proof was available to reuse";
23276
23215
  if (typeof headSha === "string") {
23216
+ const files = (dependencies.git?.changedFiles ?? changedFiles)(cwd, args.base);
23277
23217
  const applicability = resolveVerifyProofApplicability({
23278
23218
  currentVerifyIdentityForBase: () => {
23279
23219
  const selectedStablePatchId = dependencies.git?.stablePatchId ?? runStablePatchId;
@@ -23284,7 +23224,7 @@ async function ensureVerifyProof({ args, cwd, dependencies, headSha, pr, verifyP
23284
23224
  }) };
23285
23225
  },
23286
23226
  explicitProof: false,
23287
- files: (dependencies.git?.changedFiles ?? changedFiles)(cwd, args.base),
23227
+ files,
23288
23228
  headSha,
23289
23229
  proofPath: verifyProofPath
23290
23230
  });
@@ -23763,15 +23703,6 @@ const requirePromotedProofHead = ({ expectedHeadSha, promotion, proof }) => {
23763
23703
  };
23764
23704
  const candidateFollowUpAfterPromotion = (promotion, proof) => promotion.status === "not-requested" ? proof.followUp : void 0;
23765
23705
  /**
23766
- * A proof with no follow-up that is not `ready` means `pr:ready` found the
23767
- * candidate blocked solely on a pending hosted check for the family excluded
23768
- * from readiness's own evaluation (`isFactoryReadyCheck`) — the only
23769
- * condition time alone can resolve. Everything else — a human action, a
23770
- * route-owned repair, a verification rerun — carries a follow-up and is
23771
- * publish's current, actionable answer; this function must not wait on it.
23772
- */
23773
- const isAwaitingHostedRunOnly = (proof) => proof.followUp === void 0 && proof.status !== "ready";
23774
- /**
23775
23706
  * The bounded transaction's await-and-re-evaluate loop (#348). Starting from
23776
23707
  * `proof`, while the candidate is blocked solely on a pending hosted check for
23777
23708
  * its head: abort honestly if that head moves (the candidate this invocation
@@ -23784,7 +23715,7 @@ async function awaitCurrentReadyVerdict({ args, dependencies, proof }) {
23784
23715
  const originalHeadSha = proof.ledger.headSha;
23785
23716
  const sleep = dependencies.sleep ?? setTimeout$1;
23786
23717
  let current = proof;
23787
- for (let attempt = 0; isAwaitingHostedRunOnly(current); attempt += 1) {
23718
+ for (let attempt = 0; isAwaitingRequiredChecksOnly(current); attempt += 1) {
23788
23719
  if (current.ledger.headSha !== originalHeadSha) throw new PrPublishTransactionAbortedError(`awaited the newest hosted check run for ${originalHeadSha}, but the head moved to ${current.ledger.headSha} while waiting. Re-run pr:publish against the current head.`);
23789
23720
  if (attempt >= 12) throw new PrPublishTransactionAbortedError(`timed out after ${12 * PUBLISH_HOSTED_RUN_POLL_MS}ms awaiting the newest hosted check run to leave pending for ${originalHeadSha}. Re-run pr:publish once hosted CI finishes.`);
23790
23721
  await sleep(PUBLISH_HOSTED_RUN_POLL_MS);
@@ -23869,6 +23800,7 @@ async function runPrPublish(args, dependencies = {}) {
23869
23800
  const prNumber = discovered.number;
23870
23801
  const readyArgs = {
23871
23802
  ...args,
23803
+ hold: false,
23872
23804
  pr: prNumber
23873
23805
  };
23874
23806
  const fetchPr = () => withAdmissionReadRetry((extraEnv) => github.fetchPullRequest({
@@ -23959,6 +23891,12 @@ async function runPrPublish(args, dependencies = {}) {
23959
23891
  json: false,
23960
23892
  report: false
23961
23893
  };
23894
+ if (args.hold) await (dependencies.holdPullRequest ?? holdPullRequest)({
23895
+ cwd,
23896
+ owner: profile.repository.owner,
23897
+ pr: prNumber,
23898
+ repo: profile.repository.name
23899
+ });
23962
23900
  const promotionStartedAt = promotionInstant(dependencies);
23963
23901
  const promotion = await promoteDraftBeforeDemandEvaluation({
23964
23902
  cwd,
@@ -24060,16 +23998,16 @@ async function deliverSpooledEvidence({ awaitPending, cwd, flush, profilePath })
24060
23998
  process.stderr.write(`hq:flush advisory drain failed: ${error instanceof Error ? error.message : String(error)}\n`);
24061
23999
  }
24062
24000
  }
24063
- //#endregion
24064
- //#region src/commands/pr-publish.ts
24001
+ // src/commands/pr-publish.ts
24065
24002
  function createPrPublishCommand(_output, action = runPrPublish) {
24066
- return markCwdOptionDefault(new Command("pr:publish").description("Promote a proved draft, then evaluate Candidate demands; never launches review").option("--pr <number>", "pull request number", positiveInteger$1("--pr")).option("--base <ref>", "local base Git ref assertion; origin/<branch> creates against GitHub <branch>").option("--authoring-session <id>", "known authoring session identity for verification retries").option("--cwd <path>", "working directory to evaluate", collectCwdOption).option("--epic <number>", "issue carrying the factory-boundary manifest, which may be the work issue itself; the composed readiness evaluation then applies the wave-demanded review rung (#351, #789)", positiveInteger$1("--epic")).option("--findings <path>", "clean-session findings to validate when no current review proof is available").option("--json", "print the publish result as JSON").option("--output <path>", "write readiness proof JSON to a file").option("--profile <path>", "path to the project profile JSON file").option("--review-proof <path>", "pr:review proof JSON path").option("--verify-proof <path>", "pr:verify proof JSON path").action(async (options) => {
24003
+ return markCwdOptionDefault(new Command("pr:publish").description("Promote a proved draft, then evaluate Candidate demands; never launches review").option("--pr <number>", "pull request number", positiveInteger$1("--pr")).option("--base <ref>", "local base Git ref assertion; origin/<branch> creates against GitHub <branch>").option("--authoring-session <id>", "known authoring session identity for verification retries").option("--cwd <path>", "working directory to evaluate", collectCwdOption).option("--epic <number>", "issue carrying the factory-boundary manifest, which may be the work issue itself; the composed readiness evaluation then applies the wave-demanded review rung (#351, #789)", positiveInteger$1("--epic")).option("--findings <path>", "clean-session findings to validate when no current review proof is available").option("--hold", "label the pull request factory:hold before promotion, so it is admitted and held for a person instead of armed (#1513)").option("--json", "print the publish result as JSON").option("--output <path>", "write readiness proof JSON to a file").option("--profile <path>", "path to the project profile JSON file").option("--review-proof <path>", "pr:review proof JSON path").option("--verify-proof <path>", "pr:verify proof JSON path").action(async (options) => {
24067
24004
  await runPrPublishAction({
24068
24005
  authoringSessionIds: options.authoringSession ? [options.authoringSession] : void 0,
24069
24006
  base: options.base ?? "",
24070
24007
  cwd: resolveCwdOption(options.cwd),
24071
24008
  epic: options.epic,
24072
24009
  findings: options.findings,
24010
+ ...options.hold ? { hold: true } : {},
24073
24011
  json: Boolean(options.json),
24074
24012
  output: options.output,
24075
24013
  pr: options.pr,
@@ -24079,10 +24017,9 @@ function createPrPublishCommand(_output, action = runPrPublish) {
24079
24017
  }, action);
24080
24018
  }));
24081
24019
  }
24082
- //#endregion
24083
- //#region src/commands/pr-ready.ts
24020
+ // src/commands/pr-ready.ts
24084
24021
  function createPrReadyCommand(output, action) {
24085
- return markCwdOptionDefault(new Command("pr:ready").description("Evaluate typed proof and GitHub state for final readiness").requiredOption("--pr <number>", "pull request number", positiveInteger$1("--pr")).option("--base <ref>", "explicit base branch or ref override").option("--authoring-session <id...>", "recorded authoring session id(s) for review-type requiredCheck independence (ADR 0014)").option("--cwd <path>", "working directory to evaluate", collectCwdOption).option("--epic <number>", "issue carrying the factory-boundary manifest, which may be the work issue itself; readiness then evaluates the wave-demanded review rung (#351, #789)", positiveInteger$1("--epic")).option("--json", "print the readiness proof as JSON").option("--output <path>", "write proof JSON to a file").option("--profile <path>", "path to the project profile JSON file").option("--review-proof <path>", "pr:review proof JSON path").option("--verify-proof <path>", "pr:verify proof JSON path").action(withGateTiming({
24022
+ return markCwdOptionDefault(new Command("pr:ready").description("Evaluate typed proof and GitHub state for final readiness").requiredOption("--pr <number>", "pull request number", positiveInteger$1("--pr")).option("--base <ref>", "explicit base branch or ref override").option("--authoring-session <id...>", "recorded authoring session id(s) for review-type requiredCheck independence (ADR 0014)").option("--cwd <path>", "working directory to evaluate", collectCwdOption).option("--epic <number>", "issue carrying the factory-boundary manifest, which may be the work issue itself; readiness then evaluates the wave-demanded review rung (#351, #789)", positiveInteger$1("--epic")).option("--hold", "label the pull request factory:hold first, so an admitted candidate is held for a person instead of armed (#1513)").option("--json", "print the readiness proof as JSON").option("--output <path>", "write proof JSON to a file").option("--profile <path>", "path to the project profile JSON file").option("--review-proof <path>", "pr:review proof JSON path").option("--verify-proof <path>", "pr:verify proof JSON path").action(withGateTiming({
24086
24023
  gate: "pr:ready",
24087
24024
  resolveLedgerRoot: (options) => resolveCwdOption(options.cwd),
24088
24025
  stderr: output.stderr
@@ -24092,6 +24029,7 @@ function createPrReadyCommand(output, action) {
24092
24029
  base: options.base ?? "",
24093
24030
  cwd: resolveCwdOption(options.cwd),
24094
24031
  ...options.epic === void 0 ? {} : { epic: options.epic },
24032
+ ...options.hold ? { hold: true } : {},
24095
24033
  json: Boolean(options.json),
24096
24034
  output: options.output,
24097
24035
  pr: options.pr,
@@ -24107,8 +24045,7 @@ function createPrReadyCommand(output, action) {
24107
24045
  }
24108
24046
  })));
24109
24047
  }
24110
- //#endregion
24111
- //#region src/gate-foreground-guard.ts
24048
+ // src/gate-foreground-guard.ts
24112
24049
  const GATE_BACKGROUND_ENV_MARKERS = ["FACTORY_GATE_BACKGROUND", "FACTORY_GATE_DETACHED"];
24113
24050
  function isTruthyEnvFlag(value) {
24114
24051
  if (value === void 0) return false;
@@ -24131,8 +24068,7 @@ function gateForegroundGuardMessage(gate) {
24131
24068
  function assertForegroundGate({ gate, env = process.env }) {
24132
24069
  if (classifyGateInvocation(env) === "detached") throw new GateForegroundGuardError(gateForegroundGuardMessage(gate));
24133
24070
  }
24134
- //#endregion
24135
- //#region src/commands/pr-review.ts
24071
+ // src/commands/pr-review.ts
24136
24072
  function createPrReviewCommand(output, action) {
24137
24073
  return markCwdOptionDefault(new Command("pr:review").description("Assemble a factory-owned review prompt, or validate clean-session findings and write typed review proof").option("--base <ref>", "base ref to assert. With a pull request open for this branch its live base is the base and a disagreeing value is refused; without one, this ref (default origin/main) is fetched fresh and its SHA recorded").option("--cwd <path>", "working directory to review", collectCwdOption).option("--cycle <number>", "review cycle number", positiveInteger$1("--cycle"), 1).option("--mode <mode>", "correctness, security, or all", "all").option("--assemble", "write the factory-owned review prompt for a clean session; do not validate findings").option("--epic <number>", "issue carrying the factory-boundary manifest, which may be the work issue itself; --assemble then asks the reviewer for the findings schema the wave-demanded review rung accepts (#1001), and refuses while no pull request is open for the branch (#1245)", positiveInteger$1("--epic")).option("--findings <path>", "typed clean-session findings JSON file").option("--historical", "record findings that read an earlier commit on this branch: the cycle joins the ladder as prior history and renders no verdict of its own, so it never admits. It leaves the candidate's recorded verdict untouched. This recording may carry --dispositions for the findings it flags; otherwise declare them on the next cycle once they are persisted ledger entries").option("--dispositions <path>", "JSON file of ladder disposition declarations (waived / follow-up-filed / fixed-in-thread) for previously flagged findings, or for the findings a --historical recording itself flags").option("--issue <number>", "issue number recorded on the review ladder trace; --assemble also loads Review focus from this issue", positiveInteger$1("--issue")).option("--output <path>", "write proof JSON to a file").option("--allow-fault-injection", "test-only: honour FACTORY_REVIEW_FAULT (after-retain | proof-rename | after-proof-write) to interrupt the recording at that point and demonstrate that a retry resolves to already-recorded or a clean re-record (#1131)").option("--profile <path>", "path to the project profile JSON file").option("--verify-proof <path>", "pr:verify proof JSON path").action(withGateTiming({
24138
24074
  gate: "pr:review",
@@ -24165,8 +24101,7 @@ function createPrReviewCommand(output, action) {
24165
24101
  await (action ? action(args) : runPrReview(args, { publishCheckRun: createFactoryCheckPublisher(output) }));
24166
24102
  })));
24167
24103
  }
24168
- //#endregion
24169
- //#region src/commands/pr-verify.ts
24104
+ // src/commands/pr-verify.ts
24170
24105
  function createPrVerifyCommand(output, action = runPrVerifyWithAdmission) {
24171
24106
  return markCwdOptionDefault(new Command("pr:verify").description("Run project-profile verification commands and write typed proof").option("--base <ref>", "base ref to assert. With a pull request open for this branch its live base is the base and a disagreeing value is refused; without one, this ref (default origin/main) is fetched fresh and its SHA recorded").option("--cwd <path>", "working directory to verify", collectCwdOption).option("--docs-only", "run the docs/process verification gate").option("--full", "run the full verification gate").option("--authoring-session <id>", "explicit authoring session identity (required for review evidence)").option("--reuse-accepted", "reuse an exact-candidate App proof with matching current verification coverage; otherwise verify normally").option("--json", "print the proof as JSON after verification").option("--output <path>", "write proof JSON to a file").option("--profile <path>", "path to the project profile JSON file").option("--no-status", "skip posting the patronage-factory/pr-verify commit status").action(withGateTiming({
24172
24107
  gate: "pr:verify",
@@ -24199,6 +24134,15 @@ const DEPLOYMENT_RECEIPT_TASK = "patronage-factory/deployment";
24199
24134
  const PREVIEW_DEPLOYMENT_RECEIPT_TASK = "patronage-factory/preview-deployment";
24200
24135
  /** The `performed_via_github_app.id` of GitHub Actions itself. */
24201
24136
  const GITHUB_ACTIONS_APP_ID = 15368;
24137
+ /**
24138
+ * The `github-actions[bot]` account. A deployment created with a workflow's
24139
+ * `GITHUB_TOKEN` names it as creator and leaves `performed_via_github_app`
24140
+ * null (#1505).
24141
+ */
24142
+ const GITHUB_ACTIONS_BOT = {
24143
+ id: 41898282,
24144
+ login: "github-actions[bot]"
24145
+ };
24202
24146
  const RECEIPT_PAGE_SIZE = 100;
24203
24147
  var DeploymentReceiptTransportError = class extends Error {
24204
24148
  code;
@@ -24268,6 +24212,11 @@ const receiptPayloadSchema = z.object({
24268
24212
  });
24269
24213
  const deploymentRecordSchema = z.object({
24270
24214
  created_at: z.string(),
24215
+ creator: z.object({
24216
+ id: z.number().int(),
24217
+ login: z.string(),
24218
+ type: z.string()
24219
+ }).nullable().optional(),
24271
24220
  environment: z.string(),
24272
24221
  id: z.number().int(),
24273
24222
  /** Fixed at creation. `environment` can be rewritten by a later status write. */
@@ -24278,6 +24227,16 @@ const deploymentRecordSchema = z.object({
24278
24227
  sha: z.string(),
24279
24228
  task: z.string()
24280
24229
  });
24230
+ /**
24231
+ * GitHub Actions wrote this deployment: either GitHub names the Actions app,
24232
+ * or it names no app and the creator is the `github-actions[bot]` account a
24233
+ * workflow's `GITHUB_TOKEN` acts as. Any other app is refused.
24234
+ */
24235
+ const performedByGitHubActions = (deployment) => {
24236
+ const app = deployment.performed_via_github_app;
24237
+ if (app) return app.id === GITHUB_ACTIONS_APP_ID;
24238
+ return deployment.creator?.id === GITHUB_ACTIONS_BOT.id && deployment.creator.login === GITHUB_ACTIONS_BOT.login && deployment.creator.type === "Bot";
24239
+ };
24281
24240
  const workflowRunJobSchema = z.object({
24282
24241
  conclusion: z.string().nullable(),
24283
24242
  head_sha: z.string(),
@@ -24332,7 +24291,7 @@ const previewPayloadRefusal = (args, deployment, receipt) => {
24332
24291
  };
24333
24292
  const bindReceiptPayload = (args, deployment) => {
24334
24293
  const label = `deployment ${deployment.id}`;
24335
- if (deployment.performed_via_github_app?.id !== GITHUB_ACTIONS_APP_ID) return { reason: `${label} was not performed by GitHub Actions` };
24294
+ if (!performedByGitHubActions(deployment)) return { reason: `${label} was not performed by GitHub Actions` };
24336
24295
  if (deployment.task !== (args.preview ? PREVIEW_DEPLOYMENT_RECEIPT_TASK : "patronage-factory/deployment")) return { reason: `${label} has a foreign task, not a factory receipt` };
24337
24296
  const payload = receiptPayloadSchema.safeParse(deployment.payload);
24338
24297
  if (!payload.success) return { reason: `${label} payload is not a schema-version-1 factory receipt` };
@@ -24489,7 +24448,7 @@ const assertPublicationScope = (args) => {
24489
24448
  };
24490
24449
  const assertOwnPreviewIntent = (args, payload, environment, deploymentId) => {
24491
24450
  const own = z.array(deploymentRecordSchema).parse(args.transport.listDeployments()).find((record) => record.id === deploymentId);
24492
- if (!own || own.original_environment !== environment || own.sha !== args.sourceSha || own.production_environment !== false || own.task !== PREVIEW_DEPLOYMENT_RECEIPT_TASK || own.performed_via_github_app?.id !== GITHUB_ACTIONS_APP_ID || JSON.stringify(receiptPayloadSchema.parse(own.payload)) !== JSON.stringify(receiptPayloadSchema.parse(payload))) throw new Error("Preview completion must name this run's own deployment intent.");
24451
+ if (!own || own.original_environment !== environment || own.sha !== args.sourceSha || own.production_environment !== false || own.task !== PREVIEW_DEPLOYMENT_RECEIPT_TASK || !performedByGitHubActions(own) || JSON.stringify(receiptPayloadSchema.parse(own.payload)) !== JSON.stringify(receiptPayloadSchema.parse(payload))) throw new Error("Preview completion must name this run's own deployment intent.");
24493
24452
  };
24494
24453
  const publishDeploymentReceipt = (args) => {
24495
24454
  const environment = deploymentReceiptEnvironment(args.target, args.preview);
@@ -24615,8 +24574,7 @@ const ghDeploymentReceiptTransport = (cwd, repository, run = defaultGhRunner) =>
24615
24574
  listWorkflowRunJobs: (runId, attempt) => api(`${base}/actions/runs/${runId}/attempts/${attempt}/jobs?per_page=${RECEIPT_PAGE_SIZE}`)
24616
24575
  };
24617
24576
  };
24618
- //#endregion
24619
- //#region src/production-impact.ts
24577
+ // src/production-impact.ts
24620
24578
  /**
24621
24579
  * Production deployment demand (#1075, epic #1063).
24622
24580
  *
@@ -24722,12 +24680,13 @@ const resolveReceiptSource = (cwd, receipts) => {
24722
24680
  };
24723
24681
  const outputState = (state) => state === "superseded" ? "withdrawn" : state;
24724
24682
  const writeGithubOutputs = (outputPath, decision) => {
24725
- appendFileSync(outputPath, `${[
24683
+ const lines = [
24726
24684
  `decision=${decision.decision}`,
24727
24685
  `basis=${JSON.stringify(decision.basis)}`,
24728
24686
  `unsubscribed_paths=${JSON.stringify(decision.unsubscribedPaths)}`,
24729
24687
  ...decision.targets.map((target) => `${productionImpactTargetOutput(target.name)}=${outputState(target.state)}`)
24730
- ].join("\n")}\n`, "utf-8");
24688
+ ];
24689
+ appendFileSync(outputPath, `${lines.join("\n")}\n`, "utf-8");
24731
24690
  };
24732
24691
  /** Classify the delta from one baseline to the candidate, once per distinct baseline. */
24733
24692
  const classifyDelta = ({ baseline, candidate, cwd, profile, profilePath }) => {
@@ -24945,8 +24904,7 @@ const runProductionReceipt = (args) => {
24945
24904
  };
24946
24905
  };
24947
24906
  const productionReceiptSummaryLines = (result) => [`Deployment receipt: ${result.receipt.state} for ${result.receipt.payload.target}${result.receipt.payload.stage ? ` stage ${result.receipt.payload.stage}` : ""} at ${result.receipt.payload.sourceSha} (deployment ${result.receipt.deploymentId}, run ${result.receipt.payload.workflow.runId}).`, ...result.staleCandidate ? [`Stale candidate: ${result.receipt.payload.sourceSha} is an ancestor of the previously trusted baseline ${result.staleCandidate.sha} (run ${result.staleCandidate.runId}); production now runs the older revision and needs reconciliation.`] : []];
24948
- //#endregion
24949
- //#region src/commands/production-impact.ts
24907
+ // src/commands/production-impact.ts
24950
24908
  /**
24951
24909
  * `production:impact` has two modes on one command. Without
24952
24910
  * `--publish-receipt` it resolves deployment demand from receipts; with it,
@@ -24984,8 +24942,7 @@ function createProductionImpactCommand(output, receipts) {
24984
24942
  output.stdout.write(options.json ? `${JSON.stringify(decision, null, 2)}\n` : `${productionImpactSummaryLines(decision).join("\n")}\n`);
24985
24943
  }));
24986
24944
  }
24987
- //#endregion
24988
- //#region src/hq-spool-exit-report.ts
24945
+ // src/hq-spool-exit-report.ts
24989
24946
  /** A recorded reason is file content: keep the line one line, and short. */
24990
24947
  const MAX_REASON_LENGTH = 120;
24991
24948
  const printableReason = (reason) => {
@@ -25029,8 +24986,7 @@ async function reportSpooledHqEvents(input) {
25029
24986
  writeAdvisoryLine(`${describeSpooledHqEvents(counted)}\n`);
25030
24987
  } catch {}
25031
24988
  }
25032
- //#endregion
25033
- //#region src/pr-status.ts
24989
+ // src/pr-status.ts
25034
24990
  const oid = z.string().regex(/^[0-9a-f]{40}$/u);
25035
24991
  const instant = z.iso.datetime({ offset: true });
25036
24992
  const pullRequestSchema = z.object({
@@ -25154,8 +25110,7 @@ async function readPrStatus(pr, handoffSha, handoffAt) {
25154
25110
  if (report.progressSignals.length > 0) report.verdict = "progressed";
25155
25111
  return report;
25156
25112
  }
25157
- //#endregion
25158
- //#region src/pr-status-command.ts
25113
+ // src/pr-status-command.ts
25159
25114
  function createPrStatusCommand(output) {
25160
25115
  return new Command("pr:status").description("Read lane progress since handoff once: merged/closed win; progressed means head moved or a Factory run, ready-for-review transition, or auto-merge enablement strictly newer than --handoff-at. No writes.").requiredOption("--pr <number>", "pull request number in the checkout's origin repository", positiveInteger$1("--pr")).requiredOption("--since <handoff-sha>", "handoff head SHA, full or unambiguous abbreviation (at least 7 hex characters)").requiredOption("--handoff-at <iso-8601>", "handoff instant with an explicit timezone/offset").option("--json", "print one JSON object").action(async (options) => {
25161
25116
  try {
@@ -25173,8 +25128,7 @@ function createPrStatusCommand(output) {
25173
25128
  }
25174
25129
  });
25175
25130
  }
25176
- //#endregion
25177
- //#region src/pr-status-hud-command.ts
25131
+ // src/pr-status-hud-command.ts
25178
25132
  const shaSchema = z.string().regex(/^[0-9a-f]{40}$/u);
25179
25133
  const boundPlanSchema = z.object({
25180
25134
  headSha: shaSchema,
@@ -25238,9 +25192,8 @@ function createPrStatusHudCommand(output, action = runPrStatusHud, env = process
25238
25192
  output.stdout.write(`PR status HUD ${result.action}: ${result.url} (comment ${result.commentId})\n`);
25239
25193
  }));
25240
25194
  }
25241
- //#endregion
25242
- //#region src/preview-cleanup-command.ts
25243
- const ACTIONS = new Set([
25195
+ // src/preview-cleanup-command.ts
25196
+ const ACTIONS = /* @__PURE__ */ new Set([
25244
25197
  "audit",
25245
25198
  "discover",
25246
25199
  "record",
@@ -25387,8 +25340,7 @@ function createPreviewCleanupCommand(output, deps = {}) {
25387
25340
  output.stdout.write(await runPreviewCleanup(options, deps));
25388
25341
  });
25389
25342
  }
25390
- //#endregion
25391
- //#region src/preview-reaper.ts
25343
+ // src/preview-reaper.ts
25392
25344
  const previewBindingReferenceSchema = z.object({
25393
25345
  binding: z.string().min(1),
25394
25346
  consumer: z.string().min(1),
@@ -25613,7 +25565,8 @@ const listWorkerBindings = async (cfRoot, workers, headers, fetchImpl) => {
25613
25565
  const values = [];
25614
25566
  const batchSize = 20;
25615
25567
  for (let offset = 0; offset < workers.length; offset += batchSize) values.push(...await Promise.all(workers.slice(offset, offset + batchSize).map(async (worker) => {
25616
- const body = await jsonResponse(await fetchImpl(`${cfRoot}/workers/scripts/${encodeURIComponent(worker.name)}/settings`, { headers }), `Read Worker settings for ${worker.name}`);
25568
+ const response = await fetchImpl(`${cfRoot}/workers/scripts/${encodeURIComponent(worker.name)}/settings`, { headers });
25569
+ const body = await jsonResponse(response, `Read Worker settings for ${worker.name}`);
25617
25570
  const settings = workerSettingsSchema.safeParse(body.result);
25618
25571
  if (!settings.success) throw new Error(`Worker ${worker.name} settings inventory is incomplete; refusing to classify a partial binding graph.`);
25619
25572
  return [worker.name, settings.data.bindings ?? []];
@@ -25802,7 +25755,8 @@ async function createPreviewReapPlan(args, dependencies = {}) {
25802
25755
  ].filter((value) => Boolean(value)).toSorted().at(-1) ?? null;
25803
25756
  const pullRequest = stage.owner.kind === "pull-request" ? pullRequests.get(`${stage.owner.repository}#${stage.owner.pr}`) : void 0;
25804
25757
  if (stage.owner.kind === "pull-request" && !pullRequest) throw new Error(`Missing pull request result for ${stage.id}`);
25805
- const classified = classifyStage(pullRequest, newestResourceAt, cutoff, stage.owner.kind === "pull-request" || stage.workers.length > 0 && stage.workers.every((resource) => Boolean(resource.modifiedAt)) && stage.d1.every((resource) => Boolean(resource.createdAt)) && stage.r2.every((resource) => Boolean(resource.createdAt)));
25758
+ const runFreshnessComplete = stage.owner.kind === "pull-request" || stage.workers.length > 0 && stage.workers.every((resource) => Boolean(resource.modifiedAt)) && stage.d1.every((resource) => Boolean(resource.createdAt)) && stage.r2.every((resource) => Boolean(resource.createdAt));
25759
+ const classified = classifyStage(pullRequest, newestResourceAt, cutoff, runFreshnessComplete);
25806
25760
  const disposition = classified === "reclaim" && [
25807
25761
  ...stage.workers,
25808
25762
  ...stage.d1,
@@ -25845,11 +25799,12 @@ const assertPreviewReapPlanIntegrity = (plan) => {
25845
25799
  if (previewReapPlanId(payload) !== planId) throw new Error("Preview reaper plan integrity check failed; regenerate and review the dry-run plan.");
25846
25800
  };
25847
25801
  const githubPullRequest = async (claim, githubToken, fetchImpl) => {
25848
- return jsonResponse(await fetchImpl(`https://api.github.com/repos/${claim.repository}/pulls/${claim.pr}`, { headers: {
25802
+ const response = await fetchImpl(`https://api.github.com/repos/${claim.repository}/pulls/${claim.pr}`, { headers: {
25849
25803
  Accept: "application/vnd.github+json",
25850
25804
  Authorization: `Bearer ${githubToken}`,
25851
25805
  "X-GitHub-Api-Version": "2022-11-28"
25852
- } }), `Re-check ${claim.repository}#${claim.pr}`);
25806
+ } });
25807
+ return jsonResponse(response, `Re-check ${claim.repository}#${claim.pr}`);
25853
25808
  };
25854
25809
  const deleteCloudflareResource = async (url, headers, context, fetchImpl) => {
25855
25810
  const response = await fetchImpl(url, {
@@ -25869,10 +25824,11 @@ const listR2Objects = async (root, bucket, headers, fetchImpl) => {
25869
25824
  const url = new URL(`${root}/r2/buckets/${encodeURIComponent(bucket.name)}/objects`);
25870
25825
  url.searchParams.set("per_page", "1000");
25871
25826
  if (cursor) url.searchParams.set("cursor", cursor);
25872
- const page = await jsonResponse(await fetchImpl(url, { headers: {
25827
+ const response = await fetchImpl(url, { headers: {
25873
25828
  ...headers,
25874
25829
  ...bucket.jurisdiction ? { "cf-r2-jurisdiction": bucket.jurisdiction } : {}
25875
- } }), `List objects in R2 bucket ${bucket.name}`);
25830
+ } });
25831
+ const page = await jsonResponse(response, `List objects in R2 bucket ${bucket.name}`);
25876
25832
  for (const object of page.result) {
25877
25833
  if (!object.key) throw new Error(`R2 bucket ${bucket.name} returned an object without a key; refusing to delete the bucket.`);
25878
25834
  values.push(object.key);
@@ -25906,7 +25862,10 @@ async function applyPreviewReapPlan(plan, args, dependencies = {}) {
25906
25862
  if (target.claim.kind === "pull-request") {
25907
25863
  const pullRequest = await githubPullRequest(target.claim, args.githubToken, fetchImpl);
25908
25864
  if (pullRequest.state !== "closed" || !pullRequest.closed_at || new Date(pullRequest.closed_at) > new Date(plan.cutoff)) throw new Error(`${stageClaimLabel(target)} (${target.id}) is no longer reclaimable immediately before apply; refusing deletion.`);
25909
- } else if (comparableWorkers((await listWorkers(`${cfRoot}/workers/scripts?per_page=1000`, cfHeaders, fetchImpl)).filter((worker) => workerIdentity(worker.name)?.id === target.id)) !== comparableWorkers(target.resources.workers)) throw new Error(`${target.id} Worker freshness changed immediately before apply; refusing deletion.`);
25865
+ } else {
25866
+ const liveWorkers = (await listWorkers(`${cfRoot}/workers/scripts?per_page=1000`, cfHeaders, fetchImpl)).filter((worker) => workerIdentity(worker.name)?.id === target.id);
25867
+ if (comparableWorkers(liveWorkers) !== comparableWorkers(target.resources.workers)) throw new Error(`${target.id} Worker freshness changed immediately before apply; refusing deletion.`);
25868
+ }
25910
25869
  const doOwners = new Set(target.resources.durableObjects.map((namespace) => namespace.script));
25911
25870
  for (const worker of target.resources.workers) {
25912
25871
  const force = doOwners.has(worker.name) ? "?force=true" : "";
@@ -25931,8 +25890,7 @@ async function applyPreviewReapPlan(plan, args, dependencies = {}) {
25931
25890
  if (residue) throw new Error(`${residue.id} still has preview resources after apply; post-apply verification failed.`);
25932
25891
  return { appliedStages };
25933
25892
  }
25934
- //#endregion
25935
- //#region src/preview-reap-command.ts
25893
+ // src/preview-reap-command.ts
25936
25894
  const positiveNumber = (value) => {
25937
25895
  const parsed = Number(value);
25938
25896
  if (!Number.isFinite(parsed) || parsed <= 0) throw new InvalidArgumentError("must be a positive number");
@@ -25991,8 +25949,7 @@ function createPreviewReapCommand(output, deps = {}) {
25991
25949
  if (options.githubSummary) appendFileSync(options.githubSummary, rendered);
25992
25950
  });
25993
25951
  }
25994
- //#endregion
25995
- //#region src/preview-receipt-command.ts
25952
+ // src/preview-receipt-command.ts
25996
25953
  const policySchema = z.object({
25997
25954
  cleanupWorkflowPaths: z.array(z.string().regex(/^\.github\/workflows\/[^/]+\.ya?ml$/u)),
25998
25955
  publishers: z.array(z.object({
@@ -26123,8 +26080,7 @@ const createPreviewReceiptCommand = (output) => markCwdOptionDefault(new Command
26123
26080
  ]).parse(options.action);
26124
26081
  output.stdout.write(`${JSON.stringify(runPreviewReceipt(options), null, 2)}\n`);
26125
26082
  }));
26126
- //#endregion
26127
- //#region src/worktree-scratch-files.ts
26083
+ // src/worktree-scratch-files.ts
26128
26084
  var worktree_scratch_files_exports = /* @__PURE__ */ __exportAll({
26129
26085
  checkWorktreeScratchFiles: () => checkWorktreeScratchFiles,
26130
26086
  formatScratchFileCheckSummary: () => formatScratchFileCheckSummary,
@@ -26174,8 +26130,7 @@ function formatScratchFileCheckSummary(check) {
26174
26130
  if (check.status === "clean") return "Scratch files: none";
26175
26131
  return "Scratch files: not checked (no readable worktree path)";
26176
26132
  }
26177
- //#endregion
26178
- //#region src/index.ts
26133
+ // src/index.ts
26179
26134
  function createProgram(options = {}) {
26180
26135
  const factoryCliInvocation = options.factoryCliInvocation ? FactoryCliInvocationSchema.parse(options.factoryCliInvocation) : defaultFactoryCliInvocation(factoryCliEntry());
26181
26136
  const output = options.output ?? {
@@ -26219,7 +26174,7 @@ function createProgram(options = {}) {
26219
26174
  * it found it. `hq:flush` is the explicit drain and has just run.
26220
26175
  * `app-token:exec` only runs another command and records no evidence.
26221
26176
  */
26222
- const EXIT_DRAIN_EXEMPT_COMMANDS = new Set([
26177
+ const EXIT_DRAIN_EXEMPT_COMMANDS = /* @__PURE__ */ new Set([
26223
26178
  "app-token:exec",
26224
26179
  "config",
26225
26180
  "doctor",
@@ -26231,7 +26186,7 @@ const EXIT_DRAIN_EXEMPT_COMMANDS = new Set([
26231
26186
  * `pr:publish` is not one: it already runs its own `hq:flush` drain and
26232
26187
  * prints what stays spooled.
26233
26188
  */
26234
- const EXIT_SPOOL_REPORT_COMMANDS = new Set(["pr:ready"]);
26189
+ const EXIT_SPOOL_REPORT_COMMANDS = /* @__PURE__ */ new Set(["pr:ready"]);
26235
26190
  /**
26236
26191
  * Which checkout's spool the command drains on exit: its `--cwd` (closeout's
26237
26192
  * `--repo-root`), else the process directory, with its `--profile` if given.
@@ -26284,5 +26239,4 @@ async function run(argv = process.argv, cliEntry = factoryCliEntry()) {
26284
26239
  }
26285
26240
  }
26286
26241
  }
26287
- //#endregion
26288
26242
  export { DEFAULT_DEMAND_WAIVER_PATH, DEFAULT_FACTORY_REPOSITORY, DEFAULT_ROOT_SHARED_GLOBS, DemandWaiveRefusalError, EMPTY_TREE_OBJECT_HASH, EPIC_STRUCTURE_NODE_STATUSES, EPIC_STRUCTURE_SCHEMA_VERSION, EpicStructureValidationError, FACTORY_BASE_REF_ENV, FACTORY_CHANGED_FILES_ENV, FACTORY_CHANGED_FILES_FILE_ENV, FACTORY_LOCKFILE_BASE_REF_ENV, FACTORY_LOCKFILE_IMPORTERS_ENV, FactoryCliInvocationSchema, FollowUpActionSchema, MERGE_FREEZE_APP_SLUG, MERGE_FREEZE_CHECK_NAME, PrPublishFollowUpError, REVIEW_FOCUS_SECTION, WorkerCheckoutGuardError, appendWithTraceSinks, applyDemandWaiver, assembleReviewPrompt, assertFactoryPrStatusIdentity, assertWorkerCheckoutAllowed, authorizeDemandWaiver, batteryScopeSummaryLines, boundary_manifest_exports as boundaryManifest, boundary_review_proof_exports as boundaryReviewProof, buildEpicStructureEvent, buildEpicStructurePayload, buildEvidenceEnvelope, buildReviewGateNotRequiredTraceEvent, comment_provenance_exports as commentProvenance, createGitHubCheckRunMergeFreezeStore, createLocalJsonlTraceSink, createProgram, createVerificationRunContext, doctorProjectProfile, epicStructureEventId, evidenceEnvelopeFilename, followUpFromArgv, impactStampScopeDecision, isProductionHqUrl, loadProjectProfile, normalizeIssueComments, planFactoryPrStatusHud, planPreviewLifecycle, planPublishFollowUp, planVerificationBattery, readiness_evaluation_exports as prReadinessEvaluation, external_evidence_exports as prReadinessExternalEvidence, pr_body_renderer_exports as prReadinessPrBodyRenderer, proof_identity_exports as prReadinessProofIdentity, review_proof_exports as prReadinessReviewProof, status_check_rollup_exports as prReadinessStatusChecks, verification_proof_exports as prReadinessVerificationProof, presentFactoryPrStatusHud, previewLifecycleTargets, publishEpicStructure, readDemandWaivers, readFactoryPrStatusSources, readPrReadyProof, refreshFactoryPrStatusHud, refreshFactoryPrStatusHudSafely, renderFactoryPrStatusHud, resolveFactoryRepository, resolveTraceWriteSinks, reviewFocusFromIssueBody, reviewPromptSectionSchema, reviewPromptSectionsSchema, run, runBoundaryCheck, runDemandWaive, runEvidenceEmit, runPrPublish, runPrReady, runPrReview, runPrVerify, scanFactoryTraceDiagnostics, scanFactoryTraceEvents, selectWaiversForCandidate, toFactoryTraceEnvelope, tryAppendReviewGateNotRequiredTraceEvent, validateBoundaryCheckProof, validateDagDocument, validateDemandWaiverStore, validateFactoryTraceEvent, validateMergeFreezeState, validatePrReadyProof, validatePrVerifyProof, validatePreviewLifecyclePlan, waivedDemandNotice, waivedDemandSchema, worktree_scratch_files_exports as worktreeScratchFiles };