@kungfu-tech/buildchain 4.0.1-alpha.3 → 4.0.1-alpha.30

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.
Files changed (171) hide show
  1. package/actions/release-tail/README.md +8 -0
  2. package/architecture/ci-lane-change-budget.json +187 -0
  3. package/architecture/decisions/0002-next-development-transition.md +101 -0
  4. package/architecture/internal-capabilities.json +117 -8
  5. package/architecture/maintainability-policy.json +43 -25
  6. package/architecture/release-tail-contract-inventory.json +5 -2
  7. package/architecture/v3-core-mechanism-inventory.json +89 -0
  8. package/architecture/v4-adopter-delivery-parity.json +32 -5
  9. package/architecture/v4-capability-state-machine-manifest.json +73 -0
  10. package/architecture/v4-compatibility-facts-parity.json +77 -0
  11. package/architecture/v4-delivery-warrant-shadow-fixtures.json +15 -6
  12. package/architecture/v4-floating-consumer-policy.json +6 -0
  13. package/architecture/v4-next-development-parity.json +192 -0
  14. package/architecture/v4-publication-rehearsal-parity.json +84 -0
  15. package/architecture/v4-release-train-parity.json +1 -0
  16. package/architecture/v4-tail-reseal-parity.json +150 -0
  17. package/bin/buildchain.mjs +23 -2
  18. package/bin/internal/adopter-delivery-cli.mjs +70 -0
  19. package/bin/internal/command-registry.mjs +3 -0
  20. package/bin/internal/compatibility-facts-cli.mjs +101 -0
  21. package/contracts/fixtures/next-development-transition-v1/anchored-manual-waiting.json +47 -0
  22. package/contracts/fixtures/next-development-transition-v1/semver-auto-planned.json +47 -0
  23. package/contracts/fixtures/next-development-transition-v1/version-model-cases.json +40 -0
  24. package/contracts/fixtures/v4-adopter-delivery-v1/archive-template.json +19 -0
  25. package/contracts/fixtures/v4-adopter-delivery-v1/bootstrap-positive.json +93 -0
  26. package/contracts/fixtures/v4-adopter-delivery-v1/gate-positive.json +29 -0
  27. package/contracts/fixtures/v4-adopter-delivery-v1/gate-unknown-selector.json +26 -0
  28. package/contracts/fixtures/v4-adopter-delivery-v1/offline-vectors.json +50 -0
  29. package/contracts/fixtures/v4-compatibility-facts-v1/shared.json +1129 -0
  30. package/contracts/fixtures/v4-floating-consumer-policy-v1/cases.json +7 -1
  31. package/contracts/fixtures/v4-publication-rehearsal-v1/candidate/artifacts/product.bin +1 -0
  32. package/contracts/fixtures/v4-publication-rehearsal-v1/candidate/config/buildchain.toml +5 -0
  33. package/contracts/fixtures/v4-publication-rehearsal-v1/candidate/documents/release-activation.json +1 -0
  34. package/contracts/fixtures/v4-publication-rehearsal-v1/candidate/documents/signed-channel.json +1 -0
  35. package/contracts/fixtures/v4-publication-rehearsal-v1/candidate/evidence/qualification.json +1 -0
  36. package/contracts/fixtures/v4-publication-rehearsal-v1/candidate/manifests/candidate.json +5 -0
  37. package/contracts/fixtures/v4-publication-rehearsal-v1/candidate/manifests/release-passport.json +1 -0
  38. package/contracts/fixtures/v4-publication-rehearsal-v1/capsule.json +707 -0
  39. package/contracts/fixtures/v4-publication-rehearsal-v1/offline-vectors.json +27 -0
  40. package/contracts/fixtures/v4-tail-reseal-v1/valid.json +229 -0
  41. package/contracts/next-development-request-v1.schema.json +66 -0
  42. package/contracts/next-development-transition-v1.schema.json +292 -0
  43. package/contracts/v4-adopter-delivery-v1.schema.json +81 -0
  44. package/contracts/v4-compatibility-facts-v1.schema.json +230 -0
  45. package/contracts/v4-floating-consumer-policy-receipt-v1.schema.json +4 -2
  46. package/contracts/v4-publication-rehearsal-capsule-v1.schema.json +233 -0
  47. package/contracts/v4-tail-reseal-v1.schema.json +276 -0
  48. package/dist/site/agent-index.json +4 -0
  49. package/dist/site/artifact-schemas.json +8 -0
  50. package/dist/site/buildchain-contract.json +1393 -28
  51. package/dist/site/buildchain-site.json +477 -32
  52. package/dist/site/capability-registry.json +17 -14
  53. package/dist/site/cli-registry.json +159 -1
  54. package/dist/site/kfd-claims.json +455 -15
  55. package/dist/site/kfd-upstream-aggregate.json +1 -1
  56. package/dist/site/manual-registry.json +53 -7
  57. package/dist/site/node-api-registry.json +13921 -9565
  58. package/dist/site/page-registry.json +442 -21
  59. package/dist/site/public-surface-audit.json +440 -11
  60. package/dist/site/publication-authority-registry.json +44 -8
  61. package/dist/site/publication-registry.json +4 -4
  62. package/dist/site/release-provenance.json +22 -0
  63. package/dist/site/schemas/release-tail-capabilities-v1.schema.json +199 -0
  64. package/dist/site/schemas/v4-adopter-delivery-v1.schema.json +81 -0
  65. package/dist/site/schemas/v4-compatibility-facts-v1.schema.json +230 -0
  66. package/dist/site/schemas/v4-publication-rehearsal-capsule-v1.schema.json +233 -0
  67. package/dist/site/site-manifest.json +35 -11
  68. package/dist/site/workflow-registry.json +142 -8
  69. package/docs/MAP.md +7 -2
  70. package/docs/cli-reference.md +193 -0
  71. package/docs/cli.md +8 -0
  72. package/docs/dev-alpha-candidate-patrol.md +8 -0
  73. package/docs/dev-delivery-warrant.md +30 -5
  74. package/docs/next-development-transition.md +118 -0
  75. package/docs/node-api-reference.md +578 -285
  76. package/docs/release-candidate.md +7 -0
  77. package/docs/release-tail-provider-plane.md +30 -0
  78. package/docs/v4-adopter-delivery.md +133 -0
  79. package/docs/v4-compatibility-facts.md +91 -0
  80. package/docs/v4-publication-rehearsal.md +130 -0
  81. package/docs/v4-tail-reseal.md +73 -0
  82. package/docs/versioning.md +4 -3
  83. package/package.json +30 -6
  84. package/packages/core/adopter-delivery-passport.js +259 -0
  85. package/packages/core/adopter-delivery-vectors.js +158 -0
  86. package/packages/core/adopter-delivery-vectors.json +77 -0
  87. package/packages/core/buildchain-agent-manuals.js +3 -0
  88. package/packages/core/buildchain-compatibility-authority.js +336 -0
  89. package/packages/core/buildchain-compatibility-fact.js +394 -0
  90. package/packages/core/buildchain-compatibility-facts.json +217 -0
  91. package/packages/core/buildchain-compatibility-proof.js +566 -0
  92. package/packages/core/buildchain-config.js +84 -0
  93. package/packages/core/buildchain-contract.js +93 -141
  94. package/packages/core/buildchain-delivery-bootstrap.js +240 -0
  95. package/packages/core/buildchain-delivery-infrastructure.js +164 -0
  96. package/packages/core/buildchain-delivery-self-dogfood.js +395 -0
  97. package/packages/core/buildchain-publication-authority.js +1 -0
  98. package/packages/core/channel-candidate.js +8 -0
  99. package/packages/core/channel-promotion-baseline.js +55 -0
  100. package/packages/core/ci-lane-change-budget.js +247 -0
  101. package/packages/core/dev-alpha-candidate-selection.js +10 -2
  102. package/packages/core/dev-delivery-execution-transfer.js +21 -1
  103. package/packages/core/dev-delivery-native-proof.js +43 -27
  104. package/packages/core/dev-delivery-process-boundary.js +19 -7
  105. package/packages/core/dev-delivery-provider-heartbeat.js +18 -6
  106. package/packages/core/dev-delivery-warrant-state.js +32 -10
  107. package/packages/core/dev-delivery-warrant.js +9 -3
  108. package/packages/core/github-governance-authority.js +1 -0
  109. package/packages/core/index.js +5 -0
  110. package/packages/core/kungfu-temporal-fact.js +557 -0
  111. package/packages/core/legacy-kfd-adopter-driver.js +167 -0
  112. package/packages/core/next-development-candidate-reservation.js +186 -0
  113. package/packages/core/next-development-controller.js +728 -0
  114. package/packages/core/next-development-projection.js +287 -0
  115. package/packages/core/next-development-transition.js +738 -0
  116. package/packages/core/paper-agent-entry.js +11 -5
  117. package/packages/core/paper.js +16 -5
  118. package/packages/core/published-delivery-authority.js +266 -0
  119. package/packages/core/release-candidate-recovery.js +70 -15
  120. package/packages/core/release-candidate.js +2 -2
  121. package/packages/core/release-passport.js +36 -9
  122. package/packages/core/v4-adopter-delivery-parity.js +3 -3
  123. package/packages/core/v4-adopter-delivery.js +359 -0
  124. package/packages/core/v4-canonical-contracts.js +5 -0
  125. package/packages/core/v4-delivery-warrant-read-candidate.js +10 -3
  126. package/packages/core/v4-floating-consumer-evidence.js +18 -4
  127. package/packages/core/v4-floating-consumer-policy.js +143 -20
  128. package/packages/core/v4-floating-consumer-release-passport.js +35 -8
  129. package/packages/core/v4-publication-rehearsal-capsule.js +468 -0
  130. package/packages/core/v4-publication-rehearsal-provider-bindings.js +212 -0
  131. package/packages/core/v4-publication-rehearsal.js +481 -0
  132. package/packages/core/v4-tail-reseal-contract.js +26 -0
  133. package/packages/core/v4-tail-reseal-github.js +178 -0
  134. package/packages/core/v4-tail-reseal-receipt.js +225 -0
  135. package/packages/core/v4-tail-reseal.js +594 -0
  136. package/packages/core/workflow-yaml-contract.js +24 -2
  137. package/scripts/artifact-signing-controller-core.mjs +1 -1
  138. package/scripts/buildchain-cli-help.mjs +30 -0
  139. package/scripts/check-ci-lane-change-budget.mjs +100 -0
  140. package/scripts/check-inventory.mjs +14 -3
  141. package/scripts/check-v4-floating-consumer-policy-contract.mjs +23 -4
  142. package/scripts/dev-alpha-candidate-patrol.mjs +22 -1
  143. package/scripts/dev-delivery-source-proof-replay.mjs +153 -0
  144. package/scripts/dev-delivery-source-proof-reuse.mjs +13 -97
  145. package/scripts/dev-delivery-warrant-store.mjs +10 -6
  146. package/scripts/dev-delivery-warrant.mjs +5 -1
  147. package/scripts/dev-pr-auto-merge.mjs +1 -1
  148. package/scripts/dev-pr-delivery-warrant.mjs +1 -0
  149. package/scripts/dev-pr-prequeue-guard.mjs +0 -18
  150. package/scripts/dev-qualification-patrol.mjs +9 -9
  151. package/scripts/dispatch-artifact-signing-authority.mjs +1 -1
  152. package/scripts/generate-channel-promotion-workflow.mjs +2 -2
  153. package/scripts/generate-next-development-guidance.mjs +49 -0
  154. package/scripts/generate-release-candidate-passport.mjs +152 -0
  155. package/scripts/generate-site-bundle.mjs +46 -3
  156. package/scripts/init-repo.mjs +22 -4
  157. package/scripts/next-development-self-dogfood-harness.mjs +460 -0
  158. package/scripts/next-development-self-dogfood.mjs +597 -0
  159. package/scripts/next-development-transition.mjs +47 -0
  160. package/scripts/promotion-channel-router.mjs +4 -4
  161. package/scripts/release-candidate-anchor-provenance.mjs +99 -0
  162. package/scripts/release-tail.mjs +51 -3
  163. package/scripts/release-train-self-dogfood.mjs +94 -92
  164. package/scripts/resume-from-candidate-run.mjs +560 -30
  165. package/scripts/site-capability-metadata.mjs +29 -0
  166. package/scripts/stable-candidate-qualification.mjs +9 -10
  167. package/scripts/v4-consumer-policy.mjs +5 -5
  168. package/scripts/v4-publication-rehearsal-fixture.mjs +144 -0
  169. package/scripts/v4-tail-reseal-macos-rehearsal.mjs +134 -0
  170. package/scripts/v4-tail-reseal.mjs +416 -0
  171. package/templates/native-dev-delivery.yml +2 -0
@@ -3,9 +3,13 @@ import crypto from "node:crypto";
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
- import { pathToFileURL } from "node:url";
6
+ import { execFileSync } from "node:child_process";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
8
 
8
9
  import { writeGitHubOutputs } from "./build-contract-core.mjs";
10
+ import { compareSemver } from "./publication-registry-hydrate.mjs";
11
+ import { normalizeAnchorProvenance, normalizeCandidateRun, recoverCandidateProvenance } from "./release-candidate-anchor-provenance.mjs";
12
+ export { resolveAnchorRecoveryRequest } from "./release-candidate-anchor-provenance.mjs";
9
13
  import {
10
14
  generatePublishRequiredArtifacts,
11
15
  githubDownload,
@@ -27,6 +31,15 @@ import {
27
31
  } from "../packages/core/publication-artifact-candidate.js";
28
32
  import { createPublicationSealedBundle } from "../packages/core/publication-sealed-bundle.js";
29
33
  import { releaseTransactionStateRef } from "../packages/core/publish-transaction.js";
34
+ import { v4ContentRoot } from "../packages/core/v4-canonical-contracts.js";
35
+ import { validateV4StageCapsule } from "../packages/core/v4-stage-capsule.js";
36
+ import {
37
+ authorizeV4RuntimeSelection,
38
+ createV4RuntimeResumeLineage,
39
+ scanV4RuntimeSelectorPersistence,
40
+ v4RuntimeResumeDocumentRoot,
41
+ verifyV4RuntimeAuthorizationReceipt,
42
+ } from "../packages/core/v4-runtime-ref-resume-authority.js";
30
43
 
31
44
  function env(name, fallback = "") {
32
45
  return process.env[name] || fallback;
@@ -99,8 +112,376 @@ function readOnlyJson(files, label) {
99
112
  return JSON.parse(fs.readFileSync(files[0].absolutePath, "utf8"));
100
113
  }
101
114
 
102
- async function readExistingTransaction({ repoInfo, apiUrl, token, fetchImpl, version }) {
103
- const stateRef = releaseTransactionStateRef(version);
115
+ export function trackedRuntimePersistenceScan({
116
+ runtimeRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."),
117
+ } = {}) {
118
+ const paths = execFileSync(
119
+ "git",
120
+ ["-C", runtimeRoot, "ls-files", ".github/workflows", ".github/actions", ".buildchain"],
121
+ { encoding: "utf8" },
122
+ )
123
+ .split(/\r?\n/)
124
+ .filter((entry) => /\.(?:json|toml|ya?ml)$/u.test(entry));
125
+ return scanV4RuntimeSelectorPersistence({ root: runtimeRoot, paths });
126
+ }
127
+
128
+ export function verifyReleaseCandidateStageCapsules({ sidecar, passport, downloads }) {
129
+ if (
130
+ !sidecar ||
131
+ sidecar.contract !==
132
+ "kungfu-buildchain-v4-release-candidate-stage-capsules/v1" ||
133
+ sidecar.status !== "sealed"
134
+ ) {
135
+ throw new Error(
136
+ "cross-runtime recovery requires original sealed release-candidate Stage Capsules",
137
+ );
138
+ }
139
+ const payload = { ...sidecar };
140
+ delete payload.root;
141
+ const expectedAttempt =
142
+ `github-run:${passport.workflow.runId}:attempt:${passport.workflow.runAttempt}`;
143
+ if (
144
+ sidecar.root !== v4RuntimeResumeDocumentRoot(payload) ||
145
+ sidecar.repository !== passport.repository ||
146
+ sidecar.source?.sha !== passport.source.headSha ||
147
+ sidecar.source?.treeSha !== passport.source.treeHash ||
148
+ sidecar.buildAttempt?.id !== expectedAttempt ||
149
+ sidecar.buildAttempt?.runtimeSha !== passport.buildchain.sha ||
150
+ sidecar.consumerPolicyReceiptRoot !== passport.consumerPolicy?.receiptRoot
151
+ ) {
152
+ throw new Error("release-candidate Stage Capsule sidecar identity mismatch");
153
+ }
154
+ const artifactByName = new Map(downloads.map((entry) => [entry.artifact.name, entry]));
155
+ const required = [...passport.platformMatrix.map((entry) => entry.platformId)].sort();
156
+ const entries = [...(sidecar.capsules || [])].sort((left, right) =>
157
+ left.platform.localeCompare(right.platform),
158
+ );
159
+ if (
160
+ entries.length !== required.length ||
161
+ entries.some((entry, index) => entry.platform !== required[index])
162
+ ) {
163
+ throw new Error("release-candidate Stage Capsule platform set is incomplete");
164
+ }
165
+ return entries.map((entry) => {
166
+ validateV4StageCapsule(entry.capsule);
167
+ const download = artifactByName.get(entry.artifactName);
168
+ const artifact = entry.artifact;
169
+ if (
170
+ !download ||
171
+ artifact?.platformId !== entry.platform ||
172
+ artifact?.id !== String(download.artifact.id) ||
173
+ artifact?.name !== download.artifact.name ||
174
+ artifact?.digest !== entry.artifactDigest ||
175
+ artifact?.digest !== download.artifact.digest ||
176
+ artifact?.digest !== download.record.digest ||
177
+ artifact?.digest !== download.record.downloadedDigest ||
178
+ artifact?.expiresAt !==
179
+ new Date(download.artifact.expires_at).toISOString() ||
180
+ entry.capsule.identity.policyRoot !== sidecar.consumerPolicyReceiptRoot ||
181
+ entry.capsule.identity.sourceRoot !==
182
+ v4ContentRoot("candidate-identity", passport.source) ||
183
+ entry.capsule.identity.runtimeRoot !==
184
+ v4ContentRoot("candidate-identity", { sha: passport.buildchain.sha })
185
+ ) {
186
+ throw new Error(
187
+ `Stage Capsule ${entry.platform} does not bind the verified provider artifact`,
188
+ );
189
+ }
190
+ return {
191
+ platform: entry.platform,
192
+ capsuleRoot: entry.capsule.capsuleRoot,
193
+ identityRoot: entry.capsule.identityRoot,
194
+ artifactDigest: entry.artifactDigest,
195
+ sourceSha: sidecar.source.sha,
196
+ sourceTreeSha: sidecar.source.treeSha,
197
+ policyRoot: sidecar.consumerPolicyReceiptRoot,
198
+ buildRuntimeSha: sidecar.buildAttempt.runtimeSha,
199
+ sealed: true,
200
+ };
201
+ });
202
+ }
203
+
204
+ export function validateV4RuntimeResumePublicReadback({
205
+ targetRef,
206
+ targetSha,
207
+ targetVersion,
208
+ alphaSha,
209
+ exactTagSha,
210
+ tagLineage,
211
+ runtimeLineage,
212
+ floatingTargetLineage,
213
+ runtimeSha,
214
+ version,
215
+ transaction,
216
+ main,
217
+ npm,
218
+ }) {
219
+ const channelVersion = npm["dist-tags"]?.alpha;
220
+ let channelDidNotRegress = false;
221
+ try {
222
+ channelDidNotRegress = compareSemver(channelVersion, version) >= 0;
223
+ } catch { channelDidNotRegress = false; }
224
+ if (
225
+ transaction?.target_ref !== targetRef ||
226
+ transaction?.version !== version ||
227
+ exactTagSha !== transaction?.source_sha ||
228
+ !["ahead", "identical"].includes(tagLineage?.status) ||
229
+ !["ahead", "identical"].includes(runtimeLineage?.status) ||
230
+ !["ahead", "identical"].includes(floatingTargetLineage?.status) ||
231
+ !alphaSha ||
232
+ !targetSha ||
233
+ !runtimeSha ||
234
+ channelVersion !== targetVersion ||
235
+ !channelDidNotRegress ||
236
+ !npm.versions?.[channelVersion]?.dist?.integrity ||
237
+ npm.versions?.[version]?.dist?.integrity !== main.digest
238
+ ) {
239
+ throw new Error(
240
+ "cross-runtime final public readback does not match durable publication bytes and runtime",
241
+ );
242
+ }
243
+ }
244
+
245
+ export async function readPublicResumeState({
246
+ repoInfo,
247
+ targetRef,
248
+ runtimeSha,
249
+ version,
250
+ transaction,
251
+ token,
252
+ apiUrl,
253
+ fetchImpl,
254
+ }) {
255
+ const readRef = async (ref) => (await githubJson({ apiUrl, token, fetchImpl,
256
+ path: `/repos/${repoInfo.owner}/${repoInfo.repo}/git/ref/${ref}` })).object?.sha || "";
257
+ const main = transaction?.artifacts?.find((entry) => entry.kind === "npm" && entry.required !== false);
258
+ if (!main || main.ref !== version || !main.digest)
259
+ throw new Error("cross-runtime recovery requires exact durable npm publication evidence");
260
+ const packageUrl = `https://registry.npmjs.org/${encodeURIComponent(main.name)}`;
261
+ const exactTag = transaction.exact_tag || `v${version}`;
262
+ const [targetSha, alphaSha, exactTagSha, npmResponse] = await Promise.all([
263
+ readRef(`heads/${targetRef}`),
264
+ readRef("tags/v4-alpha"),
265
+ readRef(`tags/${exactTag}`),
266
+ fetchImpl(packageUrl),
267
+ ]);
268
+ if (!npmResponse.ok) {
269
+ throw new Error(`npm public readback failed with HTTP ${npmResponse.status}`);
270
+ }
271
+ const npm = await npmResponse.json();
272
+ const [tagLineage, runtimeLineage, floatingTargetLineage, targetPackageFile] = await Promise.all([
273
+ githubJson({ apiUrl, token, fetchImpl, path: `/repos/${repoInfo.owner}/${repoInfo.repo}/compare/${exactTagSha}...${targetSha}` }),
274
+ githubJson({ apiUrl, token, fetchImpl, path: `/repos/${repoInfo.owner}/${repoInfo.repo}/compare/${runtimeSha}...${alphaSha}` }),
275
+ githubJson({ apiUrl, token, fetchImpl, path: `/repos/${repoInfo.owner}/${repoInfo.repo}/compare/${alphaSha}...${targetSha}` }),
276
+ githubJson({ apiUrl, token, fetchImpl, path: `/repos/${repoInfo.owner}/${repoInfo.repo}/contents/package.json?ref=${encodeURIComponent(targetSha)}` }),
277
+ ]);
278
+ if (targetPackageFile?.type !== "file" || targetPackageFile.encoding !== "base64" || !targetPackageFile.content)
279
+ throw new Error("cross-runtime recovery requires protected target version state");
280
+ const targetVersion = JSON.parse(Buffer.from(String(targetPackageFile.content).replace(/\s/g, ""), "base64").toString("utf8")).version;
281
+ validateV4RuntimeResumePublicReadback({ targetRef, targetSha, targetVersion, alphaSha,
282
+ exactTagSha, tagLineage, runtimeLineage, floatingTargetLineage, runtimeSha,
283
+ version, transaction, main, npm });
284
+ const body = {
285
+ schemaVersion: 1,
286
+ contract: "kungfu-buildchain-v4-runtime-resume-public-readback/v1",
287
+ observedAt: new Date().toISOString(),
288
+ repository: repoInfo.fullName,
289
+ version,
290
+ refs: {
291
+ target: { ref: targetRef, sha: targetSha },
292
+ floating: { ref: "v4-alpha", sha: alphaSha },
293
+ exactTag: { ref: exactTag, sha: exactTagSha },
294
+ },
295
+ npm: {
296
+ package: main.name,
297
+ version,
298
+ distTag: "alpha",
299
+ integrity: npm.versions[version].dist.integrity,
300
+ targetVersion, distTagVersion: npm["dist-tags"].alpha,
301
+ distTagIntegrity: npm.versions[npm["dist-tags"].alpha].dist.integrity,
302
+ },
303
+ };
304
+ return { ...body, root: v4RuntimeResumeDocumentRoot(body) };
305
+ }
306
+
307
+ export const resolveV4RuntimeResumePublicRuntimeSha = (material) =>
308
+ material?.buildAttempt?.runtimeSha || "";
309
+
310
+ function prepareRuntimeResumeEvidence({
311
+ repoInfo,
312
+ targetRef,
313
+ runtimeSha,
314
+ version,
315
+ passport,
316
+ sidecar,
317
+ stageCapsules,
318
+ recovery,
319
+ outputDir,
320
+ }) {
321
+ const authorizationPath = path.resolve(".buildchain/release-candidate/v4-runtime-authorization.json");
322
+ const delegatedRaw = env("BUILDCHAIN_RUNTIME_AUTHORIZATION_JSON").trim();
323
+ const delegatedRoot = env("BUILDCHAIN_RUNTIME_AUTHORIZATION_ROOT").trim();
324
+ const authorizationFileExists = fs.existsSync(authorizationPath);
325
+ if (!authorizationFileExists && (!delegatedRaw || !delegatedRoot)) throw new Error("cross-runtime recovery requires a fresh runtime authorization receipt");
326
+ const delegated = authorizationFileExists ? readOnlyJson([{ absolutePath: authorizationPath }], "runtime authorization") : JSON.parse(delegatedRaw);
327
+ if (!authorizationFileExists && delegated.receiptRoot !== delegatedRoot) throw new Error("fresh recovery runtime authorization handoff root mismatch");
328
+ const delegatedVerification = verifyV4RuntimeAuthorizationReceipt({
329
+ receipt: delegated.receipt,
330
+ receiptRoot: delegated.receiptRoot,
331
+ repository: repoInfo.fullName,
332
+ runtimeSha,
333
+ });
334
+ if (!delegatedVerification.ok) {
335
+ throw new Error(
336
+ `fresh recovery runtime authorization rejected: ${delegatedVerification.failures.join(", ")}`,
337
+ );
338
+ }
339
+ const policy = passport.consumerPolicy.receipt;
340
+ const authorization = authorizeV4RuntimeSelection({
341
+ repository: repoInfo.fullName,
342
+ eventName: "workflow_dispatch",
343
+ mode: "resume",
344
+ actor: delegated.receipt.actor.login,
345
+ actorPermission: delegated.receipt.actor.permission,
346
+ reason:
347
+ `resume sealed candidate run ${passport.workflow.runId} from a tree-equivalent protected source`,
348
+ authorizedAt: new Date().toISOString(),
349
+ sourceSha: sidecar.source.sha,
350
+ sourceTreeSha: sidecar.source.treeSha,
351
+ requestedRef: delegated.receipt.request.ref,
352
+ resolvedRuntimeSha: runtimeSha,
353
+ approvedRefReadbacks: delegated.receipt.runtime.reachableFrom,
354
+ stableContractLockRoot: policy.contractLocks.stable.root,
355
+ alphaContractLockRoot: policy.contractLocks.alpha.root,
356
+ consumerPolicyReceiptRoot: sidecar.consumerPolicyReceiptRoot,
357
+ persistenceScan: trackedRuntimePersistenceScan(),
358
+ });
359
+ const planBody = {
360
+ schemaVersion: 1,
361
+ contract: "kungfu-buildchain-v4-runtime-resume-plan/v1",
362
+ originalRunId: String(passport.workflow.runId),
363
+ resumeRunId: String(env("GITHUB_RUN_ID")),
364
+ recoveryReceiptRoot: recovery.receipt.root,
365
+ requiredPlatforms: stageCapsules.map((entry) => entry.platform),
366
+ reusedCapsuleRoots: stageCapsules.map((entry) => entry.capsuleRoot),
367
+ rebuildPlatforms: [],
368
+ skippedBuildStages: recovery.receipt.skippedBuildStages,
369
+ };
370
+ const plan = { ...planBody, root: v4RuntimeResumeDocumentRoot(planBody) };
371
+ const materialBody = {
372
+ schemaVersion: 1,
373
+ contract: "kungfu-buildchain-v4-runtime-resume-material/v1",
374
+ repository: repoInfo.fullName,
375
+ targetRef,
376
+ runtimeSha,
377
+ version,
378
+ authorization: authorization.receipt,
379
+ authorizationRoot: authorization.receiptRoot,
380
+ buildAttempt: sidecar.buildAttempt,
381
+ resumeAttempt: {
382
+ id: `github-run:${env("GITHUB_RUN_ID")}:attempt:${env("GITHUB_RUN_ATTEMPT", "1")}`,
383
+ runtimeSha,
384
+ },
385
+ source: sidecar.source,
386
+ consumerPolicyReceiptRoot: sidecar.consumerPolicyReceiptRoot,
387
+ requiredPlatforms: stageCapsules.map((entry) => entry.platform),
388
+ stageCapsules,
389
+ resumePlanRoot: plan.root,
390
+ floatingRefBefore: {
391
+ ref: "v4-alpha",
392
+ sha: sidecar.buildAttempt.runtimeSha,
393
+ },
394
+ };
395
+ const material = {
396
+ ...materialBody,
397
+ root: v4RuntimeResumeDocumentRoot(materialBody),
398
+ };
399
+ for (const [name, value] of [
400
+ ["v4-runtime-resume-plan.json", plan],
401
+ ["v4-runtime-resume-material.json", material],
402
+ ]) {
403
+ fs.writeFileSync(
404
+ path.join(outputDir, name),
405
+ `${JSON.stringify(value, null, 2)}\n`,
406
+ );
407
+ }
408
+ return path.join(outputDir, "v4-runtime-resume-evidence.json");
409
+ }
410
+
411
+ export async function finalizeRuntimeResumeEvidence({
412
+ materialPath,
413
+ transaction,
414
+ token = env("GITHUB_TOKEN", env("INPUT_TOKEN")),
415
+ apiUrl = env("GITHUB_API_URL", "https://api.github.com"),
416
+ fetchImpl = globalThis.fetch,
417
+ outputDir = path.dirname(materialPath),
418
+ }) {
419
+ const material = JSON.parse(fs.readFileSync(materialPath, "utf8"));
420
+ const body = { ...material };
421
+ delete body.root;
422
+ if (
423
+ material.contract !== "kungfu-buildchain-v4-runtime-resume-material/v1" ||
424
+ material.root !== v4RuntimeResumeDocumentRoot(body)
425
+ ) {
426
+ throw new Error("cross-runtime resume material root mismatch");
427
+ }
428
+ const repoInfo = splitRepository(material.repository);
429
+ const version = env("BUILDCHAIN_RELEASE_VERSION", material.version);
430
+ const targetRef = env("BUILDCHAIN_RELEASE_TARGET_REF", material.targetRef);
431
+ if (
432
+ version !== material.version ||
433
+ targetRef !== material.targetRef ||
434
+ transaction?.version !== version ||
435
+ transaction?.state !== "complete"
436
+ ) {
437
+ throw new Error(
438
+ "cross-runtime resume finalization does not match the completed publication transaction",
439
+ );
440
+ }
441
+ const readback = await readPublicResumeState({
442
+ repoInfo,
443
+ targetRef,
444
+ runtimeSha: resolveV4RuntimeResumePublicRuntimeSha(material),
445
+ version,
446
+ transaction,
447
+ token,
448
+ apiUrl,
449
+ fetchImpl,
450
+ });
451
+ const resumed = createV4RuntimeResumeLineage({
452
+ authorization: material.authorization,
453
+ authorizationRoot: material.authorizationRoot,
454
+ buildAttempt: material.buildAttempt,
455
+ resumeAttempt: material.resumeAttempt,
456
+ source: material.source,
457
+ consumerPolicyReceiptRoot: material.consumerPolicyReceiptRoot,
458
+ requiredPlatforms: material.requiredPlatforms,
459
+ stageCapsules: material.stageCapsules,
460
+ resumePlanRoot: material.resumePlanRoot,
461
+ finalPublicReadbackRoot: readback.root,
462
+ floatingRefBefore: material.floatingRefBefore,
463
+ floatingRefAfter: { ref: "v4-alpha", sha: readback.refs.floating.sha },
464
+ });
465
+ const evidence = {
466
+ authorization: material.authorization,
467
+ authorizationRoot: material.authorizationRoot,
468
+ lineage: resumed.lineage,
469
+ lineageRoot: resumed.lineageRoot,
470
+ };
471
+ const evidencePath = path.join(outputDir, "v4-runtime-resume-evidence.json");
472
+ for (const [name, value] of [
473
+ ["v4-runtime-resume-public-readback.json", readback],
474
+ [path.basename(evidencePath), evidence],
475
+ ]) {
476
+ fs.writeFileSync(
477
+ path.join(outputDir, name),
478
+ `${JSON.stringify(value, null, 2)}\n`,
479
+ );
480
+ }
481
+ return { evidence, path: evidencePath, readback };
482
+ }
483
+
484
+ async function readTransactionAtRef({ repoInfo, apiUrl, token, fetchImpl, stateRef }) {
104
485
  const response = await githubJson({
105
486
  apiUrl,
106
487
  token,
@@ -109,10 +490,65 @@ async function readExistingTransaction({ repoInfo, apiUrl, token, fetchImpl, ver
109
490
  path: `/repos/${repoInfo.owner}/${repoInfo.repo}/contents/state.json?ref=${encodeURIComponent(stateRef)}`,
110
491
  });
111
492
  if (!response) return undefined;
112
- if (response.type !== "file" || response.encoding !== "base64" || !response.content) {
113
- throw new Error(`durable transaction ${stateRef} did not expose a base64 state.json file`);
493
+ if (
494
+ response.type !== "file" ||
495
+ response.encoding !== "base64" ||
496
+ !response.content
497
+ ) {
498
+ throw new Error(
499
+ `durable transaction ${stateRef} did not expose a base64 state.json file`,
500
+ );
114
501
  }
115
- return JSON.parse(Buffer.from(String(response.content).replace(/\s/g, ""), "base64").toString("utf8"));
502
+ return JSON.parse(
503
+ Buffer.from(
504
+ String(response.content).replace(/\s/g, ""),
505
+ "base64",
506
+ ).toString("utf8"),
507
+ );
508
+ }
509
+
510
+ async function readExistingTransaction({
511
+ repoInfo,
512
+ apiUrl,
513
+ token,
514
+ fetchImpl,
515
+ version,
516
+ }) {
517
+ return readTransactionAtRef({
518
+ repoInfo,
519
+ apiUrl,
520
+ token,
521
+ fetchImpl,
522
+ stateRef: releaseTransactionStateRef(version),
523
+ });
524
+ }
525
+
526
+ async function readExistingTransactionById({
527
+ repoInfo,
528
+ apiUrl,
529
+ token,
530
+ fetchImpl,
531
+ transactionId,
532
+ }) {
533
+ if (!transactionId) return undefined;
534
+ const statePrefix = "buildchain/release-state/";
535
+ const refs = await githubJson({
536
+ apiUrl,
537
+ token,
538
+ fetchImpl,
539
+ path: `/repos/${repoInfo.owner}/${repoInfo.repo}/git/matching-refs/heads/${statePrefix}`,
540
+ });
541
+ for (const ref of refs) {
542
+ const transaction = await readTransactionAtRef({
543
+ repoInfo,
544
+ apiUrl,
545
+ token,
546
+ fetchImpl,
547
+ stateRef: String(ref.ref).replace(/^refs\/heads\//, ""),
548
+ });
549
+ if (transaction?.id === transactionId) return transaction;
550
+ }
551
+ throw new Error(`durable publication transaction ${transactionId} was not found`);
116
552
  }
117
553
 
118
554
  function outputPath(filePath) {
@@ -349,6 +785,14 @@ async function recoverCandidateEvidence({
349
785
  for (const artifact of [selected.passport, selected.summary]) initialDownloads.push(await downloadArtifact({ artifact, repoInfo, apiUrl, token, archiveDir, bundleRoot, fetchImpl }));
350
786
  const passport = readOnlyJson(initialDownloads[0].files.filter((file) => path.basename(file.path) === "release-candidate-passport.json"), "release-candidate-passport.json");
351
787
  const buildSummary = readOnlyJson(initialDownloads[1].files.filter((file) => path.basename(file.path) === "build-summary.json"), "build-summary.json");
788
+ const sidecarFiles = initialDownloads[0].files.filter(
789
+ (file) =>
790
+ path.basename(file.path) === "release-candidate-stage-capsules.json",
791
+ );
792
+ const stageCapsuleSidecar =
793
+ sidecarFiles.length === 1
794
+ ? readOnlyJson(sidecarFiles, "release-candidate-stage-capsules.json")
795
+ : undefined;
352
796
  const { names: requiredNames, publicationNames } = candidateArtifactNames({ passport, selected, artifacts, artifactPatterns });
353
797
  const chosen = artifacts.filter((artifact) => requiredNames.has(artifact.name));
354
798
  if (chosen.length !== requiredNames.size) {
@@ -360,7 +804,7 @@ async function recoverCandidateEvidence({
360
804
  for (const artifact of chosen.filter((entry) => ![selected.passport.id, selected.summary.id].includes(entry.id))) downloads.push(await downloadArtifact({ artifact, repoInfo, apiUrl, token, archiveDir, bundleRoot, fetchImpl }));
361
805
  return {
362
806
  run, workflow, selected, resolvedOutput, bundleRoot, initialDownloads,
363
- passport, buildSummary, chosen, downloads, publicationNames,
807
+ passport, buildSummary, stageCapsuleSidecar, chosen, downloads, publicationNames,
364
808
  };
365
809
  }
366
810
 
@@ -370,6 +814,51 @@ async function resolveTargetAdvance({ observedTargetSha, targetSha, transactionI
370
814
  return { status: comparison.status, mergeIsAncestor: ["ahead", "identical"].includes(comparison.status) };
371
815
  }
372
816
 
817
+ export async function resolveRecoveryTransaction({
818
+ repoInfo,
819
+ apiUrl,
820
+ token,
821
+ fetchImpl,
822
+ transactionId,
823
+ publicationVersion,
824
+ }) {
825
+ let transaction = publicationVersion
826
+ ? await readExistingTransaction({
827
+ repoInfo,
828
+ apiUrl,
829
+ token,
830
+ fetchImpl,
831
+ version: publicationVersion,
832
+ })
833
+ : undefined;
834
+ if (!transaction) {
835
+ transaction = await readExistingTransactionById({
836
+ repoInfo, apiUrl, token, fetchImpl, transactionId,
837
+ });
838
+ }
839
+ return { version: transaction?.version || publicationVersion, transaction };
840
+ }
841
+
842
+ function resolveRecoveredStageCapsules({
843
+ candidateRuntimeSha,
844
+ runtimeSha,
845
+ sidecar,
846
+ passport,
847
+ downloads,
848
+ }) {
849
+ if (candidateRuntimeSha === runtimeSha) return [];
850
+ return verifyReleaseCandidateStageCapsules({ sidecar, passport, downloads });
851
+ }
852
+
853
+ function validateRecoveryCoordinates(candidateRunId, expectedSourceTree, expectedCandidateRoot) {
854
+ const runId = String(candidateRunId || "").trim();
855
+ if (!/^\d+$/.test(runId)) throw new Error("candidate run ID must be numeric");
856
+ if (!String(expectedSourceTree || "").trim() && !String(expectedCandidateRoot || "").trim()) {
857
+ throw new Error("candidate recovery requires expectedSourceTree or expectedCandidateRoot");
858
+ }
859
+ return runId;
860
+ }
861
+
373
862
  export async function resumeFromCandidateRun({
374
863
  repository, targetRepository = repository, candidateRunId,
375
864
  expectedWorkflowFile, expectedWorkflowName,
@@ -384,21 +873,23 @@ export async function resumeFromCandidateRun({
384
873
  recoveryRunId = env("GITHUB_RUN_ID"), fetchImpl = globalThis.fetch,
385
874
  } = {}) {
386
875
  const repoInfo = splitRepository(repository);
387
- const runId = String(candidateRunId || "").trim();
388
- if (!/^\d+$/.test(runId)) throw new Error("candidate run ID must be numeric");
389
- if (!String(expectedSourceTree || "").trim() && !String(expectedCandidateRoot || "").trim()) {
390
- throw new Error("candidate recovery requires expectedSourceTree or expectedCandidateRoot");
391
- }
876
+ const runId = validateRecoveryCoordinates(candidateRunId, expectedSourceTree, expectedCandidateRoot);
392
877
  const archiveDir = fs.mkdtempSync(path.join(os.tmpdir(), "buildchain-resume-"));
393
878
  try {
394
879
  const {
395
880
  run, workflow, selected, resolvedOutput, bundleRoot, initialDownloads,
396
- passport, buildSummary, chosen, downloads, publicationNames,
881
+ passport, buildSummary, stageCapsuleSidecar, chosen, downloads, publicationNames,
397
882
  } = await recoverCandidateEvidence({
398
883
  repoInfo, runId, artifactName, artifactPatterns, requiredArtifactCount,
399
884
  outputDir, apiUrl, token, fetchImpl, archiveDir,
400
885
  });
401
- const prNumber = Number(passport.pullRequest?.number || 0);
886
+ const { anchorProvenance, provenancePassport } = await recoverCandidateProvenance({
887
+ passport, buildSummary, transactionId, repoInfo, artifactName,
888
+ expectedWorkflowFile, expectedWorkflowName, channel, apiUrl, token,
889
+ fetchImpl, archiveDir, bundleRoot, githubJson, selectReleaseCandidateArtifacts,
890
+ downloadArtifact, readOnlyJson,
891
+ });
892
+ const prNumber = Number(provenancePassport.pullRequest?.number || 0);
402
893
  if (!prNumber) throw new Error("Release Candidate Passport has no PR identity");
403
894
  const pullRequest = await githubJson({ apiUrl, token, fetchImpl, path: `/repos/${repoInfo.owner}/${repoInfo.repo}/pulls/${prNumber}` });
404
895
  const targetCommit = await githubJson({ apiUrl, token, fetchImpl, path: `/repos/${repoInfo.owner}/${repoInfo.repo}/git/commits/${targetSha}` });
@@ -419,8 +910,24 @@ export async function resumeFromCandidateRun({
419
910
  releasePatterns,
420
911
  platformManifests: platformManifestEvidence.manifests,
421
912
  });
422
- const candidateVersion = publication.version;
423
- const existingTransaction = await readExistingTransaction({ repoInfo, apiUrl, token, fetchImpl, version: candidateVersion });
913
+ const stageCapsules = resolveRecoveredStageCapsules({
914
+ candidateRuntimeSha,
915
+ runtimeSha,
916
+ sidecar: stageCapsuleSidecar,
917
+ passport,
918
+ downloads,
919
+ });
920
+ const {
921
+ version: candidateVersion,
922
+ transaction: existingTransaction,
923
+ } = await resolveRecoveryTransaction({
924
+ repoInfo,
925
+ apiUrl,
926
+ token,
927
+ fetchImpl,
928
+ transactionId,
929
+ publicationVersion: publication.version,
930
+ });
424
931
  const targetAdvance = await resolveTargetAdvance({
425
932
  observedTargetSha, targetSha, transactionId, existingTransaction,
426
933
  repoInfo, apiUrl, token, fetchImpl,
@@ -448,20 +955,9 @@ export async function resumeFromCandidateRun({
448
955
  expectedRuntimeSha: candidateRuntimeSha,
449
956
  expectedTransactionId: transactionId,
450
957
  existingTransaction,
451
- run: {
452
- id: String(run.id),
453
- repository: repoInfo.fullName,
454
- headRepository: run.head_repository?.full_name || "",
455
- status: run.status,
456
- conclusion: run.conclusion,
457
- event: run.event,
458
- path: run.path,
459
- name: run.name,
460
- headSha: run.head_sha || "",
461
- headBranch: run.head_branch || "",
462
- pullRequestNumbers: (run.pull_requests || []).map((entry) => Number(entry.number)),
463
- },
958
+ run: normalizeCandidateRun(run, repoInfo.fullName),
464
959
  workflow: { path: workflow.path, name: workflow.name, state: workflow.state },
960
+ anchorProvenance: normalizeAnchorProvenance(anchorProvenance, repoInfo.fullName),
465
961
  pullRequest: {
466
962
  number: pullRequest.number,
467
963
  merged: pullRequest.merged === true,
@@ -491,6 +987,19 @@ export async function resumeFromCandidateRun({
491
987
  if (publication.manifest) fs.writeFileSync(sealedManifestPath, `${JSON.stringify(publication.manifest, null, 2)}\n`);
492
988
  const publishRequiredArtifacts = publication.publishRequiredArtifacts;
493
989
  fs.writeFileSync(requiredArtifactsPath, `${JSON.stringify(publishRequiredArtifacts, null, 2)}\n`);
990
+ const runtimeResumeEvidencePath = stageCapsules.length
991
+ ? prepareRuntimeResumeEvidence({
992
+ repoInfo,
993
+ targetRef,
994
+ runtimeSha,
995
+ version: candidateVersion,
996
+ passport,
997
+ sidecar: stageCapsuleSidecar,
998
+ stageCapsules,
999
+ recovery,
1000
+ outputDir: resolvedOutput,
1001
+ })
1002
+ : "";
494
1003
  const tarballs = publication.npmArtifacts.map((entry) => outputPath(entry.file.absolutePath));
495
1004
  return {
496
1005
  enabled: true,
@@ -514,6 +1023,9 @@ export async function resumeFromCandidateRun({
514
1023
  sealedBundleRoot: publication.manifest ? outputPath(bundleRoot) : "",
515
1024
  sealedBundleManifest: publication.manifest ? outputPath(sealedManifestPath) : "",
516
1025
  recoveryReceipt: outputPath(recoveryReceiptPath),
1026
+ runtimeResumeEvidence: runtimeResumeEvidencePath
1027
+ ? outputPath(runtimeResumeEvidencePath)
1028
+ : "",
517
1029
  },
518
1030
  };
519
1031
  } finally {
@@ -565,6 +1077,10 @@ export async function resumeFromCandidateRunCli() {
565
1077
  "release-candidate-run-url": result.run.url,
566
1078
  "release-candidate-recovery-receipt-path": result.paths.recoveryReceipt,
567
1079
  "release-candidate-recovery-root": result.receipt.root,
1080
+ "v4-runtime-resume-evidence-path": result.paths.runtimeResumeEvidence,
1081
+ "v4-runtime-resume-finalize-command": result.paths.runtimeResumeEvidence
1082
+ ? "node .buildchain/runtime/promotion-shell/scripts/resume-from-candidate-run.mjs finalize"
1083
+ : "",
568
1084
  "release-candidate-root": result.candidateRoot,
569
1085
  "release-candidate-artifact-root": result.artifactRoot,
570
1086
  "publish-sealed-bundle-root": result.paths.sealedBundleRoot,
@@ -586,7 +1102,21 @@ export async function resumeFromCandidateRunCli() {
586
1102
  }
587
1103
 
588
1104
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
589
- resumeFromCandidateRunCli().catch((error) => {
1105
+ const operation = process.argv[2] === "finalize"
1106
+ ? finalizeRuntimeResumeEvidence({
1107
+ materialPath: requiredEnv("BUILDCHAIN_V4_RUNTIME_RESUME_MATERIAL"),
1108
+ transaction: JSON.parse(
1109
+ requiredEnv("BUILDCHAIN_RELEASE_TRANSACTION_JSON"),
1110
+ ),
1111
+ outputDir: env(
1112
+ "BUILDCHAIN_RELEASE_PASSPORT_OUTPUT_DIR",
1113
+ path.dirname(requiredEnv("BUILDCHAIN_V4_RUNTIME_RESUME_MATERIAL")),
1114
+ ),
1115
+ }).then((result) =>
1116
+ console.log(JSON.stringify({ files: [outputPath(result.path)] })),
1117
+ )
1118
+ : resumeFromCandidateRunCli();
1119
+ operation.catch((error) => {
590
1120
  const failure = error.recoveryFailure || recoveryFailure(error);
591
1121
  console.error(`candidate recovery rejected [${failure.code}]: ${failure.reason}`);
592
1122
  console.error(`next action: ${failure.nextAction}`);