mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-16 09:22:00 +00:00
Merge branch 'main' into fix/zig-value-ref-edges
This commit is contained in:
commit
47ab8908eb
16 changed files with 1237 additions and 44 deletions
|
|
@ -23,6 +23,21 @@ export interface BackendRepo {
|
|||
repoPath?: string; // git HEAD returns "repoPath"; older versions return "path"
|
||||
indexedAt: string;
|
||||
lastCommit?: string;
|
||||
/**
|
||||
* Branch this index was built from. Absent on legacy entries and non-git
|
||||
* repos. Since #3199 a branch-pinned analyze registers its own entry, so this
|
||||
* is what tells two entries for the same repository apart — the name is
|
||||
* derived from the clone directory and is not a contract.
|
||||
*/
|
||||
branch?: string;
|
||||
/** Non-primary branch indexes recorded for the same path. */
|
||||
branches?: Array<{ branch: string; indexedAt?: string; lastCommit?: string }>;
|
||||
/**
|
||||
* Present only when the index is behind the repo's checked-out HEAD; absent
|
||||
* means either up to date or not answerable (see the server's
|
||||
* `repo-projection.ts`). Same shape MCP `list_repos` returns.
|
||||
*/
|
||||
staleness?: { commitsBehind: number; hint?: string };
|
||||
stats?: {
|
||||
files?: number;
|
||||
nodes?: number;
|
||||
|
|
@ -663,7 +678,14 @@ export type BackendProbeStatus = 'ok' | 'unauthorized' | 'unreachable';
|
|||
*/
|
||||
export const probeBackendStatus = async (): Promise<BackendProbeStatus> => {
|
||||
try {
|
||||
const response = await fetchWithTimeout(`${_backendUrl}/api/repos`, {}, PROBE_TIMEOUT_MS);
|
||||
// `/api/health` rather than `/api/repos`: this is a liveness question on a
|
||||
// 2s budget, and `/api/repos` now spawns a `git rev-list` per registered
|
||||
// repo to answer freshness. Probing it made the cost of "is the server up?"
|
||||
// scale with the number of indexed repos, and a failed probe re-polls,
|
||||
// stacking more children on the way (#3232 review). `/api/health` is a
|
||||
// constant, and still sits behind the same `/api/*` edge gate, so the 401
|
||||
// branch below keeps distinguishing "gated" from "not there".
|
||||
const response = await fetchWithTimeout(`${_backendUrl}/api/health`, {}, PROBE_TIMEOUT_MS);
|
||||
if (response.status === 200) return 'ok';
|
||||
return response.status === 401 ? 'unauthorized' : 'unreachable';
|
||||
} catch {
|
||||
|
|
|
|||
|
|
@ -291,13 +291,15 @@ export const doctorCommand = async () => {
|
|||
console.log(` ${padDisplayEnd('', 18)}${remedy}`);
|
||||
}
|
||||
}
|
||||
// Semantic mode follows the probe, not the platform: without a loadable
|
||||
// VECTOR extension the index can be neither built nor queried, so search is
|
||||
// really on exact scan no matter what the platform would allow.
|
||||
// Doctor has no repository target, so this probe can report only whether the
|
||||
// runtime can load VECTOR. It cannot claim that a repository has built the
|
||||
// named HNSW index. Keep the capability and repository state distinct.
|
||||
console.log(
|
||||
` ${label('doctor.labels.semanticMode', 18)}${
|
||||
vectorProbe.loaded ? capabilities.semanticMode : 'exact-scan'
|
||||
}`,
|
||||
` ${label('doctor.labels.semanticMode', 18)}${t(
|
||||
vectorProbe.loaded
|
||||
? 'doctor.vectorCapability.indexUnverified'
|
||||
: 'doctor.vectorCapability.exactScanOnly',
|
||||
)}`,
|
||||
);
|
||||
// Surface the optional-extension install policy so offline users can see
|
||||
// whether analyze/query will reach the network (extension.ladybugdb.com).
|
||||
|
|
|
|||
|
|
@ -123,8 +123,10 @@ export const en = {
|
|||
'doctor.labels.onnx': 'ONNX:',
|
||||
'doctor.labels.graphStore': 'Graph store:',
|
||||
'doctor.labels.fullTextSearch': 'Full-text search:',
|
||||
'doctor.labels.vectorIndex': 'VECTOR index:',
|
||||
'doctor.labels.semanticMode': 'Semantic mode:',
|
||||
'doctor.labels.vectorIndex': 'VECTOR extension:',
|
||||
'doctor.labels.semanticMode': 'Semantic support:',
|
||||
'doctor.vectorCapability.indexUnverified': 'vector-index capable (repository index not checked)',
|
||||
'doctor.vectorCapability.exactScanOnly': 'exact-scan only (VECTOR extension unavailable)',
|
||||
'doctor.labels.exactScanLimit': 'Exact scan limit:',
|
||||
'doctor.labels.note': 'Note:',
|
||||
'doctor.labels.backend': 'Backend:',
|
||||
|
|
|
|||
|
|
@ -119,8 +119,10 @@ export const zhCN = {
|
|||
'doctor.labels.onnx': 'ONNX:',
|
||||
'doctor.labels.graphStore': '图存储:',
|
||||
'doctor.labels.fullTextSearch': '全文搜索:',
|
||||
'doctor.labels.vectorIndex': '向量索引:',
|
||||
'doctor.labels.semanticMode': '语义模式:',
|
||||
'doctor.labels.vectorIndex': 'VECTOR 扩展:',
|
||||
'doctor.labels.semanticMode': '语义支持:',
|
||||
'doctor.vectorCapability.indexUnverified': '支持向量索引(未检查仓库索引)',
|
||||
'doctor.vectorCapability.exactScanOnly': '仅精确扫描(VECTOR 扩展不可用)',
|
||||
'doctor.labels.exactScanLimit': '精确扫描上限:',
|
||||
'doctor.labels.note': '说明:',
|
||||
'doctor.labels.backend': '后端:',
|
||||
|
|
|
|||
|
|
@ -11,6 +11,13 @@ import { findGitRootByDotGit, getCurrentCommit, getRemoteUrl } from '../storage/
|
|||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Ceiling for one `git rev-list` staleness probe. Generous for the local
|
||||
* history walk this is, and short enough that an unresponsive working tree
|
||||
* degrades to "not stale" quickly rather than holding a request open.
|
||||
*/
|
||||
const STALENESS_TIMEOUT_MS = 5_000;
|
||||
|
||||
export interface StalenessInfo {
|
||||
isStale: boolean;
|
||||
commitsBehind: number;
|
||||
|
|
@ -61,6 +68,14 @@ export async function checkStalenessAsync(
|
|||
cwd: repoPath,
|
||||
encoding: 'utf-8',
|
||||
windowsHide: true,
|
||||
// The catch below fails closed on every git ERROR, but a hang is not an
|
||||
// error — it is silence, and without a bound this await never settles.
|
||||
// A working tree on a disconnected network mount or behind a stuck lock
|
||||
// does exactly that, and `/api/repos` fans this out once per registered
|
||||
// repo, so one unreachable mount could hold the whole listing open
|
||||
// (#3232 review). The timeout kills the child and rejects, which routes
|
||||
// a hang into the same fail-closed "not stale" answer as a bad SHA.
|
||||
timeout: STALENESS_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
const commitsBehind = parseInt(stdout.trim(), 10) || 0;
|
||||
|
|
|
|||
|
|
@ -92,6 +92,134 @@ function unquote(text: string): string | null {
|
|||
return value.includes('${') ? null : value;
|
||||
}
|
||||
|
||||
const SIMPLE_TEMPLATE_ESCAPES: Record<string, string> = {
|
||||
b: '\b',
|
||||
f: '\f',
|
||||
n: '\n',
|
||||
r: '\r',
|
||||
t: '\t',
|
||||
v: '\v',
|
||||
'0': '\0',
|
||||
"'": "'",
|
||||
'"': '"',
|
||||
'\\': '\\',
|
||||
'`': '`',
|
||||
};
|
||||
|
||||
/** Graph Method `startLine` is the 0-based wrapper row (see line-base.ts). */
|
||||
function providerMemberStartLine(member: Parser.SyntaxNode): number {
|
||||
// Class-field arrows are `@declaration.property`; parse-worker falls back to
|
||||
// the `public_field_definition` wrapper (decorator row when it is a child),
|
||||
// not the initializer. Do not probe the `value` child.
|
||||
return member.startPosition.row;
|
||||
}
|
||||
|
||||
/** tree-sitter `escape_sequence.text` is the source spelling (`\\n`), not the JS value. */
|
||||
function decodeEscapeSequence(text: string): string | null {
|
||||
if (!text.startsWith('\\') || text.length < 2) return null;
|
||||
const escaped = text.slice(1);
|
||||
// Tagged-template cooked value: LineContinuation is empty; `\8`/`\9` and
|
||||
// LegacyOctalEscapeSequence (`\1`–`\7`, `\00`…) make cooked undefined.
|
||||
if (/^[\n\r\u2028\u2029]$/.test(escaped) || escaped === '\r\n') return '';
|
||||
if (/^[1-9]$/.test(escaped) || /^[0-7]{2,3}$/.test(escaped)) return null;
|
||||
if (escaped.length === 1) return SIMPLE_TEMPLATE_ESCAPES[escaped] ?? escaped;
|
||||
if (escaped[0] === 'x' && /^[0-9A-Fa-f]{2}$/.test(escaped.slice(1))) {
|
||||
return String.fromCharCode(Number.parseInt(escaped.slice(1), 16));
|
||||
}
|
||||
if (escaped.startsWith('u{') && escaped.endsWith('}')) {
|
||||
const hex = escaped.slice(2, -1);
|
||||
if (!/^[0-9A-Fa-f]{1,6}$/.test(hex)) return null;
|
||||
const codePoint = Number.parseInt(hex, 16);
|
||||
if (codePoint > 0x10ffff) return null;
|
||||
return String.fromCodePoint(codePoint);
|
||||
}
|
||||
if (escaped[0] === 'u' && /^[0-9A-Fa-f]{4}$/.test(escaped.slice(1))) {
|
||||
return String.fromCharCode(Number.parseInt(escaped.slice(1), 16));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function substitutionIdentifier(substitution: Parser.SyntaxNode): string | null {
|
||||
if (substitution.namedChildren.length !== 1) return null;
|
||||
const expr = unwrapExpression(substitution.namedChildren[0]);
|
||||
return expr.type === 'identifier' ? expr.text : null;
|
||||
}
|
||||
|
||||
function isGraphqlTagCall(call: Parser.SyntaxNode): boolean {
|
||||
const callee = call.childForFieldName('function');
|
||||
return callee?.type === 'identifier' && callee.text === 'gql';
|
||||
}
|
||||
|
||||
function pascalCaseGraphqlName(name: string): string {
|
||||
return name
|
||||
.split(/[^A-Za-z0-9]+/)
|
||||
.filter((part) => part.length > 0)
|
||||
.map((part) => `${part[0]!.toUpperCase()}${part.slice(1)}`)
|
||||
.join('');
|
||||
}
|
||||
|
||||
type InterpolationCache = Map<string, string | null>;
|
||||
|
||||
function uniqueStaticSource(
|
||||
name: string,
|
||||
declarators: GeneratedSymbolIndex,
|
||||
resolving: Set<string>,
|
||||
cache: InterpolationCache,
|
||||
): string | null {
|
||||
if (cache.has(name)) return cache.get(name) ?? null;
|
||||
if (resolving.has(name) || resolving.size >= MAX_GRAPHQL_TRAVERSAL_DEPTH) return null;
|
||||
const values = declarators.get(name) ?? [];
|
||||
if (values.length === 0) {
|
||||
cache.set(name, null);
|
||||
return null;
|
||||
}
|
||||
resolving.add(name);
|
||||
const sources = new Set<string>();
|
||||
for (const value of values) {
|
||||
const source = staticGraphqlSource(value, declarators, resolving, cache);
|
||||
// A dynamic or unprovable sibling makes the name ambiguous — do not pick
|
||||
// the one static spelling and ignore the rest.
|
||||
if (source === null) {
|
||||
resolving.delete(name);
|
||||
cache.set(name, null);
|
||||
return null;
|
||||
}
|
||||
sources.add(source);
|
||||
}
|
||||
resolving.delete(name);
|
||||
const unique = sources.size === 1 ? [...sources][0]! : null;
|
||||
cache.set(name, unique);
|
||||
return unique;
|
||||
}
|
||||
|
||||
function interpolatedTemplateSource(
|
||||
template: Parser.SyntaxNode,
|
||||
declarators: GeneratedSymbolIndex,
|
||||
resolving: Set<string>,
|
||||
cache: InterpolationCache,
|
||||
): string | null {
|
||||
let out = '';
|
||||
for (const child of template.namedChildren) {
|
||||
if (child.type === 'string_fragment') {
|
||||
out += child.text;
|
||||
} else if (child.type === 'escape_sequence') {
|
||||
const decoded = decodeEscapeSequence(child.text);
|
||||
if (decoded === null) return null;
|
||||
out += decoded;
|
||||
} else if (child.type === 'template_substitution') {
|
||||
const name = substitutionIdentifier(child);
|
||||
if (!name) return null;
|
||||
const inlined = uniqueStaticSource(name, declarators, resolving, cache);
|
||||
if (inlined === null) return null;
|
||||
out += inlined;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (out.length > MAX_GRAPHQL_TOKENS) return null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function unwrapExpression(node: Parser.SyntaxNode): Parser.SyntaxNode {
|
||||
let current = node;
|
||||
while (
|
||||
|
|
@ -214,7 +342,12 @@ function parsedDocumentProof(
|
|||
return false;
|
||||
}
|
||||
|
||||
function staticGraphqlSource(initializer: Parser.SyntaxNode): string | null {
|
||||
function staticGraphqlSource(
|
||||
initializer: Parser.SyntaxNode,
|
||||
declarators?: GeneratedSymbolIndex,
|
||||
resolving: Set<string> = new Set(),
|
||||
cache: InterpolationCache = new Map(),
|
||||
): string | null {
|
||||
const value = unwrapExpression(initializer);
|
||||
if (value.type === 'string') {
|
||||
if (value.text.startsWith('"')) {
|
||||
|
|
@ -226,11 +359,24 @@ function staticGraphqlSource(initializer: Parser.SyntaxNode): string | null {
|
|||
}
|
||||
return unquote(value.text);
|
||||
}
|
||||
if (value.type === 'template_string') return unquote(value.text);
|
||||
if (value.type === 'template_string') {
|
||||
const hasSubstitution = value.namedChildren.some(
|
||||
(child) => child.type === 'template_substitution',
|
||||
);
|
||||
if (!hasSubstitution) return unquote(value.text);
|
||||
return declarators ? interpolatedTemplateSource(value, declarators, resolving, cache) : null;
|
||||
}
|
||||
|
||||
if (value.type === 'call_expression') {
|
||||
const template = value.namedChildren.find((child) => child.type === 'template_string');
|
||||
return template ? unquote(template.text) : null;
|
||||
if (!template) return null;
|
||||
const hasSubstitution = template.namedChildren.some(
|
||||
(child) => child.type === 'template_substitution',
|
||||
);
|
||||
// Interpolated reconstruction is the cooked template. Only `gql` is
|
||||
// treated as preserving that source; String.raw / unknown tags stay fail-closed.
|
||||
if (hasSubstitution && !isGraphqlTagCall(value)) return null;
|
||||
return staticGraphqlSource(template, declarators, resolving, cache);
|
||||
}
|
||||
|
||||
if (value.type !== 'new_expression') return null;
|
||||
|
|
@ -238,7 +384,7 @@ function staticGraphqlSource(initializer: Parser.SyntaxNode): string | null {
|
|||
if (!constructor || !constructor.text.endsWith('TypedDocumentString')) return null;
|
||||
const args = value.childForFieldName('arguments');
|
||||
const first = args?.namedChildren[0];
|
||||
return first ? staticGraphqlSource(first) : null;
|
||||
return first ? staticGraphqlSource(first, declarators, resolving, cache) : null;
|
||||
}
|
||||
|
||||
export function hasGeneratedDocumentProof(
|
||||
|
|
@ -246,9 +392,10 @@ export function hasGeneratedDocumentProof(
|
|||
operationKind: GraphqlOperationKind,
|
||||
operationName: string,
|
||||
requiredFields: readonly string[],
|
||||
declarators?: GeneratedSymbolIndex,
|
||||
): boolean {
|
||||
if (!withinGeneratedAstBudget(initializer)) return false;
|
||||
const staticSource = staticGraphqlSource(initializer);
|
||||
const staticSource = staticGraphqlSource(initializer, declarators);
|
||||
if (staticSource !== null) {
|
||||
return parsedDocumentProof(staticSource, operationKind, operationName, requiredFields);
|
||||
}
|
||||
|
|
@ -430,7 +577,10 @@ function rootFields(
|
|||
|
||||
function generatedCandidates(operation: OperationDefinitionNode): string[] {
|
||||
const name = operation.name?.value;
|
||||
return name ? [`${name}Document`] : [];
|
||||
if (!name) return [];
|
||||
const exact = `${name}Document`;
|
||||
const pascal = `${pascalCaseGraphqlName(name)}Document`;
|
||||
return exact === pascal ? [exact] : [exact, pascal];
|
||||
}
|
||||
|
||||
async function generatedDocumentMatches(
|
||||
|
|
@ -450,7 +600,13 @@ async function generatedDocumentMatches(
|
|||
const index = await pendingIndex;
|
||||
const values = index?.get(symbol.name) ?? [];
|
||||
return values.some((value) =>
|
||||
hasGeneratedDocumentProof(value, operationKind, operationName, requiredFields),
|
||||
hasGeneratedDocumentProof(
|
||||
value,
|
||||
operationKind,
|
||||
operationName,
|
||||
requiredFields,
|
||||
index ?? undefined,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -593,11 +749,7 @@ export class GraphqlExtractor implements ContractExtractor {
|
|||
await dbExecutor(RESOLVE_METHOD_QUERY, {
|
||||
name: methodName,
|
||||
filePath,
|
||||
startLine:
|
||||
member.type === 'public_field_definition'
|
||||
? (member.childForFieldName('value')?.startPosition.row ??
|
||||
member.startPosition.row) + 1
|
||||
: member.startPosition.row + 1,
|
||||
startLine: providerMemberStartLine(member),
|
||||
}),
|
||||
);
|
||||
if (!symbol) continue;
|
||||
|
|
|
|||
|
|
@ -340,16 +340,17 @@ export async function loadNodeWorkspacePackages(
|
|||
const scope = await loadWorkspaceScope(repoRoot);
|
||||
const byName = new Map<string, NodeWorkspacePackage>();
|
||||
const queue: { dir: string; depth: number }[] = [{ dir: repoRoot, depth: 0 }];
|
||||
let queueHead = 0;
|
||||
let dirsScanned = 0;
|
||||
|
||||
while (queue.length > 0) {
|
||||
while (queueHead < queue.length) {
|
||||
if (dirsScanned >= SCAN_MAX_DIRS) {
|
||||
logger.warn(
|
||||
`[node] package.json scan of ${repoRoot} hit the ${SCAN_MAX_DIRS}-directory cap; workspace packages below it will not resolve`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
const { dir, depth } = queue.shift()!;
|
||||
const { dir, depth } = queue[queueHead++]!;
|
||||
dirsScanned++;
|
||||
|
||||
let entries: import('fs').Dirent[];
|
||||
|
|
|
|||
|
|
@ -278,10 +278,11 @@ async function firstReadableConfig(base: string): Promise<string | null> {
|
|||
async function findTsconfigFiles(repoRoot: string): Promise<string[]> {
|
||||
const found: string[] = [];
|
||||
const queue: { dir: string; depth: number }[] = [{ dir: repoRoot, depth: 0 }];
|
||||
let queueHead = 0;
|
||||
let dirsScanned = 0;
|
||||
|
||||
while (queue.length > 0 && dirsScanned < SCAN_MAX_DIRS) {
|
||||
const { dir, depth } = queue.shift()!;
|
||||
while (queueHead < queue.length && dirsScanned < SCAN_MAX_DIRS) {
|
||||
const { dir, depth } = queue[queueHead++]!;
|
||||
dirsScanned++;
|
||||
let entries: import('fs').Dirent[];
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -65,6 +65,8 @@ import {
|
|||
GITHUB_TOKEN_HOSTS,
|
||||
} from './git-clone.js';
|
||||
import { createAnalyzeUploadHandler } from './analyze-upload.js';
|
||||
import { checkStalenessAsync } from '../core/git-staleness.js';
|
||||
import { projectRepoDetail, projectRepoListEntry, resolveLastCommit } from './repo-projection.js';
|
||||
// Shared with the CLI's `--branch` (via the analyze-config wrapper) so both
|
||||
// entry points accept the same refs. Imported from core — not cli/ — so
|
||||
// createServer does not close a cycle with cli/serve.ts.
|
||||
|
|
@ -1000,18 +1002,24 @@ export const createServer = async (port: number, host: string = '127.0.0.1') =>
|
|||
});
|
||||
|
||||
// List all registered repos
|
||||
app.get('/api/repos', async (_req, res) => {
|
||||
// Rate-limited (CodeQL js/missing-rate-limiting) because this route now spawns
|
||||
// one `git rev-list` per registered repo to answer freshness: an unauthenticated
|
||||
// GET that costs N subprocesses is worth the same 60 rpm/IP ceiling `/api/repo`
|
||||
// already carries. Web callers hit this on connect/switch, never in a loop.
|
||||
app.get('/api/repos', createRouteLimiter(), async (_req, res) => {
|
||||
try {
|
||||
const repos = await listRegisteredRepos();
|
||||
// Checked in parallel, for the reason `list_repos` already does it that
|
||||
// way: each check spawns an async `git rev-list`, and the sequential
|
||||
// variant took ~50s across 200 repos (#1363). Projecting inside the map
|
||||
// keeps the entry and its own check together — an index-matched second
|
||||
// array is the shape that silently mispairs them if either is reordered.
|
||||
res.json(
|
||||
repos.map((r) => ({
|
||||
name: r.name,
|
||||
path: r.path,
|
||||
repoPath: r.path,
|
||||
indexedAt: r.indexedAt,
|
||||
lastCommit: r.lastCommit,
|
||||
stats: r.stats,
|
||||
})),
|
||||
await Promise.all(
|
||||
repos.map(async (r) =>
|
||||
projectRepoListEntry(r, await checkStalenessAsync(r.path, r.lastCommit)),
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (err: any) {
|
||||
res.status(500).json({ error: err.message || 'Failed to list repos' });
|
||||
|
|
@ -1038,12 +1046,8 @@ export const createServer = async (port: number, host: string = '127.0.0.1') =>
|
|||
return;
|
||||
}
|
||||
const meta = await loadMeta(entry.storagePath);
|
||||
res.json({
|
||||
name: entry.name,
|
||||
repoPath: entry.path,
|
||||
indexedAt: meta?.indexedAt ?? entry.indexedAt,
|
||||
stats: meta?.stats ?? entry.stats ?? {},
|
||||
});
|
||||
const staleness = await checkStalenessAsync(entry.path, resolveLastCommit(entry, meta));
|
||||
res.json(projectRepoDetail(entry, meta, staleness));
|
||||
} catch (err: any) {
|
||||
res.status(500).json({ error: err.message || 'Failed to get repo info' });
|
||||
}
|
||||
|
|
|
|||
81
gitnexus/src/server/repo-projection.ts
Normal file
81
gitnexus/src/server/repo-projection.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
/**
|
||||
* Response projections for the `serve` repo routes.
|
||||
*
|
||||
* Extracted from the route bodies so the field list is assertable. Inline, the
|
||||
* projections were only reachable by booting a server and indexing a real
|
||||
* repository, which is how `branch` came to sit on `RegistryEntry` unexposed
|
||||
* over HTTP while `gitnexus list` printed it, with no test to notice (#3226).
|
||||
*
|
||||
* These are pure: the caller resolves the registry entry, the on-disk metadata
|
||||
* and the staleness check, and passes the results in.
|
||||
*/
|
||||
import type { StalenessInfo } from '../core/git-staleness.js';
|
||||
import type { RegistryEntry } from '../storage/repo-manager.js';
|
||||
import type { RepoMeta } from '../storage/repo-meta.js';
|
||||
|
||||
/**
|
||||
* Staleness in the shape MCP `list_repos` already returns
|
||||
* (`mcp/local/local-backend.ts`): the key is present only when the index is
|
||||
* actually behind, so "fresh" stays the absence of a field rather than a second
|
||||
* thing for a client to interpret. Deliberately identical across the two
|
||||
* surfaces — the same fact should not have two shapes.
|
||||
*
|
||||
* `checkStalenessAsync` self-catches and reports 0 commits behind when the
|
||||
* commit cannot be resolved, so an unanswerable check degrades to "not stale"
|
||||
* rather than failing the request that carries it.
|
||||
*
|
||||
* That makes the field meaningful mainly for `path`-registered repositories,
|
||||
* where an operator commits into the working tree the index was built from.
|
||||
* A `url` repository is cloned `--depth 1` and is re-analyzed by the same run
|
||||
* that pulls it, so its recorded commit is HEAD; and were the two ever to
|
||||
* diverge, `git rev-list <old>..HEAD` cannot walk a shallow history and fails
|
||||
* closed to "not stale". Reporting fresh there is not a claim that the remote
|
||||
* has not moved — this measures the index against the local working tree, the
|
||||
* same thing `gitnexus status` and MCP `list_repos` measure.
|
||||
*/
|
||||
export const stalenessField = (
|
||||
info: StalenessInfo,
|
||||
): { staleness?: { commitsBehind: number; hint?: string } } =>
|
||||
info.isStale ? { staleness: { commitsBehind: info.commitsBehind, hint: info.hint } } : {};
|
||||
|
||||
/** One entry of `GET /api/repos`. */
|
||||
export const projectRepoListEntry = (entry: RegistryEntry, staleness: StalenessInfo) => ({
|
||||
name: entry.name,
|
||||
path: entry.path,
|
||||
repoPath: entry.path,
|
||||
indexedAt: entry.indexedAt,
|
||||
lastCommit: entry.lastCommit,
|
||||
stats: entry.stats,
|
||||
// The registry has carried these since #2106; #3199 made them load-bearing
|
||||
// over HTTP, because a branch-pinned analyze now gets its own entry and the
|
||||
// only other way to tell two entries apart is to parse the clone-directory
|
||||
// slug — a layout detail, not an API contract.
|
||||
branch: entry.branch,
|
||||
branches: entry.branches,
|
||||
...stalenessField(staleness),
|
||||
});
|
||||
|
||||
/**
|
||||
* `GET /api/repo`. `meta ?? entry` throughout, for the reason `indexedAt`
|
||||
* already did it: the on-disk metadata is the fresher record when the two
|
||||
* disagree, and the entry is the fallback for a repo whose meta cannot be read.
|
||||
*/
|
||||
export const projectRepoDetail = (
|
||||
entry: RegistryEntry,
|
||||
meta: RepoMeta | null | undefined,
|
||||
staleness: StalenessInfo,
|
||||
) => ({
|
||||
name: entry.name,
|
||||
repoPath: entry.path,
|
||||
indexedAt: meta?.indexedAt ?? entry.indexedAt,
|
||||
stats: meta?.stats ?? entry.stats ?? {},
|
||||
lastCommit: meta?.lastCommit ?? entry.lastCommit,
|
||||
branch: meta?.branch ?? entry.branch,
|
||||
...stalenessField(staleness),
|
||||
});
|
||||
|
||||
/** The commit a `/api/repo` staleness check should be measured against. */
|
||||
export const resolveLastCommit = (
|
||||
entry: RegistryEntry,
|
||||
meta: RepoMeta | null | undefined,
|
||||
): string => meta?.lastCommit ?? entry.lastCommit;
|
||||
|
|
@ -7,9 +7,11 @@ import { closeLbug, executeParameterized } from '../../../src/core/lbug/pool-ada
|
|||
import type { GroupConfig, RepoHandle } from '../../../src/core/group/types.js';
|
||||
import { withTestLbugDB } from '../../helpers/test-indexed-db.js';
|
||||
|
||||
// Graph Method.startLine is 0-based (tree-sitter row). `health()` is source line 5.
|
||||
const SEED = [
|
||||
`CREATE (:Method {id:'method:health', name:'health', filePath:'src/health.resolver.ts', startLine:5, endLine:5, content:'', description:''})`,
|
||||
`CREATE (:Const {id:'const:health-document', name:'HealthDocument', filePath:'src/generated.ts', startLine:1, endLine:1, content:'', description:''})`,
|
||||
`CREATE (:Method {id:'method:health', name:'health', filePath:'src/health.resolver.ts', startLine:4, endLine:4, content:'', description:''})`,
|
||||
`CREATE (:Method {id:'method:save', name:'save', filePath:'src/health.resolver.ts', startLine:6, endLine:6, content:'', description:''})`,
|
||||
`CREATE (:Const {id:'const:health-document', name:'HealthDocument', filePath:'src/generated.ts', startLine:0, endLine:0, content:'', description:''})`,
|
||||
];
|
||||
|
||||
withTestLbugDB(
|
||||
|
|
@ -140,6 +142,42 @@ withTestLbugDB(
|
|||
registrySpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('binds a decorated arrow-field provider at the wrapper startLine (#3201)', async () => {
|
||||
providerRoot = path.join(handle.tmpHandle.dbPath, 'arrow-provider-repo');
|
||||
await fs.mkdir(path.join(providerRoot, 'src'), { recursive: true });
|
||||
await fs.writeFile(
|
||||
path.join(providerRoot, 'src/health.resolver.ts'),
|
||||
`import { Query, Mutation, Resolver } from '@nestjs/graphql';
|
||||
@Resolver()
|
||||
class HealthResolver {
|
||||
@Query()
|
||||
health() { return 'ok'; }
|
||||
|
||||
@Mutation()
|
||||
save = async () => true;
|
||||
}`,
|
||||
'utf8',
|
||||
);
|
||||
const providerRepo: RepoHandle = {
|
||||
id: handle.repoId,
|
||||
path: 'api',
|
||||
repoPath: providerRoot,
|
||||
storagePath: handle.tmpHandle.dbPath,
|
||||
};
|
||||
const execute = (query: string, params: Record<string, unknown> = {}) =>
|
||||
executeParameterized(handle.repoId, query, params);
|
||||
const contracts = await new GraphqlExtractor().extract(execute, providerRoot, providerRepo);
|
||||
expect(contracts).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
contractId: 'graphql::mutation::save',
|
||||
role: 'provider',
|
||||
symbolUid: 'method:save',
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
},
|
||||
{ seed: SEED, poolAdapter: true },
|
||||
);
|
||||
|
|
|
|||
223
gitnexus/test/integration/server-repo-freshness.test.ts
Normal file
223
gitnexus/test/integration/server-repo-freshness.test.ts
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
/**
|
||||
* End-to-end HTTP test of the branch/freshness fields on the repo routes (#3226).
|
||||
*
|
||||
* `repo-projection.test.ts` covers the projections in isolation. This proves the
|
||||
* REAL routes call them — the gap the #3199 review named directly ("the actual
|
||||
* glue, and nothing asserts it"): a unit test of a projection stays green if the
|
||||
* route stops using it, which is exactly how `branch` sat on `RegistryEntry`
|
||||
* unexposed while `gitnexus list` printed it.
|
||||
*
|
||||
* The fixture is a real git repository with two commits, registered with
|
||||
* `lastCommit` pinned to the FIRST one, so `git rev-list --count <first>..HEAD`
|
||||
* has a genuine answer (1) rather than a trivial zero. No index is written: both
|
||||
* routes read the registry, and `loadMeta` returning null is a case the
|
||||
* projection must already handle.
|
||||
*
|
||||
* Mirrors the spawn+health-poll harness in server-analyze-branch-validation.test.ts.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(__dirname, '..', '..');
|
||||
const DIST_CLI = path.join(REPO_ROOT, 'dist', 'cli', 'index.js');
|
||||
const STARTUP_BUDGET_MS = process.env.CI ? 30_000 : 15_000;
|
||||
const REPO_NAME = 'freshness-fixture';
|
||||
const INDEXED_AT = '2026-09-08T10:00:00.000Z';
|
||||
|
||||
const allocateFreePort = (): Promise<number> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const probe = http.createServer();
|
||||
probe.once('error', reject);
|
||||
probe.listen(0, '127.0.0.1', () => {
|
||||
const addr = probe.address();
|
||||
if (typeof addr !== 'object' || !addr) {
|
||||
probe.close();
|
||||
reject(new Error('could not allocate ephemeral port'));
|
||||
return;
|
||||
}
|
||||
const port = addr.port;
|
||||
probe.close((err) => (err ? reject(err) : resolve(port)));
|
||||
});
|
||||
});
|
||||
|
||||
const httpJson = (port: number, reqPath: string): Promise<{ status: number; body: string }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const req = http.request({ host: '127.0.0.1', port, path: reqPath, method: 'GET' }, (res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (c) => chunks.push(c));
|
||||
res.on('end', () =>
|
||||
resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }),
|
||||
);
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.setTimeout(5_000, () => {
|
||||
req.destroy();
|
||||
reject(new Error(`GET ${reqPath} timed out`));
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
|
||||
// Spawned `serve` on Windows can report ready before the socket is reachable
|
||||
// from the parent (see server-http-startup.test.ts).
|
||||
const describeBlock = process.platform === 'win32' ? describe.skip : describe;
|
||||
|
||||
describeBlock('repo routes expose branch and freshness (real server)', () => {
|
||||
let proc: ChildProcessWithoutNullStreams | undefined;
|
||||
let homeDir: string | undefined;
|
||||
let port = 0;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!fs.existsSync(DIST_CLI)) {
|
||||
throw new Error(`Missing ${DIST_CLI} — run npm run build before integration tests`);
|
||||
}
|
||||
|
||||
homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-freshness-'));
|
||||
const repoPath = path.join(homeDir, 'repos', REPO_NAME);
|
||||
fs.mkdirSync(repoPath, { recursive: true });
|
||||
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync('git', args, { cwd: repoPath, encoding: 'utf-8' }).trim();
|
||||
git('init', '--quiet', '--initial-branch=main');
|
||||
git('config', 'user.email', 'test@example.com');
|
||||
git('config', 'user.name', 'GitNexus Test');
|
||||
fs.writeFileSync(path.join(repoPath, 'a.js'), 'export const a = 1;\n');
|
||||
git('add', '-A');
|
||||
git('commit', '--quiet', '-m', 'first');
|
||||
const firstCommit = git('rev-parse', 'HEAD');
|
||||
fs.writeFileSync(path.join(repoPath, 'b.js'), 'export const b = 2;\n');
|
||||
git('add', '-A');
|
||||
git('commit', '--quiet', '-m', 'second');
|
||||
|
||||
// The storage directory must exist: `serve` prunes registry rows whose
|
||||
// `storagePath` is gone, so a fixture without it is silently dropped and the
|
||||
// route legitimately returns nothing (found while writing this test).
|
||||
const storagePath = path.join(repoPath, '.gitnexus');
|
||||
fs.mkdirSync(storagePath, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(storagePath, 'gitnexus.json'),
|
||||
JSON.stringify({
|
||||
repoPath,
|
||||
indexedAt: INDEXED_AT,
|
||||
lastCommit: firstCommit,
|
||||
branch: 'main',
|
||||
stats: { files: 1, nodes: 2, edges: 1 },
|
||||
}),
|
||||
);
|
||||
|
||||
// Registered as if indexed at the FIRST commit: one commit behind HEAD.
|
||||
fs.writeFileSync(
|
||||
path.join(homeDir, 'registry.json'),
|
||||
JSON.stringify([
|
||||
{
|
||||
name: REPO_NAME,
|
||||
path: repoPath,
|
||||
storagePath,
|
||||
indexedAt: INDEXED_AT,
|
||||
lastCommit: firstCommit,
|
||||
branch: 'main',
|
||||
stats: { files: 1, nodes: 2, edges: 1 },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
port = await allocateFreePort();
|
||||
proc = spawn(
|
||||
process.execPath,
|
||||
[DIST_CLI, 'serve', '--port', String(port), '--host', '127.0.0.1'],
|
||||
{
|
||||
cwd: REPO_ROOT,
|
||||
env: { ...process.env, GITNEXUS_HOME: homeDir, NODE_OPTIONS: '' },
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
},
|
||||
);
|
||||
|
||||
let stderr = '';
|
||||
proc.stderr.on('data', (buf) => {
|
||||
stderr += buf.toString();
|
||||
});
|
||||
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < STARTUP_BUDGET_MS) {
|
||||
if (proc.exitCode !== null) {
|
||||
throw new Error(`serve exited ${proc.exitCode} before ready.\nstderr:\n${stderr}`);
|
||||
}
|
||||
try {
|
||||
const { status } = await httpJson(port, '/api/health');
|
||||
if (status === 200) return;
|
||||
} catch {
|
||||
// Server still starting — retry until budget expires.
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
throw new Error(
|
||||
`serve did not become ready within ${STARTUP_BUDGET_MS}ms.\nstderr:\n${stderr}`,
|
||||
);
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (proc && !proc.killed) {
|
||||
proc.kill('SIGTERM');
|
||||
await new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
proc?.kill('SIGKILL');
|
||||
resolve();
|
||||
}, 3_000);
|
||||
proc?.on('exit', () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
proc = undefined;
|
||||
if (homeDir) {
|
||||
fs.rmSync(homeDir, { recursive: true, force: true });
|
||||
homeDir = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
it('GET /api/repos returns branch and a real commits-behind count', async () => {
|
||||
const { status, body } = await httpJson(port, '/api/repos');
|
||||
expect(status).toBe(200);
|
||||
const entry = JSON.parse(body).find((r: { name: string }) => r.name === REPO_NAME);
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry.branch).toBe('main');
|
||||
// Genuinely computed by `git rev-list`, not a fixture constant.
|
||||
expect(entry.staleness).toEqual({
|
||||
commitsBehind: 1,
|
||||
hint: expect.stringContaining('1 commit behind'),
|
||||
});
|
||||
});
|
||||
|
||||
it('GET /api/repos still returns the fields it always did', async () => {
|
||||
// Additive only — an existing client must not notice this change.
|
||||
const { body } = await httpJson(port, '/api/repos');
|
||||
const entry = JSON.parse(body).find((r: { name: string }) => r.name === REPO_NAME);
|
||||
expect(entry).toMatchObject({
|
||||
name: REPO_NAME,
|
||||
path: expect.any(String),
|
||||
repoPath: expect.any(String),
|
||||
indexedAt: expect.any(String),
|
||||
lastCommit: expect.any(String),
|
||||
stats: expect.any(Object),
|
||||
});
|
||||
});
|
||||
|
||||
it('GET /api/repo returns lastCommit and branch, which it used to drop', async () => {
|
||||
const { status, body } = await httpJson(port, `/api/repo?repo=${REPO_NAME}`);
|
||||
expect(status).toBe(200);
|
||||
const repo = JSON.parse(body);
|
||||
expect(repo.lastCommit).toMatch(/^[0-9a-f]{40}$/);
|
||||
expect(repo.branch).toBe('main');
|
||||
expect(repo.staleness).toEqual({
|
||||
commitsBehind: 1,
|
||||
hint: expect.stringContaining('1 commit behind'),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -8,8 +8,20 @@ import {
|
|||
pageSizeDoctorLines,
|
||||
poolSizeDoctorLine,
|
||||
} from '../../src/cli/doctor.js';
|
||||
import { setCliLanguage, type SupportedCliLanguage } from '../../src/cli/i18n/index.js';
|
||||
import type { NativeCheckResult } from '../../src/core/lbug/native-check.js';
|
||||
|
||||
const nativeProbeState = vi.hoisted(() => ({ vectorLoaded: true }));
|
||||
|
||||
vi.mock('../../src/core/lbug/native-check.js', () => ({
|
||||
checkLbugNative: () => ({ ok: true, binaryPath: '/synthetic/lbugjs.node' }),
|
||||
probeFtsExtensionLoad: async () => ({ loaded: true }),
|
||||
probeVectorExtensionLoad: async () =>
|
||||
nativeProbeState.vectorLoaded
|
||||
? { loaded: true }
|
||||
: { loaded: false, reason: 'synthetic VECTOR load failure' },
|
||||
}));
|
||||
|
||||
describe('doctor output formatting', () => {
|
||||
it('keeps ASCII padding equivalent to String.padEnd', () => {
|
||||
expect(displayWidth('OS:')).toBe(3);
|
||||
|
|
@ -29,6 +41,67 @@ describe('doctor output formatting', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('doctor VECTOR capability claims', () => {
|
||||
const ENV_KEYS = [
|
||||
'GITNEXUS_EMBEDDING_URL',
|
||||
'GITNEXUS_EMBEDDING_MODEL',
|
||||
'GITNEXUS_EMBEDDING_DIMS',
|
||||
] as const;
|
||||
const savedEnv = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));
|
||||
|
||||
const renderDoctor = async (
|
||||
vectorLoaded: boolean,
|
||||
language: SupportedCliLanguage = 'en',
|
||||
): Promise<string> => {
|
||||
nativeProbeState.vectorLoaded = vectorLoaded;
|
||||
setCliLanguage(language);
|
||||
process.env.GITNEXUS_EMBEDDING_URL = 'http://127.0.0.1:9/v1';
|
||||
process.env.GITNEXUS_EMBEDDING_MODEL = 'synthetic-doctor';
|
||||
process.env.GITNEXUS_EMBEDDING_DIMS = '384';
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
|
||||
await doctorCommand();
|
||||
|
||||
return log.mock.calls.map((args) => args.map(String).join(' ')).join('\n');
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
nativeProbeState.vectorLoaded = true;
|
||||
setCliLanguage(null);
|
||||
vi.restoreAllMocks();
|
||||
for (const key of ENV_KEYS) {
|
||||
if (savedEnv[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = savedEnv[key];
|
||||
}
|
||||
});
|
||||
|
||||
it('reports a loaded extension without claiming a repository index exists', async () => {
|
||||
const output = await renderDoctor(true);
|
||||
|
||||
expect(output).toContain('VECTOR extension: available');
|
||||
expect(output).toContain(
|
||||
'Semantic support: vector-index capable (repository index not checked)',
|
||||
);
|
||||
expect(output).not.toContain('VECTOR index:');
|
||||
expect(output).not.toContain('Semantic mode:');
|
||||
});
|
||||
|
||||
it('reports exact-scan capability when the extension cannot load', async () => {
|
||||
const output = await renderDoctor(false);
|
||||
|
||||
expect(output).toContain('VECTOR extension: unavailable');
|
||||
expect(output).toContain('Semantic support: exact-scan only (VECTOR extension unavailable)');
|
||||
});
|
||||
|
||||
it('keeps the corrected capability claims localized', async () => {
|
||||
const output = await renderDoctor(true, 'zh-CN');
|
||||
|
||||
expect(output).toContain('VECTOR 扩展:');
|
||||
expect(output).toContain('语义支持:');
|
||||
expect(output).toContain('支持向量索引(未检查仓库索引)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('doctor embedding-runtime support status', () => {
|
||||
it('flags local embeddings as unavailable on macOS Intel (darwin/x64)', () => {
|
||||
const { status, detail } = localEmbeddingDoctorStatus({
|
||||
|
|
|
|||
|
|
@ -499,4 +499,408 @@ export const TwoDocument = ${generatedDocument('query', 'Two', ['two'])};
|
|||
]);
|
||||
expect(parseSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('binds NestJS providers at the 0-based graph startLine (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/health.resolver.ts': `import { Query, Mutation, Resolver } from '@nestjs/graphql';
|
||||
@Resolver()
|
||||
class HealthResolver {
|
||||
@Query()
|
||||
health() { return 'ok'; }
|
||||
|
||||
@Mutation()
|
||||
save = async () => true;
|
||||
}`,
|
||||
});
|
||||
const graphStartLine: Record<string, number> = { health: 4, save: 6 };
|
||||
const startLines: Array<{ name: string; startLine: number }> = [];
|
||||
const run: CypherExecutor = async (_query, params = {}) => {
|
||||
const name = String(params.name);
|
||||
const startLine = Number(params.startLine);
|
||||
startLines.push({ name, startLine });
|
||||
if (graphStartLine[name] !== startLine) return [];
|
||||
return [{ uid: `sym:${name}`, name, filePath: 'src/health.resolver.ts' }];
|
||||
};
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(run, root, repo);
|
||||
|
||||
expect(startLines).toEqual([
|
||||
{ name: 'health', startLine: 4 },
|
||||
{ name: 'save', startLine: 6 },
|
||||
]);
|
||||
expect(contracts.map((contract) => contract.contractId)).toEqual([
|
||||
'graphql::query::health',
|
||||
'graphql::mutation::save',
|
||||
]);
|
||||
});
|
||||
|
||||
it('tries the PascalCased Document name graphql-codegen emits (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/timeline.graphql': `query widgetTimeline { getWidget }`,
|
||||
'src/generated.ts': `export const WidgetTimelineDocument = ${generatedDocument(
|
||||
'query',
|
||||
'widgetTimeline',
|
||||
['getWidget'],
|
||||
)};`,
|
||||
});
|
||||
const lookedUp: string[] = [];
|
||||
const run: CypherExecutor = async (_query, params = {}) => {
|
||||
const name = String(params.name ?? '');
|
||||
lookedUp.push(name);
|
||||
return name === 'WidgetTimelineDocument'
|
||||
? [
|
||||
{
|
||||
uid: 'const:timeline',
|
||||
name: 'WidgetTimelineDocument',
|
||||
filePath: 'src/generated.ts',
|
||||
},
|
||||
]
|
||||
: [];
|
||||
};
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(run, root, repo);
|
||||
|
||||
expect(lookedUp).toEqual(['widgetTimelineDocument', 'WidgetTimelineDocument']);
|
||||
expect(contracts).toEqual([
|
||||
expect.objectContaining({
|
||||
contractId: 'graphql::query::getWidget',
|
||||
role: 'consumer',
|
||||
symbolUid: 'const:timeline',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('tries the full PascalCased Document name for underscored operations (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/widget.graphql': `query get_widget { getWidget }`,
|
||||
'src/generated.ts': `export const GetWidgetDocument = ${generatedDocument(
|
||||
'query',
|
||||
'get_widget',
|
||||
['getWidget'],
|
||||
)};`,
|
||||
});
|
||||
const lookedUp: string[] = [];
|
||||
const run: CypherExecutor = async (_query, params = {}) => {
|
||||
const name = String(params.name ?? '');
|
||||
lookedUp.push(name);
|
||||
return name === 'GetWidgetDocument'
|
||||
? [
|
||||
{
|
||||
uid: 'const:widget',
|
||||
name: 'GetWidgetDocument',
|
||||
filePath: 'src/generated.ts',
|
||||
},
|
||||
]
|
||||
: [];
|
||||
};
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(run, root, repo);
|
||||
|
||||
expect(lookedUp).toEqual(['get_widgetDocument', 'GetWidgetDocument']);
|
||||
expect(contracts).toEqual([
|
||||
expect.objectContaining({
|
||||
contractId: 'graphql::query::getWidget',
|
||||
role: 'consumer',
|
||||
symbolUid: 'const:widget',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('inlines sibling ${FragmentDoc} interpolations to prove generated documents (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/get-widget.graphql': `
|
||||
fragment widget on Widget { id }
|
||||
query GetWidget { getWidget { ...widget } }
|
||||
`,
|
||||
'src/root-spread.graphql': `
|
||||
fragment MoreRoots on Query { gadget }
|
||||
query GetWidgets { ...MoreRoots }
|
||||
`,
|
||||
'src/generated.ts': `
|
||||
export const WidgetFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment widget on Widget { id }
|
||||
\`;
|
||||
export const GetWidgetDocument = /*#__PURE__*/ \`
|
||||
query GetWidget {
|
||||
getWidget {
|
||||
...widget
|
||||
}
|
||||
}
|
||||
\${WidgetFragmentDoc}\`;
|
||||
export const MoreRootsFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment MoreRoots on Query { gadget }
|
||||
\`;
|
||||
export const GetWidgetsDocument = gql\`
|
||||
query GetWidgets { ...MoreRoots }
|
||||
\${MoreRootsFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
GetWidgetDocument: [
|
||||
{ uid: 'const:widget', name: 'GetWidgetDocument', filePath: 'src/generated.ts' },
|
||||
],
|
||||
GetWidgetsDocument: [
|
||||
{ uid: 'const:widgets', name: 'GetWidgetsDocument', filePath: 'src/generated.ts' },
|
||||
],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts.map((contract) => [contract.contractId, contract.symbolUid]).sort()).toEqual([
|
||||
['graphql::query::gadget', 'const:widgets'],
|
||||
['graphql::query::getWidget', 'const:widget'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails closed for dynamic or cyclic generated interpolations (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/dynamic.graphql': `query Dynamic { dynamic }`,
|
||||
'src/cycle.graphql': `query Cycle { cycle }`,
|
||||
'src/generated.ts': `
|
||||
export const DynamicDocument = \`query Dynamic { dynamic }\${foo.bar}\`;
|
||||
export const CycleFragmentDoc = \`\${CycleDocument}\`;
|
||||
export const CycleDocument = \`query Cycle { cycle }\${CycleFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
DynamicDocument: [
|
||||
{ uid: 'const:dynamic', name: 'DynamicDocument', filePath: 'src/generated.ts' },
|
||||
],
|
||||
CycleDocument: [
|
||||
{ uid: 'const:cycle', name: 'CycleDocument', filePath: 'src/generated.ts' },
|
||||
],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([]);
|
||||
});
|
||||
|
||||
it('fails closed when sibling ${FragmentDoc} names resolve to two static sources (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/get-widget.graphql': `query GetWidget { getWidget }`,
|
||||
'src/generated.ts': `
|
||||
{
|
||||
const WidgetFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment widget on Widget { id }
|
||||
\`;
|
||||
}
|
||||
export const WidgetFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment widget on Widget { name }
|
||||
\`;
|
||||
export const GetWidgetDocument = /*#__PURE__*/ \`
|
||||
query GetWidget { getWidget { ...widget } }
|
||||
\${WidgetFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
GetWidgetDocument: [
|
||||
{ uid: 'const:widget', name: 'GetWidgetDocument', filePath: 'src/generated.ts' },
|
||||
],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([]);
|
||||
});
|
||||
|
||||
it('fails closed when a FragmentDoc name has a static and a dynamic declarator (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/get-widget.graphql': `query GetWidget { getWidget }`,
|
||||
'src/generated.ts': `
|
||||
{
|
||||
const WidgetFragmentDoc = \`\${foo.bar}\`;
|
||||
}
|
||||
export const WidgetFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment widget on Widget { id }
|
||||
\`;
|
||||
export const GetWidgetDocument = /*#__PURE__*/ \`
|
||||
query GetWidget { getWidget { ...widget } }
|
||||
\${WidgetFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
GetWidgetDocument: [
|
||||
{ uid: 'const:widget', name: 'GetWidgetDocument', filePath: 'src/generated.ts' },
|
||||
],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([]);
|
||||
});
|
||||
|
||||
it('treats template line continuations as empty while inlining ${FragmentDoc} (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/q.graphql': `query Q { q }`,
|
||||
'src/generated.ts': `
|
||||
export const QFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment extra on Query { q }
|
||||
\`;
|
||||
export const QDocument = gql\`query Q { q }\\
|
||||
\${QFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
QDocument: [{ uid: 'const:q', name: 'QDocument', filePath: 'src/generated.ts' }],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([
|
||||
expect.objectContaining({
|
||||
contractId: 'graphql::query::q',
|
||||
role: 'consumer',
|
||||
symbolUid: 'const:q',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails closed for NonOctalDecimalEscapeSequence in interpolated gql templates (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/q.graphql': `query Q { q }`,
|
||||
'src/generated.ts': `
|
||||
export const QFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment extra on Query { q }
|
||||
\`;
|
||||
export const QDocument = gql\`query Q { q }\\8\${QFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
QDocument: [{ uid: 'const:q', name: 'QDocument', filePath: 'src/generated.ts' }],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([]);
|
||||
});
|
||||
|
||||
it('decodes escape_sequence nodes while inlining ${FragmentDoc} (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/q.graphql': `query Q { q }`,
|
||||
'src/generated.ts': `
|
||||
export const QFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment extra on Query { q }
|
||||
\`;
|
||||
export const QDocument = gql\`query Q { q }\\n\${QFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
QDocument: [{ uid: 'const:q', name: 'QDocument', filePath: 'src/generated.ts' }],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([
|
||||
expect.objectContaining({
|
||||
contractId: 'graphql::query::q',
|
||||
role: 'consumer',
|
||||
symbolUid: 'const:q',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails closed for interpolated templates under a non-gql tag (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/q.graphql': `query Q { q }`,
|
||||
'src/generated.ts': `
|
||||
export const QFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment extra on Query { q }
|
||||
\`;
|
||||
export const QDocument = String.raw\`query Q { q }\\n\${QFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
QDocument: [{ uid: 'const:q', name: 'QDocument', filePath: 'src/generated.ts' }],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([]);
|
||||
});
|
||||
|
||||
it('memoizes interpolation sources so duplicated fragment layers stay linear (#3201)', async () => {
|
||||
const layers = 16;
|
||||
let generated = `
|
||||
export const F0 = \`fragment f0 on Query { q }\`;
|
||||
{ const F0 = \`fragment f0 on Query { q }\`; }
|
||||
`;
|
||||
for (let i = 1; i <= layers; i++) {
|
||||
const prev = `F${i - 1}`;
|
||||
const cur = `F${i}`;
|
||||
generated += `
|
||||
export const ${cur} = \`\${${prev}}\`;
|
||||
{ const ${cur} = \`\${${prev}}\`; }
|
||||
`;
|
||||
}
|
||||
generated += `
|
||||
export const QDocument = gql\`query Q { q }\${F${layers}}\`;
|
||||
`;
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/q.graphql': `query Q { q }`,
|
||||
'src/generated.ts': generated,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
QDocument: [{ uid: 'const:q', name: 'QDocument', filePath: 'src/generated.ts' }],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([
|
||||
expect.objectContaining({
|
||||
contractId: 'graphql::query::q',
|
||||
role: 'consumer',
|
||||
symbolUid: 'const:q',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails closed for interpolated templates under a member .gql tag (#3201)', async () => {
|
||||
const { root, repo } = await makeRepo({
|
||||
'src/q.graphql': `query Q { q }`,
|
||||
'src/generated.ts': `
|
||||
export const QFragmentDoc = /*#__PURE__*/ \`
|
||||
fragment extra on Query { q }
|
||||
\`;
|
||||
export const QDocument = formatter.gql\`query Q { q }\\n\${QFragmentDoc}\`;
|
||||
`,
|
||||
});
|
||||
|
||||
const contracts = await new GraphqlExtractor().extract(
|
||||
executor({
|
||||
QDocument: [{ uid: 'const:q', name: 'QDocument', filePath: 'src/generated.ts' }],
|
||||
}),
|
||||
root,
|
||||
repo,
|
||||
);
|
||||
|
||||
expect(contracts).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -250,6 +250,14 @@ describe('production routes — rate-limit middleware wiring', () => {
|
|||
expect(apiSource).toMatch(/app\.get\('\/api\/repo',\s*createRouteLimiter\(/);
|
||||
});
|
||||
|
||||
it('GET /api/repos is wired with createRouteLimiter', () => {
|
||||
// Carries a limiter because it spawns a `git rev-list` per registered repo
|
||||
// to answer freshness — an unauthenticated GET whose cost scales with the
|
||||
// number of indexed repos. Pinned here so dropping the limiter fails a test
|
||||
// before it has to be caught by CodeQL (#3232).
|
||||
expect(apiSource).toMatch(/app\.get\('\/api\/repos',\s*createRouteLimiter\(/);
|
||||
});
|
||||
|
||||
it('POST /api/analyze is wired with createRouteLimiter', () => {
|
||||
// Tolerate Prettier wrapping the registration across lines (it does once
|
||||
// the route carries extra middleware like requireTrustedOrigin).
|
||||
|
|
|
|||
165
gitnexus/test/unit/repo-projection.test.ts
Normal file
165
gitnexus/test/unit/repo-projection.test.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
/**
|
||||
* The `serve` repo-route projections (#3226).
|
||||
*
|
||||
* These exist as a separate module precisely so this file can exist: inline in
|
||||
* `createServer`, the field list was only reachable by booting a server and
|
||||
* indexing a real repository, which is how `branch` sat on `RegistryEntry`
|
||||
* unexposed over HTTP while `gitnexus list` printed it and MCP `list_repos`
|
||||
* returned staleness.
|
||||
*
|
||||
* The cases below are the ones a projection regresses on silently: a dropped
|
||||
* optional field still serializes, and a "fresh" index is indistinguishable
|
||||
* from one whose staleness check could not run unless the shape says so.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
projectRepoDetail,
|
||||
projectRepoListEntry,
|
||||
resolveLastCommit,
|
||||
stalenessField,
|
||||
} from '../../src/server/repo-projection.js';
|
||||
import type { StalenessInfo } from '../../src/core/git-staleness.js';
|
||||
import type { RegistryEntry } from '../../src/storage/repo-manager.js';
|
||||
import type { RepoMeta } from '../../src/storage/repo-meta.js';
|
||||
|
||||
const FRESH: StalenessInfo = { isStale: false, commitsBehind: 0 };
|
||||
const BEHIND: StalenessInfo = {
|
||||
isStale: true,
|
||||
commitsBehind: 3,
|
||||
hint: '⚠️ Index is 3 commits behind HEAD. Run analyze tool to update.',
|
||||
};
|
||||
|
||||
const meta = (over: Partial<RepoMeta> = {}): RepoMeta =>
|
||||
({
|
||||
indexedAt: '2026-09-08T12:00:00.000Z',
|
||||
lastCommit: 'ffffffffffffffffffffffffffffffffffffffff',
|
||||
branch: 'develop',
|
||||
stats: { files: 11, nodes: 111, edges: 555 },
|
||||
...over,
|
||||
}) as RepoMeta;
|
||||
|
||||
const entry = (over: Partial<RegistryEntry> = {}): RegistryEntry => ({
|
||||
name: 'Hello-World',
|
||||
path: '/home/u/.gitnexus/repos/Hello-World',
|
||||
storagePath: '/home/u/.gitnexus/repos/Hello-World/.gitnexus',
|
||||
indexedAt: '2026-09-08T10:00:00.000Z',
|
||||
lastCommit: '7fd1a60b01f91b314f59955a4e4d4e80d8edf11d',
|
||||
stats: { files: 10, nodes: 100, edges: 500 },
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('stalenessField', () => {
|
||||
it('omits the key entirely for a fresh index', () => {
|
||||
// Absence IS the "fresh" signal, matching MCP list_repos. A client must not
|
||||
// have to distinguish `undefined` from `{commitsBehind: 0}`.
|
||||
expect(stalenessField(FRESH)).toEqual({});
|
||||
expect(Object.hasOwn(stalenessField(FRESH), 'staleness')).toBe(false);
|
||||
});
|
||||
|
||||
it('reports commits behind and the hint when the index is behind', () => {
|
||||
expect(stalenessField(BEHIND)).toEqual({
|
||||
staleness: { commitsBehind: 3, hint: BEHIND.hint },
|
||||
});
|
||||
});
|
||||
|
||||
it('treats an unresolvable check as fresh rather than as an error', () => {
|
||||
// checkStalenessAsync self-catches to {isStale:false, commitsBehind:0} for a
|
||||
// shallow clone, rewritten history or a non-git path. That must degrade to a
|
||||
// normal response, never a 500 on a route whose job is to list repos.
|
||||
expect(stalenessField({ isStale: false, commitsBehind: 0 })).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('projectRepoListEntry — GET /api/repos', () => {
|
||||
it('exposes branch and branches, which the registry has always carried', () => {
|
||||
const out = projectRepoListEntry(
|
||||
entry({
|
||||
branch: 'master',
|
||||
branches: [{ branch: 'test', indexedAt: '2026-09-08T11:00:00.000Z', lastCommit: 'abc123' }],
|
||||
}) as RegistryEntry,
|
||||
FRESH,
|
||||
);
|
||||
expect(out.branch).toBe('master');
|
||||
expect(out.branches).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('distinguishes the two entries #3199 creates for one repository', () => {
|
||||
// A pinned analyze registers under its clone-directory name. Without
|
||||
// `branch`, these two are only tellable apart by parsing that slug — a
|
||||
// layout detail that is trimmed for long refs and absent for path entries.
|
||||
const primary = projectRepoListEntry(entry({ branch: 'master' }), FRESH);
|
||||
const pinned = projectRepoListEntry(
|
||||
entry({ name: 'Hello-World__test-9f86d081', branch: 'test' }),
|
||||
FRESH,
|
||||
);
|
||||
expect([primary.branch, pinned.branch]).toEqual(['master', 'test']);
|
||||
});
|
||||
|
||||
it('keeps every field the route returned before, unchanged', () => {
|
||||
// Additive only: an existing client must not notice this change.
|
||||
const e = entry();
|
||||
const out = projectRepoListEntry(e, FRESH);
|
||||
expect(out).toMatchObject({
|
||||
name: e.name,
|
||||
path: e.path,
|
||||
repoPath: e.path,
|
||||
indexedAt: e.indexedAt,
|
||||
lastCommit: e.lastCommit,
|
||||
stats: e.stats,
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves branch undefined for a legacy entry that never recorded one', () => {
|
||||
const out = projectRepoListEntry(entry(), FRESH);
|
||||
expect(out.branch).toBeUndefined();
|
||||
expect(out.branches).toBeUndefined();
|
||||
});
|
||||
|
||||
it('carries staleness through for a behind index', () => {
|
||||
expect(projectRepoListEntry(entry(), BEHIND).staleness).toEqual({
|
||||
commitsBehind: 3,
|
||||
hint: BEHIND.hint,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('projectRepoDetail — GET /api/repo', () => {
|
||||
it('returns lastCommit and branch, which the route used to drop', () => {
|
||||
const out = projectRepoDetail(entry({ branch: 'master' }), null, FRESH);
|
||||
expect(out.lastCommit).toBe(entry().lastCommit);
|
||||
expect(out.branch).toBe('master');
|
||||
});
|
||||
|
||||
it('prefers on-disk metadata over the registry entry, as indexedAt already did', () => {
|
||||
const out = projectRepoDetail(entry({ branch: 'master' }), meta(), FRESH);
|
||||
expect(out.indexedAt).toBe('2026-09-08T12:00:00.000Z');
|
||||
expect(out.lastCommit).toBe('ffffffffffffffffffffffffffffffffffffffff');
|
||||
expect(out.branch).toBe('develop');
|
||||
});
|
||||
|
||||
it('falls back to the entry when metadata cannot be read', () => {
|
||||
const out = projectRepoDetail(entry({ branch: 'master' }), undefined, FRESH);
|
||||
expect(out.indexedAt).toBe(entry().indexedAt);
|
||||
expect(out.lastCommit).toBe(entry().lastCommit);
|
||||
expect(out.branch).toBe('master');
|
||||
});
|
||||
|
||||
it('still returns an empty stats object rather than undefined', () => {
|
||||
// Pre-existing contract: the route returned `{}` when neither side had stats.
|
||||
expect(projectRepoDetail(entry({ stats: undefined }), null, FRESH).stats).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveLastCommit', () => {
|
||||
it('measures staleness against the commit the response reports', () => {
|
||||
// If these two disagreed, the route would report one commit and compute
|
||||
// commits-behind from another — a freshness number for a different index.
|
||||
const e = entry();
|
||||
const m = meta();
|
||||
expect(resolveLastCommit(e, m)).toBe(projectRepoDetail(e, m, FRESH).lastCommit);
|
||||
});
|
||||
|
||||
it('falls back to the registry entry with no metadata', () => {
|
||||
expect(resolveLastCommit(entry(), null)).toBe(entry().lastCommit);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Reference in a new issue