@rightkit/release 0.6.39 → 0.6.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.
Files changed (86) hide show
  1. package/README.md +110 -11
  2. package/admission-files.mjs +40 -0
  3. package/admission-host.mjs +2 -1
  4. package/app-check.mjs +303 -16
  5. package/app-closure.mjs +6 -4
  6. package/bin/rightkit-gate.mjs +177 -32
  7. package/cargo-contract.mjs +17 -31
  8. package/cargo-license-notices.mjs +129 -19
  9. package/cargo-target-shim.mjs +14 -0
  10. package/carried-cargo.mjs +2 -4
  11. package/cli/right-release.mjs +24 -2
  12. package/cross-targets.mjs +24 -0
  13. package/deterministic-scans.mjs +167 -58
  14. package/development-signing.mjs +25 -2
  15. package/development.mjs +34 -1
  16. package/direct-release-command.mjs +154 -0
  17. package/disk-policy.mjs +16 -0
  18. package/feature-coverage.mjs +134 -0
  19. package/gate-coverage.mjs +38 -0
  20. package/gate-stages.mjs +1 -0
  21. package/ghsa-audit.mjs +95 -0
  22. package/install-app.mjs +33 -5
  23. package/install-channels.mjs +301 -0
  24. package/interactive-session-run.mjs +105 -0
  25. package/legal-contract.mjs +10 -1
  26. package/legion-freeze-consumer.mjs +241 -0
  27. package/linux-publish.mjs +136 -0
  28. package/local-publish.mjs +31 -7
  29. package/nsis-pack.mjs +95 -0
  30. package/nsis-upgrade-template.mjs +93 -0
  31. package/outdated-command.mjs +19 -0
  32. package/ownership-class-rules.mjs +32 -10
  33. package/ownership-mandatory-set.json +23 -0
  34. package/ownership-mandatory-set.mjs +66 -8
  35. package/package-recipe-targets.mjs +54 -19
  36. package/package.json +1 -1
  37. package/payload-root-install.mjs +123 -0
  38. package/plugin-delivery.mjs +141 -0
  39. package/prebuild-gates.mjs +8 -4
  40. package/preflight.mjs +6 -1
  41. package/provision-model-bundle.mjs +172 -0
  42. package/pub-upload.mjs +1 -1
  43. package/publish-local-npm.mjs +34 -9
  44. package/publish-retention.mjs +106 -0
  45. package/publish-update.mjs +15 -8
  46. package/qa-build-features.mjs +24 -15
  47. package/qa-contract.mjs +5 -6
  48. package/qa-control-scan.mjs +14 -0
  49. package/qa-web-pairing.mjs +76 -0
  50. package/r2-s3-multipart.mjs +190 -0
  51. package/r2-verified-upload.mjs +28 -16
  52. package/recipe-build.mjs +53 -3
  53. package/release-checks.mjs +53 -2
  54. package/release-config.mjs +8 -3
  55. package/release-invocation.mjs +12 -2
  56. package/release-pin-floor.mjs +44 -0
  57. package/release-qa-audit.mjs +18 -2
  58. package/release-qa-command.mjs +17 -1
  59. package/release-qa-policy.mjs +30 -3
  60. package/release-switch-cfg.mjs +271 -0
  61. package/release-switch-registry.json +60 -1
  62. package/release-switch-scan.mjs +398 -23
  63. package/release.mjs +97 -6
  64. package/render-views.mjs +141 -0
  65. package/rightkit-registry-resolver.mjs +1 -1
  66. package/rightkit-versions.json +568 -491
  67. package/runtime-artifact-manifest.mjs +9 -0
  68. package/runtime-manifest-refresh.mjs +88 -0
  69. package/rustright-stage.mjs +197 -0
  70. package/scan-digest.mjs +15 -9
  71. package/scan-tool-enrolment.mjs +1 -1
  72. package/security-policy.mjs +196 -0
  73. package/shell-contract.mjs +32 -0
  74. package/snapshot-broker.mjs +8 -1
  75. package/snapshot-check.mjs +58 -0
  76. package/snapshot-request.mjs +25 -2
  77. package/stage-commands.mjs +33 -4
  78. package/stage-ledger.mjs +6 -1
  79. package/stage-receipt.mjs +115 -0
  80. package/stage-sidecar.mjs +188 -17
  81. package/stage-xcframework.mjs +118 -0
  82. package/suite-api.generated.mjs +16 -1
  83. package/unit-gate.mjs +14 -2
  84. package/upload-large.mjs +4 -4
  85. package/upload-release.mjs +6 -0
  86. package/win-package-recipe.mjs +26 -4
package/stage-sidecar.mjs CHANGED
@@ -5,13 +5,13 @@
5
5
  // that script, driven by a `sidecars` list in right-release.config.mjs:
6
6
  //
7
7
  // sidecars: [
8
- // { kind: "cargo-bin", package: "mailright-engine", bin?, name?, profile?: "release" | { dev, release }, features?, manifestPath?, sha256?, dest?, clean?, platforms? },
8
+ // { kind: "cargo-bin", package: "mailright-engine", bin?, name?, profile?: "release" | { dev, release }, features?, manifestPath? (app-relative, or ../.. to a Cargo.toml inside the same repository), sha256?, dest?, clean?, platforms? },
9
9
  // { kind: "ffmpeg", variant?, variants?, tools?, notices: { dir, sourceOfferContact }, catalog, stage?, bundleDir?, resourceDir?, sources?, probe? },
10
10
  // { kind: "onnxruntime", version, catalog, resourceDir?: "src-tauri/resources/runtime", as?, licenseDir?, cacheDir?, companions? }, // the alias of native-library { library: "onnxruntime" }
11
11
  // { kind: "native-library", library: "onnxruntime" | "directml" | "pdfium" | "whisper-cpp" | "ggml" | "sherpa-onnx", version, catalog, resourceDir?, licenseDir?, cacheDir?, as?, files?, companions?, source?: { dir }, platforms? },
12
12
  // { kind: "resource", from, to, sha256?, machO?, clean?, platforms? }, // `from` may be a directory (copied recursively, every file hashed)
13
- // { kind: "command", name, cmd, args?, cwd?, output, externalBin: true | (false with dest), dest?, clean?, platforms? },
14
- // { kind: "remote", name, url (https), sha256, dest | to, size?, extract?, memberSha256?, executable?, clean?, platforms? },
13
+ // { kind: "command", name, cmd, args?, cwd?, output (a file, or a directory with dest), externalBin: true | (false with dest), dest?, sha256? (pins a file output), clean?, platforms? },
14
+ // { kind: "remote", name, url (https), sha256 | latest: { checksums (https), file? } (dev builds only), dest | to, size?, extract? | extractTree? (a whole archive tree into dest: Chrome for Testing), memberSha256?, executable?, clean?, platforms? },
15
15
  // { kind: "cmake", name, repo (https), commit (40 hex), target?, output?, cmakeArgs?, platformArgs?, generator?, platformGenerators?, architecture?, cmakeBin?, smoke?, sha256?, dest?, clean?, platforms? },
16
16
  // { kind: "prebuilt", name, from? (a path, or { aarch64, x86_64 } for universal-apple-darwin), manifest: { file, entry, sha256?, approvalSha256?, approvalAlgorithm? }, dest?, platforms? },
17
17
  // ]
@@ -48,6 +48,7 @@ import {
48
48
  import { ContentDigestError, contentIdentity, digestFor } from "./content-digest.mjs";
49
49
  import { oneOutput } from "./cross-targets.mjs";
50
50
 
51
+ export { readVerifiedStageReceipt, assertStageReceiptGuard } from "./stage-receipt.mjs";
51
52
  export const STAGE_SIDECAR_CONTRACT = "rightkit-stage-sidecar-v1";
52
53
  export const STAGE_SIDECAR_RECEIPT_NAME = "stage-sidecar.json";
53
54
  export const DEFAULT_STAGE_DIR = "src-tauri/binaries";
@@ -113,8 +114,8 @@ const KEYS = Object.freeze({
113
114
  onnxruntime: ["kind", "version", "catalog", "resourceDir", "as", "licenseDir", "cacheDir", "companions", "platforms"],
114
115
  "native-library": ["kind", "library", "version", "catalog", "resourceDir", "licenseDir", "cacheDir", "as", "files", "companions", "source", "platforms"],
115
116
  resource: ["kind", "from", "to", "sha256", "machO", "clean", "platforms"],
116
- command: ["kind", "name", "cmd", "args", "cwd", "output", "externalBin", "dest", "clean", "platforms"],
117
- remote: ["kind", "name", "url", "sha256", "dest", "to", "size", "extract", "extractKind", "memberSha256", "executable", "clean", "platforms"],
117
+ command: ["kind", "name", "cmd", "args", "cwd", "output", "externalBin", "dest", "sha256", "clean", "platforms"],
118
+ remote: ["kind", "name", "url", "sha256", "latest", "dest", "to", "size", "extract", "extractTree", "extractKind", "memberSha256", "executable", "clean", "platforms"],
118
119
  cmake: ["kind", "name", "repo", "commit", "target", "output", "cmakeArgs", "platformArgs", "generator", "platformGenerators", "architecture", "cmakeBin", "smoke", "sha256", "dest", "clean", "platforms"],
119
120
  prebuilt: ["kind", "name", "from", "manifest", "dest", "platforms"],
120
121
  });
@@ -158,6 +159,46 @@ function relativePath(value, label, errors, { allowRoot = false } = {}) {
158
159
  return normalized.replace(/\/+$/, "");
159
160
  }
160
161
 
162
+ /**
163
+ * A cargo-bin `manifestPath`: app-relative like every path here, or (rightkit#1247) a path that climbs out of the app with `..` to the Cargo.toml of
164
+ * a workspace elsewhere in the SAME repository (CodeRight's engine at ../../engine). The latter must name a `Cargo.toml`; whether the climb stays
165
+ * inside the repository is judged against the repository root at stage time (`manifestFileOf`), so a manifest outside it is still refused.
166
+ */
167
+ function manifestPathOf(value, label, errors) {
168
+ if (typeof value === "string" && !path.isAbsolute(value) && !/^[A-Za-z]:/.test(value) && value.replaceAll("\\", "/").split("/").includes("..")) {
169
+ const normalized = path.posix.normalize(value.replaceAll("\\", "/"));
170
+ if (!/(^|\/)Cargo\.toml$/.test(normalized)) { errors.push(`${label} must name a Cargo.toml when it leaves the app: ${value}`); return undefined; }
171
+ return normalized;
172
+ }
173
+ return relativePath(value, label, errors);
174
+ }
175
+
176
+ /** The repository root above the app: the nearest ancestor of `start` holding a `.git` entry (a directory, or a file for a linked checkout). Undefined when there is none. */
177
+ function repositoryRootOf(fs, start) {
178
+ for (let current = path.resolve(start); ; current = path.dirname(current)) {
179
+ if (fs.existsSync(path.join(current, ".git"))) return current;
180
+ if (path.dirname(current) === current) return undefined;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * The absolute manifest of a cargo-bin entry. A path with `..` must resolve inside the repository (the real path, so a link cannot reach outside) and name
186
+ * a file that exists; with no repository root above the app (no `.git`) it is refused rather than guessed.
187
+ */
188
+ function manifestFileOf(ctx, entry) {
189
+ if (!entry.manifestPath) return undefined;
190
+ const file = path.resolve(ctx.appRoot, entry.manifestPath);
191
+ if (!entry.manifestPath.split("/").includes("..")) return file;
192
+ const { fs } = ctx;
193
+ const root = repositoryRootOf(fs, ctx.appRoot) ?? (ctx.cacheRoot ? repositoryRootOf(fs, ctx.cacheRoot) : undefined);
194
+ if (!root) fail("STAGE_SIDECAR_CONFIG_INVALID", `cargo-bin ${entry.package}: manifestPath ${entry.manifestPath} leaves the app, and no repository root (.git) was found above ${ctx.appRoot} to bound it`, { package: entry.package });
195
+ if (!fs.existsSync(file)) fail("STAGE_SIDECAR_CONFIG_INVALID", `cargo-bin ${entry.package}: manifestPath ${entry.manifestPath} does not exist (${file})`, { package: entry.package });
196
+ const real = (value) => (typeof fs.realpathSync === "function" ? fs.realpathSync(value) : value);
197
+ const inside = path.relative(real(root), real(file));
198
+ if (inside === "" || inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) fail("STAGE_SIDECAR_CONFIG_INVALID", `cargo-bin ${entry.package}: manifestPath ${entry.manifestPath} resolves outside the repository ${root}`, { package: entry.package });
199
+ return file;
200
+ }
201
+
161
202
  /** A relative output path in comparison form: no "." or empty segments, lower case (Windows and macOS are case-insensitive). */
162
203
  const canonicalOutput = (value) => String(value).replaceAll("\\", "/").split("/").filter((segment) => segment !== "" && segment !== ".").join("/").toLowerCase();
163
204
  /** The claim in `claimed` that `key` equals, contains or sits inside (outputs may not be nested inside each other). */
@@ -385,7 +426,7 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
385
426
  if (badList(item.features ?? [])) errors.push(`${where}: features must be a list of feature names (package/feature allowed)`);
386
427
  if (badList(devFeatures)) errors.push(`${where}: devFeatures must be a list of feature names (package/feature allowed)`);
387
428
  const features = [...(item.features ?? []), ...(mode === "dev" && Array.isArray(devFeatures) ? devFeatures : [])];
388
- const manifestPath = item.manifestPath === undefined ? undefined : relativePath(item.manifestPath, `${where}: manifestPath`, errors);
429
+ const manifestPath = item.manifestPath === undefined ? undefined : manifestPathOf(item.manifestPath, `${where}: manifestPath`, errors);
389
430
  sha(item.sha256, "sha256");
390
431
  const dest = destOf(item.dest);
391
432
  const clean = cleanOf();
@@ -473,20 +514,49 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
473
514
  const output = relativePath(item.output, `${where}: output`, errors);
474
515
  const dest = destOf(item.dest);
475
516
  const clean = cleanOf();
517
+ sha(item.sha256, "sha256");
476
518
  if (dest) { if (item.externalBin === true) errors.push(`${where}: externalBin must be false or omitted with dest (a dest file is not staged as <name>-<triple>)`); }
477
519
  else if (item.externalBin !== true) errors.push(`${where}: externalBin must be true (the output is staged as <name>-<triple>)`);
478
520
  if (!skipped) { if (dest) claim(dest, where); else if (typeof name === "string" && stageDir) claim(stagedClaim(name), where); }
479
- Object.assign(entry, { name, cmd: item.cmd, args: Array.isArray(args) ? [...args] : [], ...(cwd ? { cwd } : {}), output, ...(dest ? { dest } : {}), ...(clean ? { clean } : {}) });
521
+ Object.assign(entry, { name, cmd: item.cmd, args: Array.isArray(args) ? [...args] : [], ...(cwd ? { cwd } : {}), output, ...(item.sha256 ? { sha256: item.sha256 } : {}), ...(dest ? { dest } : {}), ...(clean ? { clean } : {}) });
480
522
  } else if (item.kind === "remote") {
481
523
  const name = item.name;
482
524
  if (typeof name !== "string" || !NAME.test(name)) errors.push(`${where}: name must be a bare label`);
483
525
  if (typeof item.url !== "string" || !/^https:\/\/[^\s/]+\/\S*$/.test(item.url)) errors.push(`${where}: url must be an https:// URL (no other scheme is fetched)`);
484
- if (typeof item.sha256 !== "string" || !SHA256.test(item.sha256)) errors.push(`${where}: sha256 is required and must be a lowercase 64-hex SHA-256`);
526
+ // `latest` (rightkit#753): for a tool that updates itself (yt-dlp), a DEV stage may follow the publisher's latest release. The digest is not
527
+ // dropped: it is read from the publisher's checksum list (an https file of `<sha256> <name>` lines), compared with the download, and recorded
528
+ // in the receipt, so a release can pin it. A release never stages an unpinned download.
529
+ let latest;
530
+ if (item.latest !== undefined) {
531
+ if (item.sha256 !== undefined) errors.push(`${where}: give sha256 or latest, not both`);
532
+ if (!isObject(item.latest)) errors.push(`${where}: latest must be { checksums, file? }`);
533
+ else {
534
+ for (const key of Object.keys(item.latest)) if (!["checksums", "file"].includes(key)) errors.push(`${where}: latest: unknown key ${JSON.stringify(key)} (allowed: checksums, file)`);
535
+ if (typeof item.latest.checksums !== "string" || !/^https:\/\/[^\s/]+\/\S*$/.test(item.latest.checksums)) errors.push(`${where}: latest.checksums must be an https:// URL of the publisher's SHA-256 list`);
536
+ if (item.latest.file !== undefined && (typeof item.latest.file !== "string" || !item.latest.file || /[\\/\s]/.test(item.latest.file))) errors.push(`${where}: latest.file must be the bare file name listed in the checksum file (default: the last segment of url)`);
537
+ if (item.extract !== undefined || item.extractKind !== undefined) errors.push(`${where}: latest cannot be combined with extract (an archive is pinned by sha256)`);
538
+ if (mode !== "dev" && !skipped) errors.push(`${where}: latest is a dev-only policy (RIGHTKIT_BUILD_MODE=dev); a release build pins sha256 (the dev stage records the resolved digest in the receipt)`);
539
+ latest = { checksums: item.latest.checksums, ...(item.latest.file ? { file: item.latest.file } : {}) };
540
+ }
541
+ } else if (typeof item.sha256 !== "string" || !SHA256.test(item.sha256)) errors.push(`${where}: sha256 is required (or latest, in a dev build) and must be a lowercase 64-hex SHA-256`);
485
542
  if (item.dest !== undefined && item.to !== undefined) errors.push(`${where}: give dest or to, not both`);
486
543
  if (item.dest === undefined && item.to === undefined) errors.push(`${where}: dest (or to) is required`);
487
544
  const dest = destOf(item.dest ?? item.to, item.dest === undefined ? "to" : "dest");
488
545
  if (item.size !== undefined && (!Number.isSafeInteger(item.size) || item.size <= 0)) errors.push(`${where}: size must be a positive integer (bytes)`);
489
546
  if (item.extract !== undefined) { const member = normalizeArchiveMember(item.extract); if (member.error || (!member.byPath && !NAME.test(member.value))) errors.push(`${where}: extract must be the bare file name of one archive member or its archive path (posix, no leading /, no .. segment): ${member.error ?? "invalid file name"}`); }
547
+ let extractTree;
548
+ if (item.extractTree !== undefined) {
549
+ // A whole archive tree (Chrome for Testing, a browser or runtime bundle): the archive digest is the pin, every extracted file is hashed into the receipt.
550
+ if (item.extract !== undefined || item.extractKind !== undefined || item.memberSha256 !== undefined || item.executable !== undefined) errors.push(`${where}: extractTree cannot be combined with extract, extractKind, memberSha256 or executable`);
551
+ if (item.latest !== undefined) errors.push(`${where}: extractTree needs a pinned sha256, not latest`);
552
+ if (item.extractTree === true || item.extractTree === ".") extractTree = ".";
553
+ else if (typeof item.extractTree === "string") {
554
+ const root = normalizeArchiveMember(item.extractTree.replace(/\/+$/, ""));
555
+ if (root.error) errors.push(`${where}: extractTree must be true (the whole archive) or the directory inside the archive to stage (posix, no leading /, no .. segment): ${root.error}`);
556
+ else extractTree = root.value;
557
+ } else errors.push(`${where}: extractTree must be true or an archive directory path`);
558
+ if (item.dest === undefined && item.to === undefined) errors.push(`${where}: extractTree needs dest (the directory the tree is staged into)`);
559
+ }
490
560
  if (item.memberSha256 !== undefined && (item.extract === undefined || !SHA256.test(item.memberSha256 ?? ""))) errors.push(`${where}: memberSha256 must be a lowercase 64-hex SHA-256 and needs extract`);
491
561
  if (item.extractKind !== undefined && item.extractKind !== "nsis") errors.push(`${where}: extractKind must be "nsis" (omit it for tar-readable zip/tgz/nupkg archives)`);
492
562
  if (item.extractKind === "nsis") {
@@ -496,7 +566,7 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
496
566
  if (item.executable !== undefined && typeof item.executable !== "boolean") errors.push(`${where}: executable must be a boolean`);
497
567
  const clean = cleanOf();
498
568
  if (dest && !skipped) claim(dest, where);
499
- Object.assign(entry, { name, url: item.url, sha256: item.sha256, dest, ...(item.extractKind ? { extractKind: item.extractKind } : {}), ...(item.size ? { size: item.size } : {}), ...(item.extract ? { extract: item.extract } : {}), ...(item.memberSha256 ? { memberSha256: item.memberSha256 } : {}), ...(item.executable ? { executable: true } : {}), ...(clean ? { clean } : {}) });
569
+ Object.assign(entry, { name, url: item.url, ...(latest ? { latest } : { sha256: item.sha256 }), dest, ...(item.extractKind ? { extractKind: item.extractKind } : {}), ...(item.size ? { size: item.size } : {}), ...(item.extract ? { extract: item.extract } : {}), ...(extractTree ? { extractTree } : {}), ...(item.memberSha256 ? { memberSha256: item.memberSha256 } : {}), ...(item.executable ? { executable: true } : {}), ...(clean ? { clean } : {}) });
500
570
  } else if (item.kind === "cmake") {
501
571
  const name = item.name;
502
572
  if (typeof name !== "string" || !NAME.test(name) || /\.exe$/i.test(name) || name !== path.basename(name)) errors.push(`${where}: name must be a bare sidecar name (no path, no .exe, no target triple)`);
@@ -574,7 +644,7 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
574
644
  if (hit) errors.push(`${label} writes ${output}, which is or contains ${hit}; stage-sidecar never overwrites or cleans the app's stage directory, receipt, cache, .git, src, src-tauri, node_modules or package.json`);
575
645
  }
576
646
  if (errors.length) fail("STAGE_SIDECAR_CONFIG_INVALID", `invalid sidecars configuration:\n${errors.map((line) => `- ${line}`).join("\n")}`, { errors });
577
- return { target: t, stageDir, receiptPath, wipeStageDir: wrapper.wipeStageDir === true, entries, claims: claimed };
647
+ return { target: t, mode, stageDir, receiptPath, wipeStageDir: wrapper.wipeStageDir === true, entries, claims: claimed };
578
648
  }
579
649
 
580
650
  const sha256Of = (bytes) => createHash("sha256").update(bytes).digest("hex");
@@ -639,6 +709,27 @@ export function defaultExtractMember({ archive, fileName, destDir, run = default
639
709
  return out;
640
710
  }
641
711
 
712
+ /**
713
+ * Extract a whole archive (zip, tgz) into `destDir` and return the directory to stage: `<destDir>/<root>` for an `extractTree` of a sub directory, else `destDir`.
714
+ * The member list is read first and refused when any member is absolute, has a `..` segment or a drive prefix, so nothing can land outside `destDir`.
715
+ */
716
+ export function defaultExtractTree({ archive, root = ".", destDir, run = defaultRun, tar = archiveTar() }) {
717
+ const listing = run(tar, ["-tf", archive], { cwd: path.dirname(archive) });
718
+ if (listing.status !== 0) fail("STAGE_SIDECAR_EXTRACT_FAILED", `cannot list ${archive}`);
719
+ const lines = String(listing.stdout).split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
720
+ if (!lines.length) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${archive} is empty`);
721
+ for (const line of lines) {
722
+ const member = line.startsWith("./") ? line.slice(2) : line;
723
+ if (member.startsWith("/") || /^[A-Za-z]:/.test(member) || member.includes("\\") || member.split("/").includes("..")) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${archive} has an unsafe member ${JSON.stringify(line)}; nothing staged`);
724
+ }
725
+ const extracted = run(tar, ["-xf", archive, "-C", destDir], { cwd: path.dirname(archive) });
726
+ if (extracted.status !== 0) fail("STAGE_SIDECAR_EXTRACT_FAILED", `cannot extract ${archive}`);
727
+ const out = root === "." ? destDir : path.join(destDir, ...root.split("/"));
728
+ const inside = path.relative(path.resolve(destDir), path.resolve(out));
729
+ if (inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${root} of ${archive} resolves outside the extraction directory`);
730
+ return out;
731
+ }
732
+
642
733
  /** 7-Zip candidates: an explicit path (deps.sevenZip or RIGHTKIT_SEVEN_ZIP), then `7z` on PATH, then 7z.exe under Program Files on win32. */
643
734
  export function sevenZipCandidates({ explicit, env = process.env, platform = process.platform } = {}) {
644
735
  const list = [];
@@ -991,7 +1082,8 @@ function stageCargoSlice(entry, ctx, triple, { dest }) {
991
1082
  function stageCargoBuild(entry, ctx, triple) {
992
1083
  const { run, appRoot, env, fs } = ctx;
993
1084
  // One output directory (oneOutput, cross-targets.mjs): a sidecar always builds with the release profile, whatever profile its entry names.
994
- const args = oneOutput(["cargo", "build", "--locked", ...(entry.manifestPath ? ["--manifest-path", path.resolve(appRoot, entry.manifestPath)] : []),
1085
+ const manifestFile = manifestFileOf(ctx, entry);
1086
+ const args = oneOutput(["cargo", "build", "--locked", ...(manifestFile ? ["--manifest-path", manifestFile] : []),
995
1087
  "-p", entry.package, "--bin", entry.bin, "--target", triple,
996
1088
  ...(entry.features.length ? ["--features", entry.features.join(",")] : []), "--message-format=json-render-diagnostics"]);
997
1089
  ctx.log(`stage-sidecar: rightkit ${args.join(" ")}`);
@@ -1003,7 +1095,7 @@ function stageCargoBuild(entry, ctx, triple) {
1003
1095
  // the directory the binary is read from is the signed receipt's `outputDir`, never a carrier-less `cargo metadata`.
1004
1096
  const carried = Boolean(carriedCargoMapOf(env)?.map);
1005
1097
  if (ctx.split && !carried) {
1006
- const pinned = snapshotTargetDirectory(ctx, env, entry.manifestPath ? path.resolve(appRoot, entry.manifestPath) : null);
1098
+ const pinned = snapshotTargetDirectory(ctx, env, manifestFile ?? null);
1007
1099
  if (!pinned.dir) fail("STAGE_SIDECAR_BUILD_FAILED", `the cargo output directory for ${entry.package} cannot be resolved from the snapshot (${pinned.error}); nothing was built`, { package: entry.package });
1008
1100
  buildEnv = { ...env, CARGO_TARGET_DIR: pinned.dir };
1009
1101
  }
@@ -1017,7 +1109,7 @@ function stageCargoBuild(entry, ctx, triple) {
1017
1109
  source = candidates.find((file) => fs.existsSync(file));
1018
1110
  if (!source) fail("STAGE_SIDECAR_BINARY_NOT_FOUND", `the build did not produce ${entry.bin} (looked in ${candidates.join(", ")})`, { bin: entry.bin, candidates });
1019
1111
  } else if (!source || !fs.existsSync(source)) {
1020
- const meta = run("rustright", ["cargo", "metadata", "--format-version", "1", "--no-deps", ...(entry.manifestPath ? ["--manifest-path", path.resolve(appRoot, entry.manifestPath)] : [])], { cwd: appRoot, env: buildEnv });
1112
+ const meta = run("rustright", ["cargo", "metadata", "--format-version", "1", "--no-deps", ...(manifestFile ? ["--manifest-path", manifestFile] : [])], { cwd: appRoot, env: buildEnv });
1021
1113
  let targetDir;
1022
1114
  try { targetDir = JSON.parse(meta.stdout).target_directory; } catch { /* refused below */ }
1023
1115
  if (meta?.status !== 0 || typeof targetDir !== "string" || !path.isAbsolute(targetDir)) targetDir = undefined;
@@ -1611,6 +1703,25 @@ function stageResource(entry, ctx) {
1611
1703
  return [{ kind: "resource", name: path.basename(dest), path: rel(ctx, dest), ...copied, sourceSha256: actual, from: entry.from, externalBin: false }];
1612
1704
  }
1613
1705
 
1706
+ /** A `command` entry whose output is a directory: needs `dest`, takes no sha256 pin, and stages every file under it (one receipt row each). */
1707
+ function stageCommandDirectory(entry, ctx, source) {
1708
+ const { appRoot, fs } = ctx;
1709
+ if (!entry.dest) fail("STAGE_SIDECAR_CONFIG_INVALID", `command ${entry.name} produced a directory (${entry.output}); a directory output needs dest (it cannot be staged as <name>-<triple>)`, { name: entry.name });
1710
+ if (entry.sha256) fail("STAGE_SIDECAR_CONFIG_INVALID", `command ${entry.name} output ${entry.output} is a directory; sha256 pins one file, so drop it (every file is hashed into the receipt)`, { name: entry.name });
1711
+ if (ctx.target.arch === "universal") fail("STAGE_SIDECAR_CONFIG_INVALID", `command ${entry.name}: a directory output cannot be a universal binary; use a file output`, { name: entry.name });
1712
+ const members = listFilesRecursive(fs, source);
1713
+ if (!members.length) fail("STAGE_SIDECAR_BINARY_NOT_FOUND", `command ${entry.name} output directory ${entry.output} contains no files`, { name: entry.name, output: entry.output });
1714
+ const destRoot = path.resolve(appRoot, entry.dest);
1715
+ cleanDest(ctx, entry, destRoot, { directory: true });
1716
+ return members.map((member) => {
1717
+ const from = path.join(source, ...member.split("/"));
1718
+ const dest = path.join(destRoot, ...member.split("/"));
1719
+ const sourceSha256 = sha256Of(fs.readFileSync(from));
1720
+ const copied = copyInto(ctx, from, dest, { executable: false });
1721
+ return { kind: "command", name: entry.name, path: rel(ctx, dest), ...copied, sourceSha256, output: `${entry.output}/${member}`, externalBin: false };
1722
+ });
1723
+ }
1724
+
1614
1725
  /** Run the entry's command (argv, no shell), then stage its output as <name>-<triple>. */
1615
1726
  function stageCommand(entry, ctx) {
1616
1727
  const { appRoot, fs, run, env } = ctx;
@@ -1620,14 +1731,26 @@ function stageCommand(entry, ctx) {
1620
1731
  const built = runStep(ctx, entry.cmd, entry.args, { cwd, env: splitCommandEnv(ctx) });
1621
1732
  if (built?.error || built?.status !== 0) fail("STAGE_SIDECAR_BUILD_FAILED", `command ${entry.name} (${entry.cmd}) failed (${built?.error?.message ?? `exit ${built?.status}`})`, { name: entry.name, stderr: tail(built?.stderr) });
1622
1733
  const source = path.resolve(appRoot, entry.output);
1734
+ // A directory output (a runtime tree, a browser build) is copied to `dest` file by file, every file hashed into the receipt (rightkit#753).
1735
+ if (fs.existsSync(source) && fs.statSync(source).isDirectory()) return stageCommandDirectory(entry, ctx, source);
1623
1736
  if (!fs.existsSync(source) || !fs.statSync(source).isFile()) fail("STAGE_SIDECAR_BINARY_NOT_FOUND", `command ${entry.name} did not produce ${entry.output}`, { name: entry.name, output: entry.output });
1624
1737
  if (ctx.target.arch === "universal") requireUniversalFile(ctx, source, `command ${entry.name} output ${entry.output}`);
1625
1738
  const sourceSha256 = sha256Of(fs.readFileSync(source));
1739
+ // A pinned output (sha256 declared) is the bytes the command must produce: any other result stages nothing (rightkit#753).
1740
+ if (entry.sha256 && entry.sha256 !== sourceSha256) fail("STAGE_SIDECAR_HASH_MISMATCH", `command ${entry.name} produced ${entry.output} as ${sourceSha256}, expected ${entry.sha256}; nothing staged`, { name: entry.name, expected: entry.sha256, actual: sourceSha256 });
1626
1741
  const dest = destFor(entry, ctx);
1627
1742
  const copied = copyInto(ctx, source, dest, { executable: true });
1628
1743
  return [{ kind: "command", name: entry.name, path: rel(ctx, dest), ...copied, sourceSha256, output: entry.output, externalBin: !entry.dest }];
1629
1744
  }
1630
1745
 
1746
+ /** The shared, host-wide download cache directory (`RIGHT_RELEASE_DOWNLOAD_CACHE`, absolute), or null when none is set. */
1747
+ export function sharedDownloadCache(ctx) {
1748
+ const dir = ctx.env?.RIGHT_RELEASE_DOWNLOAD_CACHE;
1749
+ if (dir === undefined || dir === "") return null;
1750
+ if (typeof dir !== "string" || !path.isAbsolute(dir) || dir.split(/[\\/]/).includes("..")) fail("STAGE_SIDECAR_CONFIG_INVALID", "RIGHT_RELEASE_DOWNLOAD_CACHE must be an absolute directory path with no .. segment");
1751
+ return path.resolve(dir, "remote");
1752
+ }
1753
+
1631
1754
  /**
1632
1755
  * Download `{ url, sha256, size? }` into the content-addressed cache (`.right-release/cache/remote/<sha256>`). The bytes are
1633
1756
  * hashed before anything is written: the cache entry exists only from verified bytes. A mismatch (or a non-https redirect)
@@ -1635,8 +1758,15 @@ function stageCommand(entry, ctx) {
1635
1758
  */
1636
1759
  async function ensureCachedDownload(ctx, { url, sha256, size }) {
1637
1760
  const { fs } = ctx;
1638
- const cached = path.resolve(ctx.cacheRoot, REMOTE_CACHE_DIR, sha256);
1639
- if (fs.existsSync(cached) && sha256Of(fs.readFileSync(cached)) === sha256) return { cached, fromCache: true };
1761
+ // One download cache for every checkout of every app on this host (rightkit#753): RIGHT_RELEASE_DOWNLOAD_CACHE (an absolute directory) is looked up
1762
+ // first and is where a new download lands. The cache is content addressed and every read is re-hashed, so sharing it cannot serve a wrong byte; the
1763
+ // per-checkout `.right-release/cache/remote` stays the fallback and the home of a host with no shared cache set.
1764
+ const shared = sharedDownloadCache(ctx);
1765
+ const local = path.resolve(ctx.cacheRoot, REMOTE_CACHE_DIR, sha256);
1766
+ const cached = shared ? path.join(shared, sha256) : local;
1767
+ for (const candidate of shared ? [cached, local] : [local]) {
1768
+ if (fs.existsSync(candidate) && sha256Of(fs.readFileSync(candidate)) === sha256) return { cached: candidate, fromCache: true };
1769
+ }
1640
1770
  ctx.log(`stage-sidecar: GET ${url}`);
1641
1771
  let response;
1642
1772
  try { response = await ctx.fetch(url, { redirect: "follow" }); } catch (error) { fail("STAGE_SIDECAR_DOWNLOAD_FAILED", `GET ${url} failed: ${error.message}`, { cause: error, url }); }
@@ -1653,15 +1783,52 @@ async function ensureCachedDownload(ctx, { url, sha256, size }) {
1653
1783
  return { cached, fromCache: false };
1654
1784
  }
1655
1785
 
1786
+ /** A pinned archive staged as a directory tree: extract to a scratch directory, require `extractTree` to exist, copy every file into `dest`, one receipt row per file. */
1787
+ async function stageRemoteTree(entry, ctx, { cached, fromCache, dest }) {
1788
+ const { fs } = ctx;
1789
+ const scratch = ctx.makeTempDir();
1790
+ try {
1791
+ const root = await ctx.extractTree({ archive: cached, root: entry.extractTree, destDir: scratch });
1792
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${entry.url} has no directory ${entry.extractTree}; nothing staged`, { name: entry.name });
1793
+ const members = listFilesRecursive(fs, root);
1794
+ if (!members.length) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${entry.url} directory ${entry.extractTree} contains no files; nothing staged`, { name: entry.name });
1795
+ // Everything is verified before the destination is touched: a failed extraction never leaves a cleaned or half-staged directory.
1796
+ cleanDest(ctx, entry, dest, { directory: true });
1797
+ return members.map((member) => {
1798
+ const from = path.join(root, ...member.split("/"));
1799
+ const to = path.join(dest, ...member.split("/"));
1800
+ const sourceSha256 = sha256Of(fs.readFileSync(from));
1801
+ const copied = copyInto(ctx, from, to, { executable: false });
1802
+ return { kind: "remote", name: entry.name, path: rel(ctx, to), ...copied, sourceSha256, url: entry.url, cached: fromCache, externalBin: false, archiveSha256: entry.sha256, member: `${entry.extractTree === "." ? "" : `${entry.extractTree}/`}${member}` };
1803
+ });
1804
+ } finally { ctx.removeDir(scratch); }
1805
+ }
1806
+
1807
+ /** The publisher's SHA-256 for a `latest` remote: read from its https checksum list (`<sha256> <name>` or `<sha256> *<name>` lines). Nothing is guessed. */
1808
+ async function resolveLatestDigest(ctx, entry) {
1809
+ const name = entry.latest.file ?? decodeURIComponent(new URL(entry.url).pathname.split("/").filter(Boolean).pop() ?? "");
1810
+ ctx.log(`stage-sidecar: GET ${entry.latest.checksums} (latest digest of ${name})`);
1811
+ let response;
1812
+ try { response = await ctx.fetch(entry.latest.checksums, { redirect: "follow" }); } catch (error) { fail("STAGE_SIDECAR_DOWNLOAD_FAILED", `GET ${entry.latest.checksums} failed: ${error.message}`, { cause: error, url: entry.latest.checksums }); }
1813
+ if (!response?.ok) fail("STAGE_SIDECAR_DOWNLOAD_FAILED", `GET ${entry.latest.checksums} failed with ${response?.status}`, { url: entry.latest.checksums });
1814
+ if (typeof response.url === "string" && response.url && !response.url.startsWith("https://")) fail("STAGE_SIDECAR_DOWNLOAD_FAILED", `${entry.latest.checksums} redirected to a non-https URL: ${response.url}`, { url: entry.latest.checksums });
1815
+ const rows = String(await response.text()).split(/\r?\n/).flatMap((line) => { const match = /^([0-9a-fA-F]{64})\s+\*?(.+?)\s*$/.exec(line); return match ? [{ sha256: match[1].toLowerCase(), file: match[2] }] : []; });
1816
+ const hits = rows.filter((row) => row.file === name);
1817
+ if (hits.length !== 1) fail("STAGE_SIDECAR_HASH_MISMATCH", `${entry.latest.checksums} lists ${hits.length} row(s) for ${name} (exactly one is required); nothing staged`, { name });
1818
+ return hits[0].sha256;
1819
+ }
1820
+
1656
1821
  /**
1657
1822
  * A pinned https download. `dest` is copied only from the verified cache entry. With `extract` the download is an archive
1658
1823
  * (zip, tgz): the one member whose base name is `extract` (or, when `extract` contains `/`, whose archive path equals it) is unpacked (digest-checked against `memberSha256` when given) and
1659
1824
  * only that member is staged, so no `command` entry or shell is needed to unpack it.
1660
1825
  */
1661
- async function stageRemote(entry, ctx) {
1826
+ async function stageRemote(declared, ctx) {
1662
1827
  const { appRoot, fs } = ctx;
1828
+ const entry = declared.latest ? { ...declared, sha256: await resolveLatestDigest(ctx, declared) } : declared;
1663
1829
  const dest = path.resolve(appRoot, entry.dest);
1664
1830
  const { cached, fromCache } = await ensureCachedDownload(ctx, entry);
1831
+ if (entry.extractTree) return stageRemoteTree(entry, ctx, { cached, fromCache, dest });
1665
1832
  let source = cached;
1666
1833
  let scratch;
1667
1834
  try {
@@ -1679,7 +1846,7 @@ async function stageRemote(entry, ctx) {
1679
1846
  const copied = copyInto(ctx, source, dest, { executable: entry.executable === true });
1680
1847
  const expected = entry.extract ? entry.memberSha256 : entry.sha256;
1681
1848
  if (expected && copied.sha256 !== expected) fail("STAGE_SIDECAR_HASH_MISMATCH", `staged ${entry.dest} is ${copied.sha256}, expected ${expected}`, { expected, actual: copied.sha256 });
1682
- return [{ kind: "remote", name: entry.name, path: rel(ctx, dest), ...copied, sourceSha256: memberSha256 ?? entry.sha256, url: entry.url, cached: fromCache, externalBin: false, ...(entry.extract ? { archiveSha256: entry.sha256, member: entry.extract, memberSha256 } : {}), ...(entry.extractKind ? { extractKind: entry.extractKind } : {}) }];
1849
+ return [{ kind: "remote", name: entry.name, path: rel(ctx, dest), ...copied, sourceSha256: memberSha256 ?? entry.sha256, url: entry.url, cached: fromCache, externalBin: false, ...(declared.latest ? { latest: { checksums: declared.latest.checksums, resolvedSha256: entry.sha256 } } : {}), ...(entry.extract ? { archiveSha256: entry.sha256, member: entry.extract, memberSha256 } : {}), ...(entry.extractKind ? { extractKind: entry.extractKind } : {}) }];
1683
1850
  } finally {
1684
1851
  if (scratch) ctx.removeDir(scratch);
1685
1852
  }
@@ -1980,6 +2147,7 @@ export async function stageSidecars({ appRoot, manifest, target, cacheRoot, ifSt
1980
2147
  fetchBytes: deps.fetchBytes ?? defaultFetchBytes,
1981
2148
  fetch: deps.fetch ?? ((...args) => globalThis.fetch(...args)),
1982
2149
  extractMember: deps.extractMember ?? ((args) => defaultExtractMember({ ...args, run })),
2150
+ extractTree: deps.extractTree ?? ((args) => defaultExtractTree({ ...args, run })),
1983
2151
  extractNsisMember: deps.extractNsisMember ?? ((args) => defaultExtractNsisMember({ ...args, run, env, sevenZip: deps.sevenZip, readFile: fs.readFileSync, exists: fs.existsSync })),
1984
2152
  loadMediaCatalog: deps.loadMediaCatalog ?? (() => undefined),
1985
2153
  loadNativeCatalog: deps.loadNativeCatalog ?? (() => undefined),
@@ -2016,6 +2184,7 @@ export async function stageSidecars({ appRoot, manifest, target, cacheRoot, ifSt
2016
2184
  target: plan.target.triple,
2017
2185
  os: plan.target.os,
2018
2186
  arch: plan.target.arch,
2187
+ mode: plan.mode, // the build mode the files were staged in (dev | release): readVerifiedStageReceipt and the release guard read it back (rightkit#1039)
2019
2188
  stagedAt: (deps.now ?? (() => new Date().toISOString()))(),
2020
2189
  files,
2021
2190
  skipped,
@@ -2045,6 +2214,8 @@ function currentStageReceipt(plan, ctx) {
2045
2214
  const receiptFile = path.resolve(appRoot, plan.receiptPath);
2046
2215
  const receipt = validateStageSidecarReceipt(JSON.parse(fs.readFileSync(receiptFile, "utf8")), { target: plan.target.triple });
2047
2216
  const planned = plan.entries.filter((entry) => !entry.skipped);
2217
+ if (receipt.mode !== undefined && receipt.mode !== plan.mode) return null; // staged in another build mode: never reused
2218
+ if (planned.some((entry) => entry.latest)) return null; // a `latest` entry follows the publisher: it is re-resolved every run, never reused
2048
2219
  const skipped = plan.entries.filter((entry) => entry.skipped).map((entry) => ({ kind: entry.kind, index: entry.index, platforms: entry.platforms }));
2049
2220
  if (JSON.stringify(skipped) !== JSON.stringify(receipt.skipped ?? [])) return null;
2050
2221
  if (receipt.files.length < planned.length) return null;
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ // `right-release stage-xcframework --crate <dir> --targets <triple>[,<triple>...] --headers <dir> --out <Name.xcframework>` (rightkit#1234).
3
+ //
4
+ // A RightKit-owned way to turn a Rust staticlib crate into an iOS xcframework (Pulse: swift/MeshLink/RightKitMeshFFI.xcframework from
5
+ // rightkit-mesh-ffi), usable as a `development.targets.ios.prepare` step and as an `iosPackage.prepare` step. It replaces a hand-made, git-ignored product:
6
+ // 1. every target is compiled through RustRight's managed Cargo seam (`rustright cargo build --locked`, the same call stage-sidecar makes: through the
7
+ // broker on Mac and Dell, one output directory, the release profile - GC-A15, there is no dev or debug output), and the `.a` is read from Cargo's own
8
+ // JSON artifact stream (never a hard-coded broker path);
9
+ // 2. `xcodebuild -create-xcframework` assembles one slice per target with the headers directory;
10
+ // 3. a receipt `<out>.receipt.json` beside the product records the crate, each target's library path and sha256, the headers digest and the xcframework's
11
+ // Info.plist sha256, so the product is never a stale copy nobody can date.
12
+ // Output `--out` is replaced whole (a stale xcframework is removed first); the crate, headers and output paths must lie inside the working directory's repository.
13
+ import { createHash } from "node:crypto";
14
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
15
+ import path from "node:path";
16
+ import { pathToFileURL } from "node:url";
17
+ import { oneOutput } from "./cross-targets.mjs";
18
+ import { defaultRun } from "./stage-sidecar.mjs";
19
+ import { spawnSync } from "./background-process.mjs";
20
+
21
+ export class StageXcframeworkError extends Error {
22
+ constructor(message) { super(message); this.name = "StageXcframeworkError"; this.code = "RK_STAGE_XCFRAMEWORK"; }
23
+ }
24
+ const fail = (message) => { throw new StageXcframeworkError(message); };
25
+
26
+ export const XCFRAMEWORK_TARGETS = Object.freeze(["aarch64-apple-ios", "aarch64-apple-ios-sim", "x86_64-apple-ios"]);
27
+
28
+ export function parseStageXcframeworkArgs(argv) {
29
+ const opts = { crate: null, targets: [], headers: null, out: null, package: null };
30
+ for (let i = 0; i < argv.length; i += 1) {
31
+ const flag = argv[i];
32
+ const value = argv[i + 1];
33
+ if (!["--crate", "--targets", "--headers", "--out", "--package"].includes(flag)) fail(`unknown argument: ${flag}`);
34
+ if (value === undefined || value.startsWith("--")) fail(`${flag} needs a value`);
35
+ i += 1;
36
+ if (flag === "--targets") opts.targets = value.split(",").map((item) => item.trim()).filter(Boolean);
37
+ else opts[flag.slice(2)] = value;
38
+ }
39
+ for (const key of ["crate", "headers", "out"]) if (!opts[key]) fail(`--${key} is required`);
40
+ if (!opts.targets.length) fail("--targets is required (for example aarch64-apple-ios,aarch64-apple-ios-sim)");
41
+ const bad = opts.targets.filter((target) => !XCFRAMEWORK_TARGETS.includes(target));
42
+ if (bad.length) fail(`unsupported target(s) ${bad.join(", ")} (allowed: ${XCFRAMEWORK_TARGETS.join(", ")})`);
43
+ if (new Set(opts.targets).size !== opts.targets.length) fail("--targets lists a target twice");
44
+ if (opts.targets.includes("aarch64-apple-ios-sim") && opts.targets.includes("x86_64-apple-ios")) fail("aarch64-apple-ios-sim and x86_64-apple-ios are both simulator slices; an xcframework holds one simulator library (lipo them first)");
45
+ if (!/\.xcframework$/.test(opts.out)) fail("--out must end in .xcframework");
46
+ return opts;
47
+ }
48
+
49
+ /** The staticlib Cargo reports in its JSON stream for the crate at `manifest` (the last matching compiler-artifact), or undefined. */
50
+ export function staticlibFromStream(stdout, manifest, packageName) {
51
+ let found;
52
+ for (const line of String(stdout ?? "").split("\n")) {
53
+ if (!line.startsWith("{")) continue;
54
+ let message;
55
+ try { message = JSON.parse(line); } catch { continue; }
56
+ if (message.reason !== "compiler-artifact" || !(message.target?.kind ?? []).includes("staticlib")) continue;
57
+ if (packageName ? message.target?.name !== packageName.replaceAll("-", "_") && message.target?.name !== packageName : path.resolve(String(message.manifest_path ?? "")) !== path.resolve(manifest)) continue;
58
+ const library = (message.filenames ?? []).find((file) => file.endsWith(".a"));
59
+ if (library) found = library;
60
+ }
61
+ return found;
62
+ }
63
+
64
+ const sha256File = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");
65
+
66
+ function digestTree(dir, prefix = "") {
67
+ const hash = createHash("sha256");
68
+ for (const name of readdirSync(path.join(dir, prefix)).sort()) {
69
+ const relative = prefix ? `${prefix}/${name}` : name;
70
+ const full = path.join(dir, relative);
71
+ if (lstatSync(full).isDirectory()) hash.update(`d ${relative}\n${digestTree(dir, relative)}\n`);
72
+ else hash.update(`f ${relative} ${sha256File(full)}\n`);
73
+ }
74
+ return hash.digest("hex");
75
+ }
76
+
77
+ /** Build every slice and assemble the xcframework. Injectable: run (rustright), xcodebuild (spawnSync-shaped), fs pieces, log, cwd, platform. */
78
+ export function stageXcframework(opts, { run = defaultRun, xcodebuild = spawnSync, log = (line) => console.log(line), cwd = process.cwd(), platform = process.platform, env = process.env } = {}) {
79
+ if (platform !== "darwin") fail("stage-xcframework runs on macOS (xcodebuild assembles the xcframework)");
80
+ const crate = path.resolve(cwd, opts.crate);
81
+ const manifest = path.join(crate, "Cargo.toml");
82
+ const headers = path.resolve(cwd, opts.headers);
83
+ const out = path.resolve(cwd, opts.out);
84
+ if (!existsSync(manifest)) fail(`no Cargo.toml in the crate directory ${crate}`);
85
+ if (!existsSync(headers) || !lstatSync(headers).isDirectory()) fail(`headers directory not found: ${headers}`);
86
+ if (!readdirSync(headers).length) fail(`headers directory ${headers} is empty`);
87
+ const inside = (file) => { const relative = path.relative(path.resolve(cwd), file); return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative); };
88
+ if (!inside(out)) fail(`--out ${out} must be inside the working directory`);
89
+ const libraries = [];
90
+ for (const target of opts.targets) {
91
+ const args = oneOutput(["cargo", "build", "--locked", "--manifest-path", manifest, ...(opts.package ? ["-p", opts.package] : []), "--target", target, "--lib", "--message-format=json-render-diagnostics"]);
92
+ log(`stage-xcframework: rustright ${args.join(" ")}`);
93
+ const built = run("rustright", args, { cwd: crate, env });
94
+ if (built?.error || built?.status !== 0) fail(`the build of ${path.basename(crate)} for ${target} failed (${built?.error?.message ?? `exit ${built?.status}`})`);
95
+ const library = staticlibFromStream(built.stdout, manifest, opts.package);
96
+ if (!library || !existsSync(library)) fail(`Cargo reported no staticlib for ${path.basename(crate)} (${target}); set crate-type = ["staticlib"] in its [lib]`);
97
+ libraries.push({ target, source: library, sha256: sha256File(library) });
98
+ }
99
+ rmSync(out, { recursive: true, force: true });
100
+ mkdirSync(path.dirname(out), { recursive: true });
101
+ const created = xcodebuild("xcodebuild", ["-create-xcframework", ...libraries.flatMap((item) => ["-library", item.source, "-headers", headers]), "-output", out], { encoding: "utf8", windowsHide: true, shell: false });
102
+ if (created?.error || created?.status !== 0) { rmSync(out, { recursive: true, force: true }); fail(`xcodebuild -create-xcframework failed (${created?.error?.message ?? `exit ${created?.status}`}): ${String(created?.stderr ?? created?.stdout ?? "").trim()}`); }
103
+ const plist = path.join(out, "Info.plist");
104
+ if (!existsSync(plist)) { rmSync(out, { recursive: true, force: true }); fail(`xcodebuild reported success but ${plist} does not exist`); }
105
+ const receipt = { schema: 1, crate: path.relative(cwd, crate).split(path.sep).join("/") || ".", targets: libraries.map(({ target, sha256 }) => ({ target, sha256 })), headersSha256: digestTree(headers), xcframeworkInfoPlistSha256: sha256File(plist), profile: "release" };
106
+ writeFileSync(`${out}.receipt.json`, `${JSON.stringify(receipt, null, 2)}\n`);
107
+ log(`stage-xcframework: wrote ${out} (${libraries.length} slice(s)) and ${path.basename(out)}.receipt.json`);
108
+ return { out, receipt };
109
+ }
110
+
111
+ export function main(argv = process.argv.slice(2)) {
112
+ try { stageXcframework(parseStageXcframeworkArgs(argv)); return 0; } catch (error) {
113
+ console.error(`right-release stage-xcframework: ${error.message}`);
114
+ return error instanceof StageXcframeworkError ? 1 : 2;
115
+ }
116
+ }
117
+
118
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) process.exitCode = main();
@@ -60,6 +60,9 @@ export const APP_ARTIFACT_HOSTS = {
60
60
  "rightapps-license-gate.adrdsouza.workers.dev",
61
61
  "pub-6c73208d46c245a9b4881d5e02f6b618.r2.dev"
62
62
  ],
63
+ "cutright": [
64
+ "pub-6c73208d46c245a9b4881d5e02f6b618.r2.dev"
65
+ ],
63
66
  "heardright": [
64
67
  "rightapps-license-gate.adrdsouza.workers.dev",
65
68
  "pub-6c73208d46c245a9b4881d5e02f6b618.r2.dev"
@@ -68,6 +71,10 @@ export const APP_ARTIFACT_HOSTS = {
68
71
  "rightapps-license-gate.adrdsouza.workers.dev",
69
72
  "pub-6c73208d46c245a9b4881d5e02f6b618.r2.dev"
70
73
  ],
74
+ "scraperight": [
75
+ "rightapps-license-gate.adrdsouza.workers.dev",
76
+ "pub-6c73208d46c245a9b4881d5e02f6b618.r2.dev"
77
+ ],
71
78
  "viewright": [
72
79
  "pub-6c73208d46c245a9b4881d5e02f6b618.r2.dev"
73
80
  ]
@@ -81,7 +88,11 @@ export const RIGHT_SUITE_API_CONTRACT = {
81
88
  ],
82
89
  "licenseHost": "coderight.cc"
83
90
  },
84
- "cutright": {},
91
+ "cutright": {
92
+ "artifactHosts": [
93
+ "public"
94
+ ]
95
+ },
85
96
  "genright": {
86
97
  "licenseHost": "heardright.app"
87
98
  },
@@ -102,6 +113,10 @@ export const RIGHT_SUITE_API_CONTRACT = {
102
113
  "postright": {},
103
114
  "pulse": {},
104
115
  "scraperight": {
116
+ "artifactHosts": [
117
+ "gated",
118
+ "public"
119
+ ],
105
120
  "licenseHost": "scraperight.cc"
106
121
  },
107
122
  "viewright": {
package/unit-gate.mjs CHANGED
@@ -13,7 +13,9 @@ import { RIGHTKIT_REPOSITORY, buildDirectOrigin, directStageEvidence, verifyDire
13
13
  import { exclusionsFor } from "./pack-digest.mjs";
14
14
  import { ATTEST_STAGE_NONCE_ENV, qualificationNonce } from "./provenance-verify.mjs";
15
15
  import { verifyQualificationReceipts } from "./qualification-verify.mjs";
16
- import { assignJobs, describeCommand, expectedStageCommands } from "./stage-commands.mjs";
16
+ import { assignJobs, describeCommand, directRowsNotRun, expectedStageCommands } from "./stage-commands.mjs";
17
+ import { carriedCargoMapOf } from "./carried-cargo.mjs";
18
+ import { UNSCOPED, readLedger } from "./cargo-ledger.mjs";
17
19
  import { resolveManagedRoots } from "./managed-roots.mjs";
18
20
  import { controlPlaneProblem } from "./control-plane.mjs";
19
21
 
@@ -400,8 +402,18 @@ export async function runUnitGate({ selector, to, root, commonDir, commit, tree,
400
402
  // so a missing one fails here, before any dispatch, naming it. Jobs that are none of the stage's commands are not carried.
401
403
  const fetched = [...new Set(ids ?? [])].map((id) => fetchReceipt(id));
402
404
  // A carried cargo command is bound to the directory of the primary checkout it ran in (source.checkout; stage-commands.mjs requestIs).
403
- const { assigned, missing } = assignJobs(stageCommands({ unit, root, platform })[stage], fetched.map((r) => ({ id: r.id, payload: r.provenance.payload })), { checkout: source?.checkout ?? null });
405
+ const rows = stageCommands({ unit, root, platform })[stage];
406
+ const { assigned, missing } = assignJobs(rows, fetched.map((r) => ({ id: r.id, payload: r.provenance.payload })), { checkout: source?.checkout ?? null });
404
407
  if (missing.length) throw new Error(`the ${stage} stage's ${describeCommand(missing[0])} has no broker job receipt (${missing.length} required command(s) missing)`);
408
+ // GC-A11: a command that compiles nothing runs directly and makes no receipt (rightkit#1484); the stage's carrier ledger must show it ran with exit 0.
409
+ if (rows.some((row) => row.direct === true)) {
410
+ const carried = carriedCargoMapOf(envExtra);
411
+ let entries = null;
412
+ if (carried?.map) { try { entries = readLedger(carried.map.ledgerDir, UNSCOPED).entries; } catch { entries = null; } }
413
+ if (entries === null) throw new Error(`the ${stage} stage runs ${rows.filter((row) => row.direct === true).length} direct (non-compiling) command(s) and its carrier ledger cannot be read to verify them`);
414
+ const notRun = directRowsNotRun(rows, entries);
415
+ if (notRun.length) throw new Error(`the ${stage} stage's direct command ${describeCommand(notRun[0].row)} ${notRun[0].why} in the carrier ledger (${notRun.length} direct command(s) unverified)`);
416
+ }
405
417
  receipts[stage] = fetched.filter((r) => assigned.has(r.id));
406
418
  };
407
419
  const verifyArtifact = (result) => {
package/upload-large.mjs CHANGED
@@ -7,7 +7,7 @@ import { verifySealedRelease } from "./release-state.mjs";
7
7
  import { uploadVerifiedR2File } from "./r2-verified-upload.mjs";
8
8
  import { resolveCloudflareApiToken } from "./protected-credentials.mjs";
9
9
 
10
- export function runLargeUpload(argv, { run = spawnSync, env = process.env, credentialStore } = {}) {
10
+ export async function runLargeUpload(argv, { run = spawnSync, env = process.env, credentialStore } = {}) {
11
11
  const [localFile, r2Key, bucketAlias = "public", flag, evidencePath, ...extra] = argv;
12
12
  if (!localFile || !r2Key) throw new Error("Usage: upload-large <file> <key> public|private --evidence <json> | --seal <sealed-dir>");
13
13
  if (!["public", "private"].includes(bucketAlias)) throw new Error(`invalid bucket alias ${bucketAlias}; expected public|private`);
@@ -22,7 +22,7 @@ export function runLargeUpload(argv, { run = spawnSync, env = process.env, crede
22
22
  evidence = { sha256: value.artifactSha256, sizeBytes: value.sizeBytes };
23
23
  }
24
24
  // Validate before runner discovery or any remote operation, including dry runs.
25
- uploadVerifiedR2File(localFile, evidence, r2Key, bucketAlias, { dryRun: true });
25
+ await uploadVerifiedR2File(localFile, evidence, r2Key, bucketAlias, { dryRun: true });
26
26
  // The Cloudflare token is resolved only for a real upload; it is injected into the Wrangler child environment alone.
27
27
  const dryRun = env.RIGHT_RELEASE_UPLOAD_DRY_RUN === "1";
28
28
  const token = resolveCloudflareApiToken({ env, credentialStore, required: !dryRun });
@@ -30,11 +30,11 @@ export function runLargeUpload(argv, { run = spawnSync, env = process.env, crede
30
30
  const probe = run("pnpm", ["--version"], { env, stdio: "ignore", shell: process.platform === "win32", windowsHide: true });
31
31
  if (probe.error || probe.status !== 0) throw new Error("no package runner found: pnpm dlx");
32
32
  const object = `${bucketAlias === "public" ? "rightapps-downloads" : "rightapps-updates"}/${r2Key}`;
33
- console.log(`wrangler r2 object put ${object} --remote (mandatory hash readback)`);
33
+ console.log(`r2 put ${object} (wrangler below 200 MiB, S3 multipart above it; mandatory streamed sha256 and size readback)`);
34
34
  console.log("runner: pnpm dlx");
35
35
  return uploadVerifiedR2File(localFile, evidence, r2Key, bucketAlias, { run, env: uploadEnv, dryRun });
36
36
  }
37
37
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
38
- try { runLargeUpload(process.argv.slice(2)); }
38
+ try { await runLargeUpload(process.argv.slice(2)); }
39
39
  catch (error) { console.error(`upload-large: ${error.message}`); process.exitCode = 1; }
40
40
  }