mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* feat(mcp): add an opt-in refresh_index tool A local `gitnexus mcp` server started with GITNEXUS_MCP_ENABLE_REFRESH=1 lists refresh_index, which rebuilds one registered index from its working tree through the forked analyze worker auto-sync uses, with the same index-only options: no AGENTS.md, CLAUDE.md, skill, hook or repository file is written. The tool lives outside GITNEXUS_TOOLS, so the default catalog and its byte budget are unchanged. `gitnexus serve` never passes the option, so the web/Docker /api/mcp surface cannot list it; read-only mode hides and rejects it through the existing allowlist. A repository whose last index recorded more than GITNEXUS_MCP_REFRESH_MAX_FILES files (default 5000), or none, is refused. After GITNEXUS_MCP_REFRESH_TIMEOUT_MS the call stops waiting; the worker never interrupts a started analysis, so it finishes in the background and keeps the index lock. One refresh runs per repository at a time, and the slot is held until the worker is done. A collapsed graph write is reported as an error, as analyze and serve report it. dry_run reports staleness, the file count and whether .gitnexusrc asks for embeddings. Worker progress is relayed as MCP progress notifications when the client sends a progress token. Malformed limits fail startup. Refs #3524. * fix(mcp): keep worker log lines out of refresh progress The analyze worker sends its log lines as progress messages with percent -1. The launcher now drops them before onProgress, so the listener only sees real progress (the server relay already discarded them). The refresh tests now unset GITNEXUS_MCP_REFRESH_MAX_FILES and GITNEXUS_MCP_REFRESH_TIMEOUT_MS, so an inherited value cannot change the defaults they assert. The tool-arguments comment names the schema lookup it actually uses. * test(mcp): check ignored paths after a refresh, not only git status analyze excludes its own storage through .git/info/exclude, so a clean git status says nothing about ignored paths. The e2e now also lists them and allows none outside .gitnexus/. * fix(mcp): count the working tree against the refresh file limit refresh_index compared GITNEXUS_MCP_REFRESH_MAX_FILES with the file count of the last index. A stale index is exactly the case where that count can be far below the working tree, so a repository that grew from 100 to 50,000 files since its last index was admitted under the default limit of 5,000 and dry_run reported 100. countScanCandidates (filesystem-walker.ts) walks the same glob patterns and ignore rules as walkRepositoryPaths, without stat-ing, and stops one past the limit, so admission costs the same on a huge tree as on a small one. Large files, non-regular entries and declaration siblings are not subtracted, so the count is an upper bound on what analyze indexes. refreshIndex admits the rebuild from that count. dry_run reports it as estimatedFiles (null past the limit, where only "more than maxFiles" is known, and with no limit, where nothing is counted) and the registry count as lastIndexedFiles. An index without a recorded count is no longer refused, since the tree is counted. A tree that cannot be read is refused before the worker, like an unreadable .gitnexusrc. Tests: the walker count matches the scan's paths, stops at limit + 1, and counts a file the scan drops for its size. The backend refuses a tree over the limit whose last index was under it, without starting the worker, and does not count with no limit. The e2e test commits two files past a limit of 4 after an index of 3 and checks that dry_run and the refresh refuse, with the real enumeration, and that the index stays at its commit. Reading the registry count again fails the backend and e2e tests; dropping the early stop fails the walker test. * test(ingestion): ignore a directory only .gitignore excludes in the count test The fixture ignored generated/ through .gitignore, but the ignore service already skips a root generated/ directory on its own, so the test passed with .gitignore disabled. scratch/ is excluded by .gitignore alone. * test(mcp): cover refresh progress and readers * fix(mcp): retain timed-out refresh slots (#3769) Keep the repository busy until an abandoned worker exits, so retries cannot start another worker while the original refresh is still running. Cover late success and failure, and update the timeout documentation. --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com> Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
212 lines
8.6 KiB
TypeScript
212 lines
8.6 KiB
TypeScript
/**
|
|
* #3524, end to end: a real analyze, a new commit that leaves the index behind,
|
|
* then `refresh_index` through LocalBackend with the real analyze worker. The
|
|
* refresh must bring the index to HEAD without touching anything git tracks or
|
|
* creating the agent files a plain `gitnexus analyze` writes. analyze hides
|
|
* its own storage, `.gitnexus/`, through `.git/info/exclude`, so the check also
|
|
* lists ignored paths and allows none outside that directory.
|
|
*/
|
|
import { execFileSync } from 'node:child_process';
|
|
import { existsSync } from 'node:fs';
|
|
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 CLAUDE_MD = '# Team notes\n\nHand-written; no GitNexus block.\n';
|
|
|
|
function git(repo: string, ...args: string[]): string {
|
|
return execFileSync('git', args, { cwd: repo, encoding: 'utf-8' }).trim();
|
|
}
|
|
|
|
describe('refresh_index through a real analyze worker (#3524)', () => {
|
|
let temp: Awaited<ReturnType<typeof createTempDir>>;
|
|
let repo: string;
|
|
let backend: LocalBackend;
|
|
let indexedCommit: string;
|
|
let head: string;
|
|
|
|
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_ATOMIC_INCREMENTAL', undefined);
|
|
vi.stubEnv('GITNEXUS_ATOMIC_WINDOWS_SWAP', undefined);
|
|
vi.stubEnv('GITNEXUS_LBUG_EXTENSION_INSTALL', 'load-only');
|
|
vi.stubEnv('GITNEXUS_WAL_MANUAL_CHECKPOINT', '1');
|
|
vi.stubEnv('GITNEXUS_MCP_REFRESH_MAX_FILES', undefined);
|
|
vi.stubEnv('GITNEXUS_MCP_REFRESH_TIMEOUT_MS', undefined);
|
|
repo = path.join(root, 'repo');
|
|
await fs.mkdir(path.join(repo, 'src'), { recursive: true });
|
|
await fs.writeFile(
|
|
path.join(repo, 'src', 'orders.ts'),
|
|
'export function placeOrder(id: string) { return `order:${id}`; }\n',
|
|
);
|
|
await fs.writeFile(path.join(repo, 'CLAUDE.md'), CLAUDE_MD);
|
|
initGitRepo(repo);
|
|
git(repo, 'config', 'commit.gpgsign', 'false');
|
|
commitAll(repo, 'initial');
|
|
await runFullAnalysis(repo, { skipAgentsMd: true, skipSkills: true }, { onProgress: () => {} });
|
|
indexedCommit = git(repo, 'rev-parse', 'HEAD');
|
|
|
|
await fs.writeFile(
|
|
path.join(repo, 'src', 'invoices.ts'),
|
|
[
|
|
"import { placeOrder } from './orders';",
|
|
'export function issueInvoice(id: string) { return placeOrder(id); }',
|
|
'',
|
|
].join('\n'),
|
|
);
|
|
commitAll(repo, 'add invoices');
|
|
head = git(repo, 'rev-parse', 'HEAD');
|
|
|
|
backend = new LocalBackend();
|
|
await backend.init();
|
|
}, 180_000);
|
|
|
|
afterAll(async () => {
|
|
await backend?.dispose();
|
|
vi.unstubAllEnvs();
|
|
await temp?.cleanup();
|
|
});
|
|
|
|
it('reports the stale index on a dry run without rebuilding it', async () => {
|
|
const result = await backend.callTool('refresh_index', { repo, dry_run: true });
|
|
expect(result).toMatchObject({
|
|
status: 'dry_run',
|
|
wouldRefresh: true,
|
|
lastCommit: indexedCommit,
|
|
staleness: { status: 'behind', commitsBehind: 1 },
|
|
// Counted in the working tree, so the commit's new file is included;
|
|
// CLAUDE.md is indexed too.
|
|
estimatedFiles: 3,
|
|
lastIndexedFiles: 2,
|
|
});
|
|
const list = await backend.callTool('list_repos', {});
|
|
expect(list.repositories[0].lastCommit).toBe(indexedCommit);
|
|
});
|
|
|
|
it('refreshes with an open reader and concurrent query without touching source files', async () => {
|
|
const read = () =>
|
|
backend.callTool('cypher', {
|
|
repo,
|
|
statement: 'MATCH (n:Function) RETURN n.name AS name ORDER BY n.name',
|
|
});
|
|
const oldRows = '| name |\n| --- |\n| placeOrder |';
|
|
const newRows = '| name |\n| --- |\n| issueInvoice |\n| placeOrder |';
|
|
const before = await read();
|
|
expect(before).toMatchObject({
|
|
row_count: 1,
|
|
markdown: oldRows,
|
|
staleness: { status: 'behind', lastCommit: indexedCommit },
|
|
});
|
|
|
|
// The first query leaves the native pool open. Start another query from
|
|
// real worker progress, so it overlaps refresh without holding a query
|
|
// past its own deadline on slower CI hosts.
|
|
let concurrentRead: ReturnType<typeof read> | undefined;
|
|
let result = await backend.callTool(
|
|
'refresh_index',
|
|
{ repo },
|
|
{
|
|
onProgress: () => {
|
|
concurrentRead ??= read();
|
|
},
|
|
},
|
|
);
|
|
expect(concurrentRead).toBeDefined();
|
|
const during = await concurrentRead;
|
|
expect(during).not.toHaveProperty('error');
|
|
// Scheduling may let the query observe either generation, but never a
|
|
// partial inventory or old rows labelled with the new commit.
|
|
expect([
|
|
{ row_count: 1, markdown: oldRows, lastCommit: indexedCommit },
|
|
{ row_count: 2, markdown: newRows, lastCommit: head },
|
|
]).toContainEqual({
|
|
row_count: during.row_count,
|
|
markdown: during.markdown,
|
|
lastCommit: during.staleness.lastCommit,
|
|
});
|
|
|
|
// POSIX publishes a staged database while readers retain the old inode.
|
|
// Windows defaults to in-place writes, which may refuse the open reader;
|
|
// require an explicit lock error, an unchanged index, and a successful retry.
|
|
if (process.platform === 'win32' && result.error) {
|
|
expect(result.error).toMatch(
|
|
/could not set lock on file|database.*(?:locked|busy)|(?:locked|busy).*database/i,
|
|
);
|
|
const list = await backend.callTool('list_repos', {});
|
|
expect(list.repositories[0].lastCommit).toBe(indexedCommit);
|
|
await backend.dispose();
|
|
await backend.init();
|
|
result = await backend.callTool('refresh_index', { repo });
|
|
}
|
|
expect(result).toMatchObject({
|
|
status: 'refreshed',
|
|
previous: { lastCommit: indexedCommit, staleness: { status: 'behind' } },
|
|
lastCommit: head,
|
|
staleness: { status: 'current' },
|
|
stats: { files: 3 },
|
|
});
|
|
|
|
expect(git(repo, 'status', '--porcelain', '--untracked-files=all')).toBe('');
|
|
const ignored = git(repo, 'status', '--porcelain', '--ignored', '--untracked-files=all')
|
|
.split('\n')
|
|
.filter(Boolean);
|
|
expect(ignored.length).toBeGreaterThan(0);
|
|
expect(ignored.filter((line) => !line.startsWith('!! .gitnexus/'))).toEqual([]);
|
|
expect(await fs.readFile(path.join(repo, 'CLAUDE.md'), 'utf-8')).toBe(CLAUDE_MD);
|
|
expect(existsSync(path.join(repo, 'AGENTS.md'))).toBe(false);
|
|
expect(existsSync(path.join(repo, '.claude'))).toBe(false);
|
|
|
|
// The same backend serves the rebuilt index without a restart.
|
|
const found = await backend.callTool('context', { name: 'issueInvoice', repo });
|
|
expect(found).not.toHaveProperty('error');
|
|
expect(found.symbol).toMatchObject({ name: 'issueInvoice', filePath: 'src/invoices.ts' });
|
|
expect(found.staleness).toMatchObject({ status: 'current', lastCommit: head });
|
|
expect(await read()).toMatchObject({
|
|
row_count: 2,
|
|
markdown: newRows,
|
|
staleness: { status: 'current', lastCommit: head },
|
|
});
|
|
}, 180_000);
|
|
|
|
it('refuses once the working tree outgrows the limit, whatever the last index counted', async () => {
|
|
// The index at HEAD recorded 3 files, under the limit; the tree now holds 5.
|
|
for (const name of ['refunds', 'shipping']) {
|
|
await fs.writeFile(path.join(repo, 'src', `${name}.ts`), `export const ${name} = 1;\n`);
|
|
}
|
|
commitAll(repo, 'add refunds and shipping');
|
|
vi.stubEnv('GITNEXUS_MCP_REFRESH_MAX_FILES', '4');
|
|
try {
|
|
const dryRun = await backend.callTool('refresh_index', { repo, dry_run: true });
|
|
expect(dryRun).toMatchObject({
|
|
status: 'dry_run',
|
|
staleness: { status: 'behind' },
|
|
estimatedFiles: null,
|
|
lastIndexedFiles: 3,
|
|
maxFiles: 4,
|
|
wouldRefresh: false,
|
|
refusal: expect.stringMatching(/more than 4 files in its working tree/),
|
|
});
|
|
await expect(backend.callTool('refresh_index', { repo })).resolves.toEqual({
|
|
error: dryRun.refusal,
|
|
});
|
|
// No worker ran: the index still stops at the previous commit.
|
|
const list = await backend.callTool('list_repos', {});
|
|
expect(list.repositories[0].lastCommit).toBe(head);
|
|
} finally {
|
|
vi.stubEnv('GITNEXUS_MCP_REFRESH_MAX_FILES', undefined);
|
|
}
|
|
});
|
|
});
|