@smoothbricks/nx-plugin 0.4.22 → 0.4.23

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 (62) hide show
  1. package/README.md +77 -21
  2. package/dist/bin/smoo-nx-exec.js +35 -11
  3. package/dist/cargo-closure-input.d.ts +63 -0
  4. package/dist/cargo-closure-input.d.ts.map +1 -0
  5. package/dist/cargo-closure-input.js +197 -0
  6. package/dist/cargo-source-hash.d.ts +37 -0
  7. package/dist/cargo-source-hash.d.ts.map +1 -1
  8. package/dist/cargo-source-hash.js +108 -190
  9. package/dist/cross-check-policy.d.ts +14 -0
  10. package/dist/cross-check-policy.d.ts.map +1 -1
  11. package/dist/cross-check-policy.js +15 -1
  12. package/dist/ensure-built.d.ts +3 -2
  13. package/dist/ensure-built.d.ts.map +1 -1
  14. package/dist/ensure-built.js +33 -56
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +112 -76
  17. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  18. package/dist/managed-files/ci-workflow.js +12 -15
  19. package/dist/managed-files/files.d.ts.map +1 -1
  20. package/dist/managed-files/files.js +10 -0
  21. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  22. package/dist/managed-files/publish-workflow.js +12 -6
  23. package/dist/manifest-hash.d.ts.map +1 -1
  24. package/dist/manifest-hash.js +24 -30
  25. package/dist/package-target-policy.js +1 -1
  26. package/dist/platform-targets.d.ts +7 -0
  27. package/dist/platform-targets.d.ts.map +1 -1
  28. package/dist/platform-targets.js +7 -0
  29. package/dist/workspace-config-policy.d.ts +1 -1
  30. package/dist/workspace-config-policy.d.ts.map +1 -1
  31. package/dist/workspace-config-policy.js +1 -1
  32. package/managed/raw/envrc +38 -1
  33. package/managed/raw/tooling/direnv/developer-links.ts +201 -0
  34. package/managed/raw/tooling/direnv/devenv.smoo.nix +75 -51
  35. package/managed/raw/tooling/direnv/secret-references.ts +3 -1
  36. package/managed/raw/tooling/direnv/setup-environment.ts +562 -78
  37. package/managed/raw/tooling/direnv/shared-caches.sh +53 -0
  38. package/managed/raw/tooling/git-hooks/pre-push.sh +22 -1
  39. package/managed/templates/github/workflows/managed-files.yml +4 -3
  40. package/nextest.toml +5 -5
  41. package/package.json +2 -2
  42. package/src/__tests__/fixture-nx-env.ts +31 -0
  43. package/src/__tests__/in-process-nx-index.ts +9 -0
  44. package/src/bin/smoo-nx-exec.ts +40 -11
  45. package/src/cargo-closure-input.test.ts +184 -0
  46. package/src/cargo-closure-input.ts +247 -0
  47. package/src/cargo-source-hash.test.ts +8 -9
  48. package/src/cargo-source-hash.ts +146 -47
  49. package/src/cross-check-policy.ts +15 -3
  50. package/src/ensure-built.test.ts +65 -5
  51. package/src/ensure-built.ts +40 -85
  52. package/src/index.test.ts +94 -53
  53. package/src/index.ts +164 -84
  54. package/src/managed-files/ci-workflow.ts +12 -15
  55. package/src/managed-files/files.ts +10 -0
  56. package/src/managed-files/generator.test.ts +29 -0
  57. package/src/managed-files/publish-workflow.ts +17 -6
  58. package/src/manifest-hash.test.ts +21 -1
  59. package/src/manifest-hash.ts +26 -29
  60. package/src/package-target-policy.ts +1 -1
  61. package/src/platform-targets.ts +8 -0
  62. package/src/workspace-config-policy.ts +6 -1
package/src/index.ts CHANGED
@@ -15,6 +15,13 @@ import { AggregateCreateNodesError } from 'nx/src/project-graph/error-types.js';
15
15
  import { parse as parseToml } from 'smol-toml';
16
16
 
17
17
  import { BOUNDED_TEST_KILL_AFTER_MS, BOUNDED_TEST_TIMEOUT_MS } from './bounded-test-policy.js';
18
+ import {
19
+ CARGO_CLOSURE_INPUT,
20
+ type CargoClosureSource,
21
+ cargoClosureInputs,
22
+ indexedCargoManifests,
23
+ resolveCargoClosureSource,
24
+ } from './cargo-closure-input.js';
18
25
  import { CARGO_TOOLCHAIN_NAMED_INPUT, CARGO_TOOLCHAIN_PIN_INPUTS } from './cargo-toolchain-policy.js';
19
26
  import {
20
27
  type AttributedCargoWorkspacePackage,
@@ -49,7 +56,12 @@ import {
49
56
  } from './cross-check-policy.js';
50
57
  import { hashVersionlessCrateManifests } from './manifest-hash.js';
51
58
  import { isNonSourceDirectory } from './source-directories.js';
52
- import { isBuildOutputTargetName, isTestRunnerTargetName, PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
59
+ import {
60
+ isBuildOutputTargetName,
61
+ isTestRunnerTargetName,
62
+ PLATFORM_TARGET_GLOBS,
63
+ RELEASE_CONFIGURATION,
64
+ } from './workspace-config-policy.js';
53
65
 
54
66
  export { CARGO_TEST_COMPILE_TARGET };
55
67
 
@@ -507,17 +519,56 @@ export function napiToolchainTargetName(convention: NapiTargetConvention): strin
507
519
  return `${NAPI_TOOLCHAIN_TARGET_PREFIX}${convention.architecture}-${convention.targetFamily}`;
508
520
  }
509
521
 
522
+ /**
523
+ * Cargo's two profiles. A build target's default options compile `dev`, the
524
+ * profile every local build, test and gate shares, so one `target/` holds one
525
+ * set of units; RELEASE_CONFIGURATION compiles `release` for what ships.
526
+ */
527
+ type CargoProfile = 'dev' | 'release';
528
+
529
+ const CARGO_PROFILE_FLAG: Readonly<Record<CargoProfile, string>> = { dev: '', release: ' --release' };
530
+ /** The directory under `target/<triple>/` each profile writes. */
531
+ const CARGO_PROFILE_OUTPUT_DIR: Readonly<Record<CargoProfile, string>> = { dev: 'debug', release: 'release' };
532
+
533
+ /**
534
+ * Cargo's default target directory for a crate, relative to the command's cwd:
535
+ * `target/` beside the workspace root that owns the crate, or beside the
536
+ * crate's own manifest when no workspace claims it. Naming it rather than
537
+ * passing `--target-dir` keeps the wasm build in the directory every other
538
+ * build of the same workspace writes.
539
+ */
540
+ function cargoWasmTargetDirectory(
541
+ projectRoot: string,
542
+ config: ResolvedCargoWasmConfig,
543
+ repoRooted: boolean,
544
+ cargoWorkspace: CargoWorkspace | undefined,
545
+ ): string {
546
+ const cwd = repoRooted ? '.' : projectRoot;
547
+ const crateDir = posix.join(cwd, posix.dirname(config.manifestPath));
548
+ const owner =
549
+ cargoWorkspace !== undefined &&
550
+ cargoWorkspace.packages.some((plan) => posix.join(cargoWorkspace.projectRoot, plan.package.dir) === crateDir)
551
+ ? cargoWorkspace.projectRoot
552
+ : crateDir;
553
+ return posix.relative(cwd, posix.join(owner, 'target'));
554
+ }
555
+
510
556
  function createCargoWasmTarget(
511
557
  projectRoot: string,
512
558
  config: ResolvedCargoWasmConfig,
513
559
  repoRooted: boolean,
560
+ cargoTargetDirectory: string,
514
561
  ): TargetConfiguration {
515
- const cargoTargetDirectory = repoRooted
516
- ? 'target/cargo-wasm'
517
- : posix.join(posix.dirname(config.manifestPath), 'target/cargo-wasm');
518
- const wasmInput = `${cargoTargetDirectory}/wasm32-unknown-unknown/release/${config.libraryName}.wasm`;
519
562
  const outputDirectory = repoRooted ? posix.join(projectRoot, config.outputDirectory) : config.outputDirectory;
520
563
  const cargoSelection = repoRooted ? `-p ${config.cargoPackage}` : `--manifest-path ${config.manifestPath}`;
564
+ const commands = (profile: CargoProfile): string[] => [
565
+ cargoFrozen(`build${CARGO_PROFILE_FLAG[profile]} --target wasm32-unknown-unknown ${cargoSelection}`),
566
+ ...config.targets.map(
567
+ ({ bindgenTarget, outputName }) =>
568
+ `wasm-bindgen --target ${bindgenTarget} --out-dir ${outputDirectory}/${outputName} ` +
569
+ `${cargoTargetDirectory}/wasm32-unknown-unknown/${CARGO_PROFILE_OUTPUT_DIR[profile]}/${config.libraryName}.wasm`,
570
+ ),
571
+ ];
521
572
  return {
522
573
  executor: 'nx:run-commands',
523
574
  cache: true,
@@ -525,18 +576,11 @@ function createCargoWasmTarget(
525
576
  inputs: repoRooted ? REPO_ROOT_CARGO_OUTPUT_INPUTS : CARGO_OUTPUT_INPUTS,
526
577
  outputs: [`{projectRoot}/${config.outputDirectory}`],
527
578
  options: {
528
- commands: [
529
- cargoFrozen(
530
- `build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} ${cargoSelection}`,
531
- ),
532
- ...config.targets.map(
533
- ({ bindgenTarget, outputName }) =>
534
- `wasm-bindgen --target ${bindgenTarget} --out-dir ${outputDirectory}/${outputName} ${wasmInput}`,
535
- ),
536
- ],
579
+ commands: commands('dev'),
537
580
  cwd: repoRooted ? '.' : projectRoot,
538
581
  parallel: false,
539
582
  },
583
+ configurations: { [RELEASE_CONFIGURATION]: { commands: commands('release') } },
540
584
  };
541
585
  }
542
586
 
@@ -553,13 +597,19 @@ function createCargoWasmTarget(
553
597
  * timeout. Inference serializes writers that share the default target dir
554
598
  * (`napi-debug` after compile).
555
599
  *
556
- * Clippy writes ONE shared `--target-dir target/cargo-lint` rather than a
557
- * directory per crate. Per-crate dirs were never about overlap: clippy of a
558
- * crate is a check build of its whole closure, so 49 crates meant 49 closure
559
- * rebuilds and 11 GiB of target directories on one repository, and no
560
- * per-crate cache hit ever repaid that. Sharing the directory costs nothing:
561
- * cargo's own lock serializes the invocations that use it and each dependency
562
- * artifact is then compiled once for all of them.
600
+ * Clippy runs ONCE over the whole workspace, in that same `target/`, rather
601
+ * than once per crate. Clippy of a crate is a check build of its whole
602
+ * closure, so 49 crates meant 49 closure rebuilds and 11 GiB of target
603
+ * directories on one repository, and no per-crate cache hit ever repaid that.
604
+ * Sharing the build's directory costs nothing: cargo's own lock serializes
605
+ * the invocations that use it, and the host units a dev build compiled are
606
+ * reused instead of compiled again.
607
+ *
608
+ * Tests compile the dev profile only, so no test target carries a
609
+ * RELEASE_CONFIGURATION: Nx forwards a run's configuration down every
610
+ * `dependsOn` edge to each target that has it, and a release `build` must
611
+ * warm the dev test binaries the test run will use, not release ones nobody
612
+ * runs.
563
613
  */
564
614
  function createCargoTestCompileTarget(projectRoot: string): TargetConfiguration {
565
615
  return {
@@ -571,9 +621,6 @@ function createCargoTestCompileTarget(projectRoot: string): TargetConfiguration
571
621
  command: cargoFrozen('test --workspace --no-run'),
572
622
  cwd: projectRoot,
573
623
  },
574
- configurations: {
575
- production: { command: cargoFrozen('test --workspace --release --no-run') },
576
- },
577
624
  };
578
625
  }
579
626
 
@@ -594,25 +641,21 @@ function createCargoTestCompileTarget(projectRoot: string): TargetConfiguration
594
641
  * clippy selection exactly, so both gates unify features the same way.
595
642
  */
596
643
  function createCargoTestArchiveTarget(projectRoot: string, toolConfig: string): TargetConfiguration {
597
- const archiveCommand = (profile: string): string =>
598
- cargoFrozen(
599
- `nextest archive --workspace${profile} --archive-file ${CARGO_TEST_ARCHIVE_FILE} --user-config-file none ${toolConfig}`,
600
- );
601
644
  return {
602
645
  executor: 'nx:run-commands',
603
646
  cache: true,
604
647
  inputs: CARGO_INPUTS,
605
648
  outputs: [`{projectRoot}/${CARGO_TEST_ARCHIVE_FILE}`],
606
649
  options: {
607
- commands: [`mkdir -p ${posix.dirname(CARGO_TEST_ARCHIVE_FILE)}`, archiveCommand('')],
650
+ commands: [
651
+ `mkdir -p ${posix.dirname(CARGO_TEST_ARCHIVE_FILE)}`,
652
+ cargoFrozen(
653
+ `nextest archive --workspace --archive-file ${CARGO_TEST_ARCHIVE_FILE} --user-config-file none ${toolConfig}`,
654
+ ),
655
+ ],
608
656
  cwd: projectRoot,
609
657
  parallel: false,
610
658
  },
611
- configurations: {
612
- production: {
613
- commands: [`mkdir -p ${posix.dirname(CARGO_TEST_ARCHIVE_FILE)}`, archiveCommand(' --release')],
614
- },
615
- },
616
659
  };
617
660
  }
618
661
 
@@ -654,9 +697,6 @@ function createCargoCrossTestTargets(
654
697
  ): Record<string, TargetConfiguration> {
655
698
  const { target: triple, cargo } = crossTarget;
656
699
  const archiveFile = cargoCrossTestArchiveFile(triple);
657
- const archiveCommand = (profile: string): string =>
658
- `cargo-nextest nextest archive --workspace${profile} --target ${triple} --frozen ` +
659
- `--archive-file ${archiveFile} --user-config-file none ${toolConfig}`;
660
700
  return {
661
701
  [cargoCrossTestArchiveTargetName(triple)]: {
662
702
  executor: 'nx:run-commands',
@@ -681,7 +721,11 @@ function createCargoCrossTestTargets(
681
721
  outputs: [`{projectRoot}/${archiveFile}`],
682
722
  dependsOn: [CARGO_FETCH_TARGET],
683
723
  options: {
684
- commands: [`mkdir -p ${posix.dirname(archiveFile)}`, archiveCommand('')],
724
+ commands: [
725
+ `mkdir -p ${posix.dirname(archiveFile)}`,
726
+ `cargo-nextest nextest archive --workspace --target ${triple} --frozen ` +
727
+ `--archive-file ${archiveFile} --user-config-file none ${toolConfig}`,
728
+ ],
685
729
  cwd: projectRoot,
686
730
  parallel: false,
687
731
  // `CARGO` is cargo's own driver variable and the only seam nextest
@@ -692,11 +736,6 @@ function createCargoCrossTestTargets(
692
736
  // it applies to this archive and to nothing else cargo runs.
693
737
  ...(cargo === undefined ? {} : { env: { CARGO: cargo } }),
694
738
  },
695
- configurations: {
696
- production: {
697
- commands: [`mkdir -p ${posix.dirname(archiveFile)}`, archiveCommand(' --release')],
698
- },
699
- },
700
739
  },
701
740
  [cargoCrossTestTargetName(triple)]: {
702
741
  executor: '@smoothbricks/nx-plugin:bounded-exec',
@@ -712,9 +751,6 @@ function createCargoCrossTestTargets(
712
751
  timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
713
752
  killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
714
753
  },
715
- // The archive already holds the profile it was built with, and nextest
716
- // rejects `--release` beside `--archive-file`.
717
- configurations: { production: {} },
718
754
  },
719
755
  };
720
756
  }
@@ -731,9 +767,6 @@ function createCargoTestTarget(projectRoot: string): TargetConfiguration {
731
767
  timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
732
768
  killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
733
769
  },
734
- configurations: {
735
- production: { command: cargoFrozen('test --workspace --release') },
736
- },
737
770
  };
738
771
  }
739
772
 
@@ -855,6 +888,9 @@ function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandl
855
888
  }
856
889
  }),
857
890
  );
891
+ // A project that failed before reaching its closure never awaited Cargo;
892
+ // no process this call started may outlive it.
893
+ await Promise.all(cargoWorkspaces.map((workspace) => workspace.closureSource));
858
894
 
859
895
  if (errors.length > 0) {
860
896
  throw new AggregateCreateNodesError(errors, results);
@@ -1114,7 +1150,12 @@ async function createProjectTargets(
1114
1150
  }
1115
1151
 
1116
1152
  if (inferCargoWasm && cargoWasmConfig) {
1117
- targets['cargo-wasm'] = createCargoWasmTarget(projectRoot, cargoWasmConfig, isRepoRootedCargoProject);
1153
+ targets['cargo-wasm'] = createCargoWasmTarget(
1154
+ projectRoot,
1155
+ cargoWasmConfig,
1156
+ isRepoRootedCargoProject,
1157
+ cargoWasmTargetDirectory(projectRoot, cargoWasmConfig, isRepoRootedCargoProject, cargoWorkspace),
1158
+ );
1118
1159
  }
1119
1160
 
1120
1161
  if (napiConfig) {
@@ -1245,12 +1286,13 @@ async function createProjectTargets(
1245
1286
  aggregateDependencies.length > 0
1246
1287
  ? { executor: 'nx:noop', cache: true, outputs: [], dependsOn: aggregateDependencies }
1247
1288
  : createCargoTestTarget(cargoWorkspaceRoot);
1248
- // One clippy over the whole workspace, in one target dir. Clippy of a crate
1249
- // is a check build of its closure; a target dir per crate compiled every
1250
- // shared dependency once per crate (49 closures, 11 GiB on one repository)
1251
- // and no per-crate cache hit ever repaid that. The workspace inputs are
1252
- // exactly the union of every crate's, so the verdict caches on the same
1253
- // key set the compile does. Non-root packages depend on this target.
1289
+ // One clippy over the whole workspace, in the build's target dir. Clippy
1290
+ // of a crate is a check build of its closure; a target dir per crate
1291
+ // compiled every shared dependency once per crate (49 closures, 11 GiB on
1292
+ // one repository) and no per-crate cache hit ever repaid that. The
1293
+ // workspace inputs are exactly the union of every crate's, so the verdict
1294
+ // caches on the same key set the compile does. Non-root packages depend on
1295
+ // this target.
1254
1296
  targets['cargo-lint'] = {
1255
1297
  executor: 'nx:run-commands',
1256
1298
  cache: true,
@@ -1374,7 +1416,6 @@ async function createProjectTargets(
1374
1416
  const target = targets[name];
1375
1417
  if (target?.executor === 'nx:noop') {
1376
1418
  target.outputs = [];
1377
- target.configurations = { production: {} };
1378
1419
  }
1379
1420
  }
1380
1421
  }
@@ -1551,7 +1592,7 @@ async function createProjectTargets(
1551
1592
  // The platform binaries therefore stay Nx siblings of cargo-test-compile and
1552
1593
  // serialize on cargo's flock instead of on a graph edge. That is the same
1553
1594
  // arrangement `cli-<arch>-<os>` and `napi-<arch>-<os>` already have with each
1554
- // other — both `napi build --release` on one target dir — so this adds a third
1595
+ // other — both `napi build` on one target dir — so this adds a third
1555
1596
  // participant to an existing wait, not a new hazard. The flock makes them wait;
1556
1597
  // it does not corrupt anything, and these are unbounded `nx:run-commands`
1557
1598
  // targets, so the wait is not charged against a test budget.
@@ -1664,11 +1705,11 @@ async function createProjectTargets(
1664
1705
  }
1665
1706
  // Every cargo build directory this project's own commands write. `clean`
1666
1707
  // cannot learn them from `outputs`: a clippy or nextest target dir is a
1667
- // multi-GB build tree that must never enter the Nx cache (`target/cargo-lint`
1668
- // alone was 11 GiB when each of 49 crates had its own), so the targets
1708
+ // multi-GB build tree that must never enter the Nx cache, so the targets
1669
1709
  // deliberately declare `outputs: []`. Reading `--target-dir` back off the
1670
1710
  // commands means the list cannot drift from what actually gets written, and a
1671
1711
  // directory is named relative to the command's own cwd, not the project root.
1712
+ // The workspace's default `target/` is not listed: every dev build shares it.
1672
1713
  const cargoBuildDirs = [
1673
1714
  ...new Set(
1674
1715
  Object.entries(targets).flatMap(([name, target]) => {
@@ -1756,6 +1797,23 @@ async function createProjectTargets(
1756
1797
  ? { [CARGO_TOOLCHAIN_NAMED_INPUT]: [...CARGO_TOOLCHAIN_PIN_INPUTS] }
1757
1798
  : {}),
1758
1799
  };
1800
+ // A custom Cargo target names this instead of a hand-kept crate list or a
1801
+ // per-project runtime command: Cargo decides the closure once per graph
1802
+ // computation and Nx hashes its files from its own index. Defined for a
1803
+ // project with a workspace crate under its root — the same projects the
1804
+ // `--closure <projectRoot>` command could describe.
1805
+ const closureSources = cargoWorkspaces.filter((workspace) =>
1806
+ workspace.packages.some(({ package: pkg }) => {
1807
+ const crate = posix.join(workspace.projectRoot, pkg.dir);
1808
+ return projectRoot === '.' || crate === projectRoot || crate.startsWith(`${projectRoot}/`);
1809
+ }),
1810
+ );
1811
+ if (closureSources.length > 0) {
1812
+ namedInputs[CARGO_CLOSURE_INPUT] = await cargoClosureInputs(
1813
+ projectRoot,
1814
+ await Promise.all(closureSources.map((workspace) => workspace.closureSource)),
1815
+ );
1816
+ }
1759
1817
  return {
1760
1818
  projects: {
1761
1819
  [projectRoot]: {
@@ -2002,13 +2060,14 @@ function createNapiTargets(
2002
2060
  const targets: Record<string, TargetConfiguration> = {};
2003
2061
  const hostCompilerEnv = napiCompilerEnv(hostPlatform, hostPlatform);
2004
2062
 
2005
- // The addon the test suite loads. A dev-profile build shares target/debug
2006
- // with cargo-test's dependency graph, so after the tests compile this is
2007
- // nearly free — where the release platform build it replaces cost minutes
2008
- // and sat alone on the test critical path. The output lives OUTSIDE dist/
2009
- // because packages publish `files: ["dist"]` wholesale: a debug addon under
2010
- // dist/ would ship. native.ts resolves this directory only when the
2011
- // napi-test target sets NAPI_DEBUG_ADDON=1, so production loads never see it.
2063
+ // The addon the test suite loads. A plain dev build shares target/debug with
2064
+ // cargo-test's dependency graph, so after the tests compile this is nearly
2065
+ // free, where a `--target <triple>` platform build compiles the graph again
2066
+ // under target/<triple>/. The output lives OUTSIDE dist/ because packages
2067
+ // publish `files: ["dist"]` wholesale: an addon the test run wrote under
2068
+ // dist/ would ship in place of the release build. native.ts resolves this
2069
+ // directory only when the napi-test target sets NAPI_DEBUG_ADDON=1, so
2070
+ // production loads never see it.
2012
2071
  targets['napi-debug'] = {
2013
2072
  executor: 'nx:run-commands',
2014
2073
  cache: true,
@@ -2024,9 +2083,13 @@ function createNapiTargets(
2024
2083
 
2025
2084
  if (nativeHostTargetName === null) {
2026
2085
  // The platform target for this host triple is the same compilation, so a
2027
- // second cargo-napi invocation only buys a duplicate dependency graph in
2028
- // target/release; native.ts already resolves the identical platform-suffixed
2029
- // filename from dist/native/<platform-dir> after dist/native/host.
2086
+ // second cargo-napi invocation only buys a duplicate dependency graph
2087
+ // (a plain build and a `--target` build write different target/
2088
+ // subdirectories); native.ts already resolves the identical
2089
+ // platform-suffixed filename from dist/native/<platform-dir> after
2090
+ // dist/native/host.
2091
+ const hostBuild = (profile: CargoProfile): string =>
2092
+ `${napiCommand} build${CARGO_PROFILE_FLAG[profile]} --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir ${outputPath('dist/native/host')}`;
2030
2093
  targets['cargo-napi'] = {
2031
2094
  executor: 'nx:run-commands',
2032
2095
  cache: true,
@@ -2035,9 +2098,10 @@ function createNapiTargets(
2035
2098
  outputs: ['{projectRoot}/dist/native/host'],
2036
2099
  options: {
2037
2100
  cwd: cargoCwd,
2038
- command: `${napiCommand} build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir ${outputPath('dist/native/host')}`,
2101
+ command: hostBuild('dev'),
2039
2102
  ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
2040
2103
  },
2104
+ configurations: { [RELEASE_CONFIGURATION]: { command: hostBuild('release') } },
2041
2105
  };
2042
2106
  }
2043
2107
 
@@ -2071,6 +2135,8 @@ function createNapiTargets(
2071
2135
  const useNapiCross = usesNapiCross(convention, hostPlatform);
2072
2136
  const crossFlag = useNapiCross ? ' --use-napi-cross' : '';
2073
2137
  const compilerEnv = napiCompilerEnv(convention, hostPlatform);
2138
+ const platformBuild = (profile: CargoProfile): string =>
2139
+ `${napiCommand} build${CARGO_PROFILE_FLAG[profile]} --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputPath(outputDirectory)}`;
2074
2140
  targets[targetName] = {
2075
2141
  executor: 'nx:run-commands',
2076
2142
  cache: true,
@@ -2079,12 +2145,13 @@ function createNapiTargets(
2079
2145
  outputs: [`{projectRoot}/${outputDirectory}`],
2080
2146
  options: {
2081
2147
  cwd: cargoCwd,
2082
- command: `${napiCommand} build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputPath(outputDirectory)}`,
2148
+ command: platformBuild('dev'),
2083
2149
  // Genuine Linux cross-compiles use Clang plus napi-rs's downloaded
2084
2150
  // GNU sysroot. A native Linux target uses Nix's cc wrapper so C build
2085
2151
  // scripts resolve the host libc headers instead.
2086
2152
  ...(compilerEnv ? { env: compilerEnv } : {}),
2087
2153
  },
2154
+ configurations: { [RELEASE_CONFIGURATION]: { command: platformBuild('release') } },
2088
2155
  };
2089
2156
  }
2090
2157
  return targets;
@@ -2095,10 +2162,11 @@ function createNapiTestTarget(projectRoot: string, hasDedicatedBunfig: boolean):
2095
2162
  return {
2096
2163
  executor: '@smoothbricks/nx-plugin:bounded-exec',
2097
2164
  cache: true,
2098
- // Deliberately NOT `build`: the aggregate drags the host-platform release
2099
- // binaries onto the test critical path, and the tests assert behavior, not
2100
- // optimization level. tsc-js supplies dist/ts for the suite's own imports;
2101
- // napi-debug supplies the addon.
2165
+ // Deliberately NOT `build`: the aggregate drags the host-platform binaries
2166
+ // onto the test critical path, and a `--target <triple>` platform build
2167
+ // compiles the whole graph again. tsc-js supplies dist/ts for the suite's
2168
+ // own imports; napi-debug supplies the addon from the graph cargo-test
2169
+ // already built.
2102
2170
  dependsOn: ['cargo-test', 'napi-debug', 'tsc-js', '^build'],
2103
2171
  options: {
2104
2172
  // cwd is src/, not the package root: `bun test <arg>` treats the arg as a
@@ -2224,6 +2292,12 @@ interface CargoWorkspace {
2224
2292
  projectRoot: string;
2225
2293
  /** One derivation memo for the whole graph computation (see cargoPackageTestInputs). */
2226
2294
  inputsCache: CargoInputsCache;
2295
+ /**
2296
+ * Cargo's own resolve, started once per graph computation and awaited only
2297
+ * where a project's `cargoClosure` is built, so the `cargo metadata` process
2298
+ * overlaps the rest of inference.
2299
+ */
2300
+ closureSource: Promise<CargoClosureSource>;
2227
2301
  }
2228
2302
 
2229
2303
  type CargoTargetDependency = NonNullable<TargetConfiguration['dependsOn']>[number];
@@ -2253,7 +2327,7 @@ async function resolveCargoWorkspaces(
2253
2327
  // createProjectTargets records the path-specific parse failure below.
2254
2328
  }
2255
2329
  }
2256
- const workspaces: CargoWorkspace[] = [];
2330
+ const found: Omit<CargoWorkspace, 'closureSource'>[] = [];
2257
2331
  for (const rootProject of projects) {
2258
2332
  const absoluteRoot = join(workspaceRoot, rootProject.root);
2259
2333
  const manifest = join(absoluteRoot, 'Cargo.toml');
@@ -2292,14 +2366,25 @@ async function resolveCargoWorkspaces(
2292
2366
  }
2293
2367
  packages.push({ package: pkg, pieces });
2294
2368
  }
2295
- workspaces.push({
2369
+ found.push({
2296
2370
  packages,
2297
2371
  rootProjectName: rootProject.name,
2298
2372
  projectRoot: rootProject.root,
2299
2373
  inputsCache: createCargoInputsCache(),
2300
2374
  });
2301
2375
  }
2302
- return workspaces;
2376
+ if (found.length === 0) return [];
2377
+ // Started only once every workspace listed cleanly, so a listing that throws
2378
+ // leaves no Cargo process behind.
2379
+ const indexedManifests = indexedCargoManifests(workspaceRoot);
2380
+ return found.map((workspace) => ({
2381
+ ...workspace,
2382
+ closureSource: resolveCargoClosureSource(
2383
+ posix.join(workspace.projectRoot, 'Cargo.toml'),
2384
+ workspaceRoot,
2385
+ indexedManifests,
2386
+ ),
2387
+ }));
2303
2388
  }
2304
2389
 
2305
2390
  /**
@@ -2409,11 +2494,6 @@ async function addCargoTestTargets(
2409
2494
  timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
2410
2495
  killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
2411
2496
  },
2412
- // The archive already holds the profile it was built with, and nextest
2413
- // rejects `--release` beside `--archive-file`. Nx propagates the
2414
- // configuration to this target's dependencies, so `:production` builds
2415
- // the release archive and this command runs exactly what it finds.
2416
- configurations: { production: {} },
2417
2497
  };
2418
2498
  }
2419
2499
  }
@@ -202,7 +202,7 @@ export function defineCiWorkflow(options: CiWorkflowDefinitionOptions): CiWorkfl
202
202
  steps.push({ kind: CiWorkflowStepKind.BrowserTests, name: '🌐 Browser Tests' });
203
203
  }
204
204
  steps.push(
205
- { kind: CiWorkflowStepKind.ManagedFilesCheck, name: '🩺 Check managed-file drift' },
205
+ { kind: CiWorkflowStepKind.ManagedFilesCheck, name: '🩺 Check monorepo policies and managed-file drift' },
206
206
  { kind: CiWorkflowStepKind.ManagedFilesDispatch, name: '🔁 Dispatch managed-file drift healing' },
207
207
  { kind: CiWorkflowStepKind.SaveNxCache, name: '💾 Save Nx cache' },
208
208
  { kind: CiWorkflowStepKind.UploadTraceDbs, name: '📎 Upload trace DBs' },
@@ -477,24 +477,21 @@ function yamlLinesForStep(step: CiWorkflowStep, options: CiWorkflowDefinitionOpt
477
477
  ` run: smoo github-ci nx-run-many --targets "${darwinCrossTestTargetNames(options).join(',')}"`,
478
478
  ];
479
479
  case CiWorkflowStepKind.ManagedFilesCheck:
480
- // The authoritative drift check is nearly free here (devenv is already
481
- // up). --warn never fails the job and publishes the step output
482
- // `drifted=<count>` for the dispatch step below.
483
- return [
484
- ` - name: ${step.name}`,
485
- ' id: managed-drift',
486
- ' if:',
487
- " ${{ github.event_name == 'push' && github.ref == format('refs/heads/{0}',",
488
- ' github.event.repository.default_branch) }}',
489
- ' run: smoo monorepo check --warn',
490
- ];
480
+ // Runs on every event, pull requests included: the package policies fail the job, since
481
+ // nothing heals them, while --warn keeps managed-file drift non-blocking and publishes the
482
+ // step output `drifted=<count>` for the dispatch step below. The check is nearly free here
483
+ // (devenv is already up).
484
+ return [` - name: ${step.name}`, ' id: managed-drift', ' run: smoo monorepo check --warn'];
491
485
  case CiWorkflowStepKind.ManagedFilesDispatch:
492
486
  // Dispatches the managed-files workflow, which maintains the persistent
493
- // review PR. workflow_dispatch is exempt from GitHub's GITHUB_TOKEN
494
- // recursion guard, so the default token suffices.
487
+ // review PR, from the default branch only. workflow_dispatch is exempt from
488
+ // GitHub's GITHUB_TOKEN recursion guard, so the default token suffices.
495
489
  return [
496
490
  ` - name: ${step.name}`,
497
- " if: steps.managed-drift.outputs.drifted != '' && steps.managed-drift.outputs.drifted != '0'",
491
+ ' if: >-',
492
+ " ${{ github.event_name == 'push' && github.ref == format('refs/heads/{0}',",
493
+ " github.event.repository.default_branch) && steps.managed-drift.outputs.drifted != '' &&",
494
+ " steps.managed-drift.outputs.drifted != '0' }}",
498
495
  ' run: smoo github-ci dispatch-workflow --workflow managed-files.yml --ref "$GITHUB_REF_NAME"',
499
496
  ];
500
497
  case CiWorkflowStepKind.Deploy:
@@ -109,6 +109,11 @@ const managedFiles: ManagedFileDescriptor[] = [
109
109
  target: 'tooling/direnv/setup-environment.ts',
110
110
  executable: true,
111
111
  },
112
+ {
113
+ kind: 'raw',
114
+ source: 'tooling/direnv/developer-links.ts',
115
+ target: 'tooling/direnv/developer-links.ts',
116
+ },
112
117
  {
113
118
  kind: 'raw',
114
119
  source: 'tooling/direnv/secret-references.ts',
@@ -125,6 +130,11 @@ const managedFiles: ManagedFileDescriptor[] = [
125
130
  source: 'tooling/direnv/devenv.smoo.nix',
126
131
  target: 'tooling/direnv/devenv.smoo.nix',
127
132
  },
133
+ {
134
+ kind: 'raw',
135
+ source: 'tooling/direnv/shared-caches.sh',
136
+ target: 'tooling/direnv/shared-caches.sh',
137
+ },
128
138
  {
129
139
  kind: 'raw',
130
140
  source: 'tooling/git-hooks/pre-commit.sh',
@@ -42,6 +42,19 @@ async function generate(tree: Tree, graph: WorkspaceProjects = projects): Promis
42
42
  assertNoManagedConflicts(await generateManagedFiles(tree, graph, new Map()));
43
43
  }
44
44
 
45
+ /** Every step of every job in a workflow, as its fields. */
46
+ function workflowSteps(yaml: string): Array<Map<string, unknown>> {
47
+ const workflow: unknown = Bun.YAML.parse(yaml);
48
+ if (typeof workflow !== 'object' || workflow === null || !('jobs' in workflow)) return [];
49
+ const jobs = workflow.jobs;
50
+ if (typeof jobs !== 'object' || jobs === null) return [];
51
+ return Object.values(jobs).flatMap((job: unknown) =>
52
+ typeof job === 'object' && job !== null && 'steps' in job && Array.isArray(job.steps)
53
+ ? job.steps.map((step: unknown) => new Map(typeof step === 'object' && step !== null ? Object.entries(step) : []))
54
+ : [],
55
+ );
56
+ }
57
+
45
58
  describe('managed-files generator', () => {
46
59
  it('generates workflows and packaged bootstrap assets in a virtual workspace', async () => {
47
60
  const tree = workspace();
@@ -65,6 +78,22 @@ describe('managed-files generator', () => {
65
78
  expect(ci).not.toContain('nixos-latest');
66
79
  });
67
80
 
81
+ // The package policies fail `smoo monorepo check --warn`, so the step must run where a change is
82
+ // judged — pull requests included — while drift healing stays a default-branch concern.
83
+ it('runs the policy check on every CI event and heals drift only from the default branch', async () => {
84
+ const tree = workspace();
85
+ await generate(tree);
86
+ const steps = workflowSteps(tree.read('.github/workflows/ci.yml', 'utf8') ?? '');
87
+ const check = steps.find((step) => step.get('id') === 'managed-drift');
88
+ expect(check?.get('run')).toBe('smoo monorepo check --warn');
89
+ expect(check?.has('if')).toBe(false);
90
+ const dispatch = steps.find((step) => String(step.get('run')).includes('--workflow managed-files.yml'));
91
+ const condition = String(dispatch?.get('if'));
92
+ expect(condition).toContain("github.event_name == 'push'");
93
+ expect(condition).toContain('github.event.repository.default_branch');
94
+ expect(condition).toContain('steps.managed-drift.outputs.drifted');
95
+ });
96
+
68
97
  it('discovers publication from workspace packages and does not publish another repository', async () => {
69
98
  const tree = workspace();
70
99
  updateJson<PackageJson>(tree, 'packages/library/package.json', (pkg) => ({
@@ -1,6 +1,10 @@
1
1
  /* biome-ignore-all lint/suspicious/noTemplateCurlyInString: GitHub Actions expressions are emitted literally. */
2
2
 
3
- import { LINUX_PLATFORM_TARGET_GLOBS, MACOS_PLATFORM_TARGET_GLOBS } from '../platform-targets.js';
3
+ import {
4
+ LINUX_PLATFORM_TARGET_GLOBS,
5
+ MACOS_PLATFORM_TARGET_GLOBS,
6
+ RELEASE_CONFIGURATION,
7
+ } from '../platform-targets.js';
4
8
  import type {
5
9
  PackageCargoCredentialsConfig,
6
10
  PackagePrivateNpmConfig,
@@ -21,6 +25,13 @@ import {
21
25
  } from './ci-workflow.js';
22
26
  import { GITHUB_HOSTED_LINUX_RUNNER, renderRunsOnLine, type WorkflowRunsOn } from './github-runs-on.js';
23
27
 
28
+ /**
29
+ * Carried by every step that builds what ships: the build aggregate and each
30
+ * platform leg. Lint and unit tests keep the default configuration, cargo's
31
+ * dev profile, like every local and CI run.
32
+ */
33
+ const RELEASE_BUILD_ARGUMENT = `--configuration ${RELEASE_CONFIGURATION}`;
34
+
24
35
  export type PublishWorkflowBump = 'auto' | 'patch' | 'minor' | 'major' | 'prerelease';
25
36
  export type PublishWorkflowCondition =
26
37
  | 'plan-mode-not-none'
@@ -610,7 +621,7 @@ function yamlLinesForStep(step: PublishWorkflowStep, options: PublishWorkflowDef
610
621
  case PublishWorkflowStepKind.Build:
611
622
  return conditionalRunStep(
612
623
  step,
613
- `smoo github-ci nx-run-many --targets build --projects "${githubExpression('steps.version.outputs.projects')}"`,
624
+ `smoo github-ci nx-run-many --targets build --projects "${githubExpression('steps.version.outputs.projects')}" ${RELEASE_BUILD_ARGUMENT}`,
614
625
  );
615
626
  case PublishWorkflowStepKind.Lint:
616
627
  return conditionalRunStep(
@@ -800,7 +811,7 @@ function renderSingleJobPublishWorkflowSteps(
800
811
  " if: steps.version.outputs.mode != 'none'",
801
812
  ` run: smoo github-ci nx-run-many --targets "${LINUX_PLATFORM_TARGET_GLOBS.join(',')}" --projects "${githubExpression(
802
813
  'steps.version.outputs.projects',
803
- )}"`,
814
+ )}" ${RELEASE_BUILD_ARGUMENT}`,
804
815
  '',
805
816
  );
806
817
  if (crossOnThisRunner) {
@@ -809,7 +820,7 @@ function renderSingleJobPublishWorkflowSteps(
809
820
  " if: steps.version.outputs.mode != 'none'",
810
821
  ` run: smoo github-ci nx-run-many --targets "${macosPlatformFamilies(options).join(',')}" --projects "${githubExpression(
811
822
  'steps.version.outputs.projects',
812
- )}"`,
823
+ )}" ${RELEASE_BUILD_ARGUMENT}`,
813
824
  '',
814
825
  );
815
826
  }
@@ -947,7 +958,7 @@ function renderLinuxReleaseCandidateSteps(
947
958
  ' run:',
948
959
  ` smoo github-ci nx-run-many --targets build --projects "${githubExpression(
949
960
  'steps.version.outputs.projects',
950
- )}" --collect-outputs "${githubExpression('runner.temp')}/release-build-outputs"`,
961
+ )}" ${RELEASE_BUILD_ARGUMENT} --collect-outputs "${githubExpression('runner.temp')}/release-build-outputs"`,
951
962
  );
952
963
  } else {
953
964
  lines.push(...yamlLinesForStep(step, options));
@@ -974,7 +985,7 @@ function renderLinuxReleaseCandidateSteps(
974
985
  ',',
975
986
  )}" --projects "${githubExpression(
976
987
  'steps.version.outputs.projects',
977
- )}" --collect-outputs "${githubExpression('runner.temp')}/linux-platform-outputs"`,
988
+ )}" ${RELEASE_BUILD_ARGUMENT} --collect-outputs "${githubExpression('runner.temp')}/linux-platform-outputs"`,
978
989
  );
979
990
  stepNumber += 1;
980
991
  }