gitnexus 1.6.10-rc.151 → 1.6.10-rc.153

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.
@@ -109,6 +109,24 @@ export declare function normalizeAnalyzerRootPath(p: string, platform: NodeJS.Pl
109
109
  declare function isInside(parent: string, candidate: string, pathApi?: typeof path): boolean;
110
110
  /** Test seam for {@link isInside} (see `_hashAnalyzerIdentityFramesForTests`). */
111
111
  export declare const _isInsideForTests: typeof isInside;
112
+ /**
113
+ * Whether a REALPATH'd package root lives inside some installed dependency
114
+ * tree. Used as the resolved-location half of "is this dependency a checkout
115
+ * this repository owns?" (see {@link undeclaredLocalDevDependencyNames}).
116
+ *
117
+ * The input must already be realpath'd: `resolveDependencyPackageRoot` returns
118
+ * `realpathSync.native`, so a package reached through a link out of
119
+ * `node_modules` reports its checkout location and a package that merely lives
120
+ * in `node_modules` reports a path that still carries the segment.
121
+ *
122
+ * `pathApi` is injectable so the Windows separator handling is unit-testable
123
+ * from a POSIX runner, exactly as {@link isInside} does. The separator sets
124
+ * differ deliberately: `\` is a legal filename character on POSIX, so only
125
+ * win32 may treat it as a boundary.
126
+ */
127
+ declare function hasNodeModulesSegment(candidate: string, pathApi?: typeof path): boolean;
128
+ /** Test seam for {@link hasNodeModulesSegment} (see {@link _isInsideForTests}). */
129
+ export declare const _hasNodeModulesSegmentForTests: typeof hasNodeModulesSegment;
112
130
  export type AnalyzerRunnerSemanticIdentity = Omit<AnalyzerRunnerIdentity, 'invokedArtifact'>;
113
131
  /**
114
132
  * Normalize a raw diagnostic receipt for freshness comparison. The entrypoint
@@ -154,6 +154,24 @@ function snapshotReadableFile(candidate) {
154
154
  ...(link.isSymbolicLink() ? { symlinkTarget: readlinkSync(candidate) } : {}),
155
155
  };
156
156
  }
157
+ /**
158
+ * Snapshot a symbolic link without resolving it. Unlike
159
+ * {@link snapshotReadableFile} this never stats the target, so it is total over
160
+ * linked directories, dangling links, and links to device nodes — the inputs
161
+ * that make the readable-file snapshot throw.
162
+ */
163
+ function snapshotSymlinkArtifact(candidate) {
164
+ const link = lstatSync(candidate, { bigint: true });
165
+ if (!link.isSymbolicLink()) {
166
+ throw new Error(`Analyzer identity input is not a symbolic link: ${candidate}`);
167
+ }
168
+ return { link: statState(link), symlinkTarget: readlinkSync(candidate) };
169
+ }
170
+ function snapshotRuntimeArtifact(artifact) {
171
+ return artifact.kind === 'unfollowed-symlink'
172
+ ? snapshotSymlinkArtifact(artifact.absolutePath)
173
+ : snapshotReadableFile(artifact.absolutePath);
174
+ }
157
175
  function snapshotDirectory(candidate) {
158
176
  const stat = lstatSync(candidate, { bigint: true });
159
177
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
@@ -597,6 +615,96 @@ function runtimePackageLocator(packageRoot, runtimeRoot) {
597
615
  const relative = path.relative(packageRoot, runtimeRoot).split(path.sep).join('/');
598
616
  return `relative:${relative}`;
599
617
  }
618
+ /** Protocols that name a checkout-local package instead of a registry tarball. */
619
+ const LOCAL_LINK_PROTOCOL_PATTERN = /^(?:file|link|workspace|portal):/;
620
+ /** npm's bare local-path shorthands: `./x`, `../x`, `/x`, `~/x`, `C:\x`. */
621
+ const LOCAL_LINK_PATH_PATTERN = /^(?:\.\.?[/\\]|~[/\\]|[/\\]|[A-Za-z]:)/;
622
+ function isLocallyLinkedSpecifier(specifier) {
623
+ if (typeof specifier !== 'string')
624
+ return false;
625
+ const value = specifier.trim();
626
+ return LOCAL_LINK_PROTOCOL_PATTERN.test(value) || LOCAL_LINK_PATH_PATTERN.test(value);
627
+ }
628
+ /**
629
+ * Whether a REALPATH'd package root lives inside some installed dependency
630
+ * tree. Used as the resolved-location half of "is this dependency a checkout
631
+ * this repository owns?" (see {@link undeclaredLocalDevDependencyNames}).
632
+ *
633
+ * The input must already be realpath'd: `resolveDependencyPackageRoot` returns
634
+ * `realpathSync.native`, so a package reached through a link out of
635
+ * `node_modules` reports its checkout location and a package that merely lives
636
+ * in `node_modules` reports a path that still carries the segment.
637
+ *
638
+ * `pathApi` is injectable so the Windows separator handling is unit-testable
639
+ * from a POSIX runner, exactly as {@link isInside} does. The separator sets
640
+ * differ deliberately: `\` is a legal filename character on POSIX, so only
641
+ * win32 may treat it as a boundary.
642
+ */
643
+ function hasNodeModulesSegment(candidate, pathApi = path) {
644
+ const segments = pathApi.sep === '\\' ? candidate.split(/[\\/]+/) : candidate.split('/');
645
+ return segments.includes('node_modules');
646
+ }
647
+ /** Test seam for {@link hasNodeModulesSegment} (see {@link _isInsideForTests}). */
648
+ export const _hasNodeModulesSegmentForTests = hasNodeModulesSegment;
649
+ /**
650
+ * How many dev dependencies may be admitted by RESOLVED LOCATION alone before
651
+ * the whole resolved-location channel is treated as untrustworthy and disabled.
652
+ *
653
+ * "Realpath carries no `node_modules` segment" is a proxy for "checkout-local",
654
+ * and a layout that materializes packages outside `node_modules` — pnpm with a
655
+ * relocated `virtual-store-dir`, a custom linker — makes every dev dependency
656
+ * pass it. Folding an entire dev tree into the receipt is not a graceful
657
+ * degradation: `runtimePackages`/`runtimeEntries`/`runtimeBytes` THROW, so a
658
+ * mis-fired proxy on a legitimate install would abort analyze outright.
659
+ *
660
+ * The bound is therefore on ADMISSIONS, and overflow admits NONE of them rather
661
+ * than an arbitrary prefix. A prefix would not bound the failure — the abort
662
+ * comes from the transitive payload of whichever trees get folded in — and it
663
+ * would make the receipt depend on an arbitrary slice of a sorted name list.
664
+ * Dropping the channel wholesale falls back to the specifier-only receipt,
665
+ * which is the behaviour that ships today and is known not to abort, and leaves
666
+ * the declared-intent half in {@link dependencyNames} untouched.
667
+ *
668
+ * Four is measured, not guessed. Monorepo and workspace links are declared
669
+ * (`file:`/`link:`/`workspace:`) and travel the uncapped declared half, so this
670
+ * channel only ever carries UNDECLARED `npm link <pkg>` — a manual, per-package
671
+ * developer action, in practice one or two packages. A mis-fire admits the
672
+ * entire dev-only set instead: 13 names in this repository's own install, tens
673
+ * in a typical application. The cap sits an order of magnitude below the
674
+ * mis-fire population and comfortably above realistic link counts.
675
+ */
676
+ const MAX_UNDECLARED_LOCAL_DEV_DEPENDENCIES = 4;
677
+ /**
678
+ * Dependency names whose resolved packages can contribute analyzer semantics.
679
+ *
680
+ * The three runtime sections are enumerated wholesale. `devDependencies` are
681
+ * deliberately not: a registry dev tool (vitest, eslint, typescript) is never
682
+ * loaded by the analyzer, and folding the dev tree into the receipt would churn
683
+ * `dependencyRuntime.digest` — and force a full re-analysis — on every unrelated
684
+ * devDependency bump.
685
+ *
686
+ * Locally linked dev dependencies are the exception. A `file:`/`link:`/
687
+ * `workspace:` sibling is part of this checkout and ships code the analyzer
688
+ * imports at runtime: GitNexus links `gitnexus-shared`, whose schema constants
689
+ * feed `RELATION_SCHEMA`/`NODE_SCHEMA_QUERIES`. In `kind: 'source'` runs that
690
+ * sibling sits outside `buildRoot`, so leaving it out let a semantic change
691
+ * there alter analyzer behaviour while moving neither `build.digest` nor
692
+ * `dependencyRuntime.digest` — DDL-affecting edits were still caught by the
693
+ * schema fingerprint, semantics-only edits by nothing.
694
+ *
695
+ * An unresolvable link (a published install, where the sibling checkout does not
696
+ * exist) still contributes its `<missing>` edge, so the linked package appearing
697
+ * or disappearing remains a receipt change rather than a silent one. That is why
698
+ * the specifier check cannot be replaced by resolution: resolution returns
699
+ * `null` for an absent linked checkout exactly as it does for an uninstalled
700
+ * registry dev tool, and the two must not be conflated.
701
+ *
702
+ * This function is the DECLARED-INTENT half and is enumerated for every package
703
+ * in the dependency BFS, so it must stay a pure function of the manifest. The
704
+ * RESOLVED-LOCATION half — `npm link <pkg>`, which leaves the specifier a
705
+ * registry range — lives in {@link undeclaredLocalDevDependencyNames} and is
706
+ * applied to the root package only.
707
+ */
600
708
  function dependencyNames(manifest) {
601
709
  const names = new Set();
602
710
  for (const section of [
@@ -609,6 +717,13 @@ function dependencyNames(manifest) {
609
717
  for (const name of Object.keys(section))
610
718
  names.add(name);
611
719
  }
720
+ const development = manifest.devDependencies;
721
+ if (development && typeof development === 'object') {
722
+ for (const [name, specifier] of Object.entries(development)) {
723
+ if (isLocallyLinkedSpecifier(specifier))
724
+ names.add(name);
725
+ }
726
+ }
612
727
  return [...names].sort(compareBytes);
613
728
  }
614
729
  function resolveDependencyPackageRoot(fromRoot, packageName, pathGuards, limits) {
@@ -641,6 +756,51 @@ function resolveDependencyPackageRoot(fromRoot, packageName, pathGuards, limits)
641
756
  cursor = parent;
642
757
  }
643
758
  }
759
+ /**
760
+ * Dev dependencies that are locally linked by INSTALLED LOCATION rather than by
761
+ * declared specifier — the `npm link <pkg>` shape, where the manifest still
762
+ * carries a registry range while `node_modules/<pkg>` is a symlink into a
763
+ * working checkout. {@link isLocallyLinkedSpecifier} is blind to those, yet the
764
+ * linked code is exactly as load-bearing for analyzer semantics as a declared
765
+ * `file:` sibling, so a semantic-only edit there would move neither digest.
766
+ *
767
+ * The resolver already knows: {@link resolveDependencyPackageRoot} returns a
768
+ * realpath, so a linked package reports a root outside every `node_modules`
769
+ * tree while an ordinary installed package cannot.
770
+ *
771
+ * Two properties are load-bearing and must not be relaxed:
772
+ *
773
+ * 1. ROOT ONLY. {@link dependencyNames} runs for every package in the BFS, and
774
+ * published tarballs keep their `devDependencies`, so probing dev-only names
775
+ * everywhere costs 1998 resolutions rather than the ~13 this manifest
776
+ * declares — measured on this install, with 0 true positives. Persisted
777
+ * `dependencyPathGuards` grow 2220 → 11049, and every guard is re-probed on
778
+ * each warm validation, so the cost is recurring and on the `status` path.
779
+ * Root-only costs 13 resolutions and ~29 guards.
780
+ * 2. An unresolvable name is NEVER admitted. `null` here means "uninstalled
781
+ * registry dev tool" far more often than "broken link", and admitting it
782
+ * would emit a `<missing>` edge for every dev tool absent from a published
783
+ * install. Declared links keep that edge through {@link dependencyNames};
784
+ * undeclared ones have no declaration to honour.
785
+ *
786
+ * The admission count is bounded by {@link MAX_UNDECLARED_LOCAL_DEV_DEPENDENCIES}.
787
+ */
788
+ function undeclaredLocalDevDependencyNames(rootPackage, pathGuards, limits) {
789
+ const development = rootPackage.manifest.devDependencies;
790
+ if (!development || typeof development !== 'object')
791
+ return [];
792
+ const admitted = [];
793
+ for (const [name, specifier] of Object.entries(development)) {
794
+ // Already carried by the declared half; resolving again would only add
795
+ // guards. Its `<missing>` edge is that half's responsibility.
796
+ if (isLocallyLinkedSpecifier(specifier))
797
+ continue;
798
+ const resolved = resolveDependencyPackageRoot(rootPackage.root, name, pathGuards, limits);
799
+ if (resolved !== null && !hasNodeModulesSegment(resolved))
800
+ admitted.push(name);
801
+ }
802
+ return admitted.length <= MAX_UNDECLARED_LOCAL_DEV_DEPENDENCIES ? admitted : [];
803
+ }
644
804
  function collectRuntimePackages(packageRoot, directoryGuards, pathGuards, options, budget, limits) {
645
805
  const rootManifestPath = path.join(packageRoot, 'package.json');
646
806
  recordDirectoryGuard(directoryGuards, packageRoot);
@@ -660,7 +820,20 @@ function collectRuntimePackages(packageRoot, directoryGuards, pathGuards, option
660
820
  budget.packages = 1;
661
821
  for (let index = 0; index < queue.length; index += 1) {
662
822
  const parent = queue[index];
663
- for (const dependencyName of dependencyNames(parent.manifest)) {
823
+ // The declared half is enumerated for every package; the resolved-location
824
+ // half is scoped to the root package, where the 1998-resolution /
825
+ // 8829-extra-guard blow-up documented on
826
+ // `undeclaredLocalDevDependencyNames` cannot occur. Dropping this scope is
827
+ // the expensive regression, so it is pinned by a guard-count test.
828
+ const dependencies = parent.root === packageRoot
829
+ ? [
830
+ ...new Set([
831
+ ...dependencyNames(parent.manifest),
832
+ ...undeclaredLocalDevDependencyNames(parent, pathGuards, limits),
833
+ ]),
834
+ ].sort(compareBytes)
835
+ : dependencyNames(parent.manifest);
836
+ for (const dependencyName of dependencies) {
664
837
  budget.edges += 1;
665
838
  if (budget.edges > limits.runtimeEdges) {
666
839
  throw new Error(`Analyzer dependency graph exceeded ${limits.runtimeEdges} edges: ${packageRoot}`);
@@ -736,22 +909,63 @@ function collectArtifacts(root, canonicalPrefix, directoryGuards, options, budge
736
909
  throw new Error(`Analyzer runtime payload scan exceeded ${limits.runtimeEntries} entries: ${root}`);
737
910
  }
738
911
  for (const entry of entries) {
912
+ const absolutePath = path.join(absoluteDir, entry.name);
913
+ const relativePath = path.relative(root, absolutePath).split(path.sep).join('/');
914
+ const stat = lstatSync(absolutePath);
739
915
  // Nested dependencies are collected from their manifests as separate
740
916
  // packages. Only prune those separately traversed trees and VCS
741
917
  // metadata; generic cache/model directories can contain loadable code,
742
918
  // native addons, Wasm modules, or data consumed by the runtime.
743
- if (entry.isDirectory() && PRUNED_RUNTIME_DIRECTORIES.has(entry.name)) {
919
+ //
920
+ // Pruning is decided by NAME alone. These four names never carry analyzer
921
+ // payload in any form: `node_modules` is traversed separately through
922
+ // `resolveDependencyPackageRoot` (which follows links and guards each
923
+ // hop), and a `.git`/`.hg`/`.svn` entry is VCS metadata whether it is a
924
+ // directory, a symbolic link into a shared store, or — inside a submodule
925
+ // or linked worktree checkout — a regular file holding a gitdir pointer.
926
+ // Hashing that pointer would make analyzer identity depend on where the
927
+ // checkout happens to live, which is a false-stale source, not a
928
+ // semantic input.
929
+ if (PRUNED_RUNTIME_DIRECTORIES.has(entry.name))
744
930
  continue;
745
- }
746
- const absolutePath = path.join(absoluteDir, entry.name);
747
- const relativePath = path.relative(root, absolutePath).split(path.sep).join('/');
748
- const stat = lstatSync(absolutePath);
749
931
  if (stat.isDirectory()) {
750
932
  if (depth >= limits.runtimeDepth) {
751
933
  throw new Error(`Analyzer runtime payload scan exceeded depth ${limits.runtimeDepth}: ${absolutePath}`);
752
934
  }
753
935
  pending.push({ absoluteDir: absolutePath, depth: depth + 1 });
754
936
  }
937
+ else if (stat.isSymbolicLink() && !isFile(absolutePath)) {
938
+ // A symbolic link that does not resolve to a regular file must never
939
+ // reach the payload branch below: `snapshotReadableFile` stats the
940
+ // target, and a directory (or a dangling link) makes it throw, aborting
941
+ // the entire analyze. Workspace-linked checkouts made this reachable
942
+ // for every name, not just the pruned four — `dist -> build`, a
943
+ // vendored-grammar link, anything a sibling checkout ships.
944
+ //
945
+ // Such links are RECORDED by their link text rather than followed.
946
+ // Following them would (a) recurse without cycle protection — this
947
+ // traversal has none, so `self -> .` would ride the depth limit, which
948
+ // THROWS, trading one hard abort for another; (b) re-scan trees already
949
+ // reached by their real path, inflating the entry/byte budgets that
950
+ // also throw; and (c) need a whole containment/TOCTOU trust boundary
951
+ // for targets outside the package. Recording the text is cycle-free,
952
+ // costs one `readlink`, and still moves the receipt when the link is
953
+ // retargeted. The trade-off is that a link's target contributes no
954
+ // content of its own: when it points outside the package, only the
955
+ // link text is covered. Links that DO resolve to a regular file keep
956
+ // their content digest below, unchanged.
957
+ if (shouldHashRuntimePayload(relativePath)) {
958
+ budget.artifacts += 1;
959
+ if (budget.artifacts > limits.runtimePayloads) {
960
+ throw new Error(`Analyzer runtime payload scan exceeded ${limits.runtimePayloads} payloads: ${root}`);
961
+ }
962
+ artifacts.push({
963
+ absolutePath,
964
+ canonicalPath: `${canonicalPrefix}/${relativePath}`,
965
+ kind: 'unfollowed-symlink',
966
+ });
967
+ }
968
+ }
755
969
  else if ((stat.isFile() || stat.isSymbolicLink()) &&
756
970
  shouldHashRuntimePayload(relativePath)) {
757
971
  const readableState = snapshotReadableFile(absolutePath);
@@ -889,7 +1103,7 @@ function dependencySnapshot(inputs) {
889
1103
  absolutePath: artifact.absolutePath,
890
1104
  canonicalPath: artifact.canonicalPath,
891
1105
  kind: artifact.kind,
892
- state: snapshotReadableFile(artifact.absolutePath),
1106
+ state: snapshotRuntimeArtifact(artifact),
893
1107
  })),
894
1108
  directories: [...inputs.directoryGuards.entries()]
895
1109
  .map(([absolutePath, guard]) => ({ absolutePath, ...guard }))
@@ -903,9 +1117,26 @@ function artifactCacheKey(artifact) {
903
1117
  return JSON.stringify([artifact.kind, artifact.canonicalPath, artifact.absolutePath]);
904
1118
  }
905
1119
  function hashRuntimeArtifact(artifact, cache, options) {
1120
+ if (artifact.kind === 'unfollowed-symlink') {
1121
+ // The link text is the entire payload, so there is no file read for a
1122
+ // cached digest to amortize: recompute it and stay independent of the
1123
+ // cache's freshness. The distinct frame label keeps a link recording from
1124
+ // ever colliding with a content digest.
1125
+ const state = snapshotSymlinkArtifact(artifact.absolutePath);
1126
+ return {
1127
+ ...artifact,
1128
+ state,
1129
+ digest: hashCanonicalFrames([
1130
+ ['runtime-payload-link-v1', artifact.kind, state.symlinkTarget],
1131
+ ]),
1132
+ };
1133
+ }
906
1134
  const before = snapshotReadableFile(artifact.absolutePath);
907
- if (cache && SHA256_PATTERN.test(cache.digest) && isDeepStrictEqual(cache.state, before)) {
908
- return { digest: cache.digest, state: before };
1135
+ if (cache &&
1136
+ cache.kind !== 'unfollowed-symlink' &&
1137
+ SHA256_PATTERN.test(cache.digest) &&
1138
+ isDeepStrictEqual(cache.state, before)) {
1139
+ return { ...artifact, state: before, digest: cache.digest };
909
1140
  }
910
1141
  const stable = hashStableFile(artifact.absolutePath);
911
1142
  const digest = hashCanonicalFrames([
@@ -921,7 +1152,7 @@ function hashRuntimeArtifact(artifact, cache, options) {
921
1152
  path: artifact.absolutePath,
922
1153
  bytes: stable.bytes,
923
1154
  });
924
- return { digest, state: stable.state };
1155
+ return { ...artifact, state: stable.state, digest };
925
1156
  }
926
1157
  function compareEdges(a, b) {
927
1158
  return compareBytes(JSON.stringify([
@@ -986,7 +1217,7 @@ function hashDependencyRuntime(inputs, cache, options, runtimeVariant) {
986
1217
  artifact.kind,
987
1218
  digestBytes(hashed.digest),
988
1219
  ]);
989
- nextArtifacts.push({ ...artifact, state: hashed.state, digest: hashed.digest });
1220
+ nextArtifacts.push(hashed);
990
1221
  }
991
1222
  return {
992
1223
  identity: {
@@ -1014,6 +1245,17 @@ function isReadableFileState(value) {
1014
1245
  isStatState(record.target) &&
1015
1246
  (record.symlinkTarget === undefined || typeof record.symlinkTarget === 'string'));
1016
1247
  }
1248
+ function isSymlinkArtifactState(value) {
1249
+ if (typeof value !== 'object' || value === null)
1250
+ return false;
1251
+ const record = value;
1252
+ // `target === undefined` keeps a readable-file state from masquerading as an
1253
+ // unresolved link recording, which would otherwise be validated against the
1254
+ // wrong guard mode on the warm path.
1255
+ return (isStatState(record.link) &&
1256
+ typeof record.symlinkTarget === 'string' &&
1257
+ record.target === undefined);
1258
+ }
1017
1259
  function isDependencyPathGuardResult(value) {
1018
1260
  if (value === null)
1019
1261
  return true;
@@ -1159,13 +1401,16 @@ function isIdentityCachePayload(value, packageRoot, buildRoot, runtimeVariant, t
1159
1401
  if (typeof entry !== 'object' || entry === null)
1160
1402
  return false;
1161
1403
  const item = entry;
1162
- return (typeof item.absolutePath === 'string' &&
1163
- path.isAbsolute(item.absolutePath) &&
1164
- typeof item.canonicalPath === 'string' &&
1165
- (item.kind === 'file' || item.kind === 'symlink') &&
1166
- isReadableFileState(item.state) &&
1167
- typeof item.digest === 'string' &&
1168
- SHA256_PATTERN.test(item.digest));
1404
+ if (typeof item.absolutePath !== 'string' ||
1405
+ !path.isAbsolute(item.absolutePath) ||
1406
+ typeof item.canonicalPath !== 'string' ||
1407
+ typeof item.digest !== 'string' ||
1408
+ !SHA256_PATTERN.test(item.digest)) {
1409
+ return false;
1410
+ }
1411
+ return item.kind === 'unfollowed-symlink'
1412
+ ? isSymlinkArtifactState(item.state)
1413
+ : (item.kind === 'file' || item.kind === 'symlink') && isReadableFileState(item.state);
1169
1414
  });
1170
1415
  const hasBuildRootGuard = record.buildDirectoryGuards.some((entry) => typeof entry === 'object' &&
1171
1416
  entry !== null &&
@@ -1587,9 +1832,24 @@ function validateIdentityCache(cache, options) {
1587
1832
  }
1588
1833
  }
1589
1834
  for (const artifact of cache.artifactEntries) {
1590
- if (!add({ absolutePath: artifact.absolutePath, mode: 'readable-file' }, { type: 'readable-file', state: artifact.state })) {
1835
+ // A recorded link is re-probed as a link, never as a readable file: the
1836
+ // readable-file probe resolves the target and would report `null` for the
1837
+ // very inputs this kind exists to describe, failing every warm validation.
1838
+ const probe = artifact.kind === 'unfollowed-symlink'
1839
+ ? {
1840
+ request: { absolutePath: artifact.absolutePath, mode: 'link' },
1841
+ expected: {
1842
+ type: 'symlink',
1843
+ state: artifact.state.link,
1844
+ symlinkTarget: artifact.state.symlinkTarget,
1845
+ },
1846
+ }
1847
+ : {
1848
+ request: { absolutePath: artifact.absolutePath, mode: 'readable-file' },
1849
+ expected: { type: 'readable-file', state: artifact.state },
1850
+ };
1851
+ if (!add(probe.request, probe.expected))
1591
1852
  return false;
1592
- }
1593
1853
  }
1594
1854
  const entries = [...expected.entries()];
1595
1855
  const requests = entries.map(([key]) => {
@@ -9,7 +9,10 @@ import { loadMeta } from '../../storage/repo-manager.js';
9
9
  import { GroupNotFoundError, loadGroupConfig } from './config-parser.js';
10
10
  import { fileMatchesServicePrefix, normalizeServicePrefix, repoInSubgroup, } from './group-path-utils.js';
11
11
  import { getDefaultGitnexusDir, getGroupDir, listGroups, readContractRegistry } from './storage.js';
12
- import { syncGroup } from './sync.js';
12
+ // `./sync.js` is imported LAZILY in `groupSync` — see the comment at its call
13
+ // site. It statically pulls the six contract extractors and, through them, the
14
+ // native tree-sitter binding; a static import here puts all of that on MCP
15
+ // server startup, which never syncs.
13
16
  import { logger } from '../logger.js';
14
17
  function isStoredContract(raw) {
15
18
  if (!raw || typeof raw !== 'object')
@@ -166,6 +169,12 @@ export class GroupService {
166
169
  return { error: `Group "${name}" not found. Run group_list to see configured groups.` };
167
170
  throw err;
168
171
  }
172
+ // Lazy: `sync.js` reaches the six contract extractors and the native
173
+ // tree-sitter binding. `groupSync` is the ONLY consumer — the other seven
174
+ // group tools never need it — so deferring it here keeps that closure off
175
+ // MCP server startup entirely and off every non-sync group call. The CLI
176
+ // already does exactly this at `cli/group.ts`'s sync command.
177
+ const { syncGroup } = await import('./sync.js');
169
178
  const result = await syncGroup(config, {
170
179
  groupDir,
171
180
  exactOnly: Boolean(params.exactOnly),
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Wire format of the `BasicBlock.callees` / `BasicBlock.calleeIds` cells.
3
+ *
4
+ * A LEAF module on purpose: it declares two string constants and imports
5
+ * nothing. `cfg/emit.ts` produces those cells and `mcp/local/pdg-impact.ts`
6
+ * parses them, but `emit.ts` is analyze-only and drags the whole CFG closure
7
+ * (reaching-defs, control-dependence, post-dominators, synthetic-escape,
8
+ * call-site-harvest) behind it — 8 modules evaluated at every MCP server start
9
+ * just to read two strings, since ESM evaluates a module to import any binding
10
+ * from it (#2802 review). Splitting the format constants out deletes that cost
11
+ * rather than deferring it, which is the same bar #2802 held its own proposals
12
+ * to.
13
+ *
14
+ * `emit.ts` RE-EXPORTS both names, so every existing importer keeps working and
15
+ * the producer/consumer pair still resolves to one definition — the drift this
16
+ * shared constant exists to prevent stays impossible.
17
+ */
18
+ /**
19
+ * Reserved token placed in `BasicBlock.callees` when a statement's call sites
20
+ * were truncated at the per-statement site cap: the recorded callee list is then
21
+ * INCOMPLETE, so over-cap callees are absent. `*` is not a valid identifier
22
+ * leaf, so it cannot collide with a real callee name. The impact bridge treats a
23
+ * slice containing this sentinel as "callees unknown" and keeps reach
24
+ * callgraph-equal (proven), rather than falsely labeling an absent-but-real
25
+ * callee `unproven-bridge`.
26
+ */
27
+ export declare const CALLEES_TRUNCATED_SENTINEL = "*";
28
+ /**
29
+ * Inner separator for the `BasicBlock.calleeIds` cell (resolved callee symbol
30
+ * ids). A TAB is used — NOT a space — because resolved ids embed `filePath` and
31
+ * C++ overload shape tags with multi-word primitive types (e.g. `unsigned char`,
32
+ * `long double`), so an id can legitimately contain a space; a space-joined cell
33
+ * then fragments on read and silently drops inter-procedural reach to that
34
+ * callee (#2227 tri-review). A tab cannot appear in a tree-sitter-derived id
35
+ * token (paths/identifiers/type tokens are tab-free) and round-trips intact
36
+ * through `escapeCSVField` (tab is in its preserved set) and the RFC-4180 COPY
37
+ * reader (every cell is quoted). Producer (`calleeIdsOfBlock`) and consumer
38
+ * (`splitCalleeIds`) both resolve to this single constant so they cannot drift.
39
+ * The sibling `callees` (leaf-name) cell stays space-joined — leaf names are
40
+ * bare identifiers and never contain a space.
41
+ */
42
+ export declare const CALLEE_ID_SEP = "\t";
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Wire format of the `BasicBlock.callees` / `BasicBlock.calleeIds` cells.
3
+ *
4
+ * A LEAF module on purpose: it declares two string constants and imports
5
+ * nothing. `cfg/emit.ts` produces those cells and `mcp/local/pdg-impact.ts`
6
+ * parses them, but `emit.ts` is analyze-only and drags the whole CFG closure
7
+ * (reaching-defs, control-dependence, post-dominators, synthetic-escape,
8
+ * call-site-harvest) behind it — 8 modules evaluated at every MCP server start
9
+ * just to read two strings, since ESM evaluates a module to import any binding
10
+ * from it (#2802 review). Splitting the format constants out deletes that cost
11
+ * rather than deferring it, which is the same bar #2802 held its own proposals
12
+ * to.
13
+ *
14
+ * `emit.ts` RE-EXPORTS both names, so every existing importer keeps working and
15
+ * the producer/consumer pair still resolves to one definition — the drift this
16
+ * shared constant exists to prevent stays impossible.
17
+ */
18
+ /**
19
+ * Reserved token placed in `BasicBlock.callees` when a statement's call sites
20
+ * were truncated at the per-statement site cap: the recorded callee list is then
21
+ * INCOMPLETE, so over-cap callees are absent. `*` is not a valid identifier
22
+ * leaf, so it cannot collide with a real callee name. The impact bridge treats a
23
+ * slice containing this sentinel as "callees unknown" and keeps reach
24
+ * callgraph-equal (proven), rather than falsely labeling an absent-but-real
25
+ * callee `unproven-bridge`.
26
+ */
27
+ export const CALLEES_TRUNCATED_SENTINEL = '*';
28
+ /**
29
+ * Inner separator for the `BasicBlock.calleeIds` cell (resolved callee symbol
30
+ * ids). A TAB is used — NOT a space — because resolved ids embed `filePath` and
31
+ * C++ overload shape tags with multi-word primitive types (e.g. `unsigned char`,
32
+ * `long double`), so an id can legitimately contain a space; a space-joined cell
33
+ * then fragments on read and silently drops inter-procedural reach to that
34
+ * callee (#2227 tri-review). A tab cannot appear in a tree-sitter-derived id
35
+ * token (paths/identifiers/type tokens are tab-free) and round-trips intact
36
+ * through `escapeCSVField` (tab is in its preserved set) and the RFC-4180 COPY
37
+ * reader (every cell is quoted). Producer (`calleeIdsOfBlock`) and consumer
38
+ * (`splitCalleeIds`) both resolve to this single constant so they cannot drift.
39
+ * The sibling `callees` (leaf-name) cell stays space-joined — leaf names are
40
+ * bare identifiers and never contain a space.
41
+ */
42
+ export const CALLEE_ID_SEP = '\t';
@@ -22,30 +22,15 @@ import type { KnowledgeGraph } from '../../graph/types.js';
22
22
  import { type ReachingDefsSolver } from './reaching-defs.js';
23
23
  import type { BasicBlockData, BindingEntry, FunctionCfg } from './types.js';
24
24
  /**
25
- * Reserved token placed in `BasicBlock.callees` when a statement's call sites
26
- * were truncated at {@link DEFAULT_PDG_MAX_SITES_PER_STATEMENT}: the recorded
27
- * callee list is then INCOMPLETE, so over-cap callees are absent. `*` is not a
28
- * valid identifier leaf, so it cannot collide with a real callee name. The
29
- * impact bridge treats a slice containing this sentinel as "callees unknown" and
30
- * keeps reach callgraph-equal (proven), rather than falsely labeling an
31
- * absent-but-real callee `unproven-bridge`.
25
+ * Cell-format constants live in the LEAF module `callee-cell-format.ts` and are
26
+ * re-exported here so every existing importer keeps working. The consumer side
27
+ * (`mcp/local/pdg-impact.ts`) imports them from the leaf directly: importing any
28
+ * binding from THIS module evaluates it, and with it the whole analyze-only CFG
29
+ * closure — 8 modules on every MCP server start to read two strings (#2802
30
+ * review). Producer and consumer still resolve to one definition, so the drift
31
+ * these shared constants exist to prevent stays impossible.
32
32
  */
33
- export declare const CALLEES_TRUNCATED_SENTINEL = "*";
34
- /**
35
- * Inner separator for the `BasicBlock.calleeIds` cell (resolved callee symbol
36
- * ids). A TAB is used — NOT a space — because resolved ids embed `filePath` and
37
- * C++ overload shape tags with multi-word primitive types (e.g. `unsigned char`,
38
- * `long double`), so an id can legitimately contain a space; a space-joined cell
39
- * then fragments on read and silently drops inter-procedural reach to that
40
- * callee (#2227 tri-review). A tab cannot appear in a tree-sitter-derived id
41
- * token (paths/identifiers/type tokens are tab-free) and round-trips intact
42
- * through `escapeCSVField` (tab is in its preserved set) and the RFC-4180 COPY
43
- * reader (every cell is quoted). Producer ({@link calleeIdsOfBlock}) and
44
- * consumer (`splitCalleeIds`) import this single constant so they cannot drift.
45
- * The sibling `callees` (leaf-name) cell stays space-joined — leaf names are
46
- * bare identifiers and never contain a space.
47
- */
48
- export declare const CALLEE_ID_SEP = "\t";
33
+ export { CALLEES_TRUNCATED_SENTINEL, CALLEE_ID_SEP } from './callee-cell-format.js';
49
34
  /**
50
35
  * Default per-function CFG edge cap. A pathological generated function could
51
36
  * otherwise emit an unbounded edge set; the cap bounds graph growth and is
@@ -6,31 +6,17 @@ import { augmentForPostDom } from './synthetic-escape.js';
6
6
  import { DEFAULT_PDG_MAX_SITES_PER_STATEMENT } from './visitors/call-site-harvest.js';
7
7
  import { calleeIdPosKey } from '../scope-resolution/graph-bridge/callee-id-sink.js';
8
8
  import { encodeReachingDefReasonPairs } from './reaching-def-reason-codec.js';
9
+ import { CALLEES_TRUNCATED_SENTINEL, CALLEE_ID_SEP } from './callee-cell-format.js';
9
10
  /**
10
- * Reserved token placed in `BasicBlock.callees` when a statement's call sites
11
- * were truncated at {@link DEFAULT_PDG_MAX_SITES_PER_STATEMENT}: the recorded
12
- * callee list is then INCOMPLETE, so over-cap callees are absent. `*` is not a
13
- * valid identifier leaf, so it cannot collide with a real callee name. The
14
- * impact bridge treats a slice containing this sentinel as "callees unknown" and
15
- * keeps reach callgraph-equal (proven), rather than falsely labeling an
16
- * absent-but-real callee `unproven-bridge`.
11
+ * Cell-format constants live in the LEAF module `callee-cell-format.ts` and are
12
+ * re-exported here so every existing importer keeps working. The consumer side
13
+ * (`mcp/local/pdg-impact.ts`) imports them from the leaf directly: importing any
14
+ * binding from THIS module evaluates it, and with it the whole analyze-only CFG
15
+ * closure — 8 modules on every MCP server start to read two strings (#2802
16
+ * review). Producer and consumer still resolve to one definition, so the drift
17
+ * these shared constants exist to prevent stays impossible.
17
18
  */
18
- export const CALLEES_TRUNCATED_SENTINEL = '*';
19
- /**
20
- * Inner separator for the `BasicBlock.calleeIds` cell (resolved callee symbol
21
- * ids). A TAB is used — NOT a space — because resolved ids embed `filePath` and
22
- * C++ overload shape tags with multi-word primitive types (e.g. `unsigned char`,
23
- * `long double`), so an id can legitimately contain a space; a space-joined cell
24
- * then fragments on read and silently drops inter-procedural reach to that
25
- * callee (#2227 tri-review). A tab cannot appear in a tree-sitter-derived id
26
- * token (paths/identifiers/type tokens are tab-free) and round-trips intact
27
- * through `escapeCSVField` (tab is in its preserved set) and the RFC-4180 COPY
28
- * reader (every cell is quoted). Producer ({@link calleeIdsOfBlock}) and
29
- * consumer (`splitCalleeIds`) import this single constant so they cannot drift.
30
- * The sibling `callees` (leaf-name) cell stays space-joined — leaf names are
31
- * bare identifiers and never contain a space.
32
- */
33
- export const CALLEE_ID_SEP = '\t';
19
+ export { CALLEES_TRUNCATED_SENTINEL, CALLEE_ID_SEP } from './callee-cell-format.js';
34
20
  /**
35
21
  * Default per-function CFG edge cap. A pathological generated function could
36
22
  * otherwise emit an unbounded edge set; the cap bounds graph growth and is
@@ -10,6 +10,12 @@ import { escapeCypherString } from './cypher-escape.js';
10
10
  import { withConnLock } from './conn-lock.js';
11
11
  import { isWalDriverActive } from './wal-driver-state.js';
12
12
  import { NODE_TABLES, REL_TABLE_NAME, SCHEMA_QUERIES, EMBEDDING_TABLE_NAME, CREATE_VECTOR_INDEX_QUERY, STALE_HASH_SENTINEL, } from './schema.js';
13
+ // Analyze-only, but reached from MCP startup via `pool-adapter.js`. #2802
14
+ // proposed lazy-importing it; rejected — `core/search/bm25-index.ts` statically
15
+ // imports `normalizeFtsText` from `csv-generator.js`, and `local-backend.ts`
16
+ // dynamically imports bm25-index on the FTS query path, so deferring here
17
+ // relocates the startup cost to first query rather than removing it. The
18
+ // measured figures live in #2802; they were environment-bound, this is not.
13
19
  import { streamAllCSVsToDisk } from './csv-generator.js';
14
20
  import { getNodeLabel as deriveNodeLabel } from './rel-pair-routing.js';
15
21
  import { EMBEDDABLE_LABELS } from '../embeddings/types.js';