mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* docs(plans): add resumable analyze plan * perf(bench): measure resumable storage primitives * feat(embeddings): bound and persist work selection * feat(embeddings): persist resumable vector jobs Keep graph readers independent of vector writes. Acknowledge units only after complete chunk verification and a native checkpoint. * feat(embeddings): stream resumable job units * feat(storage): add generation publication Publish durable graph generations independently of vector jobs and gate readers on matching identities. Retain the legacy graph inode under a private name so older binaries cannot serve a stale canonical graph. Coordinator integration follows separately. Refs #3598 * feat(embeddings): coordinate durable jobs Join published graph selection, durable work, bounded native handles and vector publication behind one inactive controller. Limit optional HTTP response decoding within the job reservation and admit supported large inputs under larger budgets. Refs #3598 * feat(analyze): pass phase resource allocations Carry per-run worker heaps and native pools without changing legacy defaults. Hold parser reservations through safe native exit; refuse database reallocation after an unverified close. * feat(embeddings): reserve sidecar resources Pin each durable job to an admitted model heap and CPU config. Retain native allocations after caller cancellation until response or process exit, and reject phase handoff when release is unverified. * feat(status): separate graph and vector readiness Report embedding debt independently from graph content freshness. Read bounded durable progress without loading native runtimes, gate stale vector capability stamps, and allowlist additive phase counters on public SSE and ops payloads. * fix(embeddings): recover interrupted job setup Recover an owned empty native catalog after interrupted bootstrap, and rebuild damaged failure accounting without repeating completed provider work. Preserve foreign artifacts and propagate filesystem errors. * fix(resources): verify native pool release Keep failed and concurrent native closes tracked until release succeeds. Refuse another reserved allocation while cleanup is unverified, including failed connection construction. Let graph readers tear down after result-close errors. * fix(resources): drain graph before phase admission Wait for session work and verify the prior main graph pool has closed before parser or embedding admission. Recheck cancellation after the drain so cancelled jobs do not read or mutate job metadata. * docs(plans): revise resumable analyze seams * perf(bench): measure paired analyze runs * feat(index): publish logical graph generations Retain private database files across incremental generations and fence prepared publication against superseding writers. Exit-only producers must exit before publication; interrupted in-place writes remain explicitly dirty. * feat(index): guard graph process handoff Wait for actual process exit and reacquire the ordinary slot lock before publishing the prepared attempt. Recheck placement and the registered name, and retain graph discoverability after cancellation. Add a bounded nonterminal worker receipt without serializing the live graph. Production phase activation remains separate. * feat(cli): defer success across graph handoff Finish live-graph skill generation before the child hands off. Transfer only bounded counters, identity and the pre-run self-commit safety flags; wait for IPC delivery before returning for native process exit. Reject missing supervisors and mismatched prepared results before skill writes. Finalization, self-commit and success remain deferred until the production supervisor completes embedding; core activation follows the pending-artifact and resource contracts. Refs #3598 * feat(embeddings): rebase pending paid artifacts Separate graph job identity from mutable artifact ownership. Keep paid compatible groups across source edits using bounded revalidation and selection pruning; retain one sealed fallback for the active space. * feat(embeddings): preserve historical coverage * feat(embeddings): reuse verified legacy vectors Retain a directly referenced legacy source across pending-artifact rebases. Stream checkpoint exclusions and build a native metadata index without copying vectors or retaining corpus-sized JavaScript maps. Require recorded provider identity and provable complete input groups. Keep unknown provenance explicit, source artifacts immutable, compatible relocations free of provider calls, and new inputs in normal batches. The controller remains inactive until coordinated writer activation. Refs #3598 * feat(analyze): account for supervised phases Charge parent memory once per phase. Carry allowlisted progress through worker IPC and preserve counters across logs without completing the job. Refs #3598 * fix(storage): retain owned analysis generations Keep private generation files in place through shared-store preparation and publication. Retain prepared publications and pending embedding work across the unlocked process handoff, including work in branch slots. Refs #3598 * fix(embeddings): share pinned vector readers Share immutable vector file identities so sibling hard links retain one native reservation. Keep the handle alive until its final reader closes, including failed initialization and replacement of another reader's path. Refs #3598 * feat(storage): share completed vector artifacts Pin immutable vectors independently in checkout slots and shared graph snapshots. Keep mutable jobs with their owning checkout; resume interrupted adoption without overwriting unverified files. Refs #3598 * feat(analyze): retain caches across phase handoff Keep prepared staging during lock reacquisition and share cache publication between the graph writer and exit continuation. Bound the filesystem handoff to chunk keys; never copy live cache contents. Refs #3598 * fix(analyze): retain owned generation routing Keep prepared and pending work under its original slot lock during shared-store adoption. Preserve private generation filenames during incremental writes without copying the graph. Drain model and native resources only when graph work actually starts, including FTS repair. Leave the warm no-op path unchanged. Validated 158 tests, source build, test typecheck, formatting and lint. Complete graph gates cover 29 symbols in two files and the expected coordinator flow. End-to-end embedding activation and performance acceptance remain pending. * feat(analyze): wire resumable phase execution Publish verified graphs before embedding and hand off resource ownership across CLI, watch, auto-sync, and HTTP phases. Keep completed vectors readable while durable embedding units resume in a separate generation. Preserve legacy vector reuse, avoid graph rebuilds for dimension changes, and cover interruption boundaries with fresh-process restart tests. Refs #3598 * fix(analyze): close recovery and ownership gaps Retain interrupted private work, clear stale query widths, and keep native reservations until confirmed worker exit. Keep shared-member admission gates outside garbage-collected directories for flat and branch writers. Reject invalid routes and overlaps, and distinguish validation from uncertain writes. Make test imports work before build, isolate host-capacity assertions, and give legacy vector fixtures the production native pool allocation. Focused regressions, clean-build types, formatting and lint pass. Graph analysis maps 51 symbols across 21 paths. Two import-only test paths remain unmapped; direct review and integration tests cover them. The parent full suite passed 32,084 tests with five failures: two fixed legacy-vector fixture cases and three recovery cases awaiting isolation. Final full-suite and performance acceptance remain pending on the draft. Refs #3598 * perf(embeddings): batch reused vector writes Avoid a native transaction per reused node while retaining the byte budget and durable unit boundary. Cover mixed inputs, cancellation, and replay after read or committed-write failures. Native regression fails before the fix (65 commits for 64 nodes). 79 focused tests and all three former recovery timeouts pass. Fresh graph gate: 18 symbols, 2 files, 36 affected flows; complete mapping. Final whole-command performance acceptance remains pending. Refs #3598 * fix(analyze): honor explicit worker overrides Preserve the existing CPU oversubscription override while reserving memory for every requested worker. Automatic concurrency stays CPU-bounded. Validate on one- and four-CPU hosts: 81 tests pass; the override regressions fail before the fix. * fix(storage): validate opened artifact files Validate descriptors before reading bounded receipts and manifests. Use nonblocking opens to reject FIFO substitutions and verify directory entries when O_NOFOLLOW is unavailable. Preserve the metadata cache fast path and guard generation paths explicitly. Remove the redundant pending-node fallback. Add race, symlink, cleanup, and cache regressions to platform coverage. * fix(storage): guard the graph path directly Apply the containment check to the same path passed to lstat. The nested normalization guarded a different expression in CodeQL. path.relative already resolves its inputs, so remove the redundant normalization and retain relative-path behavior. * fix(embeddings): preserve AST inputs on resume Carry indexed source policy into bounded resumable jobs and preserve exact-input reuse across sibling edits. Include strategy and retention in job identity; admit source memory before reading. * chore: run checks for the rebased stack * refactor(embeddings): simplify reuse plumbing Name reuse-validation options and share the owned-directory loop. Preserve callback order, directory sync, and ownership checks. * test: fix recovery and Windows CI fixtures Distinguish legacy checkpoints without input provenance from verified source-aware chunks. Check the embed API at its shared-phase boundary and model pathname races without rename-over-open on Windows. * fix: close resource admission and CI gaps Keep live sidecars charged after a reap timeout. Let sync and HTTP jobs use automatic host budgets instead of overcommitting to default V8 limits. Explain the incompatible native zero-pool override, clean up failed HTTP fixtures, and run the native vector suites across platforms. * fix: preserve analysis resource ownership Pin admitted model settings and retain worker and supervisor reservations. Recheck canonical directory identity before receipt reads or writes. Canonicalize the native publication fixture for macOS and Windows. * test: distinguish parameterized CI cases * docs: remove implementation plan from PR * ci: gate resumable analyze performance * fix(analyze): close recovery and CI gaps Retain ownership receipts and paid vectors through interrupted work and cleanup. Restore automatic heap and parser-worker sizing, and cover publication, cancellation and capacity failures. Refs #3829, #3598 Note: pre-existing setup.test.ts and setup-skills.test.ts failures with inherited CODEX_HOME; all 62 tests pass with it unset for the test process. * fix(embeddings): normalize graph parent paths Bind the canonical job root to the same graph path on macOS temp aliases and Windows short paths. Keep graph identity and owned-directory checks. Canonicalize the retention fixture and show subprocess stderr on failure. Validation: 65 focused tests; 26 tests through an aliased TMPDIR; build, test typecheck, formatting and lint; graph change analysis (4 files). * fix(embeddings): batch writes and guard recovery Batch bounded vector and receipt writes to remove per-node native calls without changing validation, transactions, or durable checkpoints. Pin publication descriptors before entry validation. Preserve excluded vector coverage, reject malformed status paths, retry orphan sidecars, and complete shutdown after child spawn failures. Validation: 159 focused tests and 89 native/restart tests; build, test typecheck, lint and formatting. Refreshed graph analysis maps production changes; three test files remain unmapped. * ci: profile fresh analyze overhead Capture process and parser-worker CPU profiles in a separate CI-only run. Reject profiling with --check so diagnostic overhead never affects the acceptance gate. * perf(analyze): trim continuation startup work * fix(analyze): preserve recovery and storage bounds Keep automatic writer pools page-scaled and restore frontend heap caps. Adopt a generation recovered during handoff, reclaim sealed artifacts, and retire compatible legacy sources after migration completes. Report semantic degradation and omit provider causes from API logs. Enforce no paid replay in the CI resume benchmark. * perf(analyze): defer unused parser imports * fix(workers): retain failed shutdown reservations * perf: skip unused budget supervisor receipt * fix: bound rejection history and watch budgets * perf: batch provider vector writes within units * fix: harden cleanup and semantic availability * perf: avoid repeated analysis startup probes Skip unused automatic-heap parent provenance and reuse one npm version probe for runner selection and its warning. Keep child/watch identity capture and manual/test heap overrides. Refs #3829. * fix: normalize legacy export paths on Windows Cover Unicode export directories and restore the heap parser comment. Refs #3829. * test: restore watch resource mock contract Provide the supervisor reservation used by watch refresh admission. Refs #3829. * fix: retain watch budgets and bound lookahead Keep explicit heap reservations across refreshes and limit brace scans to the existing three-line window. Refs #3829. * fix: stop retries on shutdown and allow empty parse * refactor: simplify embedding setup and test lists * perf: batch vector completion hash updates Keep hash finalization inside the existing transaction and row bounds. Run embedding input-isolation tests in the serial native project. * fix: address PR #3829 recovery feedback Preserve terminal worker results, reclaim orphan attempt metadata, retain artifacts with unrecognized space ownership, and correct the cancellation comment. * perf: retain simple vector completion query * perf: skip redundant alias identity probes * perf: avoid Git probes for ordinary checkout roots * perf: avoid redundant vector transactions Standalone writes already execute in automatic transactions. Keep multi-query transactions and durable unit checkpoints unchanged. * docs: clarify cancellation grace period * fix: finish vector recovery and explicit drops Preserve paid peers through source-admission aborts and complete legacy retirement after interrupted publication. Explicit drops remove validated vector payloads before their ownership receipts so later runs regenerate them. Refs #3829 * fix: preserve storage errors during aborts Only unwrap aborts raised by source admission. A simultaneous native write failure must propagate instead of entering the provider-abort completion path. Refs #3829 * fix: validate retained analysis artifacts Reject malformed cache keys before shard writes and retain legacy work before shared-store adoption. Explicit drops validate legacy ownership and keep receipts until payload cleanup succeeds. Damaged registered graphs block stale local hook fallback. * fix: preserve legacy and preflight contracts Keep the native-default pool override, retain incomplete legacy seeds with their owner, and include resource preflight in the worker timeout. * fix: honor resource and preflight boundaries Release optional cache space before rejecting an admissible source read. Start server deadlines before preflight and reject null progress counts. Pass the native-default pool sentinel through the database opener. * test: align native and drop contracts Accept the documented native-default zero sentinel. Verify the rebuilt graph and empty vectors instead of an obsolete escalation log. Refs #3829 * perf: avoid redundant vector checkpoints Acknowledge verified WAL commits without rewriting the database per unit. Keep the final publication checkpoint and prove crash recovery from WAL. Give publication test cases distinct titles for the CI execution audit. Refs #3829 --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
812 lines
32 KiB
TypeScript
812 lines
32 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
|
|
vi.mock('node:child_process', () => ({
|
|
execFileSync: vi.fn(),
|
|
}));
|
|
|
|
import { execFileSync } from 'node:child_process';
|
|
import {
|
|
getNpmMajorVersion,
|
|
warnIfNpm11NpxRisk,
|
|
NPX_REF,
|
|
} from '../../src/cli/resolve-invocation.js';
|
|
import { readFileSync, mkdtempSync, writeFileSync, chmodSync, rmSync } from 'node:fs';
|
|
import { createRequire } from 'node:module';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
|
|
const mockedExec = vi.mocked(execFileSync);
|
|
|
|
const cjsRequire = createRequire(import.meta.url);
|
|
const CANONICAL_CJS = path.resolve(
|
|
__dirname,
|
|
'..',
|
|
'..',
|
|
'hooks',
|
|
'claude',
|
|
'resolve-analyze-cmd.cjs',
|
|
);
|
|
const PLUGIN_CJS = path.resolve(
|
|
__dirname,
|
|
'..',
|
|
'..',
|
|
'..',
|
|
'gitnexus-claude-plugin',
|
|
'hooks',
|
|
'resolve-analyze-cmd.cjs',
|
|
);
|
|
|
|
interface CjsModule {
|
|
formatAnalyzeCommand: (
|
|
o?: { embeddings?: boolean; indexOnly?: boolean },
|
|
deps?: {
|
|
npmMajor?: number | null;
|
|
pnpmMajor?: number | null;
|
|
pnpmMinor?: number | null;
|
|
pnpmPresent?: boolean;
|
|
pnpmRuns?: boolean;
|
|
bunPresent?: boolean;
|
|
bunRuns?: boolean;
|
|
},
|
|
) => string;
|
|
formatBunxCommand: (args: string) => string;
|
|
formatDocumentationDlxCommand: (args: string, o?: { embeddings?: boolean }) => string;
|
|
formatPnpmAllowBuildArgs: (
|
|
o?: { embeddings?: boolean; alwaysAllowBuild?: boolean },
|
|
deps?: { pnpmMajor?: number | null; pnpmMinor?: number | null },
|
|
) => string[];
|
|
resolveInvocationMode: (
|
|
probe?: (command: string, gitnexusWrapper?: boolean) => string | null,
|
|
deps?: {
|
|
npmMajor?: number | null;
|
|
pnpmMajor?: number | null;
|
|
pnpmPresent?: boolean;
|
|
pnpmRuns?: boolean;
|
|
bunPresent?: boolean;
|
|
bunRuns?: boolean;
|
|
},
|
|
) => 'gitnexus' | 'pnpm' | 'npx' | 'bun';
|
|
resolveOnPath: (
|
|
command: string,
|
|
preferExecExt?: boolean,
|
|
opts?: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv },
|
|
) => string | null;
|
|
buildRunnerArgv: (
|
|
mode: 'gitnexus' | 'pnpm' | 'npx' | 'bun',
|
|
gitnexusArgs: string[],
|
|
deps?: { pnpmMajor?: number | null; pnpmMinor?: number | null },
|
|
) => { program: string; args: string[] };
|
|
NPX_REF: string;
|
|
}
|
|
|
|
// Require the real shipped artifact — the hook runtime loads this exact file, so
|
|
// the tests exercise production code, not a TypeScript mirror of it.
|
|
//
|
|
// Determinism invariant: createRequire bypasses vitest's node:child_process mock,
|
|
// so the only live subprocess this module can run is probeVersion (`npm`/`pnpm`/
|
|
// `bunx --version`). resolveOnPath is now spawn-free — a pure PATH scan — so tests
|
|
// pin it by passing an injected `{ platform, env }` (never the host PATH). Mode
|
|
// tests inject a fake `probe` or force GITNEXUS_INVOCATION; version tests inject
|
|
// `deps`. Any test whose `probe` reports a pnpm/bunx PATH hit MUST also inject
|
|
// `pnpmRuns`/`bunRuns`, or the liveness probe spawns the host's real tool and
|
|
// the result depends on whether that tool is installed.
|
|
// Keep new tests on one of those paths so results never depend on the host.
|
|
const cjs = cjsRequire(CANONICAL_CJS) as CjsModule;
|
|
|
|
describe('resolve-analyze-cmd.cjs (canonical invocation resolver)', () => {
|
|
beforeEach(() => {
|
|
vi.stubEnv('PATH', '');
|
|
if (process.platform !== 'win32') {
|
|
vi.stubEnv('Path', '');
|
|
vi.stubEnv('path', '');
|
|
}
|
|
vi.stubEnv('GITNEXUS_INVOCATION', undefined);
|
|
});
|
|
afterEach(() => {
|
|
vi.unstubAllEnvs();
|
|
});
|
|
|
|
it('standardizes the invocation ref on gitnexus@latest', () => {
|
|
expect(cjs.NPX_REF).toBe('gitnexus@latest');
|
|
});
|
|
|
|
it('formats each forced mode, with and without --embeddings', () => {
|
|
const allow = '--allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter';
|
|
const allowEmb =
|
|
'--allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter --allow-build=onnxruntime-node';
|
|
const cases = [
|
|
['gitnexus', 'gitnexus analyze', 'gitnexus analyze --embeddings'],
|
|
[
|
|
'pnpm',
|
|
`pnpm ${allow} dlx ${cjs.NPX_REF} analyze`,
|
|
`pnpm ${allowEmb} dlx ${cjs.NPX_REF} analyze --embeddings`,
|
|
],
|
|
['npx', `npx ${cjs.NPX_REF} analyze`, `npx ${cjs.NPX_REF} analyze --embeddings`],
|
|
] as const;
|
|
for (const [mode, plain, withEmbeddings] of cases) {
|
|
process.env.GITNEXUS_INVOCATION = mode;
|
|
expect(cjs.formatAnalyzeCommand(undefined, { pnpmMajor: 11 })).toBe(plain);
|
|
expect(cjs.formatAnalyzeCommand({ embeddings: true }, { pnpmMajor: 11 })).toBe(
|
|
withEmbeddings,
|
|
);
|
|
}
|
|
});
|
|
|
|
it('appends --index-only for the routine stale-index nudge (#2907)', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'gitnexus';
|
|
expect(cjs.formatAnalyzeCommand({ indexOnly: true })).toBe('gitnexus analyze --index-only');
|
|
expect(cjs.formatAnalyzeCommand({ indexOnly: true, embeddings: true })).toBe(
|
|
'gitnexus analyze --index-only --embeddings',
|
|
);
|
|
// Absent/false leaves the doc-refreshing form untouched.
|
|
expect(cjs.formatAnalyzeCommand({ indexOnly: false })).toBe('gitnexus analyze');
|
|
});
|
|
|
|
it('auto-selects global gitnexus first', () => {
|
|
expect(cjs.resolveInvocationMode(() => '/usr/local/bin/gitnexus')).toBe('gitnexus');
|
|
});
|
|
|
|
it('auto-selects pnpm on npm 11+ when pnpm is on PATH', () => {
|
|
const probe = (c: string) => (c === 'pnpm' ? '/usr/local/bin/pnpm' : null);
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11, pnpmRuns: true })).toBe('pnpm');
|
|
});
|
|
|
|
it('auto-selects npx on npm 10 even when pnpm is on PATH', () => {
|
|
const probe = (c: string) => (c === 'pnpm' ? '/usr/local/bin/pnpm' : null);
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: 10 })).toBe('npx');
|
|
});
|
|
|
|
it('auto-selects pnpm when npm is absent (null injected) but pnpm is on PATH', () => {
|
|
// npmMajor:null means "npm absent" and must be honored via the `in` seam —
|
|
// not fall through to the host's real npm (npm 10.x on CI → would route npx).
|
|
const probe = (c: string) => (c === 'pnpm' ? '/usr/local/bin/pnpm' : null);
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: null, pnpmRuns: true })).toBe('pnpm');
|
|
});
|
|
|
|
it('falls back to npx when npm is null-absent and pnpm is also absent', () => {
|
|
// Also pins the cheapest-first gate order in hasBun: neither `bunPresent` nor
|
|
// `bunRuns` is injected, so a liveness spawn ahead of the PATH scan would
|
|
// reach the host's real bunx and make this host-dependent.
|
|
expect(cjs.resolveInvocationMode(() => null, { npmMajor: null })).toBe('npx');
|
|
});
|
|
|
|
it('falls back to npx when neither global gitnexus nor pnpm is available', () => {
|
|
expect(cjs.resolveInvocationMode(() => null, { npmMajor: 11 })).toBe('npx');
|
|
});
|
|
|
|
it('honors pnpmPresent:true — a present-but-unparseable pnpm selects pnpm, not the npx crash path', () => {
|
|
// Windows headline regression guard: when probeVersion cannot read the
|
|
// version after a successful probe (Corepack banner), formatAnalyzeCommand
|
|
// sets pnpmPresent:true so npm-11 users still get pnpm rather than the npx crash.
|
|
expect(cjs.resolveInvocationMode(() => null, { npmMajor: 11, pnpmPresent: true })).toBe('pnpm');
|
|
});
|
|
|
|
it('honors pnpmPresent:false as explicit absence (overrides a PATH hit)', () => {
|
|
const probe = (c: string) => (c === 'pnpm' ? '/usr/local/bin/pnpm' : null);
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11, pnpmPresent: false })).toBe('npx');
|
|
});
|
|
|
|
it('omits --allow-build on pnpm 9 (scripts run by default)', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'pnpm';
|
|
expect(cjs.formatAnalyzeCommand(undefined, { pnpmMajor: 9 })).toBe(
|
|
`pnpm dlx ${cjs.NPX_REF} analyze`,
|
|
);
|
|
});
|
|
|
|
it('includes --allow-build (pre-dlx) on pnpm 10.x with unknown minor (conservative)', () => {
|
|
// No pnpmMinor injected → minor is null → the gate cannot prove < 10.2, so
|
|
// it conservatively emits the flags. This is the unknown-minor fallback, NOT
|
|
// real pnpm 10.0 (which reports minor=0 and is covered separately below).
|
|
process.env.GITNEXUS_INVOCATION = 'pnpm';
|
|
const allow = '--allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter';
|
|
expect(cjs.formatAnalyzeCommand(undefined, { pnpmMajor: 10 })).toBe(
|
|
`pnpm ${allow} dlx ${cjs.NPX_REF} analyze`,
|
|
);
|
|
});
|
|
|
|
it('omits --allow-build on pnpm 10.0 (the flag did not exist until 10.2)', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'pnpm';
|
|
expect(cjs.formatAnalyzeCommand(undefined, { pnpmMajor: 10, pnpmMinor: 0 })).toBe(
|
|
`pnpm dlx ${cjs.NPX_REF} analyze`,
|
|
);
|
|
});
|
|
|
|
it('omits --allow-build on pnpm 10.1 (the flag was added in 10.2)', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'pnpm';
|
|
expect(cjs.formatAnalyzeCommand(undefined, { pnpmMajor: 10, pnpmMinor: 1 })).toBe(
|
|
`pnpm dlx ${cjs.NPX_REF} analyze`,
|
|
);
|
|
});
|
|
|
|
it('includes --allow-build on pnpm 10.2 (the first minor that accepts the flag)', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'pnpm';
|
|
const allow = '--allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter';
|
|
expect(cjs.formatAnalyzeCommand(undefined, { pnpmMajor: 10, pnpmMinor: 2 })).toBe(
|
|
`pnpm ${allow} dlx ${cjs.NPX_REF} analyze`,
|
|
);
|
|
});
|
|
|
|
it('emits --allow-build when the pnpm major is null-injected (absent/unknown)', () => {
|
|
expect(cjs.formatPnpmAllowBuildArgs({}, { pnpmMajor: null })).toEqual([
|
|
'--allow-build=@ladybugdb/core',
|
|
'--allow-build=gitnexus',
|
|
'--allow-build=tree-sitter',
|
|
]);
|
|
});
|
|
|
|
it('formatDocumentationDlxCommand always includes allow-build for committed docs', () => {
|
|
expect(cjs.formatDocumentationDlxCommand('analyze')).toContain('--allow-build=@ladybugdb/core');
|
|
expect(cjs.formatDocumentationDlxCommand('analyze')).toContain('gitnexus@latest analyze');
|
|
});
|
|
|
|
it('auto-selects bunx when npm and pnpm are both absent (bun-only machine)', () => {
|
|
// The headline gap: with no npm/npx/pnpm on PATH every rung used to fall
|
|
// through to `npx`, emitting a command the machine cannot run at all.
|
|
const probe = (c: string) => (c === 'bunx' ? '/usr/local/bin/bunx' : null);
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: null, bunRuns: true })).toBe('bun');
|
|
});
|
|
|
|
it('auto-selects bunx on npm 11+ when pnpm is absent but bunx is present', () => {
|
|
// Same #1939 crash avoidance as the pnpm rung — bunx is install-free too.
|
|
const probe = (c: string) => (c === 'bunx' ? '/usr/local/bin/bunx' : null);
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11, bunRuns: true })).toBe('bun');
|
|
});
|
|
|
|
it('still prefers pnpm over bunx on npm 11+ when both are present', () => {
|
|
const probe = (c: string) =>
|
|
c === 'pnpm' ? '/usr/local/bin/pnpm' : c === 'bunx' ? '/usr/local/bin/bunx' : null;
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11, pnpmRuns: true, bunRuns: true })).toBe(
|
|
'pnpm',
|
|
);
|
|
});
|
|
|
|
it('still prefers npx on npm 10 even when bunx is present (no behavior change)', () => {
|
|
// Regression guard: the bun rungs must not steal the working npm<11 path.
|
|
const probe = (c: string) => (c === 'bunx' ? '/usr/local/bin/bunx' : null);
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: 10, bunRuns: true })).toBe('npx');
|
|
});
|
|
|
|
it('still prefers pnpm over bunx when npm is absent and both are present', () => {
|
|
const probe = (c: string) =>
|
|
c === 'pnpm' ? '/usr/local/bin/pnpm' : c === 'bunx' ? '/usr/local/bin/bunx' : null;
|
|
expect(
|
|
cjs.resolveInvocationMode(probe, { npmMajor: null, pnpmRuns: true, bunRuns: true }),
|
|
).toBe('pnpm');
|
|
});
|
|
|
|
it('honors bunPresent:false as explicit absence (overrides a PATH hit)', () => {
|
|
const probe = (c: string) => (c === 'bunx' ? '/usr/local/bin/bunx' : null);
|
|
expect(
|
|
cjs.resolveInvocationMode(probe, { npmMajor: null, bunPresent: false, bunRuns: true }),
|
|
).toBe('npx');
|
|
});
|
|
|
|
it('rejects a bunx that is on PATH but does not run (stale shim)', () => {
|
|
// A partial bun uninstall leaves an executable `bunx` behind that no longer
|
|
// runs. PATH existence alone would select bun, emit `bunx gitnexus@latest`,
|
|
// AND suppress the npm-11 npx warning — a silent dead end until execution.
|
|
const probe = (c: string) => (c === 'bunx' ? '/usr/local/bin/bunx' : null);
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: null, bunRuns: false })).toBe('npx');
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11, bunRuns: false })).toBe('npx');
|
|
});
|
|
|
|
it('rejects a pnpm that is on PATH but does not run (stale shim, #3717)', () => {
|
|
// When pnpm is an unusable shim (e.g. NVM for Windows: `pnpm --version` exits
|
|
// non-zero), mode resolution must not pick pnpm. On npm 11+ with bunx
|
|
// available, it falls through to bunx; without bunx, to npx.
|
|
const probeBoth = (c: string) =>
|
|
c === 'pnpm' ? '/usr/local/bin/pnpm' : c === 'bunx' ? '/usr/local/bin/bunx' : null;
|
|
const probePnpmOnly = (c: string) => (c === 'pnpm' ? '/usr/local/bin/pnpm' : null);
|
|
|
|
// With working bunx available -> falls through to bun
|
|
expect(
|
|
cjs.resolveInvocationMode(probeBoth, { npmMajor: 11, pnpmRuns: false, bunRuns: true }),
|
|
).toBe('bun');
|
|
expect(
|
|
cjs.resolveInvocationMode(probeBoth, { npmMajor: null, pnpmRuns: false, bunRuns: true }),
|
|
).toBe('bun');
|
|
|
|
// Without bunx available -> falls through to npx
|
|
expect(
|
|
cjs.resolveInvocationMode(probePnpmOnly, { npmMajor: 11, pnpmRuns: false, bunRuns: false }),
|
|
).toBe('npx');
|
|
expect(
|
|
cjs.resolveInvocationMode(probePnpmOnly, { npmMajor: null, pnpmRuns: false, bunRuns: false }),
|
|
).toBe('npx');
|
|
});
|
|
|
|
it('formatAnalyzeCommand falls through to bunx or npx when pnpm does not run (#3717)', () => {
|
|
expect(
|
|
cjs.formatAnalyzeCommand(undefined, {
|
|
npmMajor: 11,
|
|
pnpmRuns: false,
|
|
bunPresent: true,
|
|
bunRuns: true,
|
|
}),
|
|
).toBe(`bunx ${cjs.NPX_REF} analyze`);
|
|
expect(
|
|
cjs.formatAnalyzeCommand(undefined, { npmMajor: 11, pnpmRuns: false, bunPresent: false }),
|
|
).toBe(`npx ${cjs.NPX_REF} analyze`);
|
|
});
|
|
|
|
it('keeps pnpm when pnpmRuns:true even if version is unparseable (#3717)', () => {
|
|
const probe = (c: string) => (c === 'pnpm' ? '/usr/local/bin/pnpm' : null);
|
|
expect(
|
|
cjs.resolveInvocationMode(probe, { npmMajor: 11, pnpmMajor: null, pnpmRuns: true }),
|
|
).toBe('pnpm');
|
|
});
|
|
|
|
it('never probes bunx when npm or pnpm already decides the mode', () => {
|
|
// The bun lookup is lazy so machines with a Node toolchain pay no extra
|
|
// PATH scan — the stale-index hook budget is tight (PROBE_TIMEOUT_MS).
|
|
const probed: string[] = [];
|
|
const probe = (c: string) => {
|
|
probed.push(c);
|
|
return c === 'pnpm' ? '/usr/local/bin/pnpm' : null;
|
|
};
|
|
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11, pnpmRuns: true })).toBe('pnpm');
|
|
expect(probed).not.toContain('bunx');
|
|
});
|
|
|
|
it('formats and executes the bun mode as an install-free bunx one-shot', () => {
|
|
expect(cjs.formatBunxCommand('analyze')).toBe(`bunx ${cjs.NPX_REF} analyze`);
|
|
process.env.GITNEXUS_INVOCATION = 'bun';
|
|
expect(cjs.formatAnalyzeCommand()).toBe(`bunx ${cjs.NPX_REF} analyze`);
|
|
expect(cjs.formatAnalyzeCommand({ embeddings: true })).toBe(
|
|
`bunx ${cjs.NPX_REF} analyze --embeddings`,
|
|
);
|
|
expect(cjs.buildRunnerArgv('bun', ['analyze'])).toEqual({
|
|
program: 'bunx',
|
|
args: [cjs.NPX_REF, 'analyze'],
|
|
});
|
|
// bun has no per-invocation allow-build equivalent, so the argv stays flag-free.
|
|
expect(cjs.buildRunnerArgv('bun', ['analyze']).args).not.toContain(
|
|
'--allow-build=@ladybugdb/core',
|
|
);
|
|
});
|
|
|
|
it('lets GITNEXUS_INVOCATION override the probe without consulting it', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'pnpm';
|
|
const probe = vi.fn(() => '/usr/local/bin/gitnexus');
|
|
expect(cjs.resolveInvocationMode(probe)).toBe('pnpm');
|
|
expect(probe).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('warnIfNpm11NpxRisk (#1939 npm-11 nudge)', () => {
|
|
afterEach(() => {
|
|
vi.clearAllMocks();
|
|
vi.unstubAllEnvs();
|
|
delete process.env.GITNEXUS_INVOCATION;
|
|
});
|
|
|
|
it('exposes the resolver contract the load-time guard enforces', () => {
|
|
// The module's createRequire guard throws at load if the cjs export shape
|
|
// drifts; that this module imported at all (and these hold) proves it passed.
|
|
expect(typeof NPX_REF).toBe('string');
|
|
expect(typeof getNpmMajorVersion).toBe('function');
|
|
expect(typeof warnIfNpm11NpxRisk).toBe('function');
|
|
});
|
|
|
|
it('parses the npm major version', () => {
|
|
mockedExec.mockReturnValue('11.5.2\n');
|
|
expect(getNpmMajorVersion()).toBe(11);
|
|
});
|
|
|
|
it('handles edge npm --version output (pre-release / empty / non-numeric)', () => {
|
|
mockedExec.mockReturnValue('12.0.0-pre\n');
|
|
expect(getNpmMajorVersion()).toBe(12);
|
|
mockedExec.mockReturnValue('\n');
|
|
expect(getNpmMajorVersion()).toBeNull();
|
|
mockedExec.mockReturnValue('not-a-version\n');
|
|
expect(getNpmMajorVersion()).toBeNull();
|
|
});
|
|
|
|
it('tolerates a Corepack/notice banner line before the version', () => {
|
|
mockedExec.mockReturnValue(
|
|
'Corepack is about to download https://registry.npmjs.org/npm/-/npm-11.0.0.tgz\n11.0.0\n',
|
|
);
|
|
expect(getNpmMajorVersion()).toBe(11);
|
|
});
|
|
|
|
it('passes a shell on Windows so the .cmd npm shim resolves (load-bearing for the warning)', () => {
|
|
const orig = Object.getOwnPropertyDescriptor(process, 'platform')!;
|
|
try {
|
|
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
|
mockedExec.mockReturnValue('11.0.0\n');
|
|
getNpmMajorVersion();
|
|
expect(mockedExec).toHaveBeenCalledWith(
|
|
'npm',
|
|
['--version'],
|
|
expect.objectContaining({ shell: true }),
|
|
);
|
|
} finally {
|
|
Object.defineProperty(process, 'platform', orig);
|
|
}
|
|
});
|
|
|
|
it('uses no shell on POSIX (direct PATH lookup)', () => {
|
|
const orig = Object.getOwnPropertyDescriptor(process, 'platform')!;
|
|
try {
|
|
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
|
mockedExec.mockReturnValue('11.0.0\n');
|
|
getNpmMajorVersion();
|
|
expect(mockedExec).toHaveBeenCalledWith(
|
|
'npm',
|
|
['--version'],
|
|
expect.objectContaining({ shell: false }),
|
|
);
|
|
} finally {
|
|
Object.defineProperty(process, 'platform', orig);
|
|
}
|
|
});
|
|
|
|
it('warns on the npm 11+ npx path', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'npx';
|
|
mockedExec.mockReturnValue('11.0.0\n');
|
|
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
|
warnIfNpm11NpxRisk();
|
|
expect(write).toHaveBeenCalledTimes(1);
|
|
expect(String(write.mock.calls[0]?.[0])).toContain('node.target is null');
|
|
expect(String(write.mock.calls[0]?.[0])).toContain('--allow-build=@ladybugdb/core');
|
|
expect(String(write.mock.calls[0]?.[0])).toContain(`gitnexus@latest analyze`);
|
|
write.mockRestore();
|
|
});
|
|
|
|
it.each(['11.0.0\n', '10.9.0\n', 'unreadable\n'])(
|
|
'shares one npm probe with automatic runner selection for %s',
|
|
(version) => {
|
|
vi.stubEnv('GITNEXUS_INVOCATION', '');
|
|
vi.stubEnv('PATH', '');
|
|
mockedExec.mockReturnValue(version);
|
|
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
|
try {
|
|
warnIfNpm11NpxRisk();
|
|
expect(mockedExec).toHaveBeenCalledOnce();
|
|
expect(write).toHaveBeenCalledTimes(version.startsWith('11.') ? 1 : 0);
|
|
} finally {
|
|
write.mockRestore();
|
|
}
|
|
},
|
|
);
|
|
|
|
it('does not warn when a global gitnexus or pnpm is preferred', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'pnpm';
|
|
mockedExec.mockReturnValue('11.0.0\n');
|
|
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
|
warnIfNpm11NpxRisk();
|
|
expect(write).not.toHaveBeenCalled();
|
|
expect(mockedExec).not.toHaveBeenCalled();
|
|
write.mockRestore();
|
|
});
|
|
|
|
it('does not warn when a global gitnexus is preferred', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'gitnexus';
|
|
mockedExec.mockReturnValue('11.0.0\n');
|
|
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
|
warnIfNpm11NpxRisk();
|
|
expect(write).not.toHaveBeenCalled();
|
|
write.mockRestore();
|
|
});
|
|
|
|
it('does not warn when npm is older than 11', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'npx';
|
|
mockedExec.mockReturnValue('10.9.0\n');
|
|
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
|
warnIfNpm11NpxRisk();
|
|
expect(write).not.toHaveBeenCalled();
|
|
write.mockRestore();
|
|
});
|
|
|
|
it('does not warn when npm is absent', () => {
|
|
process.env.GITNEXUS_INVOCATION = 'npx';
|
|
mockedExec.mockImplementation(() => {
|
|
throw new Error('missing');
|
|
});
|
|
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
|
warnIfNpm11NpxRisk();
|
|
expect(write).not.toHaveBeenCalled();
|
|
write.mockRestore();
|
|
});
|
|
});
|
|
|
|
describe('buildRunnerArgv (project-local runner exec, #1945)', () => {
|
|
it('passes gitnexus args straight through for the global-binary mode', () => {
|
|
expect(cjs.buildRunnerArgv('gitnexus', ['group', 'list'])).toEqual({
|
|
program: 'gitnexus',
|
|
args: ['group', 'list'],
|
|
});
|
|
});
|
|
|
|
it('prefixes the registry ref for npx mode', () => {
|
|
expect(cjs.buildRunnerArgv('npx', ['analyze'])).toEqual({
|
|
program: 'npx',
|
|
args: ['gitnexus@latest', 'analyze'],
|
|
});
|
|
});
|
|
|
|
it('builds the pre-`dlx` --allow-build invocation for pnpm mode', () => {
|
|
// Inject a pnpm version >= 10.2 so the allow-build flags are emitted without
|
|
// a live `pnpm --version` probe.
|
|
const { program, args } = cjs.buildRunnerArgv('pnpm', ['analyze'], {
|
|
pnpmMajor: 10,
|
|
pnpmMinor: 14,
|
|
});
|
|
expect(program).toBe('pnpm');
|
|
// Flags must precede `dlx` (ERR_PNPM_SPEC_NOT_SUPPORTED otherwise, #1939).
|
|
const dlxIdx = args.indexOf('dlx');
|
|
expect(dlxIdx).toBeGreaterThan(0);
|
|
expect(args.slice(0, dlxIdx)).toEqual([
|
|
'--allow-build=@ladybugdb/core',
|
|
'--allow-build=gitnexus',
|
|
'--allow-build=tree-sitter',
|
|
]);
|
|
expect(args.slice(dlxIdx)).toEqual(['dlx', 'gitnexus@latest', 'analyze']);
|
|
});
|
|
|
|
it('widens the pnpm allow-build set when --embeddings is requested', () => {
|
|
const { args } = cjs.buildRunnerArgv('pnpm', ['analyze', '--embeddings'], {
|
|
pnpmMajor: 10,
|
|
pnpmMinor: 14,
|
|
});
|
|
expect(args).toContain('--allow-build=onnxruntime-node');
|
|
});
|
|
|
|
it('widens the allow-build set for the --embeddings=N equals form too', () => {
|
|
const { args } = cjs.buildRunnerArgv('pnpm', ['analyze', '--embeddings=5000'], {
|
|
pnpmMajor: 10,
|
|
pnpmMinor: 14,
|
|
});
|
|
expect(args).toContain('--allow-build=onnxruntime-node');
|
|
});
|
|
|
|
it('omits onnxruntime-node when --embeddings is absent', () => {
|
|
const { args } = cjs.buildRunnerArgv('pnpm', ['analyze'], { pnpmMajor: 10, pnpmMinor: 14 });
|
|
expect(args).not.toContain('--allow-build=onnxruntime-node');
|
|
});
|
|
});
|
|
|
|
describe('resolveOnPath — pure-Node PATH scan (#1938, all-OS, spawn-free)', () => {
|
|
const tmpDirs: string[] = [];
|
|
const mkBinDir = (): string => {
|
|
const dir = mkdtempSync(path.join(os.tmpdir(), 'resolve-path-'));
|
|
tmpDirs.push(dir);
|
|
return dir;
|
|
};
|
|
afterEach(() => {
|
|
while (tmpDirs.length) rmSync(tmpDirs.pop() as string, { recursive: true, force: true });
|
|
});
|
|
|
|
it('finds an executable launcher on a POSIX PATH', () => {
|
|
const dir = mkBinDir();
|
|
const bin = path.join(dir, 'gitnexus');
|
|
writeFileSync(bin, '#!/bin/sh\nexit 0\n');
|
|
chmodSync(bin, 0o755);
|
|
expect(cjs.resolveOnPath('gitnexus', true, { platform: 'linux', env: { PATH: dir } })).toBe(
|
|
bin,
|
|
);
|
|
});
|
|
|
|
// X_OK is meaningless on Windows (every file reads as accessible), so this
|
|
// POSIX-only guarantee can only be asserted on a POSIX host.
|
|
it.skipIf(process.platform === 'win32')(
|
|
'skips a non-executable file on POSIX (requires X_OK)',
|
|
() => {
|
|
const dir = mkBinDir();
|
|
writeFileSync(path.join(dir, 'gitnexus'), 'not executable'); // intentionally no chmod +x
|
|
expect(
|
|
cjs.resolveOnPath('gitnexus', true, { platform: 'linux', env: { PATH: dir } }),
|
|
).toBeNull();
|
|
},
|
|
);
|
|
|
|
it('returns null when the launcher is absent or PATH is empty', () => {
|
|
const dir = mkBinDir();
|
|
expect(
|
|
cjs.resolveOnPath('gitnexus', true, { platform: 'linux', env: { PATH: dir } }),
|
|
).toBeNull();
|
|
expect(cjs.resolveOnPath('gitnexus', true, { platform: 'linux', env: {} })).toBeNull();
|
|
});
|
|
|
|
it('honors PATHEXT on Windows (a .cmd shim is detected)', () => {
|
|
const dir = mkBinDir();
|
|
const bin = path.join(dir, 'gitnexus.cmd');
|
|
writeFileSync(bin, '@echo off\r\n');
|
|
// The PATHEXT entry case matches the fixture so the assertion is deterministic
|
|
// on case-sensitive CI filesystems; real Windows is case-insensitive, so the
|
|
// casing of PATHEXT vs the on-disk shim never matters there.
|
|
expect(
|
|
cjs.resolveOnPath('gitnexus', true, {
|
|
platform: 'win32',
|
|
env: { PATH: dir, PATHEXT: '.COM;.EXE;.BAT;.cmd' },
|
|
}),
|
|
).toBe(bin);
|
|
});
|
|
|
|
it('does not treat a .ps1-only shim as on PATH when PATHEXT excludes .PS1', () => {
|
|
// A .ps1 is not launchable as `gitnexus` without a shell and is absent from
|
|
// default PATHEXT, so mirroring `where`/cmd.exe (PATHEXT-driven) avoids a hint
|
|
// that would fail when run.
|
|
const dir = mkBinDir();
|
|
writeFileSync(path.join(dir, 'gitnexus.ps1'), 'exit 0');
|
|
expect(
|
|
cjs.resolveOnPath('gitnexus', true, {
|
|
platform: 'win32',
|
|
env: { PATH: dir, PATHEXT: '.COM;.EXE;.BAT;.CMD' },
|
|
}),
|
|
).toBeNull();
|
|
});
|
|
|
|
it('on Windows ignores a bare extensionless file and returns the PATHEXT shim', () => {
|
|
// Windows matches PATHEXT extensions only — an extensionless `gitnexus` is not
|
|
// launchable as `gitnexus` from a shell, so when both exist the .cmd shim wins
|
|
// and the bare file is never the result (it would be an un-spawnable hint).
|
|
const dir = mkBinDir();
|
|
writeFileSync(path.join(dir, 'gitnexus'), 'not a shim');
|
|
const cmd = path.join(dir, 'gitnexus.cmd');
|
|
writeFileSync(cmd, '@echo off\r\n');
|
|
expect(
|
|
cjs.resolveOnPath('gitnexus', true, {
|
|
platform: 'win32',
|
|
env: { PATH: dir, PATHEXT: '.COM;.EXE;.BAT;.cmd' },
|
|
}),
|
|
).toBe(cmd);
|
|
});
|
|
|
|
it('on Windows returns null for an extensionless-only file (not in PATHEXT)', () => {
|
|
const dir = mkBinDir();
|
|
writeFileSync(path.join(dir, 'gitnexus'), 'not a shim');
|
|
expect(
|
|
cjs.resolveOnPath('gitnexus', true, {
|
|
platform: 'win32',
|
|
env: { PATH: dir, PATHEXT: '.COM;.EXE;.BAT;.CMD' },
|
|
}),
|
|
).toBeNull();
|
|
});
|
|
|
|
it('with preferExecExt, prefers a .cmd/.exe shim over an exotic .COM hit, but accepts .COM alone', () => {
|
|
// preferExecExt mirrors the old `where` wrapper preference: a recognized
|
|
// .cmd/.bat/.exe wins over a .COM, yet a lone .COM is still detected (better a
|
|
// resolvable hint than none). Fixture/PATHEXT cases match for CI determinism.
|
|
const both = mkBinDir();
|
|
writeFileSync(path.join(both, 'gitnexus.com'), 'x');
|
|
const cmd = path.join(both, 'gitnexus.cmd');
|
|
writeFileSync(cmd, '@echo off\r\n');
|
|
expect(
|
|
cjs.resolveOnPath('gitnexus', true, {
|
|
platform: 'win32',
|
|
env: { PATH: both, PATHEXT: '.com;.cmd' },
|
|
}),
|
|
).toBe(cmd);
|
|
|
|
const comOnly = mkBinDir();
|
|
const com = path.join(comOnly, 'gitnexus.com');
|
|
writeFileSync(com, 'x');
|
|
expect(
|
|
cjs.resolveOnPath('gitnexus', true, {
|
|
platform: 'win32',
|
|
env: { PATH: comOnly, PATHEXT: '.com;.cmd' },
|
|
}),
|
|
).toBe(com);
|
|
});
|
|
});
|
|
|
|
describe('formatAnalyzeCommand end-to-end via the pure scan (#1938)', () => {
|
|
// Real probes and runner execution, with every tool controlled by the fixture.
|
|
// Do not append the host PATH: npm 10 or a global gitnexus would win selection.
|
|
const { spawnSync } = cjsRequire('node:child_process') as typeof import('node:child_process');
|
|
const isWin = process.platform === 'win32';
|
|
let binDir: string;
|
|
beforeEach(() => {
|
|
binDir = mkdtempSync(path.join(os.tmpdir(), 'gn-runner-probe-'));
|
|
vi.stubEnv('PATH', binDir);
|
|
if (!isWin) {
|
|
vi.stubEnv('Path', '');
|
|
vi.stubEnv('path', '');
|
|
}
|
|
vi.stubEnv('PATHEXT', '.COM;.EXE;.BAT;.CMD');
|
|
vi.stubEnv('GITNEXUS_INVOCATION', undefined);
|
|
});
|
|
afterEach(() => {
|
|
vi.unstubAllEnvs();
|
|
rmSync(binDir, { recursive: true, force: true });
|
|
});
|
|
|
|
function writeTool(name: string, version: string, versionExit = 0): void {
|
|
const launcher = path.join(binDir, isWin ? `${name}.cmd` : name);
|
|
writeFileSync(
|
|
launcher,
|
|
isWin
|
|
? `@echo off\r\nif "%~1"=="--version" (\r\n echo ${version}\r\n exit /b ${versionExit}\r\n)\r\necho ${name} %*\r\nexit /b 23\r\n`
|
|
: `#!/bin/sh\nif [ "$1" = "--version" ]; then\n echo '${version}'\n exit ${versionExit}\nfi\necho "${name} $@"\nexit 23\n`,
|
|
);
|
|
if (!isWin) chmodSync(launcher, 0o755);
|
|
}
|
|
|
|
function expectRunner(program: string, prefix = cjs.NPX_REF): void {
|
|
const result = spawnSync(process.execPath, [CANONICAL_CJS, 'analyze', '--index-only'], {
|
|
env: process.env,
|
|
cwd: binDir,
|
|
encoding: 'utf-8',
|
|
timeout: 15000,
|
|
});
|
|
expect(result.error).toBeUndefined();
|
|
expect(result.status).toBe(23);
|
|
expect(result.stdout.trim()).toBe(`${program} ${prefix} analyze --index-only`);
|
|
}
|
|
|
|
it('resolves `gitnexus analyze` when a launcher is the only thing on PATH', () => {
|
|
writeTool('gitnexus', '1.6.12');
|
|
expect(cjs.formatAnalyzeCommand()).toBe('gitnexus analyze');
|
|
});
|
|
|
|
it.each([11, null])(
|
|
'falls through to bunx when pnpm fails and npm major is %s (#3717)',
|
|
(npmMajor) => {
|
|
if (npmMajor !== null) writeTool('npm', `${npmMajor}.0.0`);
|
|
writeTool('pnpm', 'pnpm is not installed for this Node.js version', 1);
|
|
writeTool('bunx', '1.2.0');
|
|
expect(cjs.formatAnalyzeCommand()).toBe(`bunx ${cjs.NPX_REF} analyze`);
|
|
expect(cjs.resolveInvocationMode()).toBe('bun');
|
|
expectRunner('bunx');
|
|
},
|
|
);
|
|
|
|
it.each([11, null])(
|
|
'falls through to npx when pnpm fails, bunx is absent, and npm major is %s',
|
|
(npmMajor) => {
|
|
if (npmMajor !== null) writeTool('npm', `${npmMajor}.0.0`);
|
|
writeTool('pnpm', 'pnpm is not installed for this Node.js version', 1);
|
|
writeTool('npx', '11.0.0');
|
|
expect(cjs.formatAnalyzeCommand()).toBe(`npx ${cjs.NPX_REF} analyze`);
|
|
expect(cjs.resolveInvocationMode()).toBe('npx');
|
|
expectRunner('npx');
|
|
},
|
|
);
|
|
|
|
it.each(['10.2.0', 'Notice: pnpm is active'])(
|
|
'keeps pnpm when a successful probe prints %s (#3717)',
|
|
(version) => {
|
|
writeTool('npm', '11.0.0');
|
|
writeTool('pnpm', version);
|
|
const prefix = `--allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter dlx ${cjs.NPX_REF}`;
|
|
expect(cjs.formatAnalyzeCommand()).toBe(`pnpm ${prefix} analyze`);
|
|
expect(cjs.resolveInvocationMode()).toBe('pnpm');
|
|
expectRunner('pnpm', prefix);
|
|
},
|
|
);
|
|
|
|
it('preserves the npx preference on npm 10 with a broken pnpm and working bunx', () => {
|
|
writeTool('npm', '10.9.0');
|
|
writeTool('pnpm', 'pnpm is not installed for this Node.js version', 1);
|
|
writeTool('bunx', '1.2.0');
|
|
writeTool('npx', '10.9.0');
|
|
expect(cjs.formatAnalyzeCommand()).toBe(`npx ${cjs.NPX_REF} analyze`);
|
|
expect(cjs.resolveInvocationMode()).toBe('npx');
|
|
expectRunner('npx');
|
|
});
|
|
});
|
|
|
|
describe('resolve-analyze-cmd.cjs parity', () => {
|
|
it('keeps the two CJS hook copies byte-identical', () => {
|
|
expect(readFileSync(CANONICAL_CJS, 'utf-8')).toBe(readFileSync(PLUGIN_CJS, 'utf-8'));
|
|
});
|
|
});
|
|
|
|
describe('CLI module-load posture (R3/R4 regression guard)', () => {
|
|
const cliDir = path.resolve(__dirname, '..', '..', 'src', 'cli');
|
|
|
|
it('does not probe invocation hints at index.ts module load (#207/#1383)', () => {
|
|
const indexSrc = readFileSync(path.join(cliDir, 'index.ts'), 'utf-8');
|
|
// Every command — including the `gitnexus mcp` stdio server — pays index.ts
|
|
// module load. warnIfNpm11NpxRisk()/PATH probing must stay out of module
|
|
// scope, or it reintroduces the startup-spawn regression (#207, #1383).
|
|
expect(indexSrc).not.toMatch(/warnIfNpm11NpxRisk/);
|
|
expect(indexSrc).not.toMatch(/resolve-invocation/);
|
|
});
|
|
|
|
it('wires the npm-11 warning into the analyze command instead', () => {
|
|
const analyzeSrc = readFileSync(path.join(cliDir, 'analyze.ts'), 'utf-8');
|
|
expect(analyzeSrc).toMatch(/warnIfNpm11NpxRisk\(\)/);
|
|
});
|
|
});
|