mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-10-06 02:49:56 +00:00
Some checks failed
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
Skill copy sync / shipped skills drift guard (push) Has been cancelled
* feat(cli): add a bunx lane to the runner ladder
The ladder assumed a Node toolchain: global gitnexus, then pnpm dlx or
npx in some order, with npx as the last resort. On a bun-only machine
npm, npx and pnpm are all absent, so every rung fell through to npx and
both the emitted hint and the generated .gitnexus/run.cjs produced a
command the machine could not run at all.
Add bun as a fourth mode, invoked as an install-free bunx one-shot, on
two rungs:
- npm 11+ with no pnpm to fall back on — bunx dodges the same arborist
install crash the pnpm rung exists for (#1939);
- npm and pnpm both absent — previously the dead end described above.
Every pre-existing outcome is preserved: pnpm still wins on npm 11+, npx
still wins on npm < 11, and pnpm still wins over bunx when npm is absent.
Regression tests pin each of those. The bun PATH probe is lazy, so a
machine with a Node toolchain pays no extra scan and the stale-index hook
budget is unchanged.
bunx takes no allow-build equivalent: bun's --trust is a bun add/install
flag that writes trustedDependencies into a project package.json, which a
one-shot has none of, so the argv stays flag-free.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016R9psS9gJ73MRyquoBoPKg
* fix(lbug): restore the prebuilt native binary when install scripts were skipped
Without this the new bunx lane resolves to a command that still fails:
bun skips lifecycle scripts for a bunx fetch, so @ladybugdb/core's
install script never copies lbugjs.node up from its per-platform
sub-package and every native command dead-ends on 'LadybugDB native
binary (lbugjs.node) is missing'.
The existing guidance cannot rescue that case. It offers pnpm
--allow-build, a global install, or adding trustedDependencies to a
project package.json — bunx has no project package.json to add to, no
per-invocation opt-in, and re-extracts the package on every run, so an
out-of-band repair is wiped before the next invocation. In-process
recovery is the only thing that can work.
Recovery is cheap because nothing is actually absent: the binary is
already on disk in @ladybugdb/core-<platform>-<arch>, and the skipped
script only copied it up. Redo that copy (prebuilt only — never a source
build, never a network fetch) before reporting failure. Best-effort by
construction: read-only node_modules, an absent sub-package or an
unsupported platform all fall through to the existing diagnostics
unchanged, which a test pins.
Also covers pnpm dlx without --allow-build and npm --ignore-scripts.
Declare trustedDependencies so a plain `bun install` in this repo
produces a working native binary too — the remedy the error message
already prescribes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016R9psS9gJ73MRyquoBoPKg
* fix(ai-context): name every install-free runner in the generated bootstrap note
The emitted gitnexus:start block told a reader with no runner yet to run
`npx gitnexus analyze`, falling back to a global npm install. Both name
binaries a bun-only machine does not have, so the generated AGENTS.md and
CLAUDE.md offered it no reachable bootstrap path.
List npx, bunx and pnpm dlx instead of resolving one. The block is
committed, so emitting the command this machine happens to resolve would
make two contributors on different package managers rewrite it at each
other on every analyze — the per-machine churn #1706 removed. Naming all
three keeps the note machine-independent and correct everywhere.
Regenerates this repo's own committed block to match.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016R9psS9gJ73MRyquoBoPKg
* fix(cli): address PR #2765 review — bunx liveness, restore diagnostics, docs
Addresses all five review comments on #2765.
P1 — `hasBun()` was a PATH-existence check only, so a present-but-broken
`bunx` shim (partial uninstall, failed `bun upgrade`) was selected with no
functional validation. Because selecting `bun` also suppresses the npm-11
npx-crash warning, the result was a silent dead end: no diagnostic, and a
`bunx gitnexus@latest analyze` command that only fails at execution time.
Add `probeRuns()` — a real `bunx --version` liveness probe, gated behind the
cheap spawn-free PATH scan so machines with npm/pnpm still pay nothing. It
ignores the output on purpose (a banner or unparseable version still counts
as alive); only a spawn failure, non-zero exit, or timeout rejects. Injectable
via a new `bunRuns` dep so the mode tests stay host-independent.
P2 — the `gitnexus-cli` skill (and both shipped mirrors) still described the
pre-bunx ladder, stranding exactly this PR's audience: a bun-only machine
whose agent bootstraps from that file was told to use npx/npm/pnpm, none of
which exist there. All three copies now name `bunx` in the ladder and the
bootstrap fallback, with a `shipped-skills-sync` fragment assertion so the
gap is CI-caught (these copies are not byte-compared, only the engineering
family is).
P2 — `restorePrebuiltNativeBinary` collapsed every failure into `false`, so an
EACCES/EROFS from `copyFileSync` was indistinguishable from "no prebuilt
sub-package exists". Users on a read-only `node_modules` layer (a baked
container image mounted read-only — a common CI pattern) got the generic
lifecycle-script advice, which cannot fix a non-writable filesystem. Return a
`RestoreOutcome` instead and route `copy-failed` to its own message.
P2 — document that `trustedDependencies` only takes effect for `bun install` /
`pnpm install` run inside this repo: it does nothing for a `bunx` one-shot or
for a consumer's `bun add gitnexus`. The note sits on
`restorePrebuiltNativeBinary` so a future maintainer cannot mistake that
function for redundant and delete the thing the bunx path actually relies on.
P3 — the `binary_missing` bun advice told `bunx` one-shot users to edit a
package.json they do not have, and listed 1 of the 3 packages this package
now trusts. Both repair messages now share one `BUN_REPAIR_LINES` const with
the full package list and a `bun install -g gitnexus` alternative.
Also: shortened the bootstrap note and raised the CLAUDE.md block budget
2900 -> 2950. The note has to name every install-free runner (that is the
point of the bun lane), and main's own growth since this PR's last green CI
had already pushed the generated block over the old ceiling.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015epfxkEMsmHFNVSFQqAkB4
* refactor(cli): simplify the #2765 review fixes
Cleanup pass over the previous commit — no intended behavior change except
the doctor status line noted below.
Reuse: `probeRuns()` duplicated `probeVersion()`'s entire spawn setup — same
argv, timeout, `windowsHide`, and the CVE-2024-27980 Windows-shim workaround —
in a file with two byte-identical committed copies, so the shim rule lived at
four sites. Its docstring's own objection was to the RETURN SHAPE, not to
reuse, so `probeVersion` now returns `{ ran, major, minor }` and `hasBun` reads
`.ran`. Existing callers only read `major`/`minor`, so nothing else changes.
Also dropped a pointless `const runs = () => …` thunk (`&&` already
short-circuits), and deleted a new test that was a character-for-character
duplicate of `falls back to npx when npm is null-absent and pnpm is also
absent` — its cheapest-first-gate rationale moved into that test's comment.
Correctness in the budget comment: the claim that the bun rung is free because
"pnpm is absent there, so its probe never ran" was wrong. `formatAnalyzeCommand`
spawns `pnpm --version` unconditionally when no global `gitnexus` is on PATH —
that spawn IS how pnpm presence is discovered. Real worst case is 5 subprocesses
/ ~8s, and the 8s needs Windows (`shell: true` spawns cmd.exe for an absent
pnpm); on POSIX an absent pnpm ENOENTs in ~1ms. Comment now says that. Likewise
"a machine with npm or pnpm never pays" was wrong for npm 11+ without pnpm —
that IS the rung that pays.
Altitude: `copy-failed` changed only the message text while still returning
`kind: 'binary_missing'`, so `doctor` would have printed "✗ lbugjs.node missing"
directly above a message saying the binary IS present — exactly the
contradiction #2672 removed. Added a `binary_unwritable` kind, a doctor case,
and a `nativeStatusCases` row. The binary-missing message construction moved
out of `checkLbugNative` into `unrestorableBinaryFailure`, typed
`Exclude<RestoreOutcome, 'restored'>` so a new outcome forces a decision
instead of silently inheriting the lifecycle-script advice.
Drift: the trusted-package list was hand-spelled in five places in
native-check.ts, with "matches gitnexus/package.json" asserted only in a
comment. All five now render from one `NATIVE_BUILD_PACKAGES` const (rendered
output is byte-identical), and the test reads the list out of package.json
instead of restating it, so a fourth native package fails the test rather than
silently shipping stale advice.
Finally, replaced the absolute CLAUDE.md block cap with the ratio the two prior
justifications actually appealed to (`< 5465 * 0.55`). Raising 2700 -> 2900 ->
2950 was a ratchet with no ratchet: an absolute cap can only fail on the PR
that adds the character, and the fix is always to nudge the number. Also fixed
a stale runner ladder in skills-steering.test.ts that still omitted bunx.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015epfxkEMsmHFNVSFQqAkB4
---------
Co-authored-by: drdave-flexnteos <revenaugh.david@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
648 lines
26 KiB
TypeScript
648 lines
26 KiB
TypeScript
import { afterEach, 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 },
|
|
deps?: { npmMajor?: number | null; pnpmMajor?: number | null; pnpmMinor?: number | null },
|
|
) => 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;
|
|
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 bunx PATH hit MUST also inject
|
|
// `bunRuns`, or the liveness probe spawns the host's real bunx and the result
|
|
// depends on whether bun 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)', () => {
|
|
afterEach(() => {
|
|
delete process.env.GITNEXUS_INVOCATION;
|
|
});
|
|
|
|
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('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 })).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 })).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 (timeout / Corepack banner) but pnpm is on PATH, 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, 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, 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('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 })).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();
|
|
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('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();
|
|
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)', () => {
|
|
// Exercises the public entry through resolveOnPath against a real PATH (no
|
|
// mocks, no GITNEXUS_INVOCATION): with a launcher on PATH the hint resolves to
|
|
// `gitnexus analyze`. Because resolveOnPath is now spawn-free, this works
|
|
// identically on every OS — there is no `where`/`which` reachability caveat.
|
|
const savedPath = process.env.PATH;
|
|
let binDir: string | undefined;
|
|
afterEach(() => {
|
|
if (savedPath === undefined) delete process.env.PATH;
|
|
else process.env.PATH = savedPath;
|
|
if (binDir) rmSync(binDir, { recursive: true, force: true });
|
|
binDir = undefined;
|
|
delete process.env.GITNEXUS_INVOCATION;
|
|
});
|
|
|
|
it('resolves `gitnexus analyze` when a launcher is the only thing on PATH', () => {
|
|
binDir = mkdtempSync(path.join(os.tmpdir(), 'gn-e2e-'));
|
|
const isWin = process.platform === 'win32';
|
|
const launcher = path.join(binDir, isWin ? 'gitnexus.cmd' : 'gitnexus');
|
|
writeFileSync(launcher, isWin ? '@echo off\r\nexit /b 0\r\n' : '#!/bin/sh\nexit 0\n');
|
|
if (!isWin) chmodSync(launcher, 0o755);
|
|
// PATH reduced to just the launcher dir — the former `where`/`which` resolver
|
|
// would have ENOENT'd here; the pure scan finds the launcher directly.
|
|
process.env.PATH = binDir;
|
|
expect(cjs.formatAnalyzeCommand()).toBe('gitnexus analyze');
|
|
});
|
|
});
|
|
|
|
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\(\)/);
|
|
});
|
|
});
|