Merge branch 'main' into dependabot/uv/eval/uv-6e0d158e28

This commit is contained in:
Gergő Magyar 2026-10-26 08:03:23 +00:00 • committed by GitHub
commit a3336cfd76
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
75 changed files with 3862 additions and 353 deletions

View file

@ -0,0 +1,66 @@
name: Upload test artifact
description: Upload required CI evidence with bounded transport retries
inputs:
name:
description: Unique artifact name for this job
required: true
path:
description: Files to upload
required: true
retention-days:
description: Artifact retention in days
default: '5'
include-hidden-files:
description: Include explicitly selected hidden report directories
default: 'false'
runs:
using: composite
steps:
- name: Upload
id: first
if: ${{ always() }}
continue-on-error: true
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
retention-days: ${{ inputs.retention-days }}
include-hidden-files: ${{ inputs.include-hidden-files }}
if-no-files-found: error
- name: Wait before retry
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
shell: bash
run: sleep 10
- name: Retry upload
id: second
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
continue-on-error: true
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
retention-days: ${{ inputs.retention-days }}
include-hidden-files: ${{ inputs.include-hidden-files }}
if-no-files-found: error
# A failed request may already have created an incomplete artifact.
overwrite: true
- name: Wait before final attempt
if: ${{ !cancelled() && steps.second.outcome == 'failure' }}
shell: bash
run: sleep 30
- name: Final upload attempt
if: ${{ !cancelled() && steps.second.outcome == 'failure' }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
retention-days: ${{ inputs.retention-days }}
include-hidden-files: ${{ inputs.include-hidden-files }}
if-no-files-found: error
overwrite: true

View file

@ -29,13 +29,12 @@ jobs:
fi
- name: Upload release accuracy evidence
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: release-tool-accuracy
path: |
${{ runner.temp }}/tool-accuracy/accuracy.json
${{ runner.temp }}/tool-accuracy/accuracy.md
if-no-files-found: error
retention-days: 30
# Ubuntu full-suite coverage, sharded. Each shard writes a vitest blob report
@ -108,7 +107,7 @@ jobs:
working-directory: gitnexus
- name: Upload coverage blob
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: coverage-blob-${{ matrix.shard }}
path: gitnexus/.vitest/blob/
@ -171,7 +170,7 @@ jobs:
run: node --test docker-server.test.mjs
- name: Upload test reports
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: coverage-reports
path: |
@ -195,9 +194,9 @@ jobs:
steps:
- id: gen
run: |
# Refreshed Windows timings leave eight shards too close to the
# 20-minute watchdog. Ten preserve headroom for runner variation.
TOTAL=10 # cross-platform (windows/macOS) shards per OS
# Keep the recorded native workload below 17 minutes, leaving
# headroom for runner variation under the 20-minute watchdog.
TOTAL=11 # cross-platform (windows/macOS) shards per OS
# Four coverage shards exceeded the 25-minute job limit while tests
# were still passing. Split the full suite further; keep the timeout
# and merged coverage thresholds unchanged.
@ -297,11 +296,10 @@ jobs:
working-directory: gitnexus
- name: Upload platform execution report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: execution-${{ matrix.os }}-${{ matrix.shard }}
path: gitnexus/${{ matrix.os }}-${{ matrix.shard }}.json
if-no-files-found: error
retention-days: 5
# Branch protection still requires these six names from the three-shard
@ -388,11 +386,12 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest, ubuntu-24.04-arm]
os: [windows-latest, macos-latest, ubuntu-latest, ubuntu-24.04-arm]
runs-on: ${{ matrix.os }}
# Windows pack + web install regularly exceeds 15 minutes when setup also
# runs prepare/postinstall/build before prepack compiles the same tree again.
timeout-minutes: 20
# Also exercise fresh npm, pnpm, and Bun installs on the three desktop OSes.
timeout-minutes: 30
steps:
# persist-credentials: false — this job runs npm pack + npm install -g
# from a tarball and never pushes back; the token in .git/config would
@ -433,6 +432,14 @@ jobs:
run: npm pack
working-directory: gitnexus
- name: Index the PR tarball with npm, pnpm, and Bun
if: matrix.os != 'ubuntu-24.04-arm'
shell: bash
run: |
npm install --global pnpm@12.10.1 bun@1.3.14 --no-audit --no-fund
node scripts/smoke-package-managers.mjs
working-directory: gitnexus
# Block native compilation only in the consumer phase. A correct bundle
# must install using prebuilds even when the runner has a toolchain.
- name: Reject ARM64 consumer compilation
@ -1103,11 +1110,10 @@ jobs:
working-directory: gitnexus
- name: Upload benchmark execution report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: execution-benchmarks
path: gitnexus/benchmarks.json
if-no-files-found: error
retention-days: 5
# Fresh-process measurements have their own runner and time budget so they
@ -1130,11 +1136,10 @@ jobs:
working-directory: gitnexus
- name: Upload scope-resolution measurements
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: scope-resolution-benchmark
path: gitnexus/scope-resolution-benchmark.json
if-no-files-found: error
retention-days: 5
# Locked eval suite. setup-uv and uv itself are immutable so CI exercises
@ -1158,11 +1163,10 @@ jobs:
working-directory: eval
- name: Upload pytest execution report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: execution-pytest-locked
path: eval/pytest-locked.xml
if-no-files-found: error
retention-days: 5
- uses: ./.github/actions/setup-gitnexus
with:
@ -1175,11 +1179,10 @@ jobs:
working-directory: gitnexus
- name: Upload preflight execution report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: execution-preflight
path: gitnexus/preflight.json
if-no-files-found: error
retention-days: 5
test-completeness:
@ -1225,7 +1228,7 @@ jobs:
run: python3 eval/check_test_execution.py execution-reports eval/pytest-results.json
- name: Upload complete test reports
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: test-reports
path: |
@ -1234,7 +1237,6 @@ jobs:
gitnexus/test-results.json
gitnexus-web/web-test-results.json
eval/pytest-results.json
if-no-files-found: error
retention-days: 5
# Native Linux ownership and Bubblewrap boundary. The environment flag makes
@ -1336,11 +1338,10 @@ jobs:
working-directory: eval
- name: Upload pytest execution report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: execution-pytest-ubuntu
path: eval/pytest-ubuntu.xml
if-no-files-found: error
retention-days: 5
# Native Windows Job Object canary. POSIX-only tests skip by platform, while
@ -1367,9 +1368,8 @@ jobs:
working-directory: eval
- name: Upload pytest execution report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: ./.github/actions/upload-test-artifact
with:
name: execution-pytest-windows
path: eval/pytest-windows.xml
if-no-files-found: error
retention-days: 5

View file

@ -228,6 +228,13 @@ passes a route's URL to a callee not proven to be a wrapper is counted on the
Route as `unverifiedConsumers` (proven consumers and the route's own file
excluded), and `api_impact` then reports its consumer count as a lower bound.
A `FETCHES` edge is file-level. Its reason also names the callables whose spans
contain the request sites (`|via:<id>`, under the same containment rule as the
R3-6 sink set). `api_impact` follows their `CALLS` edges one level up and lists
those callers as `indirectConsumers`, apart from the direct count and outside
the risk level: they never mention the URL, so no edge of their own could reach
the route. An index built before this attribution carries no such list.
An inline Express handler resolves to the anonymous Function node the capture
layer names by position, so its Route carries a `handlerSymbolId`. In a file
with several routes, response keys come from that handler's lines rather than

View file

@ -352,6 +352,62 @@ def test_platform_ci_preserves_required_check_names_with_complete_execution_gate
}
def test_test_artifact_retries_cannot_hide_missing_evidence(ci_test_jobs):
repo_root = Path(__file__).resolve().parents[2]
action_path = ".github/actions/upload-test-artifact/action.yml"
action = yaml.safe_load((repo_root / action_path).read_text())
uploads = [step for step in action["runs"]["steps"] if "uses" in step]
assert len(uploads) == 3
first, second, final = uploads
assert first["if"] == "${{ always() }}"
assert second["if"] == "${{ !cancelled() && steps.first.outcome == 'failure' }}"
assert final["if"] == "${{ !cancelled() && steps.second.outcome == 'failure' }}"
assert first["id"] == "first" and second["id"] == "second"
assert first["continue-on-error"] is True
assert second["continue-on-error"] is True
assert not final.get("continue-on-error", False)
assert not first["with"].get("overwrite", False)
assert second["with"]["overwrite"] is True
assert final["with"]["overwrite"] is True
for step in uploads:
assert re.fullmatch(r"actions/upload-artifact@[a-f0-9]{40}", step["uses"])
assert step["with"]["if-no-files-found"] == "error"
for key in ("name", "path", "retention-days", "include-hidden-files"):
assert step["with"][key] == "${{ inputs." + key + " }}"
evidence_jobs = {
"tests", "coverage-merge", "cross-platform", "benchmarks",
"scope-resolution-benchmark", "eval-tests", "test-completeness",
"eval-containment-windows", "eval-containment-linux", "tool-accuracy",
}
for name in evidence_jobs:
job = ci_test_jobs[name]
reports = [
step for step in job["steps"]
if step.get("uses") == "./.github/actions/upload-test-artifact"
]
assert reports, f"{name} must publish execution evidence"
assert not job.get("continue-on-error", False)
for step in reports:
assert not step.get("continue-on-error", False)
assert step["with"]["name"] and step["with"]["path"]
artifact_names = set()
for job in ci_test_jobs.values():
for step in job.get("steps", []):
assert not step.get("uses", "").startswith("actions/upload-artifact@")
if step.get("uses") != "./.github/actions/upload-test-artifact":
continue
name = step["with"]["name"]
assert name not in artifact_names, f"Retry could overwrite another job: {name}"
artifact_names.add(name)
for axis in job.get("strategy", {}).get("matrix", {}):
if axis not in {"include", "exclude"}:
assert "${{ matrix." + axis + " }}" in name, (
f"Artifact {name} must distinguish matrix axis {axis}"
)
@pytest.mark.parametrize("native_result", ["success", "failure", "cancelled", "skipped", ""])
@pytest.mark.parametrize("execution_result", ["success", "failure", "cancelled", "skipped", ""])
@pytest.mark.parametrize("scope_bench_result", ["success", "failure", "cancelled", "skipped", ""])

View file

@ -1298,6 +1298,53 @@ def test_overflowed_parent_capture_is_ineligible_evidence(monkeypatch, tmp_path)
assert "exceeds" in rec["error_detail"]["event_stream_error"]
@pytest.mark.parametrize("overflow", [False, True], ids=["complete-12MiB-stream", "bounded-overflow"])
def test_large_session_stream_preserves_usage_and_redacted_evidence(monkeypatch, tmp_path, overflow):
# Run a real child through the supervisor: a mocked completed capture misses
# the 8 MiB truncation that invalidated release evaluation 40181565589.
if overflow:
monkeypatch.setattr(runner_sessions, "MAX_TRANSCRIPT_BYTES", 64 * 1024)
secret = "large-stream-test-secret"
child = tmp_path / "large_session.py"
child.write_text(
"import json\n"
f"content = 'x' * (768 * 1024) + {secret!r}\n"
"for i in range(16):\n"
" print(json.dumps({'type': 'user', 'message': {'content': [\n"
" {'type': 'tool_result', 'tool_use_id': f'read-{i}', 'content': content}]}}))\n"
f"print({VALID_REPORT!r})\n"
)
record = runner_sessions.run_claude(
"task", tmp_path, claude_bin="unused", command_prefix=[sys.executable, str(child)],
timeout=30, transcript_output_dir=tmp_path, transcript_secrets=(secret,),
)
if overflow:
assert record["ok"] is False
assert record["error_kind"] == "session-error"
assert record["transcript_missing"] is True
assert record["cost_usd"] is None
assert "exceeds" in record["error_detail"]["event_stream_error"]
assert not (tmp_path / "transcripts").exists()
return
assert record["ok"] is True, record["error_detail"]
assert record["transcript_missing"] is False
assert record["cost_usd"] == 0.1
assert {field: record[field] for field in runner_sessions.USAGE_FIELDS} == json.loads(VALID_REPORT)["usage"]
artifact = record["transcript_artifact"]
payload = (tmp_path / artifact["path"]).read_bytes()
assert artifact["bytes"] == len(payload) > 8 * 1024 * 1024
assert artifact["sha256"] == hashlib.sha256(payload).hexdigest()
assert secret.encode() not in payload
assert payload.count(b"[REDACTED]") == 16
assert json.loads(payload.splitlines()[-1]) == json.loads(VALID_REPORT)
# The same limit must admit the persisted evidence for evolution and reuse.
from workflow_bench import comparator_reuse
assert evolve._transcript_artifact_metadata(artifact)[2] == len(payload)
assert comparator_reuse._transcript_metadata(artifact)[2] == len(payload)
def test_final_result_event_must_be_last(monkeypatch, tmp_path):
stream = VALID_REPORT + "\n" + json.dumps({"type": "assistant", "message": {"content": []}}) + "\n"
monkeypatch.setattr(runner_sessions, "run_managed", lambda *a, **k: fake_cli_result(stream))

View file

@ -36,7 +36,10 @@ USAGE_FIELDS = (
"cache_read_input_tokens",
"output_tokens",
)
MAX_TRANSCRIPT_BYTES = 8 * 1024 * 1024
# A successful 142-turn release session exceeded 8 MiB (#3500, run
# 40181565589). Keep capture, redacted artifacts, and reuse bounded together,
# with headroom for verbose tool results in the three concurrent paid cells.
MAX_TRANSCRIPT_BYTES = 64 * 1024 * 1024
# Wall-clock ceiling for one headless session, shared by the runner and the
# evolution loop so both CLIs kill a session at the same point. 3600s was too
# tight for the `workflow` arm: run 29907431284 lost two investigation-task

View file

@ -16,8 +16,9 @@
* resolved to `npx` and the emitted command could not run at all. `bunx` is
* bun's install-free one-shot runner and needs no allow-build equivalent — bun
* skips lifecycle scripts unconditionally for a `bunx` fetch, which the native
* loader recovers from directly (see core/lbug/native-check.ts). Both bun rungs
* gate on `bunx` actually running, not merely existing on PATH — see `hasBun`.
* loader recovers from directly (see core/lbug/native-check.ts). Both pnpm and
* bun rungs gate on the tool actually running, not merely existing on PATH —
* see `hasPnpm` (#3717) and `hasBun`.
*
* The `--allow-build` flags MUST precede the `dlx` token. pnpm < 10.14 keeps
* `dlx` in its argv escape list, so flags placed *after* `dlx` are parsed as
@ -126,10 +127,10 @@ function resolveOnPath(
// `ran` is liveness, kept separate from the version because a PATH hit proves a
// file exists, not that it works, and the two answers differ: a banner-printing
// or oddly-versioned tool is alive with `major: null`, while a stale shim left by
// a partial uninstall is neither. Only the bun rung consults `ran` today (see
// hasBun) — it is the one runner with no version to read, so a dedicated probe is
// its only liveness signal; pnpm gets the same evidence for free from the version
// spawn it must make anyway, and deliberately forgives an unreadable one (#1939).
// a partial uninstall (or an unconfigured NVM shim) is neither. Both pnpm and
// bun consult `ran` (see hasPnpm, hasBun) — pnpm gets the evidence for free
// from the version spawn it must make anyway, deliberately forgiving an
// unreadable version when the process actually ran (#1939, #3717).
function probeVersion(command) {
try {
const output = execFileSync(command, ['--version'], {
@ -214,18 +215,34 @@ function resolveInvocationMode(probe = resolveOnPath, deps = {}) {
if (probe('gitnexus', true)) return 'gitnexus';
const npmMajor = getNpmMajorVersion(deps);
// pnpm presence: prefer an explicit `pnpmPresent` flag (set by
// formatAnalyzeCommand, which falls back to a PATH probe when the version is
// unreadable) so a present-but-unparseable pnpm — slow probe, Corepack
// banner — still selects pnpm instead of the npx crash path. Otherwise an
// injected version (a successful `pnpm --version` proves presence)
// short-circuits the `which pnpm` probe; failing both, fall back to PATH.
const hasPnpm =
'pnpmPresent' in deps
? deps.pnpmPresent
: 'pnpmMajor' in deps
? deps.pnpmMajor !== null
: Boolean(probe('pnpm'));
// pnpm usability is resolved lazily, mirroring bun: prefer an explicit
// `pnpmPresent` flag (set by formatAnalyzeCommand, which captures whether
// `pnpm --version` actually ran) so a present-but-unparseable pnpm (Corepack
// banner) still selects pnpm instead of the npx crash path, while an
// unusable shim (e.g. NVM for Windows: non-zero exit) is rejected (#3717).
// Otherwise an injected version/presence short-circuits the spawn; failing
// both, check PATH presence then liveness (`pnpm --version`).
let pnpmCache;
const hasPnpm = () => {
if (pnpmCache === undefined) {
if ('pnpmPresent' in deps) {
pnpmCache =
Boolean(deps.pnpmPresent) && ('pnpmRuns' in deps ? Boolean(deps.pnpmRuns) : true);
} else if ('pnpmRuns' in deps && !deps.pnpmRuns) {
pnpmCache = false;
} else if ('pnpmMajor' in deps && deps.pnpmMajor !== null) {
pnpmCache = true;
} else if ('pnpmRuns' in deps && deps.pnpmRuns) {
pnpmCache = Boolean(probe('pnpm'));
} else if ('pnpmMajor' in deps && deps.pnpmMajor === null) {
pnpmCache = false;
} else {
const present = Boolean(probe('pnpm'));
pnpmCache = present && probeVersion('pnpm').ran;
}
}
return pnpmCache;
};
// bun usability is resolved lazily: only the two branches below can select it,
// so a machine with pnpm, or with npm < 11, never pays the PATH scan or the
@ -243,13 +260,13 @@ function resolveInvocationMode(probe = resolveOnPath, deps = {}) {
};
// npm 11+ npx install crash (#1939) — prefer pnpm dlx when available.
if (hasPnpm && npmMajor !== null && npmMajor >= 11) return 'pnpm';
if (npmMajor !== null && npmMajor >= 11 && hasPnpm()) return 'pnpm';
// Same crash, no pnpm to fall back on: bunx is install-free and unaffected.
if (npmMajor !== null && npmMajor >= 11 && hasBun()) return 'bun';
// npm 10 and earlier: npx works; prefer it over pnpm dlx when npm is present.
if (npmMajor !== null && npmMajor < 11) return 'npx';
// npm absent or unreadable — use pnpm if present (with allow-build flags).
if (hasPnpm) return 'pnpm';
if (hasPnpm()) return 'pnpm';
// Neither npm nor pnpm — bunx is the only install-free runner left. Without
// this rung a bun-only machine fell through to `npx`, which is not installed
// there, so the emitted command failed with "npx: command not found".
@ -304,12 +321,23 @@ function formatAnalyzeCommand(options = {}, deps = {}) {
const mightUsePnpm =
forced === 'pnpm' || (forced !== 'gitnexus' && forced !== 'npx' && forced !== 'bun');
if (mightUsePnpm && (forced === 'pnpm' || !probe('gitnexus', true))) {
const { major, minor } = probeVersion('pnpm');
// Carry presence separately from version: when the version probe fails
// (timeout, Corepack banner) but pnpm is on PATH, still treat it as
// present so mode resolution picks pnpm over the npx crash path. The
// PATH probe is memoized and only runs when the version is unreadable.
const pnpmPresent = major !== null || Boolean(probe('pnpm'));
let ran;
let major = null;
let minor = null;
if ('pnpmRuns' in deps && !deps.pnpmRuns) {
ran = false;
} else {
const probed = probeVersion('pnpm');
ran = 'pnpmRuns' in deps ? Boolean(deps.pnpmRuns) : probed.ran;
major = probed.major;
minor = probed.minor;
}
// Carry presence separately from version: when the version probe runs
// but produces an unparseable version (e.g. Corepack banner), still treat
// it as present (ran: true, major: null) so mode resolution picks pnpm
// over the npx crash path. A failed probe (ran: false, non-zero exit or
// absent) marks pnpm not present so it falls through to bunx/npx (#3717).
const pnpmPresent = 'pnpmPresent' in deps ? Boolean(deps.pnpmPresent) : ran;
resolved = { ...deps, pnpmMajor: major, pnpmMinor: minor, pnpmPresent };
}
}

View file

@ -15,7 +15,7 @@
* same-named callable in the file.
*
* For a synthetic corpus at two scales it reports:
* - elapsed_ms_small / elapsed_ms_large (fastest of REPS, see `fastest`) + a scaling ratio
* - elapsed_ms_small / elapsed_ms_large (median of window minima) + a scaling ratio
* `(t_large/t_small)/(LARGE/SMALL)`: ~1.0 linear, ~3.x quadratic;
* - `callable_only_ms_large`, the same corpus with the PRE-#2693 def
* population, so the cost the widening actually added stays visible as
@ -48,8 +48,9 @@ const BASELINE_PATH = path.resolve(__dirname, 'baselines.json');
const SMALL = 250;
const LARGE = 800;
const REPS = 15;
const WARMUP = 5;
const REPS = 7;
const WARMUP = 2;
const WINDOW_MS = 1000;
/**
* Deterministic synthetic corpus — no randomness, so the fingerprint is stable.
@ -144,34 +145,23 @@ function callableOnlyScopes(scopes) {
return { defs: { byId } };
}
/**
* MIN, not median. Both scales are timed in one process, and every source of
* error here is additive — scheduler preemption, GC, a noisy neighbour on a
* shared CI runner. The fastest observed run is the closest estimate of the
* uncontended cost, so the derived ratios stay comparable across machines
* instead of tracking whatever else the box was doing. (Measured directly: the
* same build reported an overhead of 1.65 idle and 2.03 while a test shard was
* running — a median-based gate would have to be loosened until it could no
* longer detect the regression it exists to catch.)
*/
function fastest(values) {
return Math.min(...values);
function median(values) {
return [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];
}
function timeIndex(scopes, nodeLookup, graph) {
// Warm up before timing: the first calls carry JIT compilation of the whole
// resolve chain, and the widened and callable-only runs would otherwise be
// measured at different optimisation tiers — which alone moved the reported
// overhead by ~30%.
for (let w = 0; w < WARMUP; w++) buildGraphTargetIndex(scopes, nodeLookup, undefined, graph);
const samples = [];
// A short handful of calls can all overlap JIT, GC or scheduler pauses.
// Keep the uncontended-cost estimator, but give each variant a full window
// to reach it. Retaining only the minimum also bounds sampling memory.
const start = performance.now();
let best = Infinity;
let last;
for (let r = 0; r < REPS; r++) {
do {
const t0 = performance.now();
last = buildGraphTargetIndex(scopes, nodeLookup, undefined, graph);
samples.push(performance.now() - t0);
}
return { ms: fastest(samples), result: last };
best = Math.min(best, performance.now() - t0);
} while (performance.now() - start < WINDOW_MS);
return { ms: best, result: last };
}
function fingerprint(targets) {
@ -179,29 +169,46 @@ function fingerprint(targets) {
return crypto.createHash('sha256').update(lines.join('\n')).digest('hex');
}
const scales = {};
for (const [name, fileCount] of [
const cases = [
['small', SMALL],
['large', LARGE],
]) {
const { graph, scopes, nodeLookup } = buildCorpus(fileCount);
const widened = timeIndex(scopes, nodeLookup, graph);
const callableOnly = timeIndex(callableOnlyScopes(scopes), nodeLookup, graph);
scales[name] = {
files: fileCount,
defs: scopes.defs.byId.size,
ms: widened.ms,
callable_only_ms: callableOnly.ms,
targets: widened.result.size,
callable_only_targets: callableOnly.result.size,
fingerprint: fingerprint(widened.result),
].map(([name, files]) => ({ name, files, ...buildCorpus(files) }));
const variants = cases.flatMap((corpus) => [
corpus,
{ ...corpus, scopes: callableOnlyScopes(corpus.scopes) },
]);
const samples = variants.map(() => []);
const results = [];
// Measure all four variants in each round, reversing their order to avoid
// consistently favouring one tier or scale. Discard complete warmup rounds.
// Pair ratios within rounds so a change in runner load does not compare a
// quiet control period with a busy widened period (or small with large).
for (let round = 0; round < WARMUP + REPS; round++) {
for (const i of round % 2 === 0 ? [0, 1, 2, 3] : [3, 2, 1, 0]) {
const { scopes, nodeLookup, graph } = variants[i];
const timed = timeIndex(scopes, nodeLookup, graph);
results[i] = timed.result;
if (round >= WARMUP) samples[i].push(timed.ms);
}
}
const scales = {};
for (const [i, corpus] of cases.entries()) {
scales[corpus.name] = {
files: corpus.files,
defs: corpus.scopes.defs.byId.size,
ms: median(samples[i * 2]),
callable_only_ms: median(samples[i * 2 + 1]),
targets: results[i * 2].size,
callable_only_targets: results[i * 2 + 1].size,
fingerprint: fingerprint(results[i * 2]),
};
}
const scalingRatio = scales.large.ms / scales.small.ms / (LARGE / SMALL);
const scalingRatio = median(samples[2].map((ms, i) => ms / samples[0][i] / (LARGE / SMALL)));
// How much slower the widened gate is than the pre-#2693 one on the same
// corpus. 1.0 = free; 2.0 = the widening doubled the index build.
const wideningOverhead = scales.large.ms / scales.large.callable_only_ms;
const wideningOverhead = median(samples[2].map((ms, i) => ms / samples[3][i]));
const report = {
small: scales.small,

View file

@ -13,6 +13,18 @@ entries. The count arm remains 138 call drops and 168 total drops.
Earlier entries below retain their original measurement contracts and source pins;
member-name-only RESOLVES claims in those entries are historical.
## api_impact indirect-consumers fixture (#3644)
The new `api-impact-indirect-consumers` fixture adds three `receiver-unresolved`
sites, none of them a resolver change: two `.then(...)` calls whose receiver is
the untyped return of `fetch(...)` (`src/client.ts`, external origin) and of the
local wrapper `apiFetch(...)` (`src/stats.ts`, in-program origin), and one
`req.query.path` read inside an inline Express handler whose `req` parameter is
untyped (`src/server.ts`), the same shape as the `express-inline-handlers`
entry below. Call drops move from 138 to 140 (`.ts` 16 -> 18, `no-chain`
36 -> 38), reads from 30 to 31, all kinds from 168 to 171. Every shape-arm
state is unchanged; no existing site changed state.
## Typed shape bodies for JavaScript, Ruby, PHP and C (#3498)
The JavaScript and Ruby rows had no type information anywhere, so every chain
@ -1478,7 +1490,6 @@ Main c30449394 is merged normally. Package-factory fallback declines inherited r
The integrated build, both TypeScript configurations, 345 tests across ten files, Kotlin capture fingerprint and regenerated receiver check pass. The baseline remains 136 call drops, 166 drops across all kinds, 30 reads and zero writes, with unchanged shape states. The 5,521-record corpus is byte-identical to the candidate before the companion-header fix. These tests overlap earlier runs. Exact-head hosted CI remains required.
### Rust pointer fields on the prepared C#/PHP/Kotlin stack
The reviewed C# parent `b74fe72b8` is merged normally, retaining PHP

View file

@ -202,16 +202,16 @@
}
},
"countArm": {
"callDrops": 138,
"totalDropsAllKinds": 168,
"callDrops": 140,
"totalDropsAllKinds": 171,
"bySiteKind": {
"call": 138,
"read": 30
"call": 140,
"read": 31
},
"callDropsByExtension": {
".java": 49,
".py": 24,
".ts": 16,
".ts": 18,
".zig": 10,
".kt": 8,
".tsx": 6,
@ -225,15 +225,15 @@
},
"callDropsByShape": {
"chain-field": 56,
"no-chain": 36,
"no-chain": 38,
"chain-call": 32,
"<<unclassified>>": 13,
"chain-unwrap": 1
},
"callDropsByOrigin": {
"in-program": 57,
"in-program": 58,
"unknown": 49,
"external": 30,
"external": 31,
"<<unclassified>>": 2
}
}

View file

@ -234,7 +234,8 @@
},
"typescript": {
"_lexical_ownership_3532": "#3532: lexical ownership captures and fixture updates; fixture identities are relative to lang-resolution so serialized scope IDs are independent of checkout location. Full capture content remains hashed; scaling_budget is unchanged.",
"fingerprint": "112cb06df38cb8144aaf4cdb5e1209f5d74ff5fa38005299fb39c853df311a68",
"fingerprint": "c32c400ad55d97605af7d48320194f39387199c34bc78cd4208c69277d479fd6",
"_rebaselined_3725_class_expression_owners": "#3725 adds qualified class/member identities. Comparing base 34b873696 and head 7e0414915 over the identical 174 fixture entries attributes the entire drift to 356 added @declaration.qualified_name tags across 85 entries. Removing only those tags restores 112cb06df38cb8144aaf4cdb5e1209f5d74ff5fa38005299fb39c853df311a68 exactly; no capture groups are added or removed (2939 total). Synthetic counts remain 4503/14403 and the scaling budget is unchanged.",
"_rebaselined_3489_inline_handlers": "#3489: Compared main 22a7608 and candidate 7456546 emitters on the same 174-entry TypeScript corpus. Exactly four callback declaration groups were added: two in typescript-hoc-wrapped/src/negative-bare-call.ts, one in typescript-hof-callbacks/src/store.ts, and one in typescript-mcp-tools/src/server.ts. Every added group has @callable.unbound; none was removed or changed. Capture groups 2935 -> 2939. JavaScript is byte-identical. Synthetic counts remain 4503/14403 and scaling budgets are unchanged; CI measured TypeScript 1.048 < 1.5 and JavaScript 0.911 < 1.5.",
"_rebaselined_3446_mcp_tools_fixture": "#3446 adds typescript-mcp-tools/src/{handlers,server,tools}.ts: corpus growth only, with fixture_count 171 -> 174 and capture_groups_fp 2753 -> 2894. Excluding only that fixture directory restores the prior fingerprint 77c9b4ea654123a64972db8348190ec250b669472b150db65ea8c7f20b355467 exactly. The scope emitter, synthetic capture counts (4503/14403), scaling budget, and other language baselines are unchanged.",
"_rebaselined_3190": "Capture matches now retain explicit ESM export/private evidence, including synthesized default HOCs; CommonJS surfaces remain undecided. Capture group counts unchanged. Scaling budget unchanged.",
@ -266,7 +267,8 @@
},
"javascript": {
"_lexical_ownership_3532": "#3532: lexical ownership captures and fixture updates; fixture identities are relative to lang-resolution so serialized scope IDs are independent of checkout location. Full capture content remains hashed; scaling_budget is unchanged.",
"fingerprint": "857b1257a001f8741412ea08a4f43d9253cc4addfa63421f3013b3ff77a390c9",
"fingerprint": "ae7b2a3dc4072c8e4cda166cb5ea11b50b8a4b9173144518129e19007f628013",
"_rebaselined_3725_class_expression_owners": "#3725 adds qualified class/member identities. Comparing base 34b873696 and head 7e0414915 over the identical 43 fixture entries attributes the entire drift to 107 added @declaration.qualified_name tags across 21 entries. Removing only those tags restores 857b1257a001f8741412ea08a4f43d9253cc4addfa63421f3013b3ff77a390c9 exactly; no capture groups are added or removed (856 total). Synthetic counts remain 3253/10403 and the scaling budget is unchanged.",
"_rebaselined_3190": "Capture matches now retain explicit ESM export/private evidence, including synthesized default HOCs; CommonJS surfaces remain undecided. Capture group counts unchanged. Scaling budget unchanged.",
"scaling_budget": 1.5,
"_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior b59fe8135b6a31a12bc3f872b224054b16592588153ae3661d03958d787c76f3 -> 479927409bbdd9852a36172c8260aa56df260e99129a7a9c20a0d1903dd5538b; scaling 1.050 < 1.5.",

View file

@ -16,8 +16,9 @@
* resolved to `npx` and the emitted command could not run at all. `bunx` is
* bun's install-free one-shot runner and needs no allow-build equivalent — bun
* skips lifecycle scripts unconditionally for a `bunx` fetch, which the native
* loader recovers from directly (see core/lbug/native-check.ts). Both bun rungs
* gate on `bunx` actually running, not merely existing on PATH — see `hasBun`.
* loader recovers from directly (see core/lbug/native-check.ts). Both pnpm and
* bun rungs gate on the tool actually running, not merely existing on PATH —
* see `hasPnpm` (#3717) and `hasBun`.
*
* The `--allow-build` flags MUST precede the `dlx` token. pnpm < 10.14 keeps
* `dlx` in its argv escape list, so flags placed *after* `dlx` are parsed as
@ -126,10 +127,10 @@ function resolveOnPath(
// `ran` is liveness, kept separate from the version because a PATH hit proves a
// file exists, not that it works, and the two answers differ: a banner-printing
// or oddly-versioned tool is alive with `major: null`, while a stale shim left by
// a partial uninstall is neither. Only the bun rung consults `ran` today (see
// hasBun) — it is the one runner with no version to read, so a dedicated probe is
// its only liveness signal; pnpm gets the same evidence for free from the version
// spawn it must make anyway, and deliberately forgives an unreadable one (#1939).
// a partial uninstall (or an unconfigured NVM shim) is neither. Both pnpm and
// bun consult `ran` (see hasPnpm, hasBun) — pnpm gets the evidence for free
// from the version spawn it must make anyway, deliberately forgiving an
// unreadable version when the process actually ran (#1939, #3717).
function probeVersion(command) {
try {
const output = execFileSync(command, ['--version'], {
@ -214,18 +215,34 @@ function resolveInvocationMode(probe = resolveOnPath, deps = {}) {
if (probe('gitnexus', true)) return 'gitnexus';
const npmMajor = getNpmMajorVersion(deps);
// pnpm presence: prefer an explicit `pnpmPresent` flag (set by
// formatAnalyzeCommand, which falls back to a PATH probe when the version is
// unreadable) so a present-but-unparseable pnpm — slow probe, Corepack
// banner — still selects pnpm instead of the npx crash path. Otherwise an
// injected version (a successful `pnpm --version` proves presence)
// short-circuits the `which pnpm` probe; failing both, fall back to PATH.
const hasPnpm =
'pnpmPresent' in deps
? deps.pnpmPresent
: 'pnpmMajor' in deps
? deps.pnpmMajor !== null
: Boolean(probe('pnpm'));
// pnpm usability is resolved lazily, mirroring bun: prefer an explicit
// `pnpmPresent` flag (set by formatAnalyzeCommand, which captures whether
// `pnpm --version` actually ran) so a present-but-unparseable pnpm (Corepack
// banner) still selects pnpm instead of the npx crash path, while an
// unusable shim (e.g. NVM for Windows: non-zero exit) is rejected (#3717).
// Otherwise an injected version/presence short-circuits the spawn; failing
// both, check PATH presence then liveness (`pnpm --version`).
let pnpmCache;
const hasPnpm = () => {
if (pnpmCache === undefined) {
if ('pnpmPresent' in deps) {
pnpmCache =
Boolean(deps.pnpmPresent) && ('pnpmRuns' in deps ? Boolean(deps.pnpmRuns) : true);
} else if ('pnpmRuns' in deps && !deps.pnpmRuns) {
pnpmCache = false;
} else if ('pnpmMajor' in deps && deps.pnpmMajor !== null) {
pnpmCache = true;
} else if ('pnpmRuns' in deps && deps.pnpmRuns) {
pnpmCache = Boolean(probe('pnpm'));
} else if ('pnpmMajor' in deps && deps.pnpmMajor === null) {
pnpmCache = false;
} else {
const present = Boolean(probe('pnpm'));
pnpmCache = present && probeVersion('pnpm').ran;
}
}
return pnpmCache;
};
// bun usability is resolved lazily: only the two branches below can select it,
// so a machine with pnpm, or with npm < 11, never pays the PATH scan or the
@ -243,13 +260,13 @@ function resolveInvocationMode(probe = resolveOnPath, deps = {}) {
};
// npm 11+ npx install crash (#1939) — prefer pnpm dlx when available.
if (hasPnpm && npmMajor !== null && npmMajor >= 11) return 'pnpm';
if (npmMajor !== null && npmMajor >= 11 && hasPnpm()) return 'pnpm';
// Same crash, no pnpm to fall back on: bunx is install-free and unaffected.
if (npmMajor !== null && npmMajor >= 11 && hasBun()) return 'bun';
// npm 10 and earlier: npx works; prefer it over pnpm dlx when npm is present.
if (npmMajor !== null && npmMajor < 11) return 'npx';
// npm absent or unreadable — use pnpm if present (with allow-build flags).
if (hasPnpm) return 'pnpm';
if (hasPnpm()) return 'pnpm';
// Neither npm nor pnpm — bunx is the only install-free runner left. Without
// this rung a bun-only machine fell through to `npx`, which is not installed
// there, so the emitted command failed with "npx: command not found".
@ -304,12 +321,23 @@ function formatAnalyzeCommand(options = {}, deps = {}) {
const mightUsePnpm =
forced === 'pnpm' || (forced !== 'gitnexus' && forced !== 'npx' && forced !== 'bun');
if (mightUsePnpm && (forced === 'pnpm' || !probe('gitnexus', true))) {
const { major, minor } = probeVersion('pnpm');
// Carry presence separately from version: when the version probe fails
// (timeout, Corepack banner) but pnpm is on PATH, still treat it as
// present so mode resolution picks pnpm over the npx crash path. The
// PATH probe is memoized and only runs when the version is unreadable.
const pnpmPresent = major !== null || Boolean(probe('pnpm'));
let ran;
let major = null;
let minor = null;
if ('pnpmRuns' in deps && !deps.pnpmRuns) {
ran = false;
} else {
const probed = probeVersion('pnpm');
ran = 'pnpmRuns' in deps ? Boolean(deps.pnpmRuns) : probed.ran;
major = probed.major;
minor = probed.minor;
}
// Carry presence separately from version: when the version probe runs
// but produces an unparseable version (e.g. Corepack banner), still treat
// it as present (ran: true, major: null) so mode resolution picks pnpm
// over the npx crash path. A failed probe (ran: false, non-zero exit or
// absent) marks pnpm not present so it falls through to bunx/npx (#3717).
const pnpmPresent = 'pnpmPresent' in deps ? Boolean(deps.pnpmPresent) : ran;
resolved = { ...deps, pnpmMajor: major, pnpmMinor: minor, pnpmPresent };
}
}

View file

@ -72,6 +72,7 @@
"@babel/parser": "^8.0.0",
"@babel/traverse": "^8.0.0",
"@babel/types": "^8.0.0",
"@mermaid-js/tiny": "11.17.2",
"@types/busboy": "^1.5.4",
"@types/cli-progress": "^3.11.6",
"@types/cors": "^2.8.17",
@ -80,6 +81,7 @@
"@types/proxy-addr": "^2.0.3",
"@vitest/coverage-v8": "^5.0.0",
"gitnexus-shared": "file:../gitnexus-shared",
"jsdom": "26.1.0",
"tsx": "^4.0.0",
"typescript": "^7.0.2",
"vitest": "^5.0.0"
@ -95,6 +97,27 @@
"typescript": "^7.0.2"
}
},
"node_modules/@asamuzakjp/css-color": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",
"integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@csstools/css-calc": "^2.1.3",
"@csstools/css-color-parser": "^3.0.9",
"@csstools/css-parser-algorithms": "^3.0.4",
"@csstools/css-tokenizer": "^3.0.3",
"lru-cache": "^10.4.3"
}
},
"node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"dev": true,
"license": "ISC"
},
"node_modules/@babel/code-frame": {
"version": "8.0.6",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.6.tgz",
@ -231,6 +254,121 @@
"node": ">=18"
}
},
"node_modules/@csstools/color-helpers": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",
"integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT-0",
"engines": {
"node": ">=18"
}
},
"node_modules/@csstools/css-calc": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",
"integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@csstools/css-parser-algorithms": "^3.0.5",
"@csstools/css-tokenizer": "^3.0.4"
}
},
"node_modules/@csstools/css-color-parser": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz",
"integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"dependencies": {
"@csstools/color-helpers": "^5.1.0",
"@csstools/css-calc": "^2.1.4"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@csstools/css-parser-algorithms": "^3.0.5",
"@csstools/css-tokenizer": "^3.0.4"
}
},
"node_modules/@csstools/css-parser-algorithms": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",
"integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@csstools/css-tokenizer": "^3.0.4"
}
},
"node_modules/@csstools/css-tokenizer": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",
"integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
@ -826,6 +964,13 @@
"integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==",
"license": "MIT"
},
"node_modules/@mermaid-js/tiny": {
"version": "11.17.2",
"resolved": "https://registry.npmjs.org/@mermaid-js/tiny/-/tiny-11.17.2.tgz",
"integrity": "sha512-PmFr1c5cSfNf5AngLLR98DrbvR4U5KeD7I+hQkGqG5w5Veu3QT4dG0qu9f99cpn/sKj2XxRBK0q7EL6hr9NY/A==",
"dev": true,
"license": "MIT"
},
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.32.1",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz",
@ -1011,9 +1156,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1032,9 +1174,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -1053,9 +1192,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1074,9 +1210,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1095,9 +1228,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1116,9 +1246,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -1832,6 +1959,16 @@
"node": ">= 0.6"
}
},
"node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 14"
}
},
"node_modules/ajv": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
@ -2376,6 +2513,34 @@
"node": ">= 8"
}
},
"node_modules/cssstyle": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",
"integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@asamuzakjp/css-color": "^3.2.0",
"rrweb-cssom": "^0.8.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/data-urls": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
"integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",
"dev": true,
"license": "MIT",
"dependencies": {
"whatwg-mimetype": "^4.0.0",
"whatwg-url": "^14.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/dateformat": {
"version": "4.6.3",
"resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
@ -2402,6 +2567,13 @@
}
}
},
"node_modules/decimal.js": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
"dev": true,
"license": "MIT"
},
"node_modules/deep-extend": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
@ -2475,6 +2647,19 @@
"once": "^1.4.0"
}
},
"node_modules/entities": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
"integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@ -3086,6 +3271,19 @@
"node": ">=16.9.0"
}
},
"node_modules/html-encoding-sniffer": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",
"integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"whatwg-encoding": "^3.1.1"
},
"engines": {
"node": ">=18"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
@ -3106,6 +3304,34 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
"integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
"dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.0",
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/https-proxy-agent": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
"dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/iconv-lite": {
"version": "0.7.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
@ -3170,6 +3396,13 @@
"node": ">=8"
}
},
"node_modules/is-potential-custom-element-name": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
"dev": true,
"license": "MIT"
},
"node_modules/is-promise": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
@ -3244,6 +3477,46 @@
"js-yaml": "bin/js-yaml.mjs"
}
},
"node_modules/jsdom": {
"version": "26.1.0",
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
"dev": true,
"license": "MIT",
"dependencies": {
"cssstyle": "^4.2.1",
"data-urls": "^5.0.0",
"decimal.js": "^10.5.0",
"html-encoding-sniffer": "^4.0.0",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"is-potential-custom-element-name": "^1.0.1",
"nwsapi": "^2.2.16",
"parse5": "^7.2.1",
"rrweb-cssom": "^0.8.0",
"saxes": "^6.0.0",
"symbol-tree": "^3.2.4",
"tough-cookie": "^5.1.1",
"w3c-xmlserializer": "^5.0.0",
"webidl-conversions": "^7.0.0",
"whatwg-encoding": "^3.1.1",
"whatwg-mimetype": "^4.0.0",
"whatwg-url": "^14.1.1",
"ws": "^8.18.0",
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"canvas": "^3.0.0"
},
"peerDependenciesMeta": {
"canvas": {
"optional": true
}
}
},
"node_modules/jsesc": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
@ -3444,9 +3717,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@ -3469,9 +3739,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@ -3494,9 +3761,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@ -3519,9 +3783,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@ -3587,9 +3848,9 @@
"license": "MIT"
},
"node_modules/lru-cache": {
"version": "11.5.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz",
"integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==",
"version": "11.5.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
@ -3839,6 +4100,13 @@
"node-gyp-build-test": "build-test.js"
}
},
"node_modules/nwsapi": {
"version": "2.2.28",
"resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz",
"integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==",
"dev": true,
"license": "MIT"
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@ -3934,6 +4202,19 @@
"obliterator": "^2.0.1"
}
},
"node_modules/parse5": {
"version": "7.3.0",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
"integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
"dev": true,
"license": "MIT",
"dependencies": {
"entities": "^6.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@ -4174,6 +4455,16 @@
"once": "^1.3.1"
}
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/qs": {
"version": "6.16.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz",
@ -4336,6 +4627,13 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/rrweb-cssom": {
"version": "0.8.0",
"resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
"integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",
"dev": true,
"license": "MIT"
},
"node_modules/safe-stable-stringify": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
@ -4351,6 +4649,19 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
"integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
"dev": true,
"license": "ISC",
"dependencies": {
"xmlchars": "^2.2.0"
},
"engines": {
"node": ">=v12.22.7"
}
},
"node_modules/secure-json-parse": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz",
@ -4649,6 +4960,13 @@
"node": ">=8"
}
},
"node_modules/symbol-tree": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
"integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
"dev": true,
"license": "MIT"
},
"node_modules/table-layout": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/table-layout/-/table-layout-4.1.1.tgz",
@ -4737,6 +5055,26 @@
"node": ">=14.0.0"
}
},
"node_modules/tldts": {
"version": "6.1.86",
"resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
"integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"tldts-core": "^6.1.86"
},
"bin": {
"tldts": "bin/cli.js"
}
},
"node_modules/tldts-core": {
"version": "6.1.86",
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
"integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
"dev": true,
"license": "MIT"
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@ -4746,6 +5084,32 @@
"node": ">=0.6"
}
},
"node_modules/tough-cookie": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
"integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"tldts": "^6.1.32"
},
"engines": {
"node": ">=16"
}
},
"node_modules/tr46": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
"integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
"dev": true,
"license": "MIT",
"dependencies": {
"punycode": "^2.3.1"
},
"engines": {
"node": ">=18"
}
},
"node_modules/tree-sitter": {
"version": "0.25.1",
"resolved": "https://registry.npmjs.org/tree-sitter/-/tree-sitter-0.25.1.tgz",
@ -5315,6 +5679,80 @@
}
}
},
"node_modules/w3c-xmlserializer": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
"integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
"dev": true,
"license": "MIT",
"dependencies": {
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/webidl-conversions": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
"integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
}
},
"node_modules/whatwg-encoding": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
"integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
"deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation",
"dev": true,
"license": "MIT",
"dependencies": {
"iconv-lite": "0.6.3"
},
"engines": {
"node": ">=18"
}
},
"node_modules/whatwg-encoding/node_modules/iconv-lite": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
"dev": true,
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/whatwg-mimetype": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
"integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/whatwg-url": {
"version": "14.2.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
"integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"tr46": "^5.1.0",
"webidl-conversions": "^7.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/which": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz",
@ -5375,6 +5813,38 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/ws": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
"integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=18"
}
},
"node_modules/xml-naming": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz",
@ -5390,6 +5860,13 @@
"node": ">=16.0.0"
}
},
"node_modules/xmlchars": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
"dev": true,
"license": "MIT"
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",

View file

@ -124,6 +124,7 @@
"@babel/parser": "^8.0.0",
"@babel/traverse": "^8.0.0",
"@babel/types": "^8.0.0",
"@mermaid-js/tiny": "11.17.2",
"@types/busboy": "^1.5.4",
"@types/cli-progress": "^3.11.6",
"@types/cors": "^2.8.17",
@ -132,6 +133,7 @@
"@types/proxy-addr": "^2.0.3",
"@vitest/coverage-v8": "^5.0.0",
"gitnexus-shared": "file:../gitnexus-shared",
"jsdom": "26.1.0",
"tsx": "^4.0.0",
"typescript": "^7.0.2",
"vitest": "^5.0.0"

View file

@ -59,13 +59,13 @@ export const WINDOWS_WEIGHTS_SEC: Readonly<Record<string, number>> = {
'test/integration/rename-provider-c.test.ts': 202,
'test/integration/rename-provider-cobol.test.ts': 75,
'test/integration/rename-provider-cpp.test.ts': 250,
'test/integration/rename-provider-csharp.test.ts': 200,
'test/integration/rename-provider-csharp.test.ts': 266,
'test/integration/rename-provider-dart.test.ts': 425,
'test/integration/rename-provider-go.test.ts': 221,
'test/integration/rename-provider-java.test.ts': 300,
'test/integration/rename-provider-javascript.test.ts': 225,
'test/integration/rename-provider-kotlin.test.ts': 300,
'test/integration/rename-provider-objective-c.test.ts': 285,
'test/integration/rename-provider-objective-c.test.ts': 386,
'test/integration/rename-provider-php.test.ts': 100,
'test/integration/rename-provider-python.test.ts': 375,
'test/integration/rename-provider-ruby.test.ts': 100,
@ -78,7 +78,12 @@ export const WINDOWS_WEIGHTS_SEC: Readonly<Record<string, number>> = {
// Windows persisted-fixture profile above. Replace with observed CI timing.
'test/integration/rename-preview-plan.test.ts': 175,
'test/integration/mcp-index-generation.test.ts': 201,
'test/unit/incremental-dirty-recovery.test.ts': 76,
// Windows run 39934695864 timed out after undercharged native suites;
// 40172490240 supplies the query-symbol and dirty-recovery measurements.
'test/integration/incremental-method-integrity.test.ts': 145,
'test/integration/fts-repair-warm-session.test.ts': 62,
'test/integration/query-symbol-integrity.test.ts': 34,
'test/unit/incremental-dirty-recovery.test.ts': 128,
// Re-measured after the analyze --watch e2e landed in #3072. The previous
// 361 s entry undercharged this suite and left shard 1 close to the watchdog.
'test/integration/cli-e2e.test.ts': 621,

View file

@ -344,6 +344,7 @@ const WORKER_THREADS = [
'test/integration/java-imported-return-types.test.ts',
'test/unit/community-processor.test.ts',
'test/integration/worker-pool.test.ts',
'test/integration/class-expression-owners.test.ts',
'test/integration/parse-impl-quarantine-cache-skip.test.ts',
// Real parse workers and both on-disk parse stores must retain lexical
// local-import ownership on each platform's native grammar/runtime pair.
@ -353,9 +354,11 @@ const WORKER_THREADS = [
'test/integration/resolvers/fetch-wrapper-persistence.test.ts',
];
// Tree-sitter native addon smoke tests — verify that native grammars
// load correctly on each platform (binary compatibility, .node loading)
// Native addon smoke tests — verify binary compatibility and recovery on each OS.
const NATIVE_ADDON_SMOKE = [
// bunx skips the native install copy; recover it before recording identity.
'test/unit/lbug-native-check.test.ts',
'test/unit/lazy-action.test.ts',
'test/integration/tree-sitter-languages.test.ts',
'test/integration/parsing.test.ts',
'test/integration/pipeline.test.ts',

View file

@ -0,0 +1,111 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { createRequire } from 'node:module';
import {
copyFile,
mkdir,
mkdtemp,
readFile,
readdir,
realpath,
rm,
writeFile,
} from 'node:fs/promises';
import { existsSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
// Run from gitnexus/ after npm pack. Each manager installs the actual PR tarball
// without lifecycle scripts, reproducing bunx's missing native install copy.
const tarballs = (await readdir('.')).filter((name) => /^gitnexus-.*\.tgz$/.test(name));
assert.equal(tarballs.length, 1, 'Expected one freshly packed gitnexus tarball');
const tarball = path.resolve(tarballs[0]);
function run(program, args, cwd, env) {
// All shell arguments are fixed literals; the tarball is copied through fs.
// Windows package-manager entrypoints are .cmd shims.
const result = spawnSync(program, args, {
cwd,
env,
shell: process.platform === 'win32',
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
});
if (result.error || result.status !== 0) {
throw new Error(
`${program} ${args.join(' ')} failed (${result.status}): ${result.error?.message ?? ''}\n` +
`${result.stdout ?? ''}\n${result.stderr ?? ''}`,
);
}
return result.stdout;
}
for (const manager of ['npm', 'pnpm', 'bun']) {
const root = await mkdtemp(path.join(os.tmpdir(), `gitnexus-${manager}-smoke-`));
const env = {
...process.env,
GITNEXUS_HOME: path.join(root, 'home'),
GITNEXUS_STORAGE_PATH: path.join(root, 'repo', '.gitnexus'),
GITNEXUS_SHARED_STORE: 'off',
GITNEXUS_MEMORY: 'off',
SCARF_ANALYTICS: 'false',
};
try {
const version = run(manager, ['--version'], root, env).trim();
await copyFile(tarball, path.join(root, 'gitnexus.tgz'));
await writeFile(
path.join(root, 'package.json'),
JSON.stringify({
name: 'gitnexus-manager-smoke',
version: '1.0.0',
private: true,
dependencies: { gitnexus: 'file:./gitnexus.tgz' },
}),
);
run(
manager,
['install', '--ignore-scripts', ...(manager === 'pnpm' ? ['--store-dir=store'] : [])],
root,
env,
);
const installed = await realpath(path.join(root, 'node_modules', 'gitnexus'));
const requireInstalled = createRequire(path.join(installed, 'package.json'));
const binaryPath = path.join(
path.dirname(requireInstalled.resolve('@ladybugdb/core')),
'lbugjs.node',
);
assert.equal(existsSync(binaryPath), false, `${manager}: fixture must skip native preparation`);
await mkdir(path.join(root, 'repo'));
await writeFile(
path.join(root, 'repo', 'index.ts'),
'export function greet(name: string) { return `Hello ${name}`; }\n' +
'export function main() { return greet("GitNexus"); }\n',
);
run('git', ['init', '-q', 'repo'], root, env);
const args = ['gitnexus', 'analyze', 'repo', '--index-only', '--workers', '1'];
const [program, prefix] =
manager === 'npm'
? ['npx', ['--no-install']]
: manager === 'pnpm'
? ['pnpm', ['exec']]
: ['bunx', ['--no-install']];
run(program, [...prefix, ...args], root, env);
assert.equal(existsSync(binaryPath), true, `${manager}: native binary was not prepared`);
const metadata = JSON.parse(
await readFile(path.join(root, 'repo', '.gitnexus', 'gitnexus.json'), 'utf8'),
);
assert.equal(metadata.stats.files, 1);
assert.ok(metadata.stats.nodes >= 4, `${manager}: missing indexed symbols`);
assert.ok(metadata.stats.edges >= 5, `${manager}: missing graph relationships`);
assert.ok(
metadata.runnerIdentity?.dependencyRuntime?.artifactCount > 0,
`${manager}: missing identity receipt`,
);
console.log(
`PASS ${process.platform}/${process.arch}: ${manager} ${version} installed and indexed the PR tarball`,
);
} finally {
await rm(root, { recursive: true, force: true });
}
}

View file

@ -4,7 +4,7 @@
* at compile time — catching typos when used with concrete module imports.
*/
import { checkLbugNative } from '../core/lbug/native-check.js';
import { checkLbugNative, prepareLbugNativeBinary } from '../core/lbug/native-check.js';
function isCallable(value: unknown): value is (...args: unknown[]) => unknown {
return typeof value === 'function';
@ -46,8 +46,9 @@ export function createLbugLazyAction<
/**
* Analyze-specific lazy action. Unlike the generic LadybugDB wrapper, this
* captures the complete analyzer receipt before probing/loading native code or
* evaluating the analyzer module graph. The target export receives that start
* prepares any skipped native install copy, then captures the complete analyzer
* receipt before probing/loading native code or evaluating the analyzer module
* graph. The target export receives that start
* receipt as its first argument and threads it to runFullAnalysis.
*/
export function createAnalyzerLbugLazyAction<
@ -62,6 +63,7 @@ export function createAnalyzerLbugLazyAction<
analyzerModuleUrl: string,
): (...args: unknown[]) => Promise<void> {
return async (...args: unknown[]): Promise<void> => {
prepareLbugNativeBinary();
const identityModule = await identityLoader();
const prepared = await identityModule.captureAnalyzerIdentityBeforeLoad(
analyzerModuleUrl,

View file

@ -17,7 +17,7 @@
import { KnowledgeGraph } from '../graph/types.js';
import type { SemanticModel, SymbolTableReader } from './model/index.js';
import { generateId } from '../../lib/utils.js';
import { compareCodeUnits, generateId } from '../../lib/utils.js';
import type { ParsedImport, SymbolDefinition } from 'gitnexus-shared';
import { yieldToEventLoop } from './utils/event-loop.js';
import type { ExtractedRoute, ExtractedFetchCall } from './workers/parse-worker.js';
@ -34,6 +34,7 @@ import { extractReturnTypeName } from './type-extractors/shared.js';
import { DATA_ROUTE_TABLE_SOURCE } from './route-extractors/data-route-table.js';
import { reconcileDispatchGuardRoutes } from './route-extractors/dispatch-guard.js';
import { toZeroBasedLine } from './utils/line-base.js';
import { EnclosingCallableIndex } from './enclosing-callable.js';
const MAX_EXPORTS_PER_FILE = 500;
const MAX_TYPE_NAME_LENGTH = 256;
@ -772,6 +773,14 @@ export const matchFetchRouteKeys = (
* route URL to the list of `routeNodeKey` identities at that URL; a single-verb
* (or method-less) URL has a one-element list, keeping edges byte-identical to
* the pre-#2289 behavior.
*
* The edge is file-level. Its reason also names the callables that hold the
* request sites, one `|via:<id>` field each, under the same attribution as the
* R3-6 sink set (the parser's enclosing callable, else the innermost span):
* `api_impact` follows their CALLS edges one level up to list the callers of
* the requesting function (#3644). A site outside any callable adds no field,
* so a reason without attribution reads as before. An id that itself contains
* the field separator cannot be carried and is left out rather than split.
*/
export const processNextjsFetchRoutes = (
graph: KnowledgeGraph,
@ -794,6 +803,15 @@ export const processNextjsFetchRoutes = (
}
}
const callables = new EnclosingCallableIndex(graph, new Set(fetchCalls.map((c) => c.filePath)));
// One edge per (consumer file, route node), in first-seen order. Several
// sites in one file for the same route share the edge, each contributing the
// callable that contains it.
const edges = new Map<
string,
{ sourceId: string; targetId: string; filePath: string; via: Set<string> }
>();
for (const call of fetchCalls) {
const normalized = normalizeFetchURL(call.fetchURL);
if (!normalized) continue;
@ -801,36 +819,49 @@ export const processNextjsFetchRoutes = (
const routeKeys = matchFetchRouteKeys(normalized, routeUrlToKeys);
if (!routeKeys) continue;
const sourceId = generateId('File', call.filePath);
const callable = callables.of(call);
// Connect to every Route node at this URL (one per verb).
for (const routeKey of routeKeys) {
const targetId = generateId('Route', routeKey);
const id = generateId('FETCHES', `${sourceId}->${targetId}`);
let edge = edges.get(id);
if (edge === undefined) {
edge = { sourceId, targetId, filePath: call.filePath, via: new Set<string>() };
edges.set(id, edge);
}
if (callable !== undefined && !callable.includes('|')) edge.via.add(callable);
}
}
for (const [id, edge] of edges) {
// Extract consumer accessed keys if file content is available
let reason = 'fetch-url-match';
if (consumerContents) {
const content = consumerContents.get(call.filePath);
if (content) {
const accessedKeys = extractConsumerAccessedKeys(content);
if (accessedKeys.length > 0) {
reason = `fetch-url-match|keys:${accessedKeys.join(',')}`;
}
const content = consumerContents?.get(edge.filePath);
if (content) {
const accessedKeys = extractConsumerAccessedKeys(content);
if (accessedKeys.length > 0) {
reason = `${reason}|keys:${accessedKeys.join(',')}`;
}
}
// Encode multi-fetch count so downstream can set confidence
const fetchCount = routeCountByFile.get(call.filePath) ?? 1;
const fetchCount = routeCountByFile.get(edge.filePath) ?? 1;
if (fetchCount > 1) {
reason = `${reason}|fetches:${fetchCount}`;
}
// Connect to every Route node at this URL (one per verb).
for (const routeKey of routeKeys) {
const routeNodeId = generateId('Route', routeKey);
graph.addRelationship({
id: generateId('FETCHES', `${sourceId}->${routeNodeId}`),
sourceId,
targetId: routeNodeId,
type: 'FETCHES',
confidence: 0.9,
reason,
});
for (const via of [...edge.via].sort(compareCodeUnits)) {
reason = `${reason}|via:${via}`;
}
graph.addRelationship({
id,
sourceId: edge.sourceId,
targetId: edge.targetId,
type: 'FETCHES',
confidence: 0.9,
reason,
});
}
};

View file

@ -2,20 +2,34 @@
import { SupportedLanguages } from 'gitnexus-shared';
import type { ClassExtractionConfig } from '../../class-types.js';
import type { LanguageProvider } from '../../language-provider.js';
import { createClassExtractor } from '../generic.js';
import { positionQualifiedCallableName } from '../../workers/callable-id.js';
const shared: Omit<ClassExtractionConfig, 'language'> = {
// Nested class expressions and their member-owner edges must use the same
// qualified identity, including when an outer class has the same name.
qualifiedNodeId: true,
typeDeclarationNodes: [
'class',
'class_declaration',
'abstract_class_declaration',
'interface_declaration',
'enum_declaration',
],
ancestorScopeNodeTypes: [
'class',
'class_declaration',
'abstract_class_declaration',
'interface_declaration',
'enum_declaration',
],
extractScopeSegments(node) {
const name = node.childForFieldName('name');
return node.type === 'class' && name !== null
? [positionQualifiedCallableName(name.text, node.startPosition)]
: undefined;
},
};
export const typescriptClassConfig: ClassExtractionConfig = {
@ -32,3 +46,38 @@ export const vueClassConfig: ClassExtractionConfig = {
...shared,
language: SupportedLanguages.Vue,
};
/** Expressions can reuse a local name in sibling factories or methods. */
export const createTsJsClassExtractor = (config: ClassExtractionConfig) => {
const extractor = createClassExtractor(config);
const extract: typeof extractor.extract = (node, fallback) => {
const owner = extractor.extract(node, fallback);
return owner !== null && node.type === 'class'
? {
...owner,
qualifiedName: positionQualifiedCallableName(owner.qualifiedName, node.startPosition),
}
: owner;
};
return {
...extractor,
extract,
extractQualifiedName: (node: Parameters<typeof extract>[0], name: string) =>
extract(node, { name })?.qualifiedName ?? null,
// TypeAlias nodes keep simple IDs, even inside qualified class owners.
qualifyScopeName: (node: Parameters<typeof extract>[0], name: string) =>
node.type === 'type_alias_declaration'
? name
: (extractor.qualifyScopeName?.(node, name) ?? name),
};
};
const ownerExtractor = createTsJsClassExtractor(typescriptClassConfig);
/** Use the definition's qualified name for both the owner and its member IDs. */
export const resolveTsJsContainerTypeOwner: NonNullable<
LanguageProvider['resolveContainerTypeOwner']
> = (node) => {
const owner = ownerExtractor.extract(node);
return owner === null ? null : { name: owner.qualifiedName, label: owner.type };
};

View file

@ -92,17 +92,18 @@ export function createClassExtractor(config: ClassExtractionConfig): ClassExtrac
]);
const buildQualifiedName = (node: SyntaxNode, simpleName: string): string => {
let root = node;
while (root.parent) root = root.parent;
const readScopeSegments = (scopeNode: SyntaxNode): string[] =>
config.extractScopeSegments?.(scopeNode) ??
extractScopeSegmentsFromNode(scopeNode, scopeNameNodeTypes);
const fileScopeSegments: string[] = [];
for (const child of root.namedChildren ?? []) {
if (fileScopeSet.has(child.type)) {
fileScopeSegments.push(...readScopeSegments(child));
if (fileScopeSet.size > 0) {
let root = node;
while (root.parent) root = root.parent;
for (const child of root.namedChildren ?? []) {
if (fileScopeSet.has(child.type)) {
fileScopeSegments.push(...readScopeSegments(child));
}
}
}

View file

@ -0,0 +1,96 @@
import type { NodeLabel } from 'gitnexus-shared';
import type { KnowledgeGraph } from '../graph/types.js';
/** Node labels whose span can contain a call site. */
export const CALLABLE_LABELS: ReadonlySet<NodeLabel> = new Set<NodeLabel>([
'Function',
'Method',
'Constructor',
]);
interface CallableSpan {
id: string;
start: number;
end: number;
}
/** A call site: where it is, and, when the parser recorded it, which callable holds it. */
export interface CallSite {
readonly filePath: string;
readonly lineNumber: number;
/** null means the AST confirmed module scope; undefined means no AST attribution. */
readonly enclosingId?: string | null;
}
/**
* Which callable contains a given line of a file.
*
* The parse phase records where the program reaches outward (a `fetch()`, an
* ORM query) as `filePath` + `lineNumber`, while the graph knows callables by
* their line spans. Attributing a site to the innermost callable whose span
* contains it turns the one into the other with no new extraction and no schema
* change. The R3-6 sink set and the FETCHES consumer attribution (#3644) both
* use this rule, through this one index, so they cannot drift apart.
*
* The parser records the enclosing callable of each site it captures from the
* AST (`enclosingId`), and that identity is used first: a line alone cannot
* tell a helper defined on the same line as the request apart from the
* function that makes it. The span lookup remains for sites found by text
* scan and for an identity the graph does not hold. An explicit null records
* module scope and must not fall back to an overlapping callable's line span.
*
* Span rule: innermost wins, a nested closure that performs the call is the
* callable, not the outer function that merely spans it. Among equal spans the
* first node seen keeps the site. Lines are 0-based on both sides, as the graph
* stores them and as tree-sitter reports them.
*/
export class EnclosingCallableIndex {
private readonly byFile = new Map<string, CallableSpan[]>();
/**
* One pass over the graph's nodes. `files` limits the index to the files
* that have sites to attribute; without it every file is indexed.
*/
constructor(
private readonly graph: KnowledgeGraph,
files?: ReadonlySet<string>,
) {
for (const node of graph.iterNodes()) {
if (!CALLABLE_LABELS.has(node.label)) continue;
const props = node.properties as {
filePath?: string;
startLine?: number;
endLine?: number;
};
if (typeof props.filePath !== 'string') continue;
if (files !== undefined && !files.has(props.filePath)) continue;
if (typeof props.startLine !== 'number' || typeof props.endLine !== 'number') continue;
const span = { id: node.id, start: props.startLine, end: props.endLine };
const list = this.byFile.get(props.filePath);
if (list === undefined) this.byFile.set(props.filePath, [span]);
else list.push(span);
}
}
/** The callable that holds `site`: its recorded enclosing callable, else the innermost span. */
of(site: CallSite): string | undefined {
if (site.enclosingId === null) return undefined;
if (site.enclosingId !== undefined) {
const node = this.graph.getNode(site.enclosingId);
if (node !== undefined && CALLABLE_LABELS.has(node.label)) return node.id;
}
return this.at(site.filePath, site.lineNumber);
}
/** Id of the innermost callable of `filePath` whose span contains `line`, if any. */
at(filePath: string, line: number): string | undefined {
const candidates = this.byFile.get(filePath);
if (candidates === undefined) return undefined;
let best: CallableSpan | undefined;
for (const c of candidates) {
if (line < c.start || line > c.end) continue;
if (best === undefined || c.end - c.start < best.end - best.start) best = c;
}
return best?.id;
}
}

View file

@ -34,6 +34,7 @@ export function constructedTypeOfFieldInitializer(node: SyntaxNode): string | un
const shared: Omit<FieldExtractionConfig, 'language'> = {
typeDeclarationNodes: [
'class',
'class_declaration',
'abstract_class_declaration',
'interface_declaration',

View file

@ -30,6 +30,7 @@ export class TypeScriptFieldExtractor extends BaseFieldExtractor {
* Node types that represent type declarations with fields in TypeScript
*/
private static readonly TYPE_DECLARATION_NODES = new Set([
'class',
'class_declaration',
'interface_declaration',
'abstract_class_declaration',
@ -258,7 +259,11 @@ export class TypeScriptFieldExtractor extends BaseFieldExtractor {
const nestedTypes: string[] = [];
// Handle different declaration types
if (node.type === 'class_declaration' || node.type === 'abstract_class_declaration') {
if (
node.type === 'class' ||
node.type === 'class_declaration' ||
node.type === 'abstract_class_declaration'
) {
// Find the class body
const bodyNode = node.childForFieldName('body');
if (bodyNode) {

View file

@ -32,6 +32,7 @@
import { recordCommonJsModuleKind } from '../typescript/module-kind.js';
import type { Capture, CaptureMatch } from 'gitnexus-shared';
import { synthesizeTsJsClassIdentity } from '../typescript/class-identity.js';
import {
findNodeAtRange,
nodeToCapture,
@ -913,6 +914,7 @@ export function emitJsScopeCaptures(
grouped[tag] = nodeToCapture(tag, c.node);
groupedNodes[tag] = c.node;
}
synthesizeTsJsClassIdentity(grouped, groupedNodes);
if (Object.keys(grouped).length === 0) continue;
// Decompose ESM import_statement / re-export export_statement.

View file

@ -101,6 +101,9 @@ ${unboundCallableQuery('declaration.function')}
(class_declaration
name: (identifier) @declaration.name) @declaration.class
(class
name: (identifier) @declaration.name) @declaration.class @class.expression
;; Declarations — methods (inside class bodies)
(method_definition
name: (property_identifier) @declaration.name) @declaration.method

View file

@ -13,10 +13,11 @@ import { unboundCallableName } from './typescript/unbound-callables.js';
import type { CaptureMatch, NodeLabel, ParsedFile } from 'gitnexus-shared';
import { defineLanguage } from '../language-provider.js';
import type { AstFrameworkPatternConfig } from '../language-provider.js';
import { createClassExtractor } from '../class-extractors/generic.js';
import {
typescriptClassConfig,
javascriptClassConfig,
resolveTsJsContainerTypeOwner,
createTsJsClassExtractor,
} from '../class-extractors/configs/typescript-javascript.js';
import type { SyntaxNode } from '../utils/ast-helpers.js';
import {
@ -524,7 +525,8 @@ export const typescriptProvider = defineLanguage({
}),
variableExtractor: createVariableExtractor(typescriptVariableConfig),
definitionPropertiesExtractor: extractConvexEndpointProperties,
classExtractor: createClassExtractor(typescriptClassConfig),
classExtractor: createTsJsClassExtractor(typescriptClassConfig),
resolveContainerTypeOwner: resolveTsJsContainerTypeOwner,
// ── JSDoc → description (issue #2270). An exported decl is captured as the
// inner declaration; its JSDoc precedes the wrapping `export_statement`. ──
descriptionExtractor: createLeadingDocDescriptionExtractor({
@ -627,7 +629,8 @@ export const javascriptProvider = defineLanguage({
}),
variableExtractor: createVariableExtractor(javascriptVariableConfig),
definitionPropertiesExtractor: extractConvexEndpointProperties,
classExtractor: createClassExtractor(javascriptClassConfig),
classExtractor: createTsJsClassExtractor(javascriptClassConfig),
resolveContainerTypeOwner: resolveTsJsContainerTypeOwner,
// ── JSDoc → description (issue #2270). An exported decl is captured as the
// inner declaration; its JSDoc precedes the wrapping `export_statement`. ──
descriptionExtractor: createLeadingDocDescriptionExtractor({

View file

@ -28,6 +28,7 @@
import { recordCommonJsModuleKind } from './module-kind.js';
import type { Capture, CaptureMatch } from 'gitnexus-shared';
import { synthesizeTsJsClassIdentity } from './class-identity.js';
import {
findNodeAtRange,
nodeToCapture,
@ -420,6 +421,7 @@ export function emitTsScopeCaptures(
groupedNodes[tag] = c.node;
}
if (Object.keys(grouped).length === 0) continue;
synthesizeTsJsClassIdentity(grouped, groupedNodes);
// Decompose each `import_statement` / re-export `export_statement`
// so `interpretTsImport` sees the kind/source/name/alias markers

View file

@ -0,0 +1,54 @@
import type { Capture } from 'gitnexus-shared';
import { resolveTsJsContainerTypeOwner } from '../../class-extractors/configs/typescript-javascript.js';
import { syntheticCapture, type SyntaxNode } from '../../utils/ast-helpers.js';
/** Keep named-expression scope declarations on the graph's owner/member IDs. */
export function synthesizeTsJsClassIdentity(
captures: Record<string, Capture>,
nodes: Record<string, SyntaxNode>,
): void {
const type =
nodes['@declaration.class'] ?? nodes['@declaration.interface'] ?? nodes['@declaration.enum'];
if (type !== undefined) {
const owner = resolveTsJsContainerTypeOwner(type, '');
if (owner !== null) {
captures['@declaration.qualified_name'] = syntheticCapture(
'@declaration.qualified_name',
type,
owner.name,
);
}
return;
}
const member =
nodes['@declaration.method'] ??
nodes['@declaration.constructor'] ??
nodes['@declaration.property'];
const name = nodes['@declaration.name'];
if (member === undefined || name === undefined) return;
for (let parent = member.parent; parent !== null; parent = parent.parent) {
// Object members and executable-body locals belong to their own scope.
if (
parent.type === 'object' ||
parent.type === 'object_type' ||
parent.type === 'statement_block'
)
return;
if (
parent.type === 'class' ||
parent.type === 'class_declaration' ||
parent.type === 'abstract_class_declaration' ||
parent.type === 'interface_declaration'
) {
const owner = resolveTsJsContainerTypeOwner(parent, '');
if (owner !== null) {
captures['@declaration.qualified_name'] = syntheticCapture(
'@declaration.qualified_name',
member,
`${owner.name}.${name.text}`,
);
}
return;
}
}
}

View file

@ -161,6 +161,10 @@ ${unboundCallableQuery('declaration.function')}
name: (type_identifier) @declaration.name
type_parameters: (type_parameters)? @declaration.type-parameters) @declaration.class
(class
name: (type_identifier) @declaration.name
type_parameters: (type_parameters)? @declaration.type-parameters) @declaration.class @class.expression
(abstract_class_declaration
name: (type_identifier) @declaration.name
type_parameters: (type_parameters)? @declaration.type-parameters) @declaration.class

View file

@ -44,7 +44,8 @@ export function tsBindingScopeFor(
): ScopeId | null {
// A named function expression binds only inside itself. Anonymous callables
// explicitly suppress their binding through @declaration.binding-name.
if (decl['@callable.unbound'] !== undefined) return innermost.id;
if (decl['@callable.unbound'] !== undefined || decl['@class.expression'] !== undefined)
return innermost.id;
// Method return type: hoist to Module (mirrors csharpBindingScopeFor).
if (decl['@type-binding.return'] !== undefined) {
return walkToScope(innermost, tree, 'Module');

View file

@ -13,8 +13,11 @@
import { SupportedLanguages } from 'gitnexus-shared';
import { isBuiltin } from 'node:module';
import { createClassExtractor } from '../class-extractors/generic.js';
import { vueClassConfig } from '../class-extractors/configs/typescript-javascript.js';
import {
vueClassConfig,
resolveTsJsContainerTypeOwner,
createTsJsClassExtractor,
} from '../class-extractors/configs/typescript-javascript.js';
import { defineLanguage } from '../language-provider.js';
import { typeConfig as typescriptConfig } from '../type-extractors/typescript.js';
import { tsExportChecker } from '../export-detection.js';
@ -77,7 +80,7 @@ const VUE_SPECIFIC_BUILT_INS = [
const VUE_BUILT_INS: ReadonlySet<string> = new Set([...TS_BUILT_INS, ...VUE_SPECIFIC_BUILT_INS]);
const vueClassExtractor = createClassExtractor(vueClassConfig);
const vueClassExtractor = createTsJsClassExtractor(vueClassConfig);
export const vueProvider = defineLanguage({
id: SupportedLanguages.Vue,
@ -92,6 +95,7 @@ export const vueProvider = defineLanguage({
fieldExtractor: typescriptFieldExtractor,
variableExtractor: createVariableExtractor(typescriptVariableConfig),
classExtractor: vueClassExtractor,
resolveContainerTypeOwner: resolveTsJsContainerTypeOwner,
builtInNames: VUE_BUILT_INS,
// A `<script>` block runs on the same host as any other module.
externalReceiverNames: TS_EXTERNAL_RECEIVER_NAMES,

View file

@ -280,6 +280,7 @@ function extractDecoratorName(decorator: SyntaxNode): string | undefined {
// nested type discovery. Methods have no such requirement.
const shared: Omit<MethodExtractionConfig, 'language'> = {
typeDeclarationNodes: [
'class',
'class_declaration',
'abstract_class_declaration',
'interface_declaration',
@ -289,8 +290,6 @@ const shared: Omit<MethodExtractionConfig, 'language'> = {
// Known gaps:
// - call_signature and construct_signature (e.g., interface Fn { (x: string): void; })
// are not extracted — they have no name field and are uncommon in practice.
// - class_expression (const Foo = class { ... }) — methods inside class expressions
// are not discovered because class_expression is not in typeDeclarationNodes.
// - declare module / declare global augmentations — methods inside ambient_module_declaration
// wrappers are not surfaced because the top-level walker doesn't descend into them.
methodNodeTypes: [

View file

@ -554,7 +554,11 @@ export const routesPhase: PipelinePhase<RoutesOutput> = {
while ((match = pattern.exec(content)) !== null) {
const url = match[2] ?? match[1];
if (url && url.startsWith('/')) {
allFetchCalls.push({ filePath, fetchURL: url, lineNumber: 0 });
// 0-based like the AST sites, so the navigation call is attributed
// to the component that contains it rather than to whatever spans
// line 0.
const lineNumber = content.slice(0, match.index).split('\n').length - 1;
allFetchCalls.push({ filePath, fetchURL: url, lineNumber });
}
}
}

View file

@ -20,6 +20,7 @@ import { isDev } from './utils/env.js';
import { PROCESS_DETECTION_BUDGET_DEFAULTS } from './process-detection-budget.js';
import { logger } from '../logger.js';
import { EnclosingCallableIndex } from './enclosing-callable.js';
// ============================================================================
// CONFIGURATION
// ============================================================================
@ -730,14 +731,10 @@ export const traceFromEntryPoint = (
export interface OutwardActionSite {
readonly filePath: string;
readonly lineNumber: number;
/** The parser's enclosing callable, null for module scope, or absent without AST attribution. */
readonly enclosingId?: string | null;
}
const CALLABLE_SINK_LABELS: ReadonlySet<NodeLabel> = new Set<NodeLabel>([
'Function',
'Method',
'Constructor',
]);
/**
* Functions that DO something outward — issue a request, run a query (R3-6).
*
@ -754,10 +751,9 @@ const CALLABLE_SINK_LABELS: ReadonlySet<NodeLabel> = new Set<NodeLabel>([
* is too coarse to end a trace on — every function in a file containing one
* would qualify. Attributing each site to the function whose range CONTAINS it
* turns the same facts into the function-level signal the walk needs, with no
* new extraction, no new relation pair, and no schema change.
*
* Innermost wins: a nested closure that performs the call is the sink, not the
* outer function that merely spans it.
* new extraction, no new relation pair, and no schema change. The containment
* rule lives in {@link EnclosingCallableIndex}, shared with the FETCHES consumer
* attribution.
*/
export function buildSinkFunctionSet(
graph: KnowledgeGraph,
@ -766,27 +762,10 @@ export function buildSinkFunctionSet(
const sinks = new Set<string>();
if (sites.length === 0) return sinks;
const byFile = new Map<string, { id: string; start: number; end: number }[]>();
for (const node of graph.iterNodes()) {
if (!CALLABLE_SINK_LABELS.has(node.label)) continue;
const props = node.properties as { filePath?: string; startLine?: number; endLine?: number };
if (typeof props.filePath !== 'string') continue;
if (typeof props.startLine !== 'number' || typeof props.endLine !== 'number') continue;
const entry = { id: node.id, start: props.startLine, end: props.endLine };
const list = byFile.get(props.filePath);
if (list === undefined) byFile.set(props.filePath, [entry]);
else list.push(entry);
}
const callables = new EnclosingCallableIndex(graph);
for (const site of sites) {
const candidates = byFile.get(site.filePath);
if (candidates === undefined) continue;
let best: { id: string; start: number; end: number } | undefined;
for (const c of candidates) {
if (site.lineNumber < c.start || site.lineNumber > c.end) continue;
if (best === undefined || c.end - c.start < best.end - best.start) best = c;
}
if (best !== undefined) sinks.add(best.id);
const id = callables.of(site);
if (id !== undefined) sinks.add(id);
}
return sinks;
}

View file

@ -34,6 +34,12 @@ export type CalleeTarget =
export interface FetchWrapperCall extends ExtractedFetchCall {
functionName: string;
target: CalleeTarget;
/**
* Start of the call node in tree coordinates (0-based, before `lineOffset`),
* so the parse worker can find the node again and record the callable that
* holds the call (#3644). `lineNumber` stays 1-based as its readers expect.
*/
callPosition: { row: number; column: number };
}
export interface ForwardedCallee {
callee: string;
@ -941,6 +947,7 @@ export function createFetchWrapperContext(
fetchURL,
lineNumber: call.startPosition.row + lineOffset + 1,
target,
callPosition: { row: call.startPosition.row, column: call.startPosition.column },
});
}
return calls;

View file

@ -23,6 +23,11 @@ ${unboundCallableQuery('definition.function')}
(class_declaration
name: (type_identifier) @name) @definition.class
; Named class expressions own members just like declarations. Anonymous
; expressions have no name and deliberately do not match this pattern.
(class
name: (type_identifier) @name) @definition.class
(abstract_class_declaration
name: (type_identifier) @name) @definition.class
@ -795,6 +800,9 @@ ${unboundCallableQuery('definition.function')}
(class_declaration
name: (identifier) @name) @definition.class
(class
name: (identifier) @name) @definition.class
(function_declaration
name: (identifier) @name) @definition.function

View file

@ -22,7 +22,7 @@ import Rust from 'tree-sitter-rust';
import PHP from 'tree-sitter-php';
import Ruby from 'tree-sitter-ruby';
import { requireVendoredGrammar } from '../../tree-sitter/vendored-grammars.js';
import { SupportedLanguages } from 'gitnexus-shared';
import { buildPositionIndex, SupportedLanguages, type PositionIndex } from 'gitnexus-shared';
import { getLanguageForFileContent, getProvider } from '../languages/index.js';
import {
getTreeSitterBufferSize,
@ -346,6 +346,12 @@ export interface ExtractedFetchCall {
filePath: string;
fetchURL: string;
lineNumber: number;
/**
* generateId of the callable whose body holds the call, from the AST;
* null for a confirmed top-level call, absent when attribution is unknown
* (text scans or callable forms the identity walk cannot name) (#3644).
*/
enclosingId?: string | null;
}
export interface FetchWrapperDef extends FetchWrapperFacts {
@ -1729,6 +1735,19 @@ const processFileGroup = (
sourceLineMap,
);
if (scopeExtractionFailed) (result.scopeExtractionFailures ??= []).push(file.path);
let requestScopeIndex: PositionIndex | undefined;
const requestEnclosingId = (node: SyntaxNode): string | null | undefined => {
const id = findEnclosingFunctionId(node, file.path, provider);
if (id !== null) return id;
if (parsedFile === undefined || scopeExtractionFailed) return undefined;
requestScopeIndex ??= buildPositionIndex(
parsedFile.scopes.filter((scope) => scope.kind === 'Function'),
);
const { row, column } = node.startPosition;
return requestScopeIndex.atPosition(file.path, mapRow(row) + 1, column) === undefined
? null
: undefined;
};
if (parsedFile !== undefined) {
// Capture-time side-channel (#1983): `extractParsedFile` just ran the
// provider's `emitScopeCaptures`, which (for C++ ADL/namespace marks,
@ -2031,10 +2050,12 @@ const processFileGroup = (
// Measured before this: 44 of 47 fetch calls in this repo pass a
// variable, so the sink signal was absent from 94% of them and
// sink-terminated flows could effectively never fire.
const fetchEnclosingId = requestEnclosingId(captureMap['route.fetch']);
result.fetchCalls.push({
filePath: file.path,
fetchURL: urlNode ? urlNode.text : '',
lineNumber: captureMap['route.fetch'].startPosition.row + lineOffset,
enclosingId: fetchEnclosingId,
});
continue;
}
@ -2045,10 +2066,12 @@ const processFileGroup = (
const method = captureMap['http_client.method']?.text;
const url = captureMap['http_client.url'].text;
if (method && HTTP_CLIENT_ONLY_METHODS.has(method) && url.startsWith('/')) {
const clientEnclosingId = requestEnclosingId(captureMap['http_client']);
result.fetchCalls.push({
filePath: file.path,
fetchURL: url,
lineNumber: captureMap['http_client'].startPosition.row + lineOffset,
enclosingId: clientEnclosingId,
});
}
continue;
@ -3309,7 +3332,13 @@ const processFileGroup = (
const calls = provider.extractFetchWrapperCalls?.(tree, parsedFile, lineOffset);
const reexports = provider.extractFetchWrapperReexports?.(tree, parsedFile, lineOffset);
const routeFacts = provider.extractRouteFacts?.(tree, parsedFile, lineOffset);
for (const call of calls ?? []) (result.fetchWrapperCalls ??= []).push(call);
for (const call of calls ?? []) {
// The wrapper call is a request site too (#3644): record the callable
// that holds it, as the direct fetch sites do.
const callNode = tree.rootNode.descendantForPosition(call.callPosition);
const callEnclosingId = requestEnclosingId(callNode);
(result.fetchWrapperCalls ??= []).push({ ...call, enclosingId: callEnclosingId });
}
for (const reexport of reexports ?? [])
(result.fetchWrapperReexports ??= []).push(reexport);
if (routeFacts)

View file

@ -202,6 +202,22 @@ function unrestorableBinaryFailure(
};
}
/**
* Materialize a skipped install-script copy before recording analyzer identity.
* This only copies the already-installed prebuilt; it never loads native code.
* checkLbugNative still owns load probing and diagnostics after identity capture.
*/
export function prepareLbugNativeBinary(overridePkgDir?: string): void {
try {
const pkgDir =
overridePkgDir ?? path.dirname(createRequire(import.meta.url).resolve('@ladybugdb/core'));
const binaryPath = path.join(pkgDir, 'lbugjs.node');
if (!fs.existsSync(binaryPath)) restorePrebuiltNativeBinary(pkgDir, binaryPath);
} catch {
// The normal check reports missing packages and failed recovery unchanged.
}
}
export function checkLbugNative(overridePkgDir?: string): NativeCheckResult {
let pkgDir: string;

View file

@ -904,9 +904,11 @@ export class WikiGenerator {
const overviewEnd = content.indexOf('### Architecture');
const overview =
overviewEnd > 0 ? content.slice(0, overviewEnd).trim() : content.slice(0, 800).trim();
childDocs.push(`#### ${child.name}\n${overview}`);
childDocs.push(`#### ${child.name} (\`${child.slug}.md\`)\n${overview}`);
} catch {
childDocs.push(`#### ${child.name}\n(Documentation not yet generated)`);
childDocs.push(
`#### ${child.name} (\`${child.slug}.md\`)\n(Documentation not yet generated)`,
);
}
}
@ -944,9 +946,9 @@ export class WikiGenerator {
const overviewEnd = content.indexOf('### Architecture');
const overview =
overviewEnd > 0 ? content.slice(0, overviewEnd).trim() : content.slice(0, 600).trim();
moduleSummaries.push(`#### ${node.name}\n${overview}`);
moduleSummaries.push(`#### ${node.name} (\`${node.slug}.md\`)\n${overview}`);
} catch {
moduleSummaries.push(`#### ${node.name}\n(Documentation pending)`);
moduleSummaries.push(`#### ${node.name} (\`${node.slug}.md\`)\n(Documentation pending)`);
}
}

View file

@ -6,9 +6,37 @@ const UNSAFE_EDGE_LABEL_RE = /[()[\]{}<>]/;
const UNSAFE_NODE_ID_RE = /[^A-Za-z0-9_-]/;
const NODE_ID_RE = /^[A-Za-z0-9_.:/()-]+$/;
const LINE_PREFIX_RE = /^(\s*(?:(?:[-A-Za-z0-9_]+)\s*:\s*)?)(.*)$/;
const EDGE_RE =
/(\s*(?:[ox])?(?:--+|==+|\.\.+)(?:[>|ox])?\|[^|\n]*\|(?:[>|ox])?|\s*(?:[ox])?(?:--+|==+|\.\.+)(?:[>|ox])?|\s*<--+>?\s*)/g;
const LINE_PREFIX_RE = /^(\s*)(.*)$/;
// One link between two node references, in the forms Mermaid accepts: a
// plain, thick or dotted link (`-->`, `===`, `-.->`), a piped label after it
// (`-->|text|`), or a label inside it (`-- text -->`, `== text ==>`,
// `-. text .->`). The labelled forms are matched whole, so their text is
// never taken for a node reference (#3705). Dots mean a link only in the
// dotted syntax: a plain run of dots is text.
//
// A labelled link opens with a bare `--`, `==` or `-.` followed by its text,
// with or without a space (`-- text -->`, `--text-->`). A complete link never
// opens one. Mermaid's lexer takes the longer match, so `--` followed by
// `-`, `>`, `x` or `o` is a link with a tail (`---`, `-->`, `--x`, `--o`),
// whatever comes after it: `A --xfile.ts --> B` is a chain of three nodes,
// and `file.ts` reaches the node sanitizer like any other reference.
const LINK_HEAD = '(?:--+|==+|-\\.+-?)';
const LABEL_OPENER = '(?:--|==|-\\.)(?![-=.>|xo])';
const EDGE_RE = new RegExp(
'(' +
[
// `-- text -->`, `--text-->`, `== text ==>`, `-. text .->`
`\\s*(?:[ox<])?${LABEL_OPENER}[^\\n]*?\\s*(?:--+|==+|\\.+-+)(?:[>ox])?`,
// `-->|text|`
`\\s*(?:[ox<])?${LINK_HEAD}(?:[>|ox])?\\|[^|\\n]*\\|(?:[>|ox])?`,
// `-->`, `---`, `-.->`, `==>`
`\\s*(?:[ox<])?${LINK_HEAD}(?:[>|ox])?`,
'\\s*<--+>?\\s*',
].join('|') +
')',
'g',
);
const EDGE_AT_RE = new RegExp(EDGE_RE.source, 'y');
export function sanitizeMermaidMarkdown(markdown: string): string {
return markdown.replace(MERMAID_FENCE_RE, (_match, diagram: string) => {
@ -17,50 +45,191 @@ export function sanitizeMermaidMarkdown(markdown: string): string {
}
export function sanitizeMermaidDiagram(diagram: string): string {
const frontmatter = diagram.match(/^\s*---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/)?.[0] ?? '';
const body = diagram.slice(frontmatter.length);
const prelude = body.match(/^(?:\s|%%\{[\s\S]*?\}%%|%%[^\n]*(?:\n|$))*/)?.[0] ?? '';
const content = body.slice(prelude.length);
if (!/^(?:graph|flowchart)\s/.test(content)) return diagram;
// Mask before splitting lines so multiline labels remain a single token.
const { masked, labels } = maskLabels(content);
const lines = masked.split('\n');
const usedIds = new Set<string>();
const labeledIds = new Set<string>();
for (const line of lines) {
sanitizeMermaidLine(
line,
(id, hasLabel) => {
usedIds.add(id);
if (hasLabel) labeledIds.add(id);
return id;
},
labeledIds,
labels,
);
}
const aliases = new Map<string, string>();
let nextAlias = 1;
const aliasFor = (id: string): string => {
if (!UNSAFE_NODE_ID_RE.test(id)) return id;
const existing = aliases.get(id);
if (existing) return existing;
const base = id.replace(/[^A-Za-z0-9_-]/g, '_').replace(/^_+|_+$/g, '') || 'node';
let base = id.replace(/[^A-Za-z0-9_-]/g, '_').replace(/^_+|_+$/g, '') || 'node';
if (
/^(?:style|classDef|class|click|linkStyle|direction|accTitle|accDescr|end)(?:-|$)/.test(base)
) {
base = `node_${base}`;
}
let alias = base;
while ([...aliases.values()].includes(alias)) {
while (usedIds.has(alias)) {
nextAlias += 1;
alias = `${base}_${nextAlias}`;
}
aliases.set(id, alias);
usedIds.add(alias);
return alias;
};
return diagram
.split('\n')
.map((line) => sanitizeMermaidLine(line, aliasFor))
.join('\n');
return (
frontmatter +
prelude +
lines
.map((line) => unmaskLabels(sanitizeMermaidLine(line, aliasFor, labeledIds, labels), labels))
.join('\n')
);
}
function sanitizeMermaidLine(line: string, aliasFor: (id: string) => string): string {
let sanitized = replaceLiteralLineBreaksInLabels(line);
sanitized = quoteUnsafeEdgeLabels(sanitized);
const prefixMatch = sanitized.match(LINE_PREFIX_RE);
if (!prefixMatch) return sanitized;
function sanitizeMermaidLine(
line: string,
aliasFor: (id: string, hasLabel?: boolean) => string,
labeledIds: ReadonlySet<string>,
labels: string[],
): string {
const prefixMatch = line.match(LINE_PREFIX_RE);
if (!prefixMatch) return line;
const prefix = prefixMatch[1];
const body = prefixMatch[2];
if (isDirectiveLine(body)) return sanitized;
const header = body.match(/^((?:graph|flowchart)\s+\w+\s*;)(.*)$/);
if (header) {
return prefix + header[1] + sanitizeMermaidLine(header[2], aliasFor, labeledIds, labels);
}
const reference = body.match(/^((?:style|class|click)\s+)([^\s]+)(.*)$/);
if (reference) {
const ids = reference[2].split(',').map((id) => aliasFor(id));
return prefix + reference[1] + ids.join(',') + reference[3];
}
const subgraph = body.match(/^(subgraph\s+)([A-Za-z0-9_.:/-]+)(\s*(?:\[.*\])?\s*)$/);
if (subgraph) {
const [, keyword, id, suffix] = subgraph;
const alias = aliasFor(id, true);
const label = alias !== id && !suffix.trim() ? `["${escapeMermaidLabel(id)}"]` : '';
return prefix + keyword + alias + label + suffix;
}
if (isDirectiveLine(body)) return line;
// Text inside quotes and inside node shapes is a label, not syntax: it is
// hidden from the split so a `...` or a `--` in it cannot read as a link,
// and from the node sanitizer so it cannot read as a node (#3705).
const parts = body.split(EDGE_RE);
if (parts.length === 1) return sanitized;
for (let i = 0; i < parts.length; i += 2) {
parts[i] = sanitizeNodeReference(parts[i], aliasFor);
for (let i = 0; i < parts.length; i += 1) {
if (i % 2 === 1) {
parts[i] = quoteUnsafeEdgeLabels(unmaskLabels(parts[i], labels));
} else {
const nodes = parts[i].split(/([&;])/);
for (let j = 0; j < nodes.length; j += 2) {
nodes[j] = sanitizeNodeReference(nodes[j], aliasFor, labels, labeledIds);
}
parts[i] = replaceLiteralLineBreaksInLabels(unmaskLabels(nodes.join(''), labels));
}
}
return prefix + parts.join('');
}
const MASK = '\u0000';
const MASK_RE = /\u0000(\d+)\u0000/g;
const OPENERS: Record<string, string> = { '[': ']', '(': ')', '{': '}' };
/**
* Replace the inside of every quoted string and every bracketed label with a
* placeholder, keeping the delimiters, so the shape of the line survives and
* the node sanitizer still sees where an inline label starts.
*/
function maskLabels(body: string): { masked: string; labels: string[] } {
const labels: string[] = [];
// Protect quoted link text before recognising links; a quoted arrow is text.
body = body.replace(/%%[^\n]*|"[^"]*"/g, (quoted) => {
if (quoted.startsWith('%%')) return quoted;
const index = labels.push(quoted.slice(1, -1)) - 1;
return '"' + MASK + index + MASK + '"';
});
let masked = '';
let i = 0;
while (i < body.length) {
if (body.startsWith('%%', i)) {
const end = body.indexOf('\n', i);
const next = end === -1 ? body.length : end;
masked += body.slice(i, next);
i = next;
continue;
}
// Consume complete links before looking for shapes. A `>` in List<T>
// belongs to the link label, not to an asymmetric node shape.
EDGE_AT_RE.lastIndex = i;
const edge = EDGE_AT_RE.exec(body);
if (edge) {
masked += edge[0];
i += edge[0].length;
continue;
}
const char = body[i];
const closer =
OPENERS[char] ?? (char === '>' && /[A-Za-z0-9_]/.test(body[i - 1] ?? '') ? ']' : undefined);
if (closer) {
const end = findLabelEnd(body, i, closer, char);
if (end === -1) {
masked += body.slice(i);
break;
}
masked += char + MASK + labels.length + MASK + body[end];
labels.push(unmaskLabels(body.slice(i + 1, end), labels));
i = end + 1;
continue;
}
masked += char;
i += 1;
}
return { masked, labels };
}
/** Index of the delimiter that closes the one at `start`, or -1. */
function findLabelEnd(body: string, start: number, closer: string, opener: string): number {
let depth = 0;
for (let i = start + 1; i < body.length; i += 1) {
const char = body[i];
if (char === '"') {
const quoteEnd = body.indexOf('"', i + 1);
if (quoteEnd === -1) return -1;
i = quoteEnd;
continue;
}
if (char === opener && opener !== '>') depth += 1;
else if (char === closer) {
if (depth === 0) return i;
depth -= 1;
}
}
return -1;
}
function unmaskLabels(masked: string, labels: string[]): string {
return masked.replace(MASK_RE, (_match, index: string) => labels[Number(index)] ?? '');
}
function replaceLiteralLineBreaksInLabels(line: string): string {
return line.replace(NODE_LABEL_RE, (label) => label.replace(/\\n/g, '<br/>'));
}
@ -79,22 +248,57 @@ function quoteUnsafeEdgeLabels(line: string): string {
});
}
function sanitizeNodeReference(segment: string, aliasFor: (id: string) => string): string {
const match = segment.match(/^(\s*)([A-Za-z0-9_.:/()-]+)(.*?)(\s*)$/);
// A masked, empty pair of parentheses right after an id: `doc()`, a
// call-shaped id the sanitizer has always repaired, not a round node. The
// member chain that may follow (`foo().bar`) belongs to the same id.
const EMPTY_PARENS_RE = /^\(\u0000(\d+)\u0000\)/;
const MEMBER_CHAIN_RE = /^(?:(?!:::)[A-Za-z0-9_.:/-])+/;
function sanitizeNodeReference(
segment: string,
aliasFor: (id: string, hasLabel?: boolean) => string,
labels: string[],
labeledIds: ReadonlySet<string>,
): string {
// The id stops where a node shape opens (`[`, `(`, `{`): `A(Start)` is the
// node `A` with a round label, and the label is already masked.
const match = segment.match(/^(\s*)((?:(?!:::)[A-Za-z0-9_.:/-])+)(.*?)(\s*)$/);
if (!match) return segment;
const [, leading, id, suffix, trailing] = match;
if (!NODE_ID_RE.test(id) || !UNSAFE_NODE_ID_RE.test(id)) return segment;
const hasInlineLabel =
suffix.trim().startsWith('[') || suffix.trim().startsWith('(') || suffix.trim().startsWith('{');
const leading = match[1];
const trailing = match[4];
let id = match[2];
let suffix = match[3];
for (;;) {
const emptyParens = suffix.match(EMPTY_PARENS_RE);
if (!emptyParens || labels[Number(emptyParens[1])] !== '') break;
id += '()';
suffix = suffix.slice(emptyParens[0].length);
const members = suffix.match(MEMBER_CHAIN_RE);
if (members) {
id += members[0];
suffix = suffix.slice(members[0].length);
}
}
if (!NODE_ID_RE.test(id)) return segment;
const hasInlineLabel = /^[\[({>]/.test(suffix.trim()) || suffix.trim().startsWith('@{');
const alias = aliasFor(id, hasInlineLabel);
if (!UNSAFE_NODE_ID_RE.test(id)) return segment;
if (hasInlineLabel) return `${leading}${aliasFor(id)}${suffix}${trailing}`;
const metadata = suffix.match(/^\s*@\{\u0000(\d+)\u0000\}/);
if (metadata) {
const content = labels[Number(metadata[1])];
if (!/(?:^|,)\s*label\s*:/.test(content.replace(/"[^"]*"|'[^']*'/g, ''))) {
suffix = suffix.replace(metadata[0], `@{ label: "${escapeMermaidLabel(id)}", ${content} }`);
}
}
if (hasInlineLabel || labeledIds.has(id)) return `${leading}${alias}${suffix}${trailing}`;
return `${leading}${aliasFor(id)}["${escapeMermaidLabel(id)}"]${suffix}${trailing}`;
return `${leading}${alias}["${escapeMermaidLabel(id)}"]${suffix}${trailing}`;
}
function escapeMermaidLabel(label: string): string {
return label.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
return label.replace(/"/g, '#quot;');
}
function isDirectiveLine(line: string): boolean {
@ -104,16 +308,10 @@ function isDirectiveLine(line: string): boolean {
trimmed.startsWith('%%') ||
trimmed.startsWith('graph ') ||
trimmed.startsWith('flowchart ') ||
trimmed.startsWith('sequenceDiagram') ||
trimmed.startsWith('classDiagram') ||
trimmed.startsWith('stateDiagram') ||
trimmed.startsWith('erDiagram') ||
trimmed.startsWith('journey') ||
trimmed.startsWith('gantt') ||
trimmed.startsWith('pie ') ||
trimmed.startsWith('mindmap') ||
trimmed.startsWith('timeline') ||
trimmed.startsWith('subgraph ') ||
/^(?:style|classDef|class|click|linkStyle|direction|accTitle|accDescr)(?:\s|:|$)/.test(
trimmed,
) ||
trimmed === 'end'
);
}

View file

@ -83,7 +83,7 @@ Shared execution flows: {{CROSS_PROCESSES}}
---
Write a concise overview of this module group. Explain its purpose, how the sub-modules fit together, and the key workflows that span them. Link to sub-module pages (e.g. \`[Sub-module Name](sub-module-slug.md)\`) rather than repeating their content. Use whatever structure fits best.`;
Write a concise overview of this module group. Explain its purpose, how the sub-modules fit together, and the key workflows that span them. Link to sub-module pages using the exact file names given (e.g. \`[Sub-module Name](sub-module-slug.md)\`) rather than repeating their content. Use whatever structure fits best.`;
// ─── Overview Prompt ──────────────────────────────────────────────────
@ -115,7 +115,7 @@ Key system flows: {{TOP_PROCESSES}}
---
Write a clear overview of this project: what it does, how it's architected, and the key end-to-end flows. Include a simple Mermaid architecture diagram (max 10 nodes, big-picture only). Link to module pages (e.g. \`[Module Name](module-slug.md)\`) naturally in the text rather than listing them in a table. If project config was provided, include brief setup instructions. Structure the page however reads best.`;
Write a clear overview of this project: what it does, how it's architected, and the key end-to-end flows. Include a simple Mermaid architecture diagram (max 10 nodes, big-picture only). Link to module pages naturally in the text using the exact file names given (e.g. \`[Module Name](module-slug.md)\`) rather than listing them in a table. If project config was provided, include brief setup instructions. Structure the page however reads best.`;
// ─── Template Substitution Helper ─────────────────────────────────────

View file

@ -1444,6 +1444,13 @@ interface ApiImpactRoute {
middlewareDetection?: 'partial';
middlewareNote?: string;
consumers: Array<{ name: string; file: string; accesses: string[]; attributionNote?: string }>;
/**
* Callers of the function that sends the request, one level up (#3644).
* Present only when a FETCHES edge names that function; an index built before
* the attribution has none. Direct consumer files and the handler file are
* left out, so an entry is a file the direct count does not already cover.
*/
indirectConsumers?: ApiImpactIndirectConsumer[];
mismatches?: Array<{
consumer: string;
field: string;
@ -1459,9 +1466,64 @@ interface ApiImpactRoute {
epistemic?: 'lower-bound';
unverifiedConsumers?: number;
boundaries?: string[];
/** Distinct files among `indirectConsumers`; not part of `riskLevel`. */
indirectConsumers?: number;
};
}
interface ApiImpactIndirectConsumer {
name: string;
file: string;
/** Name of the requesting function this caller reaches the route through. */
via: string;
}
/** A CALLS edge into one of the requesting functions a FETCHES reason names. */
interface RequestFunctionCaller {
viaId: string;
viaName: string;
name: string;
filePath: string;
}
/**
* The one-level callers of a route's requesting functions that the direct
* consumer list does not already cover. `undefined` when no consumer edge of
* the route names a requesting function, so the field stays absent instead of
* claiming an empty result the index could not have produced.
*/
function indirectConsumersOf(
route: {
filePath: string;
consumers: Array<{ filePath: string; viaSymbolIds?: string[] }>;
},
callersByVia: ReadonlyMap<string, RequestFunctionCaller[]>,
): ApiImpactIndirectConsumer[] | undefined {
const directFiles = new Set(route.consumers.map((c) => c.filePath));
const seen = new Set<string>();
const out: ApiImpactIndirectConsumer[] = [];
let attributed = false;
for (const consumer of route.consumers) {
for (const viaId of consumer.viaSymbolIds ?? []) {
attributed = true;
for (const caller of callersByVia.get(viaId) ?? []) {
if (caller.filePath === route.filePath || directFiles.has(caller.filePath)) continue;
const key = `${caller.filePath}\u0000${caller.name}\u0000${caller.viaName}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({ name: caller.name, file: caller.filePath, via: caller.viaName });
}
}
}
if (!attributed) return undefined;
return out.sort(
(a, b) =>
compareCodeUnits(a.file, b.file) ||
compareCodeUnits(a.name, b.name) ||
compareCodeUnits(a.via, b.via),
);
}
interface RouteRuntimeEvidence {
runtimeConfirmed: boolean;
runtimeSource: string | null;
@ -9739,6 +9801,7 @@ export class LocalBackend {
filePath: string;
accessedKeys?: string[];
fetchCount?: number;
viaSymbolIds?: string[];
}>;
}>
> {
@ -9797,6 +9860,7 @@ export class LocalBackend {
filePath: string;
accessedKeys?: string[];
fetchCount?: number;
viaSymbolIds?: string[];
}>;
}
>();
@ -9837,9 +9901,11 @@ export class LocalBackend {
});
}
if (consumerName && consumerFile) {
// Parse accessed keys from reason field: "fetch-url-match|keys:data,pagination|fetches:3"
// Parse accessed keys from reason field:
// "fetch-url-match|keys:data,pagination|fetches:3|via:Function:src/api.ts:getGrants"
let accessedKeys: string[] | undefined;
let fetchCount: number | undefined;
let viaSymbolIds: string[] | undefined;
if (fetchReason) {
const keysMatch = fetchReason.match(/\|keys:([^|]+)/);
if (keysMatch) {
@ -9849,12 +9915,17 @@ export class LocalBackend {
if (fetchesMatch) {
fetchCount = parseInt(fetchesMatch[1], 10);
}
// One field per requesting function (#3644); an id may hold any
// character but the separator.
const via = [...fetchReason.matchAll(/\|via:([^|]+)/g)].map((m) => m[1]);
if (via.length > 0) viaSymbolIds = via;
}
routeMap.get(id)!.consumers.push({
name: consumerName,
filePath: consumerFile,
...(accessedKeys ? { accessedKeys } : {}),
...(fetchCount && fetchCount > 1 ? { fetchCount } : {}),
...(viaSymbolIds ? { viaSymbolIds } : {}),
});
}
}
@ -9901,6 +9972,49 @@ export class LocalBackend {
return result;
}
/**
* Callers of the requesting functions a route's FETCHES reasons name, one
* CALLS hop up, keyed by the requesting function's id (#3644). One query for
* every route in the report. `undefined` when the query fails, so the caller
* leaves the field out rather than reporting an empty list it did not verify.
*/
private async fetchRequestFunctionCallers(
repoId: string,
viaIds: string[],
): Promise<Map<string, RequestFunctionCaller[]> | undefined> {
const result = new Map<string, RequestFunctionCaller[]>();
if (viaIds.length === 0) return result;
try {
const rows = await executeParameterized(
repoId,
`
MATCH (caller)-[r:CodeRelation]->(via)
WHERE r.type = 'CALLS' AND list_contains($viaIds, via.id)
RETURN DISTINCT via.id AS viaId, via.name AS viaName,
caller.name AS callerName, caller.filePath AS callerFile
`,
{ viaIds },
);
for (const row of rows) {
const viaId = row.viaId ?? row[0];
const viaName = row.viaName ?? row[1];
const name = row.callerName ?? row[2];
const filePath = row.callerFile ?? row[3];
if (!viaId || !viaName || !name || !filePath) continue;
let list = result.get(viaId);
if (!list) {
list = [];
result.set(viaId, list);
}
list.push({ viaId, viaName, name, filePath });
}
} catch (e) {
logQueryError('api_impact:indirect-consumers', e);
return undefined;
}
return result;
}
/**
* Same predicate as HTTP `getSourceAvailability`: full retention plus a live
* checkout. Meta is the graph directory so a published shared-store commit
@ -10307,6 +10421,15 @@ export class LocalBackend {
routes.map((r) => r.id),
);
// The FETCHES edge names the function that holds each request site; its
// callers, one level up, are consumers the file-level edge cannot see
// (#3644). Nothing to look up on an index built before that attribution.
const viaIds = new Set<string>();
for (const r of routes) {
for (const c of r.consumers) for (const id of c.viaSymbolIds ?? []) viaIds.add(id);
}
const callersByVia = await this.fetchRequestFunctionCallers(repo.lbugPath, [...viaIds]);
// Count verbs per handler from the FULL match (before the method filter) so a
// method-scoped query still flags a multi-verb handler's partial middleware.
const routeCountByHandler = new Map<string, number>();
@ -10360,6 +10483,9 @@ export class LocalBackend {
const flows = flowMap.get(r.id) || [];
const consumerCount = r.consumers.length;
const indirectConsumers =
callersByVia === undefined ? undefined : indirectConsumersOf(r, callersByVia);
const indirectFileCount = new Set(indirectConsumers?.map((c) => c.file)).size;
// Risk level heuristic
let riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
@ -10405,10 +10531,12 @@ export class LocalBackend {
}
: {}),
consumers,
...(indirectConsumers ? { indirectConsumers } : {}),
...(mismatches.length > 0 ? { mismatches } : {}),
executionFlows: flows,
impactSummary: {
directConsumers: consumerCount,
...(indirectConsumers ? { indirectConsumers: indirectFileCount } : {}),
affectedFlows: flows.length,
riskLevel,
...(warning ? { warning } : {}),

View file

@ -908,7 +908,7 @@ Returns routes that have both detected response keys AND consumers. Shows top-le
WHEN TO USE: BEFORE modifying any API route handler. Shows what consumers depend on, what response fields they access, what middleware protects the route, and what execution flows it triggers. Requires at least "route" or "file" parameter.
Risk levels: LOW (0-3 consumers), MEDIUM (4-9 or any mismatches), HIGH (10+ consumers or mismatches with 4+ consumers). Mismatches with confidence "low" indicate the consumer file fetches multiple routes — property attribution is approximate. When impactSummary.epistemic is "lower-bound", impactSummary.unverifiedConsumers more files pass the route's URL to a function not proven to send HTTP requests, so directConsumers is a floor; riskLevel counts proven consumers only.
Risk levels: LOW (0-3 consumers), MEDIUM (4-9 or any mismatches), HIGH (10+ consumers or mismatches with 4+ consumers). Mismatches with confidence "low" indicate the consumer file fetches multiple routes — property attribution is approximate. When impactSummary.epistemic is "lower-bound", impactSummary.unverifiedConsumers more files pass the route's URL to a function not proven to send HTTP requests, so directConsumers is a floor; riskLevel counts proven consumers only. "indirectConsumers" lists the callers of the function that sends the request, one level up, each with that function's name in "via"; impactSummary.indirectConsumers counts their distinct files. They are reported apart from the direct consumers and do not feed riskLevel. The field is absent on an index built before the requesting function was recorded.
Response shape is keyed on how many routes match, not on the data: exactly one match returns a single route object; two or more return { routes: [...], total: N }. The same URL can expose multiple HTTP verbs (e.g. GET and POST /api/orders are distinct routes that share the URL), so a bare-URL lookup may return the wrapped form — every route object carries its own "method" so verbs are distinguishable. Pass "method" to narrow to one verb; the single-object shape is returned only when exactly one route remains after filtering — a substring route/file match spanning several URLs can still return the wrapped form. A URL/file that exists but has no route for the given verb returns an error. Each route's "method" is the literal "*" for method-agnostic routes (e.g. Django function views), which match any "method" selector, or null for method-less routes (filesystem, Laravel resource), which never match a selector. Every route also carries "runtimeEvidence"; treat it as authoritative only when runtimeEvidence.confirmed is true. Combines route_map, shape_check, and impact data.`,
annotations: READ_ONLY_TOOL_ANNOTATIONS,

View file

@ -55,6 +55,24 @@ export const API_IMPACT_SEED_DATA = [
CREATE (fn)-[:CodeRelation {type: 'HANDLES_ROUTE', confidence: 1.0, reason: 'nextjs-app-router', step: 0}]->(r)`,
`MATCH (fn:Function), (r:Route) WHERE fn.id = 'func:secure-POST' AND r.id = 'Route:/api/secure'
CREATE (fn)-[:CodeRelation {type: 'HANDLES_ROUTE', confidence: 1.0, reason: 'nextjs-app-router', step: 0}]->(r)`,
// ─── Indirect consumers (#3644) ────────────────────────────────────
// backend-client.ts is the file that sends the request; the edge names the
// function holding the site. App and Header call that function without ever
// mentioning the URL. useMulti calls it too, but already fetches the route
// itself, so it stays a direct consumer only.
`CREATE (f:File {id: 'file:services/backend-client.ts', name: 'backend-client.ts', filePath: 'services/backend-client.ts', content: 'export const fetchSecure = () => fetch("/api/secure")'})`,
`CREATE (fn:Function {id: 'func:fetchSecure', name: 'fetchSecure', filePath: 'services/backend-client.ts', startLine: 1, endLine: 3, isExported: true, content: 'export const fetchSecure = () => fetch("/api/secure")', description: 'Secure request function'})`,
`CREATE (fn:Function {id: 'func:App', name: 'App', filePath: 'App.tsx', startLine: 1, endLine: 20, isExported: true, content: 'export function App() { fetchSecure() }', description: 'App root'})`,
`CREATE (fn:Function {id: 'func:Header', name: 'Header', filePath: 'components/Header.tsx', startLine: 1, endLine: 12, isExported: true, content: 'export function Header() { fetchSecure() }', description: 'Header'})`,
`MATCH (a:File), (r:Route) WHERE a.id = 'file:services/backend-client.ts' AND r.id = 'Route:/api/secure'
CREATE (a)-[:CodeRelation {type: 'FETCHES', confidence: 0.9, reason: 'fetch-url-match|via:func:fetchSecure', step: 0}]->(r)`,
`MATCH (a:Function), (b:Function) WHERE a.id = 'func:App' AND b.id = 'func:fetchSecure'
CREATE (a)-[:CodeRelation {type: 'CALLS', confidence: 1.0, reason: 'direct', step: 0}]->(b)`,
`MATCH (a:Function), (b:Function) WHERE a.id = 'func:Header' AND b.id = 'func:fetchSecure'
CREATE (a)-[:CodeRelation {type: 'CALLS', confidence: 1.0, reason: 'direct', step: 0}]->(b)`,
`MATCH (a:Function), (b:Function) WHERE a.id = 'func:useMulti' AND b.id = 'func:fetchSecure'
CREATE (a)-[:CodeRelation {type: 'CALLS', confidence: 1.0, reason: 'direct', step: 0}]->(b)`,
];
export const API_IMPACT_FTS_INDEXES: FTSIndexDef[] = [

View file

@ -0,0 +1,4 @@
// A wrapper around fetch: its callers reach the route through it.
export function apiFetch(path: string) {
return fetch(path);
}

View file

@ -0,0 +1,5 @@
import { fetchRepos } from './client';
export async function loadApp() {
return fetchRepos();
}

View file

@ -0,0 +1,15 @@
// The one function that sends the request; its callers never mention the URL.
export async function fetchRepos() {
const res = await fetch('/api/repos');
return res.json();
}
// A helper defined on the same line as the request: the request still belongs
// to fetchFile, not to decode.
export function fetchFile(path: string) {
const decode = (res: Response) => res.json(); return fetch(`/api/file?path=${path}`).then(decode);
}
export function describeClient() {
return 'repos client';
}

View file

@ -0,0 +1,3 @@
import { fetchRepos } from './client';
export const refreshHeader = () => fetchRepos();

View file

@ -0,0 +1,15 @@
import express from 'express';
export function createServer() {
const app = express();
app.get('/api/repos', (_req, res) => {
res.json({ repos: [], total: 0 });
});
app.get('/api/file', (req, res) => {
res.json({ content: '', path: String(req.query.path) });
});
app.get('/api/stats', (_req, res) => {
res.json({ files: 0, symbols: 0 });
});
return app;
}

View file

@ -0,0 +1,5 @@
import { fetchStats } from './stats';
export function renderStatsPanel() {
return fetchStats();
}

View file

@ -0,0 +1,6 @@
import { apiFetch } from './api';
// The request goes through the wrapper, and a helper shares its line again.
export function fetchStats() {
const pick = (res: Response) => res.json(); return apiFetch('/api/stats').then(pick);
}

View file

@ -0,0 +1,5 @@
import { fetchFile } from './client';
export function openFile(path: string) {
return fetchFile(path);
}

View file

@ -98,6 +98,37 @@ withTestLbugDB(
});
});
// #3644: the callers of the function that sends the request, one level up.
describe('api_impact indirect consumers', () => {
it('lists the callers of the requesting function apart from the direct consumers', async () => {
const result = await backend.callTool('api_impact', { route: '/api/secure' });
expect(result.indirectConsumers).toEqual([
{ name: 'App', file: 'App.tsx', via: 'fetchSecure' },
{ name: 'Header', file: 'components/Header.tsx', via: 'fetchSecure' },
]);
expect(result.impactSummary.indirectConsumers).toBe(2);
// useMulti calls fetchSecure too, but it fetches the route itself.
expect(result.consumers.map((c: any) => c.file)).toEqual(
expect.arrayContaining(['hooks/useMulti.ts', 'services/backend-client.ts']),
);
});
it('does not let indirect consumers change the risk level', async () => {
const result = await backend.callTool('api_impact', { route: '/api/secure' });
expect(result.impactSummary.directConsumers).toBe(2);
expect(result.impactSummary.riskLevel).toBe('LOW');
});
it('leaves the field out when no consumer edge names a requesting function', async () => {
const result = await backend.callTool('api_impact', { route: '/api/grants' });
expect(result).not.toHaveProperty('indirectConsumers');
expect(result.impactSummary).not.toHaveProperty('indirectConsumers');
});
});
// ─── Test 2: Mismatch detection ────────────────────────────────────
describe('mismatch detection e2e', () => {

View file

@ -0,0 +1,172 @@
/**
* #3644, end to end: a real analyze of a small repository, then `api_impact`
* through LocalBackend. The requesting functions sit in src/client.ts; their
* callers never mention the URL. One request shares its line with a helper
* (`const decode = …; return fetch(…).then(decode);`), which a line-only
* attribution handed to the helper, dropping the callers of fetchFile.
*/
import { execFileSync } from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { runFullAnalysis } from '../../src/core/run-analyze.js';
import { LocalBackend } from '../../src/mcp/local/local-backend.js';
import { commitAll, initGitRepo } from '../helpers/temp-git-repo.js';
import { createTempDir } from '../helpers/test-db.js';
const FIXTURE = path.resolve(
__dirname,
'..',
'fixtures',
'lang-resolution',
'api-impact-indirect-consumers',
);
describe('api_impact indirect consumers through a real analyze (#3644)', () => {
let temp: Awaited<ReturnType<typeof createTempDir>>;
let repo: string;
let backend: LocalBackend;
beforeAll(async () => {
temp = await createTempDir();
const root = await fs.realpath(temp.dbPath);
const userHome = path.join(root, 'user-home');
await fs.mkdir(userHome);
vi.stubEnv('HOME', userHome);
vi.stubEnv('USERPROFILE', userHome);
vi.stubEnv('GITNEXUS_HOME', path.join(root, 'home'));
vi.stubEnv('GITNEXUS_STORAGE_PATH', undefined);
vi.stubEnv('GITNEXUS_STORAGE_ROOT', undefined);
vi.stubEnv('GITNEXUS_SHARED_STORE', 'off');
vi.stubEnv('GITNEXUS_CONTENT_RETENTION', 'full');
vi.stubEnv('GITNEXUS_LBUG_EXTENSION_INSTALL', 'load-only');
vi.stubEnv('GITNEXUS_WAL_MANUAL_CHECKPOINT', '1');
repo = path.join(root, 'repo');
await fs.cp(FIXTURE, repo, { recursive: true });
// A top-level request can share a line with a callable without belonging
// to it. Also put a callable on the next line: wrapper sites use 1-based
// lines, which must not make that callable an indirect consumer either.
for (const [kind, request] of [
['fetch', "fetch('/api/top-level-fetch')"],
['wrapper', "apiFetch('/api/top-level-wrapper')"],
['client', "axios.head('/api/top-level-client')"],
]) {
await fs.writeFile(
path.join(repo, 'src', `top-level-${kind}.ts`),
[
"import { apiFetch } from './api';",
"import axios from 'axios';",
`export function decode(res: Response) { return res.json(); } ${request};`,
"export function afterRequest() { return 'local'; }",
].join('\n'),
);
await fs.writeFile(
path.join(repo, 'src', `local-${kind}.ts`),
[
`import { decode, afterRequest } from './top-level-${kind}';`,
'export function parseLocal(res: Response) { return decode(res); }',
'export function describeLocal() { return afterRequest(); }',
].join('\n'),
);
}
await fs.writeFile(
path.join(repo, 'src', 'lambda_client.py'),
"import requests\ncheck_health = lambda: requests.head('/api/lambda')\n",
);
for (const [kind, source] of [
[
'declaration',
"export const select = (r: Response) => r.json(), data = fetch('/api/top-level-declaration');",
],
[
'argument',
"export const select = wrap((r: Response) => r.json(), fetch('/api/top-level-argument'));",
],
]) {
await fs.writeFile(path.join(repo, 'src', `top-level-${kind}.ts`), source);
await fs.writeFile(
path.join(repo, 'src', `local-${kind}.ts`),
`import { select } from './top-level-${kind}';\nexport function parseLocal(r: Response) { return select(r); }\n`,
);
}
await fs.writeFile(
path.join(repo, 'src', 'top-level-server.ts'),
[
"import express from 'express';",
'const app = express();',
"app.get('/api/lambda', (_req, res) => res.json({ ok: true }));",
...['fetch', 'wrapper', 'client', 'declaration', 'argument'].map(
(kind) => `app.get('/api/top-level-${kind}', (_req, res) => res.json({ ok: true }));`,
),
].join('\n'),
);
await fs.writeFile(path.join(repo, '.gitignore'), '.gitnexus/\n');
initGitRepo(repo);
execFileSync('git', ['config', 'commit.gpgsign', 'false'], { cwd: repo });
commitAll(repo, 'indirect consumers fixture');
await runFullAnalysis(repo, { skipAgentsMd: true, skipSkills: true }, { onProgress: () => {} });
backend = new LocalBackend();
await backend.init();
}, 180_000);
afterAll(async () => {
await backend?.dispose();
vi.unstubAllEnvs();
await temp?.cleanup();
});
async function impact(route: string) {
const result = await backend.callTool('api_impact', { route, repo });
expect(result).not.toHaveProperty('error');
return result;
}
it('lists the callers of the requesting function, apart from the direct consumer', async () => {
const result = await impact('/api/repos');
expect(result.consumers.map((c: { file: string }) => c.file)).toEqual(['src/client.ts']);
expect(result.indirectConsumers).toEqual([
{ name: 'loadApp', file: 'src/app.ts', via: 'fetchRepos' },
{ name: 'refreshHeader', file: 'src/header.ts', via: 'fetchRepos' },
]);
expect(result.impactSummary.directConsumers).toBe(1);
expect(result.impactSummary.indirectConsumers).toBe(2);
expect(result.impactSummary.riskLevel).toBe('LOW');
});
it('keeps the callers of a request that shares its line with a helper', async () => {
const result = await impact('/api/file');
expect(result.indirectConsumers).toEqual([
{ name: 'openFile', file: 'src/viewer.ts', via: 'fetchFile' },
]);
expect(result.impactSummary.indirectConsumers).toBe(1);
});
it('keeps the callers of a request made through a wrapper function', async () => {
const result = await impact('/api/stats');
expect(result.consumers.map((c: { file: string }) => c.file)).toEqual(['src/stats.ts']);
expect(result.indirectConsumers).toEqual([
{ name: 'renderStatsPanel', file: 'src/stats-panel.ts', via: 'fetchStats' },
]);
});
it.each(['fetch', 'wrapper', 'client', 'declaration', 'argument'])(
'does not invent indirect consumers for a module-scope %s request',
async (kind) => {
const result = await impact(`/api/top-level-${kind}`);
expect(result.consumers.map((c: { file: string }) => c.file)).toEqual([
`src/top-level-${kind}.ts`,
]);
expect(result).not.toHaveProperty('indirectConsumers');
expect(result.impactSummary).not.toHaveProperty('indirectConsumers');
},
);
it('keeps attribution when a callable definition is known but the enclosing-id walk cannot name it', async () => {
const result = await impact('/api/lambda');
expect(result.consumers.map((c: { file: string }) => c.file)).toEqual(['src/lambda_client.py']);
// An attributed request with no callers reports an empty list; a request
// incorrectly classified as module scope omits the field altogether.
expect(result.indirectConsumers).toEqual([]);
expect(result.impactSummary.indirectConsumers).toBe(0);
});
});

View file

@ -0,0 +1,514 @@
import { describe, expect, it } from 'vitest';
import fs from 'node:fs/promises';
import path from 'node:path';
import {
closeLbug,
executeQuery,
initLbug,
loadGraphToLbug,
} from '../../src/core/lbug/lbug-adapter.js';
import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js';
import {
loadParseCache,
loadParseCacheChunk,
pruneCache,
saveParseCache,
} from '../../src/storage/parse-cache.js';
import {
clearParsedFileStore,
durableChunkHasShards,
getDurableParsedFileDir,
loadDurableParsedFileIndex,
loadParsedFilesForPaths,
pruneAndSaveDurableParsedFileStore,
} from '../../src/storage/parsedfile-store.js';
import { runtimeParseIdentity } from '../helpers/runtime-parse-identity.js';
import { createTempDir } from '../helpers/test-db.js';
import { parseFilesWithWorkers } from '../helpers/worker-parse.js';
import { findDanglingEdges } from './resolvers/helpers.js';
describe('named class-expression owners through the real parse worker', () => {
it.each([
['ts', '#0'],
['tsx', '#0'],
['vue', ''],
])(
'keeps method-local type alias owners aligned with their members in .%s',
async (extension, methodSuffix) => {
const source = `class Named {
m() { type Shape = { p: number; f(): void }; }
}
const Expr = class Internal {
m() { type Local = { value: string; run(): void }; }
};`;
const file = `alias.${extension}`;
const { graph } = await parseFilesWithWorkers([
{
path: file,
content: extension === 'vue' ? `<script setup lang="ts">\n${source}\n</script>` : source,
},
]);
for (const [name, property, method] of [
['Shape', 'p', 'f'],
['Local', 'value', 'run'],
]) {
const owner = `TypeAlias:${file}:${name}`;
expect(graph.getNode(owner)).toBeDefined();
const members = graph.relationships.filter(
(edge) =>
edge.sourceId === owner && (edge.type === 'HAS_PROPERTY' || edge.type === 'HAS_METHOD'),
);
expect(members.map((edge) => edge.targetId).sort()).toEqual([
`Method:${file}:${name}.${method}${methodSuffix}`,
`Property:${file}:${name}.${property}`,
]);
for (const edge of members) expect(graph.getNode(edge.targetId)).toBeDefined();
}
expect(
graph.relationships.filter(
(edge) =>
(edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY') &&
(!graph.getNode(edge.sourceId) || !graph.getNode(edge.targetId)),
),
).toEqual([]);
},
);
it('persists method-local type alias member relationships through native COPY', async () => {
const temp = await createTempDir();
try {
await fs.writeFile(
path.join(temp.dbPath, 'alias.ts'),
'class Named { m() { type Shape = { p: number; f(): void }; } }',
);
const result = await runPipelineFromRepo(temp.dbPath, () => {}, { workerPoolSize: 1 });
expect(result.usedWorkerPool).toBe(true);
await initLbug(path.join(temp.dbPath, 'lbug'), { skipFts: true });
await loadGraphToLbug(result.graph, temp.dbPath, path.join(temp.dbPath, 'storage'));
const aliases = await executeQuery('MATCH (a:TypeAlias) RETURN a.id AS id');
expect(aliases.map((row) => row.id)).toEqual(['TypeAlias:alias.ts:Shape']);
const members = await executeQuery(
"MATCH (a:TypeAlias)-[r:CodeRelation]->(m) WHERE r.type IN ['HAS_METHOD', 'HAS_PROPERTY'] RETURN a.id AS owner, m.id AS member, r.type AS type ORDER BY type",
);
expect(members).toEqual([
{
owner: 'TypeAlias:alias.ts:Shape',
member: 'Method:alias.ts:Shape.f#0',
type: 'HAS_METHOD',
},
{
owner: 'TypeAlias:alias.ts:Shape',
member: 'Property:alias.ts:Shape.p',
type: 'HAS_PROPERTY',
},
]);
} finally {
await closeLbug();
await temp.cleanup();
}
});
it.each(['ts', 'tsx', 'js', 'mjs'])(
'resolves a declaration shadowing an outer class inside an expression in .%s',
async (extension) => {
const temp = await createTempDir();
try {
await fs.writeFile(
path.join(temp.dbPath, `shadow.${extension}`),
'class Local {} const A = class Outer { m() { class Local {} return new Local(); } };',
);
const result = await runPipelineFromRepo(temp.dbPath, () => {}, { workerPoolSize: 1 });
const locals = result.graph.nodes.filter(
(node) => node.label === 'Class' && node.properties.name === 'Local',
);
expect(locals).toHaveLength(2);
const inner = locals.find((node) => node.id.includes('.Local'))!;
expect(inner).toBeDefined();
const method = result.graph.nodes.find(
(node) => node.label === 'Method' && node.properties.name === 'm',
)!;
const calls = result.graph.relationships.filter(
(edge) => edge.type === 'CALLS' && edge.sourceId === method.id,
);
expect(calls.map((edge) => edge.targetId)).toEqual([inner.id]);
} finally {
await temp.cleanup();
}
},
);
it.each(['jsx', 'vue'])('preserves owners for the shared .%s provider', async (extension) => {
const source = 'const X = class Named { status = 500; run() { return this.status; } };';
const { graph } = await parseFilesWithWorkers([
{
path: `shared.${extension}`,
content: extension === 'vue' ? `<script setup lang="ts">\n${source}\n</script>` : source,
},
]);
const owner = graph.nodes.find(
(node) => node.label === 'Class' && node.properties.name === 'Named',
);
expect(owner).toBeDefined();
const edges = graph.relationships.filter(
(edge) =>
edge.sourceId === owner!.id && (edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY'),
);
expect(edges.map((edge) => graph.getNode(edge.targetId)?.properties.name).sort()).toEqual([
'run',
'status',
]);
});
it.each(['ts', 'js'])(
'keeps declaration and anonymous-expression controls in .%s',
async (extension) => {
const { graph } = await parseFilesWithWorkers([
{
path: `control.${extension}`,
content:
'class Control { status = 1; run() {} } const Anonymous = class { value = 2; method() {} };',
},
]);
expect(
graph.nodes.filter((node) => node.label === 'Class').map((node) => node.properties.name),
).toEqual(['Control']);
const owner = graph.getNode(`Class:control.${extension}:Control`);
expect(owner).toBeDefined();
const edges = graph.relationships.filter((edge) => edge.sourceId === owner!.id);
expect(edges.map((edge) => graph.getNode(edge.targetId)?.properties.name).sort()).toEqual([
'run',
'status',
]);
},
);
it.each(['ts', 'tsx', 'js', 'mjs'])(
'retains the class and its members in .%s',
async (extension) => {
const { graph } = await parseFilesWithWorkers([
{
path: `mock.${extension}`,
content: `vi.mock('api', () => ({
ApiError: class ApiError extends Error {
status = 500;
messageForUser() { return 'Failed'; }
},
}));`,
},
]);
const owner = graph.nodes.find(
(node) => node.label === 'Class' && node.properties.name === 'ApiError',
);
expect(owner).toBeDefined();
expect(owner!.properties).toMatchObject({
filePath: `mock.${extension}`,
startLine: 1,
endLine: 4,
});
const edges = graph.relationships.filter(
(edge) => edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY',
);
expect(edges).toHaveLength(2);
expect(edges.map((edge) => graph.getNode(edge.targetId)?.properties.name).sort()).toEqual([
'messageForUser',
'status',
]);
expect(
graph.nodes.find((node) => node.properties.name === 'messageForUser')!.properties
.parameterCount,
).toBe(0);
expect(
graph.nodes.find((node) => node.properties.name === 'status')!.properties.isStatic,
).toBe(false);
for (const edge of edges) {
expect(edge.sourceId).toBe(owner!.id);
expect(graph.getNode(edge.sourceId)).toBeDefined();
expect(graph.getNode(edge.targetId)).toBeDefined();
}
},
);
it('retains a TypeScript constructor parameter property on its expression owner', async () => {
const { graph } = await parseFilesWithWorkers([
{
path: 'parameter.ts',
content: `vi.mock('api', () => ({
ApiError: class ApiError extends Error {
constructor(public readonly status: number) { super('HTTP ' + status); }
},
}));`,
},
]);
const owner = graph.nodes.find(
(node) => node.label === 'Class' && node.properties.name === 'ApiError',
);
expect(owner).toBeDefined();
const property = graph.nodes.find(
(node) => node.label === 'Property' && node.properties.name === 'status',
);
expect(property).toBeDefined();
expect(property!.id).toBe('Property:parameter.ts:ApiError@1:12.status');
expect(graph.relationships).toContainEqual(
expect.objectContaining({
type: 'HAS_PROPERTY',
sourceId: owner!.id,
targetId: property!.id,
}),
);
for (const edge of graph.relationships.filter(
(edge) => edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY',
)) {
expect(graph.getNode(edge.sourceId)).toBeDefined();
expect(graph.getNode(edge.targetId)).toBeDefined();
}
});
it.each(['ts', 'tsx', 'js', 'mjs'])(
'keeps nested expression members distinct from declarations in .%s',
async (extension) => {
const { graph } = await parseFilesWithWorkers([
{
path: `nested.${extension}`,
content: `class ApiError { status = 200; messageForUser() { return 'outer'; } }
class Holder {
nested = class ApiError { status = 500; messageForUser() { return 'inner'; } };
}`,
},
]);
const owners = graph.nodes.filter(
(node) => node.label === 'Class' && node.properties.name === 'ApiError',
);
expect(owners).toHaveLength(2);
expect(new Set(owners.map((node) => node.id)).size).toBe(2);
const memberIds = new Set<string>();
for (const owner of owners) {
const edges = graph.relationships.filter(
(edge) =>
edge.sourceId === owner.id &&
(edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY'),
);
expect(edges.map((edge) => graph.getNode(edge.targetId)?.properties.name).sort()).toEqual([
'messageForUser',
'status',
]);
edges.forEach((edge) => memberIds.add(edge.targetId));
}
expect(memberIds.size).toBe(4);
for (const edge of graph.relationships.filter(
(edge) => edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY',
)) {
expect(graph.getNode(edge.sourceId)).toBeDefined();
expect(graph.getNode(edge.targetId)).toBeDefined();
}
},
);
it.each(['ts', 'tsx', 'js', 'mjs'])(
'distinguishes same-named expressions in sibling methods in .%s',
async (extension) => {
const { graph } = await parseFilesWithWorkers([
{
path: `siblings.${extension}`,
content: `class Holder {
first() { return class Local { status = 1; run() {} }; }
second() { return class Local { status = 2; run() {} }; }
}`,
},
]);
const owners = graph.nodes.filter(
(node) => node.label === 'Class' && node.properties.name === 'Local',
);
expect(owners).toHaveLength(2);
const targets = new Set<string>();
for (const owner of owners) {
const edges = graph.relationships.filter(
(edge) =>
edge.sourceId === owner.id &&
(edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY'),
);
expect(edges.map((edge) => graph.getNode(edge.targetId)?.properties.name).sort()).toEqual([
'run',
'status',
]);
for (const edge of edges) {
targets.add(edge.targetId);
const member = graph.getNode(edge.targetId)!;
expect(member.properties.startLine).toBe(owner.properties.startLine);
}
}
expect(targets.size).toBe(4);
},
);
it.each(['ts', 'tsx', 'js', 'mjs'])(
'resolves expression members and keeps self names internal in .%s',
async (extension) => {
const temp = await createTempDir();
try {
await fs.writeFile(
path.join(temp.dbPath, `self.${extension}`),
`class Holder { child = class Child { p=1; m(){return this.p;} }; }
const X = class Named { static s() {} m() { Named.s(); } };
Named.s();`,
);
const result = await runPipelineFromRepo(temp.dbPath, () => {}, { workerPoolSize: 1 });
const member = (ownerName: string, memberName: string) => {
const owner = result.graph.nodes.find(
(node) => node.label === 'Class' && node.properties.name === ownerName,
)!;
expect(owner).toBeDefined();
const edge = result.graph.relationships.find(
(edge) =>
edge.sourceId === owner.id &&
(edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY') &&
result.graph.getNode(edge.targetId)?.properties.name === memberName,
);
expect(edge).toBeDefined();
return edge!.targetId;
};
expect(result.graph.relationships).toContainEqual(
expect.objectContaining({
type: 'ACCESSES',
sourceId: member('Child', 'm'),
targetId: member('Child', 'p'),
}),
);
const staticId = member('Named', 's');
const calls = result.graph.relationships.filter(
(edge) => edge.type === 'CALLS' && edge.targetId === staticId,
);
expect(calls).toHaveLength(1);
expect(calls[0]!.sourceId).toBe(member('Named', 'm'));
expect(
findDanglingEdges(result, ['HAS_METHOD', 'HAS_PROPERTY', 'CALLS', 'ACCESSES']),
).toEqual([]);
} finally {
await temp.cleanup();
}
},
);
it('preserves owners through the full pipeline, both durable caches, and native COPY', async () => {
const temp = await createTempDir();
const repo = path.join(temp.dbPath, 'repo');
const storage = path.join(temp.dbPath, 'storage');
const identity = await runtimeParseIdentity();
const extensions = ['ts', 'tsx', 'js', 'mjs'];
const source = `class ApiError { status = 200; messageForUser() { return 'outer'; } }
vi.mock('api', () => ({
ApiError: class MockError extends Error { status = 500; messageForUser() { return 'mock'; } },
}));
class Holder {
nested = class ApiError { status = 501; messageForUser() { return 'inner'; } };
}`;
try {
await fs.mkdir(repo);
for (const extension of extensions)
await fs.writeFile(path.join(repo, `mock.${extension}`), source);
const coldCache = await loadParseCache(storage, identity, storage);
const cold = await runPipelineFromRepo(repo, () => {}, {
workerPoolSize: 1,
parseCache: coldCache,
});
expect(cold.usedWorkerPool).toBe(true);
expect(cold.reparsedFileCount).toBe(4);
expect(cold.parseCacheHitFileCount).toBe(0);
expect(cold.scopeExtractionFailures).toEqual([]);
const assertOwners = (result: typeof cold) => {
expect(findDanglingEdges(result, ['HAS_METHOD', 'HAS_PROPERTY'])).toEqual([]);
for (const extension of extensions) {
for (const name of ['ApiError', 'MockError@2:12', 'Holder.ApiError@5:11']) {
const ownerId = `Class:mock.${extension}:${name}`;
expect(result.graph.getNode(ownerId)).toBeDefined();
const edges = result.graph.relationships.filter(
(edge) =>
edge.sourceId === ownerId &&
(edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY'),
);
expect(
edges.map((edge) => result.graph.getNode(edge.targetId)?.properties.name).sort(),
).toEqual(['messageForUser', 'status']);
expect(edges.map((edge) => edge.targetId).sort()).toEqual([
`Method:mock.${extension}:${name}.messageForUser#0`,
`Property:mock.${extension}:${name}.status`,
]);
}
}
};
assertOwners(cold);
pruneCache(coldCache, coldCache.usedKeys);
const keys = await saveParseCache(storage, coldCache);
await pruneAndSaveDurableParsedFileStore(
getDurableParsedFileDir(storage),
identity.base,
new Set(keys),
);
await clearParsedFileStore(storage);
const durable = await loadDurableParsedFileIndex(
getDurableParsedFileDir(storage),
identity.base,
);
for (const [key, wanted] of durable)
expect(await durableChunkHasShards(storage, key, wanted)).toBe(true);
const paths = new Set([...durable.values()].flatMap((paths) => [...paths]));
expect([...paths].sort()).toEqual(extensions.map((extension) => `mock.${extension}`).sort());
const parsed = await loadParsedFilesForPaths(storage, paths);
expect(parsed.size).toBe(4);
for (const file of parsed.values()) {
expect(file.scopes.filter((scope) => scope.kind === 'Class')).toHaveLength(4);
expect(
file.localDefs
.filter((definition) => definition.type === 'Property')
.map((definition) => definition.qualifiedName)
.sort(),
).toEqual([
'ApiError.status',
'Holder.ApiError@5:11.status',
'Holder.nested',
'MockError@2:12.status',
]);
}
const warmCache = await loadParseCache(storage, identity, storage);
const chunks = await Promise.all(
[...warmCache.onDiskKeys!].map((key) => loadParseCacheChunk(warmCache, key)),
);
expect(chunks.length).toBeGreaterThan(0);
// ParsedFiles must come from their durable shards, not worker-result chunks.
expect(
chunks.flatMap((chunk) => chunk ?? []).flatMap((part) => part.parsedFiles ?? []),
).toEqual([]);
const warm = await runPipelineFromRepo(repo, () => {}, {
workerPoolSize: 1,
parseCache: warmCache,
});
expect(warm.usedWorkerPool).toBe(false);
expect(warm.reparsedFileCount).toBe(0);
expect(warm.parseCacheHitFileCount).toBe(4);
expect(warm.scopeExtractionFailures).toEqual([]);
assertOwners(warm);
const members = (result: typeof cold) =>
result.graph.relationships
.filter((edge) => edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY')
.map((edge) => `${edge.type}:${edge.sourceId}->${edge.targetId}`)
.sort();
expect(members(warm)).toEqual(members(cold));
await initLbug(path.join(temp.dbPath, 'lbug'), { skipFts: true });
const loaded = await loadGraphToLbug(warm.graph, repo, storage);
expect(loaded.warnings).toEqual([]);
expect(loaded.skippedRels).toBe(0);
const rows = await executeQuery(
"MATCH (c:Class)-[r:CodeRelation]->(m) WHERE r.type IN ['HAS_METHOD', 'HAS_PROPERTY'] RETURN c.id AS owner, m.id AS member, r.type AS type",
);
expect(rows.map((row) => `${row.type}:${row.owner}->${row.member}`).sort()).toEqual(
members(warm),
);
const classes = await executeQuery('MATCH (c:Class) RETURN c.id AS id');
expect(classes).toHaveLength(16);
} finally {
await closeLbug();
await clearParsedFileStore(storage);
await temp.cleanup();
}
}, 120000);
});

View file

@ -2,6 +2,38 @@ import { describe, expect, it } from 'vitest';
import { parseFilesWithWorkers } from '../helpers/worker-parse.js';
describe('qualified class lookups', () => {
it('preserves nested names with and without file-level package scopes', async () => {
const { graph, model } = await parseFilesWithWorkers([
{
path: 'nested.ts',
content:
'class Outer { make() { class Inner { value = 1; run() { return this.value; } } return Inner; } }',
},
{
path: 'Nested.java',
content: 'package example.models; class Outer { class Inner {} }',
},
{
path: 'nested.rb',
content: 'module Root\n class Outer\n class Inner\n end\n end\nend\n',
},
]);
for (const name of ['Outer.Inner', 'example.models.Outer.Inner', 'Root.Outer.Inner']) {
expect(model.types.lookupClassByQualifiedName(name)).toHaveLength(1);
}
const ownerId = 'Class:nested.ts:Outer.Inner';
expect(graph.getNode(ownerId)).toBeDefined();
const members = graph.relationships.filter(
(edge) =>
edge.sourceId === ownerId && (edge.type === 'HAS_METHOD' || edge.type === 'HAS_PROPERTY'),
);
expect(members.map((edge) => graph.getNode(edge.targetId)?.properties.name).sort()).toEqual([
'run',
'value',
]);
for (const edge of members) expect(graph.getNode(edge.targetId)).toBeDefined();
});
it('derives canonical dot-separated names from namespaces, packages, and modules', async () => {
const { model } = await parseFilesWithWorkers([
{

View file

@ -0,0 +1,63 @@
import { describe, it, expect, beforeAll } from 'vitest';
import path from 'path';
import {
FIXTURES,
getNodesByLabelFull,
getRelationships,
runPipelineFromRepo,
type PipelineResult,
} from './helpers.js';
// The file that sends the request is the only one a FETCHES edge can name. The
// files that call its request function never mention the URL, so `api_impact`
// reaches them through the function the edge's reason records (#3644).
describe('FETCHES consumer attribution through the pipeline (#3644)', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'api-impact-indirect-consumers'),
() => {},
);
}, 60000);
it('names the function holding the fetch site on the file-level edge', () => {
expect(
getNodesByLabelFull(result, 'Function').some(
(node) => node.name === 'fetchRepos' && node.properties.filePath === 'src/client.ts',
),
).toBe(true);
const edges = getRelationships(result, 'FETCHES').filter((e) => e.target === '/api/repos');
expect(edges.map((e) => [e.sourceFilePath, e.rel.reason])).toEqual([
['src/client.ts', 'fetch-url-match|fetches:2|via:Function:src/client.ts:fetchRepos'],
]);
});
it('attributes a request to the function that makes it, not to a helper on the same line', () => {
// `const decode = (res) => res.json(); return fetch(...).then(decode);` on one
// line: by span alone the helper would win, and the callers of fetchFile
// would vanish from the report.
const edges = getRelationships(result, 'FETCHES').filter((e) => e.target === '/api/file');
expect(edges.map((e) => [e.sourceFilePath, e.rel.reason])).toEqual([
['src/client.ts', 'fetch-url-match|fetches:2|via:Function:src/client.ts:fetchFile'],
]);
});
it('attributes a request made through a wrapper to the function that calls the wrapper', () => {
// apiFetch('/api/stats') inside fetchStats, with a helper on the same line:
// the site comes from the wrapper-call capture, not from a bare fetch().
const edges = getRelationships(result, 'FETCHES').filter((e) => e.target === '/api/stats');
expect(edges.map((e) => [e.sourceFilePath, e.rel.reason])).toEqual([
['src/stats.ts', 'fetch-url-match|fetches:2|via:Function:src/stats.ts:fetchStats'],
]);
});
it('reaches the callers one level up through CALLS edges into that function', () => {
const callers = getRelationships(result, 'CALLS')
.filter((e) => e.target === 'fetchRepos' && e.targetFilePath === 'src/client.ts')
.map((e) => `${e.sourceFilePath}:${e.source}`)
.sort();
expect(callers).toEqual(['src/app.ts:loadApp', 'src/header.ts:refreshHeader']);
});
});

View file

@ -274,18 +274,19 @@ describe('workflows that need the web UI install it themselves', () => {
expect(steps.filter(installsWeb)).toHaveLength(0);
});
it('packaged install smoke skips a pre-pack CLI build and keeps a 20-minute budget', () => {
it('packaged install smoke skips a pre-pack CLI build and allows the manager smoke budget', () => {
const job = ciJobs['packaged-install-smoke'];
const setup = job?.steps?.find((step) => step.uses === './.github/actions/setup-gitnexus');
expect(job?.['timeout-minutes']).toBe(20);
expect(job?.['timeout-minutes']).toBe(30);
expect(setup?.with?.['lifecycle-scripts']).toBe('false');
expect(setup?.with?.build).toBeUndefined();
});
it('exercises the reported native ARM64 runtime alongside Windows and Linux x64', () => {
it('exercises the reported native ARM64 runtime alongside all three desktop OSes', () => {
const job = ciJobs['packaged-install-smoke'];
expect(job?.strategy?.matrix?.os).toEqual([
'windows-latest',
'macos-latest',
'ubuntu-latest',
'ubuntu-24.04-arm',
]);
@ -300,6 +301,18 @@ describe('workflows that need the web UI install it themselves', () => {
expect(String(assertArch?.run)).toContain("process.version, 'v22.23.1'");
});
it('indexes the freshly packed tarball with every manager on all three desktop OSes', () => {
const steps = ciJobs['packaged-install-smoke']?.steps ?? [];
const packIdx = stepIndex(steps, (step) => step.name === 'Pack gitnexus tarball');
const smokeIdx = stepIndex(
steps,
(step) => step.name === 'Index the PR tarball with npm, pnpm, and Bun',
);
expect(smokeIdx).toBeGreaterThan(packIdx);
expect(steps[smokeIdx]?.if).toBe("matrix.os != 'ubuntu-24.04-arm'");
expect(String(steps[smokeIdx]?.run)).toContain('node scripts/smoke-package-managers.mjs');
});
it('keeps consumer compilation guards after packing and checks both npm lockfile paths', () => {
const steps = ciJobs['packaged-install-smoke']?.steps ?? [];
const packIdx = stepIndex(steps, (step) => step.name === 'Pack gitnexus tarball');

View file

@ -2685,6 +2685,55 @@ describe('LocalBackend.callTool', () => {
expect(result.error).toContain('No routes found');
});
it('api_impact lists the callers of the requesting function as indirect consumers (#3644)', async () => {
const routeRow = (consumerName: string, consumerFile: string, fetchReason: string) => ({
routeId: 'Route:/api/grants',
routeName: '/api/grants',
handlerFile: 'app/api/grants/route.ts',
responseKeys: ['data'],
errorKeys: [],
middleware: [],
runtimeConfirmed: false,
runtimeSource: null,
runtimeStatus: null,
consumerName,
consumerFile,
fetchReason,
});
const via = 'Function:src/services/client.ts:fetchGrants';
const caller = (callerName: string, callerFile: string) => ({
viaId: via,
viaName: 'fetchGrants',
callerName,
callerFile,
});
(executeParameterized as any).mockImplementation(async (_repo: string, cypher: string) => {
if (cypher.includes("r.type = 'CALLS'")) {
return [
caller('Header', 'src/Header.tsx'),
caller('App', 'src/App.tsx'),
// Already a direct consumer file, and the handler file: neither is indirect.
caller('GrantsList', 'src/GrantsList.tsx'),
caller('GET', 'app/api/grants/route.ts'),
];
}
return [
routeRow('client.ts', 'src/services/client.ts', `fetch-url-match|via:${via}`),
routeRow('GrantsList', 'src/GrantsList.tsx', 'fetch-url-match|keys:data'),
];
});
const result = await backend.callTool('api_impact', { route: '/api/grants' });
expect(result.indirectConsumers).toEqual([
{ name: 'App', file: 'src/App.tsx', via: 'fetchGrants' },
{ name: 'Header', file: 'src/Header.tsx', via: 'fetchGrants' },
]);
expect(result.impactSummary.directConsumers).toBe(2);
expect(result.impactSummary.indirectConsumers).toBe(2);
expect(result.impactSummary.riskLevel).toBe('LOW');
});
it('api_impact detects mismatches and bumps risk level', async () => {
(executeParameterized as any).mockResolvedValue([
{

View file

@ -74,38 +74,50 @@ describe('segmentCjkSpans', () => {
expect(outputBytes).toBeLessThan(expectedBytes * 1.05);
});
it('scales linearly on realistic interleaved CJK/non-CJK content, not quadratically', () => {
// Regression guard: an earlier implementation indexed into the growing
// accumulated output string once per run boundary, which forces V8 to
// flatten its internal rope representation on every access — O(n^2) on
// content that alternates CJK and non-CJK runs (ordinary source code
// with inline CJK comments, the feature's actual target). A single-run
// input (like the growth-factor test above) never exercises this path,
// since there is only one run boundary regardless of size.
const unit = '采购订单自动审批流程 // approve the request after manual review\n';
const build = (totalBytes: number) => unit.repeat(Math.ceil(totalBytes / unit.length));
it.skipIf(!process.env.GITNEXUS_BENCH)(
'scales linearly on realistic interleaved CJK/non-CJK content, not quadratically',
() => {
// Regression guard: an earlier implementation indexed into the growing
// accumulated output string once per run boundary, which forces V8 to
// flatten its internal rope representation on every access — O(n^2) on
// content that alternates CJK and non-CJK runs (ordinary source code
// with inline CJK comments, the feature's actual target). A single-run
// input (like the growth-factor test above) never exercises this path,
// since there is only one run boundary regardless of size.
const unit = '采购订单自动审批流程 // approve the request after manual review\n';
const build = (totalBytes: number) => unit.repeat(Math.ceil(totalBytes / unit.length));
const small = build(64 * 1024);
const large = build(512 * 1024); // 8x the input size
const small = build(64 * 1024);
const large = build(512 * 1024); // 8x the input size
const timeOf = (input: string) => {
const start = performance.now();
segmentCjkSpans(input);
return performance.now() - start;
};
const timeOf = (input: string) => {
const start = performance.now();
segmentCjkSpans(input);
return performance.now() - start;
};
// Warm up the JIT before measuring either size.
timeOf(small);
timeOf(large);
// run-benchmarks.ts discovers this opt-in test and runs it serially.
// Sample both sizes after warmup: one scheduler pause must not look like
// the quadratic regression this guard is intended to catch.
const smallSamples: number[] = [];
const largeSamples: number[] = [];
for (let sample = 0; sample < 10; sample++) {
const smallMs = timeOf(small);
const largeMs = timeOf(large);
if (sample >= 3) {
smallSamples.push(smallMs);
largeSamples.push(largeMs);
}
}
const smallMs = Math.min(...smallSamples);
const largeMs = Math.min(...largeSamples);
const smallMs = timeOf(small);
const largeMs = timeOf(large);
// Linear scaling means ~8x input takes roughly ~8x time, with headroom
// for noise; quadratic scaling would mean ~64x time. 20x catches the
// regression while tolerating CI timing variance.
expect(largeMs).toBeLessThan(Math.max(smallMs, 1) * 20);
});
// Linear scaling means ~8x input takes roughly ~8x time, with headroom
// for noise; quadratic scaling would mean ~64x time. 20x catches the
// regression while tolerating CI timing variance.
expect(largeMs).toBeLessThan(Math.max(smallMs, 1) * 20);
},
);
});
describe('containsCjkIdeograph', () => {

View file

@ -134,6 +134,26 @@ describe('cross-platform shard partition', () => {
expect(Math.max(...loads)).toBeLessThanOrEqual(17 * 60);
});
it('leaves watchdog headroom for the October 23 native-suite timeout', () => {
// Windows run 39934695864: shard 10 timed out with Kotlin still pending.
// Use its completed suite times, plus the October 25 green run 40172490240
// for query-symbol-integrity and incremental-dirty-recovery. These measured
// costs must remain independent of the scheduling hints being tested.
const observed: Readonly<Record<string, number>> = {
'test/integration/rename-provider-objective-c.test.ts': 385.174,
'test/integration/rename-provider-csharp.test.ts': 265.99,
'test/integration/incremental-method-integrity.test.ts': 144.974,
'test/integration/fts-repair-warm-session.test.ts': 61.015,
'test/integration/query-symbol-integrity.test.ts': 33.892,
'test/unit/incremental-dirty-recovery.test.ts': 127.8,
};
const floor = weightOf('test/unmeasured.test.ts');
const loads = allShards(ALL_CROSS_PLATFORM, SHARD_TOTAL).map((files) =>
files.reduce((sum, file) => sum + Math.max(weightOf(file), (observed[file] ?? 0) + floor), 0),
);
expect(Math.max(...loads)).toBeLessThanOrEqual(17 * 60);
});
it('keeps each shard within a shard of the ideal weight', () => {
const shards = allShards(ALL_CROSS_PLATFORM, SHARD_TOTAL);
const weights = shards.map(shardWeight);

View file

@ -0,0 +1,188 @@
/**
* The FETCHES edge is file-level; its reason names the callables whose spans
* contain the request sites, one `|via:<id>` field each, so `api_impact` can
* follow their CALLS edges one level up (#3644). The containment rule is the
* R3-6 sink rule: innermost span wins, lines 0-based on both sides.
*/
import { describe, it, expect } from 'vitest';
import type { NodeLabel } from 'gitnexus-shared';
import { createKnowledgeGraph } from '../../src/core/graph/graph.js';
import type { KnowledgeGraph } from '../../src/core/graph/types.js';
import { processNextjsFetchRoutes } from '../../src/core/ingestion/call-processor.js';
import type { ExtractedFetchCall } from '../../src/core/ingestion/workers/parse-worker.js';
const FILE = 'src/client.ts';
const REPOS = new Map([['/api/repos', ['GET /api/repos']]]);
function addCallable(
graph: KnowledgeGraph,
id: string,
startLine: number,
endLine: number,
label: NodeLabel = 'Function',
filePath = FILE,
): void {
graph.addNode({
id,
label,
properties: { name: id.split(':').pop() ?? id, filePath, startLine, endLine },
});
}
const site = (
lineNumber: number,
filePath = FILE,
fetchURL = '/api/repos',
): ExtractedFetchCall => ({
filePath,
fetchURL,
lineNumber,
});
const reasons = (graph: KnowledgeGraph): string[] =>
[...graph.iterRelationshipsByType('FETCHES')].map((r) => r.reason);
describe('FETCHES consumer attribution (#3644)', () => {
it('names the callable whose span contains the request site', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:fetchRepos', 2, 6);
processNextjsFetchRoutes(graph, [site(3)], REPOS);
expect(reasons(graph)).toEqual(['fetch-url-match|via:Function:src/client.ts:fetchRepos']);
});
it('keeps one edge per file and route, naming every requesting callable in code-unit order', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:refresh', 10, 14);
addCallable(graph, 'Function:src/client.ts:fetchRepos', 2, 6);
// Two sites in one file for one route used to collide on the edge id, with
// the first one winning; now they share the edge.
processNextjsFetchRoutes(graph, [site(12), site(3)], REPOS);
const edges = [...graph.iterRelationshipsByType('FETCHES')];
expect(edges).toHaveLength(1);
expect(edges[0].sourceId).toBe('File:src/client.ts');
expect(edges[0].targetId).toBe('Route:GET /api/repos');
// `fetches:` counts the file's matching call sites, as before.
expect(edges[0].reason).toBe(
'fetch-url-match|fetches:2|via:Function:src/client.ts:fetchRepos|via:Function:src/client.ts:refresh',
);
});
it('picks the innermost callable, a method or constructor as well as a function', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:outer', 10, 30);
addCallable(graph, 'Function:src/client.ts:outer.inner', 12, 14);
addCallable(graph, 'Method:src/client.ts:Client.load', 40, 45, 'Method');
addCallable(graph, 'Constructor:src/client.ts:Client.constructor', 50, 52, 'Constructor');
addCallable(graph, 'Class:src/client.ts:Client', 38, 60, 'Class');
processNextjsFetchRoutes(graph, [site(13), site(42), site(51)], REPOS);
expect(reasons(graph)).toEqual([
'fetch-url-match|fetches:3' +
'|via:Constructor:src/client.ts:Client.constructor' +
'|via:Function:src/client.ts:outer.inner' +
'|via:Method:src/client.ts:Client.load',
]);
});
it('leaves the reason as before when no callable contains the site', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:fetchRepos', 2, 6);
// A module-scope call, and a file the graph has no spans for.
processNextjsFetchRoutes(graph, [site(50), site(3, 'src/other.ts')], REPOS);
expect(reasons(graph)).toEqual(['fetch-url-match', 'fetch-url-match']);
});
it('does not attribute a site to a callable of another file at the same lines', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:fetchRepos', 2, 6);
addCallable(graph, 'Function:src/other.ts:load', 2, 6, 'Function', 'src/other.ts');
processNextjsFetchRoutes(graph, [site(3, 'src/other.ts')], REPOS);
expect(reasons(graph)).toEqual(['fetch-url-match|via:Function:src/other.ts:load']);
});
it('appends the attribution after the multi-fetch count', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:fetchRepos', 2, 6);
addCallable(graph, 'Function:src/client.ts:readFile', 10, 14);
const routes = new Map([
['/api/repos', ['GET /api/repos']],
['/api/file', ['GET /api/file']],
]);
processNextjsFetchRoutes(graph, [site(3), site(12, FILE, '/api/file')], routes);
expect(reasons(graph)).toEqual([
'fetch-url-match|fetches:2|via:Function:src/client.ts:fetchRepos',
'fetch-url-match|fetches:2|via:Function:src/client.ts:readFile',
]);
});
it('appends the attribution after the accessed keys', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:fetchRepos', 2, 6);
const contents = new Map([[FILE, 'const { repos, total } = await res.json();']]);
processNextjsFetchRoutes(graph, [site(3)], REPOS, contents);
expect(reasons(graph)).toEqual([
'fetch-url-match|keys:repos,total|via:Function:src/client.ts:fetchRepos',
]);
});
it('prefers the enclosing callable the parser recorded over the innermost span', () => {
const graph = createKnowledgeGraph();
// `const decode = (res) => res.json(); return fetch('/api/repos').then(decode);`
// on one line: the helper's span is smaller, but the request belongs to fetchRepos.
addCallable(graph, 'Function:src/client.ts:fetchRepos', 2, 4);
addCallable(graph, 'Function:src/client.ts:fetchRepos.decode', 3, 3);
processNextjsFetchRoutes(
graph,
[{ ...site(3), enclosingId: 'Function:src/client.ts:fetchRepos' }],
REPOS,
);
expect(reasons(graph)).toEqual(['fetch-url-match|via:Function:src/client.ts:fetchRepos']);
});
it('falls back to the span when the recorded callable is not in the graph', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:fetchRepos', 2, 6);
processNextjsFetchRoutes(
graph,
[{ ...site(3), enclosingId: 'Function:src/client.ts:skipped' }],
REPOS,
);
expect(reasons(graph)).toEqual(['fetch-url-match|via:Function:src/client.ts:fetchRepos']);
});
it('does not use a same-line callable when the parser identified module scope', () => {
const graph = createKnowledgeGraph();
addCallable(graph, 'Function:src/client.ts:decode', 3, 3);
processNextjsFetchRoutes(graph, [{ ...site(3), enclosingId: null }], REPOS);
expect(reasons(graph)).toEqual(['fetch-url-match']);
});
it('leaves out an id that contains the field separator rather than splitting the reason', () => {
const graph = createKnowledgeGraph();
// A type tag from an overload collision can carry a union type.
addCallable(graph, 'Function:src/client.ts:load#1~string|number', 2, 6);
processNextjsFetchRoutes(graph, [site(3)], REPOS);
expect(reasons(graph)).toEqual(['fetch-url-match']);
});
});

View file

@ -14,9 +14,11 @@ import { describe, it, expect } from 'vitest';
function parseReasonField(fetchReason: string | null): {
accessedKeys?: string[];
fetchCount?: number;
viaSymbolIds?: string[];
} {
let accessedKeys: string[] | undefined;
let fetchCount: number | undefined;
let viaSymbolIds: string[] | undefined;
if (fetchReason) {
const keysMatch = fetchReason.match(/\|keys:([^|]+)/);
if (keysMatch) {
@ -26,10 +28,13 @@ function parseReasonField(fetchReason: string | null): {
if (fetchesMatch) {
fetchCount = parseInt(fetchesMatch[1], 10);
}
const via = [...fetchReason.matchAll(/\|via:([^|]+)/g)].map((m) => m[1]);
if (via.length > 0) viaSymbolIds = via;
}
return {
...(accessedKeys ? { accessedKeys } : {}),
...(fetchCount && fetchCount > 1 ? { fetchCount } : {}),
...(viaSymbolIds ? { viaSymbolIds } : {}),
};
}
@ -80,6 +85,25 @@ describe('fetch reason field parsing', () => {
expect(result.accessedKeys).not.toContain('pagination|fetches:3');
expect(result.accessedKeys).toEqual(['data', 'pagination']);
});
// #3644: one field per requesting function; ids carry ':' and '#'.
it('parses every via field, after keys and fetches', () => {
const result = parseReasonField(
'fetch-url-match|keys:data|fetches:2|via:Function:src/api.ts:getGrants#0|via:Method:src/api.ts:Api.list#1',
);
expect(result.accessedKeys).toEqual(['data']);
expect(result.fetchCount).toBe(2);
expect(result.viaSymbolIds).toEqual([
'Function:src/api.ts:getGrants#0',
'Method:src/api.ts:Api.list#1',
]);
});
it('leaves viaSymbolIds out of a reason written before the attribution', () => {
const result = parseReasonField('fetch-url-match|keys:data,pagination|fetches:3');
expect(result.viaSymbolIds).toBeUndefined();
expect(result.accessedKeys).toEqual(['data', 'pagination']);
});
});
describe('confidence derivation from fetchCount', () => {

View file

@ -179,6 +179,7 @@ for (const [name, grammar, provider] of grammars) {
fetchURL: '/api/one',
lineNumber: 12,
target: { kind: 'unresolved' },
callPosition: { row: 1, column: 8 },
},
{
filePath: 'consumer.ts',
@ -186,6 +187,7 @@ for (const [name, grammar, provider] of grammars) {
fetchURL: '/api/two',
lineNumber: 13,
target: { kind: 'member' },
callPosition: { row: 2, column: 8 },
},
{
filePath: 'consumer.ts',
@ -193,6 +195,7 @@ for (const [name, grammar, provider] of grammars) {
fetchURL: '/api/three',
lineNumber: 14,
target: { kind: 'member' },
callPosition: { row: 3, column: 8 },
},
{
filePath: 'consumer.ts',
@ -200,6 +203,7 @@ for (const [name, grammar, provider] of grammars) {
fetchURL: '/api/four',
lineNumber: 15,
target: { kind: 'unresolved' },
callPosition: { row: 4, column: 8 },
},
]);
});

View file

@ -26,7 +26,14 @@ function definition(id: string, overrides: Partial<FetchWrapperDef> = {}): Fetch
}
function call(target: CalleeTarget, functionName = 'request'): FetchWrapperCall {
return { filePath: 'client.ts', functionName, target, fetchURL: '/api/items', lineNumber: 1 };
return {
filePath: 'client.ts',
functionName,
target,
fetchURL: '/api/items',
lineNumber: 1,
callPosition: { row: 0, column: 0 },
};
}
describe('fetch wrapper target classification', () => {

View file

@ -1,7 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
import { createAnalyzerLbugLazyAction, createLazyAction } from '../../src/cli/lazy-action.js';
const { checkLbugNativeMock } = vi.hoisted(() => ({
const { checkLbugNativeMock, prepareLbugNativeBinaryMock } = vi.hoisted(() => ({
prepareLbugNativeBinaryMock: vi.fn(),
checkLbugNativeMock: vi.fn<typeof import('../../src/core/lbug/native-check.js').checkLbugNative>(
() => ({ ok: true }),
),
@ -9,6 +10,7 @@ const { checkLbugNativeMock } = vi.hoisted(() => ({
vi.mock('../../src/core/lbug/native-check.js', () => ({
checkLbugNative: checkLbugNativeMock,
prepareLbugNativeBinary: prepareLbugNativeBinaryMock,
}));
describe('createLazyAction', () => {
@ -64,6 +66,11 @@ describe('createLbugLazyAction', () => {
describe('createAnalyzerLbugLazyAction', () => {
it('captures identity before probing native code or importing the analyzer graph', async () => {
const events: string[] = [];
prepareLbugNativeBinaryMock.mockImplementationOnce(() => events.push('binary-prepared'));
checkLbugNativeMock.mockImplementationOnce(() => {
events.push('native-probed');
return { ok: true };
});
const receipt = { schemaVersion: 4 };
const run = vi.fn(async () => undefined);
const identityLoader = vi.fn(async () => {
@ -89,7 +96,13 @@ describe('createAnalyzerLbugLazyAction', () => {
await action('repo', { force: true });
expect(events).toEqual(['identity-module', 'receipt-captured', 'analyzer-module']);
expect(events).toEqual([
'binary-prepared',
'identity-module',
'receipt-captured',
'native-probed',
'analyzer-module',
]);
expect(run).toHaveBeenCalledWith(receipt, 'repo', { force: true });
});

View file

@ -2,7 +2,11 @@ import { describe, it, expect } from 'vitest';
import os from 'os';
import path from 'path';
import fs from 'fs/promises';
import { checkLbugNative, glibcTooOldMessage } from '../../src/core/lbug/native-check.js';
import {
checkLbugNative,
glibcTooOldMessage,
prepareLbugNativeBinary,
} from '../../src/core/lbug/native-check.js';
describe('checkLbugNative', () => {
it('returns ok:true when the real @ladybugdb/core binary is present', () => {
@ -72,6 +76,24 @@ describe('checkLbugNative', () => {
return { root, pkgDir, subPkgDir };
}
it('prepares a skipped lifecycle copy without loading the binary before identity capture', async () => {
const { root, pkgDir, subPkgDir } = await prebuiltFixture('lbug-prepare-');
try {
// Deliberately not a native addon: preparation must only copy bytes.
const bytes = Buffer.from('prebuilt fixture');
await fs.writeFile(path.join(subPkgDir, 'lbugjs.node'), bytes);
expect(() => prepareLbugNativeBinary(pkgDir)).not.toThrow();
expect(await fs.readFile(path.join(pkgDir, 'lbugjs.node'))).toEqual(bytes);
// An installed binary must not be replaced on a later preparation pass.
await fs.writeFile(path.join(subPkgDir, 'lbugjs.node'), 'different prebuilt');
prepareLbugNativeBinary(pkgDir);
expect(await fs.readFile(path.join(pkgDir, 'lbugjs.node'))).toEqual(bytes);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it('restores a missing lbugjs.node from the prebuilt platform sub-package', async () => {
// The "install lifecycle script was skipped" case is recoverable without a
// network fetch: the binary is already on disk in the per-platform optional

View file

@ -781,6 +781,40 @@ describe('sink-terminated flows (R3-6)', () => {
expect(sinks.has('func:inner')).toBe(true);
expect(sinks.has('func:outer')).toBe(false);
});
it('prefers the enclosing callable the parser recorded over the innermost span', () => {
const graph = createKnowledgeGraph();
graph.addNode({
id: 'func:outer',
label: 'Function',
properties: { name: 'outer', filePath: 'src/a.ts', startLine: 1, endLine: 30 },
});
graph.addNode({
id: 'func:helper',
label: 'Function',
properties: { name: 'helper', filePath: 'src/a.ts', startLine: 15, endLine: 15 },
});
const sinks = buildSinkFunctionSet(graph, [
{ filePath: 'src/a.ts', lineNumber: 15, enclosingId: 'func:outer' },
]);
expect(sinks.has('func:outer')).toBe(true);
expect(sinks.has('func:helper')).toBe(false);
});
it('does not make a same-line callable a sink for a known module-scope request', () => {
const graph = createKnowledgeGraph();
graph.addNode({
id: 'func:decode',
label: 'Function',
properties: { name: 'decode', filePath: 'src/a.ts', startLine: 3, endLine: 3 },
});
const sinks = buildSinkFunctionSet(graph, [
{ filePath: 'src/a.ts', lineNumber: 3, enclosingId: null },
]);
expect([...sinks]).toEqual([]);
});
});
describe('process selection diversity (R2-3)', () => {

View file

@ -1,4 +1,4 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('node:child_process', () => ({
execFileSync: vi.fn(),
@ -39,7 +39,15 @@ const PLUGIN_CJS = path.resolve(
interface CjsModule {
formatAnalyzeCommand: (
o?: { embeddings?: boolean; indexOnly?: boolean },
deps?: { npmMajor?: number | null; pnpmMajor?: number | null; pnpmMinor?: number | null },
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;
@ -53,6 +61,7 @@ interface CjsModule {
npmMajor?: number | null;
pnpmMajor?: number | null;
pnpmPresent?: boolean;
pnpmRuns?: boolean;
bunPresent?: boolean;
bunRuns?: boolean;
},
@ -78,15 +87,23 @@ interface CjsModule {
// `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.
// `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(() => {
delete process.env.GITNEXUS_INVOCATION;
vi.unstubAllEnvs();
});
it('standardizes the invocation ref on gitnexus@latest', () => {
@ -131,7 +148,7 @@ describe('resolve-analyze-cmd.cjs (canonical invocation resolver)', () => {
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');
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11, pnpmRuns: true })).toBe('pnpm');
});
it('auto-selects npx on npm 10 even when pnpm is on PATH', () => {
@ -143,7 +160,7 @@ describe('resolve-analyze-cmd.cjs (canonical invocation resolver)', () => {
// 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');
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', () => {
@ -159,7 +176,7 @@ describe('resolve-analyze-cmd.cjs (canonical invocation resolver)', () => {
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
// 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');
});
@ -238,7 +255,9 @@ describe('resolve-analyze-cmd.cjs (canonical invocation resolver)', () => {
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');
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)', () => {
@ -250,7 +269,9 @@ describe('resolve-analyze-cmd.cjs (canonical invocation resolver)', () => {
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');
expect(
cjs.resolveInvocationMode(probe, { npmMajor: null, pnpmRuns: true, bunRuns: true }),
).toBe('pnpm');
});
it('honors bunPresent:false as explicit absence (overrides a PATH hit)', () => {
@ -269,6 +290,52 @@ describe('resolve-analyze-cmd.cjs (canonical invocation resolver)', () => {
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).
@ -277,7 +344,7 @@ describe('resolve-analyze-cmd.cjs (canonical invocation resolver)', () => {
probed.push(c);
return c === 'pnpm' ? '/usr/local/bin/pnpm' : null;
};
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11 })).toBe('pnpm');
expect(cjs.resolveInvocationMode(probe, { npmMajor: 11, pnpmRuns: true })).toBe('pnpm');
expect(probed).not.toContain('bunx');
});
@ -606,31 +673,99 @@ describe('resolveOnPath — pure-Node PATH scan (#1938, all-OS, spawn-free)', ()
});
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;
// 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(() => {
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;
vi.unstubAllEnvs();
rmSync(binDir, { recursive: true, force: true });
});
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');
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);
// 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;
}
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', () => {

View file

@ -64,6 +64,7 @@ describe('mergeResult', () => {
fetchURL: '/a',
lineNumber: 1,
target: { kind: 'unresolved' as const },
callPosition: { row: 0, column: 0 },
};
const second = {
filePath: 'b.ts',
@ -71,6 +72,7 @@ describe('mergeResult', () => {
fetchURL: '/b',
lineNumber: 2,
target: { kind: 'member' as const },
callPosition: { row: 0, column: 0 },
};
mergeResult(target, { ...emptyResult(), fetchWrapperCalls: [first] });
mergeResult(target, emptyResult());

View file

@ -0,0 +1,222 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { WikiGenerator, type ModuleTreeNode } from '../../src/core/wiki/generator.js';
const {
callLLMMock,
getIntraModuleCallEdgesMock,
getProcessesForFilesMock,
getInterModuleEdgesForOverviewMock,
getAllProcessesMock,
} = vi.hoisted(() => ({
callLLMMock: vi.fn(),
getIntraModuleCallEdgesMock: vi.fn().mockResolvedValue([]),
getProcessesForFilesMock: vi.fn().mockResolvedValue([]),
getInterModuleEdgesForOverviewMock: vi.fn().mockResolvedValue([]),
getAllProcessesMock: vi.fn().mockResolvedValue([]),
}));
vi.mock('../../src/core/wiki/graph-queries.js', () => ({
initWikiDb: vi.fn().mockResolvedValue(undefined),
closeWikiDb: vi.fn().mockResolvedValue(undefined),
touchWikiDb: vi.fn(),
pinWikiDb: vi.fn(() => vi.fn()),
getFilesWithExports: vi.fn().mockResolvedValue([]),
getAllFiles: vi.fn().mockResolvedValue([]),
getIntraModuleCallEdges: getIntraModuleCallEdgesMock,
getInterModuleCallEdges: vi.fn().mockResolvedValue({ incoming: [], outgoing: [] }),
getProcessesForFiles: getProcessesForFilesMock,
getAllProcesses: getAllProcessesMock,
getInterModuleEdgesForOverview: getInterModuleEdgesForOverviewMock,
}));
vi.mock('../../src/core/wiki/llm-client.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/core/wiki/llm-client.js')>();
return {
...actual,
callLLM: callLLMMock,
};
});
describe('WikiGenerator slug propagation in prompts', () => {
let tmpRepoDir: string;
let tmpStorageDir: string;
let tmpWikiDir: string;
beforeEach(async () => {
tmpRepoDir = await fs.mkdtemp(path.join(os.tmpdir(), 'wiki-slugs-repo-'));
tmpStorageDir = path.join(tmpRepoDir, '.gitnexus');
tmpWikiDir = path.join(tmpStorageDir, 'wiki');
await fs.mkdir(tmpWikiDir, { recursive: true });
await fs.writeFile(
path.join(tmpRepoDir, 'package.json'),
JSON.stringify({ name: 'test-project', description: 'Test project description' }),
'utf-8',
);
callLLMMock.mockReset();
callLLMMock.mockResolvedValue({
content: '## Overview\n\nGenerated documentation content.',
});
getIntraModuleCallEdgesMock.mockResolvedValue([]);
getProcessesForFilesMock.mockResolvedValue([]);
getInterModuleEdgesForOverviewMock.mockResolvedValue([]);
getAllProcessesMock.mockResolvedValue([]);
});
afterEach(async () => {
vi.restoreAllMocks();
await fs.rm(tmpRepoDir, { recursive: true, force: true });
});
function createGenerator(): WikiGenerator {
return new WikiGenerator(tmpRepoDir, tmpStorageDir, '/dummy/lbug', {
apiKey: 'test-key',
baseUrl: 'https://test.local',
model: 'test-model',
maxTokens: 1000,
temperature: 0,
provider: 'openai',
});
}
it('generateParentPage passes each child module real slug (.md file) in the prompt context', async () => {
const generator = createGenerator();
const child1Slug = 'pkg-a-launch';
const child2Slug = 'pkg-a-composition-database';
await fs.writeFile(
path.join(tmpWikiDir, `${child1Slug}.md`),
'# pkg_a — launch\n\nLaunch sub-module handles startup.\n### Architecture\nStartup details...',
'utf-8',
);
await fs.writeFile(
path.join(tmpWikiDir, `${child2Slug}.md`),
'# pkg_a — composition/database\n\nDatabase sub-module handles pooling.\n### Architecture\nPool details...',
'utf-8',
);
const parentNode: ModuleTreeNode = {
name: 'pkg_a — Launch & Database',
slug: 'pkg-a-launch-database',
files: [],
children: [
{
name: 'pkg_a — launch',
slug: child1Slug,
files: ['packages/a/launch.ts'],
},
{
name: 'pkg_a — composition/database',
slug: child2Slug,
files: ['packages/a/db.ts'],
},
],
};
await (generator as any).generateParentPage(parentNode);
expect(callLLMMock).toHaveBeenCalledTimes(1);
const capturedPrompt = callLLMMock.mock.calls[0][0] as string;
// Both real file targets must appear in the prompt so the LLM does not guess slugs
expect(capturedPrompt).toContain(`${child1Slug}.md`);
expect(capturedPrompt).toContain(`${child2Slug}.md`);
});
it('generateParentPage passes child slug even when child doc is not yet generated', async () => {
const generator = createGenerator();
const childSlug = 'pkg-b-use-cases-1-4';
const parentNode: ModuleTreeNode = {
name: 'pkg_b — Use Cases',
slug: 'pkg-b-use-cases',
files: [],
children: [
{
name: 'pkg_b — use_cases (1/4)',
slug: childSlug,
files: ['packages/b/uc1.ts'],
},
],
};
await (generator as any).generateParentPage(parentNode);
expect(callLLMMock).toHaveBeenCalledTimes(1);
const capturedPrompt = callLLMMock.mock.calls[0][0] as string;
expect(capturedPrompt).toContain(`${childSlug}.md`);
});
it('generateOverview passes each module real slug (.md file) in the prompt context', async () => {
const generator = createGenerator();
const mod1Slug = 'pkg-a-launch-database';
const mod2Slug = 'pkg-c';
await fs.writeFile(
path.join(tmpWikiDir, `${mod1Slug}.md`),
'# pkg_a — Launch & Database\n\nParent module documentation.\n### Architecture\nDetails...',
'utf-8',
);
await fs.writeFile(
path.join(tmpWikiDir, `${mod2Slug}.md`),
'# pkg_c\n\nModule C documentation.\n### Architecture\nDetails...',
'utf-8',
);
const moduleTree: ModuleTreeNode[] = [
{
name: 'pkg_a — Launch & Database',
slug: mod1Slug,
files: [],
children: [
{
name: 'pkg_a — launch',
slug: 'pkg-a-launch',
files: ['packages/a/launch.ts'],
},
],
},
{
name: 'pkg_c',
slug: mod2Slug,
files: ['packages/c/index.ts'],
},
];
await (generator as any).generateOverview(moduleTree);
expect(callLLMMock).toHaveBeenCalledTimes(1);
const capturedPrompt = callLLMMock.mock.calls[0][0] as string;
// Both real file targets must appear in the prompt so the LLM does not guess slugs
expect(capturedPrompt).toContain(`${mod1Slug}.md`);
expect(capturedPrompt).toContain(`${mod2Slug}.md`);
});
it('generateOverview passes module slug even when module doc is pending', async () => {
const generator = createGenerator();
const modSlug = 'pkg-c-pending';
const moduleTree: ModuleTreeNode[] = [
{
name: 'pkg_c pending module',
slug: modSlug,
files: ['packages/c/pending.ts'],
},
];
await (generator as any).generateOverview(moduleTree);
expect(callLLMMock).toHaveBeenCalledTimes(1);
const capturedPrompt = callLLMMock.mock.calls[0][0] as string;
expect(capturedPrompt).toContain(`${modSlug}.md`);
});
});

View file

@ -0,0 +1,348 @@
// @vitest-environment jsdom
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { runInThisContext } from 'node:vm';
import { describe, expect, it } from 'vitest';
import { sanitizeMermaidDiagram } from '../../src/core/wiki/mermaid-sanitizer.js';
// The official tiny browser bundle includes the same flowchart parser as the
// viewer's Mermaid 11, without installing the full renderer dependency tree.
// It is a script, not an importable module; execute it as a browser script in
// this test fork's jsdom environment. Nothing here ships with the CLI.
const require = createRequire(import.meta.url);
runInThisContext(readFileSync(require.resolve('@mermaid-js/tiny'), 'utf8'));
const mermaid = (
globalThis as unknown as {
mermaid: {
initialize(config: { startOnLoad: boolean }): void;
mermaidAPI: { getDiagramFromText(text: string): Promise<{ db: unknown }> };
};
}
).mermaid;
type Graph = {
nodes: string[];
edges: string[];
labels: Array<{ text: string; type: string }>;
links: Array<{ text: string; type: string; stroke: string }>;
};
async function parseFlowchart(diagram: string): Promise<Graph> {
const parsed = await mermaid.mermaidAPI.getDiagramFromText(diagram);
const db = parsed.db as {
getVertices(): Map<string, { id: string; text: string; type: string }>;
getEdges(): Array<{ start: string; end: string; text: string; type: string; stroke: string }>;
};
return {
nodes: [...db.getVertices().keys()],
edges: db.getEdges().map((edge) => `${edge.start}->${edge.end}`),
labels: [...db.getVertices().values()].map(({ text, type }) => ({ text, type })),
links: db.getEdges().map(({ text, type, stroke }) => ({ text, type, stroke })),
};
}
describe('sanitizeMermaidDiagram, checked with the Mermaid parser', () => {
mermaid.initialize({ startOnLoad: false });
it('keeps the three diagrams from the report unchanged and valid', async () => {
const diagrams = [
'flowchart TD\n A["value.when(...)"] -->|data| B["data"]',
'flowchart TD\n G["x = compute(...).result"] --> H["done"]',
'flowchart LR\n N -- ref.invalidate --> A',
];
for (const diagram of diagrams) {
expect(sanitizeMermaidDiagram(diagram)).toBe(diagram);
await expect(parseFlowchart(diagram)).resolves.toBeTruthy();
}
});
it('leaves rounded, circular and other shaped nodes alone at both ends of a link', async () => {
const diagrams = [
'flowchart LR\n A(Start) --> B',
'flowchart LR\n X --> Y(Done)',
'flowchart LR\n A((Start)) --> B(End)',
'flowchart LR\n A[(db)] --> B{Choice} --> C>flag]',
'flowchart LR\n A([Stadium]) -->|yes| B[[Sub]]',
];
for (const diagram of diagrams) {
const sanitized = sanitizeMermaidDiagram(diagram);
expect(sanitized).toBe(diagram);
expect(await parseFlowchart(sanitized)).toEqual(await parseFlowchart(diagram));
}
});
it('aliases every reference of a node in a chained link, plain and thick', async () => {
const plain = ['flowchart LR', ' A --- file.ts --- B', ' file.ts --> C'].join('\n');
const thick = ['flowchart LR', ' A === file.ts === B', ' file.ts ==> C'].join('\n');
for (const diagram of [plain, thick]) {
const original = await parseFlowchart(diagram);
const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram));
// One node, under one id, with the same links as before.
expect(graph.nodes).toEqual(['A', 'file_ts', 'B', 'C']);
expect(graph.edges).toEqual(['A->file_ts', 'file_ts->B', 'file_ts->C']);
expect(graph.edges).toHaveLength(original.edges.length);
}
});
it('keeps labelled links written without spaces, and links with a cross or circle head', async () => {
const spaced = 'flowchart LR\n A --text--> B\n B ==text==> C\n C -.text.-> D';
expect(sanitizeMermaidDiagram(spaced)).toBe(spaced);
expect((await parseFlowchart(spaced)).edges).toEqual(['A->B', 'B->C', 'C->D']);
const heads = 'flowchart LR\n A --x B --> C\n C --o D\n D x--x E';
expect(sanitizeMermaidDiagram(heads)).toBe(heads);
expect((await parseFlowchart(heads)).edges).toEqual(['A->B', 'B->C', 'C->D', 'D->E']);
});
it('reads a compact cross or circle link as a link, so the node after it is aliased too', async () => {
const cross = ['flowchart LR', ' A --xfile.ts --> B', ' file.ts --> C'].join('\n');
const circle = ['flowchart LR', ' A --ofile.ts --> B', ' file.ts --> C'].join('\n');
for (const diagram of [cross, circle]) {
const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram));
expect(graph.nodes).toEqual(['A', 'file_ts', 'B', 'C']);
expect(graph.edges).toEqual(['A->file_ts', 'file_ts->B', 'file_ts->C']);
}
});
it('still repairs a call-shaped node id', async () => {
const sanitized = sanitizeMermaidDiagram('flowchart LR\n doc() --> B');
expect(sanitized).toBe('flowchart LR\n doc["doc()"] --> B');
expect((await parseFlowchart(sanitized)).edges).toEqual(['doc->B']);
});
it('repairs a qualified call-shaped id as one node, at either end of a link', async () => {
const diagram = ['flowchart LR', ' foo().bar --> B', ' A --> foo().bar'].join('\n');
const sanitized = sanitizeMermaidDiagram(diagram);
const graph = await parseFlowchart(sanitized);
expect(sanitized).toContain('foo___bar["foo().bar"] --> B');
expect(sanitized).toContain('A --> foo___bar["foo().bar"]');
expect(graph.nodes).toEqual(['foo___bar', 'B', 'A']);
expect(graph.edges).toEqual(['foo___bar->B', 'A->foo___bar']);
});
it('keeps the text of a labelled link and the graph around it', async () => {
const diagram = ['flowchart LR', ' cache.ts -- ref.invalidate --> store.ts'].join('\n');
const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram));
expect(graph.nodes).toEqual(['cache_ts', 'store_ts']);
expect(graph.edges).toEqual(['cache_ts->store_ts']);
});
it('does not read pipes inside a node label as an edge label', async () => {
const diagram = 'flowchart LR\nA["a|doc()|b"] --> B';
const sanitized = sanitizeMermaidDiagram(diagram);
expect(sanitized).toBe(diagram);
expect(await parseFlowchart(sanitized)).toEqual(await parseFlowchart(diagram));
});
it('repairs an edge label even when the preceding node label contains a pipe', async () => {
const sanitized = sanitizeMermaidDiagram('flowchart LR\nA["a | b"] -->|doc()| B');
expect(sanitized).toBe('flowchart LR\nA["a | b"] -->|"doc()"| B');
expect((await parseFlowchart(sanitized)).edges).toEqual(['A->B']);
});
it.each([
'A & file.ts --> B\nfile.ts --> C',
'file.ts & A --> B\nfile.ts --> C',
'A --> B & file.ts\nfile.ts --> C',
'A --> file.ts; file.ts --> C',
])('preserves shared node identities in fan-out and statements: %s', async (body) => {
const original = await parseFlowchart('flowchart LR\n' + body);
const sanitized = sanitizeMermaidDiagram('flowchart LR\n' + body);
const graph = await parseFlowchart(sanitized);
expect(graph.nodes).toEqual(original.nodes.map((id) => id.replaceAll('.', '_')));
expect(graph.edges).toEqual(original.edges.map((edge) => edge.replaceAll('.', '_')));
expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized);
});
it.each(['A --> file.ts\nfile_ts --> B', 'file_ts --> B\nA --> file.ts'])(
'does not merge an alias with an existing node: %s',
async (body) => {
const graph = await parseFlowchart(sanitizeMermaidDiagram('flowchart LR\n' + body));
expect(graph.nodes).toHaveLength(4);
expect(graph.edges).toContain('file_ts->B');
expect(graph.edges).toContain('A->file_ts_2');
},
);
it.each([
'["value.when(...) | call() | a & b; c --> d"]',
'("value.when(...) | call() | a & b; c --> d")',
'(["value.when(...) | call() | a & b; c --> d"])',
'[["value.when(...) | call() | a & b; c --> d"]]',
'[("value.when(...) | call() | a & b; c --> d")]',
'(("value.when(...) | call() | a & b; c --> d"))',
'>"value.when(...) | call() | a & b; c --> d"]',
'{"value.when(...) | call() | a & b; c --> d"}',
'{{"value.when(...) | call() | a & b; c --> d"}}',
'[/"value.when(...) | call() | a & b; c --> d"/]',
'((("value.when(...) | call() | a & b; c --> d")))',
])('preserves node shape and label contents: %s', async (shape) => {
const diagram = `flowchart LR\nA${shape} --> B${shape}`;
const original = await parseFlowchart(diagram);
const sanitized = sanitizeMermaidDiagram(diagram);
expect(sanitized).toBe(diagram);
expect(await parseFlowchart(sanitized)).toEqual(original);
});
it.each([
'-->',
'---',
'<-->',
'==>',
'===',
'-.->',
'-..-',
'--x',
'--o',
'x--x',
'o--o',
'-- text -->',
'== text ==>',
'-. text .->',
'-->|"doc()"|',
])('preserves link style and text: %s', async (link) => {
const diagram = `flowchart LR\nA ${link} B`;
expect(await parseFlowchart(sanitizeMermaidDiagram(diagram))).toEqual(
await parseFlowchart(diagram),
);
});
it('leaves sequence diagram syntax to its own parser', async () => {
const diagram = 'sequenceDiagram\nclient.ts-->>server.ts: done';
await expect(mermaid.mermaidAPI.getDiagramFromText(diagram)).resolves.toBeTruthy();
expect(sanitizeMermaidDiagram(diagram)).toBe(diagram);
});
it('quotes edge labels using Mermaid entities rather than JavaScript escapes', async () => {
const sanitized = sanitizeMermaidDiagram('flowchart LR\nA -->|doc("C:\\tmp")| B');
expect(sanitized).toBe('flowchart LR\nA -->|"doc(#quot;C:\\tmp#quot;)"| B');
expect((await parseFlowchart(sanitized)).edges).toEqual(['A->B']);
});
it('keeps an asymmetric shape and its link-like label text', async () => {
const diagram = 'flowchart LR\nfile.ts>value --> other.ts & x] --> B';
const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram));
expect(graph.nodes).toEqual(['file_ts', 'B']);
expect(graph.edges).toEqual(['file_ts->B']);
expect(graph.labels).toEqual((await parseFlowchart(diagram)).labels);
});
it.each(['file.ts["File"]\nA --> file.ts', 'A --> file.ts\nfile.ts["File"]'])(
'preserves an explicit label across bare references: %s',
async (body) => {
const original = await parseFlowchart('flowchart LR\n' + body);
const graph = await parseFlowchart(sanitizeMermaidDiagram('flowchart LR\n' + body));
expect(graph.labels).toEqual(original.labels);
},
);
it('keeps style and class references attached to the aliased node', async () => {
const diagram = 'flowchart LR\nA --> file.ts\nstyle file.ts fill:red\nclass file.ts active';
const sanitized = sanitizeMermaidDiagram(diagram);
const parsed = await mermaid.mermaidAPI.getDiagramFromText(sanitized);
const vertices = (
parsed.db as { getVertices(): Map<string, { styles: string[]; classes: string[] }> }
).getVertices();
expect([...vertices.keys()]).toEqual(['A', 'file_ts']);
expect(vertices.get('file_ts')?.styles).toContain('fill:red');
expect(vertices.get('file_ts')?.classes).toContain('active');
});
it('reserves subgraph identifiers before allocating node aliases', async () => {
const diagram = 'flowchart LR\nsubgraph file_ts\nA --> file.ts\nend';
expect((await parseFlowchart(sanitizeMermaidDiagram(diagram))).edges).toEqual(['A->file_ts_2']);
});
it.each([
['style.css', 'style_css'],
['direction.ts', 'direction_ts'],
['click-handler.ts', 'node_click-handler_ts'],
['class-loader.ts', 'node_class-loader_ts'],
])('does not mistake the filename %s for a directive', async (id, alias) => {
const sanitized = sanitizeMermaidDiagram(`flowchart LR\n${id} --> B\nA --> ${id}`);
expect((await parseFlowchart(sanitized)).edges).toEqual([`${alias}->B`, `A->${alias}`]);
expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized);
});
it('preserves frontmatter while repairing the diagram below it', async () => {
const frontmatter =
'---\ntitle: "file.ts --> doc()"\nconfig:\n flowchart:\n curve: linear\n---\n';
const sanitized = sanitizeMermaidDiagram(
frontmatter + '%% flow\nflowchart LR\ndoc() -->|doc()| B',
);
expect(sanitized.startsWith(frontmatter)).toBe(true);
expect((await parseFlowchart(sanitized)).edges).toEqual(['doc->B']);
expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized);
});
it('preserves multiline initialization directives', async () => {
const prelude = '%%{init: {\n "theme": "dark"\n}}%%\n';
const sanitized = sanitizeMermaidDiagram(prelude + 'flowchart LR\ndoc() --> B');
expect(sanitized.startsWith(prelude)).toBe(true);
expect((await parseFlowchart(sanitized)).edges).toEqual(['doc->B']);
});
it('aliases nodes following a header on the same line', async () => {
const sanitized = sanitizeMermaidDiagram('flowchart LR; A --> file.ts\nfile.ts --> B');
expect((await parseFlowchart(sanitized)).edges).toEqual(['A->file_ts', 'file_ts->B']);
});
it.each(['-->|returns List<File>|', '-- returns Map<K,V> -->'])(
'keeps generic types in link text separate from the target: %s',
async (link) => {
const diagram = `flowchart LR\nA ${link} loader.ts[Loader]\nloader.ts --> C`;
const sanitized = sanitizeMermaidDiagram(diagram);
const graph = await parseFlowchart(sanitized);
expect(graph.nodes).toEqual(['A', 'loader_ts', 'C']);
expect(graph.edges).toEqual(['A->loader_ts', 'loader_ts->C']);
expect(graph.labels).toEqual((await parseFlowchart(diagram)).labels);
expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized);
},
);
it.each(['shape: rect', 'shape: rect, label: "File"', 'label: "File", shape: rect'])(
'preserves the label of a node with metadata: %s',
async (metadata) => {
const diagram = `flowchart LR\nfile.ts@{ ${metadata} }\nfile.ts --> B`;
const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram));
expect(graph.nodes).toEqual(['file_ts', 'B']);
expect(graph.labels).toEqual((await parseFlowchart(diagram)).labels);
},
);
it('preserves multiline quoted labels containing diagram syntax', async () => {
const diagram = 'flowchart LR\nA["first\nfile.ts --> done & x; y"] --> file.ts\nfile.ts --> B';
const sanitized = sanitizeMermaidDiagram(diagram);
const graph = await parseFlowchart(sanitized);
expect(graph.nodes).toEqual(['A', 'file_ts', 'B']);
const original = await parseFlowchart(diagram);
expect(graph.labels.map(({ text }) => text)).toEqual(original.labels.map(({ text }) => text));
expect(graph.labels[0]).toEqual(original.labels[0]);
expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized);
});
it.each(['A:::hot --> B', 'A --> file.ts:::hot\nfile.ts --> B'])(
'preserves class shorthand: %s',
async (body) => {
const parsed = await mermaid.mermaidAPI.getDiagramFromText(
sanitizeMermaidDiagram('flowchart LR\n' + body),
);
const vertices = (
parsed.db as { getVertices(): Map<string, { classes: string[] }> }
).getVertices();
const id = body.startsWith('A:::') ? 'A' : 'file_ts';
expect(vertices.get(id)?.classes).toContain('hot');
expect(vertices.size).toBe(body.startsWith('A:::') ? 2 : 3);
},
);
});

View file

@ -34,12 +34,12 @@ describe('sanitizeMermaidMarkdown', () => {
expect(sanitized).toContain('Client -->|HTTP params| Script');
});
it('escapes backslashes and quotes in quoted edge labels', () => {
it('encodes quotes and preserves backslashes in quoted edge labels', () => {
const diagram = ['graph LR', ' Script -->|doc("C:\\\\tmp")| Target'].join('\n');
const sanitized = sanitizeMermaidDiagram(diagram);
expect(sanitized).toContain('Script -->|"doc(\\"C:\\\\\\\\tmp\\")"| Target');
expect(sanitized).toContain('Script -->|"doc(#quot;C:\\\\tmp#quot;)"| Target');
});
it('aliases bare node IDs that contain dots and keeps display labels', () => {
@ -74,6 +74,51 @@ describe('sanitizeMermaidMarkdown', () => {
expect(sanitized).toContain('file_name_ts[(eXist-db XML)] --> target_node["Target node"]');
});
it('leaves an ellipsis or a dotted name inside a label alone', () => {
// #3705: these three diagrams are valid; sanitizing must not change them.
const diagrams = [
'flowchart TD\n A["value.when(...)"] -->|data| B["data"]',
'flowchart TD\n G["x = compute(...).result"] --> H["done"]',
'flowchart LR\n N -- ref.invalidate --> A',
];
for (const diagram of diagrams) {
expect(sanitizeMermaidDiagram(diagram)).toBe(diagram);
}
});
it('reads dots as a link only in the dotted link syntax', () => {
const diagram = [
'flowchart LR',
' A -.-> B',
' B -. later .-> C',
' C -..- D',
' file.ts -.-> E["x..y"]',
].join('\n');
const sanitized = sanitizeMermaidDiagram(diagram);
expect(sanitized).toContain('A -.-> B');
expect(sanitized).toContain('B -. later .-> C');
expect(sanitized).toContain('C -..- D');
expect(sanitized).toContain('file_ts["file.ts"] -.-> E["x..y"]');
});
it('keeps the text of a labelled link while still aliasing the nodes around it', () => {
const diagram = [
'flowchart LR',
' cache.ts -- ref.invalidate --> store.ts',
' store.ts == on.save ==> db[(db)]',
' a.b -- plain --> c[c --> d]',
].join('\n');
const sanitized = sanitizeMermaidDiagram(diagram);
expect(sanitized).toContain('cache_ts["cache.ts"] -- ref.invalidate --> store_ts["store.ts"]');
expect(sanitized).toContain('store_ts["store.ts"] == on.save ==> db[(db)]');
expect(sanitized).toContain('a_b["a.b"] -- plain --> c[c --> d]');
});
it('only rewrites fenced Mermaid blocks in markdown', () => {
const markdown = [
'Regular text with doc() and file.name.ts.',

View file

@ -74,6 +74,7 @@ export default defineConfig({
test: {
name: 'lbug-db',
include: [
'test/integration/class-expression-owners.test.ts',
'test/integration/rename-provider-*.test.ts',
'test/integration/pdg-explicit-owner.test.ts',
'test/integration/skip-fts.test.ts',
@ -182,6 +183,7 @@ export default defineConfig({
sequence: { groupOrder: 3 },
include: ['test/**/*.test.ts'],
exclude: [
'test/integration/class-expression-owners.test.ts',
'test/integration/rename-provider-*.test.ts',
'test/integration/pdg-explicit-owner.test.ts',
'test/integration/skip-fts.test.ts',