@rightkit/ci 0.0.0-stage → 0.2.42

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/manifest.mjs ADDED
@@ -0,0 +1,1860 @@
1
+ // Loader and hand-rolled validator for the per-repo `.rightgit.json` manifest.
2
+ // Mirrors the shape documented in manifest.schema.json. No ajv dependency —
3
+ // validation is plain JS so the package stays dependency-free (node builtins only).
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { validateCheckout } from "./checkout.mjs";
8
+
9
+ export const MANIFEST_FILENAME = ".rightgit.json";
10
+
11
+ export const KNOWN_LANES = Object.freeze([
12
+ "ci",
13
+ "qualification",
14
+ "package-smoke",
15
+ "release-candidate",
16
+ "publish-npm",
17
+ "publish-package-managers",
18
+ "regenerate",
19
+ ]);
20
+
21
+ // Rendered filename for each lane, installed under <repo>/.github/workflows/.
22
+ export const LANE_FILENAMES = Object.freeze({
23
+ ci: "ci.yml",
24
+ qualification: "qualification.yml",
25
+ "package-smoke": "package-smoke.yml",
26
+ "release-candidate": "release-candidate.yml",
27
+ "publish-npm": "publish-npm.yml",
28
+ "publish-package-managers": "publish-package-managers.yml",
29
+ regenerate: "regenerate.yml",
30
+ });
31
+
32
+ const PACKAGE_MANAGER_RE = /^(pnpm|npm|yarn)@\d+\.\d+\.\d+$/;
33
+ const TEMPLATE_VERSION_RE = /^\d+\.\d+\.\d+$/;
34
+
35
+ // F15 fix: every one of these fields is manifest (attacker-controlled)
36
+ // input that flows verbatim into a rendered workflow file via render.mjs's
37
+ // literal `${TOKEN}` substitution — render.mjs does no escaping, by design
38
+ // (it is a byte-deterministic template engine, not a YAML/expression-aware
39
+ // one). The re-validation proved a hostile `publish.homebrew.formulaName`
40
+ // containing GitHub Actions expression syntax (`${{ secrets.APPLE_... }}`)
41
+ // survived unmodified into rendered YAML, which GitHub Actions would then
42
+ // evaluate as a real expression — a workflow-expression injection, not just
43
+ // a cosmetic issue. The fix is at the INPUT boundary, not the render step:
44
+ // every manifest field that reaches a template must match a strict
45
+ // allowlist charset that cannot express `${{ }}`, backticks, `$()`,
46
+ // newlines, or any other shell/YAML/expression metacharacter — validated
47
+ // once here, so render.mjs can stay a dumb, deterministic string replacer.
48
+ const SAFE_MATRIX_VALUE_RE = /^[A-Za-z0-9][A-Za-z0-9._/*-]*$/;
49
+ const GITHUB_OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
50
+ const GITHUB_REPO_RE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,99})$/;
51
+ const HOMEBREW_FORMULA_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9+_.-]*$/;
52
+ const WINGET_PACKAGE_IDENTIFIER_RE = /^[A-Za-z0-9][A-Za-z0-9-]*(?:\.[A-Za-z0-9][A-Za-z0-9-]*)+$/;
53
+
54
+ const TOP_LEVEL_KEYS = new Set([
55
+ "schemaVersion",
56
+ "compile",
57
+ "lanes",
58
+ "matrix",
59
+ "packageManager",
60
+ "publish",
61
+ "templateVersion",
62
+ "profile",
63
+ "gate",
64
+ "rustCache",
65
+ "qaEvidencePath",
66
+ "qaEvidenceRetentionDays",
67
+ "ciAllOs",
68
+ "ciIncremental",
69
+ "concurrency",
70
+ "devArtifact",
71
+ "regenerate",
72
+ "candidate",
73
+ "ownership",
74
+ "swift",
75
+ "checkout",
76
+ "defaultBranch",
77
+ ]);
78
+ // Optional QA evidence upload (rust-hybrid ci only). qaEvidencePath is a safe
79
+ // relative path under $RUNNER_TEMP; it renders as `${{ runner.temp }}/<path>`.
80
+ const QA_EVIDENCE_DEFAULT_RETENTION_DAYS = 7;
81
+ const QA_EVIDENCE_MAX_RETENTION_DAYS = 90;
82
+ // Pinned to the same upload-artifact release the rust-hybrid release-candidate template uses.
83
+ const UPLOAD_ARTIFACT_PIN = "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4";
84
+ const GATE_PATH_RE = /^(?!.*\.\.)(?!.*\s)[A-Za-z0-9][A-Za-z0-9._/-]*$/;
85
+ const RUST_WORKSPACE_PATH_RE = /^(?:\.|(?!.*\.\.)(?!.*\s)[A-Za-z0-9][A-Za-z0-9._/-]*)$/;
86
+ const PACKAGE_SCRIPT_RE = /^[A-Za-z0-9][A-Za-z0-9:_-]*$/;
87
+ const GITHUB_VARIABLE_RE = /^[A-Z][A-Z0-9_]*$/;
88
+ const RELEASE_PLATFORMS = new Set(["windows", "macos", "linux"]);
89
+ const RELEASE_ARCHITECTURES = new Set(["x86_64", "arm64"]);
90
+ const NATIVE_RUNNER_TARGETS = new Map([
91
+ ["windows-2025", ["windows", "x86_64"]],
92
+ ["windows-11-arm", ["windows", "arm64"]],
93
+ ["macos-15", ["macos", "arm64"]],
94
+ ["macos-15-intel", ["macos", "x86_64"]],
95
+ ]);
96
+
97
+ // Hosted `macos-*` runners plus the self-hosted Xcode runner labels (`xcode-27`).
98
+ const MACOS_RUNNER_RE = /^(macos|xcode)-/i;
99
+
100
+ function inferredTarget(os) {
101
+ const platform = /^windows-/i.test(os) ? "windows" : MACOS_RUNNER_RE.test(os) ? "macos" : "linux";
102
+ return { os, platform, architecture: platform === "macos" ? "arm64" : "x86_64" };
103
+ }
104
+
105
+ function candidateTargets(candidate) {
106
+ return Array.isArray(candidate?.targets) ? candidate.targets : (candidate?.os ?? []).map(inferredTarget);
107
+ }
108
+
109
+ /**
110
+ * Validate a parsed manifest object against the right-git manifest contract.
111
+ * Never throws. Returns { valid, errors }.
112
+ */
113
+ export function validateManifest(manifest) {
114
+ const errors = [];
115
+
116
+ if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) {
117
+ return { valid: false, errors: ["manifest must be a JSON object"] };
118
+ }
119
+
120
+ for (const key of Object.keys(manifest)) {
121
+ if (!TOP_LEVEL_KEYS.has(key)) errors.push(`unknown top-level field: ${key}`);
122
+ }
123
+
124
+ if (manifest.schemaVersion !== 1) {
125
+ errors.push("schemaVersion must be exactly 1");
126
+ }
127
+ if (manifest.compile !== "github-actions-only") {
128
+ errors.push("compile must be exactly 'github-actions-only' for public repositories");
129
+ }
130
+
131
+ let lanes = [];
132
+ if (!Array.isArray(manifest.lanes) || manifest.lanes.length === 0) {
133
+ errors.push("lanes must be a non-empty array");
134
+ } else {
135
+ lanes = manifest.lanes;
136
+ const seen = new Set();
137
+ for (const lane of lanes) {
138
+ if (typeof lane !== "string" || !KNOWN_LANES.includes(lane)) {
139
+ errors.push(`unknown lane: ${JSON.stringify(lane)}`);
140
+ } else if (seen.has(lane)) {
141
+ errors.push(`duplicate lane: ${lane}`);
142
+ } else {
143
+ seen.add(lane);
144
+ }
145
+ }
146
+ }
147
+
148
+ if (manifest.matrix === null || typeof manifest.matrix !== "object" || Array.isArray(manifest.matrix)) {
149
+ errors.push("matrix must be an object with os and node arrays");
150
+ } else {
151
+ for (const field of ["os", "node"]) {
152
+ const value = manifest.matrix[field];
153
+ if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && SAFE_MATRIX_VALUE_RE.test(v))) {
154
+ errors.push(
155
+ `matrix.${field} must be a non-empty array of safe runner/version labels (letters, digits, '.', '_', '-', '/', '*' only — no expression or shell syntax)`,
156
+ );
157
+ }
158
+ }
159
+ for (const key of Object.keys(manifest.matrix)) {
160
+ if (key !== "os" && key !== "node") errors.push(`unknown matrix field: ${key}`);
161
+ }
162
+ }
163
+
164
+ if (typeof manifest.packageManager !== "string" || !PACKAGE_MANAGER_RE.test(manifest.packageManager)) {
165
+ errors.push("packageManager must match '<pnpm|npm|yarn>@X.Y.Z'");
166
+ }
167
+
168
+ if (typeof manifest.templateVersion !== "string" || !TEMPLATE_VERSION_RE.test(manifest.templateVersion)) {
169
+ errors.push("templateVersion must be a semver string 'X.Y.Z'");
170
+ }
171
+
172
+ const profile = manifest.profile === undefined ? "node" : manifest.profile;
173
+ if (profile !== "node" && profile !== "rust-hybrid") errors.push("profile must be 'node' or 'rust-hybrid'");
174
+ if (profile === "rust-hybrid") {
175
+ if (lanes.some((lane) => lane !== "ci" && lane !== "release-candidate" && lane !== "regenerate") || !lanes.includes("ci")) {
176
+ errors.push("profile 'rust-hybrid' requires lane 'ci' and supports optional lanes 'release-candidate' and 'regenerate'");
177
+ }
178
+ if (!manifest.gate || typeof manifest.gate !== "object" || Array.isArray(manifest.gate) || Object.keys(manifest.gate).some((key) => key !== "path") || typeof manifest.gate.path !== "string" || !GATE_PATH_RE.test(manifest.gate.path)) {
179
+ errors.push("profile 'rust-hybrid' requires gate.path with a safe relative path");
180
+ }
181
+ } else if (manifest.gate !== undefined) {
182
+ errors.push("gate is only valid for profile 'rust-hybrid'");
183
+ }
184
+
185
+ validateCheckout(manifest.checkout, errors);
186
+ // defaultBranch: the branch the push triggers and the release-candidate admission use. Default "main".
187
+ if (manifest.defaultBranch !== undefined
188
+ && (typeof manifest.defaultBranch !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(manifest.defaultBranch) || manifest.defaultBranch.includes(".."))) {
189
+ errors.push("defaultBranch must be one safe branch name (letters, digits, '.', '_', '-'; no '/', whitespace, '..' or expression syntax)");
190
+ }
191
+
192
+ if (manifest.qaEvidencePath !== undefined) {
193
+ if (profile !== "rust-hybrid") {
194
+ errors.push("qaEvidencePath is only valid for profile 'rust-hybrid'");
195
+ } else if (typeof manifest.qaEvidencePath !== "string" || !GATE_PATH_RE.test(manifest.qaEvidencePath)) {
196
+ errors.push("qaEvidencePath must be a safe relative path under $RUNNER_TEMP (no '..', whitespace, leading '/', or expression syntax)");
197
+ }
198
+ }
199
+ if (manifest.qaEvidenceRetentionDays !== undefined) {
200
+ if (manifest.qaEvidencePath === undefined) {
201
+ errors.push("qaEvidenceRetentionDays requires qaEvidencePath");
202
+ } else if (!Number.isInteger(manifest.qaEvidenceRetentionDays) || manifest.qaEvidenceRetentionDays < 1 || manifest.qaEvidenceRetentionDays > QA_EVIDENCE_MAX_RETENTION_DAYS) {
203
+ errors.push(`qaEvidenceRetentionDays must be an integer from 1 to ${QA_EVIDENCE_MAX_RETENTION_DAYS}`);
204
+ }
205
+ }
206
+
207
+ // ciAllOs (rust-hybrid ci only): run the gate on every matrix.os runner
208
+ // instead of one declared runner. Omitted or false keeps the single-runner ci job.
209
+ if (manifest.ciAllOs !== undefined) {
210
+ if (typeof manifest.ciAllOs !== "boolean") {
211
+ errors.push("ciAllOs must be a boolean");
212
+ } else if (manifest.ciAllOs === true && profile !== "rust-hybrid") {
213
+ errors.push("ciAllOs is only valid for profile 'rust-hybrid'");
214
+ }
215
+ }
216
+
217
+ // ciIncremental (rust-hybrid ci only): opt-in incremental Rust + DerivedData caching.
218
+ if (manifest.ciIncremental !== undefined) {
219
+ if (typeof manifest.ciIncremental !== "boolean") {
220
+ errors.push("ciIncremental must be a boolean");
221
+ } else if (manifest.ciIncremental === true && profile !== "rust-hybrid") {
222
+ errors.push("ciIncremental is only valid for profile 'rust-hybrid'");
223
+ }
224
+ }
225
+
226
+ if (manifest.concurrency !== undefined) validateConcurrency(manifest, lanes, errors);
227
+ validateDevArtifact(manifest, profile, errors);
228
+ validateRegenerate(manifest, lanes, errors);
229
+
230
+ const rustCache = manifest.rustCache;
231
+ if (rustCache !== undefined) {
232
+ if (profile !== "rust-hybrid") {
233
+ errors.push("rustCache is only valid for profile 'rust-hybrid'");
234
+ } else if (rustCache === null || typeof rustCache !== "object" || Array.isArray(rustCache)) {
235
+ errors.push("rustCache must be an object");
236
+ } else {
237
+ for (const key of Object.keys(rustCache)) {
238
+ if (!["workspaces", "requiredForGate", "keySuffix"].includes(key)) errors.push(`unknown rustCache field: ${key}`);
239
+ }
240
+ if (!Array.isArray(rustCache.workspaces) || rustCache.workspaces.length === 0) {
241
+ errors.push("rustCache.workspaces must be a non-empty array");
242
+ } else if (rustCache.workspaces.some((value) => typeof value !== "string" || !RUST_WORKSPACE_PATH_RE.test(value))) {
243
+ errors.push("rustCache.workspaces entries must be safe relative paths");
244
+ } else if (new Set(rustCache.workspaces).size !== rustCache.workspaces.length) {
245
+ errors.push("rustCache.workspaces entries must be unique");
246
+ }
247
+ if (rustCache.requiredForGate !== undefined && typeof rustCache.requiredForGate !== "boolean") {
248
+ errors.push("rustCache.requiredForGate must be a boolean");
249
+ }
250
+ if (rustCache.keySuffix !== undefined && (typeof rustCache.keySuffix !== "string" || !RUST_CACHE_KEY_SUFFIX_RE.test(rustCache.keySuffix))) {
251
+ errors.push("rustCache.keySuffix must be 1 to 64 characters: letters, digits, '.', '_', '-', starting with a letter or digit");
252
+ }
253
+ }
254
+ }
255
+
256
+ const candidate = manifest.candidate;
257
+ if (candidate !== undefined) {
258
+ if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
259
+ errors.push("candidate must be an object");
260
+ } else {
261
+ for (const key of Object.keys(candidate)) {
262
+ if (!["buildScript", "checkScript", "admissionScript", "stageSummaryScript", "artifactRoot", "os", "targets", "signWindows", "signMacos", "releaseChain"].includes(key)) errors.push(`unknown candidate field: ${key}`);
263
+ }
264
+ // admissionScript & stageSummaryScript are required for EVERY release-candidate
265
+ // lane, not just signed/full-releaseChain ones: the tag-last workflow's
266
+ // `admission` job (dispatch-envelope validation) and the `candidate` job's
267
+ // stage-summary init/finalize steps are unconditional parts of the rendered
268
+ // template, independent of candidate.signWindows/signMacos/releaseChain. If
269
+ // either script were only required inside the optional releaseChain object,
270
+ // an unsigned release-candidate manifest (no releaseChain at all) would still
271
+ // render those unconditional steps with an unresolved script name.
272
+ for (const key of ["buildScript", "checkScript", "admissionScript", "stageSummaryScript"]) {
273
+ if (typeof candidate[key] !== "string" || !PACKAGE_SCRIPT_RE.test(candidate[key])) {
274
+ errors.push(`candidate.${key} must be one safe package script name`);
275
+ }
276
+ }
277
+ if (typeof candidate.artifactRoot !== "string" || !GATE_PATH_RE.test(candidate.artifactRoot)) {
278
+ errors.push("candidate.artifactRoot must be one safe relative path");
279
+ }
280
+ if (!Array.isArray(candidate.os) || candidate.os.length === 0 || candidate.os.some((value) => typeof value !== "string" || !SAFE_MATRIX_VALUE_RE.test(value))) {
281
+ errors.push("candidate.os must be a non-empty array of safe runner labels");
282
+ } else if (candidate.targets === undefined && candidate.os.some((value) => !manifest.matrix?.os?.includes(value))) {
283
+ errors.push("candidate.os entries must also exist in matrix.os");
284
+ }
285
+ if (candidate.targets !== undefined) {
286
+ if (!Array.isArray(candidate.targets) || candidate.targets.length === 0) {
287
+ errors.push("candidate.targets must be a non-empty array");
288
+ } else {
289
+ const targetKeys = new Set();
290
+ for (const target of candidate.targets) {
291
+ if (target === null || typeof target !== "object" || Array.isArray(target)) {
292
+ errors.push("candidate.targets entries must be objects");
293
+ continue;
294
+ }
295
+ if (Object.keys(target).some((key) => !["os", "platform", "architecture"].includes(key))) errors.push("candidate.targets entries may only contain os, platform, architecture");
296
+ if (typeof target.os !== "string" || !SAFE_MATRIX_VALUE_RE.test(target.os)) errors.push("candidate.targets[].os must be a safe runner label");
297
+ if (!RELEASE_PLATFORMS.has(target.platform)) errors.push("candidate.targets[].platform must be windows, macos, or linux");
298
+ if (!RELEASE_ARCHITECTURES.has(target.architecture)) errors.push("candidate.targets[].architecture must be x86_64 or arm64");
299
+ const nativeTarget = NATIVE_RUNNER_TARGETS.get(target.os);
300
+ if (nativeTarget && (target.platform !== nativeTarget[0] || target.architecture !== nativeTarget[1])) {
301
+ errors.push(`candidate.targets[] must declare ${target.os} as ${nativeTarget[0]}/${nativeTarget[1]}`);
302
+ }
303
+ if ((target.platform === "windows" && !/^windows-/i.test(target.os)) || (target.platform === "macos" && !MACOS_RUNNER_RE.test(target.os))) {
304
+ errors.push("candidate.targets[].os must match its Windows or macOS platform");
305
+ }
306
+ const targetKey = `${target.os}|${target.platform}|${target.architecture}`;
307
+ if (targetKeys.has(targetKey)) errors.push("candidate.targets entries must be unique");
308
+ targetKeys.add(targetKey);
309
+ }
310
+ const targetOs = new Set(candidate.targets.map((target) => target?.os));
311
+ if (candidate.os.some((os) => !targetOs.has(os)) || targetOs.size !== new Set(candidate.os).size || candidate.os.length !== new Set(candidate.os).size) {
312
+ errors.push("candidate.os must contain exactly candidate.targets runner labels");
313
+ }
314
+ }
315
+ }
316
+ const targets = candidateTargets(candidate);
317
+ if (candidate.signWindows !== undefined && typeof candidate.signWindows !== "boolean") {
318
+ errors.push("candidate.signWindows must be a boolean");
319
+ }
320
+ if (candidate.signWindows === true && targets.filter((target) => target?.platform === "windows").length === 0) {
321
+ errors.push("candidate.signWindows requires at least one Windows target");
322
+ }
323
+ if (candidate.signMacos !== undefined && typeof candidate.signMacos !== "boolean") {
324
+ errors.push("candidate.signMacos must be a boolean");
325
+ }
326
+ if (candidate.signMacos === true && targets.filter((target) => target?.platform === "macos").length === 0) {
327
+ errors.push("candidate.signMacos requires at least one macOS target");
328
+ }
329
+ if ((candidate.signWindows === true || candidate.signMacos === true) && manifest.matrix?.node?.length !== 1) {
330
+ errors.push("candidate signing requires exactly one matrix.node version");
331
+ }
332
+ if (candidate.releaseChain !== undefined) {
333
+ const chain = candidate.releaseChain;
334
+ // admissionScript & stageSummaryScript live on candidate directly (see
335
+ // above) — the full signed release chain adds evidenceVerificationScript
336
+ // (runs before publish, verifying aggregated same-run evidence) plus the
337
+ // finalize/qualify/publish scripts.
338
+ const allowedChainKeys = ["evidenceVerificationScript", "windowsFinalizeScript", "macosFinalizeScript", "installedQualificationScript", "publishScript", "qualificationRunnerVariable", "publishSecrets", "environments"];
339
+ if (chain === null || typeof chain !== "object" || Array.isArray(chain)) {
340
+ errors.push("candidate.releaseChain must be an object");
341
+ } else {
342
+ for (const key of Object.keys(chain)) {
343
+ if (!allowedChainKeys.includes(key)) errors.push(`unknown candidate.releaseChain field: ${key}`);
344
+ }
345
+ for (const key of ["evidenceVerificationScript", "windowsFinalizeScript", "installedQualificationScript", "publishScript"]) {
346
+ if (typeof chain[key] !== "string" || !PACKAGE_SCRIPT_RE.test(chain[key])) {
347
+ errors.push(`candidate.releaseChain.${key} must be one safe package script name`);
348
+ }
349
+ }
350
+ if (chain.macosFinalizeScript !== undefined && (typeof chain.macosFinalizeScript !== "string" || !PACKAGE_SCRIPT_RE.test(chain.macosFinalizeScript))) {
351
+ if (chain.environments !== undefined) {
352
+ const environments = chain.environments;
353
+ if (environments === null || typeof environments !== "object" || Array.isArray(environments)) {
354
+ errors.push("candidate.releaseChain.environments must be an object");
355
+ } else {
356
+ for (const key of Object.keys(environments)) {
357
+ if (!["signing", "qualification", "publication"].includes(key)) errors.push(`unknown candidate.releaseChain.environments field: ${key}`);
358
+ else if (typeof environments[key] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/.test(environments[key])) {
359
+ errors.push(`candidate.releaseChain.environments.${key} must be one safe GitHub environment name`);
360
+ }
361
+ }
362
+ }
363
+ }
364
+ errors.push("candidate.releaseChain.macosFinalizeScript must be one safe package script name");
365
+ }
366
+ if (typeof chain.qualificationRunnerVariable !== "string" || !GITHUB_VARIABLE_RE.test(chain.qualificationRunnerVariable)) {
367
+ errors.push("candidate.releaseChain.qualificationRunnerVariable must be one uppercase GitHub variable name");
368
+ }
369
+ if (chain.publishSecrets !== undefined && (!Array.isArray(chain.publishSecrets) || new Set(chain.publishSecrets).size !== chain.publishSecrets.length || chain.publishSecrets.some((value) => typeof value !== "string" || !GITHUB_VARIABLE_RE.test(value)))) {
370
+ errors.push("candidate.releaseChain.publishSecrets must be unique uppercase GitHub secret names");
371
+ }
372
+ if (candidate.signWindows !== true) errors.push("candidate.releaseChain requires candidate.signWindows=true");
373
+ if (targets.filter((target) => target?.platform === "windows").length !== 1 || targets.filter((target) => target?.platform === "macos").length > 1) {
374
+ errors.push("candidate.releaseChain requires at most one target per signing platform; multi-target aggregation is not supported");
375
+ }
376
+ if (candidate.signMacos === true && !chain.macosFinalizeScript) errors.push("candidate.releaseChain with candidate.signMacos=true requires macosFinalizeScript");
377
+ if (chain.macosFinalizeScript && candidate.signMacos !== true) errors.push("candidate.releaseChain.macosFinalizeScript requires candidate.signMacos=true");
378
+ }
379
+ }
380
+ }
381
+ }
382
+ if (profile === "rust-hybrid" && lanes.includes("release-candidate") && candidate === undefined) {
383
+ errors.push("rust-hybrid release-candidate lane requires candidate { buildScript, checkScript, artifactRoot }");
384
+ }
385
+
386
+ if (manifest.ownership !== undefined) {
387
+ if (!manifest.ownership || typeof manifest.ownership !== "object" || Array.isArray(manifest.ownership)
388
+ || Object.keys(manifest.ownership).some((key) => key !== "roots")) {
389
+ errors.push("ownership must be an object containing only roots");
390
+ } else if (!Array.isArray(manifest.ownership.roots) || manifest.ownership.roots.length === 0
391
+ || manifest.ownership.roots.some((root) => typeof root !== "string" || (root !== "." && !/^(?!.*\.\.)(?!.*\\)(?!.*\s)[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(root)) || root.startsWith("/"))) {
392
+ errors.push("ownership.roots must contain safe, non-empty repository-relative paths");
393
+ } else if (new Set(manifest.ownership.roots).size !== manifest.ownership.roots.length) {
394
+ errors.push("ownership.roots must not contain duplicates");
395
+ }
396
+ }
397
+ if (manifest.swift !== undefined) validateSwift(manifest, lanes, errors);
398
+ if (profile !== "rust-hybrid" && candidate !== undefined) {
399
+ errors.push("candidate is only valid for profile 'rust-hybrid'");
400
+ }
401
+
402
+ const publish = manifest.publish;
403
+ if (publish !== undefined) {
404
+ if (publish === null || typeof publish !== "object" || Array.isArray(publish)) {
405
+ errors.push("publish must be an object");
406
+ } else {
407
+ for (const key of Object.keys(publish)) {
408
+ if (!["npm", "homebrew", "winget"].includes(key)) errors.push(`unknown publish field: ${key}`);
409
+ }
410
+ if (publish.npm !== undefined) {
411
+ const npm = publish.npm;
412
+ if (npm === null || typeof npm !== "object") {
413
+ errors.push("publish.npm must be an object");
414
+ } else {
415
+ if (npm.oidc !== true) errors.push("publish.npm.oidc must be true (I2: OIDC is the only publish credential)");
416
+ if (typeof npm.provenance !== "boolean") errors.push("publish.npm.provenance must be a boolean");
417
+ }
418
+ }
419
+ if (publish.homebrew !== undefined) {
420
+ const hb = publish.homebrew;
421
+ if (hb === null || typeof hb !== "object") {
422
+ errors.push("publish.homebrew must be an object");
423
+ } else {
424
+ const tapMatch = typeof hb.tap === "string" ? /^([^/]+)\/([^/]+)$/.exec(hb.tap) : null;
425
+ if (!tapMatch || !GITHUB_OWNER_RE.test(tapMatch[1]) || !GITHUB_REPO_RE.test(tapMatch[2])) {
426
+ errors.push(
427
+ "publish.homebrew.tap must be 'owner/repo' using GitHub-safe characters only (letters, digits, '-', '_', '.' — no expression or shell syntax)",
428
+ );
429
+ }
430
+ if (typeof hb.formulaName !== "string" || !HOMEBREW_FORMULA_NAME_RE.test(hb.formulaName)) {
431
+ errors.push(
432
+ "publish.homebrew.formulaName must be a Homebrew-safe identifier (letters, digits, '+', '_', '.', '-' only — no expression or shell syntax)",
433
+ );
434
+ }
435
+ }
436
+ }
437
+ if (publish.winget !== undefined) {
438
+ const wg = publish.winget;
439
+ if (wg === null || typeof wg !== "object" || typeof wg.packageIdentifier !== "string" || !WINGET_PACKAGE_IDENTIFIER_RE.test(wg.packageIdentifier)) {
440
+ errors.push(
441
+ "publish.winget.packageIdentifier must be a dotted WinGet-safe identifier, e.g. 'Publisher.Package' (letters, digits, '-', '.' only — no expression or shell syntax)",
442
+ );
443
+ }
444
+ }
445
+ }
446
+ }
447
+
448
+ if (lanes.includes("publish-npm")) {
449
+ if (!publish || !publish.npm) {
450
+ errors.push("lane 'publish-npm' requires publish.npm { oidc: true, provenance }");
451
+ }
452
+ }
453
+
454
+ if (lanes.includes("publish-package-managers")) {
455
+ if (!publish || !publish.homebrew) {
456
+ errors.push("lane 'publish-package-managers' requires publish.homebrew { tap, formulaName }");
457
+ }
458
+ if (!publish || !publish.winget) {
459
+ errors.push("lane 'publish-package-managers' requires publish.winget { packageIdentifier }");
460
+ }
461
+ }
462
+
463
+ return { valid: errors.length === 0, errors };
464
+ }
465
+
466
+ /**
467
+ * Read and validate `<repoPath>/.rightgit.json`.
468
+ * Never throws — returns a typed result: { ok, manifest, errors, path }.
469
+ */
470
+ export function loadManifest(repoPath) {
471
+ const manifestPath = path.join(repoPath, MANIFEST_FILENAME);
472
+ let raw;
473
+ try {
474
+ raw = fs.readFileSync(manifestPath, "utf8");
475
+ } catch (error) {
476
+ return { ok: false, manifest: null, errors: [`cannot read ${manifestPath}: ${error.message}`], path: manifestPath };
477
+ }
478
+
479
+ let manifest;
480
+ try {
481
+ manifest = JSON.parse(raw);
482
+ } catch (error) {
483
+ return { ok: false, manifest: null, errors: [`invalid JSON in ${manifestPath}: ${error.message}`], path: manifestPath };
484
+ }
485
+
486
+ const { valid, errors } = validateManifest(manifest);
487
+ if (!valid) {
488
+ return { ok: false, manifest, errors, path: manifestPath };
489
+ }
490
+ return { ok: true, manifest, errors: [], path: manifestPath };
491
+ }
492
+
493
+ function parsePackageManager(spec) {
494
+ const match = /^(pnpm|npm|yarn)@(\d+\.\d+\.\d+)$/.exec(spec);
495
+ if (!match) throw new Error(`invalid packageManager spec: ${spec}`);
496
+ const [, name, version] = match;
497
+ const installCommand = {
498
+ pnpm: "pnpm install --frozen-lockfile",
499
+ npm: "npm ci",
500
+ yarn: "yarn install --frozen-lockfile",
501
+ }[name];
502
+ const runPrefix = { pnpm: "pnpm run", npm: "npm run", yarn: "yarn run" }[name];
503
+ const setup = {
504
+ pnpm: ` - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10\n with:\n version: ${version}`,
505
+ npm: "",
506
+ yarn: ` - run: corepack enable && corepack prepare yarn@${version} --activate`,
507
+ }[name];
508
+ return { name, version, installCommand, runPrefix, setup };
509
+ }
510
+
511
+ function yamlFlowStringList(values) {
512
+ return `[${values.map((v) => JSON.stringify(String(v))).join(", ")}]`;
513
+ }
514
+
515
+ function candidateMatrix(manifest) {
516
+ const entries = [];
517
+ for (const target of candidateTargets(manifest.candidate ?? { os: manifest.matrix.os })) {
518
+ for (const node of manifest.matrix.node) entries.push({ ...target, node, targetTriple: targetTriple(target) });
519
+ }
520
+ return [
521
+ " include:",
522
+ ...entries.flatMap((entry) => [
523
+ ` - os: ${JSON.stringify(entry.os)}`,
524
+ ` node: ${JSON.stringify(entry.node)}`,
525
+ ` platform: ${JSON.stringify(entry.platform)}`,
526
+ ` architecture: ${JSON.stringify(entry.architecture)}`,
527
+ ` targetTriple: ${JSON.stringify(entry.targetTriple)}`,
528
+ ]),
529
+ ].join("\n");
530
+ }
531
+
532
+ function targetTriple(target) {
533
+ const rustArchitecture = target.architecture === "arm64" ? "aarch64" : target.architecture;
534
+ if (target.platform === "windows") return `${rustArchitecture}-pc-windows-msvc`;
535
+ if (target.platform === "macos") return `${rustArchitecture}-apple-darwin`;
536
+ return `${rustArchitecture}-unknown-linux-gnu`;
537
+ }
538
+
539
+ function signingMatrix(manifest, platform) {
540
+ const node = String(manifest.matrix.node[0]);
541
+ const entries = candidateTargets(manifest.candidate)
542
+ .filter((target) => target.platform === platform)
543
+ .map((target) => ({ ...target, node, targetTriple: targetTriple(target) }));
544
+ return [
545
+ " include:",
546
+ ...entries.flatMap((entry) => [
547
+ ` - os: ${JSON.stringify(entry.os)}`,
548
+ ` platform: ${JSON.stringify(entry.platform)}`,
549
+ ` architecture: ${JSON.stringify(entry.architecture)}`,
550
+ ` targetTriple: ${JSON.stringify(entry.targetTriple)}`,
551
+ ` node: ${JSON.stringify(entry.node)}`,
552
+ ]),
553
+ ].join("\n");
554
+ }
555
+
556
+ const AZURE_LOGIN_SHA = "7ddb5af1ef8758cf1353cf3b42f940aee27ba21c"; // v3
557
+ const DOWNLOAD_ARTIFACT_SHA = "d3f86a106a0bac45b974a628896c90dbdf5c8093"; // v4.3.0
558
+ const UPLOAD_ARTIFACT_SHA = "ea165f8d65b6e75b540449e92b4886f43607fa02"; // v4
559
+ const ARTIFACT_SIGNING_CLIENT_VERSION = "1.0.128";
560
+ const ARTIFACT_SIGNING_CLIENT_SHA256 = "74BD7D27E6CE1051409C38D9B46BC8DF0400ECD643D51FFBF2AC00869061E40B";
561
+ const WINDOWS_SDK_BUILD_TOOLS_VERSION = "10.0.26100.4188";
562
+ const WINDOWS_SDK_BUILD_TOOLS_SHA256 = "180DEB372659029864C10A0C04787833234D64AACD1D2C0661D2C00295D8E022";
563
+
564
+ // Signing and publication credentials must be reachable behind distinct
565
+ // protected environments, so a job that may sign cannot also publish. Products
566
+ // opt in per environment; absent configuration keeps the single `release`
567
+ // environment they use today, so enabling the split cannot strand secrets.
568
+ function releaseEnvironment(manifest, role) {
569
+ const configured = manifest?.candidate?.releaseChain?.environments?.[role];
570
+ return typeof configured === "string" && configured.length > 0 ? configured : "release";
571
+ }
572
+
573
+ // Dev artifacts (rust-hybrid ci only): fast, non-release builds on push to the default branch.
574
+ const DEV_ARTIFACT_DEFAULT_RETENTION_DAYS = 7;
575
+ const DEV_ARTIFACT_MAX_RETENTION_DAYS = 90;
576
+ const DEV_MAC_PATH_RE = /^(?!.*\.\.)[A-Za-z0-9][A-Za-z0-9._/ -]*$/;
577
+ const DEV_WINDOWS_GLOB_RE = /^(?!.*\.\.)[A-Za-z0-9][A-Za-z0-9._/*?-]*$/;
578
+ const CACHE_ACTION_PIN = "actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4";
579
+
580
+ function effectiveCiRunners(manifest) {
581
+ const os = manifest.matrix?.os;
582
+ if (!Array.isArray(os) || os.length === 0) return [];
583
+ if (manifest.ciAllOs === true) return os;
584
+ return [os.find((runner) => typeof runner === "string" && runner.startsWith("windows-")) ?? os[0]];
585
+ }
586
+
587
+ // The regenerate lane is manual-only: it runs `regenerate.script`, checks the
588
+ // result, and opens a pull request from a right-git/regenerate-<run> branch.
589
+ // It never writes to the default branch.
590
+ function validateRegenerate(manifest, lanes, errors) {
591
+ const regenerate = manifest.regenerate;
592
+ const hasLane = Array.isArray(lanes) && lanes.includes("regenerate");
593
+ if (regenerate === undefined) {
594
+ if (hasLane) errors.push("lane 'regenerate' requires regenerate { script }");
595
+ return;
596
+ }
597
+ if (regenerate === null || typeof regenerate !== "object" || Array.isArray(regenerate)) {
598
+ errors.push("regenerate must be an object");
599
+ return;
600
+ }
601
+ if (!hasLane) errors.push("regenerate requires lane 'regenerate'");
602
+ for (const key of Object.keys(regenerate)) {
603
+ if (key !== "script") errors.push(`unknown regenerate field: ${key}`);
604
+ }
605
+ if (typeof regenerate.script !== "string" || !PACKAGE_SCRIPT_RE.test(regenerate.script)) {
606
+ errors.push("regenerate.script must be a package.json script name (letters, digits, ':', '_', '-')");
607
+ }
608
+ }
609
+
610
+ // swift.privatePackages (ci, qualification, release-candidate and regenerate lanes;
611
+ // the parallel dev-artifact-mac job): read access to private Swift package
612
+ // mirrors from a public repository's CI. The secret is a GitHub Actions secret
613
+ // name; the token value never appears in the rendered workflow.
614
+ const SWIFT_PRIVATE_MAX_ENTRIES = 4;
615
+ // Lanes whose workflows carry the configure and cleanup steps. package-smoke,
616
+ // publish-npm and publish-package-managers never do (clean-room or credentialed jobs).
617
+ const SWIFT_PRIVATE_LANES = ["ci", "qualification", "release-candidate", "regenerate"];
618
+ const SWIFT_PRIVATE_HOST_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,62})(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,62}))*$/;
619
+
620
+ function isSwiftPrivateSecretName(value) {
621
+ return typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,99}$/.test(value) && !/^github_/i.test(value);
622
+ }
623
+
624
+ function validateSwift(manifest, lanes, errors) {
625
+ const swift = manifest.swift;
626
+ if (swift === null || typeof swift !== "object" || Array.isArray(swift)) {
627
+ errors.push("swift must be an object");
628
+ return;
629
+ }
630
+ for (const key of Object.keys(swift)) {
631
+ if (key !== "privatePackages") errors.push(`unknown swift field: ${key}`);
632
+ }
633
+ const entries = swift.privatePackages;
634
+ if (!Array.isArray(entries) || entries.length === 0 || entries.length > SWIFT_PRIVATE_MAX_ENTRIES) {
635
+ errors.push(`swift.privatePackages must be an array of 1 to ${SWIFT_PRIVATE_MAX_ENTRIES} { host, secret } entries`);
636
+ return;
637
+ }
638
+ const hosts = new Set();
639
+ entries.forEach((entry, index) => {
640
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((key) => key !== "host" && key !== "secret")) {
641
+ errors.push(`swift.privatePackages[${index}] must be an object with only host and secret`);
642
+ return;
643
+ }
644
+ if (typeof entry.host !== "string" || !SWIFT_PRIVATE_HOST_RE.test(entry.host)) {
645
+ errors.push(`swift.privatePackages[${index}].host must be a bare host name such as github.com`);
646
+ } else if (hosts.has(entry.host)) {
647
+ errors.push(`swift.privatePackages host must be unique: ${entry.host}`);
648
+ } else {
649
+ hosts.add(entry.host);
650
+ }
651
+ if (!isSwiftPrivateSecretName(entry.secret)) {
652
+ errors.push(`swift.privatePackages[${index}].secret must be a GitHub Actions secret name (letters, digits, '_'; not starting with a digit or GITHUB_)`);
653
+ }
654
+ });
655
+ if (!Array.isArray(lanes) || !lanes.some((lane) => SWIFT_PRIVATE_LANES.includes(lane))) {
656
+ errors.push(`swift.privatePackages requires one of the lanes ${SWIFT_PRIVATE_LANES.map((lane) => `'${lane}'`).join(", ")} (the steps render into those workflows)`);
657
+ }
658
+ // Dispatched runs of ci.yml can come from any ref; the private-package secret must never reach one.
659
+ if (manifest.devArtifact?.dispatch === true) {
660
+ errors.push("swift.privatePackages cannot be combined with devArtifact.dispatch: a manual dispatch of any ref would reach the secret");
661
+ }
662
+ }
663
+
664
+ function validateDevArtifact(manifest, profile, errors) {
665
+ const dev = manifest.devArtifact;
666
+ if (dev === undefined) return;
667
+ if (profile !== "rust-hybrid") {
668
+ errors.push("devArtifact is only valid for profile 'rust-hybrid'");
669
+ return;
670
+ }
671
+ if (dev === null || typeof dev !== "object" || Array.isArray(dev)) {
672
+ errors.push("devArtifact must be an object");
673
+ return;
674
+ }
675
+ for (const key of Object.keys(dev)) {
676
+ if (!["mac", "windows", "retentionDays", "macAppPath", "macEntitlements", "windowsGlob", "dispatch", "parallel", "buildScript"].includes(key)) errors.push(`unknown devArtifact field: ${key}`);
677
+ }
678
+ if (dev.mac !== undefined && !["sign", "notarize", "unsigned", "none"].includes(dev.mac)) errors.push("devArtifact.mac must be 'sign', 'notarize', 'unsigned' or 'none'");
679
+ if (dev.windows !== undefined && dev.windows !== "unsigned" && dev.windows !== "none") errors.push("devArtifact.windows must be 'unsigned' or 'none'");
680
+ const macSigned = dev.mac === "sign" || dev.mac === "notarize";
681
+ const macActive = macSigned || dev.mac === "unsigned";
682
+ if (!macActive && dev.windows !== "unsigned") errors.push("devArtifact requires mac 'sign'/'unsigned' and/or windows 'unsigned'");
683
+ if (dev.dispatch !== undefined && dev.dispatch !== true) errors.push("devArtifact.dispatch must be true when present");
684
+ if (dev.dispatch === true && dev.mac !== "unsigned" && dev.windows !== "unsigned") {
685
+ errors.push("devArtifact.dispatch builds only unsigned legs; declare mac 'unsigned' and/or windows 'unsigned'");
686
+ }
687
+ if (dev.retentionDays !== undefined && (!Number.isInteger(dev.retentionDays) || dev.retentionDays < 1 || dev.retentionDays > DEV_ARTIFACT_MAX_RETENTION_DAYS)) {
688
+ errors.push(`devArtifact.retentionDays must be an integer from 1 to ${DEV_ARTIFACT_MAX_RETENTION_DAYS}`);
689
+ }
690
+ if (dev.parallel !== undefined && typeof dev.parallel !== "boolean") errors.push("devArtifact.parallel must be a boolean");
691
+ if (dev.buildScript !== undefined && dev.parallel !== true) errors.push("devArtifact.buildScript requires devArtifact.parallel: true");
692
+ if (dev.parallel === true && (typeof dev.buildScript !== "string" || !PACKAGE_SCRIPT_RE.test(dev.buildScript))) {
693
+ errors.push("devArtifact.buildScript must be one safe package script name when parallel is true (it compiles the dev app in the dev-artifact job)");
694
+ }
695
+ // parallel jobs run on their own platform runners, so they do not depend on ciAllOs.
696
+ const runners = (dev.parallel === true ? (Array.isArray(manifest.matrix?.os) ? manifest.matrix.os : []) : effectiveCiRunners(manifest))
697
+ .filter((runner) => typeof runner === "string");
698
+ if (macActive) {
699
+ if (typeof dev.macAppPath !== "string" || !DEV_MAC_PATH_RE.test(dev.macAppPath) || !dev.macAppPath.endsWith(".app")) {
700
+ errors.push(`devArtifact.macAppPath must be a safe repository-relative path ending in .app when mac is '${dev.mac}'`);
701
+ }
702
+ if (dev.macEntitlements !== undefined && !macSigned) {
703
+ errors.push("devArtifact.macEntitlements requires mac 'sign' or 'notarize'");
704
+ } else if (dev.macEntitlements !== undefined && (typeof dev.macEntitlements !== "string" || !GATE_PATH_RE.test(dev.macEntitlements))) {
705
+ errors.push("devArtifact.macEntitlements must be a safe repository-relative path");
706
+ }
707
+ if (!runners.some((runner) => MACOS_RUNNER_RE.test(runner))) {
708
+ errors.push(dev.parallel === true
709
+ ? `devArtifact.mac '${dev.mac}' needs a macOS runner (macos-* or xcode-*) in matrix.os`
710
+ : `devArtifact.mac '${dev.mac}' needs the ci gate to run on a macOS runner (set ciAllOs and include a macos-* or xcode-* runner in matrix.os)`);
711
+ }
712
+ } else if (dev.macAppPath !== undefined || dev.macEntitlements !== undefined) {
713
+ errors.push("devArtifact.macAppPath and macEntitlements require mac 'sign', 'notarize' or 'unsigned'");
714
+ }
715
+ if (dev.windows === "unsigned") {
716
+ if (typeof dev.windowsGlob !== "string" || !DEV_WINDOWS_GLOB_RE.test(dev.windowsGlob)) {
717
+ errors.push("devArtifact.windowsGlob must be a safe repository-relative glob when windows is 'unsigned'");
718
+ }
719
+ if (!runners.some((runner) => /^windows-/i.test(runner))) {
720
+ errors.push(dev.parallel === true
721
+ ? "devArtifact.windows 'unsigned' needs a windows-* runner in matrix.os"
722
+ : "devArtifact.windows 'unsigned' needs the ci gate to run on a windows-* runner");
723
+ }
724
+ } else if (dev.windowsGlob !== undefined) {
725
+ errors.push("devArtifact.windowsGlob requires windows 'unsigned'");
726
+ }
727
+ }
728
+
729
+ const DEV_PUSH_CONDITION = "github.event_name == 'push' && github.ref_name == github.event.repository.default_branch";
730
+
731
+ // concurrency.mainPushes: "queue" stops default-branch pushes from cancelling each other.
732
+ // PR runs keep cancel-in-progress true, so superseded PR runs still cancel.
733
+ const CONCURRENCY_MAIN_PUSHES = ["cancel", "queue"];
734
+ const CI_CANCEL_MAIN_QUEUE_EXPRESSION = "${{ !(github.event_name == 'push' && github.ref_name == github.event.repository.default_branch) }}";
735
+ // rustCache.keySuffix: charset-checked before it reaches the rendered `key` input.
736
+ const RUST_CACHE_KEY_SUFFIX_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
737
+
738
+ function validateConcurrency(manifest, lanes, errors) {
739
+ const concurrency = manifest.concurrency;
740
+ if (concurrency === null || typeof concurrency !== "object" || Array.isArray(concurrency)) {
741
+ errors.push("concurrency must be an object");
742
+ return;
743
+ }
744
+ for (const key of Object.keys(concurrency)) {
745
+ if (key !== "mainPushes") errors.push(`unknown concurrency field: ${key}`);
746
+ }
747
+ if (concurrency.mainPushes !== undefined && !CONCURRENCY_MAIN_PUSHES.includes(concurrency.mainPushes)) {
748
+ errors.push("concurrency.mainPushes must be 'cancel' or 'queue'");
749
+ }
750
+ if (!Array.isArray(lanes) || !lanes.includes("ci")) {
751
+ errors.push("concurrency requires lane 'ci' (it sets the ci workflow's concurrency)");
752
+ }
753
+ }
754
+
755
+ /**
756
+ * rustCache.keySuffix as the Swatinem/rust-cache `key` input: `<lane>-<suffix>`.
757
+ * Returns "" when unset, so unopted renders stay byte-identical. rust-cache
758
+ * never re-saves on an exact key hit; changing the suffix produces a new key,
759
+ * so the next run on the default branch saves a fresh entry.
760
+ */
761
+ function rustCacheKeyLine(manifest, lane) {
762
+ const suffix = manifest.rustCache?.keySuffix;
763
+ return suffix === undefined ? "" : ` key: ${lane}-${suffix}`;
764
+ }
765
+
766
+ /** ciIncremental: Xcode DerivedData cache step (leading newline; "" when unset). */
767
+ function derivedDataStep(manifest) {
768
+ if (manifest.ciIncremental !== true) return "";
769
+ return [
770
+ "",
771
+ " - name: Cache Xcode DerivedData",
772
+ " if: ${{ runner.os == 'macOS' }}",
773
+ ` uses: ${CACHE_ACTION_PIN}`,
774
+ " with:",
775
+ " path: ~/Library/Developer/Xcode/DerivedData",
776
+ " key: ${{ runner.os }}-${{ matrix.os }}-deriveddata-${{ hashFiles('**/Cargo.lock', '**/Package.resolved', '**/*.xcodeproj/project.pbxproj') }}",
777
+ " restore-keys: |",
778
+ " ${{ runner.os }}-${{ matrix.os }}-deriveddata-",
779
+ ].join("\n");
780
+ }
781
+
782
+ /**
783
+ * Dev artifact steps appended to the ci job (unsigned, no secrets) plus the
784
+ * separate signing job. Returns "" when devArtifact is unset.
785
+ */
786
+ // Unsigned legs may also run on a manual dispatch of any ref when
787
+ // `devArtifact.dispatch` is set; the signing job never does (push to the
788
+ // default branch only), so no secret is reachable from a dispatched run.
789
+ function devUnsignedCondition(dev) {
790
+ return dev.dispatch === true
791
+ ? `(${DEV_PUSH_CONDITION} || github.event_name == 'workflow_dispatch')`
792
+ : DEV_PUSH_CONDITION;
793
+ }
794
+
795
+ export function devArtifactDispatchTrigger(manifest) {
796
+ return manifest.devArtifact?.dispatch === true ? " workflow_dispatch:\n" : "";
797
+ }
798
+
799
+ export function devArtifactCi(manifest, options = {}) {
800
+ const dev = manifest.devArtifact;
801
+ if (dev === undefined) return "";
802
+ if (dev.parallel === true) return devArtifactParallelJobs(manifest, options);
803
+ const retention = dev.retentionDays ?? DEV_ARTIFACT_DEFAULT_RETENTION_DAYS;
804
+ const unsignedCondition = devUnsignedCondition(dev);
805
+ const parts = [];
806
+ if (dev.windows === "unsigned") {
807
+ parts.push([
808
+ " - name: Upload unsigned dev build (Windows)",
809
+ ` if: \${{ ${unsignedCondition} && runner.os == 'Windows' }}`,
810
+ ` uses: ${UPLOAD_ARTIFACT_PIN}`,
811
+ " with:",
812
+ " name: dev-windows-${{ github.sha }}",
813
+ ` path: ${dev.windowsGlob}`,
814
+ ` retention-days: ${retention}`,
815
+ " if-no-files-found: error",
816
+ "",
817
+ ].join("\n"));
818
+ }
819
+ if (dev.mac === "sign" || dev.mac === "notarize") {
820
+ parts.push([
821
+ " - name: Package unsigned dev app (macOS)",
822
+ ` if: \${{ ${DEV_PUSH_CONDITION} && runner.os == 'macOS' }}`,
823
+ " shell: bash",
824
+ " env:",
825
+ ` DEV_APP_PATH: ${JSON.stringify(dev.macAppPath)}`,
826
+ " run: |",
827
+ " set -euo pipefail",
828
+ " test -d \"$DEV_APP_PATH\"",
829
+ " mkdir -p \"$RUNNER_TEMP/dev-unsigned\"",
830
+ " ditto -c -k --keepParent \"$DEV_APP_PATH\" \"$RUNNER_TEMP/dev-unsigned/app.zip\"",
831
+ " - name: Upload unsigned dev app for signing (macOS)",
832
+ ` if: \${{ ${DEV_PUSH_CONDITION} && runner.os == 'macOS' }}`,
833
+ ` uses: ${UPLOAD_ARTIFACT_PIN}`,
834
+ " with:",
835
+ " name: dev-unsigned-mac-${{ github.sha }}",
836
+ " path: ${{ runner.temp }}/dev-unsigned/app.zip",
837
+ " retention-days: 1",
838
+ " if-no-files-found: error",
839
+ "",
840
+ ].join("\n"));
841
+ }
842
+ if (dev.mac === "unsigned") {
843
+ parts.push([
844
+ " - name: Package unsigned dev app (macOS)",
845
+ ` if: \${{ ${unsignedCondition} && runner.os == 'macOS' }}`,
846
+ " shell: bash",
847
+ " env:",
848
+ ` DEV_APP_PATH: ${JSON.stringify(dev.macAppPath)}`,
849
+ " run: |",
850
+ " set -euo pipefail",
851
+ " test -d \"$DEV_APP_PATH\"",
852
+ " mkdir -p \"$RUNNER_TEMP/dev-unsigned\"",
853
+ " ditto -c -k --keepParent \"$DEV_APP_PATH\" \"$RUNNER_TEMP/dev-unsigned/app.zip\"",
854
+ " - name: Upload unsigned dev app (macOS)",
855
+ ` if: \${{ ${unsignedCondition} && runner.os == 'macOS' }}`,
856
+ ` uses: ${UPLOAD_ARTIFACT_PIN}`,
857
+ " with:",
858
+ " name: dev-mac-unsigned-${{ github.sha }}",
859
+ " path: ${{ runner.temp }}/dev-unsigned/app.zip",
860
+ ` retention-days: ${retention}`,
861
+ " if-no-files-found: error",
862
+ "",
863
+ ].join("\n"));
864
+ }
865
+ let text = parts.join("");
866
+ if (dev.mac === "sign" || dev.mac === "notarize") text += devMacSigningJob(manifest, dev, retention);
867
+ return text;
868
+ }
869
+
870
+ // devArtifact.parallel: true. Each platform gets its own job that compiles the
871
+ // dev app (devArtifact.buildScript) and stages it. These jobs need only the
872
+ // private-repo guard, so they run beside the QA gate job instead of after it.
873
+ // Unsigned uploads therefore do not wait for the gate; the signing job still
874
+ // needs ci, so nothing is Developer ID-signed from a failed gate.
875
+ function devArtifactParallelJobs(manifest, options) {
876
+ const dev = manifest.devArtifact;
877
+ if (!options.artifactPrefix) throw new Error("devArtifactCi: options.artifactPrefix is required when devArtifact.parallel is true");
878
+ const lane = options.lane ?? "ci";
879
+ const retention = dev.retentionDays ?? DEV_ARTIFACT_DEFAULT_RETENTION_DAYS;
880
+ const shared = { manifest, lane, artifactPrefix: options.artifactPrefix, retention };
881
+ const parts = [];
882
+ if (dev.mac === "sign" || dev.mac === "notarize" || dev.mac === "unsigned") parts.push(devMacArtifactJob(shared));
883
+ if (dev.windows === "unsigned") parts.push(devWindowsArtifactJob(shared));
884
+ if (dev.mac === "sign" || dev.mac === "notarize") parts.push(devMacSigningJob(manifest, dev, retention));
885
+ return parts.join("");
886
+ }
887
+
888
+ function firstMatchingRunner(manifest, pattern, platform) {
889
+ const runner = manifest.matrix.os.find((os) => typeof os === "string" && pattern.test(os));
890
+ if (!runner) throw new Error(`devArtifact.parallel: no ${platform} runner in matrix.os`);
891
+ return runner;
892
+ }
893
+
894
+ function devMacArtifactJob({ manifest, lane, artifactPrefix, retention }) {
895
+ const dev = manifest.devArtifact;
896
+ const signed = dev.mac === "sign" || dev.mac === "notarize";
897
+ const stage = [
898
+ " - name: Package unsigned dev app (macOS)",
899
+ " shell: bash",
900
+ " env:",
901
+ ` DEV_APP_PATH: ${JSON.stringify(dev.macAppPath)}`,
902
+ " run: |",
903
+ " set -euo pipefail",
904
+ " test -d \"$DEV_APP_PATH\"",
905
+ " mkdir -p \"$RUNNER_TEMP/dev-unsigned\"",
906
+ " ditto -c -k --keepParent \"$DEV_APP_PATH\" \"$RUNNER_TEMP/dev-unsigned/app.zip\"",
907
+ ...(signed
908
+ ? [
909
+ " - name: Upload unsigned dev app for signing (macOS)",
910
+ ` uses: ${UPLOAD_ARTIFACT_PIN}`,
911
+ " with:",
912
+ " name: dev-unsigned-mac-${{ github.sha }}",
913
+ " path: ${{ runner.temp }}/dev-unsigned/app.zip",
914
+ " retention-days: 1",
915
+ " if-no-files-found: error",
916
+ ]
917
+ : [
918
+ " - name: Upload unsigned dev app (macOS)",
919
+ ` uses: ${UPLOAD_ARTIFACT_PIN}`,
920
+ " with:",
921
+ " name: dev-mac-unsigned-${{ github.sha }}",
922
+ " path: ${{ runner.temp }}/dev-unsigned/app.zip",
923
+ ` retention-days: ${retention}`,
924
+ " if-no-files-found: error",
925
+ ]),
926
+ ];
927
+ return devPlatformJob({
928
+ manifest,
929
+ id: "dev-artifact-mac",
930
+ label: "macOS",
931
+ runner: firstMatchingRunner(manifest, MACOS_RUNNER_RE, "macOS"),
932
+ condition: signed ? DEV_PUSH_CONDITION : devUnsignedCondition(dev),
933
+ lane,
934
+ artifactPrefix,
935
+ stage,
936
+ swift: true,
937
+ });
938
+ }
939
+
940
+ function devWindowsArtifactJob({ manifest, lane, artifactPrefix, retention }) {
941
+ const dev = manifest.devArtifact;
942
+ const stage = [
943
+ " - name: Upload unsigned dev build (Windows)",
944
+ ` uses: ${UPLOAD_ARTIFACT_PIN}`,
945
+ " with:",
946
+ " name: dev-windows-${{ github.sha }}",
947
+ ` path: ${dev.windowsGlob}`,
948
+ ` retention-days: ${retention}`,
949
+ " if-no-files-found: error",
950
+ ];
951
+ return devPlatformJob({
952
+ manifest,
953
+ id: "dev-artifact-windows",
954
+ label: "Windows",
955
+ runner: firstMatchingRunner(manifest, /^windows-/i, "windows-*"),
956
+ condition: devUnsignedCondition(dev),
957
+ lane,
958
+ artifactPrefix,
959
+ stage,
960
+ });
961
+ }
962
+
963
+ // One platform job: toolchain + dependency install + dev build, then the
964
+ // platform staging steps. Mirrors the ci job's setup without the gate, the
965
+ // ownership scan, or any secret.
966
+ // swift: true renders the shared private Swift package steps around the build
967
+ // (macOS job only; the Windows job never gets them). The credential exists only
968
+ // between those two steps, so the staging and upload steps run without it.
969
+ function devPlatformJob({ manifest, id, label, runner, condition, lane, artifactPrefix, stage, swift = false }) {
970
+ const dev = manifest.devArtifact;
971
+ const swiftLines = (step) => (swift && step ? step.slice(1).split("\n") : []);
972
+ const swiftConfigure = swiftLines(swiftPrivatePackagesConfigureStep(manifest));
973
+ const swiftCleanup = swiftLines(swiftPrivatePackagesCleanupStep(manifest));
974
+ const pm = parsePackageManager(manifest.packageManager);
975
+ const workspaces = (manifest.rustCache?.workspaces ?? ["engine"]).map((workspace) => ` ${workspace} -> target`).join("\n");
976
+ const cacheKey = rustCacheKeyLine(manifest, `${lane}-${id}`);
977
+ return [
978
+ "",
979
+ ` ${id}:`,
980
+ ` # ${label} dev app: builds devArtifact.buildScript and stages it. Runs beside the`,
981
+ swiftConfigure.length > 0
982
+ ? " # QA gate job, not after it, and reaches only the private Swift package secret."
983
+ : " # QA gate job, not after it, and never reaches a secret.",
984
+ " needs: [private-repo-guard]",
985
+ ` if: \${{ ${condition} }}`,
986
+ ` runs-on: ${runner}`,
987
+ " permissions:",
988
+ " contents: read",
989
+ " steps:",
990
+ " - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1",
991
+ " with:",
992
+ " persist-credentials: false",
993
+ " - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0",
994
+ " with:",
995
+ ` node-version: ${JSON.stringify(String(manifest.matrix.node[0]))}`,
996
+ " package-manager-cache: false",
997
+ ...(pm.setup ? [pm.setup] : []),
998
+ ` - run: ${pm.installCommand}`,
999
+ " - uses: dtolnay/rust-toolchain@f8be11a05b1d4f3fcebe6410cc16743212b999b0",
1000
+ " - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2",
1001
+ " with:",
1002
+ " workspaces: |",
1003
+ workspaces,
1004
+ ` shared-key: ${artifactPrefix}-rust`,
1005
+ ...(cacheKey ? [cacheKey] : []),
1006
+ " add-job-id-key: false",
1007
+ ` cache-workspace-crates: ${manifest.ciIncremental === true ? "true" : "false"}`,
1008
+ " cache-on-failure: true",
1009
+ " save-if: true",
1010
+ ...swiftConfigure,
1011
+ " - name: Build dev app",
1012
+ ` run: ${pm.runPrefix} ${dev.buildScript}`,
1013
+ ...swiftCleanup,
1014
+ ...stage,
1015
+ "",
1016
+ ].join("\n");
1017
+ }
1018
+
1019
+ function devMacSigningJob(manifest, dev, retention) {
1020
+ const parallel = dev.parallel === true;
1021
+ const runner = (parallel ? manifest.matrix.os : effectiveCiRunners(manifest)).find((os) => MACOS_RUNNER_RE.test(os));
1022
+ const entitlements = dev.macEntitlements ? ` --entitlements "$GITHUB_WORKSPACE/${dev.macEntitlements}"` : "";
1023
+ const checkout = dev.macEntitlements
1024
+ ? ` - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
1025
+ with:
1026
+ ref: \${{ github.sha }}
1027
+ persist-credentials: false
1028
+ `
1029
+ : "";
1030
+ // `mac: "notarize"` also submits the signed app to the notary service and
1031
+ // staples the ticket, so app extensions (Finder Sync, Share, ...) register on
1032
+ // current macOS, which refuses them from unnotarized Developer ID apps.
1033
+ const notarize = dev.mac === "notarize";
1034
+ const apiKeyEnv = notarize ? `
1035
+ APPLE_API_KEY_BASE64: \${{ secrets.APPLE_API_KEY_BASE64 }}` : "";
1036
+ const apiKeyInstall = notarize ? `
1037
+ printf '%s' "$APPLE_API_KEY_BASE64" | base64 --decode > "$RUNNER_TEMP/AuthKey.p8"` : "";
1038
+ const notarizeStep = notarize ? ` - name: Notarize and staple dev app
1039
+ shell: bash
1040
+ env:
1041
+ APPLE_API_KEY: \${{ secrets.APPLE_API_KEY }}
1042
+ APPLE_API_ISSUER: \${{ secrets.APPLE_API_ISSUER }}
1043
+ run: |
1044
+ set -euo pipefail
1045
+ app="$(find "$RUNNER_TEMP/dev-sign" -maxdepth 1 -name '*.app' -print -quit)"
1046
+ test -n "$app"
1047
+ zip="$RUNNER_TEMP/dev-signed/$(basename "$app").zip"
1048
+ xcrun notarytool submit "$zip" --key "$RUNNER_TEMP/AuthKey.p8" --key-id "$APPLE_API_KEY" --issuer "$APPLE_API_ISSUER" --wait
1049
+ xcrun stapler staple "$app"
1050
+ xcrun stapler validate "$app"
1051
+ rm -f "$zip"
1052
+ ditto -c -k --keepParent "$app" "$zip"
1053
+ ` : "";
1054
+ const uploadLabel = notarize ? "Upload signed and notarized dev app" : "Upload signed (not notarized) dev app";
1055
+ return `
1056
+ dev-mac-sign:
1057
+ # Push to the default branch only. The release environment's protection
1058
+ # rules (required reviewers, branch policy) apply to this job.
1059
+ needs: ${parallel ? "[ci, dev-artifact-mac]" : "[ci]"}
1060
+ if: \${{ ${DEV_PUSH_CONDITION} }}
1061
+ environment: ${releaseEnvironment(manifest, "signing")}
1062
+ runs-on: ${runner}
1063
+ permissions:
1064
+ contents: read
1065
+ steps:
1066
+ ${checkout} - name: Download unsigned dev app
1067
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1068
+ with:
1069
+ name: dev-unsigned-mac-\${{ github.sha }}
1070
+ path: \${{ runner.temp }}/dev-unsigned
1071
+ - name: Install Apple signing identity in temporary keychain
1072
+ shell: bash
1073
+ env:
1074
+ APPLE_CERTIFICATE_BASE64: \${{ secrets.APPLE_CERTIFICATE_BASE64 }}
1075
+ APPLE_CERTIFICATE_PASSWORD: \${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
1076
+ APPLE_KEYCHAIN_PASSWORD: \${{ secrets.APPLE_KEYCHAIN_PASSWORD }}${apiKeyEnv}
1077
+ run: |
1078
+ set -euo pipefail
1079
+ certificate_path="$RUNNER_TEMP/apple-signing.p12"
1080
+ keychain_path="$RUNNER_TEMP/apple-signing.keychain-db"
1081
+ printf '%s' "$APPLE_CERTIFICATE_BASE64" | base64 --decode > "$certificate_path"${apiKeyInstall}
1082
+ security create-keychain -p "$APPLE_KEYCHAIN_PASSWORD" "$keychain_path"
1083
+ security set-keychain-settings -lut 21600 "$keychain_path"
1084
+ security unlock-keychain -p "$APPLE_KEYCHAIN_PASSWORD" "$keychain_path"
1085
+ security import "$certificate_path" -P "$APPLE_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k "$keychain_path"
1086
+ security set-key-partition-list -S apple-tool:,apple: -k "$APPLE_KEYCHAIN_PASSWORD" "$keychain_path"
1087
+ security list-keychain -d user -s "$keychain_path"
1088
+ - name: Developer ID sign dev app${notarize ? "" : " (no notarization)"}
1089
+ shell: bash
1090
+ env:
1091
+ APPLE_DEVELOPER_ID: \${{ vars.APPLE_DEVELOPER_ID }}
1092
+ run: |
1093
+ set -euo pipefail
1094
+ work="$RUNNER_TEMP/dev-sign"
1095
+ rm -rf "$work" && mkdir -p "$work"
1096
+ ditto -x -k "$RUNNER_TEMP/dev-unsigned/app.zip" "$work"
1097
+ app="$(find "$work" -maxdepth 1 -name '*.app' -print -quit)"
1098
+ test -n "$app"
1099
+ codesign --force --deep --strict --options runtime --timestamp${entitlements} --sign "$APPLE_DEVELOPER_ID" "$app"
1100
+ codesign --verify --deep --strict "$app"
1101
+ mkdir -p "$RUNNER_TEMP/dev-signed"
1102
+ ditto -c -k --keepParent "$app" "$RUNNER_TEMP/dev-signed/$(basename "$app").zip"
1103
+ ${notarizeStep} - name: ${uploadLabel}
1104
+ uses: ${UPLOAD_ARTIFACT_PIN}
1105
+ with:
1106
+ name: dev-mac-\${{ github.sha }}
1107
+ path: \${{ runner.temp }}/dev-signed/*.zip
1108
+ retention-days: ${retention}
1109
+ if-no-files-found: error
1110
+ - name: Remove Apple signing material
1111
+ if: \${{ always() }}
1112
+ shell: bash
1113
+ run: |
1114
+ security delete-keychain "$RUNNER_TEMP/apple-signing.keychain-db" 2>/dev/null || true
1115
+ rm -f "$RUNNER_TEMP/apple-signing.p12"${notarize ? ' "$RUNNER_TEMP/AuthKey.p8"' : ""}
1116
+ `;
1117
+ }
1118
+
1119
+ function windowsSigningJob(manifest, pm, artifactPrefix) {
1120
+ if (manifest.candidate?.signWindows !== true) return "";
1121
+ const nodeVersion = String(manifest.matrix.node[0]);
1122
+ const releaseChain = manifest.candidate.releaseChain;
1123
+ const finalizeCommand = releaseChain
1124
+ ? `${pm.runPrefix} ${releaseChain.windowsFinalizeScript}`
1125
+ : "pnpm exec right-release build --platform win --skip-checks";
1126
+ const finalizeEnvironment = releaseChain
1127
+ ? ` RIGHT_GIT_UNSIGNED_CANDIDATE_ROOT: \${{ runner.temp }}/unsigned-windows-candidate
1128
+ RIGHT_GIT_FINALIZED_WINDOWS_ROOT: \${{ runner.temp }}/finalized-windows
1129
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}`
1130
+ : ` LEGION_UNSIGNED_CANDIDATE_ROOT: \${{ runner.temp }}/unsigned-windows-candidate
1131
+ LEGION_SOURCE_REVISION: \${{ env.RIGHT_GIT_SOURCE_REVISION }}`;
1132
+ const uploadPath = releaseChain
1133
+ ? " ${{ runner.temp }}/finalized-windows/**"
1134
+ : " dist/releases/windows/**\n .right-release/receipts/windows-*.json";
1135
+ return `
1136
+ windows-sign:
1137
+ needs: [admission, candidate]
1138
+ if: \${{ needs.admission.outputs.signed_qualification == 'true' }}
1139
+ environment: ${releaseEnvironment(manifest, "signing")}
1140
+ strategy:
1141
+ fail-fast: false
1142
+ matrix:
1143
+ ${signingMatrix(manifest, "windows")}
1144
+ runs-on: \${{ matrix.os }}
1145
+ permissions:
1146
+ contents: read
1147
+ id-token: write
1148
+ steps:
1149
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
1150
+ with:
1151
+ ref: \${{ needs.admission.outputs.source_revision }}
1152
+ fetch-depth: 0
1153
+ persist-credentials: false
1154
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
1155
+ with:
1156
+ node-version: ${nodeVersion}
1157
+ package-manager-cache: false
1158
+ ${pm.setup}
1159
+ - uses: dtolnay/rust-toolchain@f8be11a05b1d4f3fcebe6410cc16743212b999b0
1160
+ with:
1161
+ targets: \${{ matrix.targetTriple }}
1162
+ - run: ${pm.installCommand}
1163
+ - name: Initialize Windows signing stage summary
1164
+ run: ${pm.runPrefix} ${manifest.candidate.stageSummaryScript}
1165
+ env:
1166
+ RIGHT_GIT_STAGE_ACTION: init
1167
+ RIGHT_GIT_STAGE_ROOT: \${{ runner.temp }}/right-git-stage-summary
1168
+ RIGHT_GIT_STAGE_EVIDENCE_ROOT: \${{ runner.temp }}/finalized-windows
1169
+ RIGHT_GIT_STAGE: windows-sign
1170
+ RIGHT_GIT_STAGE_PRODUCER: windows-sign-\${{ matrix.architecture }}
1171
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1172
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1173
+ RIGHT_GIT_RELEASE_PLATFORM: \${{ matrix.platform }}
1174
+ RIGHT_GIT_RELEASE_ARCHITECTURE: \${{ matrix.architecture }}
1175
+ RIGHT_GIT_RUN_ID: \${{ github.run_id }}
1176
+ RIGHT_GIT_RUN_ATTEMPT: \${{ github.run_attempt }}
1177
+ - name: Download exact unsigned Windows candidate
1178
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1179
+ with:
1180
+ name: ${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-candidate-\${{ matrix.platform }}-\${{ matrix.architecture }}-\${{ needs.admission.outputs.version }}-\${{ needs.admission.outputs.source_revision }}\${{ needs.admission.outputs.artifact_suffix }}
1181
+ path: \${{ runner.temp }}/unsigned-windows-candidate
1182
+ - name: Authenticate to Azure with GitHub OIDC
1183
+ uses: azure/login@${AZURE_LOGIN_SHA} # v3
1184
+ with:
1185
+ client-id: \${{ vars.AZURE_CLIENT_ID }}
1186
+ tenant-id: \${{ vars.AZURE_TENANT_ID }}
1187
+ subscription-id: \${{ vars.AZURE_SUBSCRIPTION_ID }}
1188
+ - name: Install pinned Artifact Signing client
1189
+ shell: pwsh
1190
+ run: |
1191
+ $ErrorActionPreference = 'Stop'
1192
+ $tools = Join-Path $env:RUNNER_TEMP 'artifact-signing-tools'
1193
+ New-Item -ItemType Directory -Force -Path $tools | Out-Null
1194
+ $client = Join-Path $tools 'client.zip'
1195
+ $sdk = Join-Path $tools 'sdk.zip'
1196
+ Invoke-WebRequest 'https://api.nuget.org/v3-flatcontainer/microsoft.artifactsigning.client/${ARTIFACT_SIGNING_CLIENT_VERSION}/microsoft.artifactsigning.client.${ARTIFACT_SIGNING_CLIENT_VERSION}.nupkg' -OutFile $client
1197
+ Invoke-WebRequest 'https://api.nuget.org/v3-flatcontainer/microsoft.windows.sdk.buildtools/${WINDOWS_SDK_BUILD_TOOLS_VERSION}/microsoft.windows.sdk.buildtools.${WINDOWS_SDK_BUILD_TOOLS_VERSION}.nupkg' -OutFile $sdk
1198
+ if ((Get-FileHash $client -Algorithm SHA256).Hash -ne '${ARTIFACT_SIGNING_CLIENT_SHA256}') { throw 'Artifact Signing client hash mismatch' }
1199
+ if ((Get-FileHash $sdk -Algorithm SHA256).Hash -ne '${WINDOWS_SDK_BUILD_TOOLS_SHA256}') { throw 'Windows SDK Build Tools hash mismatch' }
1200
+ Expand-Archive $client (Join-Path $tools 'client')
1201
+ Expand-Archive $sdk (Join-Path $tools 'sdk')
1202
+ "AZURE_ARTIFACT_SIGNING_DLIB_PATH=$tools\\client\\bin\\x64\\Azure.CodeSigning.Dlib.dll" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
1203
+ "AZURE_SIGNTOOL_PATH=$tools\\sdk\\bin\\10.0.26100.0\\x64\\signtool.exe" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
1204
+ - name: Sign & finalize Windows candidate
1205
+ run: ${finalizeCommand}
1206
+ env:
1207
+ ${finalizeEnvironment}
1208
+ RIGHT_GIT_RELEASE_PLATFORM: \${{ matrix.platform }}
1209
+ RIGHT_GIT_RELEASE_ARCHITECTURE: \${{ matrix.architecture }}
1210
+ AZURE_ARTIFACT_SIGNING_ENDPOINT: \${{ vars.AZURE_ARTIFACT_SIGNING_ENDPOINT }}
1211
+ AZURE_ARTIFACT_SIGNING_ACCOUNT: \${{ vars.AZURE_ARTIFACT_SIGNING_ACCOUNT }}
1212
+ AZURE_ARTIFACT_SIGNING_PROFILE: \${{ vars.AZURE_ARTIFACT_SIGNING_PROFILE }}
1213
+ - name: Finalize Windows signing stage summary
1214
+ if: \${{ always() }}
1215
+ run: ${pm.runPrefix} ${manifest.candidate.stageSummaryScript}
1216
+ env:
1217
+ RIGHT_GIT_STAGE_ACTION: finalize
1218
+ RIGHT_GIT_STAGE_ROOT: \${{ runner.temp }}/right-git-stage-summary
1219
+ RIGHT_GIT_STAGE_EVIDENCE_ROOT: \${{ runner.temp }}/finalized-windows
1220
+ RIGHT_GIT_STAGE: windows-sign
1221
+ RIGHT_GIT_STAGE_PRODUCER: windows-sign-\${{ matrix.architecture }}
1222
+ RIGHT_GIT_STAGE_STATUS: \${{ job.status == 'success' && 'SUCCEEDED' || 'FAILED' }}
1223
+ RIGHT_GIT_STAGE_EXIT_CODE: \${{ job.status == 'success' && '0' || '1' }}
1224
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1225
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1226
+ RIGHT_GIT_RELEASE_PLATFORM: \${{ matrix.platform }}
1227
+ RIGHT_GIT_RELEASE_ARCHITECTURE: \${{ matrix.architecture }}
1228
+ RIGHT_GIT_RUN_ID: \${{ github.run_id }}
1229
+ RIGHT_GIT_RUN_ATTEMPT: \${{ github.run_attempt }}
1230
+ - name: Upload signed Windows candidate
1231
+ if: \${{ always() }}
1232
+ uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # v4
1233
+ with:
1234
+ name: ${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-signed-windows-\${{ matrix.architecture }}-\${{ needs.admission.outputs.version }}-\${{ needs.admission.outputs.source_revision }}\${{ needs.admission.outputs.artifact_suffix }}
1235
+ path: |
1236
+ ${uploadPath}
1237
+ if-no-files-found: error
1238
+ - name: Upload Windows signing stage summary
1239
+ if: \${{ always() }}
1240
+ uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # v4
1241
+ with:
1242
+ name: ${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-summary-windows-sign-\${{ matrix.architecture }}-\${{ needs.admission.outputs.version }}-\${{ needs.admission.outputs.source_revision }}\${{ needs.admission.outputs.artifact_suffix }}
1243
+ path: \${{ runner.temp }}/right-git-stage-summary/stage-summary.json
1244
+ if-no-files-found: error
1245
+ `.trimEnd();
1246
+ }
1247
+
1248
+ function macosSigningJob(manifest, pm, artifactPrefix) {
1249
+ if (manifest.candidate?.signMacos !== true) return "";
1250
+ const nodeVersion = String(manifest.matrix.node[0]);
1251
+ const releaseChain = manifest.candidate.releaseChain;
1252
+ const finalizeCommand = releaseChain
1253
+ ? `${pm.runPrefix} ${releaseChain.macosFinalizeScript}`
1254
+ : "pnpm exec right-release build --platform mac --skip-checks";
1255
+ const finalizeEnvironment = releaseChain
1256
+ ? ` RIGHT_GIT_UNSIGNED_CANDIDATE_ROOT: \${{ runner.temp }}/unsigned-macos-candidate
1257
+ RIGHT_GIT_FINALIZED_MACOS_ROOT: \${{ runner.temp }}/finalized-macos
1258
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}`
1259
+ : ` LEGION_UNSIGNED_CANDIDATE_ROOT: \${{ runner.temp }}/unsigned-macos-candidate
1260
+ LEGION_SOURCE_REVISION: \${{ env.RIGHT_GIT_SOURCE_REVISION }}`;
1261
+ const uploadPath = releaseChain
1262
+ ? " ${{ runner.temp }}/finalized-macos/**"
1263
+ : " dist/releases/mac/**\n .right-release/receipts/macos-*.json";
1264
+ return `
1265
+ macos-sign:
1266
+ needs: [admission, candidate]
1267
+ if: \${{ needs.admission.outputs.signed_qualification == 'true' }}
1268
+ environment: ${releaseEnvironment(manifest, "signing")}
1269
+ strategy:
1270
+ fail-fast: false
1271
+ matrix:
1272
+ ${signingMatrix(manifest, "macos")}
1273
+ runs-on: \${{ matrix.os }}
1274
+ permissions:
1275
+ contents: read
1276
+ steps:
1277
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
1278
+ with:
1279
+ ref: \${{ needs.admission.outputs.source_revision }}
1280
+ fetch-depth: 0
1281
+ persist-credentials: false
1282
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
1283
+ with:
1284
+ node-version: ${nodeVersion}
1285
+ package-manager-cache: false
1286
+ ${pm.setup}
1287
+ - uses: dtolnay/rust-toolchain@f8be11a05b1d4f3fcebe6410cc16743212b999b0
1288
+ with:
1289
+ targets: \${{ matrix.targetTriple }}
1290
+ - run: ${pm.installCommand}
1291
+ - name: Initialize macOS signing stage summary
1292
+ run: ${pm.runPrefix} ${manifest.candidate.stageSummaryScript}
1293
+ env:
1294
+ RIGHT_GIT_STAGE_ACTION: init
1295
+ RIGHT_GIT_STAGE_ROOT: \${{ runner.temp }}/right-git-stage-summary
1296
+ RIGHT_GIT_STAGE_EVIDENCE_ROOT: \${{ runner.temp }}/finalized-macos
1297
+ RIGHT_GIT_STAGE: macos-sign
1298
+ RIGHT_GIT_STAGE_PRODUCER: macos-sign-\${{ matrix.architecture }}
1299
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1300
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1301
+ RIGHT_GIT_RELEASE_PLATFORM: \${{ matrix.platform }}
1302
+ RIGHT_GIT_RELEASE_ARCHITECTURE: \${{ matrix.architecture }}
1303
+ RIGHT_GIT_RUN_ID: \${{ github.run_id }}
1304
+ RIGHT_GIT_RUN_ATTEMPT: \${{ github.run_attempt }}
1305
+ - name: Download exact unsigned macOS candidate
1306
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1307
+ with:
1308
+ name: ${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-candidate-\${{ matrix.platform }}-\${{ matrix.architecture }}-\${{ needs.admission.outputs.version }}-\${{ needs.admission.outputs.source_revision }}\${{ needs.admission.outputs.artifact_suffix }}
1309
+ path: \${{ runner.temp }}/unsigned-macos-candidate
1310
+ - name: Install Apple signing identity in temporary keychain
1311
+ shell: bash
1312
+ env:
1313
+ APPLE_CERTIFICATE_BASE64: \${{ secrets.APPLE_CERTIFICATE_BASE64 }}
1314
+ APPLE_CERTIFICATE_PASSWORD: \${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
1315
+ APPLE_KEYCHAIN_PASSWORD: \${{ secrets.APPLE_KEYCHAIN_PASSWORD }}
1316
+ APPLE_API_KEY_BASE64: \${{ secrets.APPLE_API_KEY_BASE64 }}
1317
+ run: |
1318
+ set -euo pipefail
1319
+ certificate_path="$RUNNER_TEMP/apple-signing.p12"
1320
+ key_path="$RUNNER_TEMP/AuthKey.p8"
1321
+ keychain_path="$RUNNER_TEMP/apple-signing.keychain-db"
1322
+ printf '%s' "$APPLE_CERTIFICATE_BASE64" | base64 --decode > "$certificate_path"
1323
+ printf '%s' "$APPLE_API_KEY_BASE64" | base64 --decode > "$key_path"
1324
+ security create-keychain -p "$APPLE_KEYCHAIN_PASSWORD" "$keychain_path"
1325
+ security set-keychain-settings -lut 21600 "$keychain_path"
1326
+ security unlock-keychain -p "$APPLE_KEYCHAIN_PASSWORD" "$keychain_path"
1327
+ security import "$certificate_path" -P "$APPLE_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k "$keychain_path"
1328
+ security set-key-partition-list -S apple-tool:,apple: -k "$APPLE_KEYCHAIN_PASSWORD" "$keychain_path"
1329
+ security list-keychain -d user -s "$keychain_path"
1330
+ printf 'APPLE_API_KEY_PATH=%s\\n' "$key_path" >> "$GITHUB_ENV"
1331
+ - name: Sign, notarize & finalize macOS candidate
1332
+ run: ${finalizeCommand}
1333
+ env:
1334
+ ${finalizeEnvironment}
1335
+ RIGHT_GIT_RELEASE_PLATFORM: \${{ matrix.platform }}
1336
+ RIGHT_GIT_RELEASE_ARCHITECTURE: \${{ matrix.architecture }}
1337
+ APPLE_DEVELOPER_ID: \${{ vars.APPLE_DEVELOPER_ID }}
1338
+ APPLE_API_KEY: \${{ secrets.APPLE_API_KEY }}
1339
+ APPLE_API_ISSUER: \${{ secrets.APPLE_API_ISSUER }}
1340
+ - name: Finalize macOS signing stage summary
1341
+ if: \${{ always() }}
1342
+ run: ${pm.runPrefix} ${manifest.candidate.stageSummaryScript}
1343
+ env:
1344
+ RIGHT_GIT_STAGE_ACTION: finalize
1345
+ RIGHT_GIT_STAGE_ROOT: \${{ runner.temp }}/right-git-stage-summary
1346
+ RIGHT_GIT_STAGE_EVIDENCE_ROOT: \${{ runner.temp }}/finalized-macos
1347
+ RIGHT_GIT_STAGE: macos-sign
1348
+ RIGHT_GIT_STAGE_PRODUCER: macos-sign-\${{ matrix.architecture }}
1349
+ RIGHT_GIT_STAGE_STATUS: \${{ job.status == 'success' && 'SUCCEEDED' || 'FAILED' }}
1350
+ RIGHT_GIT_STAGE_EXIT_CODE: \${{ job.status == 'success' && '0' || '1' }}
1351
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1352
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1353
+ RIGHT_GIT_RELEASE_PLATFORM: \${{ matrix.platform }}
1354
+ RIGHT_GIT_RELEASE_ARCHITECTURE: \${{ matrix.architecture }}
1355
+ RIGHT_GIT_RUN_ID: \${{ github.run_id }}
1356
+ RIGHT_GIT_RUN_ATTEMPT: \${{ github.run_attempt }}
1357
+ - name: Upload signed & notarized macOS candidate
1358
+ if: \${{ always() }}
1359
+ uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # v4
1360
+ with:
1361
+ name: ${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-signed-macos-\${{ matrix.architecture }}-\${{ needs.admission.outputs.version }}-\${{ needs.admission.outputs.source_revision }}\${{ needs.admission.outputs.artifact_suffix }}
1362
+ path: |
1363
+ ${uploadPath}
1364
+ if-no-files-found: error
1365
+ - name: Upload macOS signing stage summary
1366
+ if: \${{ always() }}
1367
+ uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # v4
1368
+ with:
1369
+ name: ${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-summary-macos-sign-\${{ matrix.architecture }}-\${{ needs.admission.outputs.version }}-\${{ needs.admission.outputs.source_revision }}\${{ needs.admission.outputs.artifact_suffix }}
1370
+ path: \${{ runner.temp }}/right-git-stage-summary/stage-summary.json
1371
+ if-no-files-found: error
1372
+ - name: Remove Apple signing material
1373
+ if: \${{ always() }}
1374
+ shell: bash
1375
+ run: |
1376
+ security delete-keychain "$RUNNER_TEMP/apple-signing.keychain-db" 2>/dev/null || true
1377
+ rm -f "$RUNNER_TEMP/apple-signing.p12" "$RUNNER_TEMP/AuthKey.p8"
1378
+ `.trimEnd();
1379
+ }
1380
+
1381
+ function releaseChainJobs(manifest, pm, artifactPrefix) {
1382
+ const chain = manifest.candidate?.releaseChain;
1383
+ if (!chain) return "";
1384
+ const windowsTarget = candidateTargets(manifest.candidate).find((target) => target.platform === "windows");
1385
+ const windowsRunner = windowsTarget.os;
1386
+ const windowsArchitecture = windowsTarget.architecture;
1387
+ const macosTarget = candidateTargets(manifest.candidate).find((target) => target.platform === "macos");
1388
+ const signMacos = manifest.candidate.signMacos === true;
1389
+ const macosDependency = signMacos ? ", macos-sign" : "";
1390
+ const macosSuccess = signMacos ? " && needs.macos-sign.result == 'success'" : "";
1391
+ // Run- and identity-bound: matches exactly what windows-sign/macos-sign
1392
+ // uploaded (see windowsSigningJob/macosSigningJob) — no matrix context is
1393
+ // available in these non-matrixed jobs, so the platform architecture is a
1394
+ // literal derived from the manifest's single windows/macos target.
1395
+ const VERSION = "${{ needs.admission.outputs.version }}";
1396
+ // Identity-bound artifact names end with the admission artifact_suffix (`-dry-run` on a rehearsal, empty otherwise).
1397
+ const SOURCE_REVISION = "${{ needs.admission.outputs.source_revision }}${{ needs.admission.outputs.artifact_suffix }}";
1398
+ const windowsSignedArtifact = `${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-signed-windows-${windowsArchitecture}-${VERSION}-${SOURCE_REVISION}`;
1399
+ const windowsSummaryArtifact = `${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-summary-windows-sign-${windowsArchitecture}-${VERSION}-${SOURCE_REVISION}`;
1400
+ const macosSignedArtifact = signMacos ? `${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-signed-macos-${macosTarget.architecture}-${VERSION}-${SOURCE_REVISION}` : "";
1401
+ const macosSummaryArtifact = signMacos ? `${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-summary-macos-sign-${macosTarget.architecture}-${VERSION}-${SOURCE_REVISION}` : "";
1402
+ // Candidate stage summaries are per (platform, architecture) — see the
1403
+ // `Upload candidate stage summary` step in the template. releaseChain
1404
+ // requires at most one target per signing platform (validateManifest), so
1405
+ // exactly one candidate-windows summary and at most one candidate-macos
1406
+ // summary exist for this manifest.
1407
+ const candidateWindowsSummaryArtifact = `${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-summary-candidate-windows-${windowsArchitecture}-${VERSION}-${SOURCE_REVISION}`;
1408
+ const candidateMacosSummaryArtifact = signMacos ? `${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-summary-candidate-macos-${macosTarget.architecture}-${VERSION}-${SOURCE_REVISION}` : "";
1409
+ const qualificationArtifact = `${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-installed-qualification-${VERSION}-${SOURCE_REVISION}`;
1410
+ const qualificationSummaryArtifact = `${artifactPrefix}-\${{ github.run_id }}-\${{ github.run_attempt }}-summary-installed-qualification-${VERSION}-${SOURCE_REVISION}`;
1411
+ const macosDownload = signMacos
1412
+ ? ` - name: Download same-run signed & notarized macOS release
1413
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1414
+ with:
1415
+ name: ${macosSignedArtifact}
1416
+ path: \${{ runner.temp }}/right-git-release/macos`
1417
+ : "";
1418
+ const macosSummaryDownload = signMacos
1419
+ ? ` - name: Download same-run macOS signing stage summary
1420
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1421
+ with:
1422
+ name: ${macosSummaryArtifact}
1423
+ path: \${{ runner.temp }}/right-git-release/stage-summaries/macos-sign`
1424
+ : "";
1425
+ const candidateMacosSummaryDownload = signMacos
1426
+ ? ` - name: Download same-run candidate (macOS) stage summary
1427
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1428
+ with:
1429
+ name: ${candidateMacosSummaryArtifact}
1430
+ path: \${{ runner.temp }}/right-git-release/stage-summaries/candidate-macos`
1431
+ : "";
1432
+ const finalizedMacosEnv = signMacos ? `\n RIGHT_GIT_FINALIZED_MACOS_ROOT: \${{ runner.temp }}/right-git-release/macos` : "";
1433
+ // Evidence must be bound to this exact run — not merely this
1434
+ // version+source_revision — so a stale artifact from a different run
1435
+ // cannot satisfy verification. Every job/step from installed-qualification
1436
+ // onward carries RIGHT_GIT_RUN_ID/RIGHT_GIT_RUN_ATTEMPT alongside version
1437
+ // and source_revision.
1438
+ const runIdentityEnv = ` RIGHT_GIT_RUN_ID: \${{ github.run_id }}
1439
+ RIGHT_GIT_RUN_ATTEMPT: \${{ github.run_attempt }}`;
1440
+ const publishSecretEnvironment = (chain.publishSecrets ?? [])
1441
+ .map((name) => ` ${name}: \${{ secrets.${name} }}`)
1442
+ .join("\n");
1443
+ return `
1444
+ installed-qualification:
1445
+ needs: [admission, candidate, windows-sign]
1446
+ if: \${{ always() && needs.admission.outputs.signed_qualification == 'true' && needs.candidate.result == 'success' }}
1447
+ environment: ${releaseEnvironment(manifest, "qualification")}
1448
+ runs-on: \${{ vars.${chain.qualificationRunnerVariable} || '${windowsRunner}' }}
1449
+ steps:
1450
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
1451
+ with:
1452
+ ref: \${{ needs.admission.outputs.source_revision }}
1453
+ fetch-depth: 0
1454
+ persist-credentials: false
1455
+ - name: Fail closed when protected finalization is absent
1456
+ if: \${{ needs.windows-sign.result != 'success' }}
1457
+ shell: pwsh
1458
+ run: |
1459
+ throw 'installed_qualification_failed { reason: prerequisites_absent, detail: "same-run Windows signing/finalization did not succeed" }'
1460
+ - name: Download same-run finalized Windows release
1461
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1462
+ with:
1463
+ name: ${windowsSignedArtifact}
1464
+ path: \${{ runner.temp }}/right-git-release/windows
1465
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
1466
+ with:
1467
+ node-version: ${String(manifest.matrix.node[0])}
1468
+ package-manager-cache: false
1469
+ ${pm.setup}
1470
+ - run: ${pm.installCommand}
1471
+ - name: Initialize installed-qualification stage summary
1472
+ run: ${pm.runPrefix} ${manifest.candidate.stageSummaryScript}
1473
+ env:
1474
+ RIGHT_GIT_STAGE_ACTION: init
1475
+ RIGHT_GIT_STAGE_ROOT: \${{ runner.temp }}/right-git-stage-summary
1476
+ RIGHT_GIT_STAGE_EVIDENCE_ROOT: \${{ runner.temp }}/right-git-release/qualification
1477
+ RIGHT_GIT_STAGE: installed-qualification
1478
+ RIGHT_GIT_STAGE_PRODUCER: installed-qualification
1479
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1480
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1481
+ ${runIdentityEnv}
1482
+ - name: Run installed-artifact qualification
1483
+ run: ${pm.runPrefix} ${chain.installedQualificationScript}
1484
+ env:
1485
+ GH_TOKEN: \${{ github.token }}
1486
+ RIGHT_GIT_FINALIZED_WINDOWS_ROOT: \${{ runner.temp }}/right-git-release/windows
1487
+ RIGHT_GIT_QUALIFICATION_EVIDENCE_ROOT: \${{ runner.temp }}/right-git-release/qualification
1488
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1489
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1490
+ - name: Finalize installed-qualification stage summary
1491
+ if: \${{ always() }}
1492
+ run: ${pm.runPrefix} ${manifest.candidate.stageSummaryScript}
1493
+ env:
1494
+ RIGHT_GIT_STAGE_ACTION: finalize
1495
+ RIGHT_GIT_STAGE_ROOT: \${{ runner.temp }}/right-git-stage-summary
1496
+ RIGHT_GIT_STAGE_EVIDENCE_ROOT: \${{ runner.temp }}/right-git-release/qualification
1497
+ RIGHT_GIT_STAGE: installed-qualification
1498
+ RIGHT_GIT_STAGE_PRODUCER: installed-qualification
1499
+ RIGHT_GIT_STAGE_STATUS: \${{ job.status == 'success' && 'SUCCEEDED' || 'FAILED' }}
1500
+ RIGHT_GIT_STAGE_EXIT_CODE: \${{ job.status == 'success' && '0' || '1' }}
1501
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1502
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1503
+ ${runIdentityEnv}
1504
+ - name: Upload installed qualification evidence
1505
+ if: \${{ always() }}
1506
+ uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # v4
1507
+ with:
1508
+ name: ${qualificationArtifact}
1509
+ path: \${{ runner.temp }}/right-git-release/qualification/**
1510
+ if-no-files-found: error
1511
+ - name: Upload installed-qualification stage summary
1512
+ if: \${{ always() }}
1513
+ uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # v4
1514
+ with:
1515
+ name: ${qualificationSummaryArtifact}
1516
+ path: \${{ runner.temp }}/right-git-stage-summary/stage-summary.json
1517
+ if-no-files-found: error
1518
+ publish:
1519
+ needs: [admission, installed-qualification${macosDependency}]
1520
+ if: \${{ needs.admission.outputs.publish == 'true' && needs.installed-qualification.result == 'success'${macosSuccess} }}
1521
+ environment: ${releaseEnvironment(manifest, "publication")}
1522
+ runs-on: \${{ vars.${chain.qualificationRunnerVariable} || '${windowsRunner}' }}
1523
+ permissions:
1524
+ contents: write
1525
+ steps:
1526
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
1527
+ with:
1528
+ ref: \${{ needs.admission.outputs.source_revision }}
1529
+ fetch-depth: 0
1530
+ persist-credentials: false
1531
+ - name: Download same-run finalized Windows release
1532
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1533
+ with:
1534
+ name: ${windowsSignedArtifact}
1535
+ path: \${{ runner.temp }}/right-git-release/windows
1536
+ ${macosDownload}
1537
+ - name: Download same-run installed qualification evidence
1538
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1539
+ with:
1540
+ name: ${qualificationArtifact}
1541
+ path: \${{ runner.temp }}/right-git-release/qualification
1542
+ - name: Download same-run candidate (Windows) stage summary
1543
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1544
+ with:
1545
+ name: ${candidateWindowsSummaryArtifact}
1546
+ path: \${{ runner.temp }}/right-git-release/stage-summaries/candidate-windows
1547
+ ${candidateMacosSummaryDownload}
1548
+ - name: Download same-run Windows signing stage summary
1549
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1550
+ with:
1551
+ name: ${windowsSummaryArtifact}
1552
+ path: \${{ runner.temp }}/right-git-release/stage-summaries/windows-sign
1553
+ ${macosSummaryDownload}
1554
+ - name: Download same-run installed-qualification stage summary
1555
+ uses: actions/download-artifact@${DOWNLOAD_ARTIFACT_SHA} # v4.3.0
1556
+ with:
1557
+ name: ${qualificationSummaryArtifact}
1558
+ path: \${{ runner.temp }}/right-git-release/stage-summaries/installed-qualification
1559
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
1560
+ with:
1561
+ node-version: ${String(manifest.matrix.node[0])}
1562
+ package-manager-cache: false
1563
+ ${pm.setup}
1564
+ - run: ${pm.installCommand}
1565
+ - name: Verify aggregated release evidence
1566
+ run: ${pm.runPrefix} ${chain.evidenceVerificationScript}
1567
+ env:
1568
+ GH_TOKEN: \${{ github.token }}
1569
+ RIGHT_GIT_FINALIZED_WINDOWS_ROOT: \${{ runner.temp }}/right-git-release/windows${finalizedMacosEnv}
1570
+ RIGHT_GIT_QUALIFICATION_EVIDENCE_ROOT: \${{ runner.temp }}/right-git-release/qualification
1571
+ RIGHT_GIT_STAGE_SUMMARY_ROOT: \${{ runner.temp }}/right-git-release/stage-summaries
1572
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1573
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1574
+ ${runIdentityEnv}
1575
+ - name: Publish qualified signed release
1576
+ run: ${pm.runPrefix} ${chain.publishScript}
1577
+ env:
1578
+ GH_TOKEN: \${{ github.token }}
1579
+ RIGHT_GIT_FINALIZED_WINDOWS_ROOT: \${{ runner.temp }}/right-git-release/windows${finalizedMacosEnv}
1580
+ RIGHT_GIT_QUALIFICATION_EVIDENCE_ROOT: \${{ runner.temp }}/right-git-release/qualification
1581
+ RIGHT_GIT_STAGE_SUMMARY_ROOT: \${{ runner.temp }}/right-git-release/stage-summaries
1582
+ RIGHT_GIT_RELEASE_VERSION: \${{ needs.admission.outputs.version }}
1583
+ RIGHT_GIT_SOURCE_REVISION: \${{ needs.admission.outputs.source_revision }}
1584
+ ${runIdentityEnv}
1585
+ ${publishSecretEnvironment}
1586
+ `.trimEnd();
1587
+ }
1588
+
1589
+ /**
1590
+ * Derive one project name from the target repo's package.json, falling back
1591
+ * to the repo directory's basename. Never throws.
1592
+ */
1593
+ export function deriveProjectName(repoPath) {
1594
+ try {
1595
+ const pkgRaw = fs.readFileSync(path.join(repoPath, "package.json"), "utf8");
1596
+ const pkg = JSON.parse(pkgRaw);
1597
+ if (typeof pkg.name === "string" && pkg.name.length > 0) {
1598
+ return pkg.name.replace(/^@[^/]+\//, "");
1599
+ }
1600
+ } catch {
1601
+ // fall through to directory name
1602
+ }
1603
+ return path.basename(path.resolve(repoPath));
1604
+ }
1605
+
1606
+ /**
1607
+ * Build the flat placeholder -> value map used by render.mjs, from a
1608
+ * validated manifest plus the target repo's derived project name.
1609
+ */
1610
+ /** Every managed public workflow runs ownership scanning; repository metadata cannot opt it out. */
1611
+ export function ownershipStep(manifest, lane = "ci") {
1612
+ const { name } = parsePackageManager(manifest.packageManager);
1613
+ const command = name === "pnpm" ? "pnpm exec right-release ownership --app ."
1614
+ : name === "npm" ? "npm exec -- right-release ownership --app ."
1615
+ : "yarn exec right-release ownership --app .";
1616
+ // Every lane stays advisory until ownership approval keys are enrolled (Adrian, 2026-10-09);
1617
+ // once enrolled, the flag is inert and findings block again.
1618
+ const ownershipCommand = `${command} --advisory-when-pending`;
1619
+ // Only release-candidate dispatches declare source_revision. Referencing
1620
+ // inputs.source_revision from other lanes makes actionlint reject their
1621
+ // generated workflows, even when guarded by an event-name expression.
1622
+ // rust-hybrid release-candidate is dispatch-only. The node release-candidate
1623
+ // also runs on a v* tag push, which has no input: it compares against the
1624
+ // pushed commit instead.
1625
+ const sourceRevision = lane !== "release-candidate"
1626
+ ? "\${{ github.sha }}"
1627
+ : manifest.profile === "rust-hybrid"
1628
+ ? "\${{ inputs.source_revision }}"
1629
+ : "\${{ inputs.source_revision || github.sha }}";
1630
+ return `\n - name: RightKit ownership (protected registry roots)\n shell: bash\n run: test "$(git rev-parse HEAD)" = "${sourceRevision}" && ${ownershipCommand}`;
1631
+ }
1632
+
1633
+ /**
1634
+ * pnpm stale-lockfile hint for the ci lane. The step runs only when the step
1635
+ * before it (the frozen install) failed. It regenerates the lockfile with
1636
+ * `pnpm install --lockfile-only` and prints the lockfile's git diff as a patch
1637
+ * block. It never changes the job result, which the failed install already
1638
+ * decided. Returns "" for npm and yarn, so their renders stay unchanged.
1639
+ */
1640
+ export function lockfilePatchStep(manifest) {
1641
+ const { name } = parsePackageManager(manifest.packageManager);
1642
+ if (name !== "pnpm") return "";
1643
+ return [
1644
+ "",
1645
+ " - name: Print pnpm-lock.yaml patch when the lockfile is stale",
1646
+ " if: failure()",
1647
+ " shell: bash",
1648
+ " run: |",
1649
+ " if pnpm install --lockfile-only; then",
1650
+ " if git diff --quiet -- pnpm-lock.yaml; then",
1651
+ ' echo "::notice::pnpm-lock.yaml already matches package.json; the frozen install failed for another reason."',
1652
+ " else",
1653
+ ' echo "::group::pnpm-lock.yaml patch (apply and commit)"',
1654
+ " git diff -- pnpm-lock.yaml",
1655
+ ' echo "::endgroup::"',
1656
+ ' echo "::error file=pnpm-lock.yaml::pnpm-lock.yaml is stale; commit the patch above."',
1657
+ " fi",
1658
+ " else",
1659
+ ' echo "::error::pnpm install --lockfile-only failed; no lockfile patch was produced."',
1660
+ " fi",
1661
+ ].join("\n");
1662
+ }
1663
+
1664
+ /**
1665
+ * swift.privatePackages: configure step, placed directly before the first step
1666
+ * in each opted-in job that builds or tests project code (the ci job, the
1667
+ * qualification job, the release-candidate candidate job, the regenerate job and
1668
+ * the parallel dev-artifact-mac job). It refuses to overwrite an
1669
+ * existing ~/.netrc, writes one machine entry per private host with mode 600,
1670
+ * and adds a job-scoped git insteadOf rewrite. The token reaches the step only
1671
+ * through env, never through the run script text. Returns "" when unset; the
1672
+ * value starts with a newline and has no trailing newline.
1673
+ */
1674
+ export function swiftPrivatePackagesConfigureStep(manifest) {
1675
+ const entries = manifest.swift?.privatePackages;
1676
+ if (!Array.isArray(entries) || entries.length === 0) return "";
1677
+ const env = entries.map((entry, index) => ` RIGHT_GIT_PRIVATE_TOKEN_${index}: \${{ secrets.${entry.secret} }}`);
1678
+ const checks = entries.map((entry, index) => ` test -n "$RIGHT_GIT_PRIVATE_TOKEN_${index}" || { echo "::error::right-git: secret ${entry.secret} is unavailable to this run"; exit 1; }`);
1679
+ const netrc = entries.map((entry, index) => ` printf 'machine %s\\nlogin x-access-token\\npassword %s\\n' '${entry.host}' "$RIGHT_GIT_PRIVATE_TOKEN_${index}" >> "$HOME/.netrc"`);
1680
+ const insteadOf = entries.map((entry, index) => ` git config --global "url.https://x-access-token:$RIGHT_GIT_PRIVATE_TOKEN_${index}@${entry.host}/.insteadOf" "https://${entry.host}/"`);
1681
+ return [
1682
+ "",
1683
+ " - name: Configure private Swift package access",
1684
+ " shell: bash",
1685
+ " env:",
1686
+ ...env,
1687
+ " run: |",
1688
+ " set -euo pipefail",
1689
+ " umask 077",
1690
+ ...checks,
1691
+ " test ! -e \"$HOME/.netrc\" || { echo \"::error::right-git: $HOME/.netrc already exists on this runner; refusing to overwrite it\"; exit 1; }",
1692
+ " : > \"$HOME/.netrc\"",
1693
+ // The marker follows creation so cleanup removes this file even if a later line fails.
1694
+ " : > \"$RUNNER_TEMP/right-git-private-netrc\"",
1695
+ ...netrc,
1696
+ " chmod 600 \"$HOME/.netrc\"",
1697
+ ...insteadOf,
1698
+ ].join("\n");
1699
+ }
1700
+
1701
+ /**
1702
+ * swift.privatePackages: cleanup step, rendered after the last step that builds
1703
+ * or tests project code in the same job (the end of the ci job; before any
1704
+ * push or upload elsewhere) and run even after a failed build. It only removes
1705
+ * what the configure step created (the marker file), so a cancelled run never
1706
+ * deletes a pre-existing ~/.netrc. Returns "" when unset; same newline convention as the configure step.
1707
+ */
1708
+ export function swiftPrivatePackagesCleanupStep(manifest) {
1709
+ const entries = manifest.swift?.privatePackages;
1710
+ if (!Array.isArray(entries) || entries.length === 0) return "";
1711
+ const env = entries.map((entry, index) => ` RIGHT_GIT_PRIVATE_TOKEN_${index}: \${{ secrets.${entry.secret} }}`);
1712
+ const removals = entries.map((entry, index) => ` git config --global --remove-section "url.https://x-access-token:$RIGHT_GIT_PRIVATE_TOKEN_${index}@${entry.host}/" || true`);
1713
+ return [
1714
+ "",
1715
+ " - name: Remove private Swift package access",
1716
+ " if: ${{ always() }}",
1717
+ " shell: bash",
1718
+ " env:",
1719
+ ...env,
1720
+ " run: |",
1721
+ " if [ -f \"$RUNNER_TEMP/right-git-private-netrc\" ]; then",
1722
+ " rm -f \"$HOME/.netrc\"",
1723
+ ...removals,
1724
+ " rm -f \"$RUNNER_TEMP/right-git-private-netrc\"",
1725
+ " fi",
1726
+ ].join("\n");
1727
+ }
1728
+
1729
+ /**
1730
+ * Optional QA evidence upload, rendered after the rust-hybrid gate step.
1731
+ * Returns "" when qaEvidencePath is unset, so the rendered workflow stays
1732
+ * byte-identical to a manifest without the key.
1733
+ */
1734
+ export function qaEvidenceStep(manifest) {
1735
+ if (manifest.qaEvidencePath === undefined) return "";
1736
+ const retentionDays = manifest.qaEvidenceRetentionDays ?? QA_EVIDENCE_DEFAULT_RETENTION_DAYS;
1737
+ return [
1738
+ " - name: Upload QA evidence",
1739
+ " if: always()",
1740
+ ` uses: ${UPLOAD_ARTIFACT_PIN}`,
1741
+ " with:",
1742
+ " name: qa-evidence-${{ matrix.os || runner.os }}-${{ github.run_attempt }}",
1743
+ ` path: \${{ runner.temp }}/${manifest.qaEvidencePath}`,
1744
+ ` retention-days: ${retentionDays}`,
1745
+ " if-no-files-found: ignore",
1746
+ "",
1747
+ ].join("\n");
1748
+ }
1749
+
1750
+ export function buildRenderContext(manifest, repoPath, lane = "ci") {
1751
+ const pm = parsePackageManager(manifest.packageManager);
1752
+ const projectName = deriveProjectName(repoPath);
1753
+ const artifactPrefix = projectName.toLowerCase().replace(/[^a-z0-9-]+/g, "-");
1754
+ const rustWorkspaces = manifest.rustCache?.workspaces ?? ["engine"];
1755
+ const configuredWindowsRunner = manifest.matrix.os.find((runner) => runner.startsWith("windows-"));
1756
+ const ciOs = configuredWindowsRunner ?? manifest.matrix.os[0];
1757
+ const ciMatrixOs = manifest.ciAllOs === true
1758
+ ? [
1759
+ " # ciAllOs: the gate runs on every matrix.os runner, in declared order.",
1760
+ ` os: ${yamlFlowStringList(manifest.matrix.os)}`,
1761
+ ]
1762
+ : [
1763
+ " # Full validation stays on one declared runner; prefer configured",
1764
+ " # Windows when available, otherwise preserve first configured OS.",
1765
+ ` os: ${yamlFlowStringList([ciOs])}`,
1766
+ ];
1767
+
1768
+ const cacheKeyLine = rustCacheKeyLine(manifest, lane);
1769
+ const context = {
1770
+ OS_MATRIX: yamlFlowStringList(manifest.matrix.os),
1771
+ CI_MATRIX_OS: ciMatrixOs.join("\n"),
1772
+ NODE_MATRIX: yamlFlowStringList(manifest.matrix.node),
1773
+ NODE_PUBLISH_VERSION: JSON.stringify(String(manifest.matrix.node[0])),
1774
+ PM_NAME: pm.name,
1775
+ PM_VERSION: pm.version,
1776
+ PM_CACHE: pm.name,
1777
+ INSTALL_COMMAND: pm.installCommand,
1778
+ PM_RUN: pm.runPrefix,
1779
+ PACKAGE_MANAGER_SETUP: pm.setup,
1780
+ ARTIFACT_PREFIX: artifactPrefix,
1781
+ DEFAULT_BRANCH: manifest.defaultBranch ?? "main",
1782
+ TEMPLATE_VERSION: manifest.templateVersion,
1783
+ RUST_CACHE_WORKSPACES: rustWorkspaces.map((workspace) => ` ${workspace} -> target`).join("\n"),
1784
+ RUST_REQUIRED_FOR_GATE: manifest.rustCache?.requiredForGate === true ? "true" : "false",
1785
+ WINDOWS_SIGNING_JOB: windowsSigningJob(manifest, pm, artifactPrefix),
1786
+ MACOS_SIGNING_JOB: macosSigningJob(manifest, pm, artifactPrefix),
1787
+ RELEASE_CHAIN_JOBS: releaseChainJobs(manifest, pm, artifactPrefix),
1788
+ OWNERSHIP_STEP: ownershipStep(manifest, lane),
1789
+ PNPM_LOCK_PATCH_STEP: lockfilePatchStep(manifest),
1790
+ SWIFT_PRIVATE_CONFIGURE_STEP: swiftPrivatePackagesConfigureStep(manifest),
1791
+ SWIFT_PRIVATE_CLEANUP_STEP: swiftPrivatePackagesCleanupStep(manifest),
1792
+ QA_EVIDENCE_STEP: qaEvidenceStep(manifest) + devArtifactCi(manifest, { lane, artifactPrefix }),
1793
+ CI_DISPATCH_TRIGGER: devArtifactDispatchTrigger(manifest),
1794
+ CI_CACHE_WORKSPACE_CRATES: manifest.ciIncremental === true ? "true" : "false",
1795
+ CI_CARGO_INCREMENTAL: manifest.ciIncremental === true ? "1" : "0",
1796
+ // sccache refuses CARGO_INCREMENTAL=1; incremental CI relies on the rust-cache target dir instead.
1797
+ CI_RUSTC_WRAPPER: manifest.ciIncremental === true ? '""' : "${{ steps.rust-changes.outputs.required == 'true' && 'sccache' || '' }}",
1798
+ CI_DERIVED_DATA_STEP: derivedDataStep(manifest),
1799
+ CI_CANCEL_IN_PROGRESS: manifest.concurrency?.mainPushes === "queue" ? CI_CANCEL_MAIN_QUEUE_EXPRESSION : "true",
1800
+ RUST_CACHE_KEY: cacheKeyLine ? `${cacheKeyLine}\n` : "",
1801
+ };
1802
+
1803
+ // Every key below is populated ONLY when its source manifest section is
1804
+ // actually present — mirroring the publish.npm/homebrew/winget pattern.
1805
+ // This keeps the fail-closed check just below honest: a key that is
1806
+ // legitimately inapplicable to this manifest (e.g. CANDIDATE_* for a
1807
+ // non-rust-hybrid manifest, GATE_PATH for a non-rust-hybrid profile) is
1808
+ // simply ABSENT from the context rather than present-with-undefined, so
1809
+ // render.mjs's own `Object.hasOwn` check does the right thing if a
1810
+ // template ever references a token this manifest didn't opt into.
1811
+ if (manifest.gate) {
1812
+ context.GATE_PATH = manifest.gate.path;
1813
+ }
1814
+ if (manifest.regenerate) {
1815
+ context.REGENERATE_SCRIPT = manifest.regenerate.script;
1816
+ }
1817
+ if (manifest.candidate) {
1818
+ context.CANDIDATE_BUILD_SCRIPT = manifest.candidate.buildScript;
1819
+ context.CANDIDATE_CHECK_SCRIPT = manifest.candidate.checkScript;
1820
+ context.CANDIDATE_ARTIFACT_ROOT = manifest.candidate.artifactRoot;
1821
+ context.CANDIDATE_OS_MATRIX = yamlFlowStringList(manifest.candidate.os ?? manifest.matrix.os);
1822
+ context.CANDIDATE_MATRIX = candidateMatrix(manifest);
1823
+ // admissionScript & stageSummaryScript are required candidate fields
1824
+ // (see validateManifest) whenever release-candidate is configured at
1825
+ // all — the admission job and the candidate job's stage-summary steps
1826
+ // are unconditional parts of the rendered template, independent of
1827
+ // signing/releaseChain.
1828
+ context.RELEASE_ADMISSION_SCRIPT = manifest.candidate.admissionScript;
1829
+ context.RELEASE_STAGE_SUMMARY_SCRIPT = manifest.candidate.stageSummaryScript;
1830
+ }
1831
+
1832
+ if (manifest.publish?.npm) {
1833
+ context.NPM_PROVENANCE_FLAG = manifest.publish.npm.provenance ? " --provenance" : "";
1834
+ }
1835
+ if (manifest.publish?.homebrew) {
1836
+ context.HOMEBREW_TAP = manifest.publish.homebrew.tap;
1837
+ context.HOMEBREW_FORMULA_NAME = manifest.publish.homebrew.formulaName;
1838
+ }
1839
+ if (manifest.publish?.winget) {
1840
+ context.WINGET_PACKAGE_IDENTIFIER = manifest.publish.winget.packageIdentifier;
1841
+ }
1842
+
1843
+ // F-undefined-script fix: render.mjs's `Object.hasOwn` check only proves a
1844
+ // key EXISTS in the context — it does not prove the key resolved to a real
1845
+ // value. Every field above that is sourced from an optional manifest path
1846
+ // (candidate.*, candidate.releaseChain.* via the job-builder functions,
1847
+ // gate.path) must resolve to a real string once its guarding `if` above
1848
+ // decided the section applies; a bug in one of those guards (or a
1849
+ // mis-nested manifest field) must fail the render loudly here rather than
1850
+ // silently emit a literal "undefined" into a workflow file that GitHub
1851
+ // Actions will then try to execute as a real step (e.g. `run: pnpm run
1852
+ // undefined`).
1853
+ for (const [key, value] of Object.entries(context)) {
1854
+ if (value === undefined || value === null) {
1855
+ throw new Error(`buildRenderContext: placeholder \${${key}} resolved to ${value} — check the manifest's candidate/releaseChain/gate/publish configuration`);
1856
+ }
1857
+ }
1858
+
1859
+ return context;
1860
+ }