@patronage/factory-ci 1.0.0-alpha.42 → 1.0.0-alpha.44
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/README.md +69 -3
- package/dist/.build-fingerprint.json +1 -1
- package/dist/alchemy/index.d.ts +1 -1
- package/dist/alchemy/index.js +2 -2
- package/dist/{execute-alchemy-entry-B0lBN-YZ.js → execute-alchemy-entry-C2ZhsNTN.js} +1 -1
- package/dist/index.d.ts +298 -2
- package/dist/index.js +594 -52
- package/package.json +2 -2
- package/src/alchemy/plan-effects.ts +1 -1
- package/src/alchemy-baseline.ts +1 -1
- package/src/index.ts +44 -0
- package/src/preview-cleanup-workflow.ts +422 -0
- package/src/preview-cleanup.ts +688 -0
- package/src/proof-reuse-gate.ts +27 -7
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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-
|
|
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";
|
|
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";
|
|
@@ -299,7 +299,7 @@ const githubJson$1 = async (options, errors) => {
|
|
|
299
299
|
* returns a token.
|
|
300
300
|
*/
|
|
301
301
|
/** The default request budget, matching the factory's other GitHub writes. */
|
|
302
|
-
const DEFAULT_TIMEOUT_MS$
|
|
302
|
+
const DEFAULT_TIMEOUT_MS$2 = 5e3;
|
|
303
303
|
/** Nine-minute JWT lifetime, backdated a minute against runner clock skew. */
|
|
304
304
|
const JWT_BACKDATE_SECONDS = 60;
|
|
305
305
|
const JWT_LIFETIME_SECONDS = 600;
|
|
@@ -376,7 +376,7 @@ const mintInstallationToken = async (input, options = {}) => {
|
|
|
376
376
|
const request = options.fetch ?? fetch;
|
|
377
377
|
const budget = {
|
|
378
378
|
attempts: options.transportAttempts,
|
|
379
|
-
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS$
|
|
379
|
+
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS$2
|
|
380
380
|
};
|
|
381
381
|
const jwt = githubAppJwt(credentials, options);
|
|
382
382
|
let { installationId } = credentials;
|
|
@@ -727,6 +727,14 @@ const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map(
|
|
|
727
727
|
* created no earlier than its verification began, so `started_at` is an
|
|
728
728
|
* upper bound on that start. Ranking there can only make such a run newer
|
|
729
729
|
* than it is, so it vetoes more, never less.
|
|
730
|
+
* - A pass with no usable typed proof is reused only when it is the only run
|
|
731
|
+
* at this head (#1514). Its verification started at some unknown instant
|
|
732
|
+
* no later than its `started_at`, so another run posted before that
|
|
733
|
+
* `started_at` may still have been posted after the pass began: a pass
|
|
734
|
+
* verified before a failure but posted after it would otherwise outrank
|
|
735
|
+
* the failure. Ranked at its post, such a pass can only veto more as an
|
|
736
|
+
* older run; as the newest it is `ambiguous` beside any other run. Proofs
|
|
737
|
+
* over the text cap are rare, so refusing costs a hosted run.
|
|
730
738
|
* - Neither `endedAt` nor a passing run's `started_at` is its start. The
|
|
731
739
|
* factory posts a `pr-verify` run only once verification has finished, so
|
|
732
740
|
* both say when it ended, and an older pass ordered there would hide a run
|
|
@@ -775,7 +783,7 @@ const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map(
|
|
|
775
783
|
* reimplement the CLI's payload parser. On payloads the factory's writer
|
|
776
784
|
* emits, both readers select the same pass or both refuse: the differential
|
|
777
785
|
* suite, `software-factory/src/pr-verify-reuse-differential.test.ts`,
|
|
778
|
-
* asserts it over
|
|
786
|
+
* asserts it over 10,561 generated run sets. On App-signed text the writer
|
|
779
787
|
* never emits, the two can differ in either direction. The known instances
|
|
780
788
|
* where this gate reuses and the CLI refuses are: (a) a reused run whose
|
|
781
789
|
* typed proof fails `validatePrVerifyProof`; (b) a newest pass that repeats
|
|
@@ -947,6 +955,11 @@ def releaseAuthorized($release; $commands; $stamp):
|
|
|
947
955
|
| ($newestRun.recorded | not)
|
|
948
956
|
and ([ $runs[] | select(sameVerdict($newestRun)) ] | length) > 1)
|
|
949
957
|
then ["ambiguous", "", "", ""]
|
|
958
|
+
elif ($generation[0] as $newestRun
|
|
959
|
+
| ($newestRun | passing)
|
|
960
|
+
and ($newestRun.recorded | not)
|
|
961
|
+
and ($runs | length) > 1)
|
|
962
|
+
then ["ambiguous", "", "", ""]
|
|
950
963
|
elif ($generation[0] as $newestRun
|
|
951
964
|
| ($newestRun | passing)
|
|
952
965
|
and any($observed[] | select(ownGeneration($newestRun) | not);
|
|
@@ -1076,13 +1089,15 @@ gate_lookup() {
|
|
|
1076
1089
|
lookup_detail="checks API unreadable: $lookup_response"
|
|
1077
1090
|
return 0
|
|
1078
1091
|
fi
|
|
1079
|
-
|
|
1092
|
+
# A herestring, not printf piped into jq: the lookup starts jq alone,
|
|
1093
|
+
# with no pipeline around it (#1096).
|
|
1094
|
+
if ! lookup_finding=$(jq -r -s \
|
|
1080
1095
|
--arg name "$CHECK_NAME" \
|
|
1081
1096
|
--arg app "$FACTORY_APP_ID" \
|
|
1082
1097
|
--arg sha "$1" \
|
|
1083
1098
|
--arg repository "$GITHUB_REPOSITORY" \
|
|
1084
1099
|
--argjson required "$REQUIRED_COMMANDS" \
|
|
1085
|
-
'${GATE_JQ}' 2>&1); then
|
|
1100
|
+
'${GATE_JQ}' 2>&1 <<< "$lookup_response"); then
|
|
1086
1101
|
lookup_detail="unreadable proof binding: $lookup_finding"
|
|
1087
1102
|
return 0
|
|
1088
1103
|
fi
|
|
@@ -1138,9 +1153,14 @@ if [ "$reason" = 'proven' ]; then
|
|
|
1138
1153
|
fi
|
|
1139
1154
|
|
|
1140
1155
|
# 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
|
-
|
|
1143
|
-
|
|
1156
|
+
# line so it cannot restructure the summary it is written into. Builtin
|
|
1157
|
+
# expansions, not printf | tr | cut: each process the script starts waits for
|
|
1158
|
+
# a CPU on a loaded machine, and these two pipelines were most of the
|
|
1159
|
+
# processes every gate run started (#1096).
|
|
1160
|
+
detail=${shellExpansion$1(String.raw`detail//[$'\n\r\t']/ `)}
|
|
1161
|
+
detail=${shellExpansion$1("detail:0:240")}
|
|
1162
|
+
missing=${shellExpansion$1(String.raw`missing//[$'\n\r\t']/ `)}
|
|
1163
|
+
missing=${shellExpansion$1("missing:0:240")}
|
|
1144
1164
|
if ! [[ "$source_url" =~ ^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/runs/[0-9]+$ ]]; then
|
|
1145
1165
|
source_url=''
|
|
1146
1166
|
fi
|
|
@@ -1202,7 +1222,7 @@ case "$reason" in
|
|
|
1202
1222
|
ambiguous)
|
|
1203
1223
|
say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
|
|
1204
1224
|
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."
|
|
1225
|
+
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
1226
|
say ''
|
|
1207
1227
|
say '${CORRECTIVE_LINE}'
|
|
1208
1228
|
;;
|
|
@@ -1340,7 +1360,7 @@ const PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS = Object.freeze({
|
|
|
1340
1360
|
});
|
|
1341
1361
|
const INVENTORY_KIND = "patronage-factory-preview-proof";
|
|
1342
1362
|
const INVENTORY_SCHEMA_VERSION = 1;
|
|
1343
|
-
const DEFAULT_TIMEOUT_MS = 5e3;
|
|
1363
|
+
const DEFAULT_TIMEOUT_MS$1 = 5e3;
|
|
1344
1364
|
const CHECK_RUNS_PER_PAGE = 100;
|
|
1345
1365
|
const COMMITS_PER_PAGE = 100;
|
|
1346
1366
|
const MAX_CHECK_RUN_PAGES = 10;
|
|
@@ -1364,12 +1384,12 @@ const GRAPHQL_FORCE_PUSH_BEFORE = `query PreviewProofForcePushBefore($owner: Str
|
|
|
1364
1384
|
}
|
|
1365
1385
|
}`;
|
|
1366
1386
|
const SHA_PATTERN = /^[0-9a-f]{7,40}$/u;
|
|
1367
|
-
const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/u;
|
|
1368
|
-
const isRecord$
|
|
1387
|
+
const FULL_SHA_PATTERN$1 = /^[0-9a-f]{40}$/u;
|
|
1388
|
+
const isRecord$2 = (value) => typeof value === "object" && value !== null;
|
|
1369
1389
|
const isCleanupStatus = (value) => value === "failed" || value === "passed" || value === "pending";
|
|
1370
1390
|
const readStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : null;
|
|
1371
1391
|
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;
|
|
1392
|
+
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
1393
|
const parsedStage = parseLocalPreviewStage(value.stage, {
|
|
1374
1394
|
headSha: value.headSha,
|
|
1375
1395
|
pr: value.pr
|
|
@@ -1384,7 +1404,7 @@ const readIdentity = (value) => {
|
|
|
1384
1404
|
};
|
|
1385
1405
|
};
|
|
1386
1406
|
const readCleanup = (value) => {
|
|
1387
|
-
if (!isRecord$
|
|
1407
|
+
if (!isRecord$2(value.cleanup) || !isCleanupStatus(value.cleanup.outcome)) return null;
|
|
1388
1408
|
const evidence = readStringArray(value.cleanup.evidence);
|
|
1389
1409
|
if (evidence === null) return null;
|
|
1390
1410
|
return typeof value.cleanup.runUrl === "string" && value.cleanup.runUrl.length > 0 ? {
|
|
@@ -1397,7 +1417,7 @@ const readCleanup = (value) => {
|
|
|
1397
1417
|
};
|
|
1398
1418
|
};
|
|
1399
1419
|
const readPassingChecks = (value) => {
|
|
1400
|
-
if (!isRecord$
|
|
1420
|
+
if (!isRecord$2(value.convergence) || !isRecord$2(value.smoke)) return null;
|
|
1401
1421
|
if (value.convergence.status !== "passed" || typeof value.convergence.detail !== "string" || value.smoke.outcome !== "passed" || typeof value.smoke.detail !== "string") return null;
|
|
1402
1422
|
return {
|
|
1403
1423
|
convergence: {
|
|
@@ -1411,7 +1431,7 @@ const readPassingChecks = (value) => {
|
|
|
1411
1431
|
};
|
|
1412
1432
|
};
|
|
1413
1433
|
const readProof = (value, headSha) => {
|
|
1414
|
-
if (!isRecord$
|
|
1434
|
+
if (!isRecord$2(value.proof)) return null;
|
|
1415
1435
|
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
1436
|
return {
|
|
1417
1437
|
check: value.proof.check,
|
|
@@ -1425,7 +1445,7 @@ const readProof = (value, headSha) => {
|
|
|
1425
1445
|
* fields, stack unions) are dropped. Invalid identity returns `null`.
|
|
1426
1446
|
*/
|
|
1427
1447
|
const readPreviewProofRegistration = (value) => {
|
|
1428
|
-
if (!isRecord$
|
|
1448
|
+
if (!isRecord$2(value) || value.source !== "local-self-certified") return null;
|
|
1429
1449
|
const identity = readIdentity(value);
|
|
1430
1450
|
const cleanup = readCleanup(value);
|
|
1431
1451
|
const passing = readPassingChecks(value);
|
|
@@ -1445,7 +1465,7 @@ const readPreviewProofRegistration = (value) => {
|
|
|
1445
1465
|
};
|
|
1446
1466
|
};
|
|
1447
1467
|
const readInventoryPayload = (value) => {
|
|
1448
|
-
if (!isRecord$
|
|
1468
|
+
if (!isRecord$2(value) || value.kind !== INVENTORY_KIND || value.schemaVersion !== INVENTORY_SCHEMA_VERSION) return null;
|
|
1449
1469
|
return readPreviewProofRegistration(value.registration);
|
|
1450
1470
|
};
|
|
1451
1471
|
const assertPersistableRegistration = (registration) => {
|
|
@@ -1507,22 +1527,22 @@ const githubGraphql = async (request, token, timeoutMs, query, variables) => {
|
|
|
1507
1527
|
}),
|
|
1508
1528
|
method: "POST"
|
|
1509
1529
|
}, timeoutMs);
|
|
1510
|
-
if (!isRecord$
|
|
1530
|
+
if (!isRecord$2(served)) throw new TypeError("GitHub GraphQL response was not an object");
|
|
1511
1531
|
if (served.errors !== void 0) {
|
|
1512
|
-
const details = Array.isArray(served.errors) ? served.errors.flatMap((entry) => isRecord$
|
|
1532
|
+
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
1533
|
throw new Error(details.length > 0 ? `Preview proof inventory GraphQL query failed: ${details}` : "Preview proof inventory GraphQL query failed.");
|
|
1514
1534
|
}
|
|
1515
1535
|
return served.data;
|
|
1516
1536
|
};
|
|
1517
1537
|
const repoApi = (owner, repo) => `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
|
|
1518
|
-
const isServedCheckRun = (value) => isRecord$
|
|
1538
|
+
const isServedCheckRun = (value) => isRecord$2(value);
|
|
1519
1539
|
const producedByFactoryApp = (run) => String(run.app?.id ?? "") === FACTORY_PROOF_GATE_APP_ID;
|
|
1520
1540
|
const assertFactoryAppWrite = (value) => {
|
|
1521
1541
|
if (!isServedCheckRun(value) || !producedByFactoryApp(value)) throw new Error("Preview proof inventory write must be owned by the Factory App.");
|
|
1522
1542
|
return value;
|
|
1523
1543
|
};
|
|
1524
1544
|
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;
|
|
1545
|
+
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
1546
|
const text = run.output?.text;
|
|
1527
1547
|
if (typeof text !== "string" || text.length === 0) return null;
|
|
1528
1548
|
let registration;
|
|
@@ -1589,8 +1609,8 @@ const listCompareCommitShas = (request, token, timeoutMs, owner, repo, baseSha,
|
|
|
1589
1609
|
per_page: String(COMMITS_PER_PAGE)
|
|
1590
1610
|
});
|
|
1591
1611
|
const compared = await githubJson(request, `${repoApi(owner, repo)}/compare/${encodeURIComponent(baseSha)}...${encodeURIComponent(headSha)}?${query.toString()}`, token, { method: "GET" }, timeoutMs);
|
|
1592
|
-
if (!isRecord$
|
|
1593
|
-
return compared.commits.flatMap((commit) => isRecord$
|
|
1612
|
+
if (!isRecord$2(compared) || !Array.isArray(compared.commits)) throw new TypeError("GitHub compare response omitted commits");
|
|
1613
|
+
return compared.commits.flatMap((commit) => isRecord$2(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
|
|
1594
1614
|
}, COMMITS_PER_PAGE, MAX_COMMIT_PAGES, "Preview proof inventory compare listing exhausted pagination before GitHub returned a final page.");
|
|
1595
1615
|
const listForcePushBeforeShas = async (request, token, timeoutMs, owner, repo, pr) => {
|
|
1596
1616
|
const shas = [];
|
|
@@ -1603,11 +1623,11 @@ const listForcePushBeforeShas = async (request, token, timeoutMs, owner, repo, p
|
|
|
1603
1623
|
owner,
|
|
1604
1624
|
pr
|
|
1605
1625
|
});
|
|
1606
|
-
if (!isRecord$
|
|
1626
|
+
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
1627
|
const items = data.repository.pullRequest.timelineItems;
|
|
1608
|
-
if (!Array.isArray(items.nodes) || !isRecord$
|
|
1628
|
+
if (!Array.isArray(items.nodes) || !isRecord$2(items.pageInfo)) throw new TypeError("GitHub GraphQL force-push timeline omitted nodes");
|
|
1609
1629
|
for (const node of items.nodes) {
|
|
1610
|
-
if (!isRecord$
|
|
1630
|
+
if (!isRecord$2(node) || !isRecord$2(node.beforeCommit) || typeof node.beforeCommit.oid !== "string" || !FULL_SHA_PATTERN$1.test(node.beforeCommit.oid)) continue;
|
|
1611
1631
|
shas.push(node.beforeCommit.oid);
|
|
1612
1632
|
}
|
|
1613
1633
|
if (items.pageInfo.hasNextPage !== true) return shas;
|
|
@@ -1623,10 +1643,10 @@ const listPullRequestCommitShas = (request, token, timeoutMs, owner, repo, pr) =
|
|
|
1623
1643
|
});
|
|
1624
1644
|
const commits = await githubJson(request, `${repoApi(owner, repo)}/pulls/${pr}/commits?${query.toString()}`, token, { method: "GET" }, timeoutMs);
|
|
1625
1645
|
if (!Array.isArray(commits)) throw new TypeError("GitHub pull request commits response was not an array");
|
|
1626
|
-
return commits.flatMap((commit) => isRecord$
|
|
1646
|
+
return commits.flatMap((commit) => isRecord$2(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
|
|
1627
1647
|
}, COMMITS_PER_PAGE, MAX_COMMIT_PAGES, "Preview proof inventory commit listing exhausted pagination before GitHub returned a final page.");
|
|
1628
1648
|
const readPullBaseSha = (pull) => {
|
|
1629
|
-
if (!isRecord$
|
|
1649
|
+
if (!isRecord$2(pull.base) || typeof pull.base.sha !== "string") throw new TypeError("GitHub pull request response omitted base.sha");
|
|
1630
1650
|
return pull.base.sha;
|
|
1631
1651
|
};
|
|
1632
1652
|
/**
|
|
@@ -1639,7 +1659,7 @@ const readPullBaseSha = (pull) => {
|
|
|
1639
1659
|
*/
|
|
1640
1660
|
const listCommitShasForPull = async (request, token, timeoutMs, owner, repo, pr) => {
|
|
1641
1661
|
const pull = await githubJson(request, `${repoApi(owner, repo)}/pulls/${pr}`, token, { method: "GET" }, timeoutMs);
|
|
1642
|
-
if (!isRecord$
|
|
1662
|
+
if (!isRecord$2(pull) || !isRecord$2(pull.head) || typeof pull.head.sha !== "string") throw new TypeError("GitHub pull request response omitted head.sha");
|
|
1643
1663
|
const pullCommits = await listPullRequestCommitShas(request, token, timeoutMs, owner, repo, pr);
|
|
1644
1664
|
let older = pullCommits;
|
|
1645
1665
|
if (pullCommits.length >= GITHUB_PULL_COMMITS_CAP) older = await listCompareCommitShas(request, token, timeoutMs, owner, repo, readPullBaseSha(pull), pull.head.sha);
|
|
@@ -1670,7 +1690,7 @@ const listCheckRunsOnSha = (request, token, timeoutMs, owner, repo, sha) => coll
|
|
|
1670
1690
|
per_page: String(CHECK_RUNS_PER_PAGE)
|
|
1671
1691
|
});
|
|
1672
1692
|
const served = await githubJson(request, `${repoApi(owner, repo)}/commits/${encodeURIComponent(sha)}/check-runs?${query.toString()}`, token, { method: "GET" }, timeoutMs);
|
|
1673
|
-
if (!isRecord$
|
|
1693
|
+
if (!isRecord$2(served) || !Array.isArray(served.check_runs)) throw new TypeError("GitHub check-runs response omitted check_runs");
|
|
1674
1694
|
return served.check_runs.filter((run) => isServedCheckRun(run));
|
|
1675
1695
|
}, CHECK_RUNS_PER_PAGE, MAX_CHECK_RUN_PAGES, "Preview proof inventory check-run listing exhausted pagination before GitHub returned a final page.");
|
|
1676
1696
|
const compareCheckRunsNewestFirst = (left, right) => {
|
|
@@ -1692,7 +1712,7 @@ const takeNewestRegistrations = (runsBySha, pr) => {
|
|
|
1692
1712
|
/** Reached by callers as `previewProofInventory.githubStore`. */
|
|
1693
1713
|
const githubStore = (transport) => {
|
|
1694
1714
|
const request = transport.fetch ?? fetch;
|
|
1695
|
-
const timeoutMs = transport.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1715
|
+
const timeoutMs = transport.timeoutMs ?? DEFAULT_TIMEOUT_MS$1;
|
|
1696
1716
|
const { token } = transport;
|
|
1697
1717
|
return {
|
|
1698
1718
|
list: async (input) => {
|
|
@@ -1819,7 +1839,7 @@ const SETUP_STEP_ROLES = Object.freeze([
|
|
|
1819
1839
|
"setupNode",
|
|
1820
1840
|
"install"
|
|
1821
1841
|
]);
|
|
1822
|
-
const assertSingleLine$
|
|
1842
|
+
const assertSingleLine$3 = (name, value) => {
|
|
1823
1843
|
if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
|
|
1824
1844
|
};
|
|
1825
1845
|
const usesStep = (fallbackName, action) => ({
|
|
@@ -1827,7 +1847,7 @@ const usesStep = (fallbackName, action) => ({
|
|
|
1827
1847
|
uses: action.uses
|
|
1828
1848
|
});
|
|
1829
1849
|
const assertActionFamily = (family) => {
|
|
1830
|
-
assertSingleLine$
|
|
1850
|
+
assertSingleLine$3("actionFamily.id", family.id);
|
|
1831
1851
|
assertPinnedAction("checkout", family.checkout, "actions/checkout");
|
|
1832
1852
|
assertPinnedAction("setupNode", family.setupNode, "actions/setup-node");
|
|
1833
1853
|
assertPinnedAction("setupPnpm", family.setupPnpm, "pnpm/action-setup");
|
|
@@ -1893,8 +1913,8 @@ const setupStepsForRoles = (artifact, roles) => Object.freeze(roles.map((role) =
|
|
|
1893
1913
|
* every deployment policy decision.
|
|
1894
1914
|
*/
|
|
1895
1915
|
const factoryWorkflow = (options) => {
|
|
1896
|
-
assertSingleLine$
|
|
1897
|
-
assertSingleLine$
|
|
1916
|
+
assertSingleLine$3("generated.source", options.generated.source);
|
|
1917
|
+
assertSingleLine$3("generated.regenerate", options.generated.regenerate);
|
|
1898
1918
|
assertActionFamily(options.actionFamily);
|
|
1899
1919
|
assertAdditionalActions(options.additionalActions ?? {});
|
|
1900
1920
|
const actions = Object.freeze({
|
|
@@ -2061,7 +2081,7 @@ const FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT = "decision";
|
|
|
2061
2081
|
const FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT = "basis";
|
|
2062
2082
|
const FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT = "unsubscribed_paths";
|
|
2063
2083
|
const OUTPUT_NAME_PATTERN = /[^a-z0-9_]+/gu;
|
|
2064
|
-
const shellQuote$
|
|
2084
|
+
const shellQuote$2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
2065
2085
|
/** Stable GitHub-output key for one declared target. */
|
|
2066
2086
|
const productionImpactTargetOutput = (targetName) => {
|
|
2067
2087
|
const normalized = targetName.toLowerCase().replaceAll(OUTPUT_NAME_PATTERN, "_").replaceAll(/^_+|_+$/gu, "");
|
|
@@ -2086,8 +2106,8 @@ const factoryProductionImpactWorkflow = (options) => {
|
|
|
2086
2106
|
const candidate = options.candidate ?? `\${{ github.sha }}`;
|
|
2087
2107
|
const cli = options.cli ?? "pnpm exec psf";
|
|
2088
2108
|
assertRunnableCli("cli", cli);
|
|
2089
|
-
const profile = options.profilePath ? ` --profile ${shellQuote$
|
|
2090
|
-
const stage = options.stage ? ` --stage ${shellQuote$
|
|
2109
|
+
const profile = options.profilePath ? ` --profile ${shellQuote$2(options.profilePath)}` : "";
|
|
2110
|
+
const stage = options.stage ? ` --stage ${shellQuote$2(options.stage)}` : "";
|
|
2091
2111
|
const env = {
|
|
2092
2112
|
FACTORY_CANDIDATE_SHA: candidate,
|
|
2093
2113
|
GH_TOKEN: `\${{ github.token }}`
|
|
@@ -2116,7 +2136,7 @@ const factoryProductionImpactWorkflow = (options) => {
|
|
|
2116
2136
|
id: successStepId,
|
|
2117
2137
|
if: "success()",
|
|
2118
2138
|
name: `Publish success deployment receipt for ${targetName}`,
|
|
2119
|
-
run: `${cli} production:impact --publish-receipt success --target ${shellQuote$
|
|
2139
|
+
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
2140
|
}),
|
|
2121
2141
|
Object.freeze({
|
|
2122
2142
|
env: { FACTORY_DEPLOYMENT_ID: deploymentId },
|
|
@@ -2128,7 +2148,7 @@ const factoryProductionImpactWorkflow = (options) => {
|
|
|
2128
2148
|
env,
|
|
2129
2149
|
if: "failure()",
|
|
2130
2150
|
name: `Publish failure deployment receipt for ${targetName}`,
|
|
2131
|
-
run: `${cli} production:impact --publish-receipt failure --target ${shellQuote$
|
|
2151
|
+
run: `${cli} production:impact --publish-receipt failure --target ${shellQuote$2(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
|
|
2132
2152
|
})
|
|
2133
2153
|
]);
|
|
2134
2154
|
};
|
|
@@ -2158,7 +2178,7 @@ const FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT = "decision";
|
|
|
2158
2178
|
const FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT = "basis";
|
|
2159
2179
|
const FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT = "inert_paths";
|
|
2160
2180
|
const FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT = "unsubscribed_paths";
|
|
2161
|
-
const shellQuote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
2181
|
+
const shellQuote$1 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
2162
2182
|
/**
|
|
2163
2183
|
* Generate the factory-owned candidate routing seam for a consumer
|
|
2164
2184
|
* pull-request workflow (#741). The decision step calls
|
|
@@ -2180,7 +2200,7 @@ const factoryCandidateImpactWorkflow = (options) => {
|
|
|
2180
2200
|
const head = options.head ?? `\${{ github.event.pull_request.head.sha }}`;
|
|
2181
2201
|
const cli = options.cli ?? "pnpm exec psf";
|
|
2182
2202
|
assertRunnableCli("cli", cli);
|
|
2183
|
-
const profile = options.profilePath ? ` --profile ${shellQuote(options.profilePath)}` : "";
|
|
2203
|
+
const profile = options.profilePath ? ` --profile ${shellQuote$1(options.profilePath)}` : "";
|
|
2184
2204
|
const decisionStep = {
|
|
2185
2205
|
continueOnError: true,
|
|
2186
2206
|
env: {
|
|
@@ -2231,11 +2251,11 @@ const EVIDENCE_SUMMARY = `{
|
|
|
2231
2251
|
echo "- Covers the consumer's declared Alchemy/product-stack lifecycle contracts."
|
|
2232
2252
|
echo "- This static lane is non-credentialed and does not prove live deploy, D1, smoke, convergence, or cleanup."
|
|
2233
2253
|
} >> "$GITHUB_STEP_SUMMARY"`;
|
|
2234
|
-
const assertSingleLine$
|
|
2254
|
+
const assertSingleLine$2 = (name, value) => {
|
|
2235
2255
|
if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
|
|
2236
2256
|
};
|
|
2237
2257
|
const assertPackageScriptCommand = (command) => {
|
|
2238
|
-
assertSingleLine$
|
|
2258
|
+
assertSingleLine$2("lifecycleContract.command", command);
|
|
2239
2259
|
if (CREDENTIAL_ENV.test(command)) throw new Error("lifecycleContract.command must not interpolate GitHub secrets or credential environment names.");
|
|
2240
2260
|
if (SHELL_OPERATOR.test(command)) throw new Error("lifecycleContract.command must not include a shell operator or environment expansion.");
|
|
2241
2261
|
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 +2281,7 @@ const factoryLifecycleContractLane = (declaration) => {
|
|
|
2261
2281
|
const jobId = declaration.jobId ?? "factory-contracts";
|
|
2262
2282
|
const jobName = declaration.jobName ?? "Factory / Alchemy Contracts";
|
|
2263
2283
|
if (!JOB_ID_PATTERN$1.test(jobId)) throw new Error("lifecycleContract.jobId must be a GitHub Actions job id.");
|
|
2264
|
-
assertSingleLine$
|
|
2284
|
+
assertSingleLine$2("lifecycleContract.jobName", jobName);
|
|
2265
2285
|
const runStep = Object.freeze({
|
|
2266
2286
|
name: "Run lifecycle contracts",
|
|
2267
2287
|
run: declaration.command
|
|
@@ -2531,11 +2551,11 @@ const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID = "stage-residue-audit";
|
|
|
2531
2551
|
const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME = "Stage residue audit";
|
|
2532
2552
|
const JOB_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
|
|
2533
2553
|
const STACK_JOB_SAFE = /[^A-Za-z0-9_-]+/gu;
|
|
2534
|
-
const assertSingleLine = (name, value) => {
|
|
2554
|
+
const assertSingleLine$1 = (name, value) => {
|
|
2535
2555
|
if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
|
|
2536
2556
|
};
|
|
2537
2557
|
const previewCleanupDestroyJobId = (stack) => {
|
|
2538
|
-
assertSingleLine("cleanup stack", stack);
|
|
2558
|
+
assertSingleLine$1("cleanup stack", stack);
|
|
2539
2559
|
const suffix = stack.replaceAll(STACK_JOB_SAFE, "-").replaceAll(/^-+|-+$/gu, "");
|
|
2540
2560
|
if (suffix.length === 0) throw new Error(`Cleanup stack "${stack}" has no job-id-safe characters.`);
|
|
2541
2561
|
const jobId = `destroy-${suffix}`;
|
|
@@ -2557,11 +2577,11 @@ const factoryPreviewCleanupTopology = (options) => {
|
|
|
2557
2577
|
}));
|
|
2558
2578
|
const destroyJobIds = destroyJobs.map(({ jobId }) => jobId);
|
|
2559
2579
|
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);
|
|
2580
|
+
assertSingleLine$1("audit.command", options.audit.command);
|
|
2561
2581
|
const jobId = options.audit.jobId ?? "stage-residue-audit";
|
|
2562
2582
|
const jobName = options.audit.jobName ?? "Stage residue audit";
|
|
2563
2583
|
if (!JOB_ID_PATTERN.test(jobId)) throw new Error("audit.jobId must be a GitHub Actions job id.");
|
|
2564
|
-
assertSingleLine("audit.jobName", jobName);
|
|
2584
|
+
assertSingleLine$1("audit.jobName", jobName);
|
|
2565
2585
|
if (destroyJobIds.includes(jobId)) throw new Error("audit.jobId must not collide with a destroy job id.");
|
|
2566
2586
|
const auditStep = Object.freeze({
|
|
2567
2587
|
name: "Assert stage absent",
|
|
@@ -2579,6 +2599,528 @@ const factoryPreviewCleanupTopology = (options) => {
|
|
|
2579
2599
|
});
|
|
2580
2600
|
};
|
|
2581
2601
|
//#endregion
|
|
2602
|
+
//#region src/preview-cleanup.ts
|
|
2603
|
+
const DEFAULT_SWEEP_MAX_TARGETS = 50;
|
|
2604
|
+
/** GitHub refuses a matrix with more than 256 entries. */
|
|
2605
|
+
const MATRIX_ENTRY_LIMIT$1 = 256;
|
|
2606
|
+
const DEFAULT_TIMEOUT_MS = 5e3;
|
|
2607
|
+
const PULL_STATE_CONCURRENCY = 8;
|
|
2608
|
+
const STACK_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
|
|
2609
|
+
const HOSTED_STAGE_PREFIX_PATTERN = /^[a-z][a-z0-9-]*-$/u;
|
|
2610
|
+
const OUTPUT_KEY_UNSAFE = /[^a-z0-9_]+/gu;
|
|
2611
|
+
const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/u;
|
|
2612
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null;
|
|
2613
|
+
/** The GitHub-output key a stack's matrix and presence flag use. */
|
|
2614
|
+
const previewCleanupStackOutputKey = (stack) => {
|
|
2615
|
+
const key = stack.toLowerCase().replaceAll(OUTPUT_KEY_UNSAFE, "_").replaceAll(/^_+|_+$/gu, "");
|
|
2616
|
+
if (key.length === 0) throw new Error(`Cleanup stack "${stack}" has no output-safe characters.`);
|
|
2617
|
+
return key;
|
|
2618
|
+
};
|
|
2619
|
+
/**
|
|
2620
|
+
* Validate a stack policy. Throws on an empty or duplicate stack list, a
|
|
2621
|
+
* stack name a shell or GitHub output could misread, an alias to an
|
|
2622
|
+
* undeclared stack, or a hosted prefix that is not `<word>-`.
|
|
2623
|
+
*/
|
|
2624
|
+
const assertPreviewCleanupStackPolicy = (policy) => {
|
|
2625
|
+
if (policy.stacks.length === 0) throw new Error("Preview cleanup requires at least one stack.");
|
|
2626
|
+
for (const stack of policy.stacks) if (!STACK_NAME_PATTERN.test(stack)) throw new Error(`Cleanup stack "${stack}" must match ${STACK_NAME_PATTERN.source}.`);
|
|
2627
|
+
if (new Set(policy.stacks).size !== policy.stacks.length) throw new Error("Cleanup stacks must be distinct.");
|
|
2628
|
+
const keys = policy.stacks.map(previewCleanupStackOutputKey);
|
|
2629
|
+
if (new Set(keys).size !== keys.length) throw new Error("Cleanup stacks must map to distinct output keys.");
|
|
2630
|
+
for (const [alias, stack] of Object.entries(policy.stackAliases ?? {})) {
|
|
2631
|
+
if (!STACK_NAME_PATTERN.test(alias)) throw new Error(`Cleanup stack alias "${alias}" must match ${STACK_NAME_PATTERN.source}.`);
|
|
2632
|
+
if (!policy.stacks.includes(stack)) throw new Error(`Cleanup stack alias "${alias}" names undeclared stack "${stack}".`);
|
|
2633
|
+
}
|
|
2634
|
+
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}".`);
|
|
2635
|
+
};
|
|
2636
|
+
const resolveStack = (policy, stack) => {
|
|
2637
|
+
if (policy.stacks.includes(stack)) return stack;
|
|
2638
|
+
const aliased = policy.stackAliases?.[stack];
|
|
2639
|
+
return aliased !== void 0 && policy.stacks.includes(aliased) ? aliased : void 0;
|
|
2640
|
+
};
|
|
2641
|
+
/** The PR a hosted stage belongs to, or `null` when it is not one. */
|
|
2642
|
+
const parseHostedPreviewStage = (stage, prefix) => {
|
|
2643
|
+
if (!stage.startsWith(prefix)) return null;
|
|
2644
|
+
const digits = stage.slice(prefix.length);
|
|
2645
|
+
if (!/^[1-9]\d*$/u.test(digits)) return null;
|
|
2646
|
+
const pr = Number(digits);
|
|
2647
|
+
return Number.isSafeInteger(pr) ? pr : null;
|
|
2648
|
+
};
|
|
2649
|
+
/** The PR that owns a disposable stage, or `null` when it is not disposable. */
|
|
2650
|
+
const disposableStageOwner = (policy, stage) => parseLocalPreviewStage(stage)?.pr ?? (policy.hostedStagePrefix === void 0 ? null : parseHostedPreviewStage(stage, policy.hostedStagePrefix));
|
|
2651
|
+
const targetKey = (target) => `${target.stack}\u0000${target.stage}`;
|
|
2652
|
+
const compareTargets = (left, right) => left.pr - right.pr || left.stack.localeCompare(right.stack) || left.stage.localeCompare(right.stage);
|
|
2653
|
+
const assertPositivePr = (pr) => {
|
|
2654
|
+
if (!Number.isSafeInteger(pr) || pr < 1) throw new Error(`Cleanup PR must be a positive integer, got ${pr}.`);
|
|
2655
|
+
};
|
|
2656
|
+
/**
|
|
2657
|
+
* Targets for one closed PR: its inventory registrations united with the
|
|
2658
|
+
* residue the consumer still sees for it. Only the PR's own `local-pr-<pr>-*`
|
|
2659
|
+
* stages and its hosted stage survive, in declared stacks. A registration
|
|
2660
|
+
* wins a collision so its head SHA reaches the cleanup record. A registration
|
|
2661
|
+
* whose cleanup already passed is skipped unless the residue still lists it.
|
|
2662
|
+
*/
|
|
2663
|
+
const discoverPreviewCleanupTargets = (input) => {
|
|
2664
|
+
assertPreviewCleanupStackPolicy(input);
|
|
2665
|
+
assertPositivePr(input.pr);
|
|
2666
|
+
const hostedStage = input.hostedStagePrefix === void 0 ? void 0 : `${input.hostedStagePrefix}${input.pr}`;
|
|
2667
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
2668
|
+
const residueKeys = new Set(input.residue.flatMap((row) => {
|
|
2669
|
+
const stack = resolveStack(input, row.stack);
|
|
2670
|
+
return stack === void 0 ? [] : [targetKey({
|
|
2671
|
+
stack,
|
|
2672
|
+
stage: row.stage
|
|
2673
|
+
})];
|
|
2674
|
+
}));
|
|
2675
|
+
for (const row of input.registrations) {
|
|
2676
|
+
const stack = resolveStack(input, row.stack);
|
|
2677
|
+
const settled = stack !== void 0 && row.cleanup.outcome === "passed" && !residueKeys.has(targetKey({
|
|
2678
|
+
stack,
|
|
2679
|
+
stage: row.stage
|
|
2680
|
+
}));
|
|
2681
|
+
if (row.pr === input.pr && stack !== void 0 && !settled && isLocalPreviewStage(row.stage, input.pr)) {
|
|
2682
|
+
const target = {
|
|
2683
|
+
headSha: row.headSha,
|
|
2684
|
+
pr: input.pr,
|
|
2685
|
+
stack,
|
|
2686
|
+
stage: row.stage
|
|
2687
|
+
};
|
|
2688
|
+
byKey.set(targetKey(target), target);
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
for (const row of input.residue) {
|
|
2692
|
+
const stack = resolveStack(input, row.stack);
|
|
2693
|
+
if (stack !== void 0 && (isLocalPreviewStage(row.stage, input.pr) || row.stage === hostedStage)) {
|
|
2694
|
+
const target = {
|
|
2695
|
+
pr: input.pr,
|
|
2696
|
+
stack,
|
|
2697
|
+
stage: row.stage
|
|
2698
|
+
};
|
|
2699
|
+
if (!byKey.has(targetKey(target))) byKey.set(targetKey(target), target);
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
return Object.freeze([...byKey.values()].toSorted(compareTargets));
|
|
2703
|
+
};
|
|
2704
|
+
/**
|
|
2705
|
+
* The PRs whose disposable stages appear in the residue. The sweep reads
|
|
2706
|
+
* their state before it decides anything.
|
|
2707
|
+
*/
|
|
2708
|
+
const previewCleanupResiduePullRequests = (policy, residue) => {
|
|
2709
|
+
assertPreviewCleanupStackPolicy(policy);
|
|
2710
|
+
const prs = /* @__PURE__ */ new Set();
|
|
2711
|
+
for (const row of residue) {
|
|
2712
|
+
const pr = resolveStack(policy, row.stack) === void 0 ? null : disposableStageOwner(policy, row.stage);
|
|
2713
|
+
if (pr !== null) prs.add(pr);
|
|
2714
|
+
}
|
|
2715
|
+
return Object.freeze([...prs].toSorted((left, right) => left - right));
|
|
2716
|
+
};
|
|
2717
|
+
/**
|
|
2718
|
+
* Targets for the scheduled sweep: disposable residue whose PR GitHub
|
|
2719
|
+
* reports closed. It fails closed. A stage that does not parse as disposable,
|
|
2720
|
+
* a stack the consumer did not declare, and a PR that is open or whose state
|
|
2721
|
+
* is unknown are all retained.
|
|
2722
|
+
*/
|
|
2723
|
+
const discoverOrphanedPreviewCleanupTargets = (input) => {
|
|
2724
|
+
assertPreviewCleanupStackPolicy(input);
|
|
2725
|
+
const maxTargets = input.maxTargets ?? DEFAULT_SWEEP_MAX_TARGETS;
|
|
2726
|
+
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}.`);
|
|
2727
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
2728
|
+
for (const row of input.residue) {
|
|
2729
|
+
const stack = resolveStack(input, row.stack);
|
|
2730
|
+
const pr = disposableStageOwner(input, row.stage);
|
|
2731
|
+
if (stack !== void 0 && pr !== null && input.pullRequestStates.get(pr) === "closed") {
|
|
2732
|
+
const target = {
|
|
2733
|
+
pr,
|
|
2734
|
+
stack,
|
|
2735
|
+
stage: row.stage
|
|
2736
|
+
};
|
|
2737
|
+
byKey.set(targetKey(target), target);
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
const byStage = /* @__PURE__ */ new Map();
|
|
2741
|
+
for (const target of [...byKey.values()].toSorted(compareTargets)) byStage.set(target.stage, [...byStage.get(target.stage) ?? [], target]);
|
|
2742
|
+
const taken = [];
|
|
2743
|
+
let deferred = 0;
|
|
2744
|
+
for (const group of byStage.values()) if (deferred === 0 && (taken.length === 0 || taken.length + group.length <= maxTargets)) taken.push(...group);
|
|
2745
|
+
else deferred += group.length;
|
|
2746
|
+
return Object.freeze({
|
|
2747
|
+
deferred,
|
|
2748
|
+
targets: Object.freeze(taken)
|
|
2749
|
+
});
|
|
2750
|
+
};
|
|
2751
|
+
/**
|
|
2752
|
+
* The `$GITHUB_OUTPUT` lines the cleanup workflow's discover job publishes:
|
|
2753
|
+
* `has_targets`, `targets`, and for each declared stack `has_<key>` and
|
|
2754
|
+
* `<key>_matrix`. A stack with no target still gets `has_<key>=false`, so
|
|
2755
|
+
* its destroy job skips instead of expanding an empty matrix.
|
|
2756
|
+
*/
|
|
2757
|
+
const previewCleanupGithubOutput = (policy, targets) => {
|
|
2758
|
+
assertPreviewCleanupStackPolicy(policy);
|
|
2759
|
+
const lines = [`has_targets=${targets.length > 0}`, `targets=${JSON.stringify(targets)}`];
|
|
2760
|
+
for (const stack of policy.stacks) {
|
|
2761
|
+
const key = previewCleanupStackOutputKey(stack);
|
|
2762
|
+
const include = targets.filter((target) => target.stack === stack);
|
|
2763
|
+
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}.`);
|
|
2764
|
+
lines.push(`has_${key}=${include.length > 0}`, `${key}_matrix=${JSON.stringify({ include })}`);
|
|
2765
|
+
}
|
|
2766
|
+
return `${lines.join("\n")}\n`;
|
|
2767
|
+
};
|
|
2768
|
+
/** Parse untrusted residue JSON: an array of `{ stack, stage }` rows. */
|
|
2769
|
+
const parsePreviewCleanupResidue = (value) => {
|
|
2770
|
+
if (!Array.isArray(value)) throw new TypeError("Preview cleanup residue must be a JSON array.");
|
|
2771
|
+
return Object.freeze(value.map((row, index) => {
|
|
2772
|
+
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.`);
|
|
2773
|
+
return Object.freeze({
|
|
2774
|
+
stack: row.stack,
|
|
2775
|
+
stage: row.stage
|
|
2776
|
+
});
|
|
2777
|
+
}));
|
|
2778
|
+
};
|
|
2779
|
+
/**
|
|
2780
|
+
* Parse untrusted target JSON (the discover job's `targets` output). Every
|
|
2781
|
+
* row must still be a disposable stage owned by its own PR, so a tampered
|
|
2782
|
+
* output cannot widen the audit or a record.
|
|
2783
|
+
*/
|
|
2784
|
+
const parsePreviewCleanupTargets = (policy, value) => {
|
|
2785
|
+
assertPreviewCleanupStackPolicy(policy);
|
|
2786
|
+
if (!Array.isArray(value)) throw new TypeError("Preview cleanup targets must be a JSON array.");
|
|
2787
|
+
return Object.freeze(value.map((row, index) => {
|
|
2788
|
+
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.`);
|
|
2789
|
+
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.`);
|
|
2790
|
+
return Object.freeze({
|
|
2791
|
+
...typeof row.headSha === "string" ? { headSha: row.headSha } : {},
|
|
2792
|
+
pr: row.pr,
|
|
2793
|
+
stack: row.stack,
|
|
2794
|
+
stage: row.stage
|
|
2795
|
+
});
|
|
2796
|
+
}));
|
|
2797
|
+
};
|
|
2798
|
+
/**
|
|
2799
|
+
* The whole-stage audit after every destroy. Any residue row whose stage
|
|
2800
|
+
* is a target stage fails it, whatever stack the reader assigned the row,
|
|
2801
|
+
* because a sibling stack's leftovers are the same stage's residue.
|
|
2802
|
+
*/
|
|
2803
|
+
const assertPreviewCleanupTargetsAbsent = (targets, residue) => {
|
|
2804
|
+
const stages = new Set(targets.map(({ stage }) => stage));
|
|
2805
|
+
const remaining = residue.filter(({ stage }) => stages.has(stage));
|
|
2806
|
+
if (remaining.length > 0) throw new Error(`Disposable stage residue remains: ${remaining.map(({ stack, stage }) => `${stack}/${stage}`).toSorted().join(", ")}`);
|
|
2807
|
+
};
|
|
2808
|
+
const storeFor = (role, access) => {
|
|
2809
|
+
if (access.store !== void 0) return access.store;
|
|
2810
|
+
if (access.token === void 0 || access.token.length === 0) throw new Error(`Preview cleanup ${role} access requires a token.`);
|
|
2811
|
+
return previewProofInventory.githubStore({
|
|
2812
|
+
...access.fetch === void 0 ? {} : { fetch: access.fetch },
|
|
2813
|
+
...access.timeoutMs === void 0 ? {} : { timeoutMs: access.timeoutMs },
|
|
2814
|
+
token: access.token
|
|
2815
|
+
});
|
|
2816
|
+
};
|
|
2817
|
+
/**
|
|
2818
|
+
* Record one stack destroy's outcome on the inventory registration it
|
|
2819
|
+
* cleaned up. A stage nothing registered (residue-only, or a hosted stage)
|
|
2820
|
+
* returns `unregistered` without writing. A registration whose last cleanup
|
|
2821
|
+
* failed is recovered through the same cleanup transition.
|
|
2822
|
+
*/
|
|
2823
|
+
const recordPreviewCleanupOutcome = async (input, access) => {
|
|
2824
|
+
assertPositivePr(input.pr);
|
|
2825
|
+
if (!isLocalPreviewStage(input.stage, input.pr)) return { kind: "unregistered" };
|
|
2826
|
+
const readStore = storeFor("read", access.read);
|
|
2827
|
+
const writeStore = storeFor("write", access.write);
|
|
2828
|
+
const store = {
|
|
2829
|
+
list: (query) => readStore.list(query),
|
|
2830
|
+
put: (write) => writeStore.put(write)
|
|
2831
|
+
};
|
|
2832
|
+
const canonical = (stack) => input.stackAliases?.[stack] ?? stack;
|
|
2833
|
+
const existing = (await previewProofInventory.list({
|
|
2834
|
+
owner: input.owner,
|
|
2835
|
+
pr: input.pr,
|
|
2836
|
+
repo: input.repo,
|
|
2837
|
+
stage: input.stage
|
|
2838
|
+
}, { store })).find((row) => row.pr === input.pr && row.stage === input.stage && canonical(row.stack) === canonical(input.stack));
|
|
2839
|
+
if (existing === void 0) return { kind: "unregistered" };
|
|
2840
|
+
const registration = await previewProofInventory.recordCleanup({
|
|
2841
|
+
evidence: input.evidence,
|
|
2842
|
+
...input.headSha === void 0 ? {} : { headSha: input.headSha },
|
|
2843
|
+
outcome: input.outcome,
|
|
2844
|
+
owner: input.owner,
|
|
2845
|
+
pr: input.pr,
|
|
2846
|
+
repo: input.repo,
|
|
2847
|
+
...input.runUrl === void 0 ? {} : { runUrl: input.runUrl },
|
|
2848
|
+
stack: existing.stack,
|
|
2849
|
+
stage: existing.stage
|
|
2850
|
+
}, { store });
|
|
2851
|
+
return {
|
|
2852
|
+
kind: existing.cleanup.outcome === "failed" ? "recovered" : "recorded",
|
|
2853
|
+
registration
|
|
2854
|
+
};
|
|
2855
|
+
};
|
|
2856
|
+
const readPullRequestState = async (input, access) => {
|
|
2857
|
+
let pull;
|
|
2858
|
+
try {
|
|
2859
|
+
pull = await githubJson$1({
|
|
2860
|
+
fetch: access.fetch ?? fetch,
|
|
2861
|
+
method: "GET",
|
|
2862
|
+
timeoutMs: access.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
2863
|
+
token: access.token,
|
|
2864
|
+
url: `https://api.github.com/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}/pulls/${input.pr}`
|
|
2865
|
+
}, {
|
|
2866
|
+
refusal: (status, statusText) => new GitHubApiError(status, statusText),
|
|
2867
|
+
transport: (failure, attempts) => new PreviewProofTransportError(failure.reason, attempts, failure.status)
|
|
2868
|
+
});
|
|
2869
|
+
} catch (error) {
|
|
2870
|
+
if (error instanceof GitHubApiError && error.status === 404) return null;
|
|
2871
|
+
throw error;
|
|
2872
|
+
}
|
|
2873
|
+
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}.`);
|
|
2874
|
+
return pull.state;
|
|
2875
|
+
};
|
|
2876
|
+
/**
|
|
2877
|
+
* Ask GitHub for each PR's state. A PR GitHub does not know is left out of
|
|
2878
|
+
* the map, so the sweep retains its stages.
|
|
2879
|
+
*/
|
|
2880
|
+
const readPullRequestStates = async (input, access) => {
|
|
2881
|
+
const states = /* @__PURE__ */ new Map();
|
|
2882
|
+
for (let start = 0; start < input.prs.length; start += PULL_STATE_CONCURRENCY) {
|
|
2883
|
+
const batch = input.prs.slice(start, start + PULL_STATE_CONCURRENCY);
|
|
2884
|
+
const read = await Promise.all(batch.map(async (pr) => ({
|
|
2885
|
+
pr,
|
|
2886
|
+
state: await readPullRequestState({
|
|
2887
|
+
owner: input.owner,
|
|
2888
|
+
pr,
|
|
2889
|
+
repo: input.repo
|
|
2890
|
+
}, access)
|
|
2891
|
+
})));
|
|
2892
|
+
for (const { pr, state } of read) if (state !== null) states.set(pr, state);
|
|
2893
|
+
}
|
|
2894
|
+
return states;
|
|
2895
|
+
};
|
|
2896
|
+
//#endregion
|
|
2897
|
+
//#region src/preview-cleanup-workflow.ts
|
|
2898
|
+
const FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID = "discover";
|
|
2899
|
+
const FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME = "Discover preview cleanup targets";
|
|
2900
|
+
const FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID = "targets";
|
|
2901
|
+
const FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID = "destroy";
|
|
2902
|
+
const FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID = "factory-app-token";
|
|
2903
|
+
const FACTORY_PREVIEW_CLEANUP_DEFAULT_SWEEP_CRON = "23 6 * * *";
|
|
2904
|
+
/**
|
|
2905
|
+
* A closed pull request whose head lives in this repository. A fork's head
|
|
2906
|
+
* never reaches a job that holds cleanup credentials.
|
|
2907
|
+
*/
|
|
2908
|
+
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";
|
|
2909
|
+
/**
|
|
2910
|
+
* The sweep: the schedule, which GitHub always runs on the default branch,
|
|
2911
|
+
* or a manual dispatch from the default branch.
|
|
2912
|
+
*/
|
|
2913
|
+
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))";
|
|
2914
|
+
/**
|
|
2915
|
+
* The ref every cleanup job checks out: the default branch's trusted code,
|
|
2916
|
+
* never the closed PR's head. Empty on `schedule`, where the checkout
|
|
2917
|
+
* already defaults to the default branch.
|
|
2918
|
+
*/
|
|
2919
|
+
const FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF = `\${{ github.event.repository.default_branch }}`;
|
|
2920
|
+
const RESIDUE_PATH = "$RUNNER_TEMP/factory-preview-cleanup-residue.json";
|
|
2921
|
+
const RESIDUE_AFTER_PATH = "$RUNNER_TEMP/factory-preview-cleanup-residue-after.json";
|
|
2922
|
+
const EVIDENCE_PATH = "$RUNNER_TEMP/factory-preview-cleanup-evidence.txt";
|
|
2923
|
+
const ENVIRONMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/u;
|
|
2924
|
+
const CRON_PATTERN = /^\S+(?: \S+){4}$/u;
|
|
2925
|
+
/** GitHub refuses a matrix with more than 256 entries. */
|
|
2926
|
+
const MATRIX_ENTRY_LIMIT = 256;
|
|
2927
|
+
const shellQuote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
2928
|
+
const assertSingleLine = (name, value) => {
|
|
2929
|
+
if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
|
|
2930
|
+
};
|
|
2931
|
+
const policyFlags = (policy) => [
|
|
2932
|
+
...policy.stacks.map((stack) => `--stack ${shellQuote(stack)}`),
|
|
2933
|
+
...Object.entries(policy.stackAliases ?? {}).toSorted(([left], [right]) => left.localeCompare(right)).map(([alias, stack]) => `--stack-alias ${shellQuote(`${alias}=${stack}`)}`),
|
|
2934
|
+
...policy.hostedStagePrefix === void 0 ? [] : [`--hosted-stage-prefix ${shellQuote(policy.hostedStagePrefix)}`]
|
|
2935
|
+
].join(" ");
|
|
2936
|
+
const discoverScript = (cli, flags, sweep) => {
|
|
2937
|
+
const prMode = `${cli} preview:cleanup --action discover --pr "$FACTORY_PREVIEW_CLEANUP_PR" --residue "${RESIDUE_PATH}" ${flags} --github-output "$GITHUB_OUTPUT"`;
|
|
2938
|
+
if (sweep === false) return prMode;
|
|
2939
|
+
const maxTargets = sweep?.maxTargets === void 0 ? "" : ` --max-targets ${sweep.maxTargets}`;
|
|
2940
|
+
return [
|
|
2941
|
+
"if [ \"$GITHUB_EVENT_NAME\" = pull_request_target ]; then",
|
|
2942
|
+
` ${prMode}`,
|
|
2943
|
+
"else",
|
|
2944
|
+
` ${cli} preview:cleanup --action sweep --residue "${RESIDUE_PATH}" ${flags}${maxTargets} --github-output "$GITHUB_OUTPUT"`,
|
|
2945
|
+
"fi"
|
|
2946
|
+
].join("\n");
|
|
2947
|
+
};
|
|
2948
|
+
const destroyScript = (destroyCommand) => [
|
|
2949
|
+
`evidence="${EVIDENCE_PATH}"`,
|
|
2950
|
+
": > \"$evidence\"",
|
|
2951
|
+
"export FACTORY_PREVIEW_CLEANUP_EVIDENCE=\"$evidence\"",
|
|
2952
|
+
"echo \"evidence=$evidence\" >> \"$GITHUB_OUTPUT\"",
|
|
2953
|
+
"target=\"$FACTORY_PREVIEW_CLEANUP_STACK/$FACTORY_PREVIEW_CLEANUP_STAGE\"",
|
|
2954
|
+
`if ( ${destroyCommand} ); then`,
|
|
2955
|
+
" echo \"destroy exited 0 for $target\" >> \"$evidence\"",
|
|
2956
|
+
" echo \"outcome=passed\" >> \"$GITHUB_OUTPUT\"",
|
|
2957
|
+
"else",
|
|
2958
|
+
" status=$?",
|
|
2959
|
+
" echo \"destroy exited $status for $target; the stage may remain and the stage residue audit decides\" >> \"$evidence\"",
|
|
2960
|
+
" echo \"outcome=failed\" >> \"$GITHUB_OUTPUT\"",
|
|
2961
|
+
"fi",
|
|
2962
|
+
"cat \"$evidence\"",
|
|
2963
|
+
"cat \"$evidence\" >> \"$GITHUB_STEP_SUMMARY\""
|
|
2964
|
+
].join("\n");
|
|
2965
|
+
/**
|
|
2966
|
+
* Generate the factory-owned closed-PR preview cleanup and orphan sweep
|
|
2967
|
+
* (#1540) on top of `factoryPreviewCleanupTopology`:
|
|
2968
|
+
*
|
|
2969
|
+
* - `discover` reads the consumer's residue and, for a closed same-repo PR,
|
|
2970
|
+
* unites it with the PR's inventory registrations; for the sweep, keeps the
|
|
2971
|
+
* residue of PRs GitHub reports closed. It publishes one matrix per stack.
|
|
2972
|
+
* - one destroy job per stack runs the consumer's destroy for each matrix
|
|
2973
|
+
* target, then records the outcome on the inventory with the Factory App.
|
|
2974
|
+
* - one stage-wide audit re-reads the residue after every destroy and fails
|
|
2975
|
+
* if any target stage remains, in any stack.
|
|
2976
|
+
*
|
|
2977
|
+
* Every credentialed job runs in the consumer's GitHub environment, never
|
|
2978
|
+
* behind a production deploy flag. The caller prepends its own setup steps
|
|
2979
|
+
* (checked out at `checkoutRef`), and adds `runsOn` and credential `env`.
|
|
2980
|
+
*/
|
|
2981
|
+
const factoryPreviewCleanupWorkflow = (options) => {
|
|
2982
|
+
assertPreviewCleanupStackPolicy(options);
|
|
2983
|
+
assertPinnedAction("createGithubAppToken", options.createGithubAppToken, "actions/create-github-app-token");
|
|
2984
|
+
const cli = options.cli ?? "pnpm exec psf";
|
|
2985
|
+
assertRunnableCli("cli", cli);
|
|
2986
|
+
assertSingleLine("cli", cli);
|
|
2987
|
+
assertSingleLine("residueCommand", options.residueCommand);
|
|
2988
|
+
assertSingleLine("destroyCommand", options.destroyCommand);
|
|
2989
|
+
if (!ENVIRONMENT_PATTERN.test(options.environment)) throw new Error("environment must name the GitHub environment that gates cleanup credentials.");
|
|
2990
|
+
const { sweep } = options;
|
|
2991
|
+
const cron = sweep === false ? void 0 : sweep?.cron ?? "23 6 * * *";
|
|
2992
|
+
if (cron !== void 0 && !CRON_PATTERN.test(cron)) throw new Error(`sweep.cron must have five fields, got "${cron}".`);
|
|
2993
|
+
const maxTargets = sweep === false ? void 0 : sweep?.maxTargets;
|
|
2994
|
+
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}.`);
|
|
2995
|
+
const concurrencyGroup = options.concurrencyGroup ?? `factory-preview-cleanup-\${{ github.repository }}-\${{ matrix.stack }}-\${{ matrix.stage }}`;
|
|
2996
|
+
assertSingleLine("concurrencyGroup", concurrencyGroup);
|
|
2997
|
+
const flags = policyFlags(options);
|
|
2998
|
+
const discoverIf = sweep === false ? FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION : `(${FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION}) || (${FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION})`;
|
|
2999
|
+
const discoverOutput = (name) => `\${{ steps.${FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID}.outputs.${name} }}`;
|
|
3000
|
+
const outputs = {
|
|
3001
|
+
has_targets: discoverOutput("has_targets"),
|
|
3002
|
+
targets: discoverOutput("targets")
|
|
3003
|
+
};
|
|
3004
|
+
for (const stack of options.stacks) {
|
|
3005
|
+
const key = previewCleanupStackOutputKey(stack);
|
|
3006
|
+
outputs[`has_${key}`] = discoverOutput(`has_${key}`);
|
|
3007
|
+
outputs[`${key}_matrix`] = discoverOutput(`${key}_matrix`);
|
|
3008
|
+
}
|
|
3009
|
+
const discoverJob = Object.freeze({
|
|
3010
|
+
environment: options.environment,
|
|
3011
|
+
if: discoverIf,
|
|
3012
|
+
jobId: FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID,
|
|
3013
|
+
jobName: FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME,
|
|
3014
|
+
outputs: Object.freeze(outputs),
|
|
3015
|
+
permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
|
|
3016
|
+
steps: Object.freeze([Object.freeze({
|
|
3017
|
+
name: "Read preview residue",
|
|
3018
|
+
run: `${options.residueCommand} > "${RESIDUE_PATH}"`
|
|
3019
|
+
}), Object.freeze({
|
|
3020
|
+
env: Object.freeze({
|
|
3021
|
+
FACTORY_PREVIEW_CLEANUP_PR: `\${{ github.event.pull_request.number }}`,
|
|
3022
|
+
GITHUB_TOKEN: `\${{ github.token }}`
|
|
3023
|
+
}),
|
|
3024
|
+
id: FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID,
|
|
3025
|
+
name: "Discover cleanup targets",
|
|
3026
|
+
run: discoverScript(cli, flags, sweep)
|
|
3027
|
+
})])
|
|
3028
|
+
});
|
|
3029
|
+
const topology = factoryPreviewCleanupTopology({
|
|
3030
|
+
audit: { command: `${options.residueCommand} > "${RESIDUE_AFTER_PATH}" && ${cli} preview:cleanup --action audit --residue "${RESIDUE_AFTER_PATH}" --targets "$FACTORY_PREVIEW_CLEANUP_TARGETS" ${flags}` },
|
|
3031
|
+
stacks: options.stacks
|
|
3032
|
+
});
|
|
3033
|
+
if (topology.destroyJobs.some(({ jobId }) => jobId === "discover")) throw new Error("A cleanup stack's destroy job id collides with discover.");
|
|
3034
|
+
const matrixEnv = Object.freeze({
|
|
3035
|
+
FACTORY_PREVIEW_CLEANUP_HEAD_SHA: `\${{ matrix.headSha }}`,
|
|
3036
|
+
FACTORY_PREVIEW_CLEANUP_PR: `\${{ matrix.pr }}`,
|
|
3037
|
+
FACTORY_PREVIEW_CLEANUP_STACK: `\${{ matrix.stack }}`,
|
|
3038
|
+
FACTORY_PREVIEW_CLEANUP_STAGE: `\${{ matrix.stage }}`
|
|
3039
|
+
});
|
|
3040
|
+
const destroyOutput = (name) => `\${{ steps.${FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID}.outputs.${name} }}`;
|
|
3041
|
+
const destroyedIf = `always() && steps.${FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID}.outputs.outcome != ''`;
|
|
3042
|
+
const destroySteps = Object.freeze([
|
|
3043
|
+
Object.freeze({
|
|
3044
|
+
env: matrixEnv,
|
|
3045
|
+
id: FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID,
|
|
3046
|
+
name: "Destroy the stage",
|
|
3047
|
+
run: destroyScript(options.destroyCommand)
|
|
3048
|
+
}),
|
|
3049
|
+
Object.freeze({
|
|
3050
|
+
id: FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID,
|
|
3051
|
+
if: destroyedIf,
|
|
3052
|
+
name: "Mint the factory App token",
|
|
3053
|
+
uses: options.createGithubAppToken.uses,
|
|
3054
|
+
with: Object.freeze({
|
|
3055
|
+
"client-id": FACTORY_PROOF_GATE_APP_ID,
|
|
3056
|
+
"private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`
|
|
3057
|
+
})
|
|
3058
|
+
}),
|
|
3059
|
+
Object.freeze({
|
|
3060
|
+
env: Object.freeze({
|
|
3061
|
+
...matrixEnv,
|
|
3062
|
+
FACTORY_GITHUB_APP_TOKEN: `\${{ steps.${FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID}.outputs.token }}`,
|
|
3063
|
+
FACTORY_PREVIEW_CLEANUP_EVIDENCE: destroyOutput("evidence"),
|
|
3064
|
+
FACTORY_PREVIEW_CLEANUP_OUTCOME: destroyOutput("outcome"),
|
|
3065
|
+
GITHUB_TOKEN: `\${{ github.token }}`
|
|
3066
|
+
}),
|
|
3067
|
+
if: destroyedIf,
|
|
3068
|
+
name: "Record the cleanup outcome",
|
|
3069
|
+
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}`
|
|
3070
|
+
}),
|
|
3071
|
+
Object.freeze({
|
|
3072
|
+
env: Object.freeze({ FACTORY_PREVIEW_CLEANUP_OUTCOME: destroyOutput("outcome") }),
|
|
3073
|
+
if: "always()",
|
|
3074
|
+
name: "Require a passed destroy",
|
|
3075
|
+
run: "test \"$FACTORY_PREVIEW_CLEANUP_OUTCOME\" = passed"
|
|
3076
|
+
})
|
|
3077
|
+
]);
|
|
3078
|
+
const destroyJobs = topology.destroyJobs.map(({ jobId, stack }) => {
|
|
3079
|
+
const key = previewCleanupStackOutputKey(stack);
|
|
3080
|
+
return Object.freeze({
|
|
3081
|
+
concurrency: Object.freeze({
|
|
3082
|
+
cancelInProgress: false,
|
|
3083
|
+
group: concurrencyGroup
|
|
3084
|
+
}),
|
|
3085
|
+
environment: options.environment,
|
|
3086
|
+
if: `needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.has_${key} == 'true'`,
|
|
3087
|
+
jobId,
|
|
3088
|
+
jobName: `Destroy ${stack}`,
|
|
3089
|
+
needs: Object.freeze([FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID]),
|
|
3090
|
+
permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
|
|
3091
|
+
stack,
|
|
3092
|
+
steps: destroySteps,
|
|
3093
|
+
strategy: Object.freeze({
|
|
3094
|
+
failFast: false,
|
|
3095
|
+
matrix: Object.freeze({ include: `\${{ fromJSON(needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.${key}_matrix).include }}` })
|
|
3096
|
+
})
|
|
3097
|
+
});
|
|
3098
|
+
});
|
|
3099
|
+
const auditJob = Object.freeze({
|
|
3100
|
+
env: Object.freeze({ FACTORY_PREVIEW_CLEANUP_TARGETS: `\${{ needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.targets }}` }),
|
|
3101
|
+
environment: options.environment,
|
|
3102
|
+
if: `${topology.auditJob.if} && needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.result == 'success' && needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.has_targets == 'true'`,
|
|
3103
|
+
jobId: topology.auditJob.jobId,
|
|
3104
|
+
jobName: topology.auditJob.jobName,
|
|
3105
|
+
needs: Object.freeze([FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID, ...topology.auditJob.needs]),
|
|
3106
|
+
permissions: Object.freeze({ contents: "read" }),
|
|
3107
|
+
steps: topology.auditJob.steps
|
|
3108
|
+
});
|
|
3109
|
+
const on = { pull_request_target: Object.freeze({ types: Object.freeze(["closed"]) }) };
|
|
3110
|
+
if (cron !== void 0) {
|
|
3111
|
+
on.schedule = Object.freeze([Object.freeze({ cron })]);
|
|
3112
|
+
on.workflow_dispatch = Object.freeze({});
|
|
3113
|
+
}
|
|
3114
|
+
return Object.freeze({
|
|
3115
|
+
auditJob,
|
|
3116
|
+
checkoutRef: FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF,
|
|
3117
|
+
destroyJobs: Object.freeze(destroyJobs),
|
|
3118
|
+
discoverJob,
|
|
3119
|
+
on: Object.freeze(on),
|
|
3120
|
+
permissions: Object.freeze({ contents: "read" })
|
|
3121
|
+
});
|
|
3122
|
+
};
|
|
3123
|
+
//#endregion
|
|
2582
3124
|
//#region src/preview-receipt-workflow.ts
|
|
2583
3125
|
/** Receipt transport only. The consumer owns selection, lifecycle, smoke, and freshness. */
|
|
2584
3126
|
const factoryPreviewReceiptWorkflow = (options) => {
|
|
@@ -3833,4 +4375,4 @@ const assertWorkflowShellParses = (yaml, options) => {
|
|
|
3833
4375
|
throw new Error(`${options.source} emits shell bash cannot parse; the runner would treat it as a no-op:\n${detail}`);
|
|
3834
4376
|
};
|
|
3835
4377
|
//#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 };
|
|
4378
|
+
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 };
|