@rightkit/release 0.6.52 → 0.6.54

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 (88) hide show
  1. package/README.md +1 -1
  2. package/adapter-env.mjs +16 -105
  3. package/admission-host.mjs +14 -1
  4. package/bin/darwin/rightkit-swap +0 -0
  5. package/bin/rightkit-gate.mjs +585 -404
  6. package/broker-admission.mjs +122 -2
  7. package/build-launch.mjs +52 -58
  8. package/build-release.mjs +2 -2
  9. package/cargo-ledger.mjs +24 -5
  10. package/cargo-target-shim.mjs +54 -23
  11. package/cargo-target.mjs +2 -2
  12. package/carried-adapter-run.mjs +7 -8
  13. package/carried-cargo-run.mjs +1 -1
  14. package/ci-compile-admission.mjs +1 -1
  15. package/clippy-route.mjs +65 -18
  16. package/compile-inputs.mjs +91 -15
  17. package/cross-targets.mjs +5 -3
  18. package/deps-cargo-lock.mjs +1 -1
  19. package/deterministic-scans.mjs +789 -259
  20. package/development.mjs +33 -7
  21. package/direct-receipt.mjs +3 -5
  22. package/feature-coverage.mjs +45 -9
  23. package/feature-partition.mjs +204 -0
  24. package/feature-sets.mjs +113 -0
  25. package/gate-acceptance.mjs +187 -115
  26. package/gate-seam.mjs +352 -0
  27. package/gate-serve.mjs +34 -2
  28. package/gate-stages.mjs +6 -2
  29. package/ghsa-audit.mjs +19 -4
  30. package/heavy-command.mjs +5 -4
  31. package/install-tauri-authenticode.mjs +73 -4
  32. package/ios-dev.mjs +3 -3
  33. package/ios-package-recipe.mjs +6 -6
  34. package/linux-setup.mjs +3 -2
  35. package/local-publish.mjs +113 -17
  36. package/lock-identity.mjs +24 -100
  37. package/managed-cargo.mjs +3 -3
  38. package/managed-root-guard.mjs +2 -2
  39. package/managed-roots.mjs +3 -3
  40. package/native-adapters.mjs +41 -244
  41. package/native-helpers.mjs +1 -1
  42. package/pack-digest.mjs +1 -1
  43. package/package-recipe-targets.mjs +3 -3
  44. package/package.json +2 -2
  45. package/publication-gate.mjs +29 -6
  46. package/publish-cargo.mjs +4 -5
  47. package/publish-local-cargo.mjs +77 -1
  48. package/qualification-verify.mjs +76 -49
  49. package/receipt-signature.mjs +104 -0
  50. package/release-switch-registry.json +4 -0
  51. package/release-switch-scan.mjs +13 -10
  52. package/rightkit-versions.json +126 -113
  53. package/scan-digest.mjs +43 -14
  54. package/seam-broker.mjs +168 -0
  55. package/snapshot-check.mjs +4 -1
  56. package/snapshot-dependency-reuse.mjs +1 -1
  57. package/snapshot-metadata.mjs +24 -35
  58. package/snapshot.mjs +328 -49
  59. package/stage-commands.mjs +59 -5
  60. package/stage-ledger.mjs +2 -2
  61. package/{carried-cargo.mjs → stage-seam.mjs} +118 -70
  62. package/stage-sidecar.mjs +3 -3
  63. package/tauri-bundle-marker.mjs +5 -2
  64. package/tauri-locked.mjs +1 -1
  65. package/tool-build.mjs +8 -6
  66. package/unit-gate.mjs +40 -10
  67. package/broker-handshake.mjs +0 -160
  68. package/broker-wire.mjs +0 -278
  69. package/build-ownership.mjs +0 -1578
  70. package/cargo-shapes.mjs +0 -332
  71. package/cargo-width.mjs +0 -49
  72. package/carrier-census.mjs +0 -124
  73. package/clippy-equivalence.mjs +0 -202
  74. package/freshness-census.mjs +0 -405
  75. package/handle-revocation.mjs +0 -100
  76. package/handle-revocation.rust-vector.json +0 -1
  77. package/handle-revocation.vectors.json +0 -53
  78. package/legion-freeze-consumer.mjs +0 -241
  79. package/linux-qualifier.mjs +0 -83
  80. package/native-tool-planning.mjs +0 -94
  81. package/owner-process-proof.mjs +0 -14
  82. package/ownership-mark.mjs +0 -191
  83. package/ownership-recover.mjs +0 -78
  84. package/pnpm-adapter-grammar.mjs +0 -226
  85. package/provenance-verify.mjs +0 -413
  86. package/snapshot-broker.mjs +0 -808
  87. package/snapshot-request.mjs +0 -722
  88. package/unit-list-compile.mjs +0 -356
package/development.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import { discoverBrokerSocket, resolveManagedRoots } from './managed-roots.mjs';
2
2
  import { spawnSync } from "./background-process.mjs";
3
3
  import { createHash } from "node:crypto";
4
- import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, lstatSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
4
+ import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, lstatSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import { buildLaunch, createNativeRunner } from "./build-launch.mjs";
6
- import { carriedOutputDir, carriedOutputDirsSince } from "./carried-cargo.mjs";
6
+ import { carriedOutputDir, carriedOutputDirsSince } from "./stage-seam.mjs";
7
7
  import { lockedTauriArgs } from "./tauri-locked.mjs";
8
8
  import path from "node:path";
9
9
  import { fileURLToPath } from "node:url";
@@ -444,12 +444,14 @@ export function assertInstalledExecutableMatches(built, installed, read = readFi
444
444
  const digest = (file) => createHash("sha256").update(withUnknownBundleMarker(file, read)).digest("hex");
445
445
  if (digest(built) !== digest(installed)) throw new Error(`installed executable does not match this dev build: ${installed}`);
446
446
  }
447
- // Tauri's NSIS bundler rewrites the packaged copy's bundle marker UNK -> NSS; compare both copies as UNK.
447
+ // Tauri's NSIS bundler rewrites the packaged copy's bundle marker UNK -> NSS; compare both copies with every NSS marker read as UNK.
448
+ // tauri-utils 2.10 also compiles its match literal "__TAURI_BUNDLE_TYPE_VAR_NSS" into every binary (platform.rs bundle_type), so a
449
+ // correctly patched exe carries two NSS markers (the patched static beside the literal; HeardRight Windows dev 64d82b16, 2026-11-09).
450
+ // Both copies normalise the same offsets, so any other byte difference still fails the comparison.
448
451
  function withUnknownBundleMarker(file, read) {
449
452
  const bytes = Buffer.from(read(file));
450
453
  const nsis = readTauriBundleMarkers(file, { read: () => bytes }).markers.nsis ?? [];
451
- if (nsis.length > 1) throw new Error(`installed executable verification failed: ${nsis.length} NSIS bundle markers in ${file}`);
452
- if (nsis.length === 1) bundleMarkerBuffer(BUNDLE_MARKERS.unknown).copy(bytes, nsis[0]);
454
+ for (const offset of nsis) bundleMarkerBuffer(BUNDLE_MARKERS.unknown).copy(bytes, offset);
453
455
  return bytes;
454
456
  }
455
457
  function assertNonEmptyExecutable(file) { if (!existsSync(file) || !statSync(file).isFile() || statSync(file).size === 0) throw new Error(`installed executable verification failed: missing or empty file ${file}`); }
@@ -469,7 +471,7 @@ function resolveBundleRoot(descriptor, { root, env, runCargo }) {
469
471
  } finally { process.chdir(cwd); }
470
472
  if (metadata.error || metadata.status !== 0) throw new Error(`RightKit Cargo metadata failed (${metadata.status ?? "unavailable"})${metadata.error ? `: ${metadata.error.message}` : ""}`);
471
473
  let targetDirectory;
472
- // A carried call (a snapshot stage's, carried-cargo.mjs) reports the signed receipt's output directory, not what metadata prints.
474
+ // A carried call (a snapshot stage's, stage-seam.mjs) reports the signed receipt's output directory, not what metadata prints.
473
475
  if (typeof metadata.outputDir === "string") targetDirectory = metadata.outputDir;
474
476
  else try { targetDirectory = JSON.parse(metadata.stdout).target_directory; } catch { throw new Error("RightKit Cargo metadata returned invalid JSON"); }
475
477
  if (!targetDirectory || !path.isAbsolute(targetDirectory)) throw new Error("Cargo metadata omitted absolute target_directory");
@@ -544,10 +546,12 @@ export function resolvePnpmCli({ root, env = process.env } = {}) {
544
546
  if (parent === dir) break;
545
547
  }
546
548
  // A global pnpm (no Corepack in Node >= 25) exposes its JS entry only through its PATH shim.
549
+ // pnpm >= 11 installed by pnpm itself writes a shim naming the package's native launcher (`...\node_modules\pnpm\pnpm`, no extension); the JavaScript
550
+ // entry beside it (bin/pnpm.mjs) is derived below. The Dell, 2026-11-10: sign-updater could not find pnpm.
547
551
  for (const dir of String(env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean)) {
548
552
  const shim = path.join(dir, "pnpm.CMD");
549
553
  if (!existsSync(shim)) continue;
550
- const match = /"%~dp0\\([^"]*pnpm\.(?:mjs|cjs|js))"/i.exec(readFileSync(shim, "utf8"));
554
+ const match = /"%~dp0\\([^"]*pnpm(?:\.(?:mjs|cjs|js|exe))?)"/i.exec(readFileSync(shim, "utf8"));
551
555
  if (match) candidates.push(path.resolve(dir, match[1]));
552
556
  }
553
557
  // Unix global pnpm exposes its JavaScript entry through a PATH symlink.
@@ -587,6 +591,8 @@ export async function main(args = process.argv.slice(2)) {
587
591
  }
588
592
  if (!platform) throw new Error("right-release dev requires --platform win|mac|linux|android|ios");
589
593
  const absoluteConfig = path.resolve(configPath);
594
+ // rightkit#1555: the door's report path, read before the environment is reshaped; the report is written only after the whole dev step succeeded.
595
+ const reportEnv = { [SIGNED_IN_PLACE_REPORT_ENV]: process.env[SIGNED_IN_PLACE_REPORT_ENV] };
590
596
  const safeEnv = developmentEnvironment(process.env);
591
597
  for (const [key, value] of Object.entries(safeEnv)) process.env[key] = value;
592
598
  for (const key of RELEASE_ONLY_APPLE_ENV) delete process.env[key];
@@ -596,6 +602,10 @@ export async function main(args = process.argv.slice(2)) {
596
602
  const config = await importReleaseConfig(absoluteConfig, { lenient: true });
597
603
  const result = await runDevelopment({ root: path.dirname(absoluteConfig), platform, config, dryRun, buildOnly, serial });
598
604
  if (dryRun) console.log(JSON.stringify(result.plan, null, 2));
605
+ // Written last, on every successful route, a dry run included: the Authenticode install's verified in-place signatures, an empty list on
606
+ // any other route (--dry-run, --build-only, another install kind). Whatever the app's config code or a build step wrote earlier is
607
+ // overwritten; a failed step writes none.
608
+ writeSignedInPlaceReport(reportEnv, result?.authenticode?.stageOutputs ?? { files: [] });
599
609
  return result;
600
610
  }
601
611
 
@@ -603,3 +613,19 @@ const realOrSelf = (file) => { try { return realpathSync(file); } catch { return
603
613
  if (process.argv[1] && realOrSelf(process.argv[1]) === realOrSelf(fileURLToPath(import.meta.url))) {
604
614
  main().catch((error) => { console.error(`right-release dev: ${error.code ? `[${error.code}] ` : ""}${error.message}`); process.exitCode = 1; });
605
615
  }
616
+
617
+ /** The report variable a door run names for right-release dev: where the signer's in-place rewrites of staged files are reported (rightkit#1555). */
618
+ export const SIGNED_IN_PLACE_REPORT_ENV = "RIGHTKIT_SIGNED_IN_PLACE_REPORT";
619
+ export const SIGNED_IN_PLACE_SCHEMA = "rightkit.signed-in-place/1";
620
+ /**
621
+ * A door run (the gate sets RIGHTKIT_SIGNED_IN_PLACE_REPORT to a file beside, never inside, its snapshot) learns which staged files the
622
+ * Authenticode step rewrote in place and from which bytes to which: `{ schema, files: [{ path (absolute), sha256Before, sha256After }] }`.
623
+ * Without the variable (a manual run) nothing is written.
624
+ */
625
+ export function writeSignedInPlaceReport(env, stageOutputs) {
626
+ const file = env?.[SIGNED_IN_PLACE_REPORT_ENV];
627
+ if (typeof file !== "string" || !path.isAbsolute(file)) return null;
628
+ const files = (stageOutputs?.files ?? []).filter((f) => f?.kind === "signed-in-place").map((f) => ({ path: path.resolve(f.path), sha256Before: f.sha256Before, sha256After: f.sha256 }));
629
+ writeFileSync(file, `${JSON.stringify({ schema: SIGNED_IN_PLACE_SCHEMA, files }, null, 2)}\n`, { mode: 0o600 });
630
+ return file;
631
+ }
@@ -2,19 +2,18 @@
2
2
  // - the output directory, resolved in the PRIMARY CHECKOUT with the stage's environment before the source location changes, with
3
3
  // its inputs recorded (7.09);
4
4
  // - the receipt the gate writes itself, "the same field names minus the broker-only ones (admission, queue, reusedFrom)" (7.18),
5
- // and the consumer-side matrix that refuses a receipt that lacks one, carries a broker-only one, or holds no census (7.22 Linux half).
5
+ // and the consumer-side matrix that refuses a receipt that lacks one, carries a broker-only one, (7.22 Linux half).
6
6
  // Pure functions with injected spawn and file system: the gate (bin/rightkit-gate.mjs) wires them to the host.
7
7
  import { createHash } from "node:crypto";
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
- import { validateFreshness } from "./freshness-census.mjs";
11
10
 
12
11
  export const DIRECT_RECEIPT_SCHEMA = "rightkit.gate-direct-receipt/1";
13
12
  export const DIAGNOSTICS_SCHEMA = "rightkit.gate-direct-diagnostics/1";
14
13
  /** The names GATE-CONTRACT lists as broker-only: a direct receipt never carries them. */
15
14
  export const BROKER_ONLY_FIELDS = Object.freeze(["admission", "queue", "reusedFrom"]);
16
15
  /** The contract's returned-evidence names a direct receipt carries (7.18). `snapshot.path|treeAtStart|treeAtExit` are checked inside `snapshot`. */
17
- export const DIRECT_RECEIPT_REQUIRED = Object.freeze(["requestId", "brokerVersion", "executor", "commit", "snapshot", "declaredInputDigests", "verdict", "freshness", "timingsMs", "exit", "diagnosticsPath", "outputDir", "refreshed"]);
16
+ export const DIRECT_RECEIPT_REQUIRED = Object.freeze(["requestId", "brokerVersion", "executor", "commit", "snapshot", "declaredInputDigests", "verdict", "timingsMs", "exit", "diagnosticsPath", "outputDir", "refreshed"]);
18
17
  export const TIMING_FIELDS = Object.freeze(["bind", "cargo", "afterExitBind", "diagnostics"]);
19
18
  /** The environment a `cargo metadata` target resolution reads: recorded by value (the rest of the environment by digest only). */
20
19
  export const TARGET_ENV_NAMES = Object.freeze(["CARGO_TARGET_DIR", "CARGO_BUILD_TARGET_DIR", "CARGO_HOME", "RUSTUP_TOOLCHAIN"]);
@@ -90,7 +89,7 @@ export function buildDirectReceipt({ requestId, issuedAt, commit, snapshotPath,
90
89
 
91
90
  /**
92
91
  * The consumer's matrix over a direct receipt (the Linux half of row 7.22): every contract name present with the right type, the
93
- * snapshot bound to the commit's tree at start and exit, a well formed freshness census, and none of the broker-only names.
92
+ * snapshot bound to the commit's tree at start and exit, and none of the broker-only names (no freshness census: the gate does not judge rebuild causes, reset plan section 4).
94
93
  * Returns the list of problems; an empty list means the receipt verifies.
95
94
  */
96
95
  export function verifyDirectReceipt(receipt) {
@@ -113,7 +112,6 @@ export function verifyDirectReceipt(receipt) {
113
112
  if (Object.hasOwn(receipt, "declaredInputDigests") && !Array.isArray(receipt.declaredInputDigests)) problems.push("declaredInputDigests is not a list");
114
113
  const verdict = receipt.verdict;
115
114
  if (Object.hasOwn(receipt, "verdict") && !(verdict && (verdict.result === "PASSED" || verdict.result === "FAILED"))) problems.push("verdict has no PASSED or FAILED result");
116
- if (Object.hasOwn(receipt, "freshness")) for (const p of validateFreshness(receipt.freshness)) problems.push(p);
117
115
  const timings = receipt.timingsMs;
118
116
  if (Object.hasOwn(receipt, "timingsMs")) {
119
117
  if (!timings || typeof timings !== "object") problems.push("timingsMs is not an object");
@@ -10,7 +10,11 @@
10
10
  // 2. `featureCoverageProblems`: every feature a crate's Cargo.toml declares must be enabled by at least one set of its plan (the
11
11
  // default features, a declared set, or a generated one); FEATURE_UNCOVERED names the crate and the feature.
12
12
  //
13
- // Dependency-free by design: scan-digest.mjs-style callers (the credentialed receipt verifiers) import it.
13
+ // 3. `unlintedFeatures` (ci/gate.config.json rust.<crate>): a feature the gate never lints, named with its reason; it counts as covered, and
14
+ // a name the crate does not declare, or that a set enables, is an error. Coverage is judged over every set whatever its hosts (feature-sets.mjs).
15
+ //
16
+ // Dependency-free by design (feature-sets.mjs imports nothing): scan-digest.mjs-style callers (the credentialed receipt verifiers) import it.
17
+ import { hasHostScopedSets, unlintedFeatures } from "./feature-sets.mjs";
14
18
 
15
19
  /** The feature table of a Cargo.toml: a Map of feature name to its array of members ("other", "dep:x", "x/feat", "x?/feat"). `default` included. */
16
20
  export function manifestFeatures(text) {
@@ -100,20 +104,42 @@ export function featuresEnabledBy(features, set) {
100
104
  return enabled;
101
105
  }
102
106
 
103
- /** A crate's features that none of `sets` enables: `[]` when every declared feature is covered. */
104
- export function uncoveredFeatures(manifestText, sets) {
107
+ /** A crate's features that none of `sets` enables and the crate does not list in `unlinted` (`unlintedFeatures`): `[]` when every declared feature is covered. */
108
+ export function uncoveredFeatures(manifestText, sets, unlinted = {}) {
105
109
  const features = manifestFeatures(manifestText);
106
- const declared = [...features.keys()].filter((name) => name !== "default");
110
+ const declared = [...features.keys()].filter((name) => name !== "default" && !Object.hasOwn(unlinted, name));
107
111
  const covered = new Set();
108
112
  for (const set of sets) for (const f of featuresEnabledBy(features, set)) covered.add(f);
109
113
  return declared.filter((name) => !covered.has(name)).sort();
110
114
  }
111
115
 
112
- /** The FEATURE_UNCOVERED lines of one crate (`name`, its manifest text, every feature set its plan runs). */
113
- export function featureCoverageProblems({ name, manifestText, sets }) {
114
- const missing = uncoveredFeatures(manifestText, sets);
116
+ /**
117
+ * The problem lines of a crate's `unlintedFeatures` (feature-sets.mjs): a feature it names must be declared by the crate's Cargo.toml and
118
+ * enabled by none of the planned sets, or the entry is stale and the gate would lint a feature the config says it never lints.
119
+ */
120
+ export function unlintedFeatureProblems({ name, manifestText, sets, unlinted = {} }) {
121
+ const features = manifestFeatures(manifestText);
122
+ const enabled = new Set();
123
+ for (const set of sets) for (const f of featuresEnabledBy(features, set)) enabled.add(f);
124
+ const problems = [];
125
+ for (const feature of Object.keys(unlinted).sort()) {
126
+ if (feature === "default" || !features.has(feature)) problems.push(`UNLINTED_FEATURE_UNKNOWN ${name}: unlintedFeatures names "${feature}", which the crate's Cargo.toml does not declare; remove it from ci/gate.config.json rust.${name}.unlintedFeatures`);
127
+ else if (enabled.has(feature)) problems.push(`UNLINTED_FEATURE_ENABLED ${name}: unlintedFeatures names "${feature}" but a declared feature set enables it; it is linted, so remove it from ci/gate.config.json rust.${name}.unlintedFeatures`);
128
+ }
129
+ return problems;
130
+ }
131
+
132
+ /**
133
+ * The FEATURE_UNCOVERED lines of one crate (`name`, its manifest text, every feature set its plan runs on any host, its `unlintedFeatures`),
134
+ * and the lines of an `unlintedFeatures` entry that is stale.
135
+ */
136
+ export function featureCoverageProblems({ name, manifestText, sets, unlinted = {} }) {
137
+ const missing = uncoveredFeatures(manifestText, sets, unlinted);
115
138
  const planned = sets.map((s) => (s.length ? s.join(" ") : "default features")).join("; ");
116
- return missing.map((feature) => `FEATURE_UNCOVERED ${name}: feature "${feature}" is enabled by none of the planned feature sets (${planned}); add a set that enables it to ci/gate.config.json rust.${name}.featureSets, or --all-features where the features do not conflict`);
139
+ return [
140
+ ...missing.map((feature) => `FEATURE_UNCOVERED ${name}: feature "${feature}" is enabled by none of the planned feature sets (${planned}); add a set that enables it to ci/gate.config.json rust.${name}.featureSets, or --all-features where the features do not conflict, or name it with a reason in rust.${name}.unlintedFeatures`),
141
+ ...unlintedFeatureProblems({ name, manifestText, sets, unlinted }),
142
+ ];
117
143
  }
118
144
 
119
145
  /**
@@ -125,10 +151,20 @@ export function effectiveCrateFeatures({ crateFeatures = {}, units, manifestOf }
125
151
  const out = { ...crateFeatures };
126
152
  for (const name of units) {
127
153
  const own = crateFeatures?.[name] ?? {};
154
+ // A malformed `unlintedFeatures` or host-scoped set is refused here, loudly, before any plan is built from it.
155
+ const unlinted = Object.keys(unlintedFeatures(own, name));
156
+ hasHostScopedSets(own, name);
128
157
  if (Array.isArray(own.featureSets) && own.featureSets.length) continue;
129
158
  let text = null;
130
159
  try { text = manifestOf(name); } catch { text = null; }
131
- if (typeof text === "string" && declaredFeatureNames(text).length) out[name] = { ...own, autoAllFeatures: true };
160
+ if (typeof text !== "string") continue;
161
+ const declared = declaredFeatureNames(text);
162
+ if (!declared.length) continue;
163
+ // A feature named in `unlintedFeatures` is never added to a generated set: the generated set lists every other feature instead of --all-features.
164
+ if (unlinted.length) {
165
+ const rest = declared.filter((feature) => !unlinted.includes(feature)).sort();
166
+ if (rest.length) out[name] = { ...own, autoAllFeatures: true, autoFeatures: rest };
167
+ } else out[name] = { ...own, autoAllFeatures: true };
132
168
  }
133
169
  return out;
134
170
  }
@@ -0,0 +1,204 @@
1
+ // Feature-equivalence partition of a class B group (GATE-CONTRACT GC-A18; rightkit#1538 finding 3, reset plan section 8).
2
+ //
3
+ // One cargo invocation naming several crates (`-p a -p b`) unifies features: a dependency both crates use is compiled once with the union of
4
+ // the features each enables, so `a` is checked against more of `d` than it enables alone. A grouped pass is a pass for `a` alone only when,
5
+ // for every package in `a`'s own graph, the group resolves the same feature set `a` resolves on its own (features are additive, so the group
6
+ // can only enable more). Cargo's own resolver answers that: `cargo tree -p a` lists each package of `a`'s selection with its resolved
7
+ // features, `cargo tree -p a -p b` lists the group's. The planner compares the two per member and splits a group on the first difference:
8
+ // the members that are equivalent stay one invocation (removing a member only removes features, so their own resolution is unchanged), the
9
+ // others are partitioned again among themselves, down to single crates. A crate that ends alone carries the package and the two feature
10
+ // sets that split it, for the run notes.
11
+ //
12
+ // `cargo tree` compiles nothing and reads only manifests and the lock, so it runs as a class A read (direct cargo, scratch target), and the
13
+ // partition of a configuration group is cached on the workspace's Cargo.lock, every Cargo.toml and the toolchain file: a manifest edit
14
+ // recomputes it, anything else reuses it.
15
+ //
16
+ // Dependency-free by design (node built-ins only); deterministic-scans.mjs imports it.
17
+ import crypto from "node:crypto";
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+
21
+ export const FEATURE_PARTITION_SCHEMA = "rightkit.feature-partition/1";
22
+ const sha256 = (v) => crypto.createHash("sha256").update(v).digest("hex");
23
+ /** `{p}` and `{f}` with a tab between: the package (name, version, source) and its comma-separated resolved features. */
24
+ export const TREE_FORMAT = "{p}\t{f}";
25
+
26
+ /** Flags of a cargo argv that decide feature resolution and travel to `cargo tree` unchanged. */
27
+ const FEATURE_FLAGS = new Set(["--all-features", "--no-default-features"]);
28
+ const FEATURE_VALUE_FLAGS = new Set(["--features", "-F", "--manifest-path"]);
29
+ /** Build targets whose dependencies are dev-dependencies: when one is compiled, dev edges join the resolution (resolver 2). */
30
+ const DEV_TARGET_FLAGS = new Set(["--all-targets", "--tests", "--benches", "--examples"]);
31
+
32
+ /**
33
+ * `rest` without its package selectors: every `-p <crate>` / `--package <crate>` pair and `--target <triple>` removed, nothing else touched.
34
+ * Returns { rest, crates, targets }.
35
+ */
36
+ export function stripSelectors(argv) {
37
+ const rest = []; const crates = []; const targets = [];
38
+ const stop = argv.indexOf("--"); const own = stop < 0 ? argv : argv.slice(0, stop);
39
+ for (let i = 0; i < own.length; i += 1) {
40
+ const w = own[i];
41
+ if ((w === "-p" || w === "--package") && typeof own[i + 1] === "string") { crates.push(own[i + 1]); i += 1; continue; }
42
+ if (w === "--target" && typeof own[i + 1] === "string") { targets.push(own[i + 1]); i += 1; continue; }
43
+ if (/^--package=/.test(w)) { crates.push(w.slice("--package=".length)); continue; }
44
+ if (/^--target=/.test(w)) { targets.push(w.slice("--target=".length)); continue; }
45
+ rest.push(w);
46
+ }
47
+ return { rest, crates, targets };
48
+ }
49
+
50
+ /**
51
+ * The `cargo tree` argv (after `cargo`) that resolves `packages` the way `rest` (a cargo argv after `cargo`, selectors removed) compiles
52
+ * them: the same feature flags, dev edges when the command builds dev targets (test, bench, --all-targets, --tests, --benches, --examples),
53
+ * `--target` as given, `--locked`, one line per package in TREE_FORMAT.
54
+ */
55
+ export function treeArgs({ rest, packages, target = null }) {
56
+ if (!Array.isArray(rest) || !rest.length || typeof rest[0] !== "string") throw new TypeError("treeArgs: rest must start with the cargo subcommand");
57
+ if (!Array.isArray(packages) || !packages.length || packages.some((p) => typeof p !== "string" || !/^[A-Za-z0-9_-]+$/.test(p))) throw new TypeError("treeArgs: packages must be plain crate names");
58
+ const [sub, ...own] = rest;
59
+ const stop = own.indexOf("--"); const flags = stop < 0 ? own : own.slice(0, stop);
60
+ const dev = sub === "test" || sub === "bench" || flags.some((w) => DEV_TARGET_FLAGS.has(w));
61
+ const carried = [];
62
+ for (let i = 0; i < flags.length; i += 1) {
63
+ const w = flags[i];
64
+ if (FEATURE_FLAGS.has(w)) carried.push(w);
65
+ else if (FEATURE_VALUE_FLAGS.has(w) && typeof flags[i + 1] === "string") { carried.push(w, flags[i + 1]); i += 1; }
66
+ else if (/^(?:--features=|--manifest-path=|-F.)/.test(w)) carried.push(w);
67
+ }
68
+ return ["tree", "--locked", "--prefix", "none", "-e", dev ? "normal,build,dev" : "normal,build", "-f", TREE_FORMAT, ...carried, ...(target ? ["--target", target] : []), ...packages.flatMap((p) => ["-p", p])];
69
+ }
70
+
71
+ /**
72
+ * The resolved features of a `cargo tree` run in TREE_FORMAT: Map of package (`name vX.Y.Z [(source)]`) to the Set of distinct feature lists
73
+ * it was resolved with (a proc-macro or build dependency can appear for the host and the target with different features; each list is
74
+ * sorted and comma-joined, "" for none). Lines without a tab (a client banner, a warning) are skipped; cargo's `(*)` de-duplication mark is dropped.
75
+ */
76
+ export function parseTreeFeatures(text) {
77
+ const out = new Map();
78
+ for (const raw of String(text ?? "").split(/\r?\n/)) {
79
+ const at = raw.indexOf("\t");
80
+ if (at < 0) continue;
81
+ const pkg = raw.slice(0, at).trim();
82
+ const feats = raw.slice(at + 1).replace(/\s*\(\*\)\s*$/, "").trim();
83
+ if (!pkg) continue;
84
+ const list = feats.split(",").map((f) => f.trim()).filter(Boolean).sort().join(",");
85
+ if (!out.has(pkg)) out.set(pkg, new Set());
86
+ out.get(pkg).add(list);
87
+ }
88
+ return out;
89
+ }
90
+
91
+ const sameSet = (a, b) => a.size === b.size && [...a].every((x) => b.has(x));
92
+
93
+ /**
94
+ * The first package the group resolves differently from the member alone, or null when the group is the member's own resolution for every
95
+ * package of the member's graph. `own` and `group` are parseTreeFeatures maps.
96
+ */
97
+ export function memberDifference(own, group) {
98
+ for (const [pkg, feats] of own) {
99
+ const g = group.get(pkg);
100
+ if (!g || !sameSet(feats, g)) return { package: pkg, own: [...feats].sort(), group: g ? [...g].sort() : [] };
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * Partitions `crates` into feature-equivalent groups. `tree(packages)` resolves a selection (the text of `cargo tree` in TREE_FORMAT).
107
+ * Returns `[{ crates, split }]` in a deterministic order: `split` is null for a group every member of which resolves alone exactly as in
108
+ * it, and for a crate that ends alone names the package and feature sets that separated it. `concurrency` bounds the parallel tree runs.
109
+ */
110
+ export async function partitionByFeatures({ crates, tree, concurrency = 4 }) {
111
+ if (!Array.isArray(crates) || new Set(crates).size !== crates.length) throw new TypeError("partitionByFeatures: crates must be distinct");
112
+ if (typeof tree !== "function") throw new TypeError("partitionByFeatures: tree must be a function");
113
+ const own = new Map();
114
+ let active = 0; const waiting = [];
115
+ const slot = async () => { if (active >= Math.max(1, concurrency)) await new Promise((r) => waiting.push(r)); active += 1; };
116
+ const free = () => { active -= 1; const next = waiting.shift(); if (next) next(); };
117
+ const resolve = async (packages) => { await slot(); try { return parseTreeFeatures(await tree([...packages].sort())); } finally { free(); } };
118
+ const ownOf = (c) => { if (!own.has(c)) own.set(c, resolve([c])); return own.get(c); };
119
+ const out = [];
120
+ const split = async (set, why) => {
121
+ if (set.length === 1) { out.push({ crates: set, split: why ?? null }); return; }
122
+ const [group, ...owns] = await Promise.all([resolve(set), ...set.map(ownOf)]);
123
+ const keep = []; const apart = [];
124
+ set.forEach((c, i) => { const d = memberDifference(owns[i], group); if (d) apart.push({ crate: c, d }); else keep.push(c); });
125
+ if (!apart.length) { out.push({ crates: set, split: null }); return; }
126
+ // The equivalent members stay one invocation: without the others the group resolves no more than it did, and no less than each resolves alone.
127
+ if (keep.length) out.push({ crates: keep, split: null });
128
+ // Members the whole group changed: each stands alone when every member conflicts (a smaller group of the same members would conflict the
129
+ // same way); otherwise they are partitioned again among themselves.
130
+ if (!keep.length || apart.length === 1) { for (const a of apart) out.push({ crates: [a.crate], split: { crate: a.crate, ...a.d } }); return; }
131
+ await split(apart.map((a) => a.crate), null);
132
+ };
133
+ await split([...crates].sort(), null);
134
+ out.sort((a, b) => (a.crates[0] < b.crates[0] ? -1 : 1));
135
+ return out;
136
+ }
137
+
138
+ /**
139
+ * The common refinement of several partitions of the same crates (one per `--target` of a group naming several targets, NN42): two crates share a
140
+ * group only when every partition puts them in the same part, so no boundary any target drew is crossed. A crate alone in any partition stays
141
+ * alone and keeps that partition's split reason; otherwise the split is null. Returns `[{ crates, split }]` sorted by first crate.
142
+ */
143
+ export function meetPartitions(perTarget) {
144
+ if (!Array.isArray(perTarget) || !perTarget.length) throw new TypeError("meetPartitions: needs at least one partition");
145
+ if (perTarget.length === 1) return perTarget[0];
146
+ const crates = [...new Set(perTarget.flatMap((parts) => parts.flatMap((p) => p.crates)))].sort();
147
+ const signature = new Map(); const reason = new Map();
148
+ for (const c of crates) {
149
+ const sig = perTarget.map((parts) => { const at = parts.findIndex((p) => p.crates.includes(c)); if (at >= 0 && parts[at].split && !reason.has(c)) reason.set(c, parts[at].split); return at; });
150
+ if (sig.some((at) => at < 0)) throw new Error(`meetPartitions: ${c} is missing from a partition`);
151
+ signature.set(c, sig.join("/"));
152
+ }
153
+ const groups = new Map();
154
+ for (const c of crates) { const k = signature.get(c); if (!groups.has(k)) groups.set(k, []); groups.get(k).push(c); }
155
+ return [...groups.values()].map((set) => ({ crates: set, split: set.length === 1 ? (reason.get(set[0]) ?? null) : null })).sort((a, b) => (a.crates[0] < b.crates[0] ? -1 : 1));
156
+ }
157
+
158
+ /** One line for the run notes: why a crate runs alone. */
159
+ export function splitNote(split) {
160
+ return `${split.crate} compiles alone: ${split.package} resolves to {${split.own.join(" | ") || "no features"}} for it and to {${split.group.join(" | ") || "no features"}} in its group`;
161
+ }
162
+
163
+ /**
164
+ * sha256 over what `cargo tree` reads: under `dir` Cargo.lock, every Cargo.toml, rust-toolchain(.toml) and `.cargo/config(.toml)` (target, node_modules and other dot
165
+ * directories skipped), by relative path; above it, every ancestor's and CARGO_HOME's `.cargo` configuration. The partition of a configuration group is cached on it.
166
+ */
167
+ export function workspaceManifestDigest(dir, { fsApi = fs, env = process.env } = {}) {
168
+ const h = crypto.createHash("sha256");
169
+ const walk = (d) => {
170
+ let entries; try { entries = fsApi.readdirSync(d, { withFileTypes: true }); } catch { return; }
171
+ for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
172
+ // `.cargo/config.toml` (patches, target cfg, rustflags) is a resolution input; every other dot directory is not.
173
+ if ((e.name.startsWith(".") && e.name !== ".cargo") || e.name === "node_modules" || e.name === "target") continue;
174
+ const p = path.join(d, e.name);
175
+ const inCargoDir = path.basename(d) === ".cargo";
176
+ if (e.isDirectory()) walk(p);
177
+ else if (e.isFile() && (e.name === "Cargo.toml" || e.name === "Cargo.lock" || e.name === "rust-toolchain" || e.name === "rust-toolchain.toml" || (inCargoDir && (e.name === "config.toml" || e.name === "config")))) { h.update(path.relative(dir, p).split(path.sep).join("/")); h.update("\0"); h.update(fsApi.readFileSync(p)); h.update("\0"); }
178
+ }
179
+ };
180
+ walk(dir);
181
+ // Cargo also reads the configuration of every directory above the workspace and of CARGO_HOME (Cargo's config discovery): patches, target cfg and rustflags
182
+ // there change what resolves, so their bytes are inputs too (fresh review of badf93c).
183
+ const extra = [];
184
+ for (let d = path.dirname(path.resolve(dir)); ; d = path.dirname(d)) {
185
+ for (const n of ["config.toml", "config"]) extra.push(path.join(d, ".cargo", n));
186
+ if (path.dirname(d) === d) break;
187
+ }
188
+ const cargoHome = env.CARGO_HOME || (env.HOME || env.USERPROFILE ? path.join(env.HOME || env.USERPROFILE, ".cargo") : null);
189
+ if (cargoHome) for (const n of ["config.toml", "config"]) extra.push(path.join(cargoHome, n));
190
+ for (const f of extra) { let bytes; try { bytes = fsApi.readFileSync(f); } catch { continue; } h.update(`\0config:${f}\0`); h.update(bytes); }
191
+ return h.digest("hex");
192
+ }
193
+
194
+ /** The code of this module, part of every partition key: a change to how the partition is computed invalidates every stored partition. */
195
+ let moduleDigestMemo = null;
196
+ function moduleDigest() {
197
+ if (moduleDigestMemo === null) { try { moduleDigestMemo = sha256(fs.readFileSync(new URL(import.meta.url))); } catch { moduleDigestMemo = "unreadable"; } }
198
+ return moduleDigestMemo;
199
+ }
200
+
201
+ /** The cache key of one configuration group's partition: the command shape, the crates, the target, the workspace, its manifest digest, the cargo that resolved and this module's code. */
202
+ export function partitionCacheKey({ rest, crates, target = null, cwd = ".", inputs, toolVersion = null }) {
203
+ return sha256(`${FEATURE_PARTITION_SCHEMA}\0${JSON.stringify({ rest, crates: [...crates].sort(), target, cwd, inputs, toolVersion, code: moduleDigest() })}`);
204
+ }
@@ -0,0 +1,113 @@
1
+ // The one reader of a crate's feature sets in ci/gate.config.json `rust.<crate>` (`featureSets`, `checkFeatureSets`) and of its
2
+ // `unlintedFeatures`. No imports, by design: scan-digest.mjs (shared with the credentialed receipt verifiers) uses it.
3
+ //
4
+ // A set is either an argv array (`["--features", "a,b"]`, `[]` for default features; the form every crate used before, unchanged
5
+ // in meaning: every host) or a host-scoped object
6
+ //
7
+ // { "features": ["--features", "metal,blas"], "hosts": ["darwin"], "hostsReason": "why only those hosts" }
8
+ //
9
+ // A host-scoped set is a native-host set (rightkit#1231 follow-up): it is planned only on the hosts it names (check-features, clippy, doc, test and
10
+ // publisher rows alike), and it plans no cross-target (foreign OS) lint row, because a feature whose build needs one OS's SDK or system library
11
+ // cannot be type-checked for another. Host words are `process.platform` words, the same vocabulary and validation style as the crate-level
12
+ // `platforms` / `platformsReason` (cross-targets.mjs crateRunsOn). Coverage (FEATURE_UNCOVERED) is judged over every set whatever its hosts: the
13
+ // feature is linted on the host whose plan has it.
14
+ //
15
+ // Every read site goes through `hostFeatureSets` (the sets one host plans), `crossFeatureSets` (the sets whose rows are also linted for
16
+ // foreign OS targets) or `allFeatureSets` (coverage), so downstream code keeps seeing plain argv arrays. When a list holds no object entry,
17
+ // each function returns the configured array itself: the planned rows and their ids are byte-for-byte what they were.
18
+
19
+ /** The host words a set may name; equals Object.keys(CROSS_TARGETS) (cross-targets.mjs; a test holds the two equal). */
20
+ export const FEATURE_SET_HOSTS = Object.freeze(["darwin", "win32", "linux"]);
21
+
22
+ const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
23
+ const where = (crate, key, index) => `ci/gate.config.json rust.${crate}.${key}[${index}]`;
24
+
25
+ /** True for a host-scoped (object) entry. */
26
+ export const isScopedFeatureSet = (entry) => isPlainObject(entry);
27
+
28
+ /**
29
+ * Validates one list and returns `[{ features, hosts }]` (`hosts` is null for an every-host argv array). Throws, naming the crate, on
30
+ * anything malformed: a quietly ignored scope would drop a crate's checks.
31
+ */
32
+ export function featureSetEntries(list, key = "featureSets", crate = "<crate>") {
33
+ if (!Array.isArray(list)) throw new Error(`ci/gate.config.json rust.${crate}.${key} must be a list of feature sets, not ${JSON.stringify(list)}`);
34
+ return list.map((entry, index) => {
35
+ if (Array.isArray(entry)) return { features: entry, hosts: null };
36
+ const at = where(crate, key, index);
37
+ if (!isPlainObject(entry)) throw new Error(`${at} must be an argv array or a { features, hosts, hostsReason } object, not ${JSON.stringify(entry)}`);
38
+ const unknown = Object.keys(entry).filter((k) => !["features", "hosts", "hostsReason"].includes(k));
39
+ if (unknown.length) throw new Error(`${at} has unknown key(s) ${unknown.join(", ")}; a host-scoped set is { features, hosts, hostsReason }`);
40
+ if (!Array.isArray(entry.features) || entry.features.some((word) => typeof word !== "string" || !word)) throw new Error(`${at}.features must be an argv array of non-empty strings`);
41
+ const hosts = entry.hosts;
42
+ if (!Array.isArray(hosts) || hosts.length === 0 || hosts.some((host) => !FEATURE_SET_HOSTS.includes(host)) || new Set(hosts).size !== hosts.length) {
43
+ throw new Error(`${at}.hosts must be a non-empty list of distinct hosts from ${FEATURE_SET_HOSTS.join(", ")}, not ${JSON.stringify(hosts)}`);
44
+ }
45
+ // A host scope narrows "every set on every host" (GC-A14), so it says why, as crate-level `platforms` does.
46
+ if (typeof entry.hostsReason !== "string" || !entry.hostsReason.trim()) throw new Error(`${at} needs a non-empty hostsReason (why the feature set builds on those hosts only)`);
47
+ return { features: entry.features, hosts };
48
+ });
49
+ }
50
+
51
+ // True when a list holds anything but plain argv arrays: the one case that is read through the validator (a list of arrays is used as it is).
52
+ const hasScoped = (list) => Array.isArray(list) && list.some((entry) => !Array.isArray(entry));
53
+ const needPlatform = (crate, key) => new Error(`ci/gate.config.json rust.${crate}.${key} has host-scoped sets: the host's platform (darwin, win32 or linux) is required to plan them`);
54
+
55
+ /**
56
+ * The sets `entry[key]` plans on `platform`, as argv arrays: every unscoped set and each scoped set that names the host. `undefined` when
57
+ * the entry has no such list (callers keep their own default). A list with no object entry is returned as it is.
58
+ */
59
+ export function hostFeatureSets(entry, platform, key = "featureSets", crate = "<crate>") {
60
+ const list = entry?.[key];
61
+ if (list === undefined || !hasScoped(list)) return list;
62
+ if (!FEATURE_SET_HOSTS.includes(platform)) throw needPlatform(crate, key);
63
+ return featureSetEntries(list, key, crate).filter((set) => set.hosts === null || set.hosts.includes(platform)).map((set) => set.features);
64
+ }
65
+
66
+ /** The sets of `hostFeatureSets` that are also linted for the other OSes' targets: the unscoped ones. A host-scoped set is a native-host set. */
67
+ export function crossFeatureSets(entry, platform, key = "featureSets", crate = "<crate>") {
68
+ const list = entry?.[key];
69
+ if (list === undefined || !hasScoped(list)) return list;
70
+ if (!FEATURE_SET_HOSTS.includes(platform)) throw needPlatform(crate, key);
71
+ return featureSetEntries(list, key, crate).filter((set) => set.hosts === null).map((set) => set.features);
72
+ }
73
+
74
+ /** Every set of `entry[key]` whatever its hosts, as argv arrays (feature coverage). `undefined` when the entry has no such list. */
75
+ export function allFeatureSets(entry, key = "featureSets", crate = "<crate>") {
76
+ const list = entry?.[key];
77
+ if (list === undefined || !hasScoped(list)) return list;
78
+ return featureSetEntries(list, key, crate).map((set) => set.features);
79
+ }
80
+
81
+ /** True when `entry` declares any host-scoped set in either list (validated: a malformed object throws). */
82
+ export function hasHostScopedSets(entry, crate = "<crate>") {
83
+ let scoped = false;
84
+ for (const key of ["featureSets", "checkFeatureSets"]) {
85
+ if (entry?.[key] === undefined) continue;
86
+ featureSetEntries(entry[key], key, crate);
87
+ if (hasScoped(entry[key])) scoped = true;
88
+ }
89
+ return scoped;
90
+ }
91
+
92
+ /**
93
+ * `unlintedFeatures`: `{ "<feature>": "<reason>" }`, the features the gate never lints (rightkit-tts-qwen-sys `regenerate-bindings` rewrites
94
+ * checked-in files and needs libclang). Returns `{ feature: reason }` (empty when the crate names none). Throws on a malformed value. Whether a
95
+ * name is a declared feature, and whether a set enables it, is feature-coverage.mjs `featureCoverageProblems`.
96
+ */
97
+ export function unlintedFeatures(entry, crate = "<crate>") {
98
+ const value = entry?.unlintedFeatures;
99
+ if (value === undefined) return {};
100
+ const at = `ci/gate.config.json rust.${crate}.unlintedFeatures`;
101
+ if (!isPlainObject(value) || Object.keys(value).length === 0) throw new Error(`${at} must be an object of { "<feature>": "<reason>" }`);
102
+ for (const [feature, reason] of Object.entries(value)) {
103
+ if (!feature.trim()) throw new Error(`${at} names an empty feature`);
104
+ if (typeof reason !== "string" || !reason.trim()) throw new Error(`${at}.${feature} needs a non-empty reason (why the gate never lints it)`);
105
+ }
106
+ return value;
107
+ }
108
+
109
+ /**
110
+ * The check sets a crate with no `checkFeatureSets` gets: one `--all-features` check, unless the crate names unlinted features, which
111
+ * `--all-features` would switch on (a feature named there is never added to any generated set).
112
+ */
113
+ export const defaultCheckFeatureSets = (entry, crate = "<crate>") => (Object.keys(unlintedFeatures(entry, crate)).length ? [] : [["--all-features"]]);