@rightkit/ci 0.0.0-stage → 0.2.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,178 @@
1
- # Temporary Holding Version
1
+ # @rightkit/ci
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Public-repository-only GitHub Actions workflow layer for Right Suite products. The CLI `right-git` renders and installs CI lanes into `.github/workflows/` from a `.rightgit.json` manifest.
4
+
5
+ | Item | Value |
6
+ |---|---|
7
+ | Where it runs | Build and release tooling (repository CI setup) |
8
+ | Rust pair | None |
9
+ | Version | see INDEX.md |
10
+ | License | MIT OR Apache-2.0 |
11
+
12
+ ## Commands
13
+
14
+ - `right-git install <repo> --lanes ci,...` writes `.rightgit.json` and renders workflows.
15
+ - Lanes: `ci`, `qualification`, `package-smoke`, `release-candidate`, `publish-npm`, `publish-package-managers`, `regenerate`. The `regenerate` lane is manual-only: it runs `regenerate.script`, checks the result, and opens a pull request from a `right-git/regenerate-<run>` branch; it never writes to the default branch.
16
+ - `right-git sync` re-renders installed workflows from the manifest.
17
+ - `right-git drift --all` checks installed workflows against templates and re-checks visibility. When the manifest declares the `regenerate` lane, drift also warns (never fails) if the repository's "Allow GitHub Actions to create and approve pull requests" setting is off. It reads `gh api repos/{owner}/{repo}/actions/permissions/workflow` and prints a note instead when gh is unavailable.
18
+ - `right-git adopt` maps an existing repository's workflows onto lanes for review. With `--out <dir>` it writes the candidate templates to that directory.
19
+ - `right-git uninstall` removes every managed file.
20
+
21
+ `install` and `sync` refuse private, internal and unconfirmed-visibility repositories. There is no override flag.
22
+
23
+ ## Default branch
24
+
25
+ `"defaultBranch": "master"` renders the `push` trigger of the `ci`, `qualification` and `package-smoke` lanes, and the rust-hybrid `release-candidate` admission check (`refs/heads/<branch>`), for a repository whose default branch is not `main`. Unset, it is `main` and output is byte-identical.
26
+
27
+ ## Checkout options (all lanes)
28
+
29
+ Opt-in `checkout` block applied to every `actions/checkout` step the manifest renders. Unset, `{}` or `longPaths: false` with no `sparse`, the rendered workflows are byte-identical.
30
+
31
+ ```json
32
+ { "checkout": { "longPaths": true, "sparse": ["packages/", "examples/SliceApp"] } }
33
+ ```
34
+
35
+ - `longPaths: true` renders a step directly before each checkout: `if: runner.os == 'Windows'`, `shell: bash`, `git config --system core.longpaths true`. It is the documented workaround for `Filename too long` on Windows runners (actions/checkout issue 242 recommends setting `core.longpaths` before the checkout step). Linux and macOS legs skip it, so matrix jobs stay one definition.
36
+ - `sparse` renders `sparse-checkout: |` (one directory per line) and `sparse-checkout-cone-mode: true` into each checkout of the repository itself, merged with any existing `with:` inputs. Cone mode always keeps root-level files. Entries are unique safe relative directory paths (no `..`, whitespace, leading `/` or expression syntax). Use it when only part of the tree is needed, or to skip paths that cannot exist on Windows at all. Checkouts of another repository (such as the Homebrew tap) are never sparse.
37
+
38
+ ## Optional QA evidence upload (rust-hybrid)
39
+
40
+ Set `qaEvidencePath` in `.rightgit.json` to upload the gate's QA output as a workflow artifact. The path is relative to `$RUNNER_TEMP`; the rendered step uses `${{ runner.temp }}/<path>`. Absolute paths and expression syntax are rejected.
41
+
42
+ ```json
43
+ {
44
+ "profile": "rust-hybrid",
45
+ "gate": { "path": "scripts/gate.sh" },
46
+ "qaEvidencePath": "pulse-hub-qa",
47
+ "qaEvidenceRetentionDays": 14
48
+ }
49
+ ```
50
+
51
+ - The step runs after the gate with `if: always()` and `if-no-files-found: ignore`.
52
+ - Artifact name: `qa-evidence-${{ matrix.os || runner.os }}-${{ github.run_attempt }}`.
53
+ - `qaEvidenceRetentionDays` is an integer from 1 to 90 and defaults to 7. It requires `qaEvidencePath`.
54
+ - Omit the key and the rendered `ci.yml` is unchanged.
55
+
56
+ ## Full validation on every OS (rust-hybrid)
57
+
58
+ Set `"ciAllOs": true` to run the rust-hybrid `ci` gate on every `matrix.os` runner instead of one. Runners run in declared order with `fail-fast: false`. Each leg uploads its own artifact, because the QA artifact name already includes the runner label.
59
+
60
+ ```json
61
+ {
62
+ "profile": "rust-hybrid",
63
+ "matrix": { "os": ["xcode-27", "windows-2025"], "node": ["26.8.1"] },
64
+ "ciAllOs": true
65
+ }
66
+ ```
67
+
68
+ Omit the key, or set it to `false`, and the rendered `ci.yml` keeps one runner, preferring the first `windows-*` entry. `ciAllOs: true` is rejected for other profiles.
69
+
70
+ ## Incremental CI and dev artifacts (rust-hybrid)
71
+
72
+ Both keys are opt-in; unset, the rendered `ci.yml` is byte-identical.
73
+
74
+ `"ciIncremental": true` switches Rust caching to `cache-workspace-crates: true`, sets `CARGO_INCREMENTAL=1` for the ci gate, and caches `~/Library/Developer/Xcode/DerivedData` on macOS legs (key: runner + `Cargo.lock` + `Package.resolved` + `project.pbxproj` hash).
75
+
76
+ `devArtifact` publishes fast development builds as workflow artifacts, separate from the release-candidate lane. It runs on push to the default branch only, never on pull requests. `mac` is `"sign"` (Developer ID via the `dev-mac-sign` job), `"notarize"` (signed, notarized and stapled; required for apps that ship app extensions, which macOS refuses from unnotarized Developer ID apps), `"unsigned"` (the bare `.app` zipped as `dev-mac-unsigned-<sha>`) or `"none"`; `windows` is `"unsigned"` or `"none"`. With `dispatch: true` the unsigned legs also run on a manual `workflow_dispatch` of any ref; the signing job never does.
77
+
78
+ ```json
79
+ {
80
+ "profile": "rust-hybrid",
81
+ "matrix": { "os": ["xcode-27", "windows-2025"], "node": ["26.8.1"] },
82
+ "ciAllOs": true,
83
+ "ciIncremental": true,
84
+ "devArtifact": {
85
+ "mac": "sign",
86
+ "windows": "unsigned",
87
+ "retentionDays": 7,
88
+ "macAppPath": "target/release/bundle/macos/Pulse.app",
89
+ "windowsGlob": "target/release/*.exe"
90
+ }
91
+ }
92
+ ```
93
+
94
+ - `mac: "sign"` needs `macAppPath` (the built `.app`, repository-relative) and a macOS runner in the ci gate (`ciAllOs`). The unsigned app is zipped with `ditto` and handed to a separate `dev-mac-sign` job that installs the Developer ID identity from the `release` environment secrets, runs `codesign --force --deep --strict --options runtime`, verifies, zips and uploads `dev-mac-<sha>`. No notarization, admission or ownership gate. Optional `macEntitlements` passes `--entitlements`.
95
+ - `windows: "unsigned"` needs `windowsGlob` and a `windows-*` runner in the ci gate; matched files upload as `dev-windows-<sha>`.
96
+ - The `dev-mac-sign` job uses the `release` environment, so that environment's protection rules (required reviewers, branch policy) apply. The job only exists for pushes to the default branch.
97
+ - Install a mac dev build with `right-release install-app --dev --zip <file>` (Developer ID-signed, not notarized).
98
+ - `devArtifact.parallel: true` moves each platform's build into its own job, `dev-artifact-mac` or `dev-artifact-windows`. Each runs beside the QA gate job instead of after it, needs only the private-repo guard, and compiles the dev app with `devArtifact.buildScript` (a package script name; required with `parallel`, rejected without it) before staging it. Parallel jobs run on their own platform runners, so they do not need `ciAllOs`. `mac: "sign"` still waits for the gate: `dev-mac-sign` needs `ci` and `dev-artifact-mac`. The trade-off: unsigned uploads no longer wait for the gate, so a failing gate can still leave `dev-windows-<sha>` or `dev-mac-unsigned-<sha>` behind. Unset or `false` keeps the staging inside the gate job.
99
+ - The `~/Library/Developer/Xcode/DerivedData` cache helps only builds that use Xcode's default derived data location. A gate that passes its own `-derivedDataPath` writes outside that directory and gets nothing from the cache; use the default location, or cache the custom path in the gate.
100
+
101
+ ## Cache keys and concurrency (rust-hybrid)
102
+
103
+ Both keys are opt-in; unset, the rendered workflows are byte-identical.
104
+
105
+ - `rustCache.keySuffix` (1 to 64 characters: letters, digits, `.`, `_`, `-`; starts with a letter or digit) renders `key: <lane>-<suffix>` into every Swatinem/rust-cache step: `ci`, `regenerate`, `release-candidate`. Each lane therefore keeps its own cache entry. The dev-artifact jobs use `<lane>-dev-artifact-<platform>-<suffix>`. Swatinem/rust-cache does not re-save a cache on an exact key hit (third-party behavior, not verified in this repository). To rotate the cache, change the suffix, which gives it a new key.
106
+ - `concurrency.mainPushes: "queue"` (requires lane `ci`; both profiles) renders the ci workflow's `cancel-in-progress` as an expression that is false only for pushes to the default branch. Default-branch pushes queue and each one runs to completion; PR runs still cancel superseded runs. `"cancel"` is the default and renders the current `cancel-in-progress: true`.
107
+
108
+ ```json
109
+ {
110
+ "profile": "rust-hybrid",
111
+ "rustCache": { "workspaces": ["engine"], "keySuffix": "2026-10" },
112
+ "concurrency": { "mainPushes": "queue" },
113
+ "devArtifact": {
114
+ "mac": "unsigned",
115
+ "windows": "unsigned",
116
+ "parallel": true,
117
+ "buildScript": "build:dev",
118
+ "macAppPath": "target/release/bundle/macos/Pulse.app",
119
+ "windowsGlob": "target/release/*.exe"
120
+ }
121
+ }
122
+ ```
123
+
124
+ ## Private Swift packages (ci, qualification, release-candidate, regenerate lanes)
125
+
126
+ Set `swift.privatePackages` to let a public repository's workflows fetch a private Swift package, for example `example-org/private-swift-package`:
127
+
128
+ ```json
129
+ {
130
+ "profile": "rust-hybrid",
131
+ "swift": { "privatePackages": [{ "host": "github.com", "secret": "RIGHTKIT_SWIFT_TOKEN" }] }
132
+ }
133
+ ```
134
+
135
+ - `host` is a bare host name, unique within the list (at most four entries). `secret` is a GitHub Actions secret name (letters, digits, `_`; not starting with a digit or `GITHUB_`). The manifest needs at least one of the lanes `ci`, `qualification`, `release-candidate`, `regenerate`.
136
+ - The secret must be a fine-grained token with `contents: read` on the private package repository only, and nothing else. The repository owner provisions it; the workflow never prints it.
137
+ - One implementation renders everywhere. The configure step runs right before the first build or test step of the job. It writes `~/.netrc` (`machine <host> login x-access-token password <token>`, mode 600) and a job-scoped `git config --global url."https://x-access-token:<token>@<host>/".insteadOf "https://<host>/"`. The token reaches the step through `env` (`${{ secrets.<NAME> }}` in an `env:` block), never the run script.
138
+ - It refuses to run when `~/.netrc` already exists, so a persistent self-hosted runner's own file is never overwritten. The cleanup step runs with `if: always()` after the last build or test step of the job, removes the `~/.netrc` and the git rewrite it created, and leaves a pre-existing file alone.
139
+ - Any code that runs between the configure and cleanup steps in that job can read the token. Keep the token read-only.
140
+ - Unset, the rendered workflows are byte-identical to earlier versions.
141
+ - A run from a fork gets no secrets, so the configure step fails with a message that names the secret.
142
+ - Refused with `devArtifact.dispatch: true`: a manual dispatch of any ref would reach the secret. Rendering the steps into a workflow triggered by `pull_request_target` or `workflow_run` throws; no shipped template has either trigger.
143
+
144
+ Which jobs get the steps, and why each is safe:
145
+
146
+ | Lane (workflow) | Job | Position | Triggers and why it is safe |
147
+ | --- | --- | --- | --- |
148
+ | `ci` (both profiles) | `ci` (rust-hybrid), `test` (node) | rust-hybrid: before the gate, cleanup after it. node: after install, cleanup is the last step | `pull_request` and `push` to `main`. Fork pull requests get no secrets, so the job fails closed |
149
+ | `ci`, rust-hybrid with `devArtifact.parallel` | `dev-artifact-mac` | before "Build dev app", cleanup before the staging and upload steps | Push to the default branch only (dispatch is refused). `dev-artifact-windows` and `dev-mac-sign` never get the steps |
150
+ | `qualification` (node) | `qualification` (runs `test:all`) | after the ownership step, cleanup right after `test:all` | `pull_request` and `push` to `main`, as ci. `schema`, `security`, `hardening` and `conformance` stay secret-free; `security` is a secret-egress suite |
151
+ | `release-candidate` (both profiles) | `candidate` | rust-hybrid: before "Build unsigned release candidate", cleanup right after "Check unsigned release candidate". node: after the ownership step, cleanup after `check-release.mjs` | rust-hybrid: `workflow_dispatch` only. node: `workflow_dispatch` and `v*` tag pushes. Dispatch needs write access, and this job holds no signing credential. The admission, signing, installed-qualification and publish jobs never get the steps |
152
+ | `regenerate` (both profiles) | `regenerate` | before the regenerate script, cleanup after the test or gate step and before the pull-request step | `workflow_dispatch` only. The cleanup runs before `git push`, so the push never runs under the `insteadOf` rewrite |
153
+
154
+ Never rendered: `package-smoke` (a clean-room tarball check), `publish-npm` and `publish-package-managers` (publishing credentials), and the release chain's `windows-sign`, `macos-sign`, `installed-qualification` and `publish` jobs (signing and publish credentials). Their output is the same with and without `swift.privatePackages`.
155
+
156
+ Release policy. `@rightkit/release` enforces the `right-git-ci-only` policy over the rendered workflows (`validateHostedWorkflows` in `release.mjs`). It refuses a managed workflow that references any secret outside an allowlist. The allowlist admits the `swift.privatePackages` secret only on its `RIGHT_GIT_PRIVATE_TOKEN_<n>: ${{ secrets.<NAME> }}` env line, inside the "Configure private Swift package access" or "Remove private Swift package access" step, of these jobs: `ci.yml` jobs `ci` (either profile), `dev-artifact-mac` (rust-hybrid with `devArtifact.parallel` and a `devArtifact.mac` leg) and `test` (node profile); `qualification.yml` job `qualification`; `release-candidate.yml` job `candidate`; and `regenerate.yml` job `regenerate` (`SWIFT_PRIVATE_JOBS`, `release.mjs:86-91`). Each reference also needs its lane listed in `.rightgit.json`, `devArtifact.dispatch` not true, and no `pull_request_target` or `workflow_run` trigger. `workflow_dispatch` is allowed only in `release-candidate.yml` and `regenerate.yml` (`swiftPrivateSecretRefusal`, `release.mjs`).
157
+
158
+ ## Entry points
159
+
160
+ No importable API. The package has no `main` and no `exports` map. The supported surface is the `right-git` bin.
161
+
162
+ ## Peer dependencies
163
+
164
+ None. No runtime dependencies (Node builtins only).
165
+
166
+ ## Example
167
+
168
+ ```sh
169
+ pnpm add -D @rightkit/ci
170
+ pnpm exec right-git install . --lanes ci
171
+ pnpm exec right-git drift --all
172
+ ```
173
+
174
+ ## Known issues
175
+
176
+ - The optional `publish-package-managers` lane needs two long-lived tokens in GitHub Actions secrets. Their names and scope are in the package templates, and they are not zero-exposure. Read `docs/rules/github-access.md` in the workspace before enabling it.
177
+ - Manifest fields are charset-checked before they reach workflow YAML.
178
+ - `swift.privatePackages` renders a secret reference into the workflows listed in its section. The `right-git-ci-only` policy in `@rightkit/release` refuses any reference outside the jobs listed under Release policy above.
package/adopt.mjs ADDED
@@ -0,0 +1,96 @@
1
+ // Pull an existing repo's hand-written workflows into review-ready template
2
+ // candidates (DESIGN.md §4, "Cortex bootstrap"). Read-only against the
3
+ // source repo. Never writes into templates/ directly — adopt's output is
4
+ // mapped lane content for a human (or a follow-up Sage-authorized change)
5
+ // to review and fold in; silently overwriting the curated, parameterized
6
+ // template library from an arbitrary repo's raw workflow text is exactly
7
+ // the kind of unreviewed mutation this package must not perform on its own.
8
+
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { LANE_FILENAMES } from "./manifest.mjs";
12
+
13
+ // filename (in the source repo's .github/workflows/) -> lane, for the
14
+ // lanes that map 1:1 onto an existing file.
15
+ const FILENAME_TO_LANE = {
16
+ "ci.yml": "ci",
17
+ "qualification.yml": "qualification",
18
+ "package.yml": "package-smoke",
19
+ "package-smoke.yml": "package-smoke",
20
+ "release-candidate.yml": "release-candidate",
21
+ "publish-npm.yml": "publish-npm",
22
+ "publish-package-managers.yml": "publish-package-managers",
23
+ };
24
+
25
+ /** Slice out one top-level job block from a workflow's `jobs:` map by name or predicate. */
26
+ export function extractJobBlock(yamlText, jobNameOrPredicate) {
27
+ const lines = yamlText.split("\n");
28
+ const jobsIdx = lines.findIndex((l) => /^jobs:\s*$/.test(l));
29
+ if (jobsIdx === -1) return null;
30
+
31
+ const jobStarts = [];
32
+ for (let i = jobsIdx + 1; i < lines.length; i++) {
33
+ if (/^ {2}\S.*:\s*$/.test(lines[i])) jobStarts.push(i);
34
+ }
35
+
36
+ for (let idx = 0; idx < jobStarts.length; idx++) {
37
+ const start = jobStarts[idx];
38
+ const end = idx + 1 < jobStarts.length ? jobStarts[idx + 1] : lines.length;
39
+ const nameMatch = /^ {2}(\S+):/.exec(lines[start]);
40
+ const name = nameMatch ? nameMatch[1] : null;
41
+ const block = lines.slice(start, end).join("\n");
42
+ const matches = typeof jobNameOrPredicate === "function" ? jobNameOrPredicate(name, block) : name === jobNameOrPredicate;
43
+ if (matches) return { name, block };
44
+ }
45
+ return null;
46
+ }
47
+
48
+ /**
49
+ * Inspect <repoPath>/.github/workflows/*.yml and map filenames onto known
50
+ * right-git lanes. Never throws, never writes.
51
+ * Returns { ok, mapped: [{lane, sourceFile, content}], unmapped: string[], errors }
52
+ */
53
+ export function adoptCommand(repoPath) {
54
+ const dir = path.join(repoPath, ".github", "workflows");
55
+ let entries;
56
+ try {
57
+ entries = fs.readdirSync(dir).filter((n) => n.endsWith(".yml") || n.endsWith(".yaml"));
58
+ } catch (error) {
59
+ return { ok: false, mapped: [], unmapped: [], errors: [`cannot read ${dir}: ${error.message}`] };
60
+ }
61
+
62
+ const mapped = [];
63
+ const unmapped = [];
64
+ const foundLanes = new Set();
65
+
66
+ for (const filename of entries) {
67
+ const lane = FILENAME_TO_LANE[filename];
68
+ if (lane) {
69
+ const content = fs.readFileSync(path.join(dir, filename), "utf8");
70
+ mapped.push({ lane, sourceFile: filename, content });
71
+ foundLanes.add(lane);
72
+ continue;
73
+ }
74
+ unmapped.push(filename);
75
+ }
76
+
77
+ // publish-npm has no 1:1 file in the Cortex-shaped source layout — it is a
78
+ // single job inside a larger release workflow (DESIGN.md §6). Best-effort
79
+ // extraction by scanning any remaining file for a job whose steps run
80
+ // `npm publish`.
81
+ if (!foundLanes.has("publish-npm")) {
82
+ for (const filename of unmapped.slice()) {
83
+ const content = fs.readFileSync(path.join(dir, filename), "utf8");
84
+ const job = extractJobBlock(content, (_name, block) => /npm publish/.test(block));
85
+ if (job) {
86
+ mapped.push({ lane: "publish-npm", sourceFile: `${filename}#${job.name}`, content: job.block });
87
+ foundLanes.add("publish-npm");
88
+ break;
89
+ }
90
+ }
91
+ }
92
+
93
+ return { ok: true, mapped, unmapped, errors: [] };
94
+ }
95
+
96
+ export { LANE_FILENAMES };
package/checkout.mjs ADDED
@@ -0,0 +1,93 @@
1
+ // Optional `checkout` manifest block: Windows long-path support and sparse
2
+ // checkout for every actions/checkout step in a rendered workflow.
3
+ //
4
+ // "checkout": { "longPaths": true, "sparse": ["packages/", "examples/App"] }
5
+ //
6
+ // longPaths renders, immediately before each checkout step and gated on
7
+ // `runner.os == 'Windows'`, a step running `git config --system core.longpaths true`
8
+ // (the actions/checkout workaround for "Filename too long", actions/checkout#242).
9
+ // sparse renders `sparse-checkout` (cone mode) into each checkout step's `with:`.
10
+ // Unset, rendered workflows are byte-identical.
11
+
12
+ const SPARSE_PATH_RE = /^(?!.*\.\.)(?!\.?\/)[A-Za-z0-9._][A-Za-z0-9._/-]*$/;
13
+ const CHECKOUT_KEYS = new Set(["longPaths", "sparse"]);
14
+ const CHECKOUT_USES_RE = /^(\s*)(- )?uses: actions\/checkout@/;
15
+
16
+ export function validateCheckout(checkout, errors) {
17
+ if (checkout === undefined) return;
18
+ if (checkout === null || typeof checkout !== "object" || Array.isArray(checkout)) {
19
+ errors.push("checkout must be an object");
20
+ return;
21
+ }
22
+ for (const key of Object.keys(checkout)) {
23
+ if (!CHECKOUT_KEYS.has(key)) errors.push(`unknown checkout field: ${key}`);
24
+ }
25
+ if (checkout.longPaths !== undefined && typeof checkout.longPaths !== "boolean") {
26
+ errors.push("checkout.longPaths must be a boolean");
27
+ }
28
+ if (checkout.sparse !== undefined) {
29
+ const s = checkout.sparse;
30
+ if (!Array.isArray(s) || s.length === 0 || s.length > 64
31
+ || !s.every((p) => typeof p === "string" && SPARSE_PATH_RE.test(p))
32
+ || new Set(s).size !== s.length) {
33
+ errors.push("checkout.sparse must be a non-empty array (at most 64) of unique safe repository-relative directory paths (letters, digits, '.', '_', '-', '/'; no '..', whitespace, leading '/', or expression syntax)");
34
+ }
35
+ }
36
+ }
37
+
38
+ /** Apply manifest.checkout to every actions/checkout step of a rendered workflow. */
39
+ export function applyCheckoutOptions(content, manifest) {
40
+ const opts = manifest.checkout;
41
+ if (!opts || (opts.longPaths !== true && !opts.sparse)) return content;
42
+ const lines = content.split("\n");
43
+ const out = [];
44
+ for (let i = 0; i < lines.length; i += 1) {
45
+ const match = CHECKOUT_USES_RE.exec(lines[i]);
46
+ if (!match) {
47
+ out.push(lines[i]);
48
+ continue;
49
+ }
50
+ const indent = match[1];
51
+ // Step start: the `- uses:` line itself, or the preceding `- name:` line.
52
+ let stepIndent = indent;
53
+ if (!match[2]) {
54
+ stepIndent = indent.slice(0, -2);
55
+ const previous = out[out.length - 1];
56
+ if (previous === undefined || !previous.startsWith(`${stepIndent}- `)) {
57
+ throw new Error("checkout: cannot locate the start of a named actions/checkout step");
58
+ }
59
+ }
60
+ if (opts.longPaths === true) {
61
+ const step = [
62
+ `${stepIndent}- name: Enable Windows long paths`,
63
+ `${stepIndent} if: runner.os == 'Windows'`,
64
+ `${stepIndent} shell: bash`,
65
+ `${stepIndent} run: git config --system core.longpaths true`,
66
+ ];
67
+ const at = match[2] ? out.length : out.length - 1;
68
+ // For a named step, insert before its `- name:` line (and any lines of that header already emitted).
69
+ out.splice(at, 0, ...step);
70
+ }
71
+ out.push(lines[i]);
72
+ // A checkout of another repository (e.g. a tap) keeps its own `with:` and is never sparse.
73
+ let foreign = false;
74
+ for (let j = i + 1; j < lines.length && (lines[j].startsWith(`${stepIndent} `) || lines[j] === ""); j += 1) {
75
+ if (lines[j].trim().startsWith("repository:")) foreign = true;
76
+ }
77
+ if (opts.sparse && !foreign) {
78
+ const inner = `${stepIndent} `;
79
+ const sparseLines = [
80
+ `${inner} sparse-checkout: |`,
81
+ ...opts.sparse.map((p) => `${inner} ${p}`),
82
+ `${inner} sparse-checkout-cone-mode: true`,
83
+ ];
84
+ if (lines[i + 1] === `${inner}with:`) {
85
+ out.push(lines[i + 1], ...sparseLines);
86
+ i += 1;
87
+ } else {
88
+ out.push(`${inner}with:`, ...sparseLines);
89
+ }
90
+ }
91
+ }
92
+ return out.join("\n");
93
+ }
@@ -0,0 +1,91 @@
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 { renderLanes } from "./sync.mjs";
7
+ import { applyCheckoutOptions } from "./checkout.mjs";
8
+ import { KNOWN_LANES } from "./manifest.mjs";
9
+
10
+ const BASE = {
11
+ schemaVersion: 1,
12
+ compile: "github-actions-only",
13
+ lanes: [...KNOWN_LANES],
14
+ matrix: { os: ["ubuntu-latest", "macos-latest", "windows-latest"], node: ["22.13", "24"] },
15
+ packageManager: "pnpm@11.24.0",
16
+ publish: {
17
+ npm: { oidc: true, provenance: true },
18
+ homebrew: { tap: "acme/homebrew-tap", formulaName: "widgets" },
19
+ winget: { packageIdentifier: "Acme.Widgets" },
20
+ },
21
+ regenerate: { script: "regenerate" },
22
+ templateVersion: "1.0.0",
23
+ };
24
+ const NODE_LANES = ["ci", "qualification", "package-smoke", "publish-npm", "publish-package-managers", "regenerate"];
25
+
26
+ function repo() {
27
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rg-checkout-"));
28
+ fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify({ name: "widgets" }));
29
+ return dir;
30
+ }
31
+
32
+ test("checkout unset, empty or longPaths:false leaves every lane byte-identical", () => {
33
+ const r = repo();
34
+ const base = { ...BASE, lanes: NODE_LANES };
35
+ const plain = renderLanes(base, r);
36
+ assert.deepEqual(renderLanes({ ...base, checkout: {} }, r), plain);
37
+ assert.deepEqual(renderLanes({ ...base, checkout: { longPaths: false } }, r), plain);
38
+ });
39
+
40
+ test("checkout.longPaths puts a Windows-gated system core.longpaths step before every checkout", () => {
41
+ const manifest = { ...BASE, lanes: NODE_LANES, checkout: { longPaths: true } };
42
+ for (const { content } of renderLanes(manifest, repo())) {
43
+ const lines = content.split("\n");
44
+ let seen = 0;
45
+ lines.forEach((line, i) => {
46
+ if (!/uses: actions\/checkout@/.test(line)) return;
47
+ seen += 1;
48
+ const header = /- uses:/.test(line) ? i : i - 1;
49
+ assert.equal(lines[header - 1].trim(), "run: git config --system core.longpaths true");
50
+ assert.equal(lines[header - 3].trim(), "if: runner.os == 'Windows'");
51
+ assert.equal(lines[header - 4].trim(), "- name: Enable Windows long paths");
52
+ });
53
+ assert.equal((content.match(/Enable Windows long paths/g) ?? []).length, seen);
54
+ }
55
+ });
56
+
57
+ test("checkout.sparse merges into with: and leaves other-repository checkouts alone", () => {
58
+ const manifest = { ...BASE, lanes: ["ci", "publish-package-managers"], checkout: { sparse: ["packages/", "examples/App"] } };
59
+ const [ci, pm] = renderLanes(manifest, repo()).map((r) => r.content);
60
+ assert.match(ci, /sparse-checkout: \|\n\s+packages\/\n\s+examples\/App\n\s+sparse-checkout-cone-mode: true/);
61
+ assert.doesNotMatch(ci, /core\.longpaths/);
62
+ const tap = pm.split("- name: Checkout Homebrew tap")[1].split(" - run:")[0];
63
+ assert.doesNotMatch(tap, /sparse-checkout/);
64
+ assert.match(pm, /sparse-checkout: \|/);
65
+ });
66
+
67
+ test("rust-hybrid ci renders both options deterministically", () => {
68
+ const manifest = { ...BASE, lanes: ["ci"], profile: "rust-hybrid", gate: { path: "scripts/gate.sh" }, templateVersion: "1.1.0", checkout: { longPaths: true, sparse: ["packages"] } };
69
+ const r = repo();
70
+ const a = renderLanes(manifest, r)[0].content;
71
+ assert.equal(renderLanes(manifest, r)[0].content, a);
72
+ assert.match(a, /Enable Windows long paths/);
73
+ assert.match(a, /sparse-checkout: \|\n\s+packages\n/);
74
+ });
75
+
76
+ test("applyCheckoutOptions adds with: when the step has none", () => {
77
+ const out = applyCheckoutOptions("jobs:\n a:\n steps:\n - uses: actions/checkout@v5\n - run: x\n", { checkout: { sparse: ["a"] } });
78
+ assert.equal(out, "jobs:\n a:\n steps:\n - uses: actions/checkout@v5\n with:\n sparse-checkout: |\n a\n sparse-checkout-cone-mode: true\n - run: x\n");
79
+ });
80
+
81
+ test("defaultBranch renders into push triggers; unset stays main", () => {
82
+ const r = repo();
83
+ const base = { ...BASE, lanes: ["ci", "qualification", "package-smoke"] };
84
+ for (const { content } of renderLanes(base, r)) assert.match(content, /branches: \[main\]/);
85
+ for (const { content } of renderLanes({ ...base, defaultBranch: "master" }, r)) {
86
+ assert.match(content, /branches: \[master\]/);
87
+ assert.doesNotMatch(content, /branches: \[main\]/);
88
+ }
89
+ const rh = { ...BASE, lanes: ["ci"], profile: "rust-hybrid", gate: { path: "scripts/gate.sh" }, templateVersion: "1.1.0", defaultBranch: "master" };
90
+ assert.match(renderLanes(rh, r)[0].content, /branches: \[master\]/);
91
+ });