GitNexus/gitnexus/test/integration/api-impact-indirect-consumers-e2e.test.ts
samuel mbabhazi 9772bcd24f
feat(api_impact): list the callers of the requesting function as indirect consumers (#3720)
* feat(api_impact): list the callers of the requesting function as indirect consumers

The FETCHES edge is file-level, so api_impact saw only the file that sends
the request. The files that call its request function never mention the URL
and were missing from the report (#3644).

The edge's reason now names the callables whose spans contain the request
sites, one `|via:<id>` field each, under the containment rule the R3-6 sink
set already uses; that rule moves into EnclosingCallableIndex so both stay
one. Several sites of one file for one route now share the edge instead of
colliding on its id. api_impact follows the CALLS edges into those callables
one level up and reports the callers as `indirectConsumers`, apart from the
direct consumers and outside the risk level. Direct consumer files and the
handler file are left out. An index built before the attribution carries no
field. Expo navigation sites carry their real line so they attribute to the
component that contains them.

Closes #3644

* fix(api_impact): attribute a request site by its AST enclosing callable

A helper defined on the line of the request has the smaller span, so the
line-only lookup named it and the callers of the real requesting function
vanished from indirectConsumers. The parser now records the enclosing
callable of each fetch site and of each wrapper call (through the call's
position), and attribution prefers that identity; the span lookup remains
for sites found by text scan. The same preference applies to the R3-6 sink
set. A real analyze of the fixture followed by api_impact pins the helper
case and the wrapper case.

* test(bench): rebaseline receiver resolution for the indirect-consumers fixture

The api-impact-indirect-consumers fixture adds three receiver-unresolved
sites to the corpus: two `.then(...)` calls on the untyped return of
`fetch(...)` and of the local wrapper `apiFetch(...)`, and one
`req.query.path` read inside an inline Express handler with an untyped
`req`. Call drops 138 -> 140, reads 30 -> 31, all kinds 168 -> 171. No
shape-arm state and no existing site changed.

* fix(api_impact): preserve module-scope request attribution

Keep AST-confirmed module scope distinct from missing attribution for direct
fetches, HTTP clients, and wrapper calls. Prevent overlapping callable spans
from inventing indirect consumers or process sinks.

Preserve span fallback for callable forms the generic identity walk cannot
name. Add eight regression cases, including real analyze/api_impact coverage.
Rebaseline receiver-resolution counts for the two then calls and one property
read added by this PR's existing fixtures; shape expectations are unchanged.

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-10-25 18:29:09 +00:00

172 lines
7.1 KiB
TypeScript

/**
* #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);
});
});