@kungfu-tech/buildchain 4.0.2-alpha.4 → 4.0.2-alpha.40

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 (153) hide show
  1. package/AGENTS.md +10 -1
  2. package/CONTRIBUTING.md +24 -0
  3. package/README.md +2 -2
  4. package/actions/promote-buildchain-ref/README.md +1 -1
  5. package/actions/v4-release-candidate-promote/README.md +28 -0
  6. package/architecture/agent-change-map.md +66 -7
  7. package/architecture/ci-lane-change-budget.json +366 -0
  8. package/architecture/internal-capabilities.json +52 -8
  9. package/architecture/maintainability-debt.json +148 -92
  10. package/architecture/maintainability-policy.json +34 -30
  11. package/architecture/release-tail-contract-inventory.json +6 -6
  12. package/architecture/v4-architecture-constitution.md +23 -20
  13. package/architecture/v4-cross-platform-adopter-qualification.json +1 -1
  14. package/architecture/v4-delivery-authority-parity.json +2 -2
  15. package/architecture/v4-delivery-warrant-shadow-bootstrap-plan.json +1 -1
  16. package/architecture/v4-floating-consumer-policy.json +2 -2
  17. package/architecture/v4-next-development-parity.json +5 -5
  18. package/architecture/v4-partial-mutation-recovery-qualification.json +4 -1
  19. package/architecture/v4-platform-stage-checkpoints.json +1 -1
  20. package/architecture/v4-provider-operation-journal-contract.json +5 -2
  21. package/architecture/v4-publication-facade-patches.json +53 -0
  22. package/architecture/v4-release-activation-shadow-domain.json +5 -2
  23. package/architecture/v4-release-topology.json +143 -35
  24. package/architecture/v4-rust-wasm-production-authority.json +58 -0
  25. package/architecture/v4-stable-publication-fence.json +5 -2
  26. package/architecture/v4-stage-capsule-qualification.json +2 -2
  27. package/architecture/v4-tail-reseal-parity.json +8 -6
  28. package/architecture/v4-universal-workflow-bootstrap.json +171 -0
  29. package/architecture/v4-universal-workflow-fault-campaign.json +72 -0
  30. package/architecture/v4-universal-workflow-train-admission.json +40 -0
  31. package/architecture/workflow-taxonomy.json +1451 -0
  32. package/bin/buildchain.mjs +7 -7
  33. package/contracts/buildchain-v2-residuals-v1.json +57 -48
  34. package/contracts/dev-delivery-authority-v2.schema.json +16 -2
  35. package/contracts/fixtures/v4-tail-reseal-v1/valid.json +1 -1
  36. package/contracts/v4-canonical-contracts-v1.schema.json +1 -0
  37. package/dist/site/buildchain-contract.json +93 -48
  38. package/dist/site/buildchain-site.json +222 -69
  39. package/dist/site/capability-registry.json +4 -4
  40. package/dist/site/controller-registry.json +50 -13
  41. package/dist/site/kfd-claims.json +2569 -982
  42. package/dist/site/kfd-upstream-aggregate.json +1 -1
  43. package/dist/site/manual-registry.json +13 -13
  44. package/dist/site/node-api-registry.json +88 -83
  45. package/dist/site/page-registry.json +204 -51
  46. package/dist/site/public-surface-audit.json +3207 -1219
  47. package/dist/site/publication-authority-registry.json +1124 -362
  48. package/dist/site/publication-registry.json +4 -4
  49. package/dist/site/schemas/dev-delivery-authority-v2.schema.json +16 -2
  50. package/dist/site/site-manifest.json +17 -17
  51. package/dist/site/workflow-registry.json +5063 -1659
  52. package/docs/MAP.md +1 -0
  53. package/docs/auditable-demo.md +1 -1
  54. package/docs/cli.md +3 -3
  55. package/docs/dev-delivery-warrant.md +1 -1
  56. package/docs/engineering-housekeeper.md +3 -3
  57. package/docs/kfd-support.md +26 -2
  58. package/docs/next-development-transition.md +2 -2
  59. package/docs/node-api-reference.md +129 -129
  60. package/docs/publication-authority.md +2 -2
  61. package/docs/release-candidate.md +3 -3
  62. package/docs/release-flow.md +67 -19
  63. package/docs/release-governance.md +8 -8
  64. package/docs/release-passport.md +27 -2
  65. package/docs/reusable-build-surface.md +16 -0
  66. package/docs/v4-adopter-delivery.md +2 -2
  67. package/docs/v4-production-release.md +71 -8
  68. package/docs/v4-rust-wasm-production-authority.md +58 -0
  69. package/docs/v4-stage-capsule.md +2 -2
  70. package/docs/v4-tail-reseal.md +1 -1
  71. package/docs/workflow-catalog.md +154 -0
  72. package/docs/workflow-path-migration.md +109 -0
  73. package/package.json +10 -6
  74. package/packages/core/artifact-verification-envelope.js +5 -5
  75. package/packages/core/buildchain-contract.js +1 -1
  76. package/packages/core/buildchain-kfd-claims.js +2 -2
  77. package/packages/core/buildchain-publication-authority.js +42 -26
  78. package/packages/core/buildchain-v4-domain.wasm +0 -0
  79. package/packages/core/ci-lane-change-budget.js +14 -1
  80. package/packages/core/controller-evidence.js +4 -1
  81. package/packages/core/dev-delivery-candidate-identity.js +40 -6
  82. package/packages/core/dev-delivery-warrant-state.js +3 -4
  83. package/packages/core/dev-delivery-warrant.js +12 -2
  84. package/packages/core/github-governance-authority.js +4 -4
  85. package/packages/core/kfd-adopter-manifest.js +46 -47
  86. package/packages/core/next-development-projection.js +2 -2
  87. package/packages/core/release-line-dry-run.js +1 -1
  88. package/packages/core/release-passport-contract.js +5 -5
  89. package/packages/core/release-passport.js +5 -4
  90. package/packages/core/release-tail-product-capabilities.js +29 -0
  91. package/packages/core/release-tail-provider-plane.js +68 -1048
  92. package/packages/core/v4-canonical-contracts.js +14 -75
  93. package/packages/core/v4-domain-wasm-artifact.js +7 -0
  94. package/packages/core/v4-domain-wasm.js +216 -0
  95. package/packages/core/v4-floating-consumer-evidence.js +1 -1
  96. package/packages/core/v4-floating-consumer-policy.js +1 -1
  97. package/packages/core/v4-partial-mutation-recovery-qualification.js +9 -386
  98. package/packages/core/v4-product-publication.js +57 -0
  99. package/packages/core/v4-protected-publication-source.js +19 -21
  100. package/packages/core/v4-provider-operation-journal.js +18 -487
  101. package/packages/core/v4-provider-readback-idempotency.js +12 -97
  102. package/packages/core/v4-release-activation-shadow.js +13 -500
  103. package/packages/core/v4-release-invocation.js +28 -389
  104. package/packages/core/v4-stable-publication-fence.js +13 -342
  105. package/packages/core/v4-universal-workflow-bootstrap.js +586 -0
  106. package/scripts/binary-publication-evidence.mjs +135 -0
  107. package/scripts/build-contract-core.mjs +1 -14
  108. package/scripts/build-v4-domain-wasm.mjs +189 -0
  109. package/scripts/check-action-bundles.mjs +12 -2
  110. package/scripts/check-ci-lane-change-budget.mjs +4 -1
  111. package/scripts/check-core-mechanism-inventory.mjs +4 -3
  112. package/scripts/check-inventory.mjs +35 -44
  113. package/scripts/check-maintainability.mjs +16 -113
  114. package/scripts/check-v4-floating-consumer-policy-contract.mjs +2 -2
  115. package/scripts/check-v4-public-dogfood-contract.mjs +22 -9
  116. package/scripts/check-v4-release-topology.mjs +214 -50
  117. package/scripts/check-v4-runtime-semantic-closure.mjs +4 -1
  118. package/scripts/check-v4-universal-workflow-bootstrap.mjs +266 -0
  119. package/scripts/check-workflow-taxonomy.mjs +6 -0
  120. package/scripts/copy-v4-domain-wasm.mjs +14 -0
  121. package/scripts/dev-delivery-authority-command-adapters.mjs +1 -1
  122. package/scripts/dev-delivery-authority.mjs +8 -8
  123. package/scripts/dev-delivery-source-proof-reuse.mjs +2 -1
  124. package/scripts/dev-delivery-warrant-options.mjs +14 -9
  125. package/scripts/dev-delivery-warrant-store.mjs +73 -7
  126. package/scripts/dev-delivery-warrant-transition.mjs +109 -0
  127. package/scripts/dev-delivery-warrant.mjs +76 -99
  128. package/scripts/dev-pr-auto-merge.mjs +15 -15
  129. package/scripts/generate-channel-build-workflow.mjs +7 -2
  130. package/scripts/generate-channel-promotion-workflow.mjs +7 -5
  131. package/scripts/generate-site-bundle.mjs +11 -11
  132. package/scripts/generate-v4-universal-workflow-facades.mjs +458 -0
  133. package/scripts/generate-workflow-taxonomy.mjs +25 -0
  134. package/scripts/github-output.mjs +31 -0
  135. package/scripts/maintainability-metrics.mjs +16 -5
  136. package/scripts/maintainability-public-surface.mjs +115 -0
  137. package/scripts/next-development-review.mjs +307 -0
  138. package/scripts/release-asset-client.mjs +91 -0
  139. package/scripts/release-candidate-resolver.mjs +17 -18
  140. package/scripts/resume-from-candidate-run.mjs +1 -1
  141. package/scripts/source-verification-evidence.mjs +344 -0
  142. package/scripts/stable-candidate-qualification.mjs +1 -1
  143. package/scripts/universal-facade-maintainability.mjs +82 -0
  144. package/scripts/v4-product-publication-intent.mjs +121 -0
  145. package/scripts/v4-publication-settlement.mjs +211 -0
  146. package/scripts/v4-universal-workflow-backflow.mjs +212 -0
  147. package/scripts/v4-universal-workflow-engine.mjs +618 -0
  148. package/scripts/v4-universal-workflow-self-dogfood.mjs +205 -0
  149. package/scripts/verify-version-state-delta.mjs +173 -0
  150. package/scripts/workflow-taxonomy.mjs +507 -0
  151. package/templates/native-dev-delivery.yml +4 -7
  152. package/templates/universal-buildchain-bootstrap-recovery.yml +282 -0
  153. package/templates/universal-buildchain-bootstrap.yml +28 -0
@@ -0,0 +1,586 @@
1
+ import crypto from "node:crypto";
2
+
3
+ export const V4_UNIVERSAL_WORKFLOW_REQUEST =
4
+ "kungfu-buildchain-v4-universal-workflow-request/v1";
5
+ export const V4_UNIVERSAL_WORKFLOW_ADMISSION_POLICY =
6
+ "kungfu-buildchain-v4-universal-workflow-admission-policy/v1";
7
+ export const V4_UNIVERSAL_WORKFLOW_ADMISSION =
8
+ "kungfu-buildchain-v4-universal-workflow-admission/v1";
9
+ export const V4_UNIVERSAL_WORKFLOW_TERMINAL_RECEIPT =
10
+ "kungfu-buildchain-v4-universal-workflow-terminal-receipt/v1";
11
+ const EXACT_SHA = /^[0-9a-f]{40}$/u;
12
+ const ROOT = /^sha256:[0-9a-f]{64}$/u;
13
+ const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u;
14
+ const WORKFLOW = /^\.github\/workflows\/[A-Za-z0-9_.-]+\.ya?ml$/u;
15
+ const TOKEN = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u;
16
+ const TRAIN = /^train\/v4\/v4\.\d+\/[A-Za-z0-9][A-Za-z0-9._/-]*$/u;
17
+ const MODES = new Set(["stable", "alpha", "train", "exact"]);
18
+ const PERMISSIONS = new Set([
19
+ "actions",
20
+ "artifact-metadata",
21
+ "attestations",
22
+ "checks",
23
+ "contents",
24
+ "deployments",
25
+ "id-token",
26
+ "issues",
27
+ "packages",
28
+ "pages",
29
+ "pull-requests",
30
+ "security-events",
31
+ "statuses",
32
+ ]);
33
+ const LEVELS = new Map([
34
+ ["none", 0],
35
+ ["read", 1],
36
+ ["write", 2],
37
+ ]);
38
+ function fail(code, message) {
39
+ const error = new Error(message);
40
+ error.code = code;
41
+ throw error;
42
+ }
43
+ function exactKeys(value, keys, label) {
44
+ if (!value || typeof value !== "object" || Array.isArray(value))
45
+ fail("invalid-object", `${label} must be an object`);
46
+ const actual = Object.keys(value).sort();
47
+ const expected = [...keys].sort();
48
+ if (
49
+ actual.length !== expected.length ||
50
+ actual.some((key, index) => key !== expected[index])
51
+ )
52
+ fail("invalid-field-set", `${label} has an invalid field set`);
53
+ }
54
+ function nonEmpty(value, label) {
55
+ const normalized = String(value || "").trim();
56
+ if (!normalized) fail("required-value", `${label} must be non-empty`);
57
+ return normalized;
58
+ }
59
+ function exactSha(value, label) {
60
+ const normalized = nonEmpty(value, label).toLowerCase();
61
+ if (!EXACT_SHA.test(normalized))
62
+ fail("invalid-exact-sha", `${label} must be an exact lowercase Git SHA`);
63
+ return normalized;
64
+ }
65
+ function positiveInteger(value, label) {
66
+ if (!Number.isSafeInteger(value) || value < 1)
67
+ fail("invalid-positive-integer", `${label} must be a positive integer`);
68
+ return value;
69
+ }
70
+ function root(value, label) {
71
+ const normalized = nonEmpty(value, label).toLowerCase();
72
+ if (!ROOT.test(normalized))
73
+ fail("invalid-root", `${label} must be a lowercase sha256 root`);
74
+ return normalized;
75
+ }
76
+ function canonical(value) {
77
+ if (Array.isArray(value)) return value.map(canonical);
78
+ if (value && typeof value === "object")
79
+ return Object.fromEntries(
80
+ Object.keys(value)
81
+ .sort((left, right) => Buffer.from(left).compare(Buffer.from(right)))
82
+ .map((key) => [key, canonical(value[key])]),
83
+ );
84
+ if (
85
+ value === null ||
86
+ typeof value === "string" ||
87
+ typeof value === "boolean" ||
88
+ (typeof value === "number" && Number.isSafeInteger(value))
89
+ )
90
+ return value;
91
+ fail("unsupported-json", "value is not canonical JSON");
92
+ }
93
+ function documentRoot(domain, value) {
94
+ const hash = crypto.createHash("sha256");
95
+ hash.update(domain, "utf8");
96
+ hash.update(Buffer.from([0]));
97
+ hash.update(`${JSON.stringify(canonical(value))}\n`, "utf8");
98
+ return `sha256:${hash.digest("hex")}`;
99
+ }
100
+ function sortedValues(values, label, normalize, kind) {
101
+ if (!Array.isArray(values) || values.length === 0)
102
+ fail(`required-${kind}`, `${label} must be a non-empty array`);
103
+ const normalized = values.map((value, index) =>
104
+ normalize(value, `${label}[${index}]`),
105
+ );
106
+ const expected = [...new Set(normalized)].sort((left, right) =>
107
+ Buffer.from(left).compare(Buffer.from(right)),
108
+ );
109
+ if (
110
+ normalized.length !== expected.length ||
111
+ normalized.some((value, index) => value !== expected[index])
112
+ )
113
+ fail(
114
+ `non-canonical-${kind}`,
115
+ `${label} must be byte-sorted and duplicate-free`,
116
+ );
117
+ return normalized;
118
+ }
119
+ function token(value, label) {
120
+ const token = nonEmpty(value, label);
121
+ if (!TOKEN.test(token))
122
+ fail("invalid-token", `${label} must be an ASCII token`);
123
+ return token;
124
+ }
125
+ const sortedRoots = (values, label) =>
126
+ sortedValues(values, label, root, "roots");
127
+ const sortedTokens = (values, label) =>
128
+ sortedValues(values, label, token, "tokens");
129
+ const sortedStrings = (values, label) =>
130
+ sortedValues(values, label, nonEmpty, "strings");
131
+ function permissions(value, label) {
132
+ if (!value || typeof value !== "object" || Array.isArray(value))
133
+ fail("invalid-permissions", `${label} must be an object`);
134
+ const result = {};
135
+ for (const key of Object.keys(value).sort()) {
136
+ if (!PERMISSIONS.has(key))
137
+ fail("unknown-permission", `${label}.${key} is not governed`);
138
+ const level = nonEmpty(value[key], `${label}.${key}`);
139
+ if (!LEVELS.has(level))
140
+ fail("invalid-permission-level", `${label}.${key} has an invalid level`);
141
+ result[key] = level;
142
+ }
143
+ if (Object.keys(result).length === 0)
144
+ fail("required-permissions", `${label} must not be empty`);
145
+ return result;
146
+ }
147
+ function repository(value, label) {
148
+ const normalized = nonEmpty(value, label);
149
+ if (!REPOSITORY.test(normalized))
150
+ fail("invalid-repository", `${label} must be an owner/repository slug`);
151
+ return normalized;
152
+ }
153
+
154
+ function workflow(value, label) {
155
+ const normalized = nonEmpty(value, label);
156
+ if (!WORKFLOW.test(normalized))
157
+ fail("invalid-workflow", `${label} must be a tracked workflow path`);
158
+ return normalized;
159
+ }
160
+
161
+ function timestamp(value, label) {
162
+ const normalized = nonEmpty(value, label);
163
+ const parsed = new Date(normalized);
164
+ if (!Number.isFinite(parsed.getTime()) || parsed.toISOString() !== normalized)
165
+ fail("invalid-timestamp", `${label} must be a canonical UTC timestamp`);
166
+ return normalized;
167
+ }
168
+
169
+ export function validateV4UniversalWorkflowRequest(value) {
170
+ exactKeys(
171
+ value,
172
+ ["schema", "mode", "candidate", "consumer", "capability", "payload"],
173
+ "request",
174
+ );
175
+ if (value.schema !== V4_UNIVERSAL_WORKFLOW_REQUEST)
176
+ fail("unsupported-request-schema", "request schema is unsupported");
177
+ if (!MODES.has(value.mode))
178
+ fail("unsupported-mode", "request mode is unsupported");
179
+ exactKeys(
180
+ value.candidate,
181
+ [
182
+ "repository",
183
+ "discoveryRef",
184
+ "expectedSha",
185
+ "admissionRoot",
186
+ "reviewPullRequest",
187
+ ],
188
+ "request.candidate",
189
+ );
190
+ const candidateRepository = repository(
191
+ value.candidate.repository,
192
+ "request.candidate.repository",
193
+ );
194
+ if (candidateRepository !== "kungfu-systems/buildchain")
195
+ fail(
196
+ "untrusted-candidate-repository",
197
+ "candidate repository must be kungfu-systems/buildchain",
198
+ );
199
+ const discoveryRef = nonEmpty(
200
+ value.candidate.discoveryRef,
201
+ "request.candidate.discoveryRef",
202
+ ).replace(/^refs\/(?:heads|tags)\//u, "");
203
+ if (value.mode === "train" && !TRAIN.test(discoveryRef))
204
+ fail("invalid-train-ref", "train mode requires a governed v4 Train ref");
205
+ if (value.mode === "exact" && !EXACT_SHA.test(discoveryRef.toLowerCase()))
206
+ fail("invalid-exact-ref", "exact mode requires an exact Git SHA selector");
207
+ if (value.mode === "alpha" && discoveryRef !== "v4-alpha")
208
+ fail("invalid-alpha-ref", "alpha mode requires v4-alpha discovery");
209
+ if (value.mode === "stable" && discoveryRef !== "v4")
210
+ fail("invalid-stable-ref", "stable mode requires v4 discovery");
211
+ exactKeys(
212
+ value.consumer,
213
+ ["repository", "workflow", "sourceSha"],
214
+ "request.consumer",
215
+ );
216
+ exactKeys(
217
+ value.capability,
218
+ ["id", "contractRoots", "permissions"],
219
+ "request.capability",
220
+ );
221
+ const capabilityId = nonEmpty(value.capability.id, "request.capability.id");
222
+ if (!TOKEN.test(capabilityId))
223
+ fail("invalid-capability", "request.capability.id must be an ASCII token");
224
+ canonical(value.payload);
225
+ return {
226
+ schema: value.schema,
227
+ mode: value.mode,
228
+ candidate: {
229
+ repository: candidateRepository,
230
+ discoveryRef,
231
+ expectedSha: exactSha(
232
+ value.candidate.expectedSha,
233
+ "request.candidate.expectedSha",
234
+ ),
235
+ admissionRoot: root(
236
+ value.candidate.admissionRoot,
237
+ "request.candidate.admissionRoot",
238
+ ),
239
+ reviewPullRequest: positiveInteger(
240
+ value.candidate.reviewPullRequest,
241
+ "request.candidate.reviewPullRequest",
242
+ ),
243
+ },
244
+ consumer: {
245
+ repository: repository(
246
+ value.consumer.repository,
247
+ "request.consumer.repository",
248
+ ),
249
+ workflow: workflow(value.consumer.workflow, "request.consumer.workflow"),
250
+ sourceSha: exactSha(
251
+ value.consumer.sourceSha,
252
+ "request.consumer.sourceSha",
253
+ ),
254
+ },
255
+ capability: {
256
+ id: capabilityId,
257
+ contractRoots: sortedRoots(
258
+ value.capability.contractRoots,
259
+ "request.capability.contractRoots",
260
+ ),
261
+ permissions: permissions(
262
+ value.capability.permissions,
263
+ "request.capability.permissions",
264
+ ),
265
+ },
266
+ payload: canonical(value.payload),
267
+ };
268
+ }
269
+ export function v4UniversalWorkflowRequestRoot(value) {
270
+ return documentRoot(
271
+ "universal-workflow-request",
272
+ validateV4UniversalWorkflowRequest(value),
273
+ );
274
+ }
275
+ export function v4ProductStateVersion(value, requestedSha) { const sourceSha = exactSha(requestedSha, "requestedSha"), ref = nonEmpty(value?.ref, "productStateRef.ref"), prefix = `refs/heads/buildchain/v4-product-state/${sourceSha}-`; if (!ref.startsWith(prefix)) fail("recovery-state-mismatch", "release recovery product state does not bind the requested source"); const match = ref.slice(prefix.length).match(/^(\d+)-(\d+)-(\d+)(?:-alpha-(\d+))?$/u); if (!match) fail("invalid-recovery-version", "release recovery product state version is invalid"); return `${match[1]}.${match[2]}.${match[3]}${match[4] === undefined ? "" : `-alpha.${match[4]}`}`; }
276
+ export function selectV4FinalizedProductPublicationVersion(value) { const requestedSha = exactSha(value.requestedSha, "requestedSha"), requestedTree = exactSha(value.requestedTree, "requestedTree"), lane = nonEmpty(value.targetRef, "targetRef").match(/^(alpha|release)\/v(\d+)\/v(\d+)\.(\d+)$/u); if (!lane || lane[2] !== lane[3]) fail("invalid-finalization-lane", "product publication finalization target is not a release lane"); const expectedAlpha = lane[1] === "alpha", versions = []; for (const row of Array.isArray(value.recoveryStates) ? value.recoveryStates : []) { const stateRef = row?.stateRef, match = String(stateRef?.ref || "").match(/^refs\/heads\/buildchain\/v4-product-state\/([0-9a-f]{40})-(\d+)-(\d+)-(\d+)(?:-alpha-(\d+))?$/u); if (!match || match[2] !== lane[2] || match[3] !== lane[4]) continue; const stateTree = exactSha(row?.stateCommit?.tree?.sha, "productStateCommit.tree.sha"); if (stateTree !== requestedTree || !new Set(["ahead", "identical"]).has(row.headComparisonStatus)) continue; const sourceSha = exactSha(match[1], "productStateRef.sourceSha"), version = v4ProductStateVersion(stateRef, sourceSha), parsed = version.match(/^(\d+)\.(\d+)\.(\d+)(?:-alpha\.(\d+))?$/u); if ((parsed[4] !== undefined) !== expectedAlpha) continue; if (stateRef?.object?.type !== "commit" || exactSha(stateRef?.object?.sha, "productStateRef.object.sha") !== exactSha(row?.stateCommit?.sha, "productStateCommit.sha") || row.stateCommit.parents?.length !== 1 || exactSha(row.stateCommit.parents[0]?.sha, "productStateCommit.parents[0].sha") !== sourceSha) fail("finalization-state-mismatch", "product publication finalization state does not bind its source"); if (row.exactTagRef && (row.exactTagRef.ref !== `refs/tags/v${version}` || row.exactTagRef.object?.type !== "commit" || exactSha(row.exactTagRef.object?.sha, "exactTagRef.object.sha") !== sourceSha)) fail("finalization-tag-mismatch", "product publication finalization tag does not bind its source"); versions.push(version); } const selected = [...new Set(versions)].sort(); if (selected.length > 1) fail("finalization-state-ambiguous", `publication head ${requestedSha} matches multiple product versions`); return selected[0] || ""; }
277
+ export function selectV4RecoveredProductPublicationVersion(value) {
278
+ if (value.routeDecision !== "Resume") return ""; const version = nonEmpty(value.candidateVersion, "candidateVersion"), sourceSha = exactSha(value.requestedSha, "requestedSha"), candidate = version.match(/^(\d+)\.(\d+)\.(\d+)(?:-alpha\.(\d+))?$/u); if (!candidate) fail("invalid-recovery-version", "release recovery candidate version is invalid"); if (value.explicitResume) return version;
279
+ const states = Array.isArray(value.recoveryStates) ? value.recoveryStates : []; if (states.length) { const recovered = [...new Set(states.map(({ stateRef, stateCommit, exactTagRef }) => { const selected = v4ProductStateVersion(stateRef, sourceSha), parsed = selected.match(/^(\d+)\.(\d+)\.(\d+)(?:-alpha\.(\d+))?$/u), parents = stateCommit?.parents || []; if (stateRef?.object?.type !== "commit" || exactSha(stateRef?.object?.sha, "productStateRef.object.sha") !== exactSha(stateCommit?.sha, "productStateCommit.sha") || parents.length !== 1 || exactSha(parents[0]?.sha, "productStateCommit.parents[0].sha") !== sourceSha) fail("recovery-state-mismatch", "release recovery product state commit does not bind the requested source"); if (exactTagRef && (exactTagRef.ref !== `refs/tags/v${selected}` || exactTagRef.object?.type !== "commit" || exactSha(exactTagRef.object?.sha, "exactTagRef.object.sha") !== sourceSha)) fail("recovery-tag-mismatch", "release recovery exact tag does not bind the requested source"); if (parsed[1] !== candidate[1] || parsed[2] !== candidate[2] || parsed[3] !== candidate[3] || (parsed[4] === undefined) !== (candidate[4] === undefined)) fail("recovery-state-mismatch", "release recovery product state is outside the candidate release line"); return selected; }))]; if (recovered.length !== 1) fail("recovery-state-ambiguous", "release recovery requires one exact product publication state; provide an exact transaction identity"); return recovered[0]; }
280
+ if (!value.exactTagRef) fail("recovery-tag-missing", "release recovery requires an exact partial-publication tag"); if (value.exactTagRef.ref !== `refs/tags/v${version}` || value.exactTagRef.object?.type !== "commit" || exactSha(value.exactTagRef.object?.sha, "exactTagRef.object.sha") !== sourceSha) fail("recovery-tag-mismatch", "release recovery exact tag does not bind the requested source");
281
+ return version;
282
+ }
283
+ function validatePolicy(value) {
284
+ exactKeys(
285
+ value,
286
+ [
287
+ "schema",
288
+ "sourceRepository",
289
+ "consumerAdmission",
290
+ "allowedCapabilities",
291
+ "permissionCeiling",
292
+ "contractRoots",
293
+ "targetRef",
294
+ "allowedReviewers",
295
+ "minimumApprovals",
296
+ "requiredChecks",
297
+ "validFrom",
298
+ "expiresAt",
299
+ ],
300
+ "policy",
301
+ );
302
+ if (value.schema !== V4_UNIVERSAL_WORKFLOW_ADMISSION_POLICY)
303
+ fail("unsupported-policy-schema", "policy schema is unsupported");
304
+ const consumerAdmission = nonEmpty(
305
+ value.consumerAdmission,
306
+ "consumer admission",
307
+ );
308
+ if (consumerAdmission !== "verified-caller")
309
+ fail("unsupported-consumer-admission", "unsupported admission");
310
+ const policy = {
311
+ schema: value.schema,
312
+ sourceRepository: repository(
313
+ value.sourceRepository,
314
+ "policy.sourceRepository",
315
+ ),
316
+ consumerAdmission,
317
+ allowedCapabilities: sortedTokens(
318
+ value.allowedCapabilities,
319
+ "policy.allowedCapabilities",
320
+ ),
321
+ permissionCeiling: permissions(
322
+ value.permissionCeiling,
323
+ "policy.permissionCeiling",
324
+ ),
325
+ contractRoots: sortedRoots(value.contractRoots, "policy.contractRoots"),
326
+ targetRef: nonEmpty(value.targetRef, "policy.targetRef"),
327
+ allowedReviewers: sortedTokens(
328
+ value.allowedReviewers,
329
+ "policy.allowedReviewers",
330
+ ),
331
+ minimumApprovals: positiveInteger(
332
+ value.minimumApprovals,
333
+ "policy.minimumApprovals",
334
+ ),
335
+ requiredChecks: sortedStrings(
336
+ value.requiredChecks,
337
+ "policy.requiredChecks",
338
+ ),
339
+ validFrom: timestamp(value.validFrom, "policy.validFrom"),
340
+ expiresAt: timestamp(value.expiresAt, "policy.expiresAt"),
341
+ };
342
+ if (Date.parse(policy.validFrom) >= Date.parse(policy.expiresAt))
343
+ fail("invalid-policy-window", "policy validity window is empty");
344
+ return policy;
345
+ }
346
+
347
+ function validateReviewEvidence(value) {
348
+ const hasBinding = Object.hasOwn(value || {}, "runtimeBinding");
349
+ exactKeys(value, ["repository", "pullRequest", "headSha", "baseRef", "approvals", "checks", "observedAt", ...(hasBinding ? ["runtimeBinding"] : [])], "reviewEvidence");
350
+ const approvals = value.approvals.map((approval, index) => {
351
+ exactKeys(approval, ["reviewer", "commitSha", "submittedAt"], `reviewEvidence.approvals[${index}]`);
352
+ return {
353
+ reviewer: nonEmpty(approval.reviewer, `reviewEvidence.approvals[${index}].reviewer`),
354
+ commitSha: exactSha(approval.commitSha, `reviewEvidence.approvals[${index}].commitSha`),
355
+ submittedAt: timestamp(approval.submittedAt, `reviewEvidence.approvals[${index}].submittedAt`),
356
+ };
357
+ });
358
+ const checks = value.checks.map((check, index) => {
359
+ const hasCommit = Object.hasOwn(check || {}, "commitSha");
360
+ exactKeys(check, ["name", "status", "conclusion", ...(hasCommit ? ["commitSha"] : [])], `reviewEvidence.checks[${index}]`);
361
+ return {
362
+ name: nonEmpty(check.name, `reviewEvidence.checks[${index}].name`),
363
+ status: nonEmpty(check.status, `reviewEvidence.checks[${index}].status`),
364
+ conclusion: nonEmpty(check.conclusion, `reviewEvidence.checks[${index}].conclusion`),
365
+ ...(hasCommit ? { commitSha: exactSha(check.commitSha, `reviewEvidence.checks[${index}].commitSha`) } : {}),
366
+ };
367
+ });
368
+ let runtimeBinding;
369
+ if (hasBinding) {
370
+ exactKeys(value.runtimeBinding, ["kind", "runtimeSha", "parentShas", "mergedAt"], "reviewEvidence.runtimeBinding");
371
+ const kind = nonEmpty(value.runtimeBinding.kind, "reviewEvidence.runtimeBinding.kind");
372
+ if (!new Set(["reviewed-head", "protected-alpha-merge"]).has(kind)) fail("invalid-runtime-binding", "review evidence runtime binding kind is unsupported");
373
+ const parentShas = value.runtimeBinding.parentShas.map((parent, index) => exactSha(parent, `reviewEvidence.runtimeBinding.parentShas[${index}]`));
374
+ if (new Set(parentShas).size !== parentShas.length) fail("invalid-runtime-binding", "review evidence runtime parents must be duplicate-free");
375
+ runtimeBinding = { kind, runtimeSha: exactSha(value.runtimeBinding.runtimeSha, "reviewEvidence.runtimeBinding.runtimeSha"), parentShas, mergedAt: value.runtimeBinding.mergedAt === null ? null : timestamp(value.runtimeBinding.mergedAt, "reviewEvidence.runtimeBinding.mergedAt") };
376
+ }
377
+ return {
378
+ repository: repository(value.repository, "reviewEvidence.repository"),
379
+ pullRequest: positiveInteger(value.pullRequest, "reviewEvidence.pullRequest"),
380
+ headSha: exactSha(value.headSha, "reviewEvidence.headSha"),
381
+ baseRef: nonEmpty(value.baseRef, "reviewEvidence.baseRef"),
382
+ approvals, checks,
383
+ observedAt: timestamp(value.observedAt, "reviewEvidence.observedAt"),
384
+ ...(runtimeBinding ? { runtimeBinding } : {}),
385
+ };
386
+ }
387
+
388
+ function reviewedRuntimeSha(request, policy, evidence, runtimeSha) {
389
+ const binding = evidence.runtimeBinding || { kind: "reviewed-head", runtimeSha: evidence.headSha, parentShas: [], mergedAt: null };
390
+ if (binding.runtimeSha !== runtimeSha) fail("review-runtime-mismatch", "review evidence runtime binding does not match the candidate");
391
+ const direct = binding.kind === "reviewed-head" && evidence.headSha === runtimeSha && evidence.baseRef === policy.targetRef && binding.mergedAt === null;
392
+ const alphaMerge = binding.kind === "protected-alpha-merge" && request.mode === "alpha" && evidence.baseRef === "alpha/v4/v4.0" && binding.parentShas.length === 2 && binding.parentShas.includes(evidence.headSha) && binding.mergedAt !== null && Date.parse(binding.mergedAt) <= Date.parse(evidence.observedAt);
393
+ if (!direct && !alphaMerge) fail("review-identity-mismatch", "review evidence does not bind the candidate runtime");
394
+ return evidence.headSha;
395
+ }
396
+
397
+ export function v4UniversalWorkflowAdmissionRoot(value) {
398
+ return documentRoot("universal-workflow-admission", validatePolicy(value));
399
+ }
400
+
401
+ function assertPermissionCeiling(requested, ceiling) {
402
+ for (const [name, level] of Object.entries(requested)) {
403
+ const allowed = ceiling[name] || "none";
404
+ if (LEVELS.get(level) > LEVELS.get(allowed))
405
+ fail(
406
+ "permission-widening",
407
+ `requested ${name}:${level} exceeds admitted ${name}:${allowed}`,
408
+ );
409
+ }
410
+ }
411
+
412
+ export function admitV4UniversalWorkflow({
413
+ request: requestValue,
414
+ policy: policyValue,
415
+ observedRefSha,
416
+ observedConsumerRepository,
417
+ observedConsumerSha,
418
+ observedConsumerWorkflowRef,
419
+ reviewEvidence: reviewEvidenceValue,
420
+ now,
421
+ } = {}) {
422
+ const request = validateV4UniversalWorkflowRequest(requestValue);
423
+ const policy = validatePolicy(policyValue);
424
+ const admissionRoot = v4UniversalWorkflowAdmissionRoot(policy);
425
+ if (request.candidate.admissionRoot !== admissionRoot)
426
+ fail("stale-admission", "request is not bound to the current admission");
427
+ if (policy.sourceRepository !== request.candidate.repository)
428
+ fail("source-repository-mismatch", "admission source repository mismatch");
429
+ const workflowRef = nonEmpty(observedConsumerWorkflowRef, "workflow ref");
430
+ const expectedWorkflowPrefix = `${request.consumer.repository}/${request.consumer.workflow}@`;
431
+ if (
432
+ request.consumer.repository !== observedConsumerRepository ||
433
+ request.consumer.sourceSha !==
434
+ exactSha(observedConsumerSha, "observedConsumerSha") ||
435
+ !workflowRef.startsWith(expectedWorkflowPrefix) ||
436
+ workflowRef.length === expectedWorkflowPrefix.length
437
+ )
438
+ fail("consumer-identity-mismatch", "caller identity mismatch");
439
+ if (!policy.allowedCapabilities.includes(request.capability.id))
440
+ fail("capability-not-admitted", "capability is not admitted");
441
+ if (
442
+ request.capability.contractRoots.length !== policy.contractRoots.length ||
443
+ request.capability.contractRoots.some(
444
+ (value, index) => value !== policy.contractRoots[index],
445
+ )
446
+ )
447
+ fail("contract-root-mismatch", "candidate contract roots are not admitted");
448
+ assertPermissionCeiling(
449
+ request.capability.permissions,
450
+ policy.permissionCeiling,
451
+ );
452
+ const observedAt = timestamp(now, "now");
453
+ if (
454
+ Date.parse(observedAt) < Date.parse(policy.validFrom) ||
455
+ Date.parse(observedAt) >= Date.parse(policy.expiresAt)
456
+ )
457
+ fail("stale-admission", "admission is outside its validity window");
458
+ const runtimeSha = exactSha(observedRefSha, "observedRefSha");
459
+ if (runtimeSha !== request.candidate.expectedSha)
460
+ fail(
461
+ "candidate-ref-moved",
462
+ "candidate ref readback does not match expected SHA",
463
+ );
464
+ const reviewEvidence = validateReviewEvidence(reviewEvidenceValue);
465
+ if (
466
+ reviewEvidence.repository !== request.candidate.repository ||
467
+ reviewEvidence.pullRequest !== request.candidate.reviewPullRequest
468
+ )
469
+ fail(
470
+ "review-identity-mismatch",
471
+ "review evidence does not bind the candidate",
472
+ );
473
+ const reviewedSha = reviewedRuntimeSha(request, policy, reviewEvidence, runtimeSha);
474
+ const approvedReviewers = new Set(
475
+ reviewEvidence.approvals
476
+ .filter((approval) => approval.commitSha === reviewedSha)
477
+ .map((approval) => approval.reviewer),
478
+ );
479
+ const admittedApprovalCount = policy.allowedReviewers.filter((reviewer) =>
480
+ approvedReviewers.has(reviewer),
481
+ ).length;
482
+ if (admittedApprovalCount < policy.minimumApprovals)
483
+ fail(
484
+ "independent-review-missing",
485
+ "candidate lacks exact-head independent review",
486
+ );
487
+ const checksByName = new Map();
488
+ for (const check of reviewEvidence.checks) {
489
+ const entries = checksByName.get(check.name) || [];
490
+ entries.push(check);
491
+ checksByName.set(check.name, entries);
492
+ }
493
+ if (
494
+ policy.requiredChecks.some((name) => {
495
+ const checks = checksByName.get(name) || [];
496
+ return (
497
+ checks.length === 0 ||
498
+ checks.some(
499
+ (check) =>
500
+ check.status !== "completed" || check.conclusion !== "success" ||
501
+ (check.commitSha !== undefined && check.commitSha !== runtimeSha),
502
+ )
503
+ );
504
+ })
505
+ )
506
+ fail(
507
+ "exact-head-checks-incomplete",
508
+ "candidate exact-head checks are not successful",
509
+ );
510
+ const requestRoot = v4UniversalWorkflowRequestRoot(request);
511
+ const discovery = {
512
+ repository: request.candidate.repository,
513
+ ref: request.candidate.discoveryRef,
514
+ expectedSha: request.candidate.expectedSha,
515
+ observedSha: runtimeSha,
516
+ observedAt,
517
+ };
518
+ return {
519
+ schema: V4_UNIVERSAL_WORKFLOW_ADMISSION,
520
+ status: "admitted",
521
+ requestRoot,
522
+ admissionRoot,
523
+ discoveryRoot: documentRoot("universal-workflow-discovery", discovery),
524
+ reviewRoot: documentRoot("universal-workflow-review", reviewEvidence),
525
+ consumerRoot: documentRoot("universal-workflow-consumer", request.consumer),
526
+ capabilityRoot: documentRoot(
527
+ "universal-workflow-capability",
528
+ request.capability,
529
+ ),
530
+ runtime: {
531
+ repository: request.candidate.repository,
532
+ sha: runtimeSha,
533
+ },
534
+ permissions: request.capability.permissions,
535
+ contractRoots: request.capability.contractRoots,
536
+ };
537
+ }
538
+
539
+ export function completeV4UniversalWorkflow({ admission, resultRoot, status }) {
540
+ exactKeys(
541
+ admission,
542
+ [
543
+ "schema",
544
+ "status",
545
+ "requestRoot",
546
+ "admissionRoot",
547
+ "discoveryRoot",
548
+ "reviewRoot",
549
+ "consumerRoot",
550
+ "capabilityRoot",
551
+ "runtime",
552
+ "permissions",
553
+ "contractRoots",
554
+ ],
555
+ "admission",
556
+ );
557
+ if (
558
+ admission.schema !== V4_UNIVERSAL_WORKFLOW_ADMISSION ||
559
+ admission.status !== "admitted"
560
+ )
561
+ fail("invalid-admission", "terminal receipt requires an admitted request");
562
+ if (!new Set(["succeeded", "failed", "cancelled"]).has(status))
563
+ fail("invalid-terminal-status", "terminal status is unsupported");
564
+ const receipt = {
565
+ schema: V4_UNIVERSAL_WORKFLOW_TERMINAL_RECEIPT,
566
+ status,
567
+ requestRoot: root(admission.requestRoot, "admission.requestRoot"),
568
+ admissionRoot: root(admission.admissionRoot, "admission.admissionRoot"),
569
+ discoveryRoot: root(admission.discoveryRoot, "admission.discoveryRoot"),
570
+ reviewRoot: root(admission.reviewRoot, "admission.reviewRoot"),
571
+ consumerRoot: root(admission.consumerRoot, "admission.consumerRoot"),
572
+ capabilityRoot: root(admission.capabilityRoot, "admission.capabilityRoot"),
573
+ runtime: {
574
+ repository: repository(
575
+ admission.runtime?.repository,
576
+ "admission.runtime.repository",
577
+ ),
578
+ sha: exactSha(admission.runtime?.sha, "admission.runtime.sha"),
579
+ },
580
+ resultRoot: root(resultRoot, "resultRoot"),
581
+ };
582
+ return {
583
+ ...receipt,
584
+ receiptRoot: documentRoot("universal-workflow-receipt", receipt),
585
+ };
586
+ }