@patronage/factory-ci 1.0.0-alpha.43 → 1.0.0-alpha.45

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,5 +1,5 @@
1
- import { t as bundleAlchemyEntry } from "./bundle-alchemy-entry-CT5hCphA.js";
2
- import { a as localPreviewStage, c as assertAlchemyBaseline, i as isLocalPreviewStage, n as executeAlchemyEntry, o as parseLocalPreviewStage, s as ALCHEMY_BASELINE, t as EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER } from "./execute-alchemy-entry-C2ZhsNTN.js";
1
+ import { t as bundleAlchemyEntry } from "./bundle-alchemy-entry-BuMrl5fR.js";
2
+ import { a as localPreviewStage, c as assertAlchemyBaseline, i as isLocalPreviewStage, n as executeAlchemyEntry, o as parseLocalPreviewStage, s as ALCHEMY_BASELINE, t as EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER } from "./execute-alchemy-entry-CDMdbXIi.js";
3
3
  import { createRequire } from "node:module";
4
4
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
5
5
  import path from "node:path";
@@ -291,15 +291,12 @@ const githubJson$1 = async (options, errors) => {
291
291
  * Minting a GitHub App installation token: the RS256 app JWT, the optional
292
292
  * installation lookup, and the token exchange (#617).
293
293
  *
294
- * Two projects had grown the same three steps independently — the factory's
295
- * check-run publisher and paitronage's proof-comment publisher — which is the
296
- * admitted-on-repetition bar. Only the *mechanism* lives here. Where the
297
- * private key comes from, how the app id is configured, and what the token is
298
- * then used for stay with each consumer: this module is handed credentials and
299
- * returns a token.
294
+ * Only the *mechanism* lives here. Where the private key comes from, how the
295
+ * app id is configured, and what the token is then used for stay with each
296
+ * consumer: this module is handed credentials and returns a token.
300
297
  */
301
298
  /** The default request budget, matching the factory's other GitHub writes. */
302
- const DEFAULT_TIMEOUT_MS$1 = 5e3;
299
+ const DEFAULT_TIMEOUT_MS$2 = 5e3;
303
300
  /** Nine-minute JWT lifetime, backdated a minute against runner clock skew. */
304
301
  const JWT_BACKDATE_SECONDS = 60;
305
302
  const JWT_LIFETIME_SECONDS = 600;
@@ -376,7 +373,7 @@ const mintInstallationToken = async (input, options = {}) => {
376
373
  const request = options.fetch ?? fetch;
377
374
  const budget = {
378
375
  attempts: options.transportAttempts,
379
- timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS$1
376
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS$2
380
377
  };
381
378
  const jwt = githubAppJwt(credentials, options);
382
379
  let { installationId } = credentials;
@@ -409,11 +406,7 @@ const mintInstallationToken = async (input, options = {}) => {
409
406
  * reuse the local verification the factory already published for *this exact
410
407
  * head*? It asks that only on a pull request, so every default-branch push
411
408
  * executes the full hosted suite (#863). Refusing runs hosted CI; it never
412
- * fails the candidate. Three
413
- * repositories had independently grown their own answer to that question and
414
- * had already drifted apart, so the answer lives here once, with the App
415
- * identity, check name, step identity, output names, guard, and every trust
416
- * predicate fixed rather than consumer-configurable.
409
+ * fails the candidate.
417
410
  *
418
411
  * What a consumer chooses is only *what its guarded surface requires*: the
419
412
  * plain profile command objects that surface selects. Everything else below is
@@ -522,8 +515,8 @@ const FACTORY_PROOF_GATE_GUARD = `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${
522
515
  */
523
516
  const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request'";
524
517
  /**
525
- * The complete refusal vocabulary. Deliberately few, because these are the
526
- * only distinctions the gate can honestly make from its Checks API reads.
518
+ * The complete refusal vocabulary: the only distinctions the gate can make
519
+ * from its Checks API reads.
527
520
  *
528
521
  * - `proven` a covering, passing, unambiguous proof for this exact head
529
522
  * - `none` no App-verified factory check run at this commit
@@ -534,14 +527,11 @@ const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request'";
534
527
  * cover every required command
535
528
  * - `ambiguous` two different generations share the newest instant, the
536
529
  * newest repeats another run's verdict with no proof time to
537
- * tell them apart, a run's start time cannot be ranked, or the
538
- * newest pass started before another run at this head was
539
- * posted
530
+ * tell them apart, a run's start time cannot be ranked, the
531
+ * newest pass records no verification start beside another run
532
+ * at this head (#1514), or the newest pass started before
533
+ * another run at this head was posted
540
534
  * - `error` the gate could not reach a decision (fail open)
541
- *
542
- * There is no `reduced`: mode stopped being an authorization condition in
543
- * ADR 0022, so a narrower run that still executed every required command is
544
- * indistinguishable from a full one *for this surface*, which is the point.
545
535
  */
546
536
  const FACTORY_PROOF_GATE_REASONS = [
547
537
  "proven",
@@ -622,31 +612,12 @@ const proofReuseRequiredCommands = (commands) => {
622
612
  return names.toSorted();
623
613
  };
624
614
  /**
625
- * Resolve command *identities* to their `ProofReuseCommand` objects (ADR
626
- * 0021).
627
- *
628
- * Selection by name is deliberately a consumer decision (proof-surfaces.ts in
629
- * software-factory-hq, the `paitronage:verify` filter in paitronage's
630
- * `verify.ts`): only the consumer knows which named commands a guarded
631
- * surface requires. What both of those implementations independently
632
- * hand-rolled is the same lookup — find each name in the profile's command
633
- * catalog, and refuse to silently shrink the required set when a name has no
634
- * entry. That lookup is what this function is: the mechanic, not the
635
- * selection.
636
- *
637
- * Throwing at generation time (rather than returning `undefined` or an empty
638
- * array) is deliberate: a name with no catalog entry is a mistake in the
639
- * generator source, not a runtime condition a consumer should have to check
640
- * for, and a required set that quietly loses an entry is exactly what makes a
641
- * passing proof trivially "covering".
642
- *
643
- * `selectionLabel` names the failure, nothing else: it is not part of the
644
- * selection this function resolves, only prose a consumer supplies for its
645
- * own thrown error (e.g. HQ's surface name, "core" or "docs"). The message
646
- * deliberately says "the profile's command catalog" rather than naming
647
- * `software-factory.profile.json`: a fleet-generic library must not assume
648
- * every consumer's catalog is that exact file, so this wording differs
649
- * on purpose from the HQ-local message it replaced.
615
+ * Resolve command identities to their `ProofReuseCommand` objects (ADR 0021).
616
+ * Which names a surface requires is the consumer's choice; this is only the
617
+ * lookup. A name with no catalog entry throws at generation time, because a
618
+ * required set that quietly loses an entry makes any passing proof covering.
619
+ * The message says "the profile's command catalog" rather than a file name,
620
+ * since not every consumer's catalog is `software-factory.profile.json`.
650
621
  */
651
622
  const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map((name) => {
652
623
  const command = catalog.find((entry) => entry.name === name);
@@ -727,6 +698,14 @@ const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map(
727
698
  * created no earlier than its verification began, so `started_at` is an
728
699
  * upper bound on that start. Ranking there can only make such a run newer
729
700
  * than it is, so it vetoes more, never less.
701
+ * - A pass with no usable typed proof is reused only when it is the only run
702
+ * at this head (#1514). Its verification started at some unknown instant
703
+ * no later than its `started_at`, so another run posted before that
704
+ * `started_at` may still have been posted after the pass began: a pass
705
+ * verified before a failure but posted after it would otherwise outrank
706
+ * the failure. Ranked at its post, such a pass can only veto more as an
707
+ * older run; as the newest it is `ambiguous` beside any other run. Proofs
708
+ * over the text cap are rare, so refusing costs a hosted run.
730
709
  * - Neither `endedAt` nor a passing run's `started_at` is its start. The
731
710
  * factory posts a `pr-verify` run only once verification has finished, so
732
711
  * both say when it ended, and an older pass ordered there would hide a run
@@ -775,7 +754,7 @@ const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map(
775
754
  * reimplement the CLI's payload parser. On payloads the factory's writer
776
755
  * emits, both readers select the same pass or both refuse: the differential
777
756
  * suite, `software-factory/src/pr-verify-reuse-differential.test.ts`,
778
- * asserts it over 9,653 generated run sets. On App-signed text the writer
757
+ * asserts it over 10,561 generated run sets. On App-signed text the writer
779
758
  * never emits, the two can differ in either direction. The known instances
780
759
  * where this gate reuses and the CLI refuses are: (a) a reused run whose
781
760
  * typed proof fails `validatePrVerifyProof`; (b) a newest pass that repeats
@@ -947,6 +926,11 @@ def releaseAuthorized($release; $commands; $stamp):
947
926
  | ($newestRun.recorded | not)
948
927
  and ([ $runs[] | select(sameVerdict($newestRun)) ] | length) > 1)
949
928
  then ["ambiguous", "", "", ""]
929
+ elif ($generation[0] as $newestRun
930
+ | ($newestRun | passing)
931
+ and ($newestRun.recorded | not)
932
+ and ($runs | length) > 1)
933
+ then ["ambiguous", "", "", ""]
950
934
  elif ($generation[0] as $newestRun
951
935
  | ($newestRun | passing)
952
936
  and any($observed[] | select(ownGeneration($newestRun) | not);
@@ -1013,15 +997,6 @@ def releaseAuthorized($release; $commands; $stamp):
1013
997
  | map(gsub("[\\r\\n\\t]"; " "))
1014
998
  | join("\n")
1015
999
  `.trim();
1016
- /**
1017
- * Every refusal ends on the same line. `pr:verify` is the command that
1018
- * produces the proof this job looks for, so it is the corrective action
1019
- * whatever the refusal was.
1020
- *
1021
- * It is phrased as an option, not a reprimand. A pull request opened by hand
1022
- * has no factory proof and never will; the full suite running for it is the
1023
- * designed behavior, not a mistake to report.
1024
- */
1025
1000
  const CORRECTIVE_LINE = "Run `psf pr:verify` before publishing to reuse local proof and avoid a duplicate server run.";
1026
1001
  /**
1027
1002
  * Emitted when a consumer's command selection is unusable. Mirrors the
@@ -1076,13 +1051,15 @@ gate_lookup() {
1076
1051
  lookup_detail="checks API unreadable: $lookup_response"
1077
1052
  return 0
1078
1053
  fi
1079
- if ! lookup_finding=$(printf '%s' "$lookup_response" | jq -r -s \
1054
+ # A herestring, not printf piped into jq: the lookup starts jq alone,
1055
+ # with no pipeline around it (#1096).
1056
+ if ! lookup_finding=$(jq -r -s \
1080
1057
  --arg name "$CHECK_NAME" \
1081
1058
  --arg app "$FACTORY_APP_ID" \
1082
1059
  --arg sha "$1" \
1083
1060
  --arg repository "$GITHUB_REPOSITORY" \
1084
1061
  --argjson required "$REQUIRED_COMMANDS" \
1085
- '${GATE_JQ}' 2>&1); then
1062
+ '${GATE_JQ}' 2>&1 <<< "$lookup_response"); then
1086
1063
  lookup_detail="unreadable proof binding: $lookup_finding"
1087
1064
  return 0
1088
1065
  fi
@@ -1138,9 +1115,14 @@ if [ "$reason" = 'proven' ]; then
1138
1115
  fi
1139
1116
 
1140
1117
  # detail can carry arbitrary gh or jq error text. Collapse it to one bounded
1141
- # line so it cannot restructure the summary it is written into.
1142
- detail=$(printf '%s' "$detail" | tr '\n\r\t' ' ' | cut -c1-240)
1143
- missing=$(printf '%s' "$missing" | tr '\n\r\t' ' ' | cut -c1-240)
1118
+ # line so it cannot restructure the summary it is written into. Builtin
1119
+ # expansions, not printf | tr | cut: each process the script starts waits for
1120
+ # a CPU on a loaded machine, and these two pipelines were most of the
1121
+ # processes every gate run started (#1096).
1122
+ detail=${shellExpansion$1(String.raw`detail//[$'\n\r\t']/ `)}
1123
+ detail=${shellExpansion$1("detail:0:240")}
1124
+ missing=${shellExpansion$1(String.raw`missing//[$'\n\r\t']/ `)}
1125
+ missing=${shellExpansion$1("missing:0:240")}
1144
1126
  if ! [[ "$source_url" =~ ^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/runs/[0-9]+$ ]]; then
1145
1127
  source_url=''
1146
1128
  fi
@@ -1202,7 +1184,7 @@ case "$reason" in
1202
1184
  ambiguous)
1203
1185
  say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
1204
1186
  say ''
1205
- say "Two different \`$CHECK_NAME\` proofs at head \`$HEAD_SHA\` share the newest generation, the newest repeats an earlier run's verdict with no proof time to tell them apart, a run's start time cannot be ranked, or the newest pass started before another run at this head was posted, so there is no single newest generation to trust. The gate refuses rather than picking one."
1187
+ say "Two different \`$CHECK_NAME\` proofs at head \`$HEAD_SHA\` share the newest generation, the newest repeats an earlier run's verdict with no proof time to tell them apart, a run's start time cannot be ranked, the newest pass records no verification start beside another run at this head, or the newest pass started before another run at this head was posted, so there is no single newest generation to trust. The gate refuses rather than picking one."
1206
1188
  say ''
1207
1189
  say '${CORRECTIVE_LINE}'
1208
1190
  ;;
@@ -1340,7 +1322,7 @@ const PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS = Object.freeze({
1340
1322
  });
1341
1323
  const INVENTORY_KIND = "patronage-factory-preview-proof";
1342
1324
  const INVENTORY_SCHEMA_VERSION = 1;
1343
- const DEFAULT_TIMEOUT_MS = 5e3;
1325
+ const DEFAULT_TIMEOUT_MS$1 = 5e3;
1344
1326
  const CHECK_RUNS_PER_PAGE = 100;
1345
1327
  const COMMITS_PER_PAGE = 100;
1346
1328
  const MAX_CHECK_RUN_PAGES = 10;
@@ -1364,12 +1346,12 @@ const GRAPHQL_FORCE_PUSH_BEFORE = `query PreviewProofForcePushBefore($owner: Str
1364
1346
  }
1365
1347
  }`;
1366
1348
  const SHA_PATTERN = /^[0-9a-f]{7,40}$/u;
1367
- const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/u;
1368
- const isRecord$1 = (value) => typeof value === "object" && value !== null;
1349
+ const FULL_SHA_PATTERN$1 = /^[0-9a-f]{40}$/u;
1350
+ const isRecord$2 = (value) => typeof value === "object" && value !== null;
1369
1351
  const isCleanupStatus = (value) => value === "failed" || value === "passed" || value === "pending";
1370
1352
  const readStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : null;
1371
1353
  const readIdentity = (value) => {
1372
- if (typeof value.pr !== "number" || !Number.isInteger(value.pr) || value.pr <= 0 || typeof value.headSha !== "string" || !FULL_SHA_PATTERN.test(value.headSha) || typeof value.stack !== "string" || value.stack.length === 0 || typeof value.stage !== "string" || typeof value.url !== "string" || value.url.length === 0) return null;
1354
+ if (typeof value.pr !== "number" || !Number.isInteger(value.pr) || value.pr <= 0 || typeof value.headSha !== "string" || !FULL_SHA_PATTERN$1.test(value.headSha) || typeof value.stack !== "string" || value.stack.length === 0 || typeof value.stage !== "string" || typeof value.url !== "string" || value.url.length === 0) return null;
1373
1355
  const parsedStage = parseLocalPreviewStage(value.stage, {
1374
1356
  headSha: value.headSha,
1375
1357
  pr: value.pr
@@ -1384,7 +1366,7 @@ const readIdentity = (value) => {
1384
1366
  };
1385
1367
  };
1386
1368
  const readCleanup = (value) => {
1387
- if (!isRecord$1(value.cleanup) || !isCleanupStatus(value.cleanup.outcome)) return null;
1369
+ if (!isRecord$2(value.cleanup) || !isCleanupStatus(value.cleanup.outcome)) return null;
1388
1370
  const evidence = readStringArray(value.cleanup.evidence);
1389
1371
  if (evidence === null) return null;
1390
1372
  return typeof value.cleanup.runUrl === "string" && value.cleanup.runUrl.length > 0 ? {
@@ -1397,7 +1379,7 @@ const readCleanup = (value) => {
1397
1379
  };
1398
1380
  };
1399
1381
  const readPassingChecks = (value) => {
1400
- if (!isRecord$1(value.convergence) || !isRecord$1(value.smoke)) return null;
1382
+ if (!isRecord$2(value.convergence) || !isRecord$2(value.smoke)) return null;
1401
1383
  if (value.convergence.status !== "passed" || typeof value.convergence.detail !== "string" || value.smoke.outcome !== "passed" || typeof value.smoke.detail !== "string") return null;
1402
1384
  return {
1403
1385
  convergence: {
@@ -1411,7 +1393,7 @@ const readPassingChecks = (value) => {
1411
1393
  };
1412
1394
  };
1413
1395
  const readProof = (value, headSha) => {
1414
- if (!isRecord$1(value.proof)) return null;
1396
+ if (!isRecord$2(value.proof)) return null;
1415
1397
  if (typeof value.proof.check !== "string" || value.proof.check.trim().length === 0 || value.proof.headSha !== headSha || typeof value.proof.mergeBaseSha !== "string" || !SHA_PATTERN.test(value.proof.mergeBaseSha) || typeof value.proof.patchId !== "string" || !SHA_PATTERN.test(value.proof.patchId)) return null;
1416
1398
  return {
1417
1399
  check: value.proof.check,
@@ -1425,7 +1407,7 @@ const readProof = (value, headSha) => {
1425
1407
  * fields, stack unions) are dropped. Invalid identity returns `null`.
1426
1408
  */
1427
1409
  const readPreviewProofRegistration = (value) => {
1428
- if (!isRecord$1(value) || value.source !== "local-self-certified") return null;
1410
+ if (!isRecord$2(value) || value.source !== "local-self-certified") return null;
1429
1411
  const identity = readIdentity(value);
1430
1412
  const cleanup = readCleanup(value);
1431
1413
  const passing = readPassingChecks(value);
@@ -1445,7 +1427,7 @@ const readPreviewProofRegistration = (value) => {
1445
1427
  };
1446
1428
  };
1447
1429
  const readInventoryPayload = (value) => {
1448
- if (!isRecord$1(value) || value.kind !== INVENTORY_KIND || value.schemaVersion !== INVENTORY_SCHEMA_VERSION) return null;
1430
+ if (!isRecord$2(value) || value.kind !== INVENTORY_KIND || value.schemaVersion !== INVENTORY_SCHEMA_VERSION) return null;
1449
1431
  return readPreviewProofRegistration(value.registration);
1450
1432
  };
1451
1433
  const assertPersistableRegistration = (registration) => {
@@ -1507,22 +1489,22 @@ const githubGraphql = async (request, token, timeoutMs, query, variables) => {
1507
1489
  }),
1508
1490
  method: "POST"
1509
1491
  }, timeoutMs);
1510
- if (!isRecord$1(served)) throw new TypeError("GitHub GraphQL response was not an object");
1492
+ if (!isRecord$2(served)) throw new TypeError("GitHub GraphQL response was not an object");
1511
1493
  if (served.errors !== void 0) {
1512
- const details = Array.isArray(served.errors) ? served.errors.flatMap((entry) => isRecord$1(entry) ? [[entry.type, entry.message].filter((part) => typeof part === "string").join(": ")] : []).filter((detail) => detail.length > 0).join("; ") : "";
1494
+ const details = Array.isArray(served.errors) ? served.errors.flatMap((entry) => isRecord$2(entry) ? [[entry.type, entry.message].filter((part) => typeof part === "string").join(": ")] : []).filter((detail) => detail.length > 0).join("; ") : "";
1513
1495
  throw new Error(details.length > 0 ? `Preview proof inventory GraphQL query failed: ${details}` : "Preview proof inventory GraphQL query failed.");
1514
1496
  }
1515
1497
  return served.data;
1516
1498
  };
1517
1499
  const repoApi = (owner, repo) => `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
1518
- const isServedCheckRun = (value) => isRecord$1(value);
1500
+ const isServedCheckRun = (value) => isRecord$2(value);
1519
1501
  const producedByFactoryApp = (run) => String(run.app?.id ?? "") === FACTORY_PROOF_GATE_APP_ID;
1520
1502
  const assertFactoryAppWrite = (value) => {
1521
1503
  if (!isServedCheckRun(value) || !producedByFactoryApp(value)) throw new Error("Preview proof inventory write must be owned by the Factory App.");
1522
1504
  return value;
1523
1505
  };
1524
1506
  const registrationFromCheckRun = (run, expectedHeadSha) => {
1525
- if (!producedByFactoryApp(run) || run.name !== "patronage-factory/preview-proof" || typeof run.head_sha !== "string" || !FULL_SHA_PATTERN.test(run.head_sha)) return null;
1507
+ if (!producedByFactoryApp(run) || run.name !== "patronage-factory/preview-proof" || typeof run.head_sha !== "string" || !FULL_SHA_PATTERN$1.test(run.head_sha)) return null;
1526
1508
  const text = run.output?.text;
1527
1509
  if (typeof text !== "string" || text.length === 0) return null;
1528
1510
  let registration;
@@ -1589,8 +1571,8 @@ const listCompareCommitShas = (request, token, timeoutMs, owner, repo, baseSha,
1589
1571
  per_page: String(COMMITS_PER_PAGE)
1590
1572
  });
1591
1573
  const compared = await githubJson(request, `${repoApi(owner, repo)}/compare/${encodeURIComponent(baseSha)}...${encodeURIComponent(headSha)}?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1592
- if (!isRecord$1(compared) || !Array.isArray(compared.commits)) throw new TypeError("GitHub compare response omitted commits");
1593
- return compared.commits.flatMap((commit) => isRecord$1(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
1574
+ if (!isRecord$2(compared) || !Array.isArray(compared.commits)) throw new TypeError("GitHub compare response omitted commits");
1575
+ return compared.commits.flatMap((commit) => isRecord$2(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
1594
1576
  }, COMMITS_PER_PAGE, MAX_COMMIT_PAGES, "Preview proof inventory compare listing exhausted pagination before GitHub returned a final page.");
1595
1577
  const listForcePushBeforeShas = async (request, token, timeoutMs, owner, repo, pr) => {
1596
1578
  const shas = [];
@@ -1603,11 +1585,11 @@ const listForcePushBeforeShas = async (request, token, timeoutMs, owner, repo, p
1603
1585
  owner,
1604
1586
  pr
1605
1587
  });
1606
- if (!isRecord$1(data) || !isRecord$1(data.repository) || !isRecord$1(data.repository.pullRequest) || !isRecord$1(data.repository.pullRequest.timelineItems)) throw new TypeError("GitHub GraphQL force-push timeline omitted timelineItems");
1588
+ if (!isRecord$2(data) || !isRecord$2(data.repository) || !isRecord$2(data.repository.pullRequest) || !isRecord$2(data.repository.pullRequest.timelineItems)) throw new TypeError("GitHub GraphQL force-push timeline omitted timelineItems");
1607
1589
  const items = data.repository.pullRequest.timelineItems;
1608
- if (!Array.isArray(items.nodes) || !isRecord$1(items.pageInfo)) throw new TypeError("GitHub GraphQL force-push timeline omitted nodes");
1590
+ if (!Array.isArray(items.nodes) || !isRecord$2(items.pageInfo)) throw new TypeError("GitHub GraphQL force-push timeline omitted nodes");
1609
1591
  for (const node of items.nodes) {
1610
- if (!isRecord$1(node) || !isRecord$1(node.beforeCommit) || typeof node.beforeCommit.oid !== "string" || !FULL_SHA_PATTERN.test(node.beforeCommit.oid)) continue;
1592
+ if (!isRecord$2(node) || !isRecord$2(node.beforeCommit) || typeof node.beforeCommit.oid !== "string" || !FULL_SHA_PATTERN$1.test(node.beforeCommit.oid)) continue;
1611
1593
  shas.push(node.beforeCommit.oid);
1612
1594
  }
1613
1595
  if (items.pageInfo.hasNextPage !== true) return shas;
@@ -1623,10 +1605,10 @@ const listPullRequestCommitShas = (request, token, timeoutMs, owner, repo, pr) =
1623
1605
  });
1624
1606
  const commits = await githubJson(request, `${repoApi(owner, repo)}/pulls/${pr}/commits?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1625
1607
  if (!Array.isArray(commits)) throw new TypeError("GitHub pull request commits response was not an array");
1626
- return commits.flatMap((commit) => isRecord$1(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
1608
+ return commits.flatMap((commit) => isRecord$2(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
1627
1609
  }, COMMITS_PER_PAGE, MAX_COMMIT_PAGES, "Preview proof inventory commit listing exhausted pagination before GitHub returned a final page.");
1628
1610
  const readPullBaseSha = (pull) => {
1629
- if (!isRecord$1(pull.base) || typeof pull.base.sha !== "string") throw new TypeError("GitHub pull request response omitted base.sha");
1611
+ if (!isRecord$2(pull.base) || typeof pull.base.sha !== "string") throw new TypeError("GitHub pull request response omitted base.sha");
1630
1612
  return pull.base.sha;
1631
1613
  };
1632
1614
  /**
@@ -1639,7 +1621,7 @@ const readPullBaseSha = (pull) => {
1639
1621
  */
1640
1622
  const listCommitShasForPull = async (request, token, timeoutMs, owner, repo, pr) => {
1641
1623
  const pull = await githubJson(request, `${repoApi(owner, repo)}/pulls/${pr}`, token, { method: "GET" }, timeoutMs);
1642
- if (!isRecord$1(pull) || !isRecord$1(pull.head) || typeof pull.head.sha !== "string") throw new TypeError("GitHub pull request response omitted head.sha");
1624
+ if (!isRecord$2(pull) || !isRecord$2(pull.head) || typeof pull.head.sha !== "string") throw new TypeError("GitHub pull request response omitted head.sha");
1643
1625
  const pullCommits = await listPullRequestCommitShas(request, token, timeoutMs, owner, repo, pr);
1644
1626
  let older = pullCommits;
1645
1627
  if (pullCommits.length >= GITHUB_PULL_COMMITS_CAP) older = await listCompareCommitShas(request, token, timeoutMs, owner, repo, readPullBaseSha(pull), pull.head.sha);
@@ -1670,7 +1652,7 @@ const listCheckRunsOnSha = (request, token, timeoutMs, owner, repo, sha) => coll
1670
1652
  per_page: String(CHECK_RUNS_PER_PAGE)
1671
1653
  });
1672
1654
  const served = await githubJson(request, `${repoApi(owner, repo)}/commits/${encodeURIComponent(sha)}/check-runs?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1673
- if (!isRecord$1(served) || !Array.isArray(served.check_runs)) throw new TypeError("GitHub check-runs response omitted check_runs");
1655
+ if (!isRecord$2(served) || !Array.isArray(served.check_runs)) throw new TypeError("GitHub check-runs response omitted check_runs");
1674
1656
  return served.check_runs.filter((run) => isServedCheckRun(run));
1675
1657
  }, CHECK_RUNS_PER_PAGE, MAX_CHECK_RUN_PAGES, "Preview proof inventory check-run listing exhausted pagination before GitHub returned a final page.");
1676
1658
  const compareCheckRunsNewestFirst = (left, right) => {
@@ -1692,7 +1674,7 @@ const takeNewestRegistrations = (runsBySha, pr) => {
1692
1674
  /** Reached by callers as `previewProofInventory.githubStore`. */
1693
1675
  const githubStore = (transport) => {
1694
1676
  const request = transport.fetch ?? fetch;
1695
- const timeoutMs = transport.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1677
+ const timeoutMs = transport.timeoutMs ?? DEFAULT_TIMEOUT_MS$1;
1696
1678
  const { token } = transport;
1697
1679
  return {
1698
1680
  list: async (input) => {
@@ -1819,7 +1801,7 @@ const SETUP_STEP_ROLES = Object.freeze([
1819
1801
  "setupNode",
1820
1802
  "install"
1821
1803
  ]);
1822
- const assertSingleLine$2 = (name, value) => {
1804
+ const assertSingleLine$3 = (name, value) => {
1823
1805
  if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
1824
1806
  };
1825
1807
  const usesStep = (fallbackName, action) => ({
@@ -1827,7 +1809,7 @@ const usesStep = (fallbackName, action) => ({
1827
1809
  uses: action.uses
1828
1810
  });
1829
1811
  const assertActionFamily = (family) => {
1830
- assertSingleLine$2("actionFamily.id", family.id);
1812
+ assertSingleLine$3("actionFamily.id", family.id);
1831
1813
  assertPinnedAction("checkout", family.checkout, "actions/checkout");
1832
1814
  assertPinnedAction("setupNode", family.setupNode, "actions/setup-node");
1833
1815
  assertPinnedAction("setupPnpm", family.setupPnpm, "pnpm/action-setup");
@@ -1893,8 +1875,8 @@ const setupStepsForRoles = (artifact, roles) => Object.freeze(roles.map((role) =
1893
1875
  * every deployment policy decision.
1894
1876
  */
1895
1877
  const factoryWorkflow = (options) => {
1896
- assertSingleLine$2("generated.source", options.generated.source);
1897
- assertSingleLine$2("generated.regenerate", options.generated.regenerate);
1878
+ assertSingleLine$3("generated.source", options.generated.source);
1879
+ assertSingleLine$3("generated.regenerate", options.generated.regenerate);
1898
1880
  assertActionFamily(options.actionFamily);
1899
1881
  assertAdditionalActions(options.additionalActions ?? {});
1900
1882
  const actions = Object.freeze({
@@ -1975,9 +1957,6 @@ say '## ${label} timing'
1975
1957
  say ''
1976
1958
 
1977
1959
  if [ "${shellExpansion("GITHUB_EVENT_NAME:-")}" = 'push' ] && [ -z "${shellExpansion("PROOF_REASON:-")}" ]; then
1978
- # A push run with no recorded reason is one where the gate step's condition
1979
- # kept it off entirely, so the full suite ran with no reuse decision. The
1980
- # gate runs on pull requests only (#863), so that is every push.
1981
1960
  say '- Path: full execution, no proof consulted'
1982
1961
  say '- Proof-reuse gate: did not run on this ref; the full suite ran.'
1983
1962
  say "- Verified head: \`${shellExpansion("GITHUB_SHA:-unknown")}\`"
@@ -2061,7 +2040,7 @@ const FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT = "decision";
2061
2040
  const FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT = "basis";
2062
2041
  const FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT = "unsubscribed_paths";
2063
2042
  const OUTPUT_NAME_PATTERN = /[^a-z0-9_]+/gu;
2064
- const shellQuote$1 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
2043
+ const shellQuote$2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
2065
2044
  /** Stable GitHub-output key for one declared target. */
2066
2045
  const productionImpactTargetOutput = (targetName) => {
2067
2046
  const normalized = targetName.toLowerCase().replaceAll(OUTPUT_NAME_PATTERN, "_").replaceAll(/^_+|_+$/gu, "");
@@ -2086,8 +2065,8 @@ const factoryProductionImpactWorkflow = (options) => {
2086
2065
  const candidate = options.candidate ?? `\${{ github.sha }}`;
2087
2066
  const cli = options.cli ?? "pnpm exec psf";
2088
2067
  assertRunnableCli("cli", cli);
2089
- const profile = options.profilePath ? ` --profile ${shellQuote$1(options.profilePath)}` : "";
2090
- const stage = options.stage ? ` --stage ${shellQuote$1(options.stage)}` : "";
2068
+ const profile = options.profilePath ? ` --profile ${shellQuote$2(options.profilePath)}` : "";
2069
+ const stage = options.stage ? ` --stage ${shellQuote$2(options.stage)}` : "";
2091
2070
  const env = {
2092
2071
  FACTORY_CANDIDATE_SHA: candidate,
2093
2072
  GH_TOKEN: `\${{ github.token }}`
@@ -2116,7 +2095,7 @@ const factoryProductionImpactWorkflow = (options) => {
2116
2095
  id: successStepId,
2117
2096
  if: "success()",
2118
2097
  name: `Publish success deployment receipt for ${targetName}`,
2119
- run: `${cli} production:impact --publish-receipt success --target ${shellQuote$1(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
2098
+ run: `${cli} production:impact --publish-receipt success --target ${shellQuote$2(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
2120
2099
  }),
2121
2100
  Object.freeze({
2122
2101
  env: { FACTORY_DEPLOYMENT_ID: deploymentId },
@@ -2128,7 +2107,7 @@ const factoryProductionImpactWorkflow = (options) => {
2128
2107
  env,
2129
2108
  if: "failure()",
2130
2109
  name: `Publish failure deployment receipt for ${targetName}`,
2131
- run: `${cli} production:impact --publish-receipt failure --target ${shellQuote$1(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
2110
+ run: `${cli} production:impact --publish-receipt failure --target ${shellQuote$2(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
2132
2111
  })
2133
2112
  ]);
2134
2113
  };
@@ -2158,7 +2137,7 @@ const FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT = "decision";
2158
2137
  const FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT = "basis";
2159
2138
  const FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT = "inert_paths";
2160
2139
  const FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT = "unsubscribed_paths";
2161
- const shellQuote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
2140
+ const shellQuote$1 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
2162
2141
  /**
2163
2142
  * Generate the factory-owned candidate routing seam for a consumer
2164
2143
  * pull-request workflow (#741). The decision step calls
@@ -2180,7 +2159,7 @@ const factoryCandidateImpactWorkflow = (options) => {
2180
2159
  const head = options.head ?? `\${{ github.event.pull_request.head.sha }}`;
2181
2160
  const cli = options.cli ?? "pnpm exec psf";
2182
2161
  assertRunnableCli("cli", cli);
2183
- const profile = options.profilePath ? ` --profile ${shellQuote(options.profilePath)}` : "";
2162
+ const profile = options.profilePath ? ` --profile ${shellQuote$1(options.profilePath)}` : "";
2184
2163
  const decisionStep = {
2185
2164
  continueOnError: true,
2186
2165
  env: {
@@ -2231,11 +2210,11 @@ const EVIDENCE_SUMMARY = `{
2231
2210
  echo "- Covers the consumer's declared Alchemy/product-stack lifecycle contracts."
2232
2211
  echo "- This static lane is non-credentialed and does not prove live deploy, D1, smoke, convergence, or cleanup."
2233
2212
  } >> "$GITHUB_STEP_SUMMARY"`;
2234
- const assertSingleLine$1 = (name, value) => {
2213
+ const assertSingleLine$2 = (name, value) => {
2235
2214
  if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
2236
2215
  };
2237
2216
  const assertPackageScriptCommand = (command) => {
2238
- assertSingleLine$1("lifecycleContract.command", command);
2217
+ assertSingleLine$2("lifecycleContract.command", command);
2239
2218
  if (CREDENTIAL_ENV.test(command)) throw new Error("lifecycleContract.command must not interpolate GitHub secrets or credential environment names.");
2240
2219
  if (SHELL_OPERATOR.test(command)) throw new Error("lifecycleContract.command must not include a shell operator or environment expansion.");
2241
2220
  if (!ALLOWED_PACKAGE_SCRIPT.test(command)) throw new Error("lifecycleContract.command must be a package script invocation (`run <script>` or a colon-namespaced shorthand), never a package-manager builtin or a direct Vitest run.");
@@ -2261,7 +2240,7 @@ const factoryLifecycleContractLane = (declaration) => {
2261
2240
  const jobId = declaration.jobId ?? "factory-contracts";
2262
2241
  const jobName = declaration.jobName ?? "Factory / Alchemy Contracts";
2263
2242
  if (!JOB_ID_PATTERN$1.test(jobId)) throw new Error("lifecycleContract.jobId must be a GitHub Actions job id.");
2264
- assertSingleLine$1("lifecycleContract.jobName", jobName);
2243
+ assertSingleLine$2("lifecycleContract.jobName", jobName);
2265
2244
  const runStep = Object.freeze({
2266
2245
  name: "Run lifecycle contracts",
2267
2246
  run: declaration.command
@@ -2531,11 +2510,11 @@ const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID = "stage-residue-audit";
2531
2510
  const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME = "Stage residue audit";
2532
2511
  const JOB_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
2533
2512
  const STACK_JOB_SAFE = /[^A-Za-z0-9_-]+/gu;
2534
- const assertSingleLine = (name, value) => {
2513
+ const assertSingleLine$1 = (name, value) => {
2535
2514
  if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
2536
2515
  };
2537
2516
  const previewCleanupDestroyJobId = (stack) => {
2538
- assertSingleLine("cleanup stack", stack);
2517
+ assertSingleLine$1("cleanup stack", stack);
2539
2518
  const suffix = stack.replaceAll(STACK_JOB_SAFE, "-").replaceAll(/^-+|-+$/gu, "");
2540
2519
  if (suffix.length === 0) throw new Error(`Cleanup stack "${stack}" has no job-id-safe characters.`);
2541
2520
  const jobId = `destroy-${suffix}`;
@@ -2557,11 +2536,11 @@ const factoryPreviewCleanupTopology = (options) => {
2557
2536
  }));
2558
2537
  const destroyJobIds = destroyJobs.map(({ jobId }) => jobId);
2559
2538
  if (new Set(destroyJobIds).size !== destroyJobIds.length) throw new Error("Cleanup stack names must map to distinct destroy job ids.");
2560
- assertSingleLine("audit.command", options.audit.command);
2539
+ assertSingleLine$1("audit.command", options.audit.command);
2561
2540
  const jobId = options.audit.jobId ?? "stage-residue-audit";
2562
2541
  const jobName = options.audit.jobName ?? "Stage residue audit";
2563
2542
  if (!JOB_ID_PATTERN.test(jobId)) throw new Error("audit.jobId must be a GitHub Actions job id.");
2564
- assertSingleLine("audit.jobName", jobName);
2543
+ assertSingleLine$1("audit.jobName", jobName);
2565
2544
  if (destroyJobIds.includes(jobId)) throw new Error("audit.jobId must not collide with a destroy job id.");
2566
2545
  const auditStep = Object.freeze({
2567
2546
  name: "Assert stage absent",
@@ -2579,6 +2558,528 @@ const factoryPreviewCleanupTopology = (options) => {
2579
2558
  });
2580
2559
  };
2581
2560
  //#endregion
2561
+ //#region src/preview-cleanup.ts
2562
+ const DEFAULT_SWEEP_MAX_TARGETS = 50;
2563
+ /** GitHub refuses a matrix with more than 256 entries. */
2564
+ const MATRIX_ENTRY_LIMIT$1 = 256;
2565
+ const DEFAULT_TIMEOUT_MS = 5e3;
2566
+ const PULL_STATE_CONCURRENCY = 8;
2567
+ const STACK_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
2568
+ const HOSTED_STAGE_PREFIX_PATTERN = /^[a-z][a-z0-9-]*-$/u;
2569
+ const OUTPUT_KEY_UNSAFE = /[^a-z0-9_]+/gu;
2570
+ const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/u;
2571
+ const isRecord$1 = (value) => typeof value === "object" && value !== null;
2572
+ /** The GitHub-output key a stack's matrix and presence flag use. */
2573
+ const previewCleanupStackOutputKey = (stack) => {
2574
+ const key = stack.toLowerCase().replaceAll(OUTPUT_KEY_UNSAFE, "_").replaceAll(/^_+|_+$/gu, "");
2575
+ if (key.length === 0) throw new Error(`Cleanup stack "${stack}" has no output-safe characters.`);
2576
+ return key;
2577
+ };
2578
+ /**
2579
+ * Validate a stack policy. Throws on an empty or duplicate stack list, a
2580
+ * stack name a shell or GitHub output could misread, an alias to an
2581
+ * undeclared stack, or a hosted prefix that is not `<word>-`.
2582
+ */
2583
+ const assertPreviewCleanupStackPolicy = (policy) => {
2584
+ if (policy.stacks.length === 0) throw new Error("Preview cleanup requires at least one stack.");
2585
+ for (const stack of policy.stacks) if (!STACK_NAME_PATTERN.test(stack)) throw new Error(`Cleanup stack "${stack}" must match ${STACK_NAME_PATTERN.source}.`);
2586
+ if (new Set(policy.stacks).size !== policy.stacks.length) throw new Error("Cleanup stacks must be distinct.");
2587
+ const keys = policy.stacks.map(previewCleanupStackOutputKey);
2588
+ if (new Set(keys).size !== keys.length) throw new Error("Cleanup stacks must map to distinct output keys.");
2589
+ for (const [alias, stack] of Object.entries(policy.stackAliases ?? {})) {
2590
+ if (!STACK_NAME_PATTERN.test(alias)) throw new Error(`Cleanup stack alias "${alias}" must match ${STACK_NAME_PATTERN.source}.`);
2591
+ if (!policy.stacks.includes(stack)) throw new Error(`Cleanup stack alias "${alias}" names undeclared stack "${stack}".`);
2592
+ }
2593
+ if (policy.hostedStagePrefix !== void 0 && (!HOSTED_STAGE_PREFIX_PATTERN.test(policy.hostedStagePrefix) || policy.hostedStagePrefix.startsWith("local-"))) throw new Error(`hostedStagePrefix must look like "pr-" and must not overlap the disposable local grammar, got "${policy.hostedStagePrefix}".`);
2594
+ };
2595
+ const resolveStack = (policy, stack) => {
2596
+ if (policy.stacks.includes(stack)) return stack;
2597
+ const aliased = policy.stackAliases?.[stack];
2598
+ return aliased !== void 0 && policy.stacks.includes(aliased) ? aliased : void 0;
2599
+ };
2600
+ /** The PR a hosted stage belongs to, or `null` when it is not one. */
2601
+ const parseHostedPreviewStage = (stage, prefix) => {
2602
+ if (!stage.startsWith(prefix)) return null;
2603
+ const digits = stage.slice(prefix.length);
2604
+ if (!/^[1-9]\d*$/u.test(digits)) return null;
2605
+ const pr = Number(digits);
2606
+ return Number.isSafeInteger(pr) ? pr : null;
2607
+ };
2608
+ /** The PR that owns a disposable stage, or `null` when it is not disposable. */
2609
+ const disposableStageOwner = (policy, stage) => parseLocalPreviewStage(stage)?.pr ?? (policy.hostedStagePrefix === void 0 ? null : parseHostedPreviewStage(stage, policy.hostedStagePrefix));
2610
+ const targetKey = (target) => `${target.stack}\u0000${target.stage}`;
2611
+ const compareTargets = (left, right) => left.pr - right.pr || left.stack.localeCompare(right.stack) || left.stage.localeCompare(right.stage);
2612
+ const assertPositivePr = (pr) => {
2613
+ if (!Number.isSafeInteger(pr) || pr < 1) throw new Error(`Cleanup PR must be a positive integer, got ${pr}.`);
2614
+ };
2615
+ /**
2616
+ * Targets for one closed PR: its inventory registrations united with the
2617
+ * residue the consumer still sees for it. Only the PR's own `local-pr-<pr>-*`
2618
+ * stages and its hosted stage survive, in declared stacks. A registration
2619
+ * wins a collision so its head SHA reaches the cleanup record. A registration
2620
+ * whose cleanup already passed is skipped unless the residue still lists it.
2621
+ */
2622
+ const discoverPreviewCleanupTargets = (input) => {
2623
+ assertPreviewCleanupStackPolicy(input);
2624
+ assertPositivePr(input.pr);
2625
+ const hostedStage = input.hostedStagePrefix === void 0 ? void 0 : `${input.hostedStagePrefix}${input.pr}`;
2626
+ const byKey = /* @__PURE__ */ new Map();
2627
+ const residueKeys = new Set(input.residue.flatMap((row) => {
2628
+ const stack = resolveStack(input, row.stack);
2629
+ return stack === void 0 ? [] : [targetKey({
2630
+ stack,
2631
+ stage: row.stage
2632
+ })];
2633
+ }));
2634
+ for (const row of input.registrations) {
2635
+ const stack = resolveStack(input, row.stack);
2636
+ const settled = stack !== void 0 && row.cleanup.outcome === "passed" && !residueKeys.has(targetKey({
2637
+ stack,
2638
+ stage: row.stage
2639
+ }));
2640
+ if (row.pr === input.pr && stack !== void 0 && !settled && isLocalPreviewStage(row.stage, input.pr)) {
2641
+ const target = {
2642
+ headSha: row.headSha,
2643
+ pr: input.pr,
2644
+ stack,
2645
+ stage: row.stage
2646
+ };
2647
+ byKey.set(targetKey(target), target);
2648
+ }
2649
+ }
2650
+ for (const row of input.residue) {
2651
+ const stack = resolveStack(input, row.stack);
2652
+ if (stack !== void 0 && (isLocalPreviewStage(row.stage, input.pr) || row.stage === hostedStage)) {
2653
+ const target = {
2654
+ pr: input.pr,
2655
+ stack,
2656
+ stage: row.stage
2657
+ };
2658
+ if (!byKey.has(targetKey(target))) byKey.set(targetKey(target), target);
2659
+ }
2660
+ }
2661
+ return Object.freeze([...byKey.values()].toSorted(compareTargets));
2662
+ };
2663
+ /**
2664
+ * The PRs whose disposable stages appear in the residue. The sweep reads
2665
+ * their state before it decides anything.
2666
+ */
2667
+ const previewCleanupResiduePullRequests = (policy, residue) => {
2668
+ assertPreviewCleanupStackPolicy(policy);
2669
+ const prs = /* @__PURE__ */ new Set();
2670
+ for (const row of residue) {
2671
+ const pr = resolveStack(policy, row.stack) === void 0 ? null : disposableStageOwner(policy, row.stage);
2672
+ if (pr !== null) prs.add(pr);
2673
+ }
2674
+ return Object.freeze([...prs].toSorted((left, right) => left - right));
2675
+ };
2676
+ /**
2677
+ * Targets for the scheduled sweep: disposable residue whose PR GitHub
2678
+ * reports closed. It fails closed. A stage that does not parse as disposable,
2679
+ * a stack the consumer did not declare, and a PR that is open or whose state
2680
+ * is unknown are all retained.
2681
+ */
2682
+ const discoverOrphanedPreviewCleanupTargets = (input) => {
2683
+ assertPreviewCleanupStackPolicy(input);
2684
+ const maxTargets = input.maxTargets ?? DEFAULT_SWEEP_MAX_TARGETS;
2685
+ if (!Number.isInteger(maxTargets) || maxTargets < 1 || maxTargets > MATRIX_ENTRY_LIMIT$1) throw new Error(`maxTargets must be an integer from 1 through ${MATRIX_ENTRY_LIMIT$1}, got ${maxTargets}.`);
2686
+ const byKey = /* @__PURE__ */ new Map();
2687
+ for (const row of input.residue) {
2688
+ const stack = resolveStack(input, row.stack);
2689
+ const pr = disposableStageOwner(input, row.stage);
2690
+ if (stack !== void 0 && pr !== null && input.pullRequestStates.get(pr) === "closed") {
2691
+ const target = {
2692
+ pr,
2693
+ stack,
2694
+ stage: row.stage
2695
+ };
2696
+ byKey.set(targetKey(target), target);
2697
+ }
2698
+ }
2699
+ const byStage = /* @__PURE__ */ new Map();
2700
+ for (const target of [...byKey.values()].toSorted(compareTargets)) byStage.set(target.stage, [...byStage.get(target.stage) ?? [], target]);
2701
+ const taken = [];
2702
+ let deferred = 0;
2703
+ for (const group of byStage.values()) if (deferred === 0 && (taken.length === 0 || taken.length + group.length <= maxTargets)) taken.push(...group);
2704
+ else deferred += group.length;
2705
+ return Object.freeze({
2706
+ deferred,
2707
+ targets: Object.freeze(taken)
2708
+ });
2709
+ };
2710
+ /**
2711
+ * The `$GITHUB_OUTPUT` lines the cleanup workflow's discover job publishes:
2712
+ * `has_targets`, `targets`, and for each declared stack `has_<key>` and
2713
+ * `<key>_matrix`. A stack with no target still gets `has_<key>=false`, so
2714
+ * its destroy job skips instead of expanding an empty matrix.
2715
+ */
2716
+ const previewCleanupGithubOutput = (policy, targets) => {
2717
+ assertPreviewCleanupStackPolicy(policy);
2718
+ const lines = [`has_targets=${targets.length > 0}`, `targets=${JSON.stringify(targets)}`];
2719
+ for (const stack of policy.stacks) {
2720
+ const key = previewCleanupStackOutputKey(stack);
2721
+ const include = targets.filter((target) => target.stack === stack);
2722
+ if (include.length > MATRIX_ENTRY_LIMIT$1) throw new Error(`Cleanup stack "${stack}" has ${include.length} targets; a GitHub matrix holds at most ${MATRIX_ENTRY_LIMIT$1}.`);
2723
+ lines.push(`has_${key}=${include.length > 0}`, `${key}_matrix=${JSON.stringify({ include })}`);
2724
+ }
2725
+ return `${lines.join("\n")}\n`;
2726
+ };
2727
+ /** Parse untrusted residue JSON: an array of `{ stack, stage }` rows. */
2728
+ const parsePreviewCleanupResidue = (value) => {
2729
+ if (!Array.isArray(value)) throw new TypeError("Preview cleanup residue must be a JSON array.");
2730
+ return Object.freeze(value.map((row, index) => {
2731
+ if (!isRecord$1(row) || typeof row.stack !== "string" || typeof row.stage !== "string") throw new TypeError(`Preview cleanup residue row ${index} must have string stack and stage.`);
2732
+ return Object.freeze({
2733
+ stack: row.stack,
2734
+ stage: row.stage
2735
+ });
2736
+ }));
2737
+ };
2738
+ /**
2739
+ * Parse untrusted target JSON (the discover job's `targets` output). Every
2740
+ * row must still be a disposable stage owned by its own PR, so a tampered
2741
+ * output cannot widen the audit or a record.
2742
+ */
2743
+ const parsePreviewCleanupTargets = (policy, value) => {
2744
+ assertPreviewCleanupStackPolicy(policy);
2745
+ if (!Array.isArray(value)) throw new TypeError("Preview cleanup targets must be a JSON array.");
2746
+ return Object.freeze(value.map((row, index) => {
2747
+ if (!isRecord$1(row) || typeof row.pr !== "number" || typeof row.stack !== "string" || typeof row.stage !== "string" || row.headSha !== void 0 && (typeof row.headSha !== "string" || !FULL_SHA_PATTERN.test(row.headSha))) throw new TypeError(`Preview cleanup target ${index} is malformed.`);
2748
+ if (!policy.stacks.includes(row.stack) || disposableStageOwner(policy, row.stage) !== row.pr) throw new Error(`Preview cleanup target ${row.stack}/${row.stage} is not a disposable stage of PR #${row.pr} in a declared stack.`);
2749
+ return Object.freeze({
2750
+ ...typeof row.headSha === "string" ? { headSha: row.headSha } : {},
2751
+ pr: row.pr,
2752
+ stack: row.stack,
2753
+ stage: row.stage
2754
+ });
2755
+ }));
2756
+ };
2757
+ /**
2758
+ * The whole-stage audit after every destroy. Any residue row whose stage
2759
+ * is a target stage fails it, whatever stack the reader assigned the row,
2760
+ * because a sibling stack's leftovers are the same stage's residue.
2761
+ */
2762
+ const assertPreviewCleanupTargetsAbsent = (targets, residue) => {
2763
+ const stages = new Set(targets.map(({ stage }) => stage));
2764
+ const remaining = residue.filter(({ stage }) => stages.has(stage));
2765
+ if (remaining.length > 0) throw new Error(`Disposable stage residue remains: ${remaining.map(({ stack, stage }) => `${stack}/${stage}`).toSorted().join(", ")}`);
2766
+ };
2767
+ const storeFor = (role, access) => {
2768
+ if (access.store !== void 0) return access.store;
2769
+ if (access.token === void 0 || access.token.length === 0) throw new Error(`Preview cleanup ${role} access requires a token.`);
2770
+ return previewProofInventory.githubStore({
2771
+ ...access.fetch === void 0 ? {} : { fetch: access.fetch },
2772
+ ...access.timeoutMs === void 0 ? {} : { timeoutMs: access.timeoutMs },
2773
+ token: access.token
2774
+ });
2775
+ };
2776
+ /**
2777
+ * Record one stack destroy's outcome on the inventory registration it
2778
+ * cleaned up. A stage nothing registered (residue-only, or a hosted stage)
2779
+ * returns `unregistered` without writing. A registration whose last cleanup
2780
+ * failed is recovered through the same cleanup transition.
2781
+ */
2782
+ const recordPreviewCleanupOutcome = async (input, access) => {
2783
+ assertPositivePr(input.pr);
2784
+ if (!isLocalPreviewStage(input.stage, input.pr)) return { kind: "unregistered" };
2785
+ const readStore = storeFor("read", access.read);
2786
+ const writeStore = storeFor("write", access.write);
2787
+ const store = {
2788
+ list: (query) => readStore.list(query),
2789
+ put: (write) => writeStore.put(write)
2790
+ };
2791
+ const canonical = (stack) => input.stackAliases?.[stack] ?? stack;
2792
+ const existing = (await previewProofInventory.list({
2793
+ owner: input.owner,
2794
+ pr: input.pr,
2795
+ repo: input.repo,
2796
+ stage: input.stage
2797
+ }, { store })).find((row) => row.pr === input.pr && row.stage === input.stage && canonical(row.stack) === canonical(input.stack));
2798
+ if (existing === void 0) return { kind: "unregistered" };
2799
+ const registration = await previewProofInventory.recordCleanup({
2800
+ evidence: input.evidence,
2801
+ ...input.headSha === void 0 ? {} : { headSha: input.headSha },
2802
+ outcome: input.outcome,
2803
+ owner: input.owner,
2804
+ pr: input.pr,
2805
+ repo: input.repo,
2806
+ ...input.runUrl === void 0 ? {} : { runUrl: input.runUrl },
2807
+ stack: existing.stack,
2808
+ stage: existing.stage
2809
+ }, { store });
2810
+ return {
2811
+ kind: existing.cleanup.outcome === "failed" ? "recovered" : "recorded",
2812
+ registration
2813
+ };
2814
+ };
2815
+ const readPullRequestState = async (input, access) => {
2816
+ let pull;
2817
+ try {
2818
+ pull = await githubJson$1({
2819
+ fetch: access.fetch ?? fetch,
2820
+ method: "GET",
2821
+ timeoutMs: access.timeoutMs ?? DEFAULT_TIMEOUT_MS,
2822
+ token: access.token,
2823
+ url: `https://api.github.com/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}/pulls/${input.pr}`
2824
+ }, {
2825
+ refusal: (status, statusText) => new GitHubApiError(status, statusText),
2826
+ transport: (failure, attempts) => new PreviewProofTransportError(failure.reason, attempts, failure.status)
2827
+ });
2828
+ } catch (error) {
2829
+ if (error instanceof GitHubApiError && error.status === 404) return null;
2830
+ throw error;
2831
+ }
2832
+ if (!isRecord$1(pull) || pull.number !== input.pr || pull.state !== "open" && pull.state !== "closed") throw new Error(`GitHub returned an unreadable pull request #${input.pr}.`);
2833
+ return pull.state;
2834
+ };
2835
+ /**
2836
+ * Ask GitHub for each PR's state. A PR GitHub does not know is left out of
2837
+ * the map, so the sweep retains its stages.
2838
+ */
2839
+ const readPullRequestStates = async (input, access) => {
2840
+ const states = /* @__PURE__ */ new Map();
2841
+ for (let start = 0; start < input.prs.length; start += PULL_STATE_CONCURRENCY) {
2842
+ const batch = input.prs.slice(start, start + PULL_STATE_CONCURRENCY);
2843
+ const read = await Promise.all(batch.map(async (pr) => ({
2844
+ pr,
2845
+ state: await readPullRequestState({
2846
+ owner: input.owner,
2847
+ pr,
2848
+ repo: input.repo
2849
+ }, access)
2850
+ })));
2851
+ for (const { pr, state } of read) if (state !== null) states.set(pr, state);
2852
+ }
2853
+ return states;
2854
+ };
2855
+ //#endregion
2856
+ //#region src/preview-cleanup-workflow.ts
2857
+ const FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID = "discover";
2858
+ const FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME = "Discover preview cleanup targets";
2859
+ const FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID = "targets";
2860
+ const FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID = "destroy";
2861
+ const FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID = "factory-app-token";
2862
+ const FACTORY_PREVIEW_CLEANUP_DEFAULT_SWEEP_CRON = "23 6 * * *";
2863
+ /**
2864
+ * A closed pull request whose head lives in this repository. A fork's head
2865
+ * never reaches a job that holds cleanup credentials.
2866
+ */
2867
+ const FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION = "github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository";
2868
+ /**
2869
+ * The sweep: the schedule, which GitHub always runs on the default branch,
2870
+ * or a manual dispatch from the default branch.
2871
+ */
2872
+ const FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION = "github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch))";
2873
+ /**
2874
+ * The ref every cleanup job checks out: the default branch's trusted code,
2875
+ * never the closed PR's head. Empty on `schedule`, where the checkout
2876
+ * already defaults to the default branch.
2877
+ */
2878
+ const FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF = `\${{ github.event.repository.default_branch }}`;
2879
+ const RESIDUE_PATH = "$RUNNER_TEMP/factory-preview-cleanup-residue.json";
2880
+ const RESIDUE_AFTER_PATH = "$RUNNER_TEMP/factory-preview-cleanup-residue-after.json";
2881
+ const EVIDENCE_PATH = "$RUNNER_TEMP/factory-preview-cleanup-evidence.txt";
2882
+ const ENVIRONMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/u;
2883
+ const CRON_PATTERN = /^\S+(?: \S+){4}$/u;
2884
+ /** GitHub refuses a matrix with more than 256 entries. */
2885
+ const MATRIX_ENTRY_LIMIT = 256;
2886
+ const shellQuote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
2887
+ const assertSingleLine = (name, value) => {
2888
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
2889
+ };
2890
+ const policyFlags = (policy) => [
2891
+ ...policy.stacks.map((stack) => `--stack ${shellQuote(stack)}`),
2892
+ ...Object.entries(policy.stackAliases ?? {}).toSorted(([left], [right]) => left.localeCompare(right)).map(([alias, stack]) => `--stack-alias ${shellQuote(`${alias}=${stack}`)}`),
2893
+ ...policy.hostedStagePrefix === void 0 ? [] : [`--hosted-stage-prefix ${shellQuote(policy.hostedStagePrefix)}`]
2894
+ ].join(" ");
2895
+ const discoverScript = (cli, flags, sweep) => {
2896
+ const prMode = `${cli} preview:cleanup --action discover --pr "$FACTORY_PREVIEW_CLEANUP_PR" --residue "${RESIDUE_PATH}" ${flags} --github-output "$GITHUB_OUTPUT"`;
2897
+ if (sweep === false) return prMode;
2898
+ const maxTargets = sweep?.maxTargets === void 0 ? "" : ` --max-targets ${sweep.maxTargets}`;
2899
+ return [
2900
+ "if [ \"$GITHUB_EVENT_NAME\" = pull_request_target ]; then",
2901
+ ` ${prMode}`,
2902
+ "else",
2903
+ ` ${cli} preview:cleanup --action sweep --residue "${RESIDUE_PATH}" ${flags}${maxTargets} --github-output "$GITHUB_OUTPUT"`,
2904
+ "fi"
2905
+ ].join("\n");
2906
+ };
2907
+ const destroyScript = (destroyCommand) => [
2908
+ `evidence="${EVIDENCE_PATH}"`,
2909
+ ": > \"$evidence\"",
2910
+ "export FACTORY_PREVIEW_CLEANUP_EVIDENCE=\"$evidence\"",
2911
+ "echo \"evidence=$evidence\" >> \"$GITHUB_OUTPUT\"",
2912
+ "target=\"$FACTORY_PREVIEW_CLEANUP_STACK/$FACTORY_PREVIEW_CLEANUP_STAGE\"",
2913
+ `if ( ${destroyCommand} ); then`,
2914
+ " echo \"destroy exited 0 for $target\" >> \"$evidence\"",
2915
+ " echo \"outcome=passed\" >> \"$GITHUB_OUTPUT\"",
2916
+ "else",
2917
+ " status=$?",
2918
+ " echo \"destroy exited $status for $target; the stage may remain and the stage residue audit decides\" >> \"$evidence\"",
2919
+ " echo \"outcome=failed\" >> \"$GITHUB_OUTPUT\"",
2920
+ "fi",
2921
+ "cat \"$evidence\"",
2922
+ "cat \"$evidence\" >> \"$GITHUB_STEP_SUMMARY\""
2923
+ ].join("\n");
2924
+ /**
2925
+ * Generate the factory-owned closed-PR preview cleanup and orphan sweep
2926
+ * (#1540) on top of `factoryPreviewCleanupTopology`:
2927
+ *
2928
+ * - `discover` reads the consumer's residue and, for a closed same-repo PR,
2929
+ * unites it with the PR's inventory registrations; for the sweep, keeps the
2930
+ * residue of PRs GitHub reports closed. It publishes one matrix per stack.
2931
+ * - one destroy job per stack runs the consumer's destroy for each matrix
2932
+ * target, then records the outcome on the inventory with the Factory App.
2933
+ * - one stage-wide audit re-reads the residue after every destroy and fails
2934
+ * if any target stage remains, in any stack.
2935
+ *
2936
+ * Every credentialed job runs in the consumer's GitHub environment, never
2937
+ * behind a production deploy flag. The caller prepends its own setup steps
2938
+ * (checked out at `checkoutRef`), and adds `runsOn` and credential `env`.
2939
+ */
2940
+ const factoryPreviewCleanupWorkflow = (options) => {
2941
+ assertPreviewCleanupStackPolicy(options);
2942
+ assertPinnedAction("createGithubAppToken", options.createGithubAppToken, "actions/create-github-app-token");
2943
+ const cli = options.cli ?? "pnpm exec psf";
2944
+ assertRunnableCli("cli", cli);
2945
+ assertSingleLine("cli", cli);
2946
+ assertSingleLine("residueCommand", options.residueCommand);
2947
+ assertSingleLine("destroyCommand", options.destroyCommand);
2948
+ if (!ENVIRONMENT_PATTERN.test(options.environment)) throw new Error("environment must name the GitHub environment that gates cleanup credentials.");
2949
+ const { sweep } = options;
2950
+ const cron = sweep === false ? void 0 : sweep?.cron ?? "23 6 * * *";
2951
+ if (cron !== void 0 && !CRON_PATTERN.test(cron)) throw new Error(`sweep.cron must have five fields, got "${cron}".`);
2952
+ const maxTargets = sweep === false ? void 0 : sweep?.maxTargets;
2953
+ if (maxTargets !== void 0 && (!Number.isInteger(maxTargets) || maxTargets < 1 || maxTargets > MATRIX_ENTRY_LIMIT)) throw new Error(`sweep.maxTargets must be an integer from 1 through ${MATRIX_ENTRY_LIMIT}, got ${maxTargets}.`);
2954
+ const concurrencyGroup = options.concurrencyGroup ?? `factory-preview-cleanup-\${{ github.repository }}-\${{ matrix.stack }}-\${{ matrix.stage }}`;
2955
+ assertSingleLine("concurrencyGroup", concurrencyGroup);
2956
+ const flags = policyFlags(options);
2957
+ const discoverIf = sweep === false ? FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION : `(${FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION}) || (${FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION})`;
2958
+ const discoverOutput = (name) => `\${{ steps.${FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID}.outputs.${name} }}`;
2959
+ const outputs = {
2960
+ has_targets: discoverOutput("has_targets"),
2961
+ targets: discoverOutput("targets")
2962
+ };
2963
+ for (const stack of options.stacks) {
2964
+ const key = previewCleanupStackOutputKey(stack);
2965
+ outputs[`has_${key}`] = discoverOutput(`has_${key}`);
2966
+ outputs[`${key}_matrix`] = discoverOutput(`${key}_matrix`);
2967
+ }
2968
+ const discoverJob = Object.freeze({
2969
+ environment: options.environment,
2970
+ if: discoverIf,
2971
+ jobId: FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID,
2972
+ jobName: FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME,
2973
+ outputs: Object.freeze(outputs),
2974
+ permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
2975
+ steps: Object.freeze([Object.freeze({
2976
+ name: "Read preview residue",
2977
+ run: `${options.residueCommand} > "${RESIDUE_PATH}"`
2978
+ }), Object.freeze({
2979
+ env: Object.freeze({
2980
+ FACTORY_PREVIEW_CLEANUP_PR: `\${{ github.event.pull_request.number }}`,
2981
+ GITHUB_TOKEN: `\${{ github.token }}`
2982
+ }),
2983
+ id: FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID,
2984
+ name: "Discover cleanup targets",
2985
+ run: discoverScript(cli, flags, sweep)
2986
+ })])
2987
+ });
2988
+ const topology = factoryPreviewCleanupTopology({
2989
+ audit: { command: `${options.residueCommand} > "${RESIDUE_AFTER_PATH}" && ${cli} preview:cleanup --action audit --residue "${RESIDUE_AFTER_PATH}" --targets "$FACTORY_PREVIEW_CLEANUP_TARGETS" ${flags}` },
2990
+ stacks: options.stacks
2991
+ });
2992
+ if (topology.destroyJobs.some(({ jobId }) => jobId === "discover")) throw new Error("A cleanup stack's destroy job id collides with discover.");
2993
+ const matrixEnv = Object.freeze({
2994
+ FACTORY_PREVIEW_CLEANUP_HEAD_SHA: `\${{ matrix.headSha }}`,
2995
+ FACTORY_PREVIEW_CLEANUP_PR: `\${{ matrix.pr }}`,
2996
+ FACTORY_PREVIEW_CLEANUP_STACK: `\${{ matrix.stack }}`,
2997
+ FACTORY_PREVIEW_CLEANUP_STAGE: `\${{ matrix.stage }}`
2998
+ });
2999
+ const destroyOutput = (name) => `\${{ steps.${FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID}.outputs.${name} }}`;
3000
+ const destroyedIf = `always() && steps.${FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID}.outputs.outcome != ''`;
3001
+ const destroySteps = Object.freeze([
3002
+ Object.freeze({
3003
+ env: matrixEnv,
3004
+ id: FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID,
3005
+ name: "Destroy the stage",
3006
+ run: destroyScript(options.destroyCommand)
3007
+ }),
3008
+ Object.freeze({
3009
+ id: FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID,
3010
+ if: destroyedIf,
3011
+ name: "Mint the factory App token",
3012
+ uses: options.createGithubAppToken.uses,
3013
+ with: Object.freeze({
3014
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
3015
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`
3016
+ })
3017
+ }),
3018
+ Object.freeze({
3019
+ env: Object.freeze({
3020
+ ...matrixEnv,
3021
+ FACTORY_GITHUB_APP_TOKEN: `\${{ steps.${FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID}.outputs.token }}`,
3022
+ FACTORY_PREVIEW_CLEANUP_EVIDENCE: destroyOutput("evidence"),
3023
+ FACTORY_PREVIEW_CLEANUP_OUTCOME: destroyOutput("outcome"),
3024
+ GITHUB_TOKEN: `\${{ github.token }}`
3025
+ }),
3026
+ if: destroyedIf,
3027
+ name: "Record the cleanup outcome",
3028
+ run: `${cli} preview:cleanup --action record --pr "$FACTORY_PREVIEW_CLEANUP_PR" --target-stack "$FACTORY_PREVIEW_CLEANUP_STACK" --target-stage "$FACTORY_PREVIEW_CLEANUP_STAGE" --outcome "$FACTORY_PREVIEW_CLEANUP_OUTCOME" --evidence-file "$FACTORY_PREVIEW_CLEANUP_EVIDENCE" \${FACTORY_PREVIEW_CLEANUP_HEAD_SHA:+--head-sha "$FACTORY_PREVIEW_CLEANUP_HEAD_SHA"} ${flags}`
3029
+ }),
3030
+ Object.freeze({
3031
+ env: Object.freeze({ FACTORY_PREVIEW_CLEANUP_OUTCOME: destroyOutput("outcome") }),
3032
+ if: "always()",
3033
+ name: "Require a passed destroy",
3034
+ run: "test \"$FACTORY_PREVIEW_CLEANUP_OUTCOME\" = passed"
3035
+ })
3036
+ ]);
3037
+ const destroyJobs = topology.destroyJobs.map(({ jobId, stack }) => {
3038
+ const key = previewCleanupStackOutputKey(stack);
3039
+ return Object.freeze({
3040
+ concurrency: Object.freeze({
3041
+ cancelInProgress: false,
3042
+ group: concurrencyGroup
3043
+ }),
3044
+ environment: options.environment,
3045
+ if: `needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.has_${key} == 'true'`,
3046
+ jobId,
3047
+ jobName: `Destroy ${stack}`,
3048
+ needs: Object.freeze([FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID]),
3049
+ permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
3050
+ stack,
3051
+ steps: destroySteps,
3052
+ strategy: Object.freeze({
3053
+ failFast: false,
3054
+ matrix: Object.freeze({ include: `\${{ fromJSON(needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.${key}_matrix).include }}` })
3055
+ })
3056
+ });
3057
+ });
3058
+ const auditJob = Object.freeze({
3059
+ env: Object.freeze({ FACTORY_PREVIEW_CLEANUP_TARGETS: `\${{ needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.targets }}` }),
3060
+ environment: options.environment,
3061
+ if: `${topology.auditJob.if} && needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.result == 'success' && needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.has_targets == 'true'`,
3062
+ jobId: topology.auditJob.jobId,
3063
+ jobName: topology.auditJob.jobName,
3064
+ needs: Object.freeze([FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID, ...topology.auditJob.needs]),
3065
+ permissions: Object.freeze({ contents: "read" }),
3066
+ steps: topology.auditJob.steps
3067
+ });
3068
+ const on = { pull_request_target: Object.freeze({ types: Object.freeze(["closed"]) }) };
3069
+ if (cron !== void 0) {
3070
+ on.schedule = Object.freeze([Object.freeze({ cron })]);
3071
+ on.workflow_dispatch = Object.freeze({});
3072
+ }
3073
+ return Object.freeze({
3074
+ auditJob,
3075
+ checkoutRef: FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF,
3076
+ destroyJobs: Object.freeze(destroyJobs),
3077
+ discoverJob,
3078
+ on: Object.freeze(on),
3079
+ permissions: Object.freeze({ contents: "read" })
3080
+ });
3081
+ };
3082
+ //#endregion
2582
3083
  //#region src/preview-receipt-workflow.ts
2583
3084
  /** Receipt transport only. The consumer owns selection, lifecycle, smoke, and freshness. */
2584
3085
  const factoryPreviewReceiptWorkflow = (options) => {
@@ -2646,11 +3147,6 @@ const factoryPreviewReceiptWorkflow = (options) => {
2646
3147
  * the pin it validates against. */
2647
3148
  const UPLOAD_ARTIFACT_REPOSITORY = UPLOAD_ARTIFACT.uses.slice(0, UPLOAD_ARTIFACT.uses.indexOf("@"));
2648
3149
  const FACTORY_PUSH_IDENTITY_SCHEMA_VERSION = 1;
2649
- /**
2650
- * The artifact prefix and the five step IDs are module-private. Alpha.13
2651
- * removed them from the public surface (#719). A caller reads a step ID from
2652
- * the builder's returned `steps` (`step.id`) or from `artifactName`.
2653
- */
2654
3150
  const FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX = "factory-push-identity";
2655
3151
  const FACTORY_PUSH_IDENTITY_RECORD_STEP_ID = "factory_push_identity_record";
2656
3152
  const FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID = "factory_push_identity_lookup";
@@ -3833,4 +4329,4 @@ const assertWorkflowShellParses = (yaml, options) => {
3833
4329
  throw new Error(`${options.source} emits shell bash cannot parse; the runner would treat it as a no-op:\n${detail}`);
3834
4330
  };
3835
4331
  //#endregion
3836
- export { ALCHEMY_BASELINE, EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER, FACTORY_APP_BROKER_ORIGIN, FACTORY_APP_BROKER_PATH, FACTORY_APP_BROKER_TOKEN_PERMISSIONS, FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT, FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT, FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT, FACTORY_CANDIDATE_IMPACT_STEP_ID, FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT, FACTORY_CANDIDATE_PULL_REQUEST_TYPES, FACTORY_CURSOR_OIDC_AUDIENCE, FACTORY_CURSOR_OIDC_ISSUER, FACTORY_CURSOR_OIDC_JWKS_URL, FACTORY_CURSOR_OIDC_MANAGED_RUNTIME, FACTORY_LIFECYCLE_CONTRACT_JOB_ID, FACTORY_LIFECYCLE_CONTRACT_JOB_NAME, FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID, FACTORY_MERGE_FREEZE_CHECK_NAME, FACTORY_MERGE_FREEZE_IF, FACTORY_MERGE_FREEZE_JOB_ID, FACTORY_MERGE_FREEZE_JOB_NAME, FACTORY_MERGE_FREEZE_PERMISSIONS, FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION, FACTORY_MERGE_TARGET_REF_CONDITION, FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID, FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME, FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT, FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT, FACTORY_PRODUCTION_IMPACT_STEP_ID, FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT, FACTORY_PROOF_GATE_APP_ID, FACTORY_PROOF_GATE_CHECK_NAME, FACTORY_PROOF_GATE_GUARD, FACTORY_PROOF_GATE_IF, FACTORY_PROOF_GATE_MODE_OUTPUT, FACTORY_PROOF_GATE_OUTPUT, FACTORY_PROOF_GATE_REASONS, FACTORY_PROOF_GATE_REASON_OUTPUT, FACTORY_PROOF_GATE_SHELL, FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT, FACTORY_PROOF_GATE_STEP_ID, FACTORY_PROOF_GATE_STEP_NAME, FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID, FACTORY_PR_STATUS_HUD_CONCURRENCY, FACTORY_PR_STATUS_HUD_IF, FACTORY_PR_STATUS_HUD_JOB_ID, FACTORY_PR_STATUS_HUD_JOB_NAME, FACTORY_PR_STATUS_HUD_PERMISSIONS, FACTORY_PR_STATUS_HUD_PLAN_PATH, FACTORY_PUSH_IDENTITY_SCHEMA_VERSION, GitHubApiError, GitHubAppTokenTransportError, NODE_PNPM_ACTION_FAMILY_NODE24, PREVIEW_PROOF_INVENTORY_CHECK_NAME, PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS, PreviewProofTransportError, SETUP_STEP_ROLES, UPLOAD_ARTIFACT, VITEST_PROFILE_SCHEMA_VERSION, VITEST_PROFILE_TOOL, VitestProfileError, assertAlchemyBaseline, assertProofReuseCoverage, assertVerifyRunnerPolicy, assertWorkflowShellParses, bundleAlchemyEntry, captureVitestProfileEnvironment, executeAlchemyEntry, factoryCandidateImpactWorkflow, factoryCandidateOrPushCondition, factoryLifecycleContractLane, factoryMergeFreezeJob, factoryMergeFreezeScript, factoryPrStatusHudWorkflow, factoryPreviewCleanupTopology, factoryPreviewReceiptWorkflow, factoryProductionImpactWorkflow, factoryProofGateScript, factoryProofGateStep, factoryProofReuseSummaryStep, factoryProofTimingStartStep, factoryPushIdentityConsumer, factoryPushIdentityProducer, factoryVerifyRunner, factoryWorkflow, githubAppJwt, isLocalPreviewStage, localPreviewStage, mintInstallationToken, normalizeVitestProfileSample, parseLocalPreviewStage, previewCleanupDestroyJobId, previewProofInventory, previewProofLifecycle, productionImpactTargetOutput, proofReuseCoverage, proofReuseRequiredCommands, readVitestProfileDocument, resolveProofReuseCommands, runVitestProfile, setupStepsForRoles, verifyRunnerPolicy, workflowRunBlocks, workflowShellParseFailures, writeVitestProfile };
4332
+ export { ALCHEMY_BASELINE, EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER, FACTORY_APP_BROKER_ORIGIN, FACTORY_APP_BROKER_PATH, FACTORY_APP_BROKER_TOKEN_PERMISSIONS, FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT, FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT, FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT, FACTORY_CANDIDATE_IMPACT_STEP_ID, FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT, FACTORY_CANDIDATE_PULL_REQUEST_TYPES, FACTORY_CURSOR_OIDC_AUDIENCE, FACTORY_CURSOR_OIDC_ISSUER, FACTORY_CURSOR_OIDC_JWKS_URL, FACTORY_CURSOR_OIDC_MANAGED_RUNTIME, FACTORY_LIFECYCLE_CONTRACT_JOB_ID, FACTORY_LIFECYCLE_CONTRACT_JOB_NAME, FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID, FACTORY_MERGE_FREEZE_CHECK_NAME, FACTORY_MERGE_FREEZE_IF, FACTORY_MERGE_FREEZE_JOB_ID, FACTORY_MERGE_FREEZE_JOB_NAME, FACTORY_MERGE_FREEZE_PERMISSIONS, FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION, FACTORY_MERGE_TARGET_REF_CONDITION, FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID, FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID, FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME, FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF, FACTORY_PREVIEW_CLEANUP_DEFAULT_SWEEP_CRON, FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID, FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID, FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME, FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID, FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION, FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION, FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT, FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT, FACTORY_PRODUCTION_IMPACT_STEP_ID, FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT, FACTORY_PROOF_GATE_APP_ID, FACTORY_PROOF_GATE_CHECK_NAME, FACTORY_PROOF_GATE_GUARD, FACTORY_PROOF_GATE_IF, FACTORY_PROOF_GATE_MODE_OUTPUT, FACTORY_PROOF_GATE_OUTPUT, FACTORY_PROOF_GATE_REASONS, FACTORY_PROOF_GATE_REASON_OUTPUT, FACTORY_PROOF_GATE_SHELL, FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT, FACTORY_PROOF_GATE_STEP_ID, FACTORY_PROOF_GATE_STEP_NAME, FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID, FACTORY_PR_STATUS_HUD_CONCURRENCY, FACTORY_PR_STATUS_HUD_IF, FACTORY_PR_STATUS_HUD_JOB_ID, FACTORY_PR_STATUS_HUD_JOB_NAME, FACTORY_PR_STATUS_HUD_PERMISSIONS, FACTORY_PR_STATUS_HUD_PLAN_PATH, FACTORY_PUSH_IDENTITY_SCHEMA_VERSION, GitHubApiError, GitHubAppTokenTransportError, NODE_PNPM_ACTION_FAMILY_NODE24, PREVIEW_PROOF_INVENTORY_CHECK_NAME, PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS, PreviewProofTransportError, SETUP_STEP_ROLES, UPLOAD_ARTIFACT, VITEST_PROFILE_SCHEMA_VERSION, VITEST_PROFILE_TOOL, VitestProfileError, assertAlchemyBaseline, assertPreviewCleanupStackPolicy, assertPreviewCleanupTargetsAbsent, assertProofReuseCoverage, assertVerifyRunnerPolicy, assertWorkflowShellParses, bundleAlchemyEntry, captureVitestProfileEnvironment, discoverOrphanedPreviewCleanupTargets, discoverPreviewCleanupTargets, executeAlchemyEntry, factoryCandidateImpactWorkflow, factoryCandidateOrPushCondition, factoryLifecycleContractLane, factoryMergeFreezeJob, factoryMergeFreezeScript, factoryPrStatusHudWorkflow, factoryPreviewCleanupTopology, factoryPreviewCleanupWorkflow, factoryPreviewReceiptWorkflow, factoryProductionImpactWorkflow, factoryProofGateScript, factoryProofGateStep, factoryProofReuseSummaryStep, factoryProofTimingStartStep, factoryPushIdentityConsumer, factoryPushIdentityProducer, factoryVerifyRunner, factoryWorkflow, githubAppJwt, isLocalPreviewStage, localPreviewStage, mintInstallationToken, normalizeVitestProfileSample, parseHostedPreviewStage, parseLocalPreviewStage, parsePreviewCleanupResidue, parsePreviewCleanupTargets, previewCleanupDestroyJobId, previewCleanupGithubOutput, previewCleanupResiduePullRequests, previewCleanupStackOutputKey, previewProofInventory, previewProofLifecycle, productionImpactTargetOutput, proofReuseCoverage, proofReuseRequiredCommands, readPullRequestStates, readVitestProfileDocument, recordPreviewCleanupOutcome, resolveProofReuseCommands, runVitestProfile, setupStepsForRoles, verifyRunnerPolicy, workflowRunBlocks, workflowShellParseFailures, writeVitestProfile };