@rightkit/release 0.6.56 → 0.6.61

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 (71) hide show
  1. package/README.md +4 -0
  2. package/acceptance-admission.mjs +104 -0
  3. package/acceptance-launch.mjs +234 -0
  4. package/acceptance-lines.mjs +1254 -0
  5. package/acceptance-result.mjs +77 -0
  6. package/acceptance-rows.mjs +47 -0
  7. package/admission-files.mjs +2 -0
  8. package/affected-units.mjs +17 -0
  9. package/app-check.mjs +6 -2
  10. package/app-closure.mjs +3 -1
  11. package/bin/rightkit-gate.mjs +546 -121
  12. package/broker-admission.mjs +45 -2
  13. package/broker-pins.mjs +11 -1
  14. package/broker-toolchain.mjs +113 -0
  15. package/cargo-profile-contract.mjs +7 -2
  16. package/class-a-cache-history.mjs +135 -0
  17. package/cli/right-release.mjs +0 -0
  18. package/code-closure.mjs +24 -0
  19. package/config-inspect.mjs +6 -0
  20. package/consumer-contracts.mjs +3 -1
  21. package/contract-nn.json +166 -0
  22. package/deterministic-scans.mjs +835 -112
  23. package/feature-coverage.mjs +109 -82
  24. package/feature-partition.mjs +76 -0
  25. package/forbidden-literals.mjs +78 -0
  26. package/gate/calls.mjs +121 -0
  27. package/gate/compile.mjs +190 -0
  28. package/gate/crate-results.mjs +127 -0
  29. package/gate/run-calls.mjs +241 -0
  30. package/gate/tests.mjs +234 -0
  31. package/gate-coverage.mjs +12 -3
  32. package/gate-release-admission.mjs +200 -0
  33. package/gate-seam.mjs +100 -4
  34. package/gate-serve.mjs +178 -32
  35. package/gate-stages.mjs +59 -0
  36. package/legacy-contract-receipt.mjs +809 -0
  37. package/local-publish.mjs +7 -5
  38. package/local-runtime.mjs +2 -2
  39. package/nsis-payload.mjs +4 -3
  40. package/ownership-applicability.mjs +5 -0
  41. package/ownership-class-rules.mjs +19 -8
  42. package/ownership-mandatory-set.json +15 -21
  43. package/ownership-mandatory-set.mjs +19 -4
  44. package/package.json +14 -8
  45. package/probe-memo.mjs +252 -0
  46. package/publication-artifacts.mjs +56 -2
  47. package/publish-local-npm.mjs +3 -0
  48. package/publish-update.mjs +2 -2
  49. package/receipt-signature.mjs +40 -0
  50. package/release.mjs +47 -29
  51. package/resident-answers.mjs +66 -0
  52. package/rightkit-ownership.json +20 -11
  53. package/rightkit-versions.json +349 -183
  54. package/runtime-bundle-stage.mjs +146 -0
  55. package/scan-digest.mjs +28 -4
  56. package/seam-broker.mjs +8 -1
  57. package/shell-contract.mjs +23 -2
  58. package/snapshot-changes.mjs +106 -0
  59. package/snapshot-check.mjs +17 -13
  60. package/snapshot-dependency-reuse.mjs +186 -14
  61. package/snapshot-git.mjs +17 -1
  62. package/snapshot-metadata.mjs +155 -3
  63. package/snapshot.mjs +90 -12
  64. package/spawn-ledger.mjs +21 -2
  65. package/stage-sidecar.mjs +231 -19
  66. package/suite-trust-roots.mjs +2 -2
  67. package/test-env.mjs +26 -0
  68. package/tool-version-memo.mjs +46 -0
  69. package/win-package-recipe.mjs +11 -0
  70. package/bin/darwin/rightkit-swap +0 -0
  71. package/gate-acceptance.mjs +0 -3362
package/stage-sidecar.mjs CHANGED
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // sidecars: [
8
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
- // { kind: "ffmpeg", variant?, variants?, tools?, notices: { dir, sourceOfferContact }, catalog, stage?, bundleDir?, resourceDir?, sources?, probe? },
9
+ // { kind: "ffmpeg", variant?, variants?, tools?, notices: { dir, sourceOfferContact }, catalog, stage?, bundleDir?, resourceDir?, sources?, probe?: boolean | { filters?, encoders?, forbidConfigureFlags? } },
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)
@@ -33,6 +33,7 @@
33
33
  //
34
34
  // It never signs (release.mjs signs staged files) and never calls bare cargo. Every effect goes through `deps`.
35
35
  import { createHash } from "node:crypto";
36
+ import { checkRuntimeBundleOutput, checkRuntimeBundlePath, planRuntimeBundle, runtimeBundleRelative } from "./runtime-bundle-stage.mjs";
36
37
  import nodeFs from "node:fs";
37
38
  import os from "node:os";
38
39
  import path from "node:path";
@@ -81,7 +82,7 @@ export class StageSidecarError extends Error {
81
82
  const fail = (code, message, details) => { throw new StageSidecarError(code, message, details); };
82
83
  const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
83
84
  const SHA256 = /^[0-9a-f]{64}$/;
84
- const KINDS = new Set(["cargo-bin", "ffmpeg", "onnxruntime", "native-library", "resource", "command", "remote", "cmake", "prebuilt"]);
85
+ const KINDS = new Set(["cargo-bin", "ffmpeg", "onnxruntime", "native-library", "resource", "command", "remote", "cmake", "prebuilt", "runtime-manifest"]);
85
86
  export const NESTED_BROKER_CODE = "STAGE_SIDECAR_NESTED_BROKER";
86
87
  export const REMOTE_CACHE_DIR = ".right-release/cache/remote";
87
88
  /** Per-arch staging for a universal ffmpeg or onnxruntime entry: `<SLICE_ROOT>/<triple>/...`, merged with lipo afterwards. */
@@ -123,6 +124,7 @@ const NATIVE_OTHER_ROUTE = Object.freeze({ ffmpeg: "has its own kind: use { kind
123
124
  /** A catalog version token (1.24.4, chromium/8021): only compared with the rows, never used as a path. */
124
125
  const NATIVE_VERSION = /^[A-Za-z0-9][A-Za-z0-9._+/-]{0,63}$/;
125
126
  const KEYS = Object.freeze({
127
+ "runtime-manifest": ["kind", "dir", "onnxruntime", "platforms"],
126
128
  "cargo-bin": ["kind", "package", "bin", "name", "profile", "features", "devFeatures", "manifestPath", "sha256", "dest", "clean", "platforms"],
127
129
  ffmpeg: ["kind", "variant", "variants", "tools", "notices", "catalog", "stage", "bundleDir", "resourceDir", "sources", "probe", "platforms"],
128
130
  onnxruntime: ["kind", "version", "catalog", "resourceDir", "as", "licenseDir", "cacheDir", "companions", "platforms"],
@@ -425,7 +427,14 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
425
427
  return item.clean === true;
426
428
  };
427
429
  const stagedClaim = (name) => `${stageDir}/${stagedName(name, t)}`;
428
- if (item.kind === "cargo-bin") {
430
+ if (item.kind === "runtime-manifest") {
431
+ const dir = relativePath(item.dir, `${where}: dir`, errors);
432
+ if (dir && !runtimeBundleRelative(dir)) errors.push(`${where}: dir contains a non-portable or reserved path component`);
433
+ const identity = item.onnxruntime;
434
+ if (!isObject(identity) || Object.keys(identity).some((key) => !["version", "variant", "catalogRow"].includes(key)) || [identity.version, identity.variant, identity.catalogRow].some((value) => typeof value !== "string" || !value || value.trim() !== value)) errors.push(`${where}: onnxruntime must be exactly { version, variant, catalogRow } with nonblank strings`);
435
+ if (!skipped && dir) claim(`${dir}/manifest.json`, where);
436
+ Object.assign(entry, { dir, onnxruntime: identity });
437
+ } else if (item.kind === "cargo-bin") {
429
438
  if (typeof item.package !== "string" || !NAME.test(item.package)) errors.push(`${where}: package must be a Cargo package name`);
430
439
  const bin = item.bin ?? item.package;
431
440
  if (typeof bin !== "string" || !NAME.test(bin)) errors.push(`${where}: bin must be a binary target name`);
@@ -452,8 +461,21 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
452
461
  if (rest.stage !== undefined && isObject(rest.stage) && rest.stage.cmd === "rightkit") errors.push(`${where}: stage.cmd "rightkit" is the retired name of the RustRight client (rustright#91); use { cmd: "rustright", args: ["cargo", ...] }`);
453
462
  const catalogSpec = parseCatalogSpec(rawCatalog, `${where}: catalog`, errors, "ffmpeg");
454
463
  if (catalogSpec) entry.catalogSpec = catalogSpec;
455
- if (rawProbe !== undefined && typeof rawProbe !== "boolean") errors.push(`${where}: probe must be a boolean`);
464
+ if (rawProbe !== undefined && typeof rawProbe !== "boolean" && !isObject(rawProbe)) errors.push(`${where}: probe must be a boolean or a probe policy`);
456
465
  if (rawProbe === true) entry.probe = true;
466
+ if (isObject(rawProbe)) {
467
+ const policy = {};
468
+ for (const key of Object.keys(rawProbe)) if (!["filters", "encoders", "forbidConfigureFlags"].includes(key)) errors.push(`${where}: probe has unknown key ${JSON.stringify(key)}`);
469
+ for (const key of ["filters", "encoders", "forbidConfigureFlags"]) {
470
+ if (rawProbe[key] === undefined) continue;
471
+ const list = rawProbe[key];
472
+ const pattern = key === "forbidConfigureFlags" ? /^--[a-z0-9][a-z0-9-]*$/ : /^[A-Za-z0-9_]+$/;
473
+ if (!Array.isArray(list) || list.some((value) => typeof value !== "string" || !pattern.test(value)) || new Set(list).size !== list.length) errors.push(`${where}: probe.${key} must contain unique, valid names`);
474
+ else policy[key] = [...list];
475
+ }
476
+ if (["filters", "encoders", "forbidConfigureFlags"].some((key) => policy[key]?.length) && Array.isArray(item.tools) && !item.tools.includes("ffmpeg")) errors.push(`${where}: probe capability and forbidden-flag checks require ffmpeg in tools`);
477
+ entry.probe = policy;
478
+ }
457
479
  // A row the platform filter skips (a Windows ffmpeg in a Mac universal staging) is not judged for universal slices, as the prebuilt rows are not (HeardRight Mac package, 2026-11-02).
458
480
  const sources = parseFfmpegSources(rawSources, where, errors, { universal: !skipped && t.arch === "universal" });
459
481
  if (sources) entry.sources = sources;
@@ -652,6 +674,13 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
652
674
  }
653
675
  entries.push(entry);
654
676
  }
677
+ for (const entry of entries.filter((item) => item.kind === "runtime-manifest" && !item.skipped)) {
678
+ const dir = entry.dir && canonicalOutput(entry.dir);
679
+ if (dir && [receiptPath, stageDir].filter(Boolean).some((output) => { const key = canonicalOutput(output); return key === dir || key.startsWith(`${dir}/`) || dir.startsWith(`${key}/`); })) errors.push(`sidecars[${entry.index}] (runtime-manifest) cannot overlap the stage directory or receipt`);
680
+ if (entries.some((item) => !item.skipped && item.index > entry.index)) errors.push(`sidecars[${entry.index}] (runtime-manifest) must follow every active staging entry`);
681
+ const producers = entries.filter((item) => !item.skipped && item.index < entry.index && (item.kind === "onnxruntime" || (item.kind === "native-library" && item.library === "onnxruntime")) && item.resourceDir === entry.dir);
682
+ if (producers.length !== 1) errors.push(`sidecars[${entry.index}] (runtime-manifest) needs exactly one earlier ONNX producer in its directory`);
683
+ }
655
684
  const protectedPaths = protectedOutputPaths({ stageDir, receiptPath, entries });
656
685
  for (const { key, output, label } of claimed) {
657
686
  const hit = protectedPaths.find((protectedPath) => reaches(key, protectedPath));
@@ -1200,14 +1229,22 @@ async function fetchFfmpegSources(entry, ctx, plan, arch) {
1200
1229
  * encoders; ffmpeg's `-encoders` list must not carry libx264, libx265, libxvid or libfdk_aac. A binary built for another
1201
1230
  * architecture or OS than this host is not run: the row says `skipped-cross-target`. Returns "passed" or "skipped-cross-target".
1202
1231
  */
1203
- function probeFfmpegBinary(ctx, { file, tool, target }) {
1232
+ function probeFfmpegBinary(ctx, { file, tool, target, policy, row }) {
1204
1233
  if (!canRunTarget(ctx, target)) return "skipped-cross-target";
1205
1234
  const text = (result, what) => {
1206
1235
  if (result?.error || result?.status !== 0) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `${tool} ${what} failed (${result?.error?.message ?? `exit ${result?.status}`})`, { file });
1207
1236
  return String(result.stdout ?? "");
1208
1237
  };
1209
1238
  const version = text(ctx.run(file, ["-version"], { cwd: ctx.appRoot, env: ctx.env }), "-version");
1210
- const configuration = /^configuration:(.*)$/m.exec(version)?.[1] ?? "";
1239
+ const configuration = (isObject(policy) ? /^\s*configuration:(.*)$/m : /^configuration:(.*)$/m).exec(version)?.[1] ?? "";
1240
+ if (isObject(policy)) {
1241
+ if (!row || typeof row.version !== "string" || !row.version || !Array.isArray(row.requiredConfigureFlags) || !row.requiredConfigureFlags.length || row.requiredConfigureFlags.some((flag) => typeof flag !== "string" || !/^--[a-z0-9][a-z0-9-]*$/.test(flag))) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `${tool} has no valid selected catalog probe requirements`, { file });
1242
+ const headline = version.split(/\r?\n/).find((line) => line.startsWith(`${tool} version `));
1243
+ if (!headline || headline.slice(`${tool} version `.length).split(/\s+/)[0] !== row.version) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `${tool} version does not match catalog ${row.version}`, { file });
1244
+ const tokens = new Set(configuration.trim().split(/\s+/));
1245
+ for (const flag of row.requiredConfigureFlags) if (!tokens.has(flag)) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `${tool} lacks catalog configure flag ${flag}`, { file });
1246
+ if (tool === "ffmpeg") for (const flag of policy.forbidConfigureFlags ?? []) if (tokens.has(flag)) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `${tool} has forbidden configure flag ${flag}`, { file });
1247
+ }
1211
1248
  for (const flag of ["--disable-gpl", "--disable-nonfree"]) if (!configuration.includes(flag)) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `${tool} was not built with ${flag}; the LGPL redistribution terms do not hold`, { file });
1212
1249
  const enabled = /--enable-(gpl|nonfree|libx264|libx265|libxvid|libfdk-aac)\b/.exec(configuration);
1213
1250
  if (enabled) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `${tool} was built with --enable-${enabled[1]}; it cannot ship under the LGPL`, { file });
@@ -1215,6 +1252,15 @@ function probeFfmpegBinary(ctx, { file, tool, target }) {
1215
1252
  const encoders = text(ctx.run(file, ["-hide_banner", "-encoders"], { cwd: ctx.appRoot, env: ctx.env }), "-encoders");
1216
1253
  const gpl = /\b(libx264|libx264rgb|libx265|libxvid|libfdk_aac)\b/.exec(encoders);
1217
1254
  if (gpl) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `ffmpeg lists the ${gpl[1]} encoder; it cannot ship under the LGPL`, { file });
1255
+ if (isObject(policy)) {
1256
+ const names = new Set(encoders.split(/\r?\n/).map((line) => line.trim().split(/\s+/)).filter(([flags, name]) => /^[VAS][A-Z.]{5}$/.test(flags ?? "") && name !== "=").map((columns) => columns[1]));
1257
+ for (const name of policy.encoders ?? []) if (!names.has(name)) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `ffmpeg lacks encoder ${name}`, { file });
1258
+ if (policy.filters?.length) {
1259
+ const filters = text(ctx.run(file, ["-hide_banner", "-filters"], { cwd: ctx.appRoot, env: ctx.env }), "-filters");
1260
+ const names = new Set(filters.split(/\r?\n/).map((line) => line.trim().split(/\s+/)).filter(([flags, name]) => /^[TSC.]{3}$/.test(flags ?? "") && name !== "=").map((columns) => columns[1]));
1261
+ for (const name of policy.filters) if (!names.has(name)) fail("STAGE_SIDECAR_FFMPEG_PROBE_FAILED", `ffmpeg lacks filter ${name}`, { file });
1262
+ }
1263
+ }
1218
1264
  }
1219
1265
  return "passed";
1220
1266
  }
@@ -1247,8 +1293,8 @@ async function stageFfmpegSlice(entry, ctx, resolved, { config, t, writeNotices,
1247
1293
  // Catalog rows pin the signature-independent content digest; preSignSha256 stays whole-file signing evidence.
1248
1294
  const contentDigest = catalogContentDigest(fs.readFileSync(file.stagedPath), t.arch);
1249
1295
  if (contentDigest !== file.contentSha256) fail("STAGE_SIDECAR_HASH_MISMATCH", `${file.tool} staged with content digest ${contentDigest}, the approved catalog row ${file.artifactId} says ${file.contentSha256}`, { expected: file.contentSha256, actual: contentDigest });
1250
- const probe = entry.probe ? probeFfmpegBinary(ctx, { file: file.stagedPath, tool: file.tool, target: t }) : undefined;
1251
- return { kind: "ffmpeg", name: file.tool, path: rel(ctx, file.stagedPath), sha256: file.preSignSha256, sizeBytes: file.preSignSizeBytes, changed: null, catalogRow: file.artifactId, version: file.version, catalogContentSha256: file.contentSha256, ...(file.variant ? { variant: file.variant } : {}), externalBin: !flat, license: "LGPL-2.1-or-later", notices, ...(probe ? { probe } : {}) };
1296
+ const probe = entry.probe ? probeFfmpegBinary(ctx, { file: file.stagedPath, tool: file.tool, target: t, policy: entry.probe, row: plan.rows.find((row) => row.tool === file.tool) }) : undefined;
1297
+ return { kind: "ffmpeg", name: file.tool, path: rel(ctx, file.stagedPath), sha256: file.preSignSha256, sizeBytes: file.preSignSizeBytes, changed: null, catalogRow: file.artifactId, version: file.version, catalogContentSha256: file.contentSha256, ...(file.variant ? { variant: file.variant } : {}), externalBin: !flat, license: "LGPL-2.1-or-later", notices, ...(probe ? { probe } : {}), ...(isObject(entry.probe) ? { probePolicySha256: ctx.strictProbeDigests.get(entry.index) } : {}) };
1252
1298
  });
1253
1299
  return { plan, rows };
1254
1300
  }
@@ -1283,24 +1329,104 @@ async function stageFfmpegUniversal(entry, ctx, resolved) {
1283
1329
  const parts = results.map(({ slice, rows }) => ({ slice, row: rows.find((row) => row.name === tool) }));
1284
1330
  const dest = path.resolve(appRoot, ffmpegOutput(entry, ctx.stageDir, tool, ctx.target));
1285
1331
  const merged = lipoMergeInto(ctx, parts.map(({ row }) => path.resolve(appRoot, row.path)), dest, `ffmpeg sidecar ${tool}`, { executable: true });
1286
- const probe = entry.probe ? probeFfmpegBinary(ctx, { file: dest, tool, target: ctx.target }) : undefined;
1332
+ const hostSlice = results.find(({ slice }) => slice.arch === ctx.host.arch);
1333
+ const row = hostSlice?.plan.rows.find((item) => item.tool === tool);
1334
+ const probe = entry.probe ? probeFfmpegBinary(ctx, { file: dest, tool, target: ctx.target, policy: entry.probe, row }) : undefined;
1287
1335
  return {
1288
1336
  kind: "ffmpeg", name: tool, path: rel(ctx, dest), ...merged, sourceSha256: merged.sha256, catalogRow: parts.map(({ row }) => row.catalogRow).join("+"), version: parts[0].row.version,
1289
- externalBin: !entry.resourceDir, license: "LGPL-2.1-or-later", notices, ...(probe ? { probe } : {}),
1337
+ externalBin: !entry.resourceDir, license: "LGPL-2.1-or-later", notices, ...(probe ? { probe } : {}), ...(isObject(entry.probe) ? { probePolicySha256: ctx.strictProbeDigests.get(entry.index) } : {}),
1290
1338
  slices: parts.map(({ slice, row }) => ({ triple: slice.triple, sha256: row.sha256, catalogRow: row.catalogRow, catalogContentSha256: row.catalogContentSha256 })),
1291
1339
  };
1292
1340
  });
1293
1341
  }
1294
1342
 
1343
+ async function loadMediaCatalogOf(entry, ctx) {
1344
+ if (ctx.mediaCatalogs.has(entry)) return ctx.mediaCatalogs.get(entry);
1345
+ let loaded = await ctx.loadMediaCatalog({ config: entry.media, appRoot: ctx.appRoot, entry });
1346
+ if (!loaded) {
1347
+ if (!entry.catalogSpec) fail("STAGE_SIDECAR_CATALOG_UNREADABLE", "ffmpeg needs a catalog (the rightkit-ffmpeg artifacts.json: a path, { crate } or { npm }) or deps.loadMediaCatalog");
1348
+ loaded = readJsonCatalog(resolveCatalogFile(entry.catalogSpec, ctx, "ffmpeg"), ctx.appRoot, ctx.fs, "rightkit-ffmpeg");
1349
+ }
1350
+ ctx.mediaCatalogs.set(entry, loaded);
1351
+ return loaded;
1352
+ }
1353
+
1354
+ // Before a mixed runtime writes anything, claim catalog-generated notices too.
1355
+ // Shared notices are allowed only when their source bytes agree.
1356
+ async function claimRuntimeNotices(plan, ctx) {
1357
+ const runtimeDirs = plan.entries.filter((entry) => !entry.skipped && entry.kind === "runtime-manifest").map((entry) => canonicalOutput(entry.dir));
1358
+ const notices = new Map();
1359
+ const prefixes = new Map();
1360
+ const register = (output) => {
1361
+ const parts = output.split("/");
1362
+ for (let index = 1; index <= parts.length; index += 1) {
1363
+ const spelling = parts.slice(0, index).join("/");
1364
+ const key = canonicalOutput(spelling);
1365
+ if (prefixes.has(key) && prefixes.get(key) !== spelling) fail("STAGE_SIDECAR_CONFIG_INVALID", `case-colliding runtime path ${spelling}`);
1366
+ prefixes.set(key, spelling);
1367
+ }
1368
+ };
1369
+ const outputs = [...plan.claims];
1370
+ for (const claim of outputs) if (runtimeDirs.some((dir) => claim.key.startsWith(`${dir}/`))) { register(claim.output); checkRuntimeBundleOutput(ctx.appRoot, claim.output, ctx.fs); }
1371
+ for (const entry of plan.entries.filter((item) => !item.skipped && (item.kind === "onnxruntime" || item.kind === "native-library"))) {
1372
+ const loaded = await loadNativeCatalogOf(entry, ctx);
1373
+ const targets = plan.target.arch === "universal" ? SLICES.map((triple) => parseTargetTriple(triple)) : [plan.target];
1374
+ for (const target of targets) for (const item of planNativeSet(entry, ctx, loaded, target)) {
1375
+ const output = `${entry.resourceDir}/${item.outName}`;
1376
+ const key = canonicalOutput(output);
1377
+ if (runtimeDirs.some((dir) => key.startsWith(`${dir}/`))) { register(output); checkRuntimeBundleOutput(ctx.appRoot, output, ctx.fs); }
1378
+ if (!outputs.some((claim) => claim.key === key)) outputs.push({ key, output, label: `sidecars[${entry.index}]` });
1379
+ }
1380
+ }
1381
+ const add = (dest, bytes, label) => {
1382
+ const output = rel(ctx, dest);
1383
+ const key = canonicalOutput(output);
1384
+ if (!runtimeDirs.some((dir) => key.startsWith(`${dir}/`))) return;
1385
+ register(output);
1386
+ checkRuntimeBundleOutput(ctx.appRoot, output, ctx.fs);
1387
+ const digest = sha256Of(bytes);
1388
+ const previous = notices.get(key);
1389
+ if (previous && (previous.output !== output || previous.digest !== digest)) fail("STAGE_SIDECAR_CONFIG_INVALID", `conflicting notices write ${output}`);
1390
+ const noticeClaims = [...notices.entries()].map(([noticeKey, notice]) => ({ key: noticeKey, output: notice.output, label: "another notice" }));
1391
+ const clash = findClaimClash([...outputs, ...noticeClaims], key);
1392
+ if (clash && !(previous && clash.key === key && clash.label === "another notice")) fail("STAGE_SIDECAR_CONFIG_INVALID", `${label} notice ${output} overlaps ${clash.label} output ${clash.output}`);
1393
+ notices.set(key, { output, digest });
1394
+ };
1395
+ for (const entry of plan.entries.filter((item) => !item.skipped)) {
1396
+ if (entry.kind === "onnxruntime" || entry.kind === "native-library") {
1397
+ const loaded = await loadNativeCatalogOf(entry, ctx);
1398
+ const targets = plan.target.arch === "universal" ? SLICES.map((triple) => parseTargetTriple(triple)) : [plan.target];
1399
+ for (const target of targets) for (const item of planNativeSet(entry, ctx, loaded, target)) {
1400
+ if (!Array.isArray(item.row.noticeFiles) || !item.row.noticeFiles.length) fail("STAGE_SIDECAR_NOTICE_MISSING", `${item.row.id} has no notices`);
1401
+ for (const notice of item.row.noticeFiles) {
1402
+ const normalized = String(notice).replaceAll("\\", "/");
1403
+ if (path.isAbsolute(notice) || normalized.split("/").includes("..")) fail("STAGE_SIDECAR_NOTICE_MISSING", `notice escapes catalog: ${notice}`);
1404
+ const source = path.join(loaded.crateDir, ...normalized.split("/"));
1405
+ add(path.resolve(ctx.appRoot, entry.licenseDir, path.posix.basename(normalized)), ctx.fs.readFileSync(source), item.row.id);
1406
+ }
1407
+ }
1408
+ } else if (entry.kind === "ffmpeg") {
1409
+ const loaded = await loadMediaCatalogOf(entry, ctx);
1410
+ const configs = plan.target.arch === "universal" ? entry.slices.map((slice) => slice.media) : [entry.media];
1411
+ const plans = configs.map((config) => planMediaSidecar({ config, catalog: loaded.catalog, crateDir: loaded.crateDir, crateVersion: loaded.crateVersion, catalogBytes: loaded.catalogBytes, root: ctx.appRoot }));
1412
+ const rows = new Map();
1413
+ for (const part of plans) {
1414
+ for (const notice of part.notices) add(notice.dest, ctx.fs.readFileSync(notice.source), "ffmpeg");
1415
+ for (const row of part.rows) rows.set(row.id, row);
1416
+ }
1417
+ const offer = plan.target.arch === "universal" ? sourceOfferText({ rows: [...rows.values()], contact: entry.media.notices.sourceOfferContact, crateVersion: loaded.crateVersion }) : plans[0].offer;
1418
+ add(plans[0].offerPath, Buffer.from(offer), "ffmpeg");
1419
+ }
1420
+ }
1421
+ ctx.runtimeNotices = notices;
1422
+ ctx.runtimeNoticeDigest = sha256Of(Buffer.from(JSON.stringify([...notices.entries()].sort())));
1423
+ }
1424
+
1295
1425
  async function stageFfmpeg(entry, ctx) {
1296
1426
  const { appRoot, fs, target } = ctx;
1297
1427
  const config = entry.media;
1298
1428
  try {
1299
- let resolved = await ctx.loadMediaCatalog({ config, appRoot, entry });
1300
- if (!resolved) {
1301
- if (!entry.catalogSpec) fail("STAGE_SIDECAR_CATALOG_UNREADABLE", "ffmpeg needs a catalog (the rightkit-ffmpeg artifacts.json: a path, { crate } or { npm }) or deps.loadMediaCatalog");
1302
- resolved = readJsonCatalog(resolveCatalogFile(entry.catalogSpec, ctx, "ffmpeg"), appRoot, fs, "rightkit-ffmpeg");
1303
- }
1429
+ const resolved = await loadMediaCatalogOf(entry, ctx);
1304
1430
  if (target.arch === "universal") return await stageFfmpegUniversal(entry, ctx, resolved);
1305
1431
  return (await stageFfmpegSlice(entry, ctx, resolved, { config, t: target, writeNotices: true, flat: Boolean(entry.resourceDir) })).rows;
1306
1432
  } catch (error) {
@@ -2114,6 +2240,7 @@ export function planSidecarStaging({ manifest, target, env = process.env } = {})
2114
2240
  const plan = validateSidecarManifest(manifest, { target, mode: resolveBuildMode(env) });
2115
2241
  const t = plan.target;
2116
2242
  const outputsOf = (entry) => {
2243
+ if (entry.kind === "runtime-manifest") return [`${entry.dir}/manifest.json`];
2117
2244
  if (["cargo-bin", "command", "cmake", "prebuilt"].includes(entry.kind)) return [entry.dest ?? `${plan.stageDir}/${stagedName(entry.name, t)}`];
2118
2245
  if (entry.kind === "remote") return [entry.dest];
2119
2246
  if (entry.kind === "resource") return [entry.to];
@@ -2162,6 +2289,7 @@ export async function stageSidecars({ appRoot, manifest, target, cacheRoot, ifSt
2162
2289
  // Warnings (a never-run row, a row left out) go to deps.warn; without one they join the progress log, so a caller that sets only `log` still sees them.
2163
2290
  warn: deps.warn ?? deps.log ?? (() => {}),
2164
2291
  nativeCatalogs: new Map(),
2292
+ mediaCatalogs: new Map(),
2165
2293
  fetchBytes: deps.fetchBytes ?? defaultFetchBytes,
2166
2294
  fetch: deps.fetch ?? ((...args) => globalThis.fetch(...args)),
2167
2295
  extractMember: deps.extractMember ?? ((args) => defaultExtractMember({ ...args, run })),
@@ -2177,15 +2305,45 @@ export async function stageSidecars({ appRoot, manifest, target, cacheRoot, ifSt
2177
2305
  // nested-broker refusal, which guards only a step that would build.
2178
2306
  // Opt-in (`ifStale`, `stage-sidecar --if-stale`): only a Mac package recipe's own prepare step asks for it. The check is structural (no source hash), so every
2179
2307
  // other caller, the gate's staging step included, builds as before.
2180
- const current = ifStale ? currentStageReceipt(plan, ctx) : null;
2308
+ ctx.strictProbeDigests = new Map();
2309
+ for (const entry of plan.entries.filter((item) => !item.skipped && item.kind === "ffmpeg" && isObject(item.probe))) {
2310
+ const loaded = await loadMediaCatalogOf(entry, ctx);
2311
+ ctx.strictProbeDigests.set(entry.index, sha256Of(Buffer.from(JSON.stringify({ policy: entry.probe, catalog: loaded.catalog, target: plan.target.triple, host: ctx.host, media: entry.media }))));
2312
+ }
2313
+ const runtimeRows = new Map();
2314
+ if (plan.entries.some((entry) => !entry.skipped && entry.kind === "runtime-manifest")) {
2315
+ const catalogs = [];
2316
+ for (const entry of plan.entries.filter((item) => !item.skipped)) {
2317
+ if (entry.kind === "onnxruntime" || entry.kind === "native-library") catalogs.push([entry.index, (await loadNativeCatalogOf(entry, ctx)).catalog]);
2318
+ if (entry.kind === "ffmpeg") catalogs.push([entry.index, (await loadMediaCatalogOf(entry, ctx)).catalog]);
2319
+ }
2320
+ ctx.runtimeCatalogDigest = sha256Of(Buffer.from(JSON.stringify(catalogs)));
2321
+ }
2322
+ for (const entry of plan.entries.filter((item) => !item.skipped && item.kind === "runtime-manifest")) {
2323
+ checkRuntimeBundlePath(appRoot, entry.dir, fs);
2324
+ const producer = plan.entries.find((item) => !item.skipped && item.index < entry.index && (item.kind === "onnxruntime" || (item.kind === "native-library" && item.library === "onnxruntime")) && item.resourceDir === entry.dir);
2325
+ const catalog = await loadNativeCatalogOf(producer, ctx);
2326
+ const targets = plan.target.arch === "universal" ? SLICES.map((triple) => parseTargetTriple(triple)) : [plan.target];
2327
+ const selected = targets.map((target) => planNativeSet(producer, ctx, catalog, target).filter((item) => !item.companionOf));
2328
+ if (selected.some((items) => items.length !== 1) || selected.some((items) => items[0].row.id !== selected[0][0].row.id)) fail("STAGE_SIDECAR_NOT_APPROVED", "runtime-manifest requires one shared ONNX catalog row for its target");
2329
+ runtimeRows.set(entry.index, selected[0][0].row);
2330
+ }
2331
+ if (runtimeRows.size) {
2332
+ checkRuntimeBundleOutput(appRoot, plan.stageDir, fs);
2333
+ checkRuntimeBundleOutput(appRoot, plan.receiptPath, fs);
2334
+ await claimNativeOutputs(plan, ctx);
2335
+ await claimRuntimeNotices(plan, ctx);
2336
+ }
2337
+ const current = ifStale ? currentStageReceipt(plan, ctx, runtimeRows) : null;
2181
2338
  if (current) return { receipt: current, receiptPath: path.resolve(appRoot, plan.receiptPath), files: current.files, externalBinNames: current.files.filter((file) => file.externalBin).map((file) => file.name), unchanged: true };
2182
2339
  assertNotNested(plan, env);
2183
- await claimNativeOutputs(plan, ctx);
2340
+ if (!runtimeRows.size) await claimNativeOutputs(plan, ctx);
2184
2341
  const files = [];
2185
2342
  const skipped = [];
2186
2343
  for (const entry of plan.entries) {
2187
2344
  if (entry.skipped) { skipped.push({ kind: entry.kind, index: entry.index, platforms: entry.platforms }); continue; }
2188
- const staged = entry.kind === "cargo-bin" ? stageCargoBin(entry, ctx)
2345
+ const staged = entry.kind === "runtime-manifest" ? stageRuntimeManifest(entry, ctx, plan, files, runtimeRows.get(entry.index))
2346
+ : entry.kind === "cargo-bin" ? stageCargoBin(entry, ctx)
2189
2347
  : entry.kind === "ffmpeg" ? await stageFfmpeg(entry, ctx)
2190
2348
  : entry.kind === "onnxruntime" || entry.kind === "native-library" ? await stageNativeLibrary(entry, ctx)
2191
2349
  : entry.kind === "command" ? stageCommand(entry, ctx)
@@ -2195,6 +2353,7 @@ export async function stageSidecars({ appRoot, manifest, target, cacheRoot, ifSt
2195
2353
  : stageResource(entry, ctx);
2196
2354
  files.push(...staged);
2197
2355
  }
2356
+ if (runtimeRows.size) checkRuntimeBundleOutput(appRoot, plan.stageDir, fs);
2198
2357
  const wiped = plan.wipeStageDir ? wipeStaleStageDir(ctx, plan, files.map((file) => path.resolve(appRoot, file.path))) : [];
2199
2358
  const receipt = {
2200
2359
  schema: 1,
@@ -2217,19 +2376,57 @@ export async function stageSidecars({ appRoot, manifest, target, cacheRoot, ifSt
2217
2376
  const stable = (r) => { const { stagedAt: _t, wiped: _w, files, ...rest } = r; return JSON.stringify({ ...rest, files: (files ?? []).map(({ changed: _c, cached: _k, ...file }) => file) }); };
2218
2377
  const sameAs = (old) => stable(old) === stable(receipt);
2219
2378
  let previous = null;
2379
+ if (runtimeRows.size) checkRuntimeBundleOutput(appRoot, plan.receiptPath, fs);
2220
2380
  try { previous = JSON.parse(fs.readFileSync(receiptFile, "utf8")); } catch { previous = null; }
2221
2381
  if (previous && sameAs(previous)) return { receipt: previous, receiptPath: receiptFile, files: previous.files, externalBinNames: previous.files.filter((file) => file.externalBin).map((file) => file.name), unchanged: true };
2382
+ if (runtimeRows.size) checkRuntimeBundleOutput(appRoot, plan.receiptPath, fs);
2222
2383
  fs.mkdirSync(path.dirname(receiptFile), { recursive: true });
2223
2384
  fs.writeFileSync(receiptFile, `${JSON.stringify(receipt, null, 2)}\n`);
2224
2385
  return { receipt, receiptPath: receiptFile, files, externalBinNames: files.filter((file) => file.externalBin).map((file) => file.name) };
2225
2386
  }
2226
2387
 
2388
+ /** Configuration binding for runtime-manifest reuse; the selected catalog row is checked separately. */
2389
+ const runtimePlanDigest = (plan, ctx) => sha256Of(Buffer.from(JSON.stringify({ target: plan.target.triple, mode: plan.mode, entries: plan.entries, catalogDigest: ctx.runtimeCatalogDigest, noticeDigest: ctx.runtimeNoticeDigest })));
2390
+
2391
+ /** The notices actually recorded must equal the preclaimed source bytes. */
2392
+ function validateRuntimeNotices(entry, ctx, rows) {
2393
+ const prefix = `${canonicalOutput(entry.dir)}/`;
2394
+ const expected = new Map([...ctx.runtimeNotices].filter(([key]) => key.startsWith(prefix)));
2395
+ const actual = new Map();
2396
+ for (const row of rows) for (const notice of row.notices ?? []) {
2397
+ const key = canonicalOutput(notice.path);
2398
+ if (!key.startsWith(prefix)) continue;
2399
+ const previous = actual.get(key);
2400
+ if (previous && (previous.output !== notice.path || previous.digest !== notice.sha256)) fail("STAGE_SIDECAR_HASH_MISMATCH", `conflicting notice receipt ${notice.path}`);
2401
+ actual.set(key, { output: notice.path, digest: notice.sha256 });
2402
+ }
2403
+ if (expected.size !== actual.size || [...expected].some(([key, value]) => actual.get(key)?.output !== value.output || actual.get(key)?.digest !== value.digest)) fail("STAGE_SIDECAR_HASH_MISMATCH", `runtime notices changed after planning: ${entry.dir}`);
2404
+ }
2405
+
2406
+ /** Construct only from this run's staged receipt rows, then atomically install the manifest. */
2407
+ function stageRuntimeManifest(entry, ctx, plan, files, catalogRow) {
2408
+ validateRuntimeNotices(entry, ctx, files);
2409
+ const manifest = planRuntimeBundle({ root: ctx.appRoot, dir: entry.dir, target: plan.target, identity: entry.onnxruntime, catalogRow, rows: files, io: ctx.fs });
2410
+ const dest = path.resolve(ctx.appRoot, entry.dir, "manifest.json");
2411
+ const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
2412
+ checkRuntimeBundlePath(ctx.appRoot, entry.dir, ctx.fs);
2413
+ const temp = `${dest}.${ctx.pid}.${Math.random().toString(16).slice(2)}.tmp`;
2414
+ let created = false;
2415
+ try {
2416
+ ctx.fs.writeFileSync(temp, bytes, { flag: "wx" });
2417
+ created = true;
2418
+ ctx.fs.renameSync(temp, dest);
2419
+ created = false;
2420
+ } finally { if (created) ctx.fs.rmSync(temp, { force: true }); }
2421
+ return [{ kind: "runtime-manifest", name: "manifest.json", path: `${entry.dir}/manifest.json`, sha256: sha256Of(bytes), sizeBytes: bytes.length, planSha256: runtimePlanDigest(plan, ctx), externalBin: false }];
2422
+ }
2423
+
2227
2424
  /**
2228
2425
  * The receipt at the plan's receipt path when staging is already current, else null: a valid receipt of this target whose skipped rows are the plan's, that has a file of the
2229
2426
  * same kind and name for every named row the plan stages, and whose every file is on disk, a regular file, with its recorded sha256 (and, for a plan that wipes its stage
2230
2427
  * directory, nothing else in that directory). A receipt that cannot be read or does not match is not current; nothing is ever written.
2231
2428
  */
2232
- function currentStageReceipt(plan, ctx) {
2429
+ function currentStageReceipt(plan, ctx, runtimeRows = new Map()) {
2233
2430
  const { fs, appRoot } = ctx;
2234
2431
  try {
2235
2432
  const receiptFile = path.resolve(appRoot, plan.receiptPath);
@@ -2241,6 +2438,13 @@ function currentStageReceipt(plan, ctx) {
2241
2438
  if (JSON.stringify(skipped) !== JSON.stringify(receipt.skipped ?? [])) return null;
2242
2439
  if (receipt.files.length < planned.length) return null;
2243
2440
  for (const entry of planned) if (typeof entry.name === "string" && ["cargo-bin", "command", "cmake", "prebuilt", "remote"].includes(entry.kind) && !receipt.files.some((file) => file.kind === entry.kind && file.name === entry.name)) return null;
2441
+ for (const entry of planned.filter((item) => item.kind === "ffmpeg" && isObject(item.probe))) {
2442
+ for (const tool of entry.media.tools) {
2443
+ const expectedPath = ffmpegOutput(entry, plan.stageDir, tool, plan.target);
2444
+ const matches = receipt.files.filter((file) => file.kind === "ffmpeg" && file.name === tool && file.path === expectedPath);
2445
+ if (matches.length !== 1 || matches[0].probePolicySha256 !== ctx.strictProbeDigests.get(entry.index) || matches[0].probe !== (canRunTarget(ctx, plan.target) ? "passed" : "skipped-cross-target")) return null;
2446
+ }
2447
+ }
2244
2448
  const named = new Set();
2245
2449
  for (const file of receipt.files) {
2246
2450
  const full = path.resolve(appRoot, file.path);
@@ -2248,6 +2452,14 @@ function currentStageReceipt(plan, ctx) {
2248
2452
  if (!meta.isFile() || sha256Of(fs.readFileSync(full)) !== file.sha256) return null;
2249
2453
  named.add(full.toLowerCase());
2250
2454
  }
2455
+ for (const entry of planned.filter((item) => item.kind === "runtime-manifest")) {
2456
+ const manifestRows = receipt.files.filter((file) => file.kind === "runtime-manifest" && file.path === `${entry.dir}/manifest.json`);
2457
+ if (manifestRows.length !== 1 || manifestRows[0].planSha256 !== runtimePlanDigest(plan, ctx)) return null;
2458
+ const stagedRows = receipt.files.filter((file) => file !== manifestRows[0]);
2459
+ validateRuntimeNotices(entry, ctx, stagedRows);
2460
+ const expected = planRuntimeBundle({ root: appRoot, dir: entry.dir, target: plan.target, identity: entry.onnxruntime, catalogRow: runtimeRows.get(entry.index), rows: stagedRows, io: fs });
2461
+ if (String(fs.readFileSync(path.resolve(appRoot, manifestRows[0].path))) !== `${JSON.stringify(expected, null, 2)}\n`) return null;
2462
+ }
2251
2463
  if (plan.wipeStageDir) {
2252
2464
  named.add(receiptFile.toLowerCase());
2253
2465
  const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).every((item) => {
@@ -185,11 +185,11 @@ const RECORD_STORE_CALL = new RegExp(literal(`${RECORD_STORE_READER}(`), "g");
185
185
  // The crate that defines the reader, and the one place that may call it.
186
186
  const RECORD_STORE_OWNER = "crates/rightkit-license/";
187
187
 
188
- /** A tracked non-test file outside the licence crate that calls the engine's record-store reader. */
188
+ /** A tracked non-test Rust source file outside the licence crate that calls the engine's record-store reader. */
189
189
  export function engineRecordStore(root, files) {
190
190
  const out = [];
191
191
  for (const file of files) {
192
- if (!scanned(file) || file.startsWith(RECORD_STORE_OWNER)) continue;
192
+ if (path.posix.extname(file) !== ".rs" || !scanned(file) || file.startsWith(RECORD_STORE_OWNER)) continue;
193
193
  const text = textOf(root, file);
194
194
  if (text === null || !text.includes(`${RECORD_STORE_READER}(`)) continue;
195
195
  out.push({ file, subject: RECORD_STORE_READER, problem: `${file}:${listed(matchLines(text, RECORD_STORE_CALL))} calls ${RECORD_STORE_READER}: the engine reads the owner's record store itself`, fix: 'have the owner binary hand the engine a snapshot through rightkit_credentials::handoff instead (rightkit-credentials README "Helpers, sidecars and CLIs")' });
package/test-env.mjs ADDED
@@ -0,0 +1,26 @@
1
+ // The environment a unit's test programs run in. One definition for both compile paths (loop review 11, D1): the per-crate rows
2
+ // (local-publish.mjs) and the build-together path (gate/tests.mjs). Before this module the second ran test programs with the gate's
3
+ // whole environment, credentials included.
4
+
5
+ /** Names that carry a credential: a test program never inherits them. */
6
+ export const CREDENTIAL_NAME = /(TOKEN|SECRET|PASSWORD|API_KEY|PRIVATE_KEY)/i;
7
+
8
+ /**
9
+ * `env` without credential-named variables, plus the three settings every unit test runs under: assets are required unless the unit is
10
+ * listed in ci/asset-gated.json (`assetGated`), the checkout is isolated, Cargo prints no colour.
11
+ */
12
+ export function testProgramEnv(env = process.env, assetGated = false) {
13
+ const inherited = Object.fromEntries(Object.entries(env ?? {}).filter(([key]) => !CREDENTIAL_NAME.test(key)));
14
+ return { ...inherited, RIGHTKIT_REQUIRE_ASSETS: assetGated ? "0" : "1", RIGHTKIT_ISOLATED_CHECKOUT: "1", CARGO_TERM_COLOR: "never" };
15
+ }
16
+
17
+ /**
18
+ * The environment part of the key a passed test program is remembered under (gate/tests.mjs): every variable the program will really
19
+ * get, name and value, sorted. Nothing is left out. A test may read any of them (TEMP decides where rightkit-sandbox's tests work), and a
20
+ * shorter list was a guess about which ones matter. The cost is known: a rerun of the same commit from another terminal or session differs
21
+ * in some variable and runs the test programs again. That reruns programs, not Cargo: the remembered broker calls have their own key.
22
+ */
23
+ // One variable is left out: RUST_TEST_THREADS. The gate sets it itself from the size of the machine and of the list (gate/tests.mjs testWidth), so it
24
+ // would change the key whenever one more crate is on the list and every remembered pass would be lost for no reason. It is a share of the
25
+ // machine, not an input of the test. A run that needs one thread says so in its arguments, and those are in the key.
26
+ export const testKeyEnv = (programEnv) => Object.entries(programEnv ?? {}).filter(([name, value]) => typeof value === "string" && name !== "RUST_TEST_THREADS").sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
@@ -0,0 +1,46 @@
1
+ // A tool's version across gate runs, without starting the tool again while its program file is unchanged (GATE-CONTRACT NN01, NN25).
2
+ //
3
+ // Every door run recorded the versions of cargo-deny, cargo-audit, actionlint, shellcheck, rustc and pnpm in the stage binding (gate-stages.mjs
4
+ // bindingOf), by starting each one. So a warm run whose actionlint and shellcheck rows were cache hits still started actionlint and shellcheck
5
+ // (witness fixture, Dell, 2026-11-17: NN01 failed on exactly that). The binding decides whether a whole stage may be reused, so a remembered
6
+ // answer must belong to exactly the program that would run:
7
+ // - the name is resolved on PATH here, as the operating system resolves it (PATHEXT on Windows);
8
+ // - only a real executable is remembered, keyed by its resolved path, size and modification time and the arguments asked;
9
+ // - a .cmd or .bat shim (pnpm, the broker client) is never remembered: what it runs is not the file itself.
10
+ // A failed answer is never stored.
11
+ import crypto from "node:crypto";
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+
15
+ /** The file `cmd` names when started with `env` on `platform`, or null. Absolute paths are taken as they are. */
16
+ export function resolveOnPath(cmd, { env = process.env, platform = process.platform, exists = (f) => { try { return fs.statSync(f).isFile(); } catch { return false; } } } = {}) {
17
+ if (typeof cmd !== "string" || !cmd) return null;
18
+ const exts = platform === "win32" ? (path.extname(cmd) ? [""] : String(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((e) => e.toLowerCase())) : [""];
19
+ const p = platform === "win32" ? path.win32 : path.posix;
20
+ if (p.isAbsolute(cmd)) { for (const e of exts) if (exists(cmd + e)) return cmd + e; return null; }
21
+ if (cmd.includes("/") || cmd.includes("\\")) return null; // a relative path depends on the working directory: not resolved here
22
+ const dirs = String(env.PATH ?? env.Path ?? "").split(platform === "win32" ? ";" : ":").filter(Boolean);
23
+ for (const dir of dirs) for (const e of exts) { const f = p.join(dir, cmd + e); if (exists(f)) return f; }
24
+ return null;
25
+ }
26
+
27
+ /** The remembering key of `cmd args` resolved to `file`, or null when it must not be remembered. */
28
+ export function versionKey(cmd, args, file, { stat = (f) => fs.statSync(f) } = {}) {
29
+ if (!file || /\.(cmd|bat)$/i.test(file)) return null;
30
+ let st; try { st = stat(file); } catch { return null; }
31
+ if (!st?.isFile?.()) return null;
32
+ return crypto.createHash("sha256").update(JSON.stringify(["rightkit.tool-version/1", cmd, args, file, st.size, Math.trunc(st.mtimeMs)])).digest("hex");
33
+ }
34
+
35
+ /**
36
+ * `run(cmd, args)` -> the first line of its output, or null; remembered in `storeFile` (JSON, key -> version). Returns the version or null.
37
+ * `storeFile` null: nothing is remembered (the answer is still returned).
38
+ */
39
+ export function rememberedVersion(cmd, args, { run, storeFile = null, env = process.env, platform = process.platform, resolve = resolveOnPath, stat, readFile = (f) => fs.readFileSync(f, "utf8"), writeFile = (f, t) => { fs.mkdirSync(path.dirname(f), { recursive: true }); const tmp = `${f}.${process.pid}.tmp`; fs.writeFileSync(tmp, t); fs.renameSync(tmp, f); } } = {}) {
40
+ const key = storeFile ? versionKey(cmd, args, resolve(cmd, { env, platform }), stat ? { stat } : {}) : null;
41
+ let store = {};
42
+ if (key) { try { store = JSON.parse(readFile(storeFile)) ?? {}; } catch { store = {}; } if (typeof store[key] === "string" && store[key]) return store[key]; }
43
+ const version = run(cmd, args);
44
+ if (key && typeof version === "string" && version) { try { writeFile(storeFile, JSON.stringify({ ...store, [key]: version })); } catch { /* not remembered: asked again next time */ } }
45
+ return version;
46
+ }
@@ -155,6 +155,10 @@ export function validateWinPackage({ appRoot, config = {}, target, env = process
155
155
  }
156
156
  }
157
157
  if (spec.updater === true && target.updater !== undefined && !isPlainObject(target.updater)) issues.push("target.updater must be an object when winPackage.updater is true");
158
+ if (spec.updater === false && target.updater?.artifacts !== undefined) {
159
+ if (!Array.isArray(target.updater.artifacts)) issues.push("target.updater.artifacts must be an array");
160
+ else if (target.updater.artifacts.length) issues.push("winPackage.updater false conflicts with updater.artifacts");
161
+ }
158
162
  if (isPlainObject(target.updater) && Object.prototype.hasOwnProperty.call(target.updater, "keyFile")) {
159
163
  issues.push("target.updater.keyFile is not supported: updater signing keys come from the OS credential provider (rightkit-credentials, namespace rightsuite-updater-key; see protected-credentials.mjs and sign-updater.mjs), never from a key file. Remove updater.keyFile");
160
164
  }
@@ -174,6 +178,13 @@ export function validateWinPackage({ appRoot, config = {}, target, env = process
174
178
  });
175
179
  }
176
180
 
181
+ /** Only an expanded, explicitly disabled winPackage may omit updater signing. */
182
+ export function winPackageUpdaterDisabled(rawTarget, expandedTarget) {
183
+ return rawTarget?.winPackage?.updater === false
184
+ && expandedTarget?.recipe?.kind === "winPackage"
185
+ && expandedTarget.recipe.updater === false;
186
+ }
187
+
177
188
  function sha256File(file, read) {
178
189
  return createHash("sha256").update(read(file)).digest("hex");
179
190
  }
Binary file