@rightkit/ci 0.0.0-stage → 0.2.43

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.
@@ -0,0 +1,1722 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ import crypto from "node:crypto";
8
+ import { fileURLToPath } from "node:url";
9
+ import { renderTemplate, MANAGED_MARKER } from "./render.mjs";
10
+ import { buildRenderContext, LANE_FILENAMES, KNOWN_LANES, validateManifest, swiftPrivatePackagesConfigureStep, swiftPrivatePackagesCleanupStep } from "./manifest.mjs";
11
+
12
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)));
13
+ const templatesDir = path.join(packageRoot, "templates");
14
+
15
+ const FULL_MANIFEST = {
16
+ schemaVersion: 1,
17
+ compile: "github-actions-only",
18
+ lanes: [...KNOWN_LANES],
19
+ matrix: { os: ["ubuntu-latest", "macos-latest", "windows-latest"], node: ["22.13", "24"] },
20
+ packageManager: "pnpm@11.24.0",
21
+ publish: {
22
+ npm: { oidc: true, provenance: true },
23
+ homebrew: { tap: "acme/homebrew-tap", formulaName: "widgets" },
24
+ winget: { packageIdentifier: "Acme.Widgets" },
25
+ },
26
+ regenerate: { script: "regenerate" },
27
+ templateVersion: "1.0.0",
28
+ };
29
+
30
+ function renderAllLanes(manifest, repoPath) {
31
+ const rendered = {};
32
+ for (const lane of manifest.lanes) {
33
+ const templatePath = path.join(templatesDir, LANE_FILENAMES[lane]);
34
+ const templateText = fs.readFileSync(templatePath, "utf8");
35
+ rendered[lane] = renderTemplate(templateText, buildRenderContext(manifest, repoPath, lane));
36
+ }
37
+ return rendered;
38
+ }
39
+
40
+ test("every known lane has a template file and renders without an unresolved placeholder", () => {
41
+ for (const lane of KNOWN_LANES) {
42
+ const templatePath = path.join(templatesDir, LANE_FILENAMES[lane]);
43
+ assert.ok(fs.existsSync(templatePath), `missing template for lane ${lane}`);
44
+ }
45
+ const rendered = renderAllLanes(FULL_MANIFEST, "/repos/widgets");
46
+ assert.equal(Object.keys(rendered).length, KNOWN_LANES.length);
47
+ });
48
+
49
+ test("rust-hybrid ci renders its pinned package manager and gate", () => {
50
+ const manifest = { ...FULL_MANIFEST, lanes: ["ci"], profile: "rust-hybrid", gate: { path: "scripts/gate.sh" }, templateVersion: "1.1.0" };
51
+ const content = renderTemplate(fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/ci.yml"), "utf8"), buildRenderContext(manifest, "/repos/widgets"));
52
+ assert.match(content, /uses: pnpm\/action-setup@[a-f0-9]{40}/);
53
+ assert.match(content, /fetch-depth: 0/);
54
+ assert.match(content, /^name: widgets-ci$/m);
55
+ assert.match(content, /version: 11\.24\.0/);
56
+ assert.match(content, /components: rustfmt, clippy/);
57
+ assert.doesNotMatch(content, /toolchain:/);
58
+ assert.match(content, /group: \$\{\{ github\.workflow \}\}-\$\{\{ github\.ref \}\}/);
59
+ assert.match(content, /cancel-in-progress: true/);
60
+ assert.match(content, /bash \.\/scripts\/gate\.sh/);
61
+ assert.match(content, /name: Detect Rust-affecting changes\n id: rust-changes/);
62
+ assert.match(content, /RIGHT_GIT_DIFF_BASE: \$\{\{ github\.event_name == 'pull_request' && github\.event\.pull_request\.base\.sha \|\| '' \}\}/);
63
+ assert.doesNotMatch(content, /github\.event\.before/, "a push never diffs against the previous push: a failed run would be skipped over");
64
+ assert.match(content, /actions\/cache\/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6\.1\.0[\s\S]*restore-keys: \|\n widgets-last-green-\$\{\{ matrix\.os \}\}-\$\{\{ matrix\.node \}\}-\$\{\{ github\.ref_name \}\}-\n - name: Detect Rust-affecting changes/);
65
+ assert.match(content, /GITHUB_EVENT_NAME" != "pull_request"[\s\S]*base=""[\s\S]*\.right-git-last-green\/sha[\s\S]*merge-base --is-ancestor[\s\S]*git cat-file -e/, "no marker or a non-ancestor marker leaves changed=true");
66
+ assert.match(content, /bash \.\/scripts\/gate\.sh[\s\S]*name: Record last green commit marker\n if: github\.event_name != 'pull_request'[\s\S]*actions\/cache\/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6\.1\.0[\s\S]*github\.run_attempt \}\}\n/, "the marker is written only after the gate passed, as the job's last steps");
67
+ assert.match(content, /changed=true[\s\S]*\^0\{40\}\$[\s\S]*git cat-file -e[\s\S]*git diff --name-only --diff-filter=ACDMRTUXB/);
68
+ assert.match(content, /--diff-filter=ACDMRTUXB/, "deleted Rust inputs must trigger Rust setup");
69
+ assert.match(content, /\*\.rs\|Cargo\.toml[\s\S]*scripts\/gate\.sh/);
70
+ assert.doesNotMatch(content, /\|build\.rs\||\|\*\/build\.rs\|/);
71
+ assert.match(content, /\.rightgit\.json\|\.github\/workflows\/\*\.yml\|\.github\/workflows\/\*\.yaml/);
72
+ assert.equal((content.match(/if: steps\.rust-changes\.outputs\.required == 'true'/g) ?? []).length, 3);
73
+ assert.match(content, /RIGHT_GIT_RUST_CHANGED: \$\{\{ steps\.rust-changes\.outputs\.changed \}\}/);
74
+ assert.match(content, /RIGHT_GIT_RUST_REQUIRED: \$\{\{ steps\.rust-changes\.outputs\.required \}\}/);
75
+ assert.match(content, /RUSTC_WRAPPER: \$\{\{ steps\.rust-changes\.outputs\.required == 'true' && 'sccache' \|\| '' \}\}/);
76
+ assert.match(content, /CARGO_INCREMENTAL: "0"/);
77
+ assert.match(content, /CARGO_PROFILE_DEV_DEBUG: "0"/);
78
+ assert.match(content, /CARGO_PROFILE_TEST_DEBUG: "0"/);
79
+ assert.doesNotMatch(content, /opt-level|codegen-units|\blto\b|strip\s*=/i);
80
+ assert.match(content, /os: \["windows-latest"\]/);
81
+ assert.doesNotMatch(content, /ubuntu-latest|macos-latest/);
82
+ });
83
+
84
+ test("every generated workflow profile runs ownership scanning independent of optional repository roots", () => {
85
+ const roots = ["engine", "apps/client"];
86
+ const manifest = { ...FULL_MANIFEST, ownership: { roots } };
87
+ const rendered = renderAllLanes(manifest, "C:/repos/coderight");
88
+ for (const [lane, content] of Object.entries(rendered)) {
89
+ assert.match(content, /right-release ownership --app \./, lane);
90
+ assert.match(content, /protected registry roots/, lane);
91
+ }
92
+ const rust = renderTemplate(fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/ci.yml"), "utf8"), buildRenderContext({ ...manifest, profile: "rust-hybrid", gate: { path: "scripts/gate.sh" } }, "C:/repos/coderight"));
93
+ assert.match(rust, /RightKit ownership \(protected registry roots\)/);
94
+ assert.match(rust, /pnpm exec right-release ownership --app \./);
95
+ const withoutRoots = renderAllLanes(FULL_MANIFEST, "C:/repos/widgets");
96
+ for (const [lane, content] of Object.entries(withoutRoots)) assert.match(content, /right-release ownership --app \./, lane);
97
+ });
98
+
99
+ test("ordinary CI templates cancel superseded runs on the same ref", () => {
100
+ const generic = renderAllLanes(FULL_MANIFEST, "/repos/widgets").ci;
101
+ assert.match(generic, /group: \$\{\{ github\.workflow \}\}-\$\{\{ github\.ref \}\}/);
102
+ assert.match(generic, /cancel-in-progress: true/);
103
+ });
104
+
105
+ test("ownership revision expression matches each lane trigger contract", () => {
106
+ const rendered = renderAllLanes(FULL_MANIFEST, "/repos/widgets");
107
+ assert.match(rendered.ci, /git rev-parse HEAD\)" = "\$\{\{ github\.sha \}\}/);
108
+ assert.doesNotMatch(rendered.ci, /inputs\.source_revision/);
109
+ assert.match(rendered["publish-package-managers"], /git rev-parse HEAD\)" = "\$\{\{ github\.sha \}\}/);
110
+ assert.doesNotMatch(rendered["publish-package-managers"], /inputs\.source_revision/);
111
+ assert.match(rendered["release-candidate"], /git rev-parse HEAD\)" = "\$\{\{ inputs\.source_revision \|\| github\.sha \}\}/);
112
+ });
113
+
114
+ test("rust-hybrid ci preserves a declared macOS-only lane", () => {
115
+ const manifest = {
116
+ ...FULL_MANIFEST,
117
+ lanes: ["ci"],
118
+ profile: "rust-hybrid",
119
+ gate: { path: "scripts/gate.sh" },
120
+ matrix: { os: ["macos-14"], node: ["26.8.1"] },
121
+ };
122
+ const content = renderTemplate(
123
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/ci.yml"), "utf8"),
124
+ buildRenderContext(manifest, "/repos/widgets"),
125
+ );
126
+ assert.match(content, /os: \["macos-14"\]/);
127
+ assert.doesNotMatch(content, /windows-2025/);
128
+ });
129
+
130
+ test("rust-hybrid ci runs every matrix.os runner when ciAllOs is true, in declared order", () => {
131
+ const base = {
132
+ ...FULL_MANIFEST,
133
+ lanes: ["ci"],
134
+ profile: "rust-hybrid",
135
+ gate: { path: "scripts/gate.sh" },
136
+ qaEvidencePath: "pulse-hub-qa",
137
+ matrix: { os: ["xcode-27", "windows-2025"], node: ["26.8.1"] },
138
+ };
139
+ const render = (manifest) => renderTemplate(
140
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/ci.yml"), "utf8"),
141
+ buildRenderContext(manifest, "/repos/pulse"),
142
+ );
143
+ const all = render({ ...base, ciAllOs: true });
144
+ assert.match(all, /^ {8}os: \["xcode-27", "windows-2025"\]$/m);
145
+ assert.match(all, /runs-on: \$\{\{ matrix\.os \}\}/);
146
+ assert.match(all, /fail-fast: false/);
147
+ assert.match(all, /name: qa-evidence-\$\{\{ matrix\.os \|\| runner\.os \}\}-\$\{\{ github\.run_attempt \}\}/);
148
+ assert.doesNotMatch(all, /Full validation stays/);
149
+ // ciAllOs false and unset render the same single-runner matrix as before.
150
+ for (const manifest of [base, { ...base, ciAllOs: false }]) {
151
+ const single = render(manifest);
152
+ assert.match(single, /# Full validation stays on one declared runner; prefer configured\n {8}# Windows when available, otherwise preserve first configured OS\.\n {8}os: \["windows-2025"\]\n/);
153
+ assert.doesNotMatch(single, /xcode-27/);
154
+ }
155
+ // Unset and false produce byte-identical output.
156
+ assert.equal(render({ ...base, ciAllOs: false }), render(base));
157
+ });
158
+
159
+ test("rust-hybrid release candidate renders product scripts, artifact handoff, and no signing secret", () => {
160
+ const manifest = {
161
+ ...FULL_MANIFEST,
162
+ lanes: ["ci", "release-candidate"],
163
+ profile: "rust-hybrid",
164
+ gate: { path: "scripts/gate.sh" },
165
+ candidate: {
166
+ buildScript: "ci:candidate",
167
+ checkScript: "ci:candidate-check",
168
+ admissionScript: "release:admit",
169
+ stageSummaryScript: "release:stage-summary",
170
+ artifactRoot: "widgets-unsigned",
171
+ os: ["macos-latest", "windows-latest"],
172
+ },
173
+ templateVersion: "1.2.0",
174
+ };
175
+ const content = renderTemplate(
176
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
177
+ buildRenderContext(manifest, "/repos/widgets"),
178
+ );
179
+ assert.match(content, /pnpm run ci:candidate/);
180
+ assert.match(content, /pnpm run ci:candidate-check/);
181
+ assert.match(content, /pnpm run release:admit/);
182
+ assert.match(content, /pnpm run release:stage-summary/);
183
+ assert.match(content, /Mozilla-Actions\/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba/);
184
+ assert.match(content, /shared-key: widgets-rust/);
185
+ assert.doesNotMatch(content, /bash \.\/scripts\/gate\.sh/);
186
+ assert.match(content, /RIGHT_GIT_ARTIFACT_ROOT/);
187
+ assert.match(content, /os: "macos-latest"/);
188
+ assert.match(content, /platform: "windows"/);
189
+ assert.match(content, /RIGHT_GIT_RELEASE_ARCHITECTURE: \$\{\{ matrix\.architecture \}\}/);
190
+ assert.match(content, /actions\/upload-artifact@[a-f0-9]{40}/);
191
+ assert.doesNotMatch(content, /secrets\.|AZURE_|APPLE_|certificate|private.key/i);
192
+ assert.doesNotMatch(content, /rust-changes|RIGHT_GIT_RUST_CHANGED/);
193
+ assert.doesNotMatch(content, /if: steps\.rust-changes/);
194
+ assert.match(content, /uses: dtolnay\/rust-toolchain@[a-f0-9]{40}\n with:/);
195
+ // workflow_dispatch tag-last envelope: no windows-sign/macos-sign/release
196
+ // chain jobs render at all when signing is not configured.
197
+ assert.match(content, /^on:\n workflow_dispatch:/m);
198
+ assert.doesNotMatch(content, /^ {2}(?:windows-sign|macos-sign|installed-qualification|publish):\s*$/m);
199
+ assert.doesNotMatch(content, /run: (?:pnpm|npm|yarn) run undefined\b/);
200
+ assert.doesNotMatch(content, /\$\{\{\s*github\.output\s*\}\}/);
201
+ });
202
+
203
+ test("rust-hybrid cache contract renders every declared Cargo workspace", () => {
204
+ const manifest = {
205
+ ...FULL_MANIFEST,
206
+ lanes: ["ci"],
207
+ profile: "rust-hybrid",
208
+ gate: { path: "scripts/gate.sh" },
209
+ rustCache: { workspaces: [".", "apps/studio/src-tauri"], requiredForGate: true },
210
+ matrix: { os: ["windows-2025"], node: ["22.23.2"] },
211
+ };
212
+ const content = renderTemplate(
213
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/ci.yml"), "utf8"),
214
+ buildRenderContext(manifest, "/repos/widgets"),
215
+ );
216
+ assert.match(content, /workspaces: \|\n \. -> target\n apps\/studio\/src-tauri -> target/);
217
+ assert.match(content, /add-job-id-key: false/);
218
+ assert.match(content, /cache-workspace-crates: false/);
219
+ assert.match(content, /cache-on-failure: true/);
220
+ assert.match(content, /if \[\[ "true" == "true" \]\]; then[\s\S]*required=true/);
221
+ assert.match(content, /RUSTC_WRAPPER: \$\{\{ steps\.rust-changes\.outputs\.required == 'true' && 'sccache' \|\| '' \}\}/);
222
+ });
223
+
224
+ test("release-candidate artifact names all carry the admission artifact_suffix so dry-run artifacts cannot impersonate real ones", () => {
225
+ const manifest = {
226
+ ...FULL_MANIFEST,
227
+ lanes: ["ci", "release-candidate"],
228
+ profile: "rust-hybrid",
229
+ gate: { path: "scripts/gate.sh" },
230
+ candidate: {
231
+ buildScript: "ci:candidate",
232
+ checkScript: "ci:candidate-check",
233
+ admissionScript: "release:admit",
234
+ stageSummaryScript: "release:stage-summary",
235
+ artifactRoot: "widgets-unsigned",
236
+ os: ["windows-2025", "macos-15"],
237
+ targets: [
238
+ { os: "windows-2025", platform: "windows", architecture: "x86_64" },
239
+ { os: "macos-15", platform: "macos", architecture: "arm64" },
240
+ ],
241
+ signWindows: true,
242
+ signMacos: true,
243
+ releaseChain: {
244
+ evidenceVerificationScript: "release:verify-evidence",
245
+ windowsFinalizeScript: "release:finalize-windows",
246
+ macosFinalizeScript: "release:finalize-macos",
247
+ installedQualificationScript: "release:qualify-installed",
248
+ publishScript: "release:publish-qualified",
249
+ qualificationRunnerVariable: "WIDGETS_QUALIFICATION_RUNNER",
250
+ },
251
+ },
252
+ matrix: { os: ["ubuntu-24.04", "windows-2025", "macos-15"], node: ["22.23.2"] },
253
+ templateVersion: "1.8.0",
254
+ };
255
+ const content = renderTemplate(
256
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
257
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
258
+ );
259
+ const identityNames = content.split("\n").filter((line) => /^\s*name: .*needs\.admission\.outputs\.source_revision/.test(line));
260
+ assert.ok(identityNames.length >= 8, `expected identity-bound artifact names, got ${identityNames.length}`);
261
+ for (const line of identityNames) {
262
+ assert.ok(line.endsWith("${{ needs.admission.outputs.source_revision }}${{ needs.admission.outputs.artifact_suffix }}"), line.trim());
263
+ }
264
+ assert.match(content, /artifact_suffix: \$\{\{ steps\.admit\.outputs\.artifact_suffix \}\}/);
265
+ // The publish gate text is pinned by @rightkit/release's hosted-workflow policy; dry runs are refused by admission, not by this `if`.
266
+ assert.match(content, /publish:\n needs: \[[^\n]*\]\n if: \$\{\{ needs\.admission\.outputs\.publish == 'true' && needs\.installed-qualification\.result == 'success' && needs\.macos-sign\.result == 'success' \}\}/);
267
+ });
268
+
269
+ test("rust-hybrid release candidate can opt into OIDC Windows signing without long-lived secrets", () => {
270
+ const manifest = {
271
+ ...FULL_MANIFEST,
272
+ lanes: ["ci", "release-candidate"],
273
+ profile: "rust-hybrid",
274
+ gate: { path: "scripts/gate.sh" },
275
+ candidate: {
276
+ buildScript: "ci:candidate",
277
+ checkScript: "ci:candidate-check",
278
+ admissionScript: "release:admit",
279
+ stageSummaryScript: "release:stage-summary",
280
+ artifactRoot: "widgets-unsigned",
281
+ os: ["windows-2025"],
282
+ signWindows: true,
283
+ },
284
+ matrix: { os: ["ubuntu-24.04", "windows-2025"], node: ["22.23.2"] },
285
+ templateVersion: "1.3.0",
286
+ };
287
+ const content = renderTemplate(
288
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
289
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
290
+ );
291
+ assert.match(content, /environment: release/);
292
+ // Tag-last contract: signing is gated on the admitted, same-run
293
+ // signed_qualification OUTPUT of the `admission` job — never on a ref/tag
294
+ // and never on the raw workflow_dispatch input directly.
295
+ assert.match(content, /windows-sign:\n needs: \[admission, candidate\]\n if: \$\{\{ needs\.admission\.outputs\.signed_qualification == 'true' \}\}/);
296
+ assert.doesNotMatch(content, /startsWith\(github\.ref, 'refs\/tags\/v'\)/);
297
+ assert.match(content, /id-token: write/);
298
+ assert.match(content, /azure\/login@[a-f0-9]{40}/);
299
+ assert.match(content, /vars\.AZURE_CLIENT_ID/);
300
+ assert.match(content, /right-release build --platform win --skip-checks/);
301
+ assert.match(content, /Artifact Signing client hash mismatch/);
302
+ // Every downstream job (admission, candidate, and windows-sign here) checks
303
+ // out the exact admitted revision by SHA, never by resolving HEAD after a
304
+ // ref-triggered checkout.
305
+ assert.match(content, /windows-sign:[\s\S]*?ref: \$\{\{ needs\.admission\.outputs\.source_revision \}\}\n\s+fetch-depth: 0\n\s+persist-credentials: false/);
306
+ assert.match(content, /git rev-parse HEAD.*inputs\.source_revision/);
307
+ assert.ok(content.includes("LEGION_SOURCE_REVISION: ${{ needs.admission.outputs.source_revision }}"));
308
+ assert.ok(content.includes("RIGHT_GIT_SOURCE_REVISION: ${{ needs.admission.outputs.source_revision }}"));
309
+ assert.doesNotMatch(content, /env\.RIGHT_GIT_SOURCE_REVISION/);
310
+ assert.doesNotMatch(content, /LEGION_SOURCE_REVISION: \$\{\{ github\.sha \}\}/);
311
+ assert.doesNotMatch(content, /secrets\.|client-secret|private.key/i);
312
+ assert.doesNotMatch(content, /run: (?:pnpm|npm|yarn) run undefined\b/);
313
+ assert.doesNotMatch(content, /\$\{\{\s*github\.output\s*\}\}/);
314
+ });
315
+
316
+ test("rust-hybrid release candidate can opt into protected macOS signing & notarization", () => {
317
+ const manifest = {
318
+ ...FULL_MANIFEST,
319
+ lanes: ["ci", "release-candidate"],
320
+ profile: "rust-hybrid",
321
+ gate: { path: "scripts/gate.sh" },
322
+ candidate: {
323
+ buildScript: "ci:candidate",
324
+ checkScript: "ci:candidate-check",
325
+ admissionScript: "release:admit",
326
+ stageSummaryScript: "release:stage-summary",
327
+ artifactRoot: "widgets-unsigned",
328
+ os: ["macos-15"],
329
+ signMacos: true,
330
+ },
331
+ matrix: { os: ["ubuntu-24.04", "macos-15"], node: ["22.23.2"] },
332
+ templateVersion: "1.3.0",
333
+ };
334
+ const content = renderTemplate(
335
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
336
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
337
+ );
338
+ assert.match(content, /macos-sign:/);
339
+ assert.match(content, /macos-sign:\n needs: \[admission, candidate\]\n if: \$\{\{ needs\.admission\.outputs\.signed_qualification == 'true' \}\}/);
340
+ assert.doesNotMatch(content, /startsWith\(github\.ref, 'refs\/tags\/v'\)/);
341
+ assert.match(content, /environment: release/);
342
+ assert.match(content, /secrets\.APPLE_CERTIFICATE_BASE64/);
343
+ assert.match(content, /temporary keychain/i);
344
+ assert.match(content, /right-release build --platform mac --skip-checks/);
345
+ assert.match(content, /secrets\.APPLE_API_KEY_BASE64/);
346
+ assert.match(content, /macos-sign:[\s\S]*?ref: \$\{\{ needs\.admission\.outputs\.source_revision \}\}\n\s+fetch-depth: 0\n\s+persist-credentials: false/);
347
+ assert.match(content, /git rev-parse HEAD.*inputs\.source_revision/);
348
+ assert.ok(content.includes("LEGION_SOURCE_REVISION: ${{ needs.admission.outputs.source_revision }}"));
349
+ assert.ok(content.includes("RIGHT_GIT_SOURCE_REVISION: ${{ needs.admission.outputs.source_revision }}"));
350
+ assert.doesNotMatch(content, /env\.RIGHT_GIT_SOURCE_REVISION/);
351
+ assert.doesNotMatch(content, /LEGION_SOURCE_REVISION: \$\{\{ github\.sha \}\}/);
352
+ assert.match(content, /security delete-keychain/);
353
+ assert.doesNotMatch(content, /pull_request_target/);
354
+ assert.doesNotMatch(content, /run: (?:pnpm|npm|yarn) run undefined\b/);
355
+ assert.doesNotMatch(content, /\$\{\{\s*github\.output\s*\}\}/);
356
+ });
357
+
358
+ test("rust-hybrid multi-architecture candidates bind every native target to exact artifacts and signing", () => {
359
+ const manifest = {
360
+ ...FULL_MANIFEST,
361
+ lanes: ["ci", "release-candidate"],
362
+ profile: "rust-hybrid",
363
+ gate: { path: "scripts/gate.sh" },
364
+ matrix: { os: ["ubuntu-24.04"], node: ["22.23.2"] },
365
+ candidate: {
366
+ buildScript: "ci:candidate",
367
+ checkScript: "ci:candidate-check",
368
+ admissionScript: "release:admit",
369
+ stageSummaryScript: "release:stage-summary",
370
+ artifactRoot: "widgets-unsigned",
371
+ os: ["windows-2025", "windows-11-arm", "macos-15", "macos-15-intel"],
372
+ targets: [
373
+ { os: "windows-2025", platform: "windows", architecture: "x86_64" },
374
+ { os: "windows-11-arm", platform: "windows", architecture: "arm64" },
375
+ { os: "macos-15", platform: "macos", architecture: "arm64" },
376
+ { os: "macos-15-intel", platform: "macos", architecture: "x86_64" },
377
+ ],
378
+ signWindows: true,
379
+ signMacos: true,
380
+ },
381
+ templateVersion: "1.5.0",
382
+ };
383
+ const content = renderTemplate(
384
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
385
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
386
+ );
387
+ for (const [runner, triple] of [["windows-2025", "x86_64-pc-windows-msvc"], ["windows-11-arm", "aarch64-pc-windows-msvc"], ["macos-15", "aarch64-apple-darwin"], ["macos-15-intel", "x86_64-apple-darwin"]]) {
388
+ assert.match(content, new RegExp(`os: ${JSON.stringify(runner).replace(/[.*+?^${}()|[\\]\\]/g, "\\$&")}`));
389
+ assert.match(content, new RegExp(`targetTriple: ${JSON.stringify(triple).replace(/[.*+?^${}()|[\\]\\]/g, "\\$&")}`));
390
+ }
391
+ assert.match(content, /targets: \$\{\{ matrix\.targetTriple \}\}/);
392
+ assert.doesNotMatch(content, /bash \.\/scripts\/gate\.sh/);
393
+ assert.match(content, /windows-sign:[\s\S]*matrix:[\s\S]*windows-11-arm/);
394
+ assert.match(content, /macos-sign:[\s\S]*matrix:[\s\S]*macos-15-intel/);
395
+ // Every artifact name is run- and identity-bound: <prefix>-<run_id>-<run_attempt>-<kind>-...-<version>-<source_revision>.
396
+ assert.match(content, /name: widgets-\$\{\{ github\.run_id \}\}-\$\{\{ github\.run_attempt \}\}-candidate-\$\{\{ matrix\.platform \}\}-\$\{\{ matrix\.architecture \}\}-\$\{\{ needs\.admission\.outputs\.version \}\}-\$\{\{ needs\.admission\.outputs\.source_revision \}\}/);
397
+ assert.match(content, /name: widgets-\$\{\{ github\.run_id \}\}-\$\{\{ github\.run_attempt \}\}-signed-windows-\$\{\{ matrix\.architecture \}\}-\$\{\{ needs\.admission\.outputs\.version \}\}-\$\{\{ needs\.admission\.outputs\.source_revision \}\}/);
398
+ assert.match(content, /name: widgets-\$\{\{ github\.run_id \}\}-\$\{\{ github\.run_attempt \}\}-signed-macos-\$\{\{ matrix\.architecture \}\}-\$\{\{ needs\.admission\.outputs\.version \}\}-\$\{\{ needs\.admission\.outputs\.source_revision \}\}/);
399
+ // Exact-count regression guard across the candidate job's build/check/
400
+ // stage-summary steps and the windows-sign/macos-sign stage-summary steps.
401
+ assert.equal((content.match(/RIGHT_GIT_RELEASE_ARCHITECTURE: \$\{\{ matrix\.architecture \}\}/g) ?? []).length, 10);
402
+ assert.doesNotMatch(content, /run: (?:pnpm|npm|yarn) run undefined\b/);
403
+ assert.doesNotMatch(content, /\$\{\{\s*github\.output\s*\}\}/);
404
+ });
405
+
406
+ test("rust-hybrid release chain preserves signed candidate, installed qualification, then publish", () => {
407
+ const manifest = {
408
+ ...FULL_MANIFEST,
409
+ lanes: ["ci", "release-candidate"],
410
+ profile: "rust-hybrid",
411
+ gate: { path: "scripts/gate.sh" },
412
+ candidate: {
413
+ buildScript: "ci:candidate",
414
+ checkScript: "ci:candidate-check",
415
+ admissionScript: "release:admit",
416
+ stageSummaryScript: "release:stage-summary",
417
+ artifactRoot: "widgets-unsigned",
418
+ os: ["windows-2025", "macos-15"],
419
+ signWindows: true,
420
+ signMacos: true,
421
+ releaseChain: {
422
+ evidenceVerificationScript: "release:verify-evidence",
423
+ windowsFinalizeScript: "release:finalize:win",
424
+ macosFinalizeScript: "release:finalize:mac",
425
+ installedQualificationScript: "release:qualify:installed",
426
+ publishScript: "release:publish:qualified",
427
+ qualificationRunnerVariable: "QUALIFICATION_RUNNER_LABEL",
428
+ publishSecrets: ["CLOUDFLARE_API_TOKEN"],
429
+ },
430
+ },
431
+ matrix: { os: ["ubuntu-24.04", "windows-2025", "macos-15"], node: ["22.23.2"] },
432
+ templateVersion: "1.4.0",
433
+ };
434
+ const content = renderTemplate(
435
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
436
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
437
+ );
438
+ assert.match(content, /windows-sign:[\s\S]*pnpm run release:finalize:win/);
439
+ assert.match(content, /macos-sign:[\s\S]*pnpm run release:finalize:mac/);
440
+ // Tag-last contract: every gate reads the ADMITTED, same-run outputs of
441
+ // the `admission` job — never the raw workflow_dispatch input directly,
442
+ // and never a ref/tag.
443
+ assert.match(content, /signed_qualification:\n description: Run protected signing, installed qualification, & evidence verification/);
444
+ assert.doesNotMatch(content, /inputs\.signed_qualification == true/);
445
+ assert.doesNotMatch(content, /startsWith\(github\.ref, 'refs\/tags\/v'\)/);
446
+ assert.match(content, /windows-sign:\n needs: \[admission, candidate\]\n if: \$\{\{ needs\.admission\.outputs\.signed_qualification == 'true' \}\}/);
447
+ assert.match(content, /macos-sign:\n needs: \[admission, candidate\]\n if: \$\{\{ needs\.admission\.outputs\.signed_qualification == 'true' \}\}/);
448
+ assert.match(content, /installed-qualification:\n needs: \[admission, candidate, windows-sign\]/);
449
+ assert.match(content, /installed-qualification:[\s\S]*?if: \$\{\{ always\(\) && needs\.admission\.outputs\.signed_qualification == 'true' && needs\.candidate\.result == 'success' \}\}/);
450
+ assert.match(content, /installed_qualification_failed/);
451
+ assert.match(content, /shell: pwsh\n run: \|\n throw 'installed_qualification_failed \{ reason: prerequisites_absent, detail: "same-run Windows signing\/finalization did not succeed" \}'/);
452
+ assert.doesNotMatch(content, /^ run: throw 'installed_qualification_failed .*detail: /m);
453
+ assert.match(content, /pnpm run release:qualify:installed/);
454
+ assert.match(content, /installed-qualification:[\s\S]*GH_TOKEN: \$\{\{ github\.token \}\}/);
455
+ assert.match(content, /publish:\n needs: \[admission, installed-qualification, macos-sign\]/);
456
+ assert.match(content, /publish:[\s\S]*?if: \$\{\{ needs\.admission\.outputs\.publish == 'true' && needs\.installed-qualification\.result == 'success' && needs\.macos-sign\.result == 'success' \}\}/);
457
+ const publishJobIndex = content.search(/^ {2}publish:\n {4}needs:/m);
458
+ assert.ok(publishJobIndex >= 0, "publish job must be present");
459
+ assert.doesNotMatch(content.slice(publishJobIndex), /inputs\.signed_qualification|inputs\.publish/);
460
+ assert.match(content, /contents: write/);
461
+ // Publish is the sole creator of the tag/release: it must not require a
462
+ // pre-existing tag anywhere in its gate.
463
+ assert.doesNotMatch(content.slice(publishJobIndex), /refs\/tags/);
464
+ assert.match(content, /pnpm run release:verify-evidence/);
465
+ assert.match(content, /Verify aggregated release evidence[\s\S]*?pnpm run release:verify-evidence/);
466
+ assert.match(content, /pnpm run release:publish:qualified/);
467
+ assert.match(content, /CLOUDFLARE_API_TOKEN: \$\{\{ secrets\.CLOUDFLARE_API_TOKEN \}\}/);
468
+ // Ownership scan binds to the source revision input before admission emits
469
+ // that same revision for every downstream job.
470
+ assert.match(content, /git rev-parse HEAD.*inputs\.source_revision/);
471
+ assert.doesNotMatch(content, /RIGHT_GIT_SOURCE_REVISION: \$\{\{ github\.sha \}\}/);
472
+ // candidate, windows-sign, macos-sign, installed-qualification and publish all
473
+ // check out the admitted revision with full history; admission checks out
474
+ // ${{ inputs.source_revision }} (it IS the admission job — there is no
475
+ // needs.admission yet). Full history is load-bearing, not cosmetic: see
476
+ // "every job checking out an admitted revision fetches full history".
477
+ assert.equal((content.match(/ref: \$\{\{ needs\.admission\.outputs\.source_revision \}\}\n\s+fetch-depth: 0\n\s+persist-credentials: false/g) ?? []).length, 5, "candidate, windows-sign, macos-sign, installed-qualification & publish should all pin the admitted revision with full history");
478
+ assert.doesNotMatch(content, /ref: \$\{\{ needs\.admission\.outputs\.source_revision \}\}\n\s+persist-credentials: false/, "no admitted-revision checkout may be shallow");
479
+ assert.match(content, /ref: \$\{\{ inputs\.source_revision \}\}\n\s+fetch-depth: 0\n\s+persist-credentials: false/, "admission must check out the exact dispatch-supplied revision");
480
+ assert.doesNotMatch(content.slice(0, content.indexOf(" windows-sign:")), /secrets\.|id-token: write|contents: write/);
481
+ // Downstream download-artifact names must match exactly what windows-sign/
482
+ // macos-sign uploaded (see the multi-architecture test) — this is the
483
+ // regression guard for the artifact-name mismatch bug.
484
+ const windowsSignedArtifact = "widgets-${{ github.run_id }}-${{ github.run_attempt }}-signed-windows-x86_64-${{ needs.admission.outputs.version }}-${{ needs.admission.outputs.source_revision }}";
485
+ const macosSignedArtifact = "widgets-${{ github.run_id }}-${{ github.run_attempt }}-signed-macos-arm64-${{ needs.admission.outputs.version }}-${{ needs.admission.outputs.source_revision }}";
486
+ assert.equal((content.match(new RegExp(windowsSignedArtifact.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")) ?? []).length, 2, "windows-sign upload + installed-qualification/publish download must share one artifact name");
487
+ assert.ok(content.includes(macosSignedArtifact), "publish must download the exact macOS artifact macos-sign uploaded");
488
+ assert.doesNotMatch(content, /run: (?:pnpm|npm|yarn) run undefined\b/);
489
+ assert.doesNotMatch(content, /\$\{\{\s*github\.output\s*\}\}/);
490
+ });
491
+
492
+ // Part E regression guard: every `run: <pm> run <script>` line in a
493
+ // rendered full release-chain workflow must name a script the manifest
494
+ // actually declares. This is the general form of the `pnpm run undefined`
495
+ // class of bug — it would also catch a typo'd or stale script reference
496
+ // even when it resolves to a real (but wrong) string, which the fail-closed
497
+ // undefined/null check in buildRenderContext cannot.
498
+ test("every 'run <script>' in a full release-chain workflow names a script the manifest declares", () => {
499
+ const manifest = {
500
+ ...FULL_MANIFEST,
501
+ lanes: ["ci", "release-candidate"],
502
+ profile: "rust-hybrid",
503
+ gate: { path: "scripts/gate.sh" },
504
+ candidate: {
505
+ buildScript: "ci:candidate",
506
+ checkScript: "ci:candidate-check",
507
+ admissionScript: "release:admit",
508
+ stageSummaryScript: "release:stage-summary",
509
+ artifactRoot: "widgets-unsigned",
510
+ os: ["windows-2025", "macos-15"],
511
+ signWindows: true,
512
+ signMacos: true,
513
+ releaseChain: {
514
+ evidenceVerificationScript: "release:verify-evidence",
515
+ windowsFinalizeScript: "release:finalize:win",
516
+ macosFinalizeScript: "release:finalize:mac",
517
+ installedQualificationScript: "release:qualify:installed",
518
+ publishScript: "release:publish:qualified",
519
+ qualificationRunnerVariable: "QUALIFICATION_RUNNER_LABEL",
520
+ publishSecrets: ["CLOUDFLARE_API_TOKEN"],
521
+ },
522
+ },
523
+ matrix: { os: ["ubuntu-24.04", "windows-2025", "macos-15"], node: ["22.23.2"] },
524
+ templateVersion: "1.4.0",
525
+ };
526
+ const content = renderTemplate(
527
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
528
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
529
+ );
530
+ const declaredScripts = new Set([
531
+ manifest.candidate.buildScript,
532
+ manifest.candidate.checkScript,
533
+ manifest.candidate.admissionScript,
534
+ manifest.candidate.stageSummaryScript,
535
+ manifest.candidate.releaseChain.evidenceVerificationScript,
536
+ manifest.candidate.releaseChain.windowsFinalizeScript,
537
+ manifest.candidate.releaseChain.macosFinalizeScript,
538
+ manifest.candidate.releaseChain.installedQualificationScript,
539
+ manifest.candidate.releaseChain.publishScript,
540
+ ]);
541
+ const runLines = content.match(/run: (?:pnpm|npm|yarn) run \S+/g) ?? [];
542
+ assert.ok(runLines.length > 0, "expected at least one package-script run line");
543
+ for (const line of runLines) {
544
+ const script = line.split(" run ").pop();
545
+ assert.ok(declaredScripts.has(script), `rendered step runs undeclared script: ${line}`);
546
+ }
547
+ });
548
+
549
+ // Downstream-consumer gap fix: the evidence verifier can only prove a stage
550
+ // ran and succeeded if that stage produces a stage summary AND the publish
551
+ // job actually downloads it. This test proves all four authoritative
552
+ // stages (candidate, windows-sign, macos-sign, installed-qualification)
553
+ // produce a summary, that installed-qualification wraps itself in
554
+ // init/finalize like every other stage, that publish downloads the
555
+ // complete same-run set into distinct subdirectories (no collisions
556
+ // between candidate's two platform legs), and that evidence is bound to
557
+ // this exact run (not merely version+source_revision) via RIGHT_GIT_RUN_ID/
558
+ // RIGHT_GIT_RUN_ATTEMPT on both the verification and publish steps.
559
+ test("release chain: installed-qualification has a stage summary and publish downloads the complete same-run evidence set", () => {
560
+ const manifest = {
561
+ ...FULL_MANIFEST,
562
+ lanes: ["ci", "release-candidate"],
563
+ profile: "rust-hybrid",
564
+ gate: { path: "scripts/gate.sh" },
565
+ candidate: {
566
+ buildScript: "ci:candidate",
567
+ checkScript: "ci:candidate-check",
568
+ admissionScript: "release:admit",
569
+ stageSummaryScript: "release:stage-summary",
570
+ artifactRoot: "widgets-unsigned",
571
+ os: ["windows-2025", "macos-15"],
572
+ signWindows: true,
573
+ signMacos: true,
574
+ releaseChain: {
575
+ evidenceVerificationScript: "release:verify-evidence",
576
+ windowsFinalizeScript: "release:finalize:win",
577
+ macosFinalizeScript: "release:finalize:mac",
578
+ installedQualificationScript: "release:qualify:installed",
579
+ publishScript: "release:publish:qualified",
580
+ qualificationRunnerVariable: "QUALIFICATION_RUNNER_LABEL",
581
+ publishSecrets: ["CLOUDFLARE_API_TOKEN"],
582
+ },
583
+ },
584
+ matrix: { os: ["ubuntu-24.04", "windows-2025", "macos-15"], node: ["22.23.2"] },
585
+ templateVersion: "1.4.0",
586
+ };
587
+ const content = renderTemplate(
588
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
589
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
590
+ );
591
+ const installedQualificationJob = content.slice(
592
+ content.search(/^ {2}installed-qualification:\n {4}needs:/m),
593
+ content.search(/^ {2}publish:\n {4}needs:/m),
594
+ );
595
+
596
+ // Point 1: installed-qualification wraps itself in stage-summary
597
+ // init/finalize like candidate/windows-sign/macos-sign, with the correct
598
+ // authoritative stage identifier, and finalize runs unconditionally.
599
+ assert.match(installedQualificationJob, /name: Initialize installed-qualification stage summary\n\s+run: pnpm run release:stage-summary\n\s+env:\n\s+RIGHT_GIT_STAGE_ACTION: init/);
600
+ assert.match(installedQualificationJob, /RIGHT_GIT_STAGE: installed-qualification/);
601
+ assert.match(installedQualificationJob, /name: Finalize installed-qualification stage summary\n\s+if: \$\{\{ always\(\) \}\}\n\s+run: pnpm run release:stage-summary\n\s+env:\n\s+RIGHT_GIT_STAGE_ACTION: finalize/);
602
+ assert.equal((installedQualificationJob.match(/RIGHT_GIT_STAGE: installed-qualification/g) ?? []).length, 2, "both init and finalize must carry the installed-qualification stage id");
603
+ assert.match(installedQualificationJob, /name: Upload installed-qualification stage summary\n\s+if: \$\{\{ always\(\) \}\}/);
604
+
605
+ const publishJob = content.slice(content.search(/^ {2}publish:\n {4}needs:/m));
606
+
607
+ // Point 2: publish downloads the complete same-run evidence set — both
608
+ // candidate legs (windows + macos) in distinct subdirectories, plus
609
+ // windows-sign, macos-sign, and installed-qualification summaries.
610
+ assert.match(publishJob, /Download same-run candidate \(Windows\) stage summary[\s\S]*?path: \$\{\{ runner\.temp \}\}\/right-git-release\/stage-summaries\/candidate-windows/);
611
+ assert.match(publishJob, /Download same-run candidate \(macOS\) stage summary[\s\S]*?path: \$\{\{ runner\.temp \}\}\/right-git-release\/stage-summaries\/candidate-macos/);
612
+ assert.match(publishJob, /Download same-run Windows signing stage summary[\s\S]*?path: \$\{\{ runner\.temp \}\}\/right-git-release\/stage-summaries\/windows-sign/);
613
+ assert.match(publishJob, /Download same-run macOS signing stage summary[\s\S]*?path: \$\{\{ runner\.temp \}\}\/right-git-release\/stage-summaries\/macos-sign/);
614
+ assert.match(publishJob, /Download same-run installed-qualification stage summary[\s\S]*?path: \$\{\{ runner\.temp \}\}\/right-git-release\/stage-summaries\/installed-qualification/);
615
+ // Distinct subdirectories: no two downloads share a path.
616
+ const downloadPaths = [...publishJob.matchAll(/path: (\$\{\{ runner\.temp \}\}\/right-git-release\/stage-summaries\/\S+)/g)].map((m) => m[1]);
617
+ assert.equal(downloadPaths.length, 5);
618
+ assert.equal(new Set(downloadPaths).size, 5, "every stage-summary download must use a distinct subdirectory");
619
+
620
+ // Point 3: both the evidence-verification step and the publish step carry
621
+ // the full run-identity contract (RIGHT_GIT_STAGE_SUMMARY_ROOT, run id,
622
+ // run attempt) alongside version/source_revision — evidence is bound to
623
+ // THIS run, not merely reusable across runs of the same version+SHA.
624
+ const verifyStep = publishJob.slice(publishJob.indexOf("Verify aggregated release evidence"), publishJob.indexOf("Publish qualified signed release"));
625
+ assert.match(verifyStep, /RIGHT_GIT_STAGE_SUMMARY_ROOT: \$\{\{ runner\.temp \}\}\/right-git-release\/stage-summaries/);
626
+ assert.match(verifyStep, /RIGHT_GIT_RUN_ID: \$\{\{ github\.run_id \}\}/);
627
+ assert.match(verifyStep, /RIGHT_GIT_RUN_ATTEMPT: \$\{\{ github\.run_attempt \}\}/);
628
+ const publishStep = publishJob.slice(publishJob.indexOf("Publish qualified signed release"));
629
+ assert.match(publishStep, /RIGHT_GIT_STAGE_SUMMARY_ROOT: \$\{\{ runner\.temp \}\}\/right-git-release\/stage-summaries/);
630
+ assert.match(publishStep, /RIGHT_GIT_RUN_ID: \$\{\{ github\.run_id \}\}/);
631
+ assert.match(publishStep, /RIGHT_GIT_RUN_ATTEMPT: \$\{\{ github\.run_attempt \}\}/);
632
+
633
+ assert.doesNotMatch(content, /run: (?:pnpm|npm|yarn) run undefined\b/);
634
+ assert.doesNotMatch(content, /\$\{\{\s*github\.output\s*\}\}/);
635
+ });
636
+
637
+ test("render determinism: same manifest renders byte-identical output every time", () => {
638
+ const first = renderAllLanes(FULL_MANIFEST, "/repos/widgets");
639
+ const second = renderAllLanes(FULL_MANIFEST, "/repos/widgets");
640
+ for (const lane of KNOWN_LANES) {
641
+ assert.equal(first[lane], second[lane], `lane ${lane} was not deterministic`);
642
+ }
643
+ });
644
+
645
+ test("rendered workflows never request pnpm or yarn setup-node caching before package-manager activation", () => {
646
+ for (const packageManager of ["pnpm@11.24.0", "yarn@4.6.0"]) {
647
+ const rendered = renderAllLanes({ ...FULL_MANIFEST, packageManager }, "/repos/widgets");
648
+ for (const [lane, content] of Object.entries(rendered)) {
649
+ assert.doesNotMatch(
650
+ content,
651
+ /^\s*cache:\s*(?:pnpm|yarn)\s*$/m,
652
+ `lane ${lane} must not ask actions/setup-node for ${packageManager.split("@")[0]} caching before corepack activation`,
653
+ );
654
+ }
655
+ }
656
+ });
657
+
658
+ test("rendered workflows bootstrap each declared package manager safely", () => {
659
+ const pnpm = renderAllLanes({ ...FULL_MANIFEST, packageManager: "pnpm@11.24.0" }, "/repos/widgets");
660
+ for (const content of Object.values(pnpm)) {
661
+ assert.match(content, /uses: pnpm\/action-setup@[a-f0-9]{40}/);
662
+ assert.match(content, /version: 11\.24\.0/);
663
+ assert.doesNotMatch(content, /corepack enable/);
664
+ }
665
+
666
+ const npm = renderAllLanes({ ...FULL_MANIFEST, packageManager: "npm@11.0.0" }, "/repos/widgets");
667
+ for (const content of Object.values(npm)) {
668
+ assert.doesNotMatch(content, /pnpm\/action-setup|corepack enable/);
669
+ }
670
+
671
+ const yarn = renderAllLanes({ ...FULL_MANIFEST, packageManager: "yarn@4.6.0" }, "/repos/widgets");
672
+ for (const content of Object.values(yarn)) {
673
+ assert.match(content, /corepack prepare yarn@4\.6\.0 --activate/);
674
+ assert.doesNotMatch(content, /pnpm\/action-setup/);
675
+ }
676
+ });
677
+
678
+ // F5 fix: a job-level `if: !private` on the real work job means GitHub
679
+ // SKIPS that job entirely for a private repo — the nested "refuse" step
680
+ // inside it is then unreachable and never runs, so nothing fails and the
681
+ // workflow can read as "nothing to do" rather than a loud failure. The
682
+ // fix moves the refusal into its own `private-repo-guard` job that carries
683
+ // NO job-level `if` (so it always executes); its single step's own `if`
684
+ // fires only when private and exits 1, which fails that job outright. Real
685
+ // work jobs `needs: [private-repo-guard]` instead of gating themselves, so
686
+ // a failed (not skipped) guard blocks them via GitHub's default
687
+ // needs-implies-success semantics. This test asserts the corrected shape;
688
+ // see guard-coverage.test.mjs for the full job-graph reachability proof.
689
+ test("guard injection: every rendered workflow has an unconditional guard job that refuses a private repository", () => {
690
+ const rendered = renderAllLanes(FULL_MANIFEST, "/repos/widgets");
691
+ for (const lane of KNOWN_LANES) {
692
+ const content = rendered[lane];
693
+ assert.ok(content.startsWith(MANAGED_MARKER), `lane ${lane} is missing the managed marker`);
694
+ assert.match(content, /^ {2}private-repo-guard:\s*$/m, `lane ${lane} missing the private-repo-guard job`);
695
+ assert.match(content, /Refuse private repository/, `lane ${lane} missing the fail-fast guard step`);
696
+ assert.match(content, /if: \$\{\{ github\.event\.repository\.private \}\}/, `lane ${lane} guard step missing its own if condition`);
697
+ assert.match(content, /exit 1/, `lane ${lane} guard step must exit non-zero`);
698
+ // No job anywhere in the file may gate itself on the OLD (skip, not
699
+ // fail) pattern — that is exactly the bug being fixed.
700
+ assert.doesNotMatch(
701
+ content,
702
+ /if: \$\{\{ !github\.event\.repository\.private \}\}/,
703
+ `lane ${lane} still gates a job with the skip-not-fail 'if: !private' pattern`,
704
+ );
705
+ }
706
+ });
707
+
708
+ // F15 regression: the old template shipped HOMEBREW_TAP_TOKEN and
709
+ // WINGET_CREATE_GITHUB_TOKEN with no documentation of what they are or why
710
+ // they don't violate I2, while the surrounding design text describes a
711
+ // strict credential boundary ("no signing credential ... beyond OIDC-to-npm"
712
+ // / "never signs in CI") without acknowledging these two long-lived PATs.
713
+ // Fails against the pre-fix header comment (no such text existed) and
714
+ // passes once the template documents the boundary honestly.
715
+ test("F15: publish-package-managers documents its credential boundary honestly", () => {
716
+ const rendered = renderAllLanes(FULL_MANIFEST, "/repos/widgets")["publish-package-managers"];
717
+ assert.match(rendered, /CREDENTIAL BOUNDARY/, "template must call out its credential boundary explicitly");
718
+ assert.match(rendered, /HOMEBREW_TAP_TOKEN:[\s\S]*?PAT/i, "must document what HOMEBREW_TAP_TOKEN is");
719
+ assert.match(rendered, /WINGET_CREATE_GITHUB_TOKEN:[\s\S]*?PAT/i, "must document what WINGET_CREATE_GITHUB_TOKEN is");
720
+ assert.match(rendered, /not signing credentials/i, "must state that these tokens are not signing material (I2 is about signing credentials specifically)");
721
+ assert.match(rendered, /opt-in/i, "must state the lane is opt-in, not rendered by default");
722
+ });
723
+
724
+ // F15 non-regression: the two PAT-style secrets must never leak into any
725
+ // OTHER lane's rendered output — they belong solely to the explicitly
726
+ // opted-in publish-package-managers lane.
727
+ test("F15: HOMEBREW_TAP_TOKEN and WINGET_CREATE_GITHUB_TOKEN never appear outside the publish-package-managers lane", () => {
728
+ const otherLanes = KNOWN_LANES.filter((lane) => lane !== "publish-package-managers");
729
+ const rendered = renderAllLanes({ ...FULL_MANIFEST, lanes: otherLanes }, "/repos/widgets");
730
+ for (const lane of otherLanes) {
731
+ assert.doesNotMatch(rendered[lane], /HOMEBREW_TAP_TOKEN|WINGET_CREATE_GITHUB_TOKEN/, `lane ${lane} must never reference the package-manager PAT secrets`);
732
+ }
733
+ });
734
+
735
+ test("renderTemplate throws on an unresolved placeholder rather than emitting it", () => {
736
+ assert.throws(() => renderTemplate("value: ${MISSING_TOKEN}\n", {}), /no value provided/);
737
+ });
738
+
739
+ test("renderTemplate never substitutes inside GitHub Actions double-brace expressions", () => {
740
+ const out = renderTemplate("run: echo ${{ github.repository }}\nname: ${TEMPLATE_VERSION}\n", { TEMPLATE_VERSION: "1.0.0" });
741
+ assert.equal(out, "run: echo ${{ github.repository }}\nname: 1.0.0\n");
742
+ });
743
+
744
+ test("renderTemplate normalizes an empty final release-chain fragment to one newline", () => {
745
+ const out = renderTemplate("jobs:\n${RELEASE_CHAIN_JOBS}\n", { RELEASE_CHAIN_JOBS: "" });
746
+ assert.equal(out, "jobs:\n");
747
+ assert.equal((out.match(/\n/g) ?? []).length, 1);
748
+ });
749
+
750
+ // Tag-last has no tag to check out, so every stage checks out one exact admitted
751
+ // commit SHA and HEAD is always detached. @rightkit/release only exempts a
752
+ // detached HEAD when it can prove the commit is reachable from the dispatched
753
+ // remote branch — and proving reachability needs history plus the
754
+ // remote-tracking ref. A default shallow checkout has neither, so the signing,
755
+ // qualification, and publish jobs would be refused. Every job that checks out an
756
+ // admitted revision must therefore ask for full history.
757
+ test("every job checking out an admitted revision fetches full history", () => {
758
+ const manifest = {
759
+ ...FULL_MANIFEST,
760
+ lanes: ["ci", "release-candidate"],
761
+ profile: "rust-hybrid",
762
+ gate: { path: "scripts/gate.sh" },
763
+ candidate: {
764
+ buildScript: "ci:candidate",
765
+ checkScript: "ci:candidate-check",
766
+ admissionScript: "release:admission",
767
+ stageSummaryScript: "release:stage-summary",
768
+ artifactRoot: "widgets-unsigned",
769
+ os: ["windows-2025", "macos-15"],
770
+ signWindows: true,
771
+ signMacos: true,
772
+ releaseChain: {
773
+ evidenceVerificationScript: "release:verify:evidence",
774
+ windowsFinalizeScript: "release:finalize:win",
775
+ macosFinalizeScript: "release:finalize:mac",
776
+ installedQualificationScript: "release:qualify:installed",
777
+ publishScript: "release:publish:qualified",
778
+ qualificationRunnerVariable: "QUALIFICATION_RUNNER_LABEL",
779
+ publishSecrets: ["CLOUDFLARE_API_TOKEN"],
780
+ },
781
+ },
782
+ matrix: { os: ["ubuntu-24.04", "windows-2025", "macos-15"], node: ["22.23.2"] },
783
+ templateVersion: "1.9.0",
784
+ };
785
+ const content = renderTemplate(
786
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
787
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
788
+ );
789
+ const checkouts = content
790
+ .split(/^ {6}- uses: actions\/checkout@/m)
791
+ .slice(1)
792
+ .map((step) => step.split(/^ {6}- /m)[0]);
793
+ assert.ok(checkouts.length >= 6, `expected every stage to check out; found ${checkouts.length}`);
794
+ for (const step of checkouts) {
795
+ if (!/ref: \$\{\{ (needs\.admission\.outputs\.source_revision|inputs\.source_revision) \}\}/.test(step)) continue;
796
+ assert.match(step, /fetch-depth: 0/, `a checkout of an admitted revision must fetch full history:\n${step}`);
797
+ }
798
+ // The four downstream stages specifically — these were the ones shipping shallow.
799
+ for (const job of ["windows-sign", "macos-sign", "installed-qualification", "publish"]) {
800
+ const body = content.split(new RegExp(`^ ${job}:$`, "m"))[1] ?? "";
801
+ const checkout = body.split(/^ {6}- uses: actions\/checkout@/m)[1]?.split(/^ {6}- /m)[0] ?? "";
802
+ assert.match(checkout, /fetch-depth: 0/, `${job} must check out with full history`);
803
+ }
804
+ });
805
+
806
+ // Rule 3 (release workflows have a dry run): a boolean dry_run input, runnable
807
+ // from a branch, must thread through admission so packaging/signing/qualification
808
+ // run while publication is skipped and artifacts carry a dry-run suffix.
809
+ test("release-candidate template exposes a dry_run input threaded through admission", () => {
810
+ const manifest = {
811
+ ...FULL_MANIFEST,
812
+ lanes: ["ci", "release-candidate"],
813
+ profile: "rust-hybrid",
814
+ gate: { path: "scripts/gate.sh" },
815
+ candidate: {
816
+ buildScript: "ci:candidate",
817
+ checkScript: "ci:candidate-check",
818
+ admissionScript: "release:admission",
819
+ stageSummaryScript: "release:stage-summary",
820
+ artifactRoot: "widgets-unsigned",
821
+ os: ["windows-2025", "macos-15"],
822
+ signWindows: true,
823
+ signMacos: true,
824
+ },
825
+ matrix: { os: ["ubuntu-24.04", "windows-2025", "macos-15"], node: ["22.23.2"] },
826
+ templateVersion: "1.9.0",
827
+ };
828
+ const content = renderTemplate(
829
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
830
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
831
+ );
832
+ assert.match(content, /^ dry_run:\n description: .*\n required: false\n type: boolean\n default: false$/m);
833
+ assert.match(content, /dry_run: \$\{\{ steps\.admit\.outputs\.dry_run \}\}/);
834
+ assert.match(content, /artifact_suffix: \$\{\{ steps\.admit\.outputs\.artifact_suffix \}\}/);
835
+ assert.match(content, /RIGHT_GIT_DRY_RUN: \$\{\{ inputs\.dry_run \}\}/);
836
+ // The envelope only pins refs/heads/main and first-attempt for a real dispatch.
837
+ assert.match(content, /if \[\[ "\$\{\{ inputs\.dry_run \}\}" == "true" \]\]; then\n \[\[ "\$GITHUB_REF" == refs\/heads\/\* \]\]/);
838
+ });
839
+
840
+ // Correction 11: Windows signing, macOS signing, installed qualification and
841
+ // publication all shared one `release` environment, so no signing/publication
842
+ // grant separation existed. The split is opt-in per product because the secrets
843
+ // live in the existing environment until an operator moves them.
844
+ function environmentManifest(environments) {
845
+ const manifest = {
846
+ schemaVersion: 1,
847
+ compile: "github-actions-only",
848
+ lanes: ["ci", "release-candidate"],
849
+ packageManager: "pnpm@11.24.0",
850
+ profile: "rust-hybrid",
851
+ gate: { path: "scripts/gate.sh" },
852
+ candidate: {
853
+ buildScript: "ci:candidate",
854
+ checkScript: "ci:candidate-check",
855
+ admissionScript: "release:admit",
856
+ stageSummaryScript: "release:stage-summary",
857
+ artifactRoot: "widgets-unsigned",
858
+ os: ["windows-2025", "macos-15"],
859
+ targets: [
860
+ { os: "windows-2025", platform: "windows", architecture: "x86_64" },
861
+ { os: "macos-15", platform: "macos", architecture: "arm64" },
862
+ ],
863
+ signWindows: true,
864
+ signMacos: true,
865
+ releaseChain: {
866
+ windowsFinalizeScript: "release:finalize-windows",
867
+ macosFinalizeScript: "release:finalize-macos",
868
+ installedQualificationScript: "release:qualify-installed",
869
+ publishScript: "release:publish-qualified",
870
+ qualificationRunnerVariable: "WIDGETS_QUALIFICATION_RUNNER",
871
+ },
872
+ },
873
+ matrix: { os: ["ubuntu-24.04", "windows-2025"], node: ["22.23.2"] },
874
+ templateVersion: "1.8.0",
875
+ };
876
+ if (environments) manifest.candidate.releaseChain.environments = environments;
877
+ return manifest;
878
+ }
879
+
880
+ function renderRelease(manifest) {
881
+ return renderTemplate(
882
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"),
883
+ buildRenderContext(manifest, "/repos/widgets", "release-candidate"),
884
+ );
885
+ }
886
+
887
+ test("release environments default to the single release environment", () => {
888
+ const content = renderRelease(environmentManifest(null));
889
+ assert.ok((content.match(/environment: release$/gm) ?? []).length >= 2);
890
+ assert.doesNotMatch(content, /environment: signing-authorized/);
891
+ });
892
+
893
+ test("signing and publication split into distinct protected environments", () => {
894
+ const content = renderRelease(environmentManifest({
895
+ signing: "signing-authorized",
896
+ publication: "release-authorized",
897
+ qualification: "qualification",
898
+ }));
899
+ assert.equal((content.match(/environment: signing-authorized$/gm) ?? []).length, 2);
900
+ assert.equal((content.match(/environment: release-authorized$/gm) ?? []).length, 1);
901
+ // A job that may sign must never also be the job that publishes.
902
+ assert.doesNotMatch(content, /environment: release$/m);
903
+ });
904
+
905
+ test("an unsafe or unknown release environment is rejected", () => {
906
+ assert.equal(validateManifest(environmentManifest({ signing: "bad name!" })).valid, false);
907
+ assert.equal(validateManifest(environmentManifest({ promotion: "x" })).valid, false);
908
+ });
909
+
910
+ test("ci.yml ownership check cannot be removed by deleting optional repo metadata", () => {
911
+ const manifest = { ...structuredClone(FULL_MANIFEST), ownership: { roots: [".", "engine"] } };
912
+ const template = fs.readFileSync(path.join(templatesDir, "ci.yml"), "utf8");
913
+ const withStep = renderTemplate(template, buildRenderContext(manifest, "/repos/coderight"));
914
+ assert.match(withStep, /RightKit ownership \(protected registry roots\)/);
915
+ const without = renderTemplate(template, buildRenderContext(structuredClone(FULL_MANIFEST), "/repos/widgets"));
916
+ assert.match(without, /RightKit ownership \(protected registry roots\)/);
917
+ });
918
+
919
+ test("rust-hybrid ci uploads QA evidence after the gate only when qaEvidencePath is set", () => {
920
+ const base = { ...FULL_MANIFEST, lanes: ["ci"], profile: "rust-hybrid", gate: { path: "scripts/gate.sh" }, templateVersion: "1.1.0" };
921
+ const template = fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/ci.yml"), "utf8");
922
+
923
+ const unset = renderTemplate(template, buildRenderContext(structuredClone(base), "/repos/widgets"));
924
+ assert.doesNotMatch(unset, /upload-artifact|QA evidence|runner\.temp/);
925
+ assert.match(unset, /CARGO_PROFILE_TEST_DEBUG: "0"\n - name: Record last green commit marker[\s\S]*github\.run_attempt \}\}\n$/);
926
+
927
+ const set = renderTemplate(template, buildRenderContext({ ...structuredClone(base), qaEvidencePath: "pulse-hub-qa" }, "/repos/widgets"));
928
+ assert.ok(set.indexOf("bash ./scripts/gate.sh") < set.indexOf("- name: Upload QA evidence"), "upload must follow the gate step");
929
+ assert.match(
930
+ set,
931
+ / - name: Upload QA evidence\n if: always\(\)\n uses: actions\/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4\n with:\n name: qa-evidence-\$\{\{ matrix\.os \|\| runner\.os \}\}-\$\{\{ github\.run_attempt \}\}\n path: \$\{\{ runner\.temp \}\}\/pulse-hub-qa\n retention-days: 7\n if-no-files-found: ignore\n$/,
932
+ );
933
+ // The upload step is the only difference between the two renders.
934
+ assert.equal(set.replace(/ - name: Upload QA evidence[\s\S]*$/, ""), unset);
935
+
936
+ const custom = renderTemplate(template, buildRenderContext({ ...structuredClone(base), qaEvidencePath: "pulse-hub-qa", qaEvidenceRetentionDays: 30 }, "/repos/widgets"));
937
+ assert.match(custom, /retention-days: 30\n/);
938
+ });
939
+
940
+ const INCREMENTAL_BASE = {
941
+ ...FULL_MANIFEST,
942
+ lanes: ["ci"],
943
+ profile: "rust-hybrid",
944
+ gate: { path: "scripts/gate.sh" },
945
+ matrix: { os: ["xcode-27", "windows-2025"], node: ["26.8.1"] },
946
+ ciAllOs: true,
947
+ };
948
+ const renderRustCi = (manifest) => renderTemplate(
949
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/ci.yml"), "utf8"),
950
+ buildRenderContext(structuredClone(manifest), "/repos/pulse"),
951
+ );
952
+
953
+ test("ciIncremental unset or false renders the legacy cache settings; true opts in", () => {
954
+ const unset = renderRustCi(INCREMENTAL_BASE);
955
+ assert.match(unset, /cache-workspace-crates: false/);
956
+ assert.match(unset, /CARGO_INCREMENTAL: "0"/);
957
+ assert.doesNotMatch(unset, /DerivedData|actions\/cache@|dev-mac|dev-windows/);
958
+ assert.equal(renderRustCi({ ...INCREMENTAL_BASE, ciIncremental: false }), unset);
959
+
960
+ const on = renderRustCi({ ...INCREMENTAL_BASE, ciIncremental: true });
961
+ assert.match(on, /cache-workspace-crates: true/);
962
+ assert.match(on, /CARGO_INCREMENTAL: "1"/);
963
+ assert.match(on, /RUSTC_WRAPPER: ""\n/, "sccache refuses incremental builds");
964
+ assert.doesNotMatch(on, /RUSTC_WRAPPER: \$\{\{ steps\.rust-changes/);
965
+ assert.match(on, /Cache Xcode DerivedData\n if: \$\{\{ runner\.os == 'macOS' \}\}\n uses: actions\/cache@[0-9a-f]{40} # v4\.2\.4/);
966
+ assert.match(on, /hashFiles\('\*\*\/Cargo\.lock', '\*\*\/Package\.resolved'/);
967
+ });
968
+
969
+ const DEV_MANIFEST = {
970
+ ...INCREMENTAL_BASE,
971
+ devArtifact: {
972
+ mac: "sign",
973
+ windows: "unsigned",
974
+ retentionDays: 5,
975
+ macAppPath: "target/release/bundle/macos/Pulse.app",
976
+ windowsGlob: "target/release/*.exe",
977
+ },
978
+ };
979
+
980
+ test("devArtifact renders push-to-default-branch dev steps and a signing job; unset adds nothing", () => {
981
+ const out = renderRustCi(DEV_MANIFEST);
982
+ assert.match(out, /name: dev-windows-\$\{\{ github\.sha \}\}\n path: target\/release\/\*\.exe\n retention-days: 5/);
983
+ assert.match(out, /DEV_APP_PATH: "target\/release\/bundle\/macos\/Pulse\.app"/);
984
+ assert.match(out, /dev-mac-sign:\n[\s\S]*needs: \[ci\]\n if: \$\{\{ github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch \}\}\n environment: release\n runs-on: xcode-27/);
985
+ assert.match(out, /codesign --force --deep --strict --options runtime --timestamp --sign "\$APPLE_DEVELOPER_ID"/);
986
+ assert.match(out, /name: dev-mac-\$\{\{ github\.sha \}\}/);
987
+ assert.doesNotMatch(out, /notarytool|APPLE_API_KEY|stapler/);
988
+ // Signing material never reaches the PR-reachable ci job.
989
+ assert.doesNotMatch(out.split(" dev-mac-sign:")[0], /secrets\./);
990
+ // mac/windows only render the legs they declare.
991
+ const winOnly = renderRustCi({ ...DEV_MANIFEST, devArtifact: { windows: "unsigned", windowsGlob: "dist/*.exe" } });
992
+ assert.doesNotMatch(winOnly, /dev-mac-sign|dev-unsigned-mac/);
993
+ assert.match(winOnly, /retention-days: 7/);
994
+ assert.equal(renderRustCi({ ...INCREMENTAL_BASE, devArtifact: undefined }), renderRustCi(INCREMENTAL_BASE));
995
+ });
996
+
997
+ test("devArtifact mac 'unsigned' uploads the bare app with no signing job, and dispatch opens unsigned legs only", () => {
998
+ const unsigned = { ...DEV_MANIFEST, devArtifact: { ...DEV_MANIFEST.devArtifact, mac: "unsigned" } };
999
+ const out = renderRustCi(unsigned);
1000
+ assert.match(out, /DEV_APP_PATH: "target\/release\/bundle\/macos\/Pulse\.app"/);
1001
+ assert.match(out, /name: dev-mac-unsigned-\$\{\{ github\.sha \}\}\n path: \$\{\{ runner\.temp \}\}\/dev-unsigned\/app\.zip\n retention-days: 5/);
1002
+ assert.doesNotMatch(out, /dev-mac-sign|dev-unsigned-mac-|secrets\.|environment:/);
1003
+ assert.doesNotMatch(out, /workflow_dispatch/);
1004
+ assert.equal(out, renderRustCi({ ...unsigned, devArtifact: { ...unsigned.devArtifact, dispatch: undefined } }));
1005
+
1006
+ const dispatch = renderRustCi({ ...unsigned, devArtifact: { ...unsigned.devArtifact, dispatch: true } });
1007
+ assert.match(dispatch, /^on:\n pull_request:\n push:\n branches: \[main\]\n workflow_dispatch:\npermissions:/m);
1008
+ const cond = "\\(github\\.event_name == 'push' && github\\.ref_name == github\\.event\\.repository\\.default_branch \\|\\| github\\.event_name == 'workflow_dispatch'\\)";
1009
+ assert.match(dispatch, new RegExp(`if: \\$\\{\\{ ${cond} && runner\\.os == 'Windows' \\}\\}`));
1010
+ assert.match(dispatch, new RegExp(`if: \\$\\{\\{ ${cond} && runner\\.os == 'macOS' \\}\\}`));
1011
+
1012
+ // Dispatch beside a signed mac leg: the signing job and its package step stay push-only.
1013
+ const signedDispatch = renderRustCi({ ...DEV_MANIFEST, devArtifact: { ...DEV_MANIFEST.devArtifact, dispatch: true } });
1014
+ assert.match(signedDispatch, /workflow_dispatch:/);
1015
+ assert.match(signedDispatch, /Package unsigned dev app for signing \(macOS\)|Package unsigned dev app \(macOS\)\n if: \$\{\{ github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch && runner\.os == 'macOS' \}\}/);
1016
+ assert.match(signedDispatch, /dev-mac-sign:\n[\s\S]*?if: \$\{\{ github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch \}\}\n environment: release/);
1017
+ assert.doesNotMatch(signedDispatch.split(" dev-mac-sign:")[1], /workflow_dispatch/);
1018
+ });
1019
+
1020
+ test("regenerate lane is dispatch-only, pushes only to right-git/regenerate-<run>, opens a PR, and reaches no secret", () => {
1021
+ for (const profile of ["rust-hybrid", "node"]) {
1022
+ const manifest = profile === "rust-hybrid"
1023
+ ? { ...INCREMENTAL_BASE, lanes: ["ci", "regenerate"], regenerate: { script: "regenerate" } }
1024
+ : { ...FULL_MANIFEST, lanes: ["ci", "regenerate"], regenerate: { script: "regenerate" } };
1025
+ assert.equal(validateManifest(manifest).valid, true, JSON.stringify(validateManifest(manifest).errors));
1026
+ const templatePath = profile === "rust-hybrid" ? "profiles/rust-hybrid/regenerate.yml" : "regenerate.yml";
1027
+ const out = renderTemplate(fs.readFileSync(path.join(templatesDir, templatePath), "utf8"), buildRenderContext(manifest, "/repos/widgets", "regenerate"));
1028
+ assert.match(out, /^on:\n workflow_dispatch:\npermissions:\n contents: read\n/m);
1029
+ assert.match(out, /regenerate:\n needs: \[private-repo-guard\]\n if: \$\{\{ github\.event_name == 'workflow_dispatch' \}\}\n/);
1030
+ assert.match(out, / permissions:\n contents: write\n pull-requests: write\n/);
1031
+ assert.match(out, /run: pnpm run regenerate\n/);
1032
+ assert.match(out, /branch="right-git\/regenerate-\$\{\{ github\.run_id \}\}-\$\{\{ github\.run_attempt \}\}"\n/);
1033
+ assert.match(out, /git push origin "HEAD:refs\/heads\/\$branch"\n/);
1034
+ assert.match(out, /gh pr create --base "\$RIGHT_GIT_DEFAULT_BRANCH" --head "\$branch"/);
1035
+ assert.doesNotMatch(out, /secrets\.|HEAD:main|HEAD:refs\/heads\/main|pull_request:|push:\n/);
1036
+ assert.equal((out.match(/git push/g) ?? []).length, 1);
1037
+ if (profile === "rust-hybrid") {
1038
+ assert.match(out, /run: bash \.\/scripts\/gate\.sh\n/);
1039
+ assert.match(out, /dtolnay\/rust-toolchain@/);
1040
+ } else {
1041
+ assert.match(out, /run: pnpm run test\n/);
1042
+ assert.doesNotMatch(out, /rust-toolchain/);
1043
+ }
1044
+ }
1045
+ assert.equal(validateManifest({ ...FULL_MANIFEST, lanes: ["ci", "regenerate"], regenerate: undefined }).valid, false, "lane needs regenerate.script");
1046
+ assert.equal(validateManifest({ ...FULL_MANIFEST, lanes: ["ci"], regenerate: { script: "x" } }).valid, false, "regenerate needs the lane");
1047
+ assert.equal(validateManifest({ ...FULL_MANIFEST, lanes: ["ci", "regenerate"], regenerate: { script: "re gen" } }).valid, false, "script name charset");
1048
+ });
1049
+
1050
+ test("devArtifact mac 'notarize' notarizes and staples inside dev-mac-sign only; 'sign' output is unchanged", () => {
1051
+ const signed = renderRustCi(DEV_MANIFEST);
1052
+ const notarized = renderRustCi({ ...DEV_MANIFEST, devArtifact: { ...DEV_MANIFEST.devArtifact, mac: "notarize" } });
1053
+ assert.doesNotMatch(signed, /notarytool|stapler|AuthKey|APPLE_API/);
1054
+ const [ciPart, jobPart] = notarized.split(" dev-mac-sign:");
1055
+ assert.doesNotMatch(ciPart, /secrets\.|notarytool/);
1056
+ assert.match(jobPart, /xcrun notarytool submit "\$zip" --key "\$RUNNER_TEMP\/AuthKey\.p8" --key-id "\$APPLE_API_KEY" --issuer "\$APPLE_API_ISSUER" --wait\n\s+xcrun stapler staple "\$app"\n\s+xcrun stapler validate "\$app"/);
1057
+ assert.match(jobPart, /APPLE_API_KEY_BASE64: \$\{\{ secrets\.APPLE_API_KEY_BASE64 \}\}/);
1058
+ assert.match(jobPart, /Upload signed and notarized dev app/);
1059
+ assert.match(jobPart, /rm -f "\$RUNNER_TEMP\/apple-signing\.p12" "\$RUNNER_TEMP\/AuthKey\.p8"/);
1060
+ assert.match(jobPart, /if: \$\{\{ github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch \}\}\n environment: release/);
1061
+ const notarizeEntitled = validateManifest({ ...DEV_MANIFEST, regenerate: undefined, devArtifact: { ...DEV_MANIFEST.devArtifact, mac: "notarize", macEntitlements: "build/pulse.entitlements" } });
1062
+ assert.equal(notarizeEntitled.valid, true, JSON.stringify(notarizeEntitled.errors));
1063
+ assert.equal(validateManifest({ ...DEV_MANIFEST, regenerate: undefined, devArtifact: { mac: "notarize" } }).valid, false, "notarize needs macAppPath");
1064
+ });
1065
+
1066
+ test("devArtifact entitlements add a checkout and --entitlements", () => {
1067
+ const out = renderRustCi({ ...DEV_MANIFEST, devArtifact: { ...DEV_MANIFEST.devArtifact, macEntitlements: "build/pulse.entitlements" } });
1068
+ assert.match(out, /--entitlements "\$GITHUB_WORKSPACE\/build\/pulse\.entitlements"/);
1069
+ assert.match(out.split(" dev-mac-sign:")[1], /actions\/checkout@/);
1070
+ });
1071
+
1072
+ test("rendered ciIncremental + devArtifact workflows pass actionlint", (t) => {
1073
+ const bin = spawnSync("actionlint", ["-version"], { encoding: "utf8" });
1074
+ if (bin.error) return t.skip("actionlint not installed");
1075
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-actionlint-"));
1076
+ try {
1077
+ fs.mkdirSync(path.join(dir, ".github", "workflows"), { recursive: true });
1078
+ fs.writeFileSync(path.join(dir, ".github", "actionlint.yaml"), "self-hosted-runner:\n labels:\n - xcode-*\n");
1079
+ const samples = {
1080
+ "ci-default.yml": INCREMENTAL_BASE,
1081
+ "ci-incremental.yml": { ...INCREMENTAL_BASE, ciIncremental: true },
1082
+ "ci-dev.yml": { ...DEV_MANIFEST, ciIncremental: true },
1083
+ "ci-dev-entitlements.yml": { ...DEV_MANIFEST, devArtifact: { ...DEV_MANIFEST.devArtifact, macEntitlements: "build/pulse.entitlements" } },
1084
+ "ci-dev-unsigned-dispatch.yml": { ...DEV_MANIFEST, devArtifact: { ...DEV_MANIFEST.devArtifact, mac: "unsigned", dispatch: true } },
1085
+ "ci-parallel-dev.yml": { ...DEV_MANIFEST, devArtifact: { ...DEV_MANIFEST.devArtifact, parallel: true, buildScript: "build:dev" } },
1086
+ "ci-parallel-unsigned-dispatch.yml": {
1087
+ ...INCREMENTAL_BASE,
1088
+ rustCache: { workspaces: ["engine"], keySuffix: "v2" },
1089
+ concurrency: { mainPushes: "queue" },
1090
+ devArtifact: { mac: "unsigned", windows: "unsigned", dispatch: true, parallel: true, buildScript: "build:dev", macAppPath: "a/B.app", windowsGlob: "dist/*.exe" },
1091
+ },
1092
+ };
1093
+ const files = [];
1094
+ for (const [name, manifest] of Object.entries(samples)) {
1095
+ const file = path.join(dir, ".github", "workflows", name);
1096
+ fs.writeFileSync(file, renderRustCi(manifest));
1097
+ files.push(file);
1098
+ }
1099
+ for (const [name, template] of [["regenerate-rust.yml", "profiles/rust-hybrid/regenerate.yml"], ["regenerate-node.yml", "regenerate.yml"]]) {
1100
+ const manifest = template.startsWith("profiles/")
1101
+ ? { ...INCREMENTAL_BASE, lanes: ["ci", "regenerate"], regenerate: { script: "regenerate" } }
1102
+ : { ...FULL_MANIFEST, lanes: ["ci", "regenerate"], regenerate: { script: "regenerate" } };
1103
+ const file = path.join(dir, ".github", "workflows", name);
1104
+ fs.writeFileSync(file, renderTemplate(fs.readFileSync(path.join(templatesDir, template), "utf8"), buildRenderContext(manifest, "/repos/widgets", "regenerate")));
1105
+ files.push(file);
1106
+ }
1107
+ const result = spawnSync("actionlint", ["-shellcheck=", "-pyflakes=", "-config-file", path.join(dir, ".github", "actionlint.yaml"), ...files], { encoding: "utf8" });
1108
+ assert.equal(result.status, 0, result.stdout + result.stderr);
1109
+ } finally {
1110
+ fs.rmSync(dir, { recursive: true, force: true });
1111
+ }
1112
+ });
1113
+
1114
+ // rustCache.keySuffix: unset renders no key (byte-identical); set renders `<lane>-<suffix>`
1115
+ // in every rust-cache step, and the dev-artifact jobs get their own key.
1116
+ const RELEASE_CANDIDATE_MANIFEST = {
1117
+ ...FULL_MANIFEST,
1118
+ lanes: ["ci", "release-candidate"],
1119
+ profile: "rust-hybrid",
1120
+ gate: { path: "scripts/gate.sh" },
1121
+ regenerate: undefined,
1122
+ candidate: {
1123
+ buildScript: "ci:candidate",
1124
+ checkScript: "ci:candidate-check",
1125
+ admissionScript: "release:admit",
1126
+ stageSummaryScript: "release:stage-summary",
1127
+ artifactRoot: "widgets-unsigned",
1128
+ os: ["macos-latest", "windows-latest"],
1129
+ },
1130
+ templateVersion: "1.2.0",
1131
+ };
1132
+ const VALID_RUST_HYBRID = { ...INCREMENTAL_BASE, regenerate: undefined };
1133
+
1134
+ test("rustCache.keySuffix: unset adds no key; set renders a lane-scoped key in every rust-cache step", () => {
1135
+ const unset = renderRustCi({ ...INCREMENTAL_BASE, rustCache: { workspaces: ["engine"] } });
1136
+ assert.doesNotMatch(unset, /add-job-id-key: false\n key: /);
1137
+ assert.equal(renderRustCi({ ...INCREMENTAL_BASE, rustCache: { workspaces: ["engine"] } }), renderRustCi({ ...INCREMENTAL_BASE, rustCache: { workspaces: ["engine"], keySuffix: undefined } }));
1138
+
1139
+ const set = renderRustCi({ ...INCREMENTAL_BASE, rustCache: { workspaces: ["engine"], keySuffix: "v2" } });
1140
+ assert.match(set, / shared-key: pulse-rust\n add-job-id-key: false\n key: ci-v2\n cache-workspace-crates: /);
1141
+ assert.equal(set.replace(" key: ci-v2\n", ""), unset, "the key line is the only difference");
1142
+
1143
+ const withDev = renderRustCi({ ...DEV_MANIFEST, rustCache: { workspaces: ["engine"], keySuffix: "v2" }, devArtifact: { ...DEV_MANIFEST.devArtifact, parallel: true, buildScript: "build:dev" } });
1144
+ assert.match(withDev, /dev-artifact-mac:[\s\S]*? key: ci-dev-artifact-mac-v2\n/);
1145
+ assert.match(withDev, /dev-artifact-windows:[\s\S]*? key: ci-dev-artifact-windows-v2\n/);
1146
+
1147
+ const lanes = [
1148
+ ["regenerate", { ...INCREMENTAL_BASE, lanes: ["ci", "regenerate"], regenerate: { script: "regenerate" }, rustCache: { workspaces: ["engine"], keySuffix: "v2" } }, "profiles/rust-hybrid/regenerate.yml"],
1149
+ ["release-candidate", { ...RELEASE_CANDIDATE_MANIFEST, rustCache: { workspaces: ["engine"], keySuffix: "v2" } }, "profiles/rust-hybrid/release-candidate.yml"],
1150
+ ];
1151
+ for (const [lane, manifest, template] of lanes) {
1152
+ const out = renderTemplate(fs.readFileSync(path.join(templatesDir, template), "utf8"), buildRenderContext(structuredClone(manifest), "/repos/pulse", lane));
1153
+ assert.match(out, new RegExp(` add-job-id-key: false\n key: ${lane}-v2\n`), lane);
1154
+ }
1155
+ const unkeyed = renderTemplate(fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/release-candidate.yml"), "utf8"), buildRenderContext(structuredClone(RELEASE_CANDIDATE_MANIFEST), "/repos/pulse", "release-candidate"));
1156
+ assert.doesNotMatch(unkeyed, /add-job-id-key: false\n key: /);
1157
+
1158
+ for (const bad of ["${{ secrets.X }}", "has space", "-leading", "semi;colon", "a".repeat(65), 7]) {
1159
+ assert.equal(validateManifest({ ...VALID_RUST_HYBRID, rustCache: { workspaces: ["engine"], keySuffix: bad } }).valid, false, String(bad));
1160
+ }
1161
+ assert.equal(validateManifest({ ...VALID_RUST_HYBRID, rustCache: { workspaces: ["engine"], keySuffix: "v2" } }).valid, true);
1162
+ assert.equal(validateManifest({ ...FULL_MANIFEST, lanes: ["ci"], rustCache: { workspaces: ["engine"], keySuffix: "v2" } }).valid, false, "rustCache stays rust-hybrid only");
1163
+ });
1164
+
1165
+ // concurrency.mainPushes: default and "cancel" keep cancel-in-progress true. "queue" cancels only
1166
+ // runs that are not default-branch pushes; PR runs keep cancelling superseded runs.
1167
+ test("concurrency.mainPushes: 'queue' stops default-branch pushes cancelling each other and leaves PR runs cancelling", () => {
1168
+ const unset = renderRustCi(INCREMENTAL_BASE);
1169
+ assert.match(unset, /^concurrency:\n group: \$\{\{ github\.workflow \}\}-\$\{\{ github\.ref \}\}\n cancel-in-progress: true\n/m);
1170
+ assert.equal(renderRustCi({ ...INCREMENTAL_BASE, concurrency: { mainPushes: "cancel" } }), unset);
1171
+ assert.equal(renderRustCi({ ...INCREMENTAL_BASE, concurrency: {} }), unset);
1172
+
1173
+ const queue = renderRustCi({ ...INCREMENTAL_BASE, concurrency: { mainPushes: "queue" } });
1174
+ assert.match(queue, /^concurrency:\n group: \$\{\{ github\.workflow \}\}-\$\{\{ github\.ref \}\}\n cancel-in-progress: \$\{\{ !\(github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch\) \}\}\n/m);
1175
+ assert.equal(queue.replace(/ cancel-in-progress: .*\n/, " cancel-in-progress: true\n"), unset, "the concurrency line is the only difference");
1176
+
1177
+ const generic = renderTemplate(fs.readFileSync(path.join(templatesDir, "ci.yml"), "utf8"), buildRenderContext({ ...FULL_MANIFEST, lanes: ["ci"], concurrency: { mainPushes: "queue" } }, "/repos/widgets", "ci"));
1178
+ assert.match(generic, / cancel-in-progress: \$\{\{ !\(github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch\) \}\}\n/);
1179
+ assert.match(renderTemplate(fs.readFileSync(path.join(templatesDir, "ci.yml"), "utf8"), buildRenderContext({ ...FULL_MANIFEST, lanes: ["ci"] }, "/repos/widgets", "ci")), / cancel-in-progress: true\n/);
1180
+
1181
+ const regenerate = renderTemplate(
1182
+ fs.readFileSync(path.join(templatesDir, "profiles/rust-hybrid/regenerate.yml"), "utf8"),
1183
+ buildRenderContext({ ...INCREMENTAL_BASE, lanes: ["ci", "regenerate"], regenerate: { script: "regenerate" }, concurrency: { mainPushes: "queue" } }, "/repos/pulse", "regenerate"),
1184
+ );
1185
+ assert.match(regenerate, / cancel-in-progress: false\n/, "the regenerate lane is never cancelled");
1186
+
1187
+ assert.equal(validateManifest({ ...VALID_RUST_HYBRID, concurrency: { mainPushes: "queue" } }).valid, true);
1188
+ assert.equal(validateManifest({ ...VALID_RUST_HYBRID, concurrency: { mainPushes: "bogus" } }).valid, false);
1189
+ assert.equal(validateManifest({ ...VALID_RUST_HYBRID, concurrency: { mainPushes: "queue", extra: true } }).valid, false);
1190
+ assert.equal(validateManifest({ ...VALID_RUST_HYBRID, concurrency: "queue" }).valid, false);
1191
+ assert.equal(validateManifest({ ...FULL_MANIFEST, lanes: ["package-smoke"], regenerate: undefined, concurrency: { mainPushes: "queue" } }).valid, false, "concurrency needs lane ci");
1192
+ });
1193
+
1194
+ // devArtifact.parallel: each platform builds and stages the dev app in its own job beside the gate.
1195
+ // The gate job renders exactly as it does without devArtifact; parallel: false is the in-gate default.
1196
+ const PARALLEL_DEV = {
1197
+ ...VALID_RUST_HYBRID,
1198
+ ciAllOs: undefined,
1199
+ devArtifact: { ...DEV_MANIFEST.devArtifact, parallel: true, buildScript: "build:dev" },
1200
+ };
1201
+
1202
+ test("devArtifact.parallel renders per-platform dev-artifact jobs beside the gate; the gate job is unchanged", () => {
1203
+ const inGate = renderRustCi(DEV_MANIFEST);
1204
+ const parallel = renderRustCi(PARALLEL_DEV);
1205
+
1206
+ const gateJobs = parallel.slice(0, parallel.indexOf("\n dev-artifact-mac:"));
1207
+ assert.equal(gateJobs, renderRustCi({ ...PARALLEL_DEV, devArtifact: undefined }), "the gate job matches a manifest with no devArtifact");
1208
+ assert.doesNotMatch(gateJobs, /Build dev app|dev-windows-|dev-mac-unsigned|dev-unsigned-mac|Package unsigned dev app|DEV_APP_PATH/);
1209
+
1210
+ const devJobs = parallel.slice(parallel.indexOf("\n dev-artifact-mac:"), parallel.indexOf("\n dev-mac-sign:"));
1211
+ assert.match(devJobs, /\n dev-artifact-mac:\n # macOS dev app[^\n]*\n[^\n]*\n needs: \[private-repo-guard\]\n if: \$\{\{ github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch \}\}\n runs-on: xcode-27\n/);
1212
+ assert.match(devJobs, /\n dev-artifact-windows:\n # Windows dev app[^\n]*\n[^\n]*\n needs: \[private-repo-guard\]\n if: \$\{\{ github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch \}\}\n runs-on: windows-2025\n/);
1213
+ assert.equal((devJobs.match(/ run: pnpm run build:dev\n/g) ?? []).length, 2, "each platform job compiles devArtifact.buildScript");
1214
+ assert.doesNotMatch(devJobs, /secrets\./, "the dev-artifact jobs never reach a secret");
1215
+ assert.match(devJobs, /name: dev-unsigned-mac-\$\{\{ github\.sha \}\}\n path: \$\{\{ runner\.temp \}\}\/dev-unsigned\/app\.zip\n retention-days: 1/);
1216
+ assert.match(devJobs, /name: dev-windows-\$\{\{ github\.sha \}\}\n path: target\/release\/\*\.exe\n retention-days: 5/);
1217
+
1218
+ assert.match(parallel, /\n dev-mac-sign:\n # Push to the default branch only[^\n]*\n[^\n]*\n needs: \[ci, dev-artifact-mac\]\n/);
1219
+ assert.match(inGate, /\n dev-mac-sign:\n[\s\S]*? needs: \[ci\]\n/, "the in-gate signing job still waits only for ci");
1220
+ assert.equal(renderRustCi({ ...DEV_MANIFEST, devArtifact: { ...DEV_MANIFEST.devArtifact, parallel: false } }), inGate, "parallel: false is the in-gate default");
1221
+ assert.doesNotMatch(inGate, /dev-artifact-mac:|dev-artifact-windows:/);
1222
+ assert.doesNotMatch(parallel.slice(0, parallel.indexOf("\n dev-artifact-mac:")), /dev-artifact/);
1223
+ });
1224
+
1225
+ test("devArtifact.parallel: unsigned legs keep manual dispatch and the signing job stays push-only", () => {
1226
+ const out = renderRustCi({
1227
+ ...VALID_RUST_HYBRID,
1228
+ devArtifact: { mac: "unsigned", windows: "unsigned", dispatch: true, parallel: true, buildScript: "build:dev", macAppPath: "a/B.app", windowsGlob: "*.exe" },
1229
+ });
1230
+ const cond = "\\(github\\.event_name == 'push' && github\\.ref_name == github\\.event\\.repository\\.default_branch \\|\\| github\\.event_name == 'workflow_dispatch'\\)";
1231
+ assert.match(out, /^on:\n pull_request:\n push:\n branches: \[main\]\n workflow_dispatch:\npermissions:/m);
1232
+ assert.match(out, new RegExp(`dev-artifact-mac:\\n[\\s\\S]*? if: \\$\\{\\{ ${cond} \\}\\}\\n runs-on: xcode-27`));
1233
+ assert.match(out, new RegExp(`dev-artifact-windows:\\n[\\s\\S]*? if: \\$\\{\\{ ${cond} \\}\\}\\n runs-on: windows-2025`));
1234
+ assert.doesNotMatch(out, /dev-mac-sign/);
1235
+ });
1236
+
1237
+ test("devArtifact.parallel validates its own runners, buildScript and flag; ciAllOs is not required", () => {
1238
+ assert.equal(validateManifest(PARALLEL_DEV).valid, true, JSON.stringify(validateManifest(PARALLEL_DEV).errors));
1239
+ assert.equal(validateManifest({ ...PARALLEL_DEV, ciAllOs: true }).valid, true);
1240
+ const dev = PARALLEL_DEV.devArtifact;
1241
+ assert.equal(validateManifest({ ...PARALLEL_DEV, devArtifact: { ...dev, buildScript: undefined } }).valid, false, "parallel needs buildScript");
1242
+ assert.equal(validateManifest({ ...PARALLEL_DEV, devArtifact: { ...dev, buildScript: "build dev" } }).valid, false, "buildScript charset");
1243
+ assert.equal(validateManifest({ ...PARALLEL_DEV, devArtifact: { ...dev, parallel: undefined } }).valid, false, "buildScript requires parallel");
1244
+ assert.equal(validateManifest({ ...PARALLEL_DEV, devArtifact: { ...dev, parallel: "yes" } }).valid, false, "parallel is a boolean");
1245
+ assert.equal(validateManifest({ ...PARALLEL_DEV, matrix: { os: ["windows-2025"], node: ["26.8.1"] } }).valid, false, "mac sign needs a macOS runner in matrix.os");
1246
+ assert.equal(validateManifest({ ...PARALLEL_DEV, matrix: { os: ["xcode-27"], node: ["26.8.1"] }, devArtifact: { mac: "unsigned", windows: "unsigned", parallel: true, buildScript: "build:dev", macAppPath: "a/B.app", windowsGlob: "*.exe" } }).valid, false, "windows unsigned needs a windows runner");
1247
+ });
1248
+
1249
+ // swift.privatePackages: read access to a private Swift package mirror from the ci job.
1250
+ // The configure step sits right before the first build or test step; the cleanup step
1251
+ // runs always, after the gate. The secret is referenced only from step env, never a run script.
1252
+ const SWIFT_ONE = [{ host: "github.com", secret: "RIGHTKIT_SWIFT_TOKEN" }];
1253
+ const NODE_CI_BASE = { schemaVersion: 1, compile: "github-actions-only", lanes: ["ci"], matrix: { os: ["ubuntu-latest"], node: ["24"] }, packageManager: "pnpm@11.24.0", templateVersion: "1.0.0" };
1254
+ const renderNodeCi = (manifest) => renderTemplate(
1255
+ fs.readFileSync(path.join(templatesDir, "ci.yml"), "utf8"),
1256
+ buildRenderContext(structuredClone(manifest), "/repos/widgets"),
1257
+ );
1258
+ const CONFIGURE_HEAD = " - name: Configure private Swift package access\n";
1259
+ const CLEANUP_HEAD = " - name: Remove private Swift package access\n";
1260
+ // The rendered run body of a step, with the 10-space YAML block indent removed.
1261
+ const stepScript = (step) => step.slice(step.indexOf(" run: |\n") + " run: |\n".length).split("\n").map((line) => line.slice(10)).join("\n");
1262
+
1263
+ test("swift.privatePackages unset renders nothing new in either ci template", () => {
1264
+ for (const [render, base] of [[renderRustCi, INCREMENTAL_BASE], [renderNodeCi, NODE_CI_BASE]]) {
1265
+ const unset = render(base);
1266
+ assert.doesNotMatch(unset, /private Swift package|\.netrc|insteadOf|RIGHT_GIT_PRIVATE_TOKEN/);
1267
+ assert.equal(render({ ...base, swift: undefined }), unset);
1268
+ }
1269
+ });
1270
+
1271
+ test("rust-hybrid ci: configure follows the toolchain and precedes the gate; cleanup runs always after it", () => {
1272
+ const out = renderRustCi({ ...INCREMENTAL_BASE, swift: { privatePackages: SWIFT_ONE } });
1273
+ const configure = out.indexOf(CONFIGURE_HEAD);
1274
+ const gate = out.indexOf(" - run: bash ./scripts/gate.sh\n");
1275
+ const cleanup = out.indexOf(CLEANUP_HEAD);
1276
+ assert.ok(out.indexOf("Swatinem/rust-cache") < configure && configure < gate && gate < cleanup, "order: toolchain, configure, gate, cleanup");
1277
+ assert.match(out.slice(cleanup), / if: \$\{\{ always\(\) \}\}\n/);
1278
+ assert.equal(out.slice(0, configure).includes("RIGHT_GIT_PRIVATE_TOKEN"), false);
1279
+ assert.equal(out.match(/\$\{\{ secrets\.RIGHTKIT_SWIFT_TOKEN \}\}/g)?.length, 2, "one env reference per step");
1280
+ assert.equal(out.match(/^ RIGHT_GIT_PRIVATE_TOKEN_0: \$\{\{ secrets\.RIGHTKIT_SWIFT_TOKEN \}\}$/gm)?.length, 2);
1281
+ assert.doesNotMatch(stepScript(out.slice(configure, gate)), /secrets\./);
1282
+ });
1283
+
1284
+ test("node ci: configure follows install and precedes the tests; cleanup is the last step", () => {
1285
+ const out = renderNodeCi({ ...NODE_CI_BASE, swift: { privatePackages: SWIFT_ONE } });
1286
+ const install = out.indexOf(" - run: pnpm install");
1287
+ const configure = out.indexOf(CONFIGURE_HEAD);
1288
+ const firstTest = out.search(/ - run: pnpm (?:run )?test\n/);
1289
+ const cleanup = out.indexOf(CLEANUP_HEAD);
1290
+ assert.ok(install > 0 && install < configure && configure < firstTest && firstTest < cleanup, "order: install, configure, tests, cleanup");
1291
+ assert.ok(out.indexOf("check-network-boundary") < cleanup);
1292
+ assert.match(out, / fi\n$/);
1293
+ });
1294
+
1295
+ test("swift.privatePackages renders one machine entry and one job-scoped rewrite per host", () => {
1296
+ const out = renderRustCi({ ...INCREMENTAL_BASE, swift: { privatePackages: [...SWIFT_ONE, { host: "git.example.com", secret: "SECOND_SWIFT_TOKEN" }] } });
1297
+ assert.ok(out.includes(`'git.example.com' "$RIGHT_GIT_PRIVATE_TOKEN_1"`));
1298
+ assert.ok(out.includes(`git config --global "url.https://x-access-token:$RIGHT_GIT_PRIVATE_TOKEN_1@git.example.com/.insteadOf" "https://git.example.com/"`));
1299
+ assert.ok(out.includes(`git config --global --remove-section "url.https://x-access-token:$RIGHT_GIT_PRIVATE_TOKEN_1@git.example.com/" || true`));
1300
+ assert.equal(out.match(/printf 'machine/g)?.length, 2);
1301
+ });
1302
+
1303
+ test("swift.privatePackages validation refuses unsafe names, hosts and duplicates, and placements it cannot serve", () => {
1304
+ const withSwift = (swift, base = VALID_RUST_HYBRID) => validateManifest({ ...base, swift }).errors;
1305
+ assert.deepEqual(validateManifest({ ...VALID_RUST_HYBRID, swift: { privatePackages: SWIFT_ONE } }).errors, []);
1306
+ assert.deepEqual(validateManifest({ ...NODE_CI_BASE, swift: { privatePackages: SWIFT_ONE } }).errors, []);
1307
+ for (const secret of ["GITHUB_TOKEN", "github_token", "1BAD", "A B", "A}}", "${{ secrets.X }}", ""]) {
1308
+ assert.ok(withSwift({ privatePackages: [{ host: "github.com", secret }] }).some((e) => /GitHub Actions secret name/.test(e)), `secret ${secret}`);
1309
+ }
1310
+ for (const host of ["github.com/evil", "-bad.example", "https://github.com", "git hub.com"]) {
1311
+ assert.ok(withSwift({ privatePackages: [{ host, secret: "A_B" }] }).some((e) => /bare host name/.test(e)), `host ${host}`);
1312
+ }
1313
+ assert.ok(withSwift({ privatePackages: [SWIFT_ONE[0], SWIFT_ONE[0]] }).some((e) => /must be unique/.test(e)));
1314
+ assert.ok(withSwift({ privatePackages: [] }).some((e) => /1 to 4/.test(e)));
1315
+ assert.ok(withSwift({ privatePackages: Array.from({ length: 5 }, (_, i) => ({ host: `h${i}.example`, secret: `S${i}` })) }).some((e) => /1 to 4/.test(e)));
1316
+ assert.ok(withSwift({ privatePackages: [{ host: "github.com", secret: "A", extra: 1 }] }).some((e) => /only host and secret/.test(e)));
1317
+ assert.ok(withSwift({ privatePackages: SWIFT_ONE, other: 1 }).some((e) => /unknown swift field: other/.test(e)));
1318
+ assert.ok(validateManifest({ ...NODE_CI_BASE, lanes: ["publish-npm"], publish: { npm: { oidc: true, provenance: true } }, swift: { privatePackages: SWIFT_ONE } }).errors.some((e) => /requires one of the lanes 'ci', 'qualification', 'release-candidate', 'regenerate'/.test(e)));
1319
+ assert.ok(validateManifest({ ...VALID_RUST_HYBRID, devArtifact: { mac: "unsigned", dispatch: true, macAppPath: "a/B.app" }, swift: { privatePackages: SWIFT_ONE } }).errors.some((e) => /cannot be combined with devArtifact\.dispatch/.test(e)));
1320
+ });
1321
+
1322
+ test("swift.privatePackages configure and cleanup scripts write, refuse and remove only the credentials they own", () => {
1323
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-swift-"));
1324
+ try {
1325
+ const home = path.join(scratch, "home");
1326
+ const runnerTemp = path.join(scratch, "runner-temp");
1327
+ fs.mkdirSync(home);
1328
+ fs.mkdirSync(runnerTemp);
1329
+ const manifest = { ...VALID_RUST_HYBRID, swift: { privatePackages: SWIFT_ONE } };
1330
+ const configure = stepScript(swiftPrivatePackagesConfigureStep(manifest));
1331
+ const cleanup = stepScript(swiftPrivatePackagesCleanupStep(manifest));
1332
+ const run = (script, token) => spawnSync("bash", ["-c", script], {
1333
+ encoding: "utf8",
1334
+ windowsHide: true,
1335
+ env: { PATH: process.env.PATH, HOME: home, XDG_CONFIG_HOME: path.join(home, ".config"), RUNNER_TEMP: runnerTemp, RIGHT_GIT_PRIVATE_TOKEN_0: token },
1336
+ });
1337
+ const netrc = path.join(home, ".netrc");
1338
+ const gitconfig = path.join(home, ".gitconfig");
1339
+
1340
+ // A missing secret fails closed before anything is written.
1341
+ assert.notEqual(run(configure, "").status, 0);
1342
+ assert.equal(fs.existsSync(netrc), false);
1343
+
1344
+ const configured = run(configure, "placeholder-value");
1345
+ assert.equal(configured.status, 0, configured.stderr);
1346
+ assert.equal(fs.readFileSync(netrc, "utf8"), "machine github.com\nlogin x-access-token\npassword placeholder-value\n");
1347
+ // NTFS has no permission bits for chmod to set; the mode is checked where the workflow runs.
1348
+ if (process.platform !== "win32") assert.equal(fs.statSync(netrc).mode & 0o777, 0o600);
1349
+ assert.match(fs.readFileSync(gitconfig, "utf8"), /\[url "https:\/\/x-access-token:placeholder-value@github\.com\/"\]\n\tinsteadOf = https:\/\/github\.com\//);
1350
+
1351
+ // A second configure refuses to replace the file it already owns.
1352
+ assert.notEqual(run(configure, "placeholder-value").status, 0);
1353
+
1354
+ const cleaned = run(cleanup, "placeholder-value");
1355
+ assert.equal(cleaned.status, 0, cleaned.stderr);
1356
+ assert.equal(fs.existsSync(netrc), false);
1357
+ assert.doesNotMatch(fs.existsSync(gitconfig) ? fs.readFileSync(gitconfig, "utf8") : "", /x-access-token/);
1358
+
1359
+ // Cleanup on a run that never configured leaves a pre-existing netrc alone.
1360
+ fs.writeFileSync(netrc, "machine other.example\nlogin a\npassword b\n", { mode: 0o600 });
1361
+ assert.equal(run(cleanup, "placeholder-value").status, 0);
1362
+ assert.equal(fs.readFileSync(netrc, "utf8"), "machine other.example\nlogin a\npassword b\n");
1363
+ } finally {
1364
+ fs.rmSync(scratch, { recursive: true, force: true });
1365
+ }
1366
+ });
1367
+
1368
+ test("rendered swift.privatePackages workflows pass actionlint", (t) => {
1369
+ const bin = spawnSync("actionlint", ["-version"], { encoding: "utf8" });
1370
+ if (bin.error) return t.skip("actionlint not installed");
1371
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-swift-actionlint-"));
1372
+ try {
1373
+ fs.mkdirSync(path.join(dir, ".github", "workflows"), { recursive: true });
1374
+ fs.writeFileSync(path.join(dir, ".github", "actionlint.yaml"), "self-hosted-runner:\n labels:\n - xcode-*\n");
1375
+ const files = [
1376
+ ["swift-rust.yml", renderRustCi({ ...INCREMENTAL_BASE, swift: { privatePackages: SWIFT_ONE } })],
1377
+ ["swift-rust-two-hosts.yml", renderRustCi({ ...INCREMENTAL_BASE, swift: { privatePackages: [...SWIFT_ONE, { host: "git.example.com", secret: "SECOND_SWIFT_TOKEN" }] } })],
1378
+ ["swift-node.yml", renderNodeCi({ ...NODE_CI_BASE, swift: { privatePackages: SWIFT_ONE } })],
1379
+ ].map(([name, text]) => {
1380
+ const file = path.join(dir, ".github", "workflows", name);
1381
+ fs.writeFileSync(file, text);
1382
+ return file;
1383
+ });
1384
+ const result = spawnSync("actionlint", ["-shellcheck=", "-pyflakes=", "-config-file", path.join(dir, ".github", "actionlint.yaml"), ...files], { encoding: "utf8" });
1385
+ assert.equal(result.status, 0, result.stdout + result.stderr);
1386
+ } finally {
1387
+ fs.rmSync(dir, { recursive: true, force: true });
1388
+ }
1389
+ });
1390
+
1391
+ // Lane fixtures for the swift.privatePackages tests: one manifest per profile/shape and the
1392
+ // template each lane renders from. SW_BASELINE pins the unset output to the 0.2.41 renders.
1393
+ const SW_NODE = {
1394
+ schemaVersion: 1,
1395
+ compile: "github-actions-only",
1396
+ lanes: ["ci", "qualification", "package-smoke", "release-candidate", "regenerate", "publish-npm", "publish-package-managers"],
1397
+ matrix: { os: ["ubuntu-latest", "macos-latest"], node: ["24"] },
1398
+ packageManager: "pnpm@11.24.0",
1399
+ publish: {
1400
+ npm: { oidc: true, provenance: true },
1401
+ homebrew: { tap: "acme/homebrew-tap", formulaName: "widgets" },
1402
+ winget: { packageIdentifier: "Acme.Widgets" },
1403
+ },
1404
+ regenerate: { script: "regenerate" },
1405
+ templateVersion: "1.0.0",
1406
+ };
1407
+ const SW_RUST = {
1408
+ schemaVersion: 1,
1409
+ compile: "github-actions-only",
1410
+ profile: "rust-hybrid",
1411
+ lanes: ["ci", "release-candidate", "regenerate"],
1412
+ gate: { path: "scripts/gate.sh" },
1413
+ matrix: { os: ["xcode-27", "windows-2025"], node: ["26.8.1"] },
1414
+ packageManager: "pnpm@11.24.0",
1415
+ regenerate: { script: "regenerate" },
1416
+ candidate: {
1417
+ buildScript: "ci:candidate",
1418
+ checkScript: "ci:candidate-check",
1419
+ admissionScript: "release:admit",
1420
+ stageSummaryScript: "release:stage-summary",
1421
+ artifactRoot: "widgets-unsigned",
1422
+ os: ["xcode-27", "windows-2025"],
1423
+ },
1424
+ devArtifact: {
1425
+ mac: "sign",
1426
+ windows: "unsigned",
1427
+ parallel: true,
1428
+ buildScript: "build:dev",
1429
+ macAppPath: "target/release/bundle/macos/Pulse.app",
1430
+ windowsGlob: "target/release/*.exe",
1431
+ },
1432
+ templateVersion: "1.2.0",
1433
+ };
1434
+ // Every signing, qualification and publish job the release chain can render.
1435
+ const SW_RUST_CHAIN = {
1436
+ ...SW_RUST,
1437
+ lanes: ["ci", "release-candidate"],
1438
+ regenerate: undefined,
1439
+ devArtifact: { ...SW_RUST.devArtifact, mac: "notarize" },
1440
+ matrix: { os: ["ubuntu-24.04", "windows-2025", "macos-15"], node: ["22.23.2"] },
1441
+ candidate: {
1442
+ buildScript: "ci:candidate",
1443
+ checkScript: "ci:candidate-check",
1444
+ admissionScript: "release:admission",
1445
+ stageSummaryScript: "release:stage-summary",
1446
+ artifactRoot: "widgets-unsigned",
1447
+ os: ["windows-2025", "macos-15"],
1448
+ signWindows: true,
1449
+ signMacos: true,
1450
+ releaseChain: {
1451
+ evidenceVerificationScript: "release:verify:evidence",
1452
+ windowsFinalizeScript: "release:finalize:win",
1453
+ macosFinalizeScript: "release:finalize:mac",
1454
+ installedQualificationScript: "release:qualify:installed",
1455
+ publishScript: "release:publish:qualified",
1456
+ qualificationRunnerVariable: "QUALIFICATION_RUNNER_LABEL",
1457
+ publishSecrets: ["CLOUDFLARE_API_TOKEN"],
1458
+ },
1459
+ },
1460
+ };
1461
+ const SW_CASES = [
1462
+ ["node/ci", SW_NODE, "ci"],
1463
+ ["node/qualification", SW_NODE, "qualification"],
1464
+ ["node/package-smoke", SW_NODE, "package-smoke"],
1465
+ ["node/release-candidate", SW_NODE, "release-candidate"],
1466
+ ["node/regenerate", SW_NODE, "regenerate"],
1467
+ ["node/publish-npm", SW_NODE, "publish-npm"],
1468
+ ["node/publish-package-managers", SW_NODE, "publish-package-managers"],
1469
+ ["rust-hybrid/ci", SW_RUST, "ci"],
1470
+ ["rust-hybrid/release-candidate", SW_RUST, "release-candidate"],
1471
+ ["rust-hybrid/regenerate", SW_RUST, "regenerate"],
1472
+ ["rust-hybrid-chain/ci", SW_RUST_CHAIN, "ci"],
1473
+ ["rust-hybrid-chain/release-candidate", SW_RUST_CHAIN, "release-candidate"],
1474
+ ];
1475
+ const swRender = (manifest, lane, swift) => {
1476
+ const clone = structuredClone(manifest);
1477
+ if (swift !== undefined) clone.swift = swift;
1478
+ const dir = clone.profile === "rust-hybrid" ? path.join(templatesDir, "profiles", "rust-hybrid") : templatesDir;
1479
+ return renderTemplate(fs.readFileSync(path.join(dir, LANE_FILENAMES[lane]), "utf8"), buildRenderContext(clone, "/repos/widgets", lane));
1480
+ };
1481
+
1482
+ const SW_BASELINE = {
1483
+ "node/ci": "4eee8dbd414921ac4bb34488c251c3b9641db2805d02989276218d4d1b73b7ad",
1484
+ "node/qualification": "730cc94fde3400079c2a4e66effed0e8957de2b75576d13f02b9398059ccc921",
1485
+ "node/package-smoke": "bc981ccb7248cc022cb8157c1fbdb7895c48f6a3fe4eeaf5a76eb5bba4206517",
1486
+ "node/release-candidate": "6ff48f01cadc95e5e92cc225432aa280a7baac46017ae30e54a165e3db2d1539",
1487
+ "node/regenerate": "82bfa3063ae0bc04ba52fecc14d562b418037716283648a887c206683a4e1c14",
1488
+ "node/publish-npm": "50882207659dfb6e0207fc0d9b33d86b7c10a2d2e3e6c65b2db05d5261982834",
1489
+ "node/publish-package-managers": "106b8d28ed76d916afe68808388cd5dc0de0ddd719b566832a6e8280410f9d7f",
1490
+ "rust-hybrid/ci": "9652939dae20655f893694e6ef59b521c1c8805817a9048f1347e128ffa5cefb",
1491
+ "rust-hybrid/release-candidate": "a0405dd2d6df8cfe2909fe8b371a068838617174e0d591b367b9dc5866400348",
1492
+ "rust-hybrid/regenerate": "14b7adfb5839df53f53bfe9599ef1358ff51d160a21b9ce1ca5d843a87156b36",
1493
+ "rust-hybrid-chain/ci": "413071a268dfa3b72a5b483173551f5e56818ed60f0cd6b15cd5a730584d8a6e",
1494
+ "rust-hybrid-chain/release-candidate": "0dc667ce2c399f87b962d31752980b87eb83b3becc9c05ca076ecdf6a0fc7b02",
1495
+ };
1496
+
1497
+ // Each lane that builds Swift renders the shared configure and cleanup steps into exactly these jobs.
1498
+ const SW_EXPECTED_JOBS = {
1499
+ "node/ci": ["test"],
1500
+ "node/qualification": ["qualification"],
1501
+ "node/package-smoke": [],
1502
+ "node/release-candidate": ["candidate"],
1503
+ "node/regenerate": ["regenerate"],
1504
+ "node/publish-npm": [],
1505
+ "node/publish-package-managers": [],
1506
+ "rust-hybrid/ci": ["ci", "dev-artifact-mac"],
1507
+ "rust-hybrid/release-candidate": ["candidate"],
1508
+ "rust-hybrid/regenerate": ["regenerate"],
1509
+ "rust-hybrid-chain/ci": ["ci", "dev-artifact-mac"],
1510
+ "rust-hybrid-chain/release-candidate": ["candidate"],
1511
+ };
1512
+ const SW_SECRET_ENV_LINE = /^ {10}RIGHT_GIT_PRIVATE_TOKEN_0: \$\{\{ secrets\.RIGHTKIT_SWIFT_TOKEN \}\}$/;
1513
+
1514
+ // jobs: { id -> text } for a rendered workflow.
1515
+ const swJobs = (workflow) => {
1516
+ const body = workflow.slice(workflow.indexOf("\njobs:\n") + "\njobs:\n".length);
1517
+ const parts = body.split(/^ ([A-Za-z0-9_-]+):$/m);
1518
+ const jobs = {};
1519
+ for (let i = 1; i < parts.length; i += 2) jobs[parts[i]] = parts[i + 1];
1520
+ return jobs;
1521
+ };
1522
+ const swStepNames = (job) => [...job.matchAll(/^ {6}- (?:name: (.+)|(uses|run): (.+))$/gm)].map((m) => m[1] ?? `${m[2]}: ${m[3]}`);
1523
+ const swSwiftJobs = (workflow) => Object.entries(swJobs(workflow)).filter(([, job]) => job.includes(CONFIGURE_HEAD)).map(([id]) => id);
1524
+ const SW_SET = { privatePackages: SWIFT_ONE };
1525
+
1526
+ test("swift.privatePackages unset: every lane's output is byte-identical to 0.2.41", () => {
1527
+ for (const [name, manifest, lane] of SW_CASES) {
1528
+ const unset = swRender(manifest, lane);
1529
+ assert.equal(crypto.createHash("sha256").update(unset).digest("hex"), SW_BASELINE[name], `${name} differs from the 0.2.41 render`);
1530
+ assert.equal(swRender({ ...manifest, swift: undefined }, lane), unset, `${name}: swift: undefined`);
1531
+ assert.doesNotMatch(unset, /private Swift package|\.netrc|insteadOf|RIGHT_GIT_PRIVATE_TOKEN/);
1532
+ }
1533
+ for (const manifest of [SW_NODE, SW_RUST, SW_RUST_CHAIN]) assert.deepEqual(validateManifest(manifest).errors, []);
1534
+ });
1535
+
1536
+ test("swift.privatePackages renders only into the jobs that build Swift; refused lanes and jobs stay byte-identical", () => {
1537
+ for (const [name, manifest, lane] of SW_CASES) {
1538
+ const out = swRender(manifest, lane, SW_SET);
1539
+ assert.deepEqual(swSwiftJobs(out), SW_EXPECTED_JOBS[name], `${name}: jobs carrying the steps`);
1540
+ if (SW_EXPECTED_JOBS[name].length === 0) {
1541
+ assert.equal(out, swRender(manifest, lane), `${name}: no placeholder, so no change`);
1542
+ }
1543
+ // The secret is named only by the two env lines per carrying job, never anywhere else.
1544
+ const refs = out.split("\n").filter((line) => line.includes("secrets.RIGHTKIT_SWIFT_TOKEN"));
1545
+ assert.equal(refs.length, SW_EXPECTED_JOBS[name].length * 2, `${name}: two env references per carrying job`);
1546
+ for (const line of refs) assert.match(line, SW_SECRET_ENV_LINE, `${name}: secret outside an env line: ${line}`);
1547
+ // Signing, qualification and publish jobs and the Windows dev job never see it.
1548
+ for (const [id, job] of Object.entries(swJobs(out))) {
1549
+ if (SW_EXPECTED_JOBS[name].includes(id)) continue;
1550
+ assert.doesNotMatch(job, /RIGHTKIT_SWIFT_TOKEN|RIGHT_GIT_PRIVATE_TOKEN|Swift package access/, `${name}/${id} must stay secret-free`);
1551
+ }
1552
+ }
1553
+ // The release chain really renders the jobs the argument above excludes.
1554
+ const chain = swJobs(swRender(SW_RUST_CHAIN, "release-candidate", SW_SET));
1555
+ for (const id of ["admission", "windows-sign", "macos-sign", "installed-qualification", "publish"]) assert.ok(id in chain, `fixture renders ${id}`);
1556
+ const chainCi = swJobs(swRender(SW_RUST_CHAIN, "ci", SW_SET));
1557
+ for (const id of ["dev-artifact-windows", "dev-mac-sign"]) assert.ok(id in chainCi, `fixture renders ${id}`);
1558
+ });
1559
+
1560
+ test("swift.privatePackages steps: position, always-run cleanup, and the secret only in env, per lane", () => {
1561
+ const stepOrder = (out, jobId) => swStepNames(swJobs(out)[jobId]);
1562
+ const ORDER = [
1563
+ // [case, job, steps in required order]
1564
+ ["node/ci", "test", ["Configure private Swift package access", "run: pnpm run test", "run: node scripts/ci/check-network-boundary.mjs", "Remove private Swift package access"]],
1565
+ ["node/qualification", "qualification", ["RightKit ownership (protected registry roots)", "Configure private Swift package access", "run: pnpm run test:all", "Remove private Swift package access"]],
1566
+ ["node/release-candidate", "candidate", ["RightKit ownership (protected registry roots)", "Configure private Swift package access", "run: node --test tests/release-candidate.test.mjs", "run: node scripts/release/build-candidate.mjs --platform current --out \"${{ runner.temp }}/widgets-rc\"", "run: node scripts/release/check-release.mjs \"${{ runner.temp }}/widgets-rc\"", "Remove private Swift package access", "uses: actions/upload-artifact@v4"]],
1567
+ ["node/regenerate", "regenerate", ["RightKit ownership (protected registry roots)", "Configure private Swift package access", "Regenerate derived artifacts", "Test the regenerated tree", "Remove private Swift package access", "Open a pull request with the regenerated files"]],
1568
+ ["rust-hybrid/ci", "ci", ["uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11", "Configure private Swift package access", "run: bash ./scripts/gate.sh", "Remove private Swift package access", "Record last green commit marker"]],
1569
+ ["rust-hybrid/ci", "dev-artifact-mac", ["uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2", "Configure private Swift package access", "Build dev app", "Remove private Swift package access", "Package unsigned dev app (macOS)", "Upload unsigned dev app for signing (macOS)"]],
1570
+ ["rust-hybrid/release-candidate", "candidate", ["Initialize candidate stage summary", "Configure private Swift package access", "Build unsigned release candidate", "Check unsigned release candidate", "Remove private Swift package access", "Finalize candidate stage summary", "Upload unsigned candidate handoff"]],
1571
+ ["rust-hybrid/regenerate", "regenerate", ["uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2", "Configure private Swift package access", "Regenerate derived artifacts", "Gate the regenerated tree", "Remove private Swift package access", "Open a pull request with the regenerated files"]],
1572
+ ];
1573
+ for (const [name, jobId, expected] of ORDER) {
1574
+ const [, manifest, lane] = SW_CASES.find(([n]) => n === name);
1575
+ const out = swRender(manifest, lane, SW_SET);
1576
+ const actual = stepOrder(out, jobId);
1577
+ let cursor = -1;
1578
+ for (const step of expected) {
1579
+ const at = actual.findIndex((candidate, index) => index > cursor && (candidate === step || candidate.startsWith(step)));
1580
+ assert.ok(at > cursor, `${name}/${jobId}: expected "${step}" after position ${cursor} in ${JSON.stringify(actual)}`);
1581
+ cursor = at;
1582
+ }
1583
+ const job = swJobs(out)[jobId];
1584
+ const configure = job.slice(job.indexOf(CONFIGURE_HEAD), job.indexOf(CLEANUP_HEAD));
1585
+ const cleanup = job.slice(job.indexOf(CLEANUP_HEAD)).split(/^ {6}- /m)[1];
1586
+ assert.match(` - ${cleanup}`, /^ {6}- name: Remove private Swift package access\n if: \$\{\{ always\(\) \}\}\n/, `${name}/${jobId}: cleanup always runs`);
1587
+ assert.doesNotMatch(configure.split(/^ {6}- /m)[1].split(" run: |\n")[1], /secrets\./, `${name}/${jobId}: no secret expression in the configure run script`);
1588
+ // Nothing before the configure step touches the credential.
1589
+ assert.equal(job.slice(0, job.indexOf(CONFIGURE_HEAD)).includes("RIGHT_GIT_PRIVATE_TOKEN"), false);
1590
+ // Every secret expression in the job is an env value; no run script line contains one.
1591
+ let inRun = false;
1592
+ for (const line of job.split("\n")) {
1593
+ if (/^ {8}run: \|$/.test(line)) { inRun = true; continue; }
1594
+ if (inRun && /^ {0,8}\S/.test(line)) inRun = false;
1595
+ if (inRun) assert.doesNotMatch(line, /secrets\./, `${name}/${jobId}: secret in a run script`);
1596
+ if (line.includes("secrets.")) assert.match(line, SW_SECRET_ENV_LINE);
1597
+ }
1598
+ }
1599
+ });
1600
+
1601
+ test("regenerate lanes remove the credential before the branch is pushed", () => {
1602
+ for (const name of ["node/regenerate", "rust-hybrid/regenerate"]) {
1603
+ const [, manifest, lane] = SW_CASES.find(([n]) => n === name);
1604
+ const out = swRender(manifest, lane, SW_SET);
1605
+ assert.ok(out.indexOf(CLEANUP_HEAD) < out.indexOf("git push origin"), `${name}: cleanup precedes the push`);
1606
+ assert.ok(out.indexOf(CONFIGURE_HEAD) < out.indexOf("Regenerate derived artifacts"), `${name}: configure precedes the regenerate script`);
1607
+ assert.match(out, /^on:\n workflow_dispatch:\npermissions:/m);
1608
+ }
1609
+ });
1610
+
1611
+ test("rust-hybrid dev-artifact: the Windows job never gets the steps; a Windows-only devArtifact renders nothing new", () => {
1612
+ const out = swRender(SW_RUST, "ci", SW_SET);
1613
+ const jobs = swJobs(out);
1614
+ assert.match(jobs["dev-artifact-mac"], /# QA gate job, not after it, and reaches only the private Swift package secret\./);
1615
+ assert.match(jobs["dev-artifact-windows"], /# QA gate job, not after it, and never reaches a secret\./);
1616
+ assert.doesNotMatch(jobs["dev-artifact-windows"], /Swift package|RIGHT_GIT_PRIVATE_TOKEN/);
1617
+ assert.match(jobs["dev-artifact-mac"], /persist-credentials: false/);
1618
+ assert.match(jobs["dev-artifact-mac"], /if: \$\{\{ github\.event_name == 'push' && github\.ref_name == github\.event\.repository\.default_branch \}\}/);
1619
+ const windowsOnly = { ...SW_RUST, devArtifact: { windows: "unsigned", parallel: true, buildScript: "build:dev", windowsGlob: "target/release/*.exe" } };
1620
+ assert.equal(
1621
+ swRender(windowsOnly, "ci", SW_SET).slice(swRender(windowsOnly, "ci", SW_SET).indexOf("\n dev-artifact-windows:")),
1622
+ swRender(windowsOnly, "ci").slice(swRender(windowsOnly, "ci").indexOf("\n dev-artifact-windows:")),
1623
+ );
1624
+ });
1625
+
1626
+ test("every template's triggers are safe for the swift credential: none is pull_request_target or workflow_run", () => {
1627
+ const templates = [
1628
+ ...fs.readdirSync(templatesDir).filter((f) => f.endsWith(".yml")).map((f) => path.join(templatesDir, f)),
1629
+ ...fs.readdirSync(path.join(templatesDir, "profiles", "rust-hybrid")).filter((f) => f.endsWith(".yml")).map((f) => path.join(templatesDir, "profiles", "rust-hybrid", f)),
1630
+ ];
1631
+ assert.equal(templates.length, 10);
1632
+ for (const file of templates) {
1633
+ const onBlock = fs.readFileSync(file, "utf8").split("\njobs:")[0].split(/^on:/m)[1] ?? "";
1634
+ assert.doesNotMatch(onBlock.split(/^permissions:/m)[0], /pull_request_target|workflow_run/, path.relative(templatesDir, file));
1635
+ }
1636
+ });
1637
+
1638
+ test("rendering the credential steps under pull_request_target or workflow_run is refused", () => {
1639
+ const step = swiftPrivatePackagesConfigureStep({ swift: SW_SET });
1640
+ for (const trigger of ["pull_request_target:", "workflow_run:\n workflows: [ci]\n types: [completed]"]) {
1641
+ const template = `name: x\non:\n ${trigger}\njobs:\n a:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\${SWIFT_PRIVATE_CONFIGURE_STEP}\n`;
1642
+ assert.throws(() => renderTemplate(template, { SWIFT_PRIVATE_CONFIGURE_STEP: step }), /refusing to render the private Swift package credential steps/);
1643
+ // The same trigger without the credential step is not this guard's business.
1644
+ assert.doesNotThrow(() => renderTemplate(template, { SWIFT_PRIVATE_CONFIGURE_STEP: "" }));
1645
+ }
1646
+ const flow = "name: x\non: [pull_request_target]\njobs:\n a:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi${SWIFT_PRIVATE_CONFIGURE_STEP}\n";
1647
+ assert.throws(() => renderTemplate(flow, { SWIFT_PRIVATE_CONFIGURE_STEP: step }), /refusing/);
1648
+ const safe = "name: x\non:\n pull_request:\n workflow_dispatch:\njobs:\n a:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi${SWIFT_PRIVATE_CONFIGURE_STEP}\n";
1649
+ assert.doesNotThrow(() => renderTemplate(safe, { SWIFT_PRIVATE_CONFIGURE_STEP: step }));
1650
+ });
1651
+
1652
+ test("swift.privatePackages lane validation: needs ci, qualification, release-candidate or regenerate; refuses lanes that never render it", () => {
1653
+ const errorsFor = (lanes) => validateManifest({ ...SW_NODE, lanes, regenerate: lanes.includes("regenerate") ? SW_NODE.regenerate : undefined, swift: SW_SET }).errors;
1654
+ for (const lane of ["ci", "qualification", "release-candidate", "regenerate"]) {
1655
+ assert.deepEqual(errorsFor([lane]), [], lane);
1656
+ }
1657
+ for (const lanes of [["package-smoke"], ["publish-npm"], ["publish-package-managers"]]) {
1658
+ assert.ok(errorsFor(lanes).some((e) => /requires one of the lanes/.test(e)), lanes.join());
1659
+ }
1660
+ });
1661
+
1662
+ test("rendered swift.privatePackages workflows for every lane pass actionlint", (t) => {
1663
+ const bin = spawnSync("actionlint", ["-version"], { encoding: "utf8" });
1664
+ if (bin.error) return t.skip("actionlint not installed");
1665
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-swift-lanes-"));
1666
+ try {
1667
+ fs.mkdirSync(path.join(dir, ".github", "workflows"), { recursive: true });
1668
+ fs.writeFileSync(path.join(dir, ".github", "actionlint.yaml"), "self-hosted-runner:\n labels:\n - xcode-*\n");
1669
+ const files = SW_CASES.flatMap(([name, manifest, lane]) => {
1670
+ const file = path.join(dir, ".github", "workflows", `${name.replace("/", "-")}.yml`);
1671
+ fs.writeFileSync(file, swRender(manifest, lane, { privatePackages: [...SWIFT_ONE, { host: "git.example.com", secret: "SECOND_SWIFT_TOKEN" }] }));
1672
+ return [file];
1673
+ });
1674
+ const result = spawnSync("actionlint", ["-shellcheck=", "-pyflakes=", "-config-file", path.join(dir, ".github", "actionlint.yaml"), ...files], { encoding: "utf8" });
1675
+ assert.equal(result.status, 0, result.stdout + result.stderr);
1676
+ } finally {
1677
+ fs.rmSync(dir, { recursive: true, force: true });
1678
+ }
1679
+ });
1680
+
1681
+ // node release-candidate: the ownership step proves the checked-out commit is the revision the
1682
+ // candidate was requested for. A dispatch names it through the source_revision input; a v* tag
1683
+ // push has no input and compares against the pushed commit.
1684
+ test("node release-candidate declares source_revision, checks it out, and binds the ownership step to it", () => {
1685
+ const out = swRender(SW_NODE, "release-candidate");
1686
+ assert.match(out, /^on:\n workflow_dispatch:\n inputs:\n source_revision:\n description: [^\n]+\n required: true\n type: string\n push:\n tags: \['v\*'\]\npermissions:/m);
1687
+ assert.match(out, /- uses: actions\/checkout@v5\n with:\n ref: \$\{\{ inputs\.source_revision \|\| github\.sha \}\}\n/);
1688
+ assert.match(out, /run: test "\$\(git rev-parse HEAD\)" = "\$\{\{ inputs\.source_revision \|\| github\.sha \}\}" && /);
1689
+ assert.doesNotMatch(out, /= "\$\{\{ inputs\.source_revision \}\}"/);
1690
+ // The rust-hybrid dispatch-only lane keeps its input-only comparison.
1691
+ assert.match(swRender(SW_RUST, "release-candidate"), /run: test "\$\(git rev-parse HEAD\)" = "\$\{\{ inputs\.source_revision \}\}" && /);
1692
+ // Other node lanes still compare with the run's own commit.
1693
+ assert.match(swRender(SW_NODE, "qualification"), /= "\$\{\{ github\.sha \}\}" && /);
1694
+ });
1695
+
1696
+ test("node release-candidate ownership step passes on both triggers and fails on a revision mismatch", () => {
1697
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-rc-revision-"));
1698
+ try {
1699
+ const git = (...args) => spawnSync("git", ["-C", scratch, ...args], { encoding: "utf8" });
1700
+ git("init", "-q");
1701
+ git("-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "--allow-empty", "-m", "one");
1702
+ git("-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "--allow-empty", "-m", "two");
1703
+ const head = git("rev-parse", "HEAD").stdout.trim();
1704
+ const other = git("rev-parse", "HEAD~1").stdout.trim();
1705
+ const line = swRender(SW_NODE, "release-candidate").split("\n").find((l) => l.includes("git rev-parse HEAD"));
1706
+ const script = line.replace(/^\s*run: /, "").replace(/ && .*$/, "").replace("${{ inputs.source_revision || github.sha }}", "$RC_EXPECTED");
1707
+ const check = (inputRevision, sha) => spawnSync("bash", ["-c", script], {
1708
+ cwd: scratch,
1709
+ encoding: "utf8",
1710
+ env: { PATH: process.env.PATH, RC_EXPECTED: inputRevision || sha },
1711
+ }).status;
1712
+ // workflow_dispatch: the input names the commit that was checked out.
1713
+ assert.equal(check(head, other), 0, "dispatch input equals HEAD");
1714
+ assert.notEqual(check(other, head), 0, "dispatch input differs from HEAD");
1715
+ // v* tag push: no input, so the pushed commit is the expectation.
1716
+ assert.equal(check("", head), 0, "tag push at HEAD");
1717
+ assert.notEqual(check("", other), 0, "tag push whose commit is not HEAD");
1718
+ assert.match(script, /^test "\$\(git rev-parse HEAD\)" = "\$RC_EXPECTED"$/);
1719
+ } finally {
1720
+ fs.rmSync(scratch, { recursive: true, force: true });
1721
+ }
1722
+ });