@rightkit/ci 0.2.49 → 0.3.1

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
@@ -17,9 +17,23 @@ Public-repository-only GitHub Actions workflow layer for Right Suite products. T
17
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
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
19
  - `right-git uninstall` removes every managed file.
20
+ - `right-git artifacts fetch --run <id> --out <dir> [--name <glob>] [--repo owner/repo] [--expect-sha256 <hex> [--file <path>]] [--receipt <file>] [--json]` downloads the artifacts of one workflow run through `gh`, merges them into one tree and writes a JSON receipt (see Fetch CI artifacts).
20
21
 
21
22
  `install` and `sync` refuse private, internal and unconfirmed-visibility repositories. There is no override flag.
22
23
 
24
+ ## RightKit check job (ci, qualification, package-smoke, release-candidate, swift-check, publish-npm)
25
+
26
+ Each lane that compiles or tests renders a `check` job right after `private-repo-guard`, and every other job of that workflow needs it, directly or through a job that does. Nothing builds or qualifies a tree the check refused (pipeline invariant P1, rightkit#833).
27
+
28
+ - **What it runs.** `actions/checkout` at depth 1 (`persist-credentials: false`), `setup-node` (first `matrix.node`), the package manager, a frozen install without lifecycle scripts (`pnpm install --frozen-lockfile --ignore-scripts`; `npm ci --ignore-scripts`; `yarn install --frozen-lockfile --ignore-scripts`), then `pnpm exec rightkit-gate check --commit HEAD`. Committed files only: no network after the install, no compile, no broker, no secret. The job runs where the workflow's guard runs, times out after 15 minutes and pins its actions like the other jobs of the same file (tags in the node lane files, commits in `swift-check` and the rust-hybrid files).
29
+ - **Dependencies.** It needs only `private-repo-guard`. `test` (node `ci`), `ci` and `quick` (rust-hybrid), `qualification`, `clean-tarball`, `candidate`, `swift-check`, `publish-npm`, the release chain's `admission` and the parallel `dev-artifact-*` jobs list it in `needs`. `ci-summary` still reports `ci` and `quick`; a failed check leaves both skipped, which it reports as failed.
30
+ - **The repository must depend on `@rightkit/release` 0.6.5 or later**, the first release with `rightkit-gate check`. Sync the new render only after the app has bumped it, or every run fails at the last step. `right-git sync` and `right-git install` read the pin from `package.json` (`devDependencies`, else `dependencies`) whenever a lane that renders the check job is declared: an exact pin below 0.6.5 is refused at stage `dependency` and nothing is written; a range, a non-registry spec or no `@rightkit/release` dependency prints a `warn:` line to stderr and the sync goes on, because the install may still resolve a new enough version. (`candidate.releaseChain` keeps its own, stricter rule: a direct devDependency pinned to an exact published version.) The install is not filtered to `@rightkit/release`: `pnpm install --filter` selects workspace projects, and in a consumer `@rightkit/release` is a registry dependency, so the filter matches no project, installs nothing and exits 0. npm and yarn call `./node_modules/.bin/rightkit-gate` by path, because `npm exec` fetches an unknown name from the registry in CI.
31
+ - **A release-candidate checks the revision it builds** (`inputs.source_revision`, or the pushed commit in the node lane's tag push). Its checkout is the one shallow checkout among the jobs of an admitted revision: the check only reads the committed files of HEAD and never runs `right-release`, so it has no reachability to prove.
32
+ - **publish-npm checks the release tag it publishes.** The lane checks out `github.event.release.tag_name`, installs, rebuilds the tarball from source (`build-candidate.mjs`), runs `check-release.mjs` and publishes with `id-token: write`, so it builds and tests like the other lanes. Its `check` job checks out the same tag, has no permission beyond the workflow's `contents: read`, no environment and no secret, and the publish job needs it: a tag whose committed files the check refuses never reaches the OIDC token or the registry.
33
+ - **Stale lockfile.** The `ci` lane's check job prints the same lockfile patch as the ci job after a failed frozen install; with the check first, the ci job no longer runs when the lockfile is stale.
34
+ - **Lanes without it.** `regenerate` repairs derived files and lockfiles, which the check flags, so a red check must not block it. `sign-existing`, the `supersede` job and `regenerate` are admitted by `@rightkit/release` (`right-git-ci-only`) only in their exact rendered shape, `needs: [private-repo-guard]`. `publish-package-managers` builds and tests nothing: it installs, syntax-checks the committed Homebrew formula and opens a tap pull request, or submits a WinGet manifest, for a version that is already released. Workflows under the manifest's `workflows` block are unchanged.
35
+ - **Breaking render change.** Every `ci`, `qualification`, `package-smoke`, `release-candidate`, `swift-check` and `publish-npm` render changes (a new job and a `check` entry in `needs`); there is no manifest flag. `right-git drift` on a synced repository shows exactly that job, and the `needs` lines. The hash-pinned renders in `render.test.mjs` were taken again, and each is also kept against its previous hash with the job removed.
36
+
23
37
  ## Default branch
24
38
 
25
39
  `"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.
@@ -67,6 +81,33 @@ Set `"ciAllOs": true` to run the rust-hybrid `ci` gate on every `matrix.os` runn
67
81
 
68
82
  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
83
 
84
+ ## Parallel gate shards (rust-hybrid)
85
+
86
+ A gate that runs everything in one step on each runner is as slow as the sum of its parts. `gate.shards` splits it. The repository compiles locally for a warm cache; this is about running GitHub qualification in parallel.
87
+
88
+ ```json
89
+ {
90
+ "profile": "rust-hybrid",
91
+ "ciAllOs": true,
92
+ "gate": {
93
+ "path": "scripts/gate.sh",
94
+ "quick": true,
95
+ "shards": [{ "id": "workspace" }, { "id": "linters" }, { "id": "rust-tools" }]
96
+ }
97
+ }
98
+ ```
99
+
100
+ - **Shards.** Each shard is one more `matrix.shard` value, so the gate runs once per shard per runner as `bash <path> --group <id>`. `fail-fast: false` still applies, and all legs share one Rust cache key, so one leg's build warms the others.
101
+ - **Per-leg state.** Each leg keeps its own last-green marker and its own QA evidence artifact (the shard id is in both names). On a default-branch push each leg is its own concurrency slot.
102
+ - **`quick: true`.** Adds a `quick` job (`bash <path> --quick`, on `ubuntu-24.04`, after the check job) for the fast deterministic checks. Every leg needs it, so a formatting or record error stops the run before any shard starts.
103
+ - **`ci-summary`.** Passes only when every leg passed (and `quick`, when set). Use it as the one required status check: matrix job names change with the shard list.
104
+ - **Validation.**
105
+ - 2 to 16 shards.
106
+ - Ids are lowercase letters, digits and `-`, at most 32 characters, and unique.
107
+ - `quick` needs `shards`.
108
+ - A `devArtifact` must use `parallel: true`, because a dev artifact staged inside the ci job would be built once per shard.
109
+ - **Without `shards`.** The rendered `ci.yml` is byte-identical.
110
+
70
111
  ## Incremental CI and dev artifacts (rust-hybrid)
71
112
 
72
113
  Both keys are opt-in; unset, the rendered `ci.yml` is byte-identical.
@@ -96,7 +137,7 @@ Both keys are opt-in; unset, the rendered `ci.yml` is byte-identical.
96
137
  - 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
138
  - Install a mac dev build with `right-release install-app --dev --zip <file>` (Developer ID-signed, not notarized).
98
139
  - `devArtifact.macSignManifest` (with `macPayloadMetadata`) replaces `codesign --deep` on the `.app` with `right-release sign-dev-artifact`: each file in the repository-relative sign manifest (`{ "schema": 1, "entries": [{ "file": "Legion.app/Contents/MacOS/legion", "identifier": "com.example.legion" }] }`, paths relative to the extracted archive, nested code before its bundle) is signed with its fixed identifier, the archive's payload metadata (`macPayloadMetadata`, relative to the archive root) is verified before and refreshed after signing, and `sign-evidence.json` is uploaded beside the zip. The job then also checks out the repo and installs dependencies, so `@rightkit/release` 0.2.172 or later must be a dependency. Requires `mac: "sign"`; not combinable with `macEntitlements` (put per-file entitlements in the manifest) or `mac: "notarize"`. Unset keeps the `--deep` lane.
99
- - `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.
140
+ - `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 the check job, 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.
100
141
  - 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.
101
142
 
102
143
  ## Sign an existing artifact (rust-hybrid, `sign-existing` lane)
@@ -146,7 +187,7 @@ Both keys are opt-in; unset, the rendered workflows are byte-identical.
146
187
 
147
188
  ## Dev qualification (rust-hybrid release-candidate)
148
189
 
149
- `candidate.devQualification: { "buildScript": "...", "journeyScript": "..." }` adds a `dev-qualification` job beside the QA-free candidate (Orthic-Labs/rightkit#107). `@rightkit/release` refuses `qa-native`, `qa-control`, `dev-native`, `dev-inspect` and `test-mode` in any release tier, so in-app journeys cannot run against the sealed candidate. The job needs `admission`, uses the candidate's target matrix, checks out the same `source_revision`, runs `buildScript` (the dev build, QA surface on) and then `journeyScript`, and uploads its evidence as `<prefix>-<run>-<attempt>-devqual-<platform>-<arch>-<version>-<revision><suffix>` plus a `dev-qualification` stage summary. When set, `windows-sign` and `macos-sign` need it, so a failure blocks signing. Installed qualification of the signed candidate is unchanged. Unset, the workflow is byte-identical. Validation refuses a candidate build or check script whose name mentions a QA surface and a `devQualification.buildScript` equal to `candidate.buildScript`; it cannot see cargo features inside a script.
190
+ `candidate.devQualification: { "buildScript": "...", "journeyScript": "..." }` adds a `dev-qualification` job beside the QA-free candidate (bogusyogi/rightkit#107). `@rightkit/release` refuses `qa-native`, `qa-control`, `dev-native`, `dev-inspect` and `test-mode` in any release tier, so in-app journeys cannot run against the sealed candidate. The job needs `admission`, uses the candidate's target matrix, checks out the same `source_revision`, runs `buildScript` (the dev build, QA surface on) and then `journeyScript`, and uploads its evidence as `<prefix>-<run>-<attempt>-devqual-<platform>-<arch>-<version>-<revision><suffix>` plus a `dev-qualification` stage summary. When set, `windows-sign` and `macos-sign` need it, so a failure blocks signing. Installed qualification of the signed candidate is unchanged. Unset, the workflow is byte-identical. Validation refuses a candidate build or check script whose name mentions a QA surface and a `devQualification.buildScript` equal to `candidate.buildScript`; it cannot see cargo features inside a script.
150
191
 
151
192
  ## Private Swift packages (ci, qualification, release-candidate, regenerate lanes)
152
193
 
@@ -182,6 +223,38 @@ Never rendered: `package-smoke` (a clean-room tarball check), `publish-npm` and
182
223
 
183
224
  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`).
184
225
 
226
+ ## Named workflows: custom, swift-host and dispatch-matrix
227
+
228
+ The `workflows` block renders named workflow files beside the lane files (`right-git sync`, `drift` and `uninstall` treat them like lane files; the file starts with the managed marker). Each entry has a `kind`. Every kind renders: top-level `permissions: contents: read`, a `private-repo-guard` job that every job needs, actions pinned to commit SHAs, `persist-credentials: false` on every checkout, the shared ownership scan (skipped on Linux runners, which ownership approval does not support) after the pinned package-manager install, and no `secrets` reference. Steps may not mention `secrets` or interpolate untrusted event data (`github.head_ref`, `github.event.pull_request.*` and similar); `workflow_dispatch` inputs reach scripts as `RIGHT_GIT_INPUT_<NAME>` environment variables. The node and package-manager setup, install and ownership steps come from the manifest's `matrix.node[0]` and `packageManager`, so a sparse checkout must keep `package.json`, the lockfile and whatever the install needs (cone mode keeps root files).
229
+
230
+ Common fields: `file` (default `<name>.yml`; never a built-in lane filename), `on` (`push` and `pull_request`: `true` or `{ branches, paths }`; `workflow_dispatch: true`), `concurrency` (`{ group, cancelInProgress }`, rendered as `<group>-${{ github.ref }}`), `checkout` (`{ sparse, longPaths }`, replaces the global `checkout` for this workflow), `timeoutMinutes` (default 60).
231
+
232
+ **`custom`** (Orthic-Labs/rightkit#465): `runsOn` (one label or several, which become a matrix), `toolchain` (`rust`: `stable`, `beta`, `nightly` or an exact version, rendered as the pinned `dtolnay/rust-toolchain` `toolchain:` input; `swift`: see below), `steps` (`{ name?, shell: bash|pwsh, workingDirectory?, run }`) and `artifact` (`{ name, path, retentionDays 1-90 (default 14), ifNoFilesFound error|warn|ignore (default error), when success|always }`). Artifact names accept the tokens `{sha}`, `{run_id}`, `{run_attempt}`, `{os}` and `{matrix.<key>}`; with several runners the name must carry `{os}`.
233
+
234
+ ```json
235
+ { "workflows": { "render-windows": {
236
+ "kind": "custom", "file": "render-windows.yml", "runsOn": "windows-2025",
237
+ "on": { "push": { "branches": ["main"], "paths": ["render/**"] }, "workflow_dispatch": true },
238
+ "concurrency": { "group": "render-windows", "cancelInProgress": false },
239
+ "checkout": { "sparse": ["render"], "longPaths": true },
240
+ "toolchain": { "rust": "1.91.0" },
241
+ "steps": [{ "name": "Unit tests", "shell": "pwsh", "workingDirectory": "render", "run": "cargo test --release" }],
242
+ "artifact": { "name": "swiftright-render-{sha}", "path": "render/target/release/render.dll", "retentionDays": 30 }
243
+ } } }
244
+ ```
245
+
246
+ **`swift-host`** (Orthic-Labs/rightkit#437): `os` (for example `["windows-2025", "macos-15"]`, rendered as a matrix), `packages` (one `swift test` step per package directory), optional `swiftArgs` (plain options such as `--parallel`), `toolchain.swift` (required when `os` has a Windows runner) and an optional `artifact`. `on` defaults to push on the default branch plus `pull_request`.
247
+
248
+ **`dispatch-matrix`** (Orthic-Labs/rightkit#437): `on.workflow_dispatch: true`, `inputs` (`{ description, type string|boolean|choice, default, required, options }`), `plan` (`{ shell, run, runsOn?, workingDirectory? }`; the script writes `matrix=<JSON>` to `$GITHUB_OUTPUT`), `jobs` (up to 6 per-item jobs `{ id, runsOn, toolchain?, steps, artifact? }`, each run once per matrix entry, artifact names carrying `{matrix.<key>}`) and an optional `collect` job (`{ runsOn?, download: { pattern, path }, steps }`, which runs after the item jobs and only when the guard passed).
249
+
250
+ **`swift-toolchain` step** (Orthic-Labs/rightkit#436): `toolchain.swift = { version, sha256 }` renders, on Windows runners only, `<pm> exec right-release toolchain swift --version <v> --sha256 <pin> --github-env`. The installer's sha256 is verified before it runs, and `--github-env` exports what the installer changed to `GITHUB_ENV` and `GITHUB_PATH` for the later steps. The repository must depend on `@rightkit/release` (the same dependency the ownership scan needs). The step builder is exported as `swiftToolchainStep` from `workflows.mjs`.
251
+
252
+ `@rightkit/release`'s `right-git-ci-only` policy accepts only `<lane>.yml` files for the declared lanes, so a repository that declares `workflows` fails its release check until that policy also accepts the files named by `workflows` (needs an update in the release package).
253
+
254
+ ## Fetch CI artifacts
255
+
256
+ `right-git artifacts fetch --run <id> --out <dir>` lists the run's artifacts (`gh api`), keeps those matching `--name` (a glob with `*` and `?`; default all), downloads each by exact name into a staging directory next to `<dir>`, and merges them into `<dir>`. Two artifacts that disagree about a file's bytes fail the fetch. `--repo owner/repo` selects the repository (default: the current checkout's). `--expect-sha256 <hex>` is verified before anything reaches `<dir>`: with `--file <relative path>` it pins that one file (the renderer DLL, for example); without it, the tree digest (sha256 over the sorted lines `<sha256> <path>`). A mismatch, an expired or unsafe-named artifact, a symbolic link or a failed download exits 1 and leaves `<dir>` untouched. `--receipt <file>` writes the JSON receipt (`schema right-git.artifacts-receipt/1`: run, repo, name pattern, per-artifact files with sizes and sha256, `fileCount`, `treeSha256`, `pin`, `verified`); `--json` prints it.
257
+
185
258
  ## Entry points
186
259
 
187
260
  No importable API. The package has no `main` and no `exports` map. The supported surface is the `right-git` bin.
package/artifacts.mjs ADDED
@@ -0,0 +1,290 @@
1
+ // `right-git artifacts fetch`: download the artifacts of one workflow run through `gh`, merge them into one
2
+ // output tree, verify a sha256 pin, and write a JSON receipt (Orthic-Labs/rightkit#439).
3
+ //
4
+ // right-git artifacts fetch --run <id> --out <dir> [--name <glob>] [--repo owner/repo]
5
+ // [--expect-sha256 <hex> [--file <relative path>]] [--receipt <file>]
6
+ //
7
+ // Artifacts are listed first (gh api), filtered by the name glob, then each one is downloaded by its immutable
8
+ // numeric artifact id (gh api .../artifacts/<id>/zip, never by the mutable name) into a staging directory next
9
+ // to <dir>. Nothing reaches <dir> until every artifact downloaded, no two artifacts disagree about a file, the
10
+ // pin matched, and the receipt path does not collide with a fetched file. Files are then placed through
11
+ // no-follow destination checks (a symbolic link in any destination component refuses the fetch). A mismatch
12
+ // removes the staging directory and leaves <dir> as it was.
13
+ //
14
+ // The pin: with --file it is the sha256 of that one file in the merged tree (the renderer DLL, say); without it,
15
+ // the tree digest: sha256 over the lines "<sha256> <relative path>\n" of every file, sorted by path.
16
+
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import crypto from "node:crypto";
20
+ import { execFile as execFileCb } from "node:child_process";
21
+ import { promisify } from "node:util";
22
+
23
+ const execFileAsync = promisify(execFileCb);
24
+ const RUN_ID_RE = /^[0-9]{1,20}$/;
25
+ const NAME_GLOB_RE = /^[A-Za-z0-9._*?-]{1,120}$/;
26
+ const REPO_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}$/;
27
+ const SHA256_RE = /^[0-9a-f]{64}$/;
28
+ const ARTIFACT_NAME_RE = /^[A-Za-z0-9._-]{1,120}$/;
29
+ export const RECEIPT_SCHEMA = "right-git.artifacts-receipt/1";
30
+
31
+ function fail(code, message) {
32
+ const error = new Error(message);
33
+ error.code = code;
34
+ return error;
35
+ }
36
+
37
+ /** Glob (`*`, `?`) to an anchored RegExp. */
38
+ export function globToRegExp(glob) {
39
+ const source = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
40
+ return new RegExp(`^${source}$`);
41
+ }
42
+
43
+ /** Parse and validate argv for `artifacts fetch`. Throws a coded Error on bad input. */
44
+ export function parseFetchArgs(argv) {
45
+ const opts = {};
46
+ for (let i = 0; i < argv.length; i += 1) {
47
+ const arg = argv[i];
48
+ const value = () => {
49
+ if (i + 1 >= argv.length || argv[i + 1].startsWith("--")) throw fail("ARTIFACTS_USAGE", `${arg} needs a value`);
50
+ i += 1;
51
+ return argv[i];
52
+ };
53
+ if (arg === "--run") opts.run = value();
54
+ else if (arg === "--out") opts.out = value();
55
+ else if (arg === "--name") opts.name = value();
56
+ else if (arg === "--repo") opts.repo = value();
57
+ else if (arg === "--expect-sha256") opts.expectSha256 = value().toLowerCase();
58
+ else if (arg === "--file") opts.file = value();
59
+ else if (arg === "--receipt") opts.receipt = value();
60
+ else if (arg === "--json") opts.json = true;
61
+ else throw fail("ARTIFACTS_USAGE", `unknown option: ${arg}`);
62
+ }
63
+ if (!opts.run || !RUN_ID_RE.test(opts.run)) throw fail("ARTIFACTS_USAGE", "--run <numeric run id> is required");
64
+ if (!opts.out) throw fail("ARTIFACTS_USAGE", "--out <dir> is required");
65
+ if (opts.name !== undefined && !NAME_GLOB_RE.test(opts.name)) throw fail("ARTIFACTS_USAGE", "--name must be a glob of letters, digits, '.', '_', '-', '*', '?'");
66
+ if (opts.repo !== undefined && !REPO_RE.test(opts.repo)) throw fail("ARTIFACTS_USAGE", "--repo must be owner/repo");
67
+ if (opts.expectSha256 !== undefined && !SHA256_RE.test(opts.expectSha256)) throw fail("ARTIFACTS_USAGE", "--expect-sha256 must be 64 hex characters");
68
+ if (opts.file !== undefined) {
69
+ if (opts.expectSha256 === undefined) throw fail("ARTIFACTS_USAGE", "--file needs --expect-sha256");
70
+ if (path.isAbsolute(opts.file) || opts.file.split(/[\\/]/).includes("..")) throw fail("ARTIFACTS_USAGE", "--file must be a relative path inside the output tree");
71
+ }
72
+ return opts;
73
+ }
74
+
75
+ /** Refuse when `target` or any existing component between `root` (exclusive) and it is a symbolic link. */
76
+ function assertNoSymlinkPath(root, target) {
77
+ const rel = path.relative(root, target);
78
+ let current = root;
79
+ for (const part of rel.split(path.sep).filter(Boolean)) {
80
+ current = path.join(current, part);
81
+ let stat;
82
+ try {
83
+ stat = fs.lstatSync(current);
84
+ } catch (error) {
85
+ if (error.code === "ENOENT") return;
86
+ throw error;
87
+ }
88
+ if (stat.isSymbolicLink()) throw fail("ARTIFACTS_DEST_SYMLINK", `refusing to write through a symbolic link: ${path.relative(root, current) || current}`);
89
+ }
90
+ }
91
+
92
+ function sha256File(file) {
93
+ const hash = crypto.createHash("sha256");
94
+ hash.update(fs.readFileSync(file));
95
+ return hash.digest("hex");
96
+ }
97
+
98
+ function listFiles(root) {
99
+ const out = [];
100
+ const walk = (dir) => {
101
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
102
+ const full = path.join(dir, entry.name);
103
+ if (entry.isSymbolicLink()) throw fail("ARTIFACTS_SYMLINK", `artifact contains a symbolic link: ${path.relative(root, full)}`);
104
+ if (entry.isDirectory()) walk(full);
105
+ else if (entry.isFile()) out.push(full);
106
+ }
107
+ };
108
+ walk(root);
109
+ return out;
110
+ }
111
+
112
+ /** Digest of a file list [{path, sha256}]: sha256 over sorted "<sha256> <path>\n" lines. */
113
+ export function treeDigest(files) {
114
+ const lines = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)).map((file) => `${file.sha256} ${file.path}\n`);
115
+ return crypto.createHash("sha256").update(lines.join("")).digest("hex");
116
+ }
117
+
118
+ /**
119
+ * Fetch, merge, verify. `deps.execFile(cmd, args, opts)` defaults to child_process.execFile (promisified).
120
+ * Returns the receipt; throws a coded Error on any failure (staging removed, output tree untouched).
121
+ */
122
+ export async function fetchArtifacts(options, deps = {}) {
123
+ const execFile = deps.execFile ?? execFileAsync;
124
+ const out = path.resolve(options.out);
125
+ const repoArg = options.repo ?? "{owner}/{repo}";
126
+ const gh = (args) => execFile("gh", args, { maxBuffer: 64 * 1024 * 1024 });
127
+
128
+ let listed;
129
+ try {
130
+ const { stdout } = await gh(["api", "--paginate", "--slurp", `repos/${repoArg}/actions/runs/${options.run}/artifacts`]);
131
+ const pages = JSON.parse(stdout);
132
+ listed = (Array.isArray(pages) ? pages : [pages]).flatMap((page) => page.artifacts ?? []);
133
+ } catch (error) {
134
+ throw fail("ARTIFACTS_LIST", `gh could not list the artifacts of run ${options.run}: ${String(error.message ?? error).split("\n")[0]}`);
135
+ }
136
+
137
+ const matcher = options.name === undefined ? null : globToRegExp(options.name);
138
+ const matched = listed.filter((artifact) => typeof artifact.name === "string" && (matcher === null || matcher.test(artifact.name)));
139
+ if (matched.length === 0) throw fail("ARTIFACTS_NONE", `run ${options.run} has no artifact matching ${options.name ?? "*"}`);
140
+ for (const artifact of matched) {
141
+ if (!ARTIFACT_NAME_RE.test(artifact.name)) throw fail("ARTIFACTS_NAME", `refusing artifact with an unsafe name: ${JSON.stringify(artifact.name)}`);
142
+ if (artifact.expired === true) throw fail("ARTIFACTS_EXPIRED", `artifact ${artifact.name} of run ${options.run} has expired`);
143
+ }
144
+
145
+ fs.mkdirSync(path.dirname(out), { recursive: true });
146
+ const staging = fs.mkdtempSync(path.join(path.dirname(out), `.${path.basename(out)}.fetch-`));
147
+ try {
148
+ const merged = new Map();
149
+ const perArtifact = [];
150
+ for (const artifact of matched.sort((a, b) => (a.name < b.name ? -1 : 1))) {
151
+ const dir = path.join(staging, "dl", artifact.name);
152
+ fs.mkdirSync(dir, { recursive: true });
153
+ if (!Number.isSafeInteger(artifact.id) || artifact.id <= 0) throw fail("ARTIFACTS_ID", `artifact ${artifact.name} has no numeric id; refusing to download by name`);
154
+ const zip = path.join(staging, `${artifact.id}.zip`);
155
+ try {
156
+ const { stdout } = await execFile("gh", ["api", `repos/${repoArg}/actions/artifacts/${artifact.id}/zip`], { maxBuffer: 1024 * 1024 * 1024, encoding: "buffer" });
157
+ fs.writeFileSync(zip, stdout);
158
+ const [cmd, args] = process.platform === "win32" ? ["tar", ["-xf", zip, "-C", dir]] : ["unzip", ["-q", "-o", zip, "-d", dir]];
159
+ await execFile(cmd, args, { maxBuffer: 64 * 1024 * 1024 });
160
+ } catch (error) {
161
+ throw fail("ARTIFACTS_DOWNLOAD", `could not download artifact ${artifact.name} (id ${artifact.id}): ${String(error.message ?? error).split("\n")[0]}`);
162
+ }
163
+ const zipSha256 = sha256File(zip);
164
+ const files = [];
165
+ for (const file of listFiles(dir)) {
166
+ const rel = path.relative(dir, file).split(path.sep).join("/");
167
+ const digest = sha256File(file);
168
+ const earlier = merged.get(rel);
169
+ if (earlier && earlier.sha256 !== digest) {
170
+ throw fail("ARTIFACTS_CONFLICT", `artifacts ${earlier.artifact} and ${artifact.name} disagree about ${rel}`);
171
+ }
172
+ if (!earlier) merged.set(rel, { sha256: digest, source: file, artifact: artifact.name });
173
+ files.push({ path: rel, sha256: digest, size: fs.statSync(file).size });
174
+ }
175
+ perArtifact.push({ name: artifact.name, id: artifact.id, zipSha256, files });
176
+ }
177
+
178
+ const tree = [...merged.entries()].map(([rel, entry]) => ({ path: rel, sha256: entry.sha256 }));
179
+ const treeSha256 = treeDigest(tree);
180
+ let pinned = null;
181
+ if (options.expectSha256 !== undefined) {
182
+ const subject = options.file === undefined ? "tree" : options.file.split(path.sep).join("/");
183
+ const actual = options.file === undefined ? treeSha256 : merged.get(subject)?.sha256;
184
+ if (actual === undefined) throw fail("ARTIFACTS_PIN_FILE", `--file ${subject} is not in the fetched artifacts`);
185
+ if (actual !== options.expectSha256) {
186
+ throw fail("ARTIFACTS_PIN_MISMATCH", `sha256 pin mismatch for ${options.file ?? "the artifact tree"}: expected ${options.expectSha256}, got ${actual}`);
187
+ }
188
+ pinned = { subject: options.file ?? "tree", expected: options.expectSha256, actual };
189
+ }
190
+
191
+ const receiptPath = options.receipt ? path.resolve(options.receipt) : null;
192
+ if (receiptPath) {
193
+ const key = (value) => path.resolve(value).toLowerCase();
194
+ if (key(receiptPath) === key(out)) throw fail("ARTIFACTS_RECEIPT_COLLISION", "--receipt must not be the output directory");
195
+ if (key(receiptPath).startsWith(`${key(out)}${path.sep}`)) {
196
+ for (const rel of merged.keys()) {
197
+ const target = key(path.join(out, ...rel.split("/")));
198
+ if (target === key(receiptPath) || target.startsWith(`${key(receiptPath)}${path.sep}`)) {
199
+ throw fail("ARTIFACTS_RECEIPT_COLLISION", `--receipt ${options.receipt} collides with fetched file ${rel}; choose a path outside the artifacts`);
200
+ }
201
+ }
202
+ }
203
+ try {
204
+ if (fs.lstatSync(receiptPath).isSymbolicLink()) throw fail("ARTIFACTS_DEST_SYMLINK", `refusing to write the receipt through a symbolic link: ${options.receipt}`);
205
+ } catch (error) {
206
+ if (error.code !== "ENOENT") throw error;
207
+ }
208
+ }
209
+
210
+ let outStat = null;
211
+ try {
212
+ outStat = fs.lstatSync(out);
213
+ } catch (error) {
214
+ if (error.code !== "ENOENT") throw error;
215
+ }
216
+ if (outStat?.isSymbolicLink()) throw fail("ARTIFACTS_DEST_SYMLINK", `refusing to write through a symbolic link: ${out}`);
217
+ // Stage the verified tree fresh, re-verify it, refuse symlinked destinations, then rename each file into place.
218
+ const verifiedTree = path.join(staging, "tree");
219
+ for (const [rel, entry] of merged) {
220
+ const staged = path.join(verifiedTree, ...rel.split("/"));
221
+ fs.mkdirSync(path.dirname(staged), { recursive: true });
222
+ fs.copyFileSync(entry.source, staged, fs.constants.COPYFILE_EXCL);
223
+ if (sha256File(staged) !== entry.sha256) throw fail("ARTIFACTS_CHANGED", `${rel} changed while staging`);
224
+ }
225
+ for (const rel of merged.keys()) assertNoSymlinkPath(out, path.join(out, ...rel.split("/")));
226
+ fs.mkdirSync(out, { recursive: true });
227
+ let counter = 0;
228
+ for (const [rel, entry] of merged) {
229
+ const target = path.join(out, ...rel.split("/"));
230
+ assertNoSymlinkPath(out, path.dirname(target));
231
+ fs.mkdirSync(path.dirname(target), { recursive: true });
232
+ assertNoSymlinkPath(out, path.dirname(target));
233
+ counter += 1;
234
+ const temp = path.join(path.dirname(target), `.${path.basename(target)}.${process.pid}.${counter}.tmp`);
235
+ fs.copyFileSync(path.join(verifiedTree, ...rel.split("/")), temp, fs.constants.COPYFILE_EXCL);
236
+ try {
237
+ if (sha256File(temp) !== entry.sha256) throw fail("ARTIFACTS_CHANGED", `${rel} changed while publishing`);
238
+ assertNoSymlinkPath(out, target);
239
+ fs.renameSync(temp, target);
240
+ } catch (error) {
241
+ fs.rmSync(temp, { force: true });
242
+ throw error;
243
+ }
244
+ }
245
+
246
+ const receipt = {
247
+ schema: RECEIPT_SCHEMA,
248
+ run: options.run,
249
+ repo: options.repo ?? null,
250
+ name: options.name ?? null,
251
+ out,
252
+ artifacts: perArtifact,
253
+ fileCount: merged.size,
254
+ treeSha256,
255
+ pin: pinned,
256
+ verified: pinned !== null,
257
+ };
258
+ if (receiptPath) {
259
+ fs.mkdirSync(path.dirname(receiptPath), { recursive: true });
260
+ fs.writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`, "utf8");
261
+ }
262
+ return receipt;
263
+ } finally {
264
+ fs.rmSync(staging, { recursive: true, force: true });
265
+ }
266
+ }
267
+
268
+ /** CLI entry: argv after `artifacts`. Returns the process exit code. */
269
+ export async function artifactsCommand(argv, deps = {}, io = { log: console.log, error: console.error }) {
270
+ const [sub, ...rest] = argv;
271
+ if (sub !== "fetch") {
272
+ io.error("right-git artifacts fetch --run <id> --out <dir> [--name <glob>] [--repo owner/repo] [--expect-sha256 <hex> [--file <path>]] [--receipt <file>] [--json]");
273
+ return 2;
274
+ }
275
+ let options;
276
+ try {
277
+ options = parseFetchArgs(rest);
278
+ } catch (error) {
279
+ io.error(`right-git artifacts: ${error.message}`);
280
+ return 2;
281
+ }
282
+ try {
283
+ const receipt = await fetchArtifacts(options, deps);
284
+ io.log(options.json ? JSON.stringify(receipt, null, 2) : `right-git artifacts: fetched ${receipt.artifacts.length} artifact(s), ${receipt.fileCount} file(s) into ${receipt.out} (tree sha256 ${receipt.treeSha256}${receipt.verified ? ", pin verified" : ""})`);
285
+ return 0;
286
+ } catch (error) {
287
+ io.error(`right-git artifacts: ${error.code ?? "ERROR"}: ${error.message}`);
288
+ return 1;
289
+ }
290
+ }
package/cli/right-git.mjs CHANGED
@@ -6,6 +6,7 @@ import { syncCommand } from "../sync.mjs";
6
6
  import { driftCommand, driftAll } from "../drift.mjs";
7
7
  import { adoptCommand } from "../adopt.mjs";
8
8
  import { uninstallCommand } from "../uninstall.mjs";
9
+ import { artifactsCommand } from "../artifacts.mjs";
9
10
 
10
11
  const commands = new Map([
11
12
  ["install", runInstall],
@@ -13,6 +14,7 @@ const commands = new Map([
13
14
  ["drift", runDrift],
14
15
  ["adopt", runAdopt],
15
16
  ["uninstall", runUninstall],
17
+ ["artifacts", (argv) => artifactsCommand(argv)],
16
18
  ]);
17
19
 
18
20
  // F7 fix: flags that are always boolean and must never consume the next
@@ -30,20 +32,28 @@ const BOOLEAN_ONLY_FLAGS = new Set(["all"]);
30
32
  const args = process.argv.slice(2);
31
33
  const first = args[0];
32
34
 
35
+ // process.exit() ends the process with whatever stdout and stderr still have queued: on a pipe that had not been read yet (`right-git sync
36
+ // --dry-run | tee log`, a CI log collector) the end of the diff and the result line were lost. A write of nothing completes only after
37
+ // everything written before it, so waiting for both streams puts all output out before the exit code is returned.
38
+ function exitAfterFlush(code) {
39
+ const flushed = (stream) => new Promise((resolve) => stream.write("", resolve));
40
+ return Promise.all([flushed(process.stdout), flushed(process.stderr)]).then(() => process.exit(code));
41
+ }
42
+
33
43
  if (!first || first === "-h" || first === "--help") {
34
44
  printHelp();
35
- process.exit(first ? 0 : 1);
45
+ await exitAfterFlush(first ? 0 : 1);
36
46
  } else if (first === "--version" || first === "-v") {
37
47
  const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
38
48
  console.log(pkg.version);
39
- process.exit(0);
49
+ await exitAfterFlush(0);
40
50
  } else if (commands.has(first)) {
41
51
  const exitCode = await commands.get(first)(args.slice(1));
42
- process.exit(exitCode);
52
+ await exitAfterFlush(exitCode);
43
53
  } else {
44
54
  console.error(`right-git: unknown command: ${first}\n`);
45
55
  printHelp();
46
- process.exit(2);
56
+ await exitAfterFlush(2);
47
57
  }
48
58
 
49
59
  /** Split argv into positional args and --flag / --flag=value pairs. */
@@ -75,6 +85,12 @@ function printErrors(errors) {
75
85
  for (const error of errors || []) console.error(` ${error}`);
76
86
  }
77
87
 
88
+ // A sync or install warning (a @rightkit/release pin the rendered check job cannot be proved to have) is printed beside the result,
89
+ // to stderr like an error, and never changes the exit code.
90
+ function printWarnings(warnings) {
91
+ for (const warning of warnings || []) console.error(` warn: ${warning}`);
92
+ }
93
+
78
94
  // Advisory lines never change drift's exit code: warnings are settings to fix,
79
95
  // notes are checks that could not run here.
80
96
  function printAdvisories(result) {
@@ -102,8 +118,10 @@ async function runInstall(argv) {
102
118
  if (!result.ok) {
103
119
  console.error(`right-git install: failed at stage '${result.stage}'`);
104
120
  printErrors(result.errors);
121
+ printWarnings(result.plan?.warnings);
105
122
  return 1;
106
123
  }
124
+ printWarnings(result.plan.warnings);
107
125
  console.log(`right-git install: wrote ${result.manifestPath} and synced ${result.plan.changes.length} workflow file(s).`);
108
126
  return 0;
109
127
  }
@@ -119,8 +137,10 @@ async function runSync(argv) {
119
137
  if (!result.ok) {
120
138
  console.error(`right-git sync: failed at stage '${result.stage}'`);
121
139
  printErrors(result.errors);
140
+ printWarnings(result.warnings);
122
141
  return 1;
123
142
  }
143
+ printWarnings(result.warnings);
124
144
  const changed = result.changes.filter((c) => c.action !== "unchanged");
125
145
  console.log(changed.length === 0 ? "right-git sync: already up to date." : `right-git sync: ${changed.length} file(s) ${flags["dry-run"] ? "would change" : "changed"}.`);
126
146
  return 0;
@@ -213,6 +233,8 @@ Commands:
213
233
  drift --all [workspace-root] Drift-check + re-check visibility for every managed repo found
214
234
  adopt <repo-path> [--out <dir>] Map an existing repo's workflows onto right-git lanes for review
215
235
  uninstall <repo-path> Remove every right-git-managed workflow file
236
+ artifacts fetch --run <id> --out <dir> [--name <glob>] [--repo owner/repo] [--expect-sha256 <hex> [--file <path>]] [--receipt <file>] [--json]
237
+ Download a run's artifacts via gh, merge them, verify the sha256 pin, write a JSON receipt
216
238
 
217
239
  Public-repo only: install/sync refuse private, internal, or unconfirmed-visibility repos. No override flag (invariant I1).`);
218
240
  }
package/install.mjs CHANGED
@@ -12,7 +12,7 @@ import { MANIFEST_FILENAME, validateManifest } from "./manifest.mjs";
12
12
  import { applyPlan, planSync } from "./sync.mjs";
13
13
 
14
14
  export const DEFAULT_MATRIX = { os: ["ubuntu-latest", "macos-latest", "windows-latest"], node: ["22.13", "24"] };
15
- export const DEFAULT_PACKAGE_MANAGER = "pnpm@11.24.0";
15
+ export const DEFAULT_PACKAGE_MANAGER = "pnpm@11.25.0";
16
16
  export const DEFAULT_TEMPLATE_VERSION = "1.8.0";
17
17
 
18
18
  /**