From 00966630c4e2645fda4909913a9deed10963002d Mon Sep 17 00:00:00 2001 From: ivkond Date: Mon, 20 Apr 2026 13:55:07 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20cross-repo=20impact=20analysis=20(#794)?= =?UTF-8?q?=20=E2=80=94=20@repo=20MCP=20routing=20+=20group=20resources=20?= =?UTF-8?q?(#984)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 + AGENTS.md | 11 +- ARCHITECTURE.md | 13 +- gitnexus/CHANGELOG.md | 6 + gitnexus/src/cli/ai-context.ts | 2 +- gitnexus/src/cli/group.ts | 77 +++ gitnexus/src/core/group/cross-impact.ts | 562 ++++++++++++++++++ gitnexus/src/core/group/group-path-utils.ts | 42 ++ gitnexus/src/core/group/resolve-at-member.ts | 34 ++ gitnexus/src/core/group/service.ts | 330 ++++++++-- gitnexus/src/core/group/types.ts | 33 + gitnexus/src/core/lbug/lbug-adapter.ts | 36 ++ gitnexus/src/core/run-analyze.ts | 18 +- gitnexus/src/core/search/bm25-index.ts | 72 ++- gitnexus/src/mcp/local/local-backend.ts | 156 ++++- gitnexus/src/mcp/resources.ts | 149 ++++- gitnexus/src/mcp/tools.ts | 144 +++-- .../test/integration/group/group-cli.test.ts | 47 ++ .../integration/group/group-impact.test.ts | 74 +++ gitnexus/test/unit/group/cross-impact.test.ts | 196 ++++++ .../test/unit/group/group-path-utils.test.ts | 87 +++ .../group/group-service-group-mode.test.ts | 129 ++++ gitnexus/test/unit/group/group-tools.test.ts | 10 +- gitnexus/test/unit/group/service.test.ts | 173 ++++++ .../test/unit/mcp/group-repo-routing.test.ts | 230 +++++++ gitnexus/test/unit/resources.test.ts | 86 ++- gitnexus/test/unit/tools.test.ts | 42 +- 27 files changed, 2584 insertions(+), 178 deletions(-) create mode 100644 gitnexus/src/core/group/cross-impact.ts create mode 100644 gitnexus/src/core/group/group-path-utils.ts create mode 100644 gitnexus/src/core/group/resolve-at-member.ts create mode 100644 gitnexus/test/integration/group/group-impact.test.ts create mode 100644 gitnexus/test/unit/group/cross-impact.test.ts create mode 100644 gitnexus/test/unit/group/group-path-utils.test.ts create mode 100644 gitnexus/test/unit/group/group-service-group-mode.test.ts create mode 100644 gitnexus/test/unit/mcp/group-repo-routing.test.ts diff --git a/.gitignore b/.gitignore index 95c9164e0..92027b529 100644 --- a/.gitignore +++ b/.gitignore @@ -103,3 +103,6 @@ gitnexus/vendor/**/node_modules/ local_docs/ +# Local agent scratch / review prompts (never commit) +.tmp/ +.agents/ diff --git a/AGENTS.md b/AGENTS.md index f4fbcadc0..6e916ff0b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,6 +47,7 @@ Commands and gotchas live under **Repo reference** below and in **[CONTRIBUTING. | Date | Version | Change | |------|---------|--------| +| 2026-04-19 | 1.5.0 | Cross-repo impact (#794): `impact`/`query`/`context` accept `repo: "@"` + `service`. Removed `group_query`/`group_contracts`/`group_status` MCP tools; added `gitnexus://group/{name}/contracts` and `gitnexus://group/{name}/status` resources. | | 2026-04-16 | 1.4.0 | Fixed: web UI description, pre-commit behavior, MCP tools (7->16), added gitnexus-shared, removed stale vite-plugin-wasm gotcha. | | 2026-04-13 | 1.3.0 | Updated GitNexus index stats after DAG refactor. | | 2026-03-24 | 1.2.0 | Fixed gitnexus:start block duplication. | @@ -107,10 +108,12 @@ Indexed as **GitNexus** (4325 symbols, 10556 relationships, 300 execution flows) | `tool_map` | MCP/RPC tool definitions | `gitnexus_tool_map({})` | | `shape_check` | Response shape vs consumer access | `gitnexus_shape_check({route: "/api/users"})` | | `group_list` | List repo groups | `gitnexus_group_list({})` | -| `group_query` | Cross-repo search in a group | `gitnexus_group_query({name: "myGroup", query: "auth"})` | | `group_sync` | Rebuild group Contract Registry | `gitnexus_group_sync({name: "myGroup"})` | -| `group_contracts` | Inspect group contracts | `gitnexus_group_contracts({name: "myGroup"})` | -| `group_status` | Group staleness report | `gitnexus_group_status({name: "myGroup"})` | +| `query` (group mode) | Cross-repo search in a group (RRF-merged) | `gitnexus_query({repo: "@myGroup", query: "auth"})` | +| `context` (group mode) | 360° view across all member repos | `gitnexus_context({repo: "@myGroup", name: "validateUser"})` | +| `impact` (group mode) | Cross-repo blast radius via Contract Bridge | `gitnexus_impact({repo: "@myGroup", target: "X", direction: "upstream"})` | + +> Group mode: pass `repo: "@"` to fan out across all member repos, or `repo: "@/"` to target a single member (path keys from `group.yaml`). Optional `service: ""` filters by service root. Group-level state (contracts, staleness) lives in the resources table below — there are **no** `group_query` / `group_context` / `group_impact` / `group_contracts` / `group_status` MCP tools. ## Impact Risk Levels @@ -128,6 +131,8 @@ Indexed as **GitNexus** (4325 symbols, 10556 relationships, 300 execution flows) | `gitnexus://repo/GitNexus/clusters` | All functional areas | | `gitnexus://repo/GitNexus/processes` | All execution flows | | `gitnexus://repo/GitNexus/process/{name}` | Step-by-step execution trace | +| `gitnexus://group/{name}/contracts` | Group Contract Registry (provider/consumer rows + cross-links) | +| `gitnexus://group/{name}/status` | Per-member index + Contract Registry staleness report | ## Self-Check Before Finishing diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d934cd8b6..ceb2f9583 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -42,10 +42,14 @@ Monorepo: **CLI/MCP** (`gitnexus/`) + **browser UI** (`gitnexus-web/`). | `tool_map` | MCP/RPC tool definitions and handlers | | `shape_check` | Response shape vs consumer property access mismatches | | `group_list` | List repo groups or details for one group | -| `group_query` | Cross-repo search in a group (reciprocal rank fusion) | -| `group_sync` | Rebuild group Contract Registry (`contracts.json`) | -| `group_contracts` | Inspect group contracts and cross-links | -| `group_status` | Index and Contract Registry staleness per repo in a group | +| `group_sync` | Rebuild group Contract Registry (`contracts.json`) and bridge graph | + +`query`, `context`, and `impact` are group-aware: pass `repo: "@"` (or `"@/"` to scope to one member) plus optional `service: ""`. Group-mode `query` merges per-repo results via Reciprocal Rank Fusion; group-mode `impact` runs the local walk in the chosen member and fans out across boundaries via the Contract Bridge (`gitnexus/src/core/group/cross-impact.ts`). The previously-planned `group_query`, `group_context`, `group_impact`, `group_contracts`, `group_status` MCP tools are intentionally not introduced — group-level state is exposed via resources instead: + +| Resource URI | Purpose | +|--------------|---------| +| `gitnexus://group/{name}/contracts` | Contract Registry (provider/consumer rows + cross-links) | +| `gitnexus://group/{name}/status` | Per-member index + Contract Registry staleness | ## Where to change what @@ -55,6 +59,7 @@ Monorepo: **CLI/MCP** (`gitnexus/`) + **browser UI** (`gitnexus-web/`). | Parsing/graph construction | `src/core/ingestion/pipeline-phases/` + `pipeline.ts` | | Graph schema/DB | `src/core/lbug/` (`schema.ts`, `lbug-adapter.ts`) | | MCP tools/resources | `src/mcp/server.ts`, `tools.ts`, `resources.ts` | +| Cross-repo groups (sync, contracts, `@` routing) | `src/core/group/` (`service.ts`, `cross-impact.ts`, `sync.ts`, `bridge-db.ts`) | | Search ranking | `src/core/search/` (BM25, hybrid fusion) | | Embeddings | `src/core/embeddings/` + `src/core/run-analyze.ts` | | Wiki generation | `src/core/wiki/` | diff --git a/gitnexus/CHANGELOG.md b/gitnexus/CHANGELOG.md index 203089d93..e4a5041ba 100644 --- a/gitnexus/CHANGELOG.md +++ b/gitnexus/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to GitNexus will be documented in this file. +## [Unreleased] + +### Performance + +- **`analyze` ~33% faster** — moved FTS index creation from the analyze pipeline to first-use lazy initialisation. The 5 `CREATE_FTS_INDEX` calls cost ~440 ms each in LadybugDB regardless of table size (≈2 s fixed overhead) and dominated runtime on small repos and slow CI runners. The cost now amortises across the first `query`/`context` call in a session via a new `ensureFTSIndex` helper. Mini-repo `analyze` measured locally on Windows: 6.4 s → 4.0 s warm; on CI Windows runners (≈3× slower) restores comfortable headroom against the 30 s e2e test budget. + ## [1.6.2] - 2026-04-18 ### Added diff --git a/gitnexus/src/cli/ai-context.ts b/gitnexus/src/cli/ai-context.ts index 984d1432a..984a16f7b 100644 --- a/gitnexus/src/cli/ai-context.ts +++ b/gitnexus/src/cli/ai-context.ts @@ -121,7 +121,7 @@ ${ groupNames && groupNames.length > 0 ? `## Cross-Repo Groups -This repository is listed under GitNexus **group(s): ${groupNames.join(', ')}** (see \`~/.gitnexus/groups/\`). For blast radius across repository boundaries, use MCP tools \`group_impact\`, \`group_sync\`, \`group_query\`, \`group_contracts\`, \`group_status\`, and \`group_list\`. From the terminal: \`npx gitnexus group list\`, \`npx gitnexus group sync \`, \`npx gitnexus group impact --target --repo \`. +This repository is listed under GitNexus **group(s): ${groupNames.join(', ')}** (see \`~/.gitnexus/groups/\`). For cross-repo analysis, use MCP tools \`impact\`, \`query\`, and \`context\` with \`repo\` set to \`@\` or \`@/\` (paths match keys in that group’s \`group.yaml\`). Use \`group_list\` / \`group_sync\` for membership and sync. From the terminal: \`npx gitnexus group list\`, \`npx gitnexus group sync \`, \`npx gitnexus group impact --target --repo \`. ` : '' diff --git a/gitnexus/src/cli/group.ts b/gitnexus/src/cli/group.ts index 70ca9537a..eb0dffc3d 100644 --- a/gitnexus/src/cli/group.ts +++ b/gitnexus/src/cli/group.ts @@ -184,6 +184,83 @@ export function registerGroupCommands(program: Command): void { } }); + group + .command('impact ') + .description('Cross-repo impact for a symbol in one member repo of a group') + .requiredOption('--target ', 'Symbol or file name to analyze') + .requiredOption( + '--repo ', + 'Member path from group.yaml (e.g. app/backend), not the indexed repo name', + ) + .option('--direction ', 'upstream or downstream', 'upstream') + .option('--service ', 'Optional monorepo service directory prefix (path filter)') + .option( + '--subgroup ', + 'Optional prefix limiting which group repos participate in cross fan-out', + ) + .option('--max-depth ', 'Max graph traversal depth') + .option('--cross-depth ', 'Cross-repository hop depth') + .option('--min-confidence ', 'Minimum relation confidence (0–1)') + .option('--include-tests', 'Include test files in traversal', false) + .option('--timeout-ms ', 'Phase-1 local impact wall time in milliseconds') + .option('--json', 'JSON output') + .action(async (name: string, opts: Record) => { + const { LocalBackend } = await import('../mcp/local/local-backend.js'); + + const backend = new LocalBackend(); + try { + await backend.init(); + + const payload: Record = { + name, + repo: opts.repo, + target: opts.target, + direction: (opts.direction as string) || 'upstream', + }; + if (opts.service) payload.service = opts.service; + if (opts.subgroup) payload.subgroup = opts.subgroup; + if (opts.maxDepth !== undefined && opts.maxDepth !== '') { + const n = parseInt(String(opts.maxDepth), 10); + if (!Number.isNaN(n)) payload.maxDepth = n; + } + if (opts.crossDepth !== undefined && opts.crossDepth !== '') { + const n = parseInt(String(opts.crossDepth), 10); + if (!Number.isNaN(n)) payload.crossDepth = n; + } + if (opts.minConfidence !== undefined && opts.minConfidence !== '') { + const n = parseFloat(String(opts.minConfidence)); + if (!Number.isNaN(n)) payload.minConfidence = n; + } + if (opts.timeoutMs !== undefined && opts.timeoutMs !== '') { + const n = parseInt(String(opts.timeoutMs), 10); + if (!Number.isNaN(n)) payload.timeoutMs = n; + } + if (opts.includeTests) payload.includeTests = true; + + const raw = await backend.getGroupService().groupImpact(payload); + if (raw && typeof raw === 'object' && 'error' in raw) { + console.error(String((raw as { error: string }).error)); + process.exitCode = 1; + return; + } + + if (opts.json) { + console.log(JSON.stringify(raw, null, 2)); + } else { + const summary = (raw as { summary?: Record })?.summary; + const risk = (raw as { risk?: string })?.risk; + console.log(`Group impact for "${name}" (${String(opts.repo)}): risk=${risk ?? '?'}`); + if (summary) { + console.log( + ` direct=${summary.direct ?? 0} processes=${summary.processes_affected ?? 0} cross=${summary.cross_repo_hits ?? 0}`, + ); + } + } + } finally { + await backend.dispose().catch(() => {}); + } + }); + group .command('query ') .description('Search execution flows across all repos in a group') diff --git a/gitnexus/src/core/group/cross-impact.ts b/gitnexus/src/core/group/cross-impact.ts new file mode 100644 index 000000000..8739584c7 --- /dev/null +++ b/gitnexus/src/core/group/cross-impact.ts @@ -0,0 +1,562 @@ +/** + * Cross-repo impact (Phase 1 local walk + Phase 2 bridge fan-out). + * All bridge Cypher for this feature lives in this module. + */ + +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import type { + BridgeHandle, + ContractType, + CrossRepoImpact, + GroupConfig, + GroupImpactResult, + MatchType, + OutOfScopeLink, +} from './types.js'; +import type { GroupRepoHandle, GroupToolPort } from './service.js'; +import { loadGroupConfig } from './config-parser.js'; +import { + fileMatchesServicePrefix, + normalizeServicePrefix, + repoInSubgroup, +} from './group-path-utils.js'; +import { getGroupDir } from './storage.js'; +import { closeBridgeDb, openBridgeDbReadOnly, queryBridge, readBridgeMeta } from './bridge-db.js'; +import { BRIDGE_SCHEMA_VERSION } from './bridge-schema.js'; + +/** Cross-boundary hops beyond this value are clamped (multi-hop reserved for future work). */ +export const MAX_SUPPORTED_CROSS_DEPTH = 1; + +/** Default wall-clock budget for the Phase 1 `impact` leg when callers omit `timeoutMs`. */ +export const DEFAULT_LOCAL_IMPACT_TIMEOUT_MS = 30_000; + +const CY_NEIGHBORS_UPSTREAM = ` +MATCH (consumer:Contract)-[l:ContractLink]->(provider:Contract) +WHERE provider.repo = $localRepo + AND provider.symbolUid IN $uids + AND provider.role = 'provider' +RETURN consumer.repo AS neighborRepo, + consumer.symbolUid AS neighborUid, + consumer.filePath AS neighborFilePath, + l.matchType AS matchType, + l.confidence AS confidence, + l.contractId AS contractId, + consumer.type AS contractType +`; + +const CY_NEIGHBORS_DOWNSTREAM = ` +MATCH (consumer:Contract)-[l:ContractLink]->(provider:Contract) +WHERE consumer.repo = $localRepo + AND consumer.symbolUid IN $uids + AND consumer.role = 'consumer' +RETURN provider.repo AS neighborRepo, + provider.symbolUid AS neighborUid, + provider.filePath AS neighborFilePath, + l.matchType AS matchType, + l.confidence AS confidence, + l.contractId AS contractId, + provider.type AS contractType +`; + +type BridgeNeighborRow = { + neighborRepo: string; + neighborUid: string; + neighborFilePath?: string; + matchType: string; + confidence: number; + contractId: string; + contractType: string; +}; + +export interface RunGroupImpactDeps { + port: GroupToolPort; + gitnexusDir: string; +} + +function parseDirection(raw: unknown): 'upstream' | 'downstream' | null { + if (raw === 'upstream' || raw === 'downstream') return raw; + return null; +} + +function clampCrossDepth(raw: unknown): { depth: number; warning?: string } { + const n = typeof raw === 'number' && Number.isFinite(raw) ? Math.floor(raw) : 1; + const d = n < 1 ? 1 : n; + if (d > MAX_SUPPORTED_CROSS_DEPTH) { + return { + depth: MAX_SUPPORTED_CROSS_DEPTH, + warning: `crossDepth was ${d}; multi-hop cross-boundary traversal beyond ${MAX_SUPPORTED_CROSS_DEPTH} is not implemented yet. Using crossDepth ${MAX_SUPPORTED_CROSS_DEPTH}.`, + }; + } + return { depth: d }; +} + +export function validateGroupImpactParams(params: Record): + | { + ok: true; + name: string; + repoPath: string; + target: string; + direction: 'upstream' | 'downstream'; + maxDepth: number; + crossDepth: number; + crossDepthWarning?: string; + relationTypes?: string[]; + includeTests: boolean; + minConfidence: number; + service?: string; + subgroup?: string; + timeoutMs: number; + } + | { ok: false; error: string } { + const name = String(params.name ?? '').trim(); + const repoPath = String(params.repo ?? '').trim(); + const target = String(params.target ?? '').trim(); + if (!name) return { ok: false, error: 'name is required' }; + if (!repoPath) + return { ok: false, error: 'repo is required (group repo path, e.g. app/backend)' }; + if (!target) return { ok: false, error: 'target is required' }; + if ( + params.service !== undefined && + params.service !== null && + String(params.service).trim() === '' + ) { + return { ok: false, error: 'service must not be an empty string' }; + } + const direction = parseDirection(params.direction); + if (!direction) return { ok: false, error: 'direction must be upstream or downstream' }; + + let maxDepth = typeof params.maxDepth === 'number' && params.maxDepth > 0 ? params.maxDepth : 3; + if (maxDepth > 32) maxDepth = 32; + + const { depth: crossDepth, warning: crossDepthWarning } = clampCrossDepth(params.crossDepth); + + const relationTypes = Array.isArray(params.relationTypes) + ? params.relationTypes.filter((t): t is string => typeof t === 'string') + : undefined; + + const includeTests = Boolean(params.includeTests); + let minConfidence = typeof params.minConfidence === 'number' ? params.minConfidence : 0; + if (minConfidence < 0) minConfidence = 0; + if (minConfidence > 1) minConfidence = 1; + + const service = normalizeServicePrefix(params.service); + const subgroup = typeof params.subgroup === 'string' ? params.subgroup : undefined; + + let timeoutMs = + typeof params.timeoutMs === 'number' && params.timeoutMs > 0 + ? params.timeoutMs + : typeof params.timeout === 'number' && params.timeout > 0 + ? params.timeout + : DEFAULT_LOCAL_IMPACT_TIMEOUT_MS; + if (timeoutMs > 3_600_000) timeoutMs = 3_600_000; + + return { + ok: true, + name, + repoPath, + target, + direction, + maxDepth, + crossDepth, + crossDepthWarning, + relationTypes, + includeTests, + minConfidence, + service, + subgroup, + timeoutMs, + }; +} + +async function resolveGroupRepo( + port: GroupToolPort, + config: GroupConfig, + repoPath: string, +): Promise { + const registryName = config.repos[repoPath]; + if (!registryName) { + return { error: `Unknown repo path "${repoPath}" in this group.` }; + } + try { + return await port.resolveRepo(registryName); + } catch (e) { + return { error: e instanceof Error ? e.message : String(e) }; + } +} + +async function safeLocalImpact( + port: GroupToolPort, + repo: GroupRepoHandle, + impactParams: Parameters[1], + timeoutMs: number, +): Promise<{ value: unknown; timedOut: boolean }> { + let timer: ReturnType | undefined; + const impactP = port.impact(repo, impactParams).catch((err) => ({ + error: err instanceof Error ? err.message : String(err), + })); + const timeoutP = new Promise<'timeout'>((resolve) => { + timer = setTimeout(() => resolve('timeout'), timeoutMs); + }); + const won = await Promise.race([ + impactP.then((v) => ({ tag: 'impact' as const, v })), + timeoutP.then(() => ({ tag: 'timeout' as const })), + ]); + if (timer !== undefined) clearTimeout(timer); + if (won.tag === 'timeout') { + return { + value: { error: 'Local impact timed out', partial: true }, + timedOut: true, + }; + } + return { value: won.v, timedOut: false }; +} + +export function collectImpactSymbolUids( + local: unknown, + servicePrefix: string | undefined, +): { uids: string[]; targetFilePath?: string } { + const uids = new Set(); + let targetFilePath: string | undefined; + const obj = local as Record | null; + if (!obj || typeof obj !== 'object') return { uids: [], targetFilePath }; + + const target = obj.target as { id?: string; filePath?: string } | undefined; + if (target?.id) { + targetFilePath = typeof target.filePath === 'string' ? target.filePath : undefined; + if (fileMatchesServicePrefix(targetFilePath, servicePrefix)) { + uids.add(String(target.id)); + } + } + + const byDepth = obj.byDepth as Record | undefined; + if (byDepth && typeof byDepth === 'object') { + for (const items of Object.values(byDepth)) { + if (!Array.isArray(items)) continue; + for (const it of items) { + const row = it as { id?: string; filePath?: string }; + if (row?.id && fileMatchesServicePrefix(row.filePath, servicePrefix)) { + uids.add(String(row.id)); + } + } + } + } + return { uids: [...uids], targetFilePath }; +} + +function extractProcessNames(impact: unknown): string[] { + const o = impact as { affected_processes?: Array<{ name?: string }> }; + if (!o?.affected_processes) return []; + return o.affected_processes.map((p) => String(p.name ?? '')).filter(Boolean); +} + +function mergeRisk(localRisk: string, cross: CrossRepoImpact[]): string { + const highConf = cross.some((c) => c.contract.confidence >= 0.85); + if (localRisk === 'CRITICAL') return 'CRITICAL'; + if (cross.length >= 3) return 'CRITICAL'; + if (highConf) return 'HIGH'; + if (cross.length > 0 && (localRisk === 'LOW' || localRisk === 'UNKNOWN')) return 'MEDIUM'; + return localRisk; +} + +async function ensureBridgeReady( + groupDir: string, +): Promise<{ handle: BridgeHandle } | { error: string }> { + const meta = await readBridgeMeta(groupDir); + if (meta.version > 0 && meta.version !== BRIDGE_SCHEMA_VERSION) { + return { + error: `Bridge schema version mismatch (meta.json has ${meta.version}, expected ${BRIDGE_SCHEMA_VERSION}). Run gitnexus group sync for this group.`, + }; + } + const dbPath = path.join(groupDir, 'bridge.lbug'); + try { + await fsp.access(dbPath); + } catch { + return { + error: `No bridge.lbug in this group directory. Run gitnexus group sync (schema ${BRIDGE_SCHEMA_VERSION}).`, + }; + } + const handle = await openBridgeDbReadOnly(groupDir); + if (!handle) { + return { + error: `Could not open bridge.lbug read-only (schema ${BRIDGE_SCHEMA_VERSION}). Run gitnexus group sync.`, + }; + } + return { handle }; +} + +function rowToNeighbor(r: Record): BridgeNeighborRow | null { + const neighborRepo = String(r.neighborRepo ?? r[0] ?? ''); + const neighborUid = String(r.neighborUid ?? r[1] ?? ''); + if (!neighborRepo || !neighborUid) return null; + return { + neighborRepo, + neighborUid, + neighborFilePath: + r.neighborFilePath !== undefined ? String(r.neighborFilePath) : String(r[2] ?? ''), + matchType: String(r.matchType ?? r[3] ?? 'exact'), + confidence: Number(r.confidence ?? r[4] ?? 0), + contractId: String(r.contractId ?? r[5] ?? ''), + contractType: String(r.contractType ?? r[6] ?? 'custom'), + }; +} + +export async function runGroupImpact( + deps: RunGroupImpactDeps, + params: Record, +): Promise { + const parsed = validateGroupImpactParams(params); + if (parsed.ok === false) return { error: parsed.error }; + + const { + name, + repoPath, + target, + direction, + maxDepth, + crossDepth: _crossDepth, + crossDepthWarning, + relationTypes, + includeTests, + minConfidence, + service: servicePrefix, + subgroup, + timeoutMs, + } = parsed; + + const groupDir = getGroupDir(deps.gitnexusDir, name); + let config: GroupConfig; + try { + config = await loadGroupConfig(groupDir); + } catch (e) { + return { error: e instanceof Error ? e.message : String(e) }; + } + + const resolved = await resolveGroupRepo(deps.port, config, repoPath); + if ('error' in resolved) return { error: resolved.error }; + + const impactParams: Parameters[1] = { + target, + direction, + maxDepth, + relationTypes: relationTypes && relationTypes.length > 0 ? relationTypes : undefined, + includeTests, + minConfidence, + }; + + // Single shared deadline for Phase 1 (local walk) + Phase 2 (bridge fan-out). + // Phase 1 still gets the full budget; Phase 2 only uses whatever wall-clock + // time is left, so total work cannot exceed `timeoutMs`. + const deadline = Date.now() + Math.max(0, timeoutMs); + + const { value: local, timedOut: localTimedOut } = await safeLocalImpact( + deps.port, + resolved, + impactParams, + timeoutMs, + ); + + if (localTimedOut) { + const base = local as Record; + return { + local, + group: name, + cross: [], + outOfScope: [], + truncated: true, + truncatedRepos: [], + summary: { + direct: 0, + processes_affected: 0, + modules_affected: 0, + cross_repo_hits: 0, + }, + risk: 'UNKNOWN', + timeoutMs, + truncationReason: 'timeout', + crossDepthWarning, + }; + } + + const localObj = local as Record | null; + if (localObj?.error && typeof localObj.error === 'string') { + const empty: GroupImpactResult = { + local, + group: name, + cross: [], + outOfScope: [], + truncated: false, + truncatedRepos: [], + summary: { + direct: 0, + processes_affected: 0, + modules_affected: 0, + cross_repo_hits: 0, + }, + risk: 'UNKNOWN', + timeoutMs, + crossDepthWarning, + }; + return empty; + } + + if (servicePrefix) { + const tf = (localObj?.target as { filePath?: string } | undefined)?.filePath; + if (!fileMatchesServicePrefix(tf, servicePrefix)) { + return { + local: {}, + group: name, + cross: [], + outOfScope: [], + truncated: false, + truncatedRepos: [], + summary: { + direct: 0, + processes_affected: 0, + modules_affected: 0, + cross_repo_hits: 0, + }, + risk: 'LOW', + timeoutMs, + crossDepthWarning, + }; + } + } + + const { uids } = collectImpactSymbolUids(local, servicePrefix); + if (uids.length === 0) { + const s = (local as { summary?: Record })?.summary || {}; + return { + local, + group: name, + cross: [], + outOfScope: [], + truncated: Boolean((local as { partial?: boolean }).partial), + truncatedRepos: [], + summary: { + direct: s.direct ?? 0, + processes_affected: s.processes_affected ?? 0, + modules_affected: s.modules_affected ?? 0, + cross_repo_hits: 0, + }, + risk: String((local as { risk?: string }).risk ?? 'LOW'), + timeoutMs, + truncationReason: (local as { partial?: boolean }).partial ? 'partial' : undefined, + crossDepthWarning, + }; + } + + const bridgePrep = await ensureBridgeReady(groupDir); + if ('error' in bridgePrep) return { error: bridgePrep.error }; + + const handle = bridgePrep.handle; + const cross: CrossRepoImpact[] = []; + const outOfScope: OutOfScopeLink[] = []; + const truncatedRepos: string[] = []; + + try { + const cypher = direction === 'upstream' ? CY_NEIGHBORS_UPSTREAM : CY_NEIGHBORS_DOWNSTREAM; + const rows = await queryBridge>(handle, cypher, { + localRepo: repoPath, + uids, + }); + + const neighbors: BridgeNeighborRow[] = []; + for (const raw of rows) { + const n = rowToNeighbor(raw); + if (n) neighbors.push(n); + } + neighbors.sort((a, b) => b.confidence - a.confidence); + + const seen = new Set(); + + for (const n of neighbors) { + if (servicePrefix && !fileMatchesServicePrefix(n.neighborFilePath, servicePrefix)) { + continue; + } + if (!repoInSubgroup(n.neighborRepo, subgroup)) { + // CrossLink convention: consumer -> provider + outOfScope.push({ + from: direction === 'upstream' ? n.neighborRepo : repoPath, + to: direction === 'upstream' ? repoPath : n.neighborRepo, + contractId: n.contractId, + confidence: n.confidence, + }); + continue; + } + + const key = `${n.neighborRepo}\0${n.neighborUid}\0${n.contractId}`; + if (seen.has(key)) continue; + seen.add(key); + + if (Date.now() > deadline) { + truncatedRepos.push(n.neighborRepo); + continue; + } + + const regName = config.repos[n.neighborRepo]; + if (!regName) continue; + + let neighborHandle: GroupRepoHandle; + try { + neighborHandle = await deps.port.resolveRepo(regName); + } catch { + truncatedRepos.push(n.neighborRepo); + continue; + } + + const fan = await deps.port.impactByUid(neighborHandle.id, n.neighborUid, direction, { + maxDepth, + relationTypes: relationTypes ?? [], + minConfidence, + includeTests, + }); + if (fan == null) { + truncatedRepos.push(n.neighborRepo); + continue; + } + + cross.push({ + repo: regName, + repo_path: n.neighborRepo, + contract: { + id: n.contractId, + type: n.contractType as ContractType, + match_type: (n.matchType as MatchType) || 'exact', + confidence: n.confidence, + }, + by_depth: ((fan as { byDepth?: unknown }).byDepth ?? {}) as Record, + affected_processes: extractProcessNames(fan), + }); + } + } finally { + await closeBridgeDb(handle); + } + + const localSum = (local as { summary?: Record })?.summary || {}; + const localRisk = String((local as { risk?: string }).risk ?? 'LOW'); + const localPartial = Boolean((local as { partial?: boolean }).partial); + const truncated = truncatedRepos.length > 0 || localPartial; + + const result: GroupImpactResult = { + local, + group: name, + cross, + outOfScope, + truncated, + truncatedRepos: [...new Set(truncatedRepos)], + summary: { + direct: localSum.direct ?? 0, + processes_affected: localSum.processes_affected ?? 0, + modules_affected: localSum.modules_affected ?? 0, + cross_repo_hits: cross.length, + }, + risk: mergeRisk(localRisk, cross), + timeoutMs, + truncationReason: truncated ? 'partial' : undefined, + crossDepthWarning, + }; + return result; +} + +export { normalizeServicePrefix, fileMatchesServicePrefix } from './group-path-utils.js'; diff --git a/gitnexus/src/core/group/group-path-utils.ts b/gitnexus/src/core/group/group-path-utils.ts new file mode 100644 index 000000000..ab6a1effb --- /dev/null +++ b/gitnexus/src/core/group/group-path-utils.ts @@ -0,0 +1,42 @@ +/** + * Shared service-path normalization for group tools (`service` monorepo filter) + * and subgroup membership checks. + * + * Inputs may originate from tree-sitter, the OS file API, or user-supplied + * MCP arguments, so both `\` and `/` separators are accepted. Internally we + * normalize to POSIX-style `/` for case-sensitive segment comparisons. + */ + +function toPosix(p: string): string { + return p.replace(/\\/g, '/'); +} + +export function normalizeServicePrefix(service: unknown): string | undefined { + if (service === undefined || service === null) return undefined; + const s = toPosix(String(service)).trim().replace(/\/+$/, ''); + return s.length > 0 ? s : undefined; +} + +export function fileMatchesServicePrefix( + filePath: string | undefined, + prefix: string | undefined, +): boolean { + if (!prefix) return true; + if (!filePath) return false; + const normalized = toPosix(filePath); + return normalized === prefix || normalized.startsWith(`${prefix}/`); +} + +/** + * True if `repoPath` is at or beneath `subgroup` (member-path prefix in + * `group.yaml`). Empty / missing `subgroup` matches every repo. + * + * @param exact When set, requires an exact equality match (no descendant repos). + */ +export function repoInSubgroup(repoPath: string, subgroup?: string, exact?: boolean): boolean { + if (!subgroup?.trim()) return true; + const s = toPosix(subgroup).replace(/\/+$/, ''); + const r = toPosix(repoPath); + if (exact) return r === s; + return r === s || r.startsWith(`${s}/`); +} diff --git a/gitnexus/src/core/group/resolve-at-member.ts b/gitnexus/src/core/group/resolve-at-member.ts new file mode 100644 index 000000000..e36506c38 --- /dev/null +++ b/gitnexus/src/core/group/resolve-at-member.ts @@ -0,0 +1,34 @@ +/** + * Map MCP/CLI `@groupName` or `@groupName/memberPath` to a concrete member path in group.yaml. + */ + +import { loadGroupConfig } from './config-parser.js'; +import { getDefaultGitnexusDir, getGroupDir } from './storage.js'; + +export async function resolveAtGroupMemberRepoPath( + groupName: string, + explicitMemberPath: string | undefined, +): Promise<{ ok: true; repoPath: string } | { ok: false; error: string }> { + const trimmed = groupName.trim(); + if (!trimmed) return { ok: false, error: 'Group name is empty.' }; + try { + const groupDir = getGroupDir(getDefaultGitnexusDir(), trimmed); + const config = await loadGroupConfig(groupDir); + const keys = Object.keys(config.repos).sort((a, b) => a.localeCompare(b)); + if (keys.length === 0) { + return { ok: false, error: `Group "${trimmed}" has no repos in group.yaml.` }; + } + if (explicitMemberPath !== undefined && explicitMemberPath !== '') { + if (!(explicitMemberPath in config.repos)) { + return { + ok: false, + error: `Unknown member path "${explicitMemberPath}" in group "${trimmed}". Known paths: ${keys.join(', ')}`, + }; + } + return { ok: true, repoPath: explicitMemberPath }; + } + return { ok: true, repoPath: keys[0]! }; + } catch (e) { + return { ok: false, error: e instanceof Error ? e.message : String(e) }; + } +} diff --git a/gitnexus/src/core/group/service.ts b/gitnexus/src/core/group/service.ts index 1530cd6dd..afbb66e0e 100644 --- a/gitnexus/src/core/group/service.ts +++ b/gitnexus/src/core/group/service.ts @@ -3,10 +3,24 @@ * DB access is injected via GroupToolPort so this module stays free of LocalBackend private API. */ +import fsp from 'node:fs/promises'; +import path from 'node:path'; import { checkStaleness } from '../git-staleness.js'; import { loadGroupConfig } from './config-parser.js'; +import { + fileMatchesServicePrefix, + normalizeServicePrefix, + repoInSubgroup, +} from './group-path-utils.js'; import { getDefaultGitnexusDir, getGroupDir, listGroups, readContractRegistry } from './storage.js'; import { syncGroup } from './sync.js'; +import type { + ContractRegistry, + CrossLink, + GroupConfig, + GroupContextResult, + StoredContract, +} from './types.js'; export interface GroupRepoHandle { id: string; @@ -52,12 +66,149 @@ export interface GroupToolPort { includeTests: boolean; }, ): Promise; + context( + repo: GroupRepoHandle, + params: { + name?: string; + uid?: string; + file_path?: string; + include_content?: boolean; + }, + ): Promise; } -function repoInSubgroup(repoPath: string, subgroup?: string): boolean { - if (!subgroup?.trim()) return true; - const s = subgroup.replace(/\/+$/, ''); - return repoPath === s || repoPath.startsWith(`${s}/`); +function isStoredContract(raw: unknown): raw is StoredContract { + if (!raw || typeof raw !== 'object') return false; + const o = raw as Record; + return ( + typeof o.contractId === 'string' && + typeof o.type === 'string' && + typeof o.repo === 'string' && + typeof o.role === 'string' && + (o.role === 'provider' || o.role === 'consumer') && + typeof o.symbolUid === 'string' && + typeof o.symbolName === 'string' && + typeof o.confidence === 'number' && + o.meta !== undefined && + typeof o.meta === 'object' && + o.meta !== null && + o.symbolRef !== undefined && + typeof o.symbolRef === 'object' && + o.symbolRef !== null && + typeof (o.symbolRef as Record).filePath === 'string' && + typeof (o.symbolRef as Record).name === 'string' + ); +} + +function filterQueryByServicePrefix( + queryResult: { + processes?: Array>; + process_symbols?: Array>; + }, + servicePrefix: string, +): { processes: Array>; process_symbols: Array> } { + const symbols = (queryResult.process_symbols || []).filter((s) => + fileMatchesServicePrefix( + typeof s.filePath === 'string' ? s.filePath : undefined, + servicePrefix, + ), + ); + const allowed = new Set( + symbols.map((s) => String((s as { process_id?: string }).process_id ?? '')).filter(Boolean), + ); + const processes = (queryResult.processes || []).filter((p) => allowed.has(String(p.id))); + return { processes, process_symbols: symbols }; +} + +function isCrossLink(raw: unknown): raw is CrossLink { + if (!raw || typeof raw !== 'object') return false; + const o = raw as Record; + const from = o.from as Record | undefined; + const to = o.to as Record | undefined; + if (!from || !to) return false; + if (typeof from.repo !== 'string' || typeof to.repo !== 'string') return false; + return typeof o.contractId === 'string' && typeof o.type === 'string'; +} + +async function loadContractRegistryResilient( + groupDir: string, +): Promise< + { ok: true; registry: ContractRegistry; skippedCorrupt: number } | { ok: false; error: string } +> { + const filePath = path.join(groupDir, 'contracts.json'); + let raw: string; + try { + raw = await fsp.readFile(filePath, 'utf-8'); + } catch (e) { + if ((e as NodeJS.ErrnoException).code === 'ENOENT') { + return { ok: false, error: `No contracts.json for this group. Run group_sync first.` }; + } + return { ok: false, error: e instanceof Error ? e.message : String(e) }; + } + + let root: unknown; + try { + root = JSON.parse(raw); + } catch { + return { ok: false, error: 'contracts.json is not valid JSON' }; + } + + if (!root || typeof root !== 'object' || Array.isArray(root)) { + return { ok: false, error: 'contracts.json has an invalid root object' }; + } + + const base = root as Record; + const contractsRaw = base.contracts; + const crossRaw = base.crossLinks; + let skippedCorrupt = 0; + + const contracts: StoredContract[] = []; + if (Array.isArray(contractsRaw)) { + for (const row of contractsRaw) { + try { + if (isStoredContract(row)) { + contracts.push(row); + } else { + skippedCorrupt++; + console.warn('[group] skipping corrupt contract row in contracts.json'); + } + } catch { + skippedCorrupt++; + console.warn('[group] skipping corrupt contract row in contracts.json'); + } + } + } + + const crossLinks: CrossLink[] = []; + if (Array.isArray(crossRaw)) { + for (const row of crossRaw) { + try { + if (isCrossLink(row)) { + crossLinks.push(row); + } else { + skippedCorrupt++; + console.warn('[group] skipping corrupt crossLinks row in contracts.json'); + } + } catch { + skippedCorrupt++; + console.warn('[group] skipping corrupt crossLinks row in contracts.json'); + } + } + } + + const registry: ContractRegistry = { + version: typeof base.version === 'number' ? base.version : 0, + generatedAt: typeof base.generatedAt === 'string' ? base.generatedAt : '', + repoSnapshots: + base.repoSnapshots && typeof base.repoSnapshots === 'object' && base.repoSnapshots !== null + ? (base.repoSnapshots as Record) + : {}, + missingRepos: Array.isArray(base.missingRepos) ? (base.missingRepos as string[]) : [], + contracts, + crossLinks, + }; + + return { ok: true, registry, skippedCorrupt }; } export class GroupService { @@ -103,10 +254,14 @@ export class GroupService { const name = String(params.name ?? '').trim(); if (!name) return { error: 'name is required' }; const groupDir = getGroupDir(getDefaultGitnexusDir(), name); - const registry = await readContractRegistry(groupDir); - if (!registry) { - return { error: `No contracts.json for group "${name}". Run group_sync first.` }; + const loaded = await loadContractRegistryResilient(groupDir); + if (loaded.ok === false) { + if (loaded.error.includes('No contracts.json')) { + return { error: `No contracts.json for group "${name}". Run group_sync first.` }; + } + return { error: loaded.error }; } + const { registry, skippedCorrupt } = loaded; let contracts = registry.contracts; if (params.type) contracts = contracts.filter((c) => c.type === params.type); if (params.repo) contracts = contracts.filter((c) => c.repo === params.repo); @@ -119,41 +274,151 @@ export class GroupService { ); contracts = contracts.filter((c) => !matchedIds.has(`${c.repo}::${c.contractId}`)); } - return { contracts, crossLinks: registry.crossLinks }; + const out: Record = { contracts, crossLinks: registry.crossLinks }; + if (skippedCorrupt > 0) out.skippedCorrupt = skippedCorrupt; + return out; + } + + async groupImpact(params: Record): Promise { + const { runGroupImpact } = await import('./cross-impact.js'); + return runGroupImpact({ port: this.port, gitnexusDir: getDefaultGitnexusDir() }, params); + } + + async groupContext(params: Record): Promise { + const name = String(params.name ?? '').trim(); + const target = typeof params.target === 'string' ? params.target.trim() : ''; + const uid = typeof params.uid === 'string' ? params.uid.trim() : undefined; + const file_path = typeof params.file_path === 'string' ? params.file_path : undefined; + const include_content = Boolean(params.include_content); + if ( + params.service !== undefined && + params.service !== null && + String(params.service).trim() === '' + ) { + return { group: name || '', error: 'service must not be an empty string', results: [] }; + } + const servicePrefix = normalizeServicePrefix(params.service); + const subgroup = typeof params.subgroup === 'string' ? params.subgroup : undefined; + const subgroupExact = params.subgroupExact === true; + + if (!name) { + return { group: '', error: 'name is required', results: [] }; + } + if (!uid && !target) { + return { group: name, error: 'target or uid is required', results: [] }; + } + + const groupDir = getGroupDir(getDefaultGitnexusDir(), name); + let config: GroupConfig; + try { + config = await loadGroupConfig(groupDir); + } catch (e) { + return { + group: name, + target: target || uid, + service: servicePrefix, + error: e instanceof Error ? e.message : String(e), + results: [], + }; + } + + const memberEntries = Object.entries(config.repos).filter(([repoPath]) => + repoInSubgroup(repoPath, subgroup, subgroupExact), + ); + + // Per-repo work is independent (each repo opens its own DB handle and the + // group-level result preserves repo iteration order via the indexed map). + // Errors are caught per repo so one slow/failed member does not block the rest. + const results: GroupContextResult['results'] = await Promise.all( + memberEntries.map(async ([repoPath, registryName]) => { + try { + const repoObj = await this.port.resolveRepo(registryName); + const payload = await this.port.context(repoObj, { + name: target || undefined, + uid, + file_path, + include_content, + }); + + if (servicePrefix) { + const st = (payload as { status?: string })?.status; + const sym = (payload as { symbol?: { filePath?: string } })?.symbol; + if (st === 'found' && !fileMatchesServicePrefix(sym?.filePath, servicePrefix)) { + return { repoPath, registryName, payload: {} }; + } + } + + return { repoPath, registryName, payload }; + } catch (e) { + return { + repoPath, + registryName, + payload: { error: e instanceof Error ? e.message : String(e) }, + }; + } + }), + ); + + return { + group: name, + target: target || uid, + service: servicePrefix, + results, + }; } async groupQuery(params: Record): Promise { const name = String(params.name ?? '').trim(); const queryText = String(params.query ?? '').trim(); if (!name || !queryText) return { error: 'name and query are required' }; + if ( + params.service !== undefined && + params.service !== null && + String(params.service).trim() === '' + ) { + return { error: 'service must not be an empty string' }; + } + const servicePrefix = normalizeServicePrefix(params.service); const limit = typeof params.limit === 'number' && params.limit > 0 ? params.limit : 5; const subgroup = typeof params.subgroup === 'string' ? params.subgroup : undefined; + const subgroupExact = params.subgroupExact === true; const groupDir = getGroupDir(getDefaultGitnexusDir(), name); const config = await loadGroupConfig(groupDir); - const perRepo: Array<{ repo: string; score: number; processes: unknown[] }> = []; - for (const [repoPath, registryName] of Object.entries(config.repos)) { - if (!repoInSubgroup(repoPath, subgroup)) continue; - try { - const repoObj = await this.port.resolveRepo(registryName); - const queryResult = (await this.port.query(repoObj, { - query: queryText, - limit, - max_symbols: 10, - include_content: false, - })) as { processes?: Array> }; - const processes = queryResult.processes || []; - const scored = processes.map((p, idx) => ({ - ...p, - _rrf_score: 1 / (idx + 1 + 60), - _repo: repoPath, - })); - perRepo.push({ repo: repoPath, score: 0, processes: scored }); - } catch { - perRepo.push({ repo: repoPath, score: 0, processes: [] }); - } - } + const memberEntries = Object.entries(config.repos).filter(([repoPath]) => + repoInSubgroup(repoPath, subgroup, subgroupExact), + ); + + // Per-repo query is independent; run them concurrently and isolate + // failures so one slow/failed member does not block the rest. + const perRepo = await Promise.all( + memberEntries.map(async ([repoPath, registryName]) => { + try { + const repoObj = await this.port.resolveRepo(registryName); + const queryResult = (await this.port.query(repoObj, { + query: queryText, + limit, + max_symbols: 10, + include_content: false, + })) as { + processes?: Array>; + process_symbols?: Array>; + }; + const processes = servicePrefix + ? filterQueryByServicePrefix(queryResult, servicePrefix).processes + : queryResult.processes || []; + const scored = processes.map((p, idx) => ({ + ...p, + _rrf_score: 1 / (idx + 1 + 60), + _repo: repoPath, + })); + return { repo: repoPath, score: 0, processes: scored as unknown[] }; + } catch { + return { repo: repoPath, score: 0, processes: [] as unknown[] }; + } + }), + ); const allProcesses = perRepo.flatMap((r) => r.processes as Array>); allProcesses.sort((a, b) => (b._rrf_score as number) - (a._rrf_score as number)); @@ -184,13 +449,10 @@ export class GroupService { } > = {}; - const fsp = await import('node:fs/promises'); - const pathMod = await import('node:path'); - for (const [repoPath, registryName] of Object.entries(config.repos)) { try { const repoObj = await this.port.resolveRepo(registryName); - const metaPath = pathMod.join(repoObj.storagePath, 'meta.json'); + const metaPath = path.join(repoObj.storagePath, 'meta.json'); const metaRaw = await fsp.readFile(metaPath, 'utf-8').catch(() => '{}'); const meta = JSON.parse(metaRaw) as { lastCommit?: string; indexedAt?: string }; diff --git a/gitnexus/src/core/group/types.ts b/gitnexus/src/core/group/types.ts index b9ba97582..793d3d0ad 100644 --- a/gitnexus/src/core/group/types.ts +++ b/gitnexus/src/core/group/types.ts @@ -96,6 +96,9 @@ export interface RepoHandle { storagePath: string; } +/** Why local impact or fan-out stopped early (e.g. wall-clock budget exhausted). */ +export type GroupImpactTruncationReason = 'timeout' | 'partial'; + export interface GroupImpactResult { local: unknown; group: string; @@ -110,6 +113,36 @@ export interface GroupImpactResult { cross_repo_hits: number; }; risk: string; + /** + * Milliseconds budget applied to the **Phase 1 local impact** leg (`safeLocalImpact`). + * If the walk hits this wall first, expect `truncationReason: 'timeout'` and a partial `local` payload. + */ + timeoutMs?: number; + /** Present when local impact or fan-out stopped early (timeout, graph cap, etc.). */ + truncationReason?: GroupImpactTruncationReason; + /** + * Human-readable note when `crossDepth` was clamped (e.g. multi-hop not implemented yet). + */ + crossDepthWarning?: string; +} + +/** One repo’s `context` tool payload in a group-scoped context run. */ +export interface GroupContextRepoEntry { + repoPath: string; + registryName: string; + payload: unknown; +} + +/** + * Aggregated group `context`: explicit per-repo rows (no merged symbol payloads). + * Use top-level `error` only for unrecoverable failures, not for “no matches” or service scope misses. + */ +export interface GroupContextResult { + group: string; + target?: string; + service?: string; + error?: string; + results: GroupContextRepoEntry[]; } export interface CrossRepoImpact { diff --git a/gitnexus/src/core/lbug/lbug-adapter.ts b/gitnexus/src/core/lbug/lbug-adapter.ts index f019960c5..e4190c323 100644 --- a/gitnexus/src/core/lbug/lbug-adapter.ts +++ b/gitnexus/src/core/lbug/lbug-adapter.ts @@ -144,6 +144,18 @@ let currentDbPath: string | null = null; let ftsLoaded = false; let vectorExtensionLoaded = false; +/** + * In-process cache of FTS indexes that have been ensured against the current + * connection. Prevents repeated `CALL CREATE_FTS_INDEX` round-trips inside a + * single CLI/MCP session — the first call to `ensureFTSIndex` for a given + * `(tableName, indexName)` pays the LadybugDB cost (~440 ms even when the + * index already exists on disk), subsequent calls are a Set lookup. Cleared + * by `closeLbug` so a re-init starts fresh. + * + * Key format: `${tableName}:${indexName}`. + */ +const ensuredFTSIndexes = new Set(); + /** * Check if an error indicates a missing column or table (schema-level problem) * rather than a transient/connection error. Used for legacy DB fallback logic. @@ -1037,6 +1049,7 @@ export const closeLbug = async (): Promise => { currentDbPath = null; ftsLoaded = false; vectorExtensionLoaded = false; + ensuredFTSIndexes.clear(); }; export const isLbugReady = (): boolean => conn !== null && db !== null; @@ -1219,6 +1232,29 @@ export const createFTSIndex = async ( } }; +/** + * Lazy-create an FTS index, caching the fact in-process. + * + * Used by `queryFTS` so that `analyze` doesn't pay the ~440 ms × 5 fixed + * LadybugDB cost up-front (it dominates analyze on small repos). Instead, + * the cost is moved to the first `query`/`context` call in a session, + * where it's amortised across many lookups. + * + * Safe to call repeatedly — the in-process Set guarantees only the first + * call hits LadybugDB. `closeLbug` clears the cache so re-init starts fresh. + */ +export const ensureFTSIndex = async ( + tableName: string, + indexName: string, + properties: string[], + stemmer: string = 'porter', +): Promise => { + const key = `${tableName}:${indexName}`; + if (ensuredFTSIndexes.has(key)) return; + await createFTSIndex(tableName, indexName, properties, stemmer); + ensuredFTSIndexes.add(key); +}; + /** * Query a full-text search index * @param tableName - The node table name diff --git a/gitnexus/src/core/run-analyze.ts b/gitnexus/src/core/run-analyze.ts index 5c2191003..e61c20f21 100644 --- a/gitnexus/src/core/run-analyze.ts +++ b/gitnexus/src/core/run-analyze.ts @@ -19,7 +19,6 @@ import { executeQuery, executeWithReusedStatement, closeLbug, - createFTSIndex, loadCachedEmbeddings, } from './lbug/lbug-adapter.js'; import { @@ -215,17 +214,12 @@ export async function runFullAnalysis( }); // ── Phase 3: FTS (85–90%) ───────────────────────────────────────── - progress('fts', 85, 'Creating search indexes...'); - - try { - await createFTSIndex('File', 'file_fts', ['name', 'content']); - await createFTSIndex('Function', 'function_fts', ['name', 'content']); - await createFTSIndex('Class', 'class_fts', ['name', 'content']); - await createFTSIndex('Method', 'method_fts', ['name', 'content']); - await createFTSIndex('Interface', 'interface_fts', ['name', 'content']); - } catch { - // Non-fatal — FTS is best-effort - } + // FTS indexes are created lazily on first `query`/`context` call instead + // of eagerly here. On small repos / CI runners the LadybugDB + // CREATE_FTS_INDEX cost is ~440 ms × 5 (≈2 s) regardless of table size, + // which dominated `analyze` runtime and pushed Windows CI past its + // 30 s test budget. Lazy creation is implemented in + // `core/search/bm25-index.ts` via `ensureFTSIndex`. // ── Phase 3.5: Re-insert cached embeddings ──────────────────────── if (cachedEmbeddings.length > 0) { diff --git a/gitnexus/src/core/search/bm25-index.ts b/gitnexus/src/core/search/bm25-index.ts index ae433ad28..040440999 100644 --- a/gitnexus/src/core/search/bm25-index.ts +++ b/gitnexus/src/core/search/bm25-index.ts @@ -3,9 +3,15 @@ * * Uses LadybugDB's built-in full-text search indexes for keyword-based search. * Always reads from the database (no cached state to drift). + * + * FTS indexes are created lazily on first query (via `ensureFTSIndex`) — see + * `lbug-adapter.ts` for the rationale. This keeps `analyze` fast (the + * ~440 ms × 5 LadybugDB CREATE_FTS_INDEX cost dominates pipeline time on + * small repos / CI runners) at the cost of paying that overhead on the + * first `query`/`context` call in a session. */ -import { queryFTS } from '../lbug/lbug-adapter.js'; +import { queryFTS, ensureFTSIndex } from '../lbug/lbug-adapter.js'; export interface BM25SearchResult { filePath: string; @@ -13,6 +19,56 @@ export interface BM25SearchResult { rank: number; } +/** + * FTS schema served by `searchFTSFromLbug`. Centralised so that both the + * CLI/pipeline path and the MCP pool path use identical (table, index, + * properties) tuples and the lazy-create logic stays in one place. + */ +const FTS_INDEXES: ReadonlyArray<{ + table: string; + indexName: string; + properties: readonly string[]; +}> = [ + { table: 'File', indexName: 'file_fts', properties: ['name', 'content'] }, + { table: 'Function', indexName: 'function_fts', properties: ['name', 'content'] }, + { table: 'Class', indexName: 'class_fts', properties: ['name', 'content'] }, + { table: 'Method', indexName: 'method_fts', properties: ['name', 'content'] }, + { table: 'Interface', indexName: 'interface_fts', properties: ['name', 'content'] }, +]; + +/** + * Per-process cache for the MCP pool path: tracks which `(repoId, table)` + * pairs have been ensured. The CLI/pipeline path gets its own cache inside + * `lbug-adapter.ts` keyed by table/index, scoped to the singleton connection. + */ +const ensuredPoolFTS = new Set(); + +async function ensureFTSIndexViaExecutor( + executor: (cypher: string) => Promise, + repoId: string, + table: string, + indexName: string, + properties: readonly string[], +): Promise { + const key = `${repoId}:${table}:${indexName}`; + if (ensuredPoolFTS.has(key)) return; + const propList = properties.map((p) => `'${p}'`).join(', '); + try { + await executor( + `CALL CREATE_FTS_INDEX('${table}', '${indexName}', [${propList}], stemmer := 'porter')`, + ); + } catch (e: any) { + // 'already exists' is the happy path (index persists on disk between + // process invocations) — anything else we swallow because FTS is + // best-effort: queryFTS itself returns [] on missing-index errors. + const msg = String(e?.message ?? ''); + if (!msg.includes('already exists')) { + // Best-effort — continue without index, queryFTS will fall back to []. + } + } + ensuredPoolFTS.add(key); +} + /** * Execute a single FTS query via a custom executor (for MCP connection pool). * Returns the same shape as core queryFTS (from LadybugDB adapter). @@ -75,6 +131,13 @@ export const searchFTSFromLbug = async ( // The MCP pool supports multiple connections, but FTS is best run serially. const { executeQuery } = await import('../lbug/pool-adapter.js'); const executor = (cypher: string) => executeQuery(repoId, cypher); + + // Lazy-create FTS indexes on first query for this repo (analyze no longer + // creates them up-front, so we ensure them here). Cached per-process. + for (const { table, indexName, properties } of FTS_INDEXES) { + await ensureFTSIndexViaExecutor(executor, repoId, table, indexName, properties); + } + fileResults = await queryFTSViaExecutor(executor, 'File', 'file_fts', query, limit); functionResults = await queryFTSViaExecutor(executor, 'Function', 'function_fts', query, limit); classResults = await queryFTSViaExecutor(executor, 'Class', 'class_fts', query, limit); @@ -87,7 +150,12 @@ export const searchFTSFromLbug = async ( limit, ); } else { - // Use core lbug adapter (CLI / pipeline context) — also sequential for safety + // Use core lbug adapter (CLI / pipeline context) — also sequential for safety. + // Lazy-create FTS indexes on first query (analyze no longer does it). + for (const { table, indexName, properties } of FTS_INDEXES) { + await ensureFTSIndex(table, indexName, [...properties]).catch(() => {}); + } + fileResults = await queryFTS('File', 'file_fts', query, limit, false).catch(() => []); functionResults = await queryFTS('Function', 'function_fts', query, limit, false).catch( () => [], diff --git a/gitnexus/src/mcp/local/local-backend.ts b/gitnexus/src/mcp/local/local-backend.ts index 55157cf05..129cda678 100644 --- a/gitnexus/src/mcp/local/local-backend.ts +++ b/gitnexus/src/mcp/local/local-backend.ts @@ -28,6 +28,7 @@ import { type RegistryEntry, } from '../../storage/repo-manager.js'; import { GroupService, type GroupToolPort } from '../../core/group/service.js'; +import { resolveAtGroupMemberRepoPath } from '../../core/group/resolve-at-member.js'; import { collectBestChunks } from '../../core/embeddings/types.js'; import { EMBEDDING_TABLE_NAME, EMBEDDING_INDEX_NAME } from '../../core/lbug/schema.js'; import { PhaseTimer } from '../../core/search/phase-timer.js'; @@ -218,6 +219,7 @@ export class LocalBackend { impact: (r, p) => this.impact(r as RepoHandle, p), query: (r, p) => this.query(r as RepoHandle, p), impactByUid: (id, uid, d, o) => this.impactByUid(id, uid, d, o), + context: (r, p) => this.context(r as RepoHandle, p), }; this.groupToolSvc = new GroupService(port); } @@ -499,8 +501,17 @@ export class LocalBackend { return this.handleGroupTool(method, params || {}); } + const p = params && typeof params === 'object' ? (params as Record) : {}; + if ( + (method === 'impact' || method === 'query' || method === 'context') && + typeof p.repo === 'string' && + p.repo.startsWith('@') + ) { + return this.callToolAtGroupRepo(method, p); + } + // Resolve repo from optional param (re-reads registry on miss) - const repo = await this.resolveRepo(params?.repo); + const repo = await this.resolveRepo((params as { repo?: string } | undefined)?.repo); switch (method) { case 'query': @@ -2835,17 +2846,103 @@ export class LocalBackend { return this.groupList(params); case 'group_sync': return this.groupSync(params); - case 'group_contracts': - return this.groupContracts(params); - case 'group_query': - return this.groupQuery(params); - case 'group_status': - return this.groupStatus(params); default: - throw new Error(`Unknown group tool: ${method}`); + throw new Error( + `Unknown group tool: ${method}. Removed tools: use repo "@" on impact, query, or context (optional "/"), or MCP resources.`, + ); } } + /** + * Dispatch impact/query/context when `repo` is `@groupName` or `@groupName/memberPath` + * (group mode — not the global indexed-repo `repo` parameter). + */ + private async callToolAtGroupRepo( + method: string, + params: Record, + ): Promise { + await this.refreshRepos(); + + if ( + params.service !== undefined && + params.service !== null && + String(params.service).trim() === '' + ) { + return { error: 'service must not be an empty string' }; + } + + const raw = String(params.repo).slice(1); + const slash = raw.indexOf('/'); + const groupName = (slash === -1 ? raw : raw.slice(0, slash)).trim(); + const memberRest = slash === -1 ? undefined : raw.slice(slash + 1).trim() || undefined; + + const resolved = await resolveAtGroupMemberRepoPath(groupName, memberRest); + if (resolved.ok === false) return { error: resolved.error }; + + const svc = this.getGroupService(); + if (method === 'impact') { + const impactArgs: Record = { + name: groupName, + repo: resolved.repoPath, + target: params.target, + direction: params.direction, + }; + if (params.maxDepth !== undefined) impactArgs.maxDepth = params.maxDepth; + if (params.crossDepth !== undefined) impactArgs.crossDepth = params.crossDepth; + if (params.relationTypes !== undefined) impactArgs.relationTypes = params.relationTypes; + if (params.includeTests !== undefined) impactArgs.includeTests = params.includeTests; + if (params.minConfidence !== undefined) impactArgs.minConfidence = params.minConfidence; + if (params.service !== undefined && params.service !== null) + impactArgs.service = params.service; + if (typeof params.subgroup === 'string') impactArgs.subgroup = params.subgroup; + if (params.timeoutMs !== undefined) impactArgs.timeoutMs = params.timeoutMs; + if (params.timeout !== undefined) impactArgs.timeout = params.timeout; + return svc.groupImpact(impactArgs); + } + if (method === 'query') { + const queryArgs: Record = { + name: groupName, + query: params.query, + }; + if (typeof params.task_context === 'string') queryArgs.task_context = params.task_context; + if (typeof params.goal === 'string') queryArgs.goal = params.goal; + if (typeof params.limit === 'number') queryArgs.limit = params.limit; + if (typeof params.max_symbols === 'number') queryArgs.max_symbols = params.max_symbols; + if (params.include_content !== undefined) queryArgs.include_content = params.include_content; + if (params.service !== undefined && params.service !== null) + queryArgs.service = params.service; + if (memberRest !== undefined) { + queryArgs.subgroup = memberRest; + queryArgs.subgroupExact = true; + } + return svc.groupQuery(queryArgs); + } + if (method === 'context') { + const targetSym = + typeof params.target === 'string' && params.target.trim() !== '' + ? params.target.trim() + : typeof params.name === 'string' && params.name.trim() !== '' + ? params.name.trim() + : undefined; + const contextArgs: Record = { + name: groupName, + target: targetSym, + }; + if (typeof params.uid === 'string') contextArgs.uid = params.uid; + if (typeof params.file_path === 'string') contextArgs.file_path = params.file_path; + if (params.include_content !== undefined) + contextArgs.include_content = params.include_content; + if (params.service !== undefined && params.service !== null) + contextArgs.service = params.service; + if (memberRest !== undefined) { + contextArgs.subgroup = memberRest; + contextArgs.subgroupExact = true; + } + return svc.groupContext(contextArgs); + } + throw new Error(`Internal: unsupported group-repo tool ${method}`); + } + private async groupList(params: Record): Promise { return this.getGroupService().groupList(params); } @@ -2854,18 +2951,45 @@ export class LocalBackend { return this.getGroupService().groupSync(params); } - private async groupContracts(params: Record): Promise { - return this.getGroupService().groupContracts(params); + /** + * MCP resource body for `gitnexus://group/{name}/contracts` (Issue #794). + */ + async readGroupContractsResource( + groupName: string, + filter: { type?: string; repo?: string; unmatchedOnly?: boolean }, + ): Promise { + try { + const params: Record = { name: groupName }; + if (filter.type !== undefined) params.type = filter.type; + if (filter.repo !== undefined) params.repo = filter.repo; + if (filter.unmatchedOnly === true) params.unmatchedOnly = true; + const raw = await this.getGroupService().groupContracts(params); + return LocalBackend.formatGroupResourcePayload(raw); + } catch (e) { + return `error: ${e instanceof Error ? e.message : String(e)}`; + } } - private async groupQuery(params: Record): Promise { - await this.refreshRepos(); - return this.getGroupService().groupQuery(params); + /** + * MCP resource body for `gitnexus://group/{name}/status` (Issue #794). + */ + async readGroupStatusResource(groupName: string): Promise { + try { + const raw = await this.getGroupService().groupStatus({ name: groupName }); + return LocalBackend.formatGroupResourcePayload(raw); + } catch (e) { + return `error: ${e instanceof Error ? e.message : String(e)}`; + } } - private async groupStatus(params: Record): Promise { - await this.refreshRepos(); - return this.getGroupService().groupStatus(params); + private static formatGroupResourcePayload(raw: unknown): string { + if (raw && typeof raw === 'object' && 'error' in raw) { + const err = (raw as { error?: unknown }).error; + if (typeof err === 'string' && err.length > 0) { + return `error: ${err}`; + } + } + return JSON.stringify(raw, null, 2); } /** diff --git a/gitnexus/src/mcp/resources.ts b/gitnexus/src/mcp/resources.ts index dce81bab4..88e7a99cc 100644 --- a/gitnexus/src/mcp/resources.ts +++ b/gitnexus/src/mcp/resources.ts @@ -84,38 +84,140 @@ export function getResourceTemplates(): ResourceTemplate[] { description: 'Step-by-step execution trace', mimeType: 'text/yaml', }, + { + uriTemplate: 'gitnexus://group/{name}/contracts', + name: 'Group Contract Registry', + description: + 'Cross-repo contract registry for a repository group. Optional query: type, repo, unmatchedOnly (true|false).', + mimeType: 'text/yaml', + }, + { + uriTemplate: 'gitnexus://group/{name}/status', + name: 'Group Index Status', + description: 'Per-repo index and contract-registry staleness for a repository group', + mimeType: 'text/yaml', + }, ]; } -/** - * Parse a resource URI to extract the repo name and resource type. - */ -function parseUri(uri: string): { repoName?: string; resourceType: string; param?: string } { - if (uri === 'gitnexus://repos') return { resourceType: 'repos' }; - if (uri === 'gitnexus://setup') return { resourceType: 'setup' }; +/** Query parameters for `gitnexus://group/{name}/contracts` */ +export type GroupContractsResourceFilter = { + type?: string; + repo?: string; + unmatchedOnly?: boolean; +}; - // Repo-scoped: gitnexus://repo/{name}/context - const repoMatch = uri.match(/^gitnexus:\/\/repo\/([^/]+)\/(.+)$/); - if (repoMatch) { - const repoName = decodeURIComponent(repoMatch[1]); - const rest = repoMatch[2]; +/** Normalized parse result for GitNexus MCP resource URIs */ +export type ParsedGitnexusResource = + | { kind: 'repos' } + | { kind: 'setup' } + | { + kind: 'repo'; + repoName: string; + resourceType: string; + param?: string; + } + | { + kind: 'group'; + groupName: string; + resourceType: 'contracts'; + contractsFilter: GroupContractsResourceFilter; + } + | { kind: 'group'; groupName: string; resourceType: 'status' }; + +function parseUnmatchedOnlyParam(raw: string | null): boolean | undefined { + if (raw === null) return undefined; + const v = raw.trim().toLowerCase(); + if (v === 'true' || v === '1') return true; + if (v === 'false' || v === '0') return false; + return undefined; +} + +/** + * Parse a GitNexus resource URI (repos, setup, per-repo, or per-group templates). + * Used by `readResource` and tests (round-trip / dispatch coverage). + */ +export function parseResourceUri(uri: string): ParsedGitnexusResource { + if (uri === 'gitnexus://repos') return { kind: 'repos' }; + if (uri === 'gitnexus://setup') return { kind: 'setup' }; + + let u: URL; + try { + u = new URL(uri); + } catch { + throw new Error(`Unknown resource URI: ${uri}`); + } + + if (u.protocol !== 'gitnexus:') { + throw new Error(`Unknown resource URI: ${uri}`); + } + + if (u.hostname === 'group') { + const segments = u.pathname + .replace(/^\/+|\/+$/g, '') + .split('/') + .filter(Boolean); + if (segments.length < 2) { + throw new Error( + `Invalid group resource URI (expected gitnexus://group/{name}/contracts or .../status): ${uri}`, + ); + } + const tail = segments[segments.length - 1]!; + if (tail !== 'contracts' && tail !== 'status') { + throw new Error(`Unknown group resource path in URI: ${uri}`); + } + const groupName = segments + .slice(0, -1) + .map((s) => decodeURIComponent(s)) + .join('/'); + if (!groupName) { + throw new Error(`Invalid group resource URI (empty group name): ${uri}`); + } + if (tail === 'status') { + return { kind: 'group', groupName, resourceType: 'status' }; + } + const contractsFilter: GroupContractsResourceFilter = {}; + const type = u.searchParams.get('type'); + if (type && type.trim()) contractsFilter.type = type.trim(); + const repo = u.searchParams.get('repo'); + if (repo && repo.trim()) contractsFilter.repo = repo.trim(); + if (u.searchParams.has('unmatchedOnly')) { + const coerced = parseUnmatchedOnlyParam(u.searchParams.get('unmatchedOnly')); + if (coerced !== undefined) contractsFilter.unmatchedOnly = coerced; + } + return { kind: 'group', groupName, resourceType: 'contracts', contractsFilter }; + } + + if (u.hostname === 'repo') { + const segments = u.pathname + .replace(/^\/+|\/+$/g, '') + .split('/') + .filter(Boolean); + if (segments.length < 2) { + throw new Error(`Unknown resource URI: ${uri}`); + } + const repoName = decodeURIComponent(segments[0]!); + const restEncoded = segments.slice(1); + const rest = restEncoded.map((s) => decodeURIComponent(s)).join('/'); if (rest.startsWith('cluster/')) { return { + kind: 'repo', repoName, resourceType: 'cluster', - param: decodeURIComponent(rest.replace('cluster/', '')), + param: rest.replace(/^cluster\//, ''), }; } if (rest.startsWith('process/')) { return { + kind: 'repo', repoName, resourceType: 'process', - param: decodeURIComponent(rest.replace('process/', '')), + param: rest.replace(/^process\//, ''), }; } - return { repoName, resourceType: rest }; + return { kind: 'repo', repoName, resourceType: rest }; } throw new Error(`Unknown resource URI: ${uri}`); @@ -125,18 +227,23 @@ function parseUri(uri: string): { repoName?: string; resourceType: string; param * Read a resource and return its content */ export async function readResource(uri: string, backend: LocalBackend): Promise { - const parsed = parseUri(uri); + const parsed = parseResourceUri(uri); - // Global repos list — no repo context needed - if (parsed.resourceType === 'repos') { + if (parsed.kind === 'repos') { return getReposResource(backend); } - // Setup resource — returns AGENTS.md content for all repos - if (parsed.resourceType === 'setup') { + if (parsed.kind === 'setup') { return getSetupResource(backend); } + if (parsed.kind === 'group') { + if (parsed.resourceType === 'contracts') { + return backend.readGroupContractsResource(parsed.groupName, parsed.contractsFilter); + } + return backend.readGroupStatusResource(parsed.groupName); + } + const repoName = parsed.repoName; switch (parsed.resourceType) { @@ -241,6 +348,10 @@ async function getContextResource(backend: LocalBackend, repoName?: string): Pro lines.push(` - gitnexus://repo/${context.projectName}/processes: All execution flows`); lines.push(` - gitnexus://repo/${context.projectName}/cluster/{name}: Module details`); lines.push(` - gitnexus://repo/${context.projectName}/process/{name}: Process trace`); + lines.push( + ' - gitnexus://group/{name}/contracts: Group contract registry (optional ?type=&repo=&unmatchedOnly=)', + ); + lines.push(' - gitnexus://group/{name}/status: Group index / contract staleness'); return lines.join('\n'); } diff --git a/gitnexus/src/mcp/tools.ts b/gitnexus/src/mcp/tools.ts index 7beb2e970..491c24557 100644 --- a/gitnexus/src/mcp/tools.ts +++ b/gitnexus/src/mcp/tools.ts @@ -15,9 +15,12 @@ export interface ToolDefinition { { type: string; description?: string; - default?: any; + default?: unknown; items?: { type: string }; enum?: string[]; + minimum?: number; + maximum?: number; + minLength?: number; } >; required: string[]; @@ -55,7 +58,11 @@ Returns results grouped by process (execution flow): - process_symbols: all symbols in those flows with file locations and module (functional area) - definitions: standalone types/interfaces not in any process -Hybrid ranking: BM25 keyword + semantic vector search, ranked by Reciprocal Rank Fusion.`, +Hybrid ranking: BM25 keyword + semantic vector search, ranked by Reciprocal Rank Fusion. + +GROUP MODE: set "repo" to "@" to search all member repos in that group (merged via RRF), or "@/" to run against a single member (same path keys as in group.yaml). If you use "@" only, the member repo defaults to the lexicographically first key in group.yaml "repos". Prefer resources for contracts/status (see migration from legacy group_* tools). + +SERVICE: optional monorepo path prefix (POSIX-style, case-sensitive segments). When "repo" starts with "@", only processes whose symbols fall under that prefix are included. For a normal indexed repo name (no leading @), this field is currently ignored by the server.`, inputSchema: { type: 'object', properties: { @@ -69,11 +76,19 @@ Hybrid ranking: BM25 keyword + semantic vector search, ranked by Reciprocal Rank description: 'What you want to find (e.g., "existing auth validation logic"). Helps ranking.', }, - limit: { type: 'number', description: 'Max processes to return (default: 5)', default: 5 }, + limit: { + type: 'number', + description: 'Max processes to return (default: 5)', + default: 5, + minimum: 1, + maximum: 100, + }, max_symbols: { type: 'number', description: 'Max symbols per process (default: 10)', default: 10, + minimum: 1, + maximum: 200, }, include_content: { type: 'boolean', @@ -82,7 +97,14 @@ Hybrid ranking: BM25 keyword + semantic vector search, ranked by Reciprocal Rank }, repo: { type: 'string', - description: 'Repository name or path. Omit if only one repo is indexed.', + description: + 'Indexed repository name or path, or group mode "@" / "@/" (member path keys from group.yaml). Omit when only one indexed repo exists.', + }, + service: { + type: 'string', + minLength: 1, + description: + 'Optional monorepo service root (relative path, "/" separators). In group mode (@repo), prefix-matches symbol file paths; ignored for a normal repo name. Empty string is rejected server-side.', }, }, required: ['query'], @@ -156,7 +178,11 @@ AFTER THIS: Use impact() if planning changes, or READ gitnexus://repo/{name}/pro Handles disambiguation: if multiple symbols share the same name, returns ranked candidates (each with a relevance score) for you to pick from. Use uid for zero-ambiguity lookup, or narrow the search with file_path and/or kind hints. -NOTE: ACCESSES edges (field read/write tracking) are included in context results with reason 'read' or 'write'. CALLS edges resolve through field access chains and method-call chains (e.g., user.address.getCity().save() produces CALLS edges at each step).`, +NOTE: ACCESSES edges (field read/write tracking) are included in context results with reason 'read' or 'write'. CALLS edges resolve through field access chains and method-call chains (e.g., user.address.getCity().save() produces CALLS edges at each step). + +GROUP MODE: set "repo" to "@" to run context in each member repo (aggregated list), or "@/" for one member. If you use "@" only, the member defaults to the lexicographically first key in group.yaml "repos". + +SERVICE: optional monorepo path prefix (case-sensitive path segments). When "repo" starts with "@", prefix-matches resolved symbol file paths; when a hit is outside the prefix, that member returns an empty payload for the symbol. Ignored for a normal indexed repo name.`, inputSchema: { type: 'object', properties: { @@ -178,7 +204,14 @@ NOTE: ACCESSES edges (field read/write tracking) are included in context results }, repo: { type: 'string', - description: 'Repository name or path. Omit if only one repo is indexed.', + description: + 'Indexed repository name or path, or group mode "@" / "@/". Omit if only one repo is indexed.', + }, + service: { + type: 'string', + minLength: 1, + description: + 'Optional monorepo service root (relative path). Applies in group mode (@repo) only; ignored for a normal repo name. Empty string is rejected server-side.', }, }, required: [], @@ -273,7 +306,11 @@ TIP: Default traversal uses CALLS/IMPORTS/EXTENDS/IMPLEMENTS. For class members, Handles disambiguation: when multiple symbols share the target name, returns ranked candidates (each with a relevance score) instead of silently picking one. Use target_uid for zero-ambiguity lookup, or narrow with file_path and/or kind hints. EdgeType: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, HAS_METHOD, HAS_PROPERTY, METHOD_OVERRIDES, METHOD_IMPLEMENTS, ACCESSES -Confidence: 1.0 = certain, <0.8 = fuzzy match`, +Confidence: 1.0 = certain, <0.8 = fuzzy match + +GROUP MODE: set "repo" to "@" for cross-repo impact anchored at the default member (lexicographically first key in group.yaml "repos"), or "@/" to choose the member (same path keys as in group.yaml). Phase-1 walk runs in that member; cross-boundary fan-out uses the group bridge. + +SERVICE: optional monorepo path prefix (case-sensitive path segments). When "repo" starts with "@", scopes the local impact walk and cross-repo symbol paths to files under that prefix; ignored for a normal indexed repo name.`, inputSchema: { type: 'object', properties: { @@ -298,8 +335,18 @@ Confidence: 1.0 = certain, <0.8 = fuzzy match`, }, maxDepth: { type: 'number', - description: 'Max relationship depth (default: 3)', + description: 'Max relationship depth (default: 3, server clamps to 1–32)', default: 3, + minimum: 1, + maximum: 32, + }, + crossDepth: { + type: 'number', + description: + 'Cross-repository hop depth via contract bridge (default: 1; values above server maximum are clamped)', + default: 1, + minimum: 1, + maximum: 32, }, relationTypes: { type: 'array', @@ -308,10 +355,42 @@ Confidence: 1.0 = certain, <0.8 = fuzzy match`, 'Filter: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, HAS_METHOD, HAS_PROPERTY, METHOD_OVERRIDES, METHOD_IMPLEMENTS, ACCESSES (default: usage-based, ACCESSES excluded by default)', }, includeTests: { type: 'boolean', description: 'Include test files (default: false)' }, - minConfidence: { type: 'number', description: 'Minimum confidence 0-1 (default: 0.7)' }, + minConfidence: { + type: 'number', + description: + 'Minimum edge confidence 0–1 (default: 0 when omitted; server clamps to 0–1)', + default: 0, + minimum: 0, + maximum: 1, + }, repo: { type: 'string', - description: 'Repository name or path. Omit if only one repo is indexed.', + description: + 'Indexed repository name or path, or group mode "@" / "@/". Omit if only one repo is indexed.', + }, + service: { + type: 'string', + minLength: 1, + description: + 'Optional monorepo service root (relative path). Applies when "repo" is group mode (@…); ignored for a normal repo name. Empty string is rejected server-side.', + }, + subgroup: { + type: 'string', + description: + 'Optional group subgroup prefix (member repo paths) limiting which repos participate in cross fan-out.', + }, + timeoutMs: { + type: 'number', + description: + 'Wall-clock budget in milliseconds for the Phase-1 local impact leg (default 30000)', + minimum: 1, + maximum: 3600000, + }, + timeout: { + type: 'number', + description: 'Alias of timeoutMs (milliseconds) when timeoutMs is omitted', + minimum: 1, + maximum: 3600000, }, }, required: ['target', 'direction'], @@ -429,49 +508,4 @@ WHEN TO USE: After changing group.yaml or re-indexing member repos.`, required: ['name'], }, }, - { - name: 'group_contracts', - description: `Inspect contracts and cross-links from the group's contracts.json. - -WHEN TO USE: Debug cross-repo links after group_sync.`, - inputSchema: { - type: 'object', - properties: { - name: { type: 'string', description: 'Group name' }, - type: { type: 'string', description: 'Filter by contract type (http, topic, …)' }, - repo: { type: 'string', description: 'Filter by group repo path (e.g. app/backend)' }, - unmatchedOnly: { type: 'boolean', description: 'Only contracts with no cross-link' }, - }, - required: ['name'], - }, - }, - { - name: 'group_query', - description: `Run the query tool across all repos in a group and merge process results via reciprocal rank fusion. - -WHEN TO USE: Semantic / hybrid search across a whole product group.`, - inputSchema: { - type: 'object', - properties: { - name: { type: 'string', description: 'Group name' }, - query: { type: 'string', description: 'Search query' }, - subgroup: { type: 'string', description: 'Limit to repo paths under this prefix' }, - limit: { type: 'number', description: 'Max merged results (default 5)' }, - }, - required: ['name', 'query'], - }, - }, - { - name: 'group_status', - description: `Report index staleness (commit vs HEAD) and Contract Registry staleness (indexedAt) for each repo in a group. - -WHEN TO USE: Before group_sync or when agents should refresh indexes.`, - inputSchema: { - type: 'object', - properties: { - name: { type: 'string', description: 'Group name' }, - }, - required: ['name'], - }, - }, ]; diff --git a/gitnexus/test/integration/group/group-cli.test.ts b/gitnexus/test/integration/group/group-cli.test.ts index 02da904dc..7a76f86fd 100644 --- a/gitnexus/test/integration/group/group-cli.test.ts +++ b/gitnexus/test/integration/group/group-cli.test.ts @@ -65,4 +65,51 @@ describe('group CLI', () => { const blanketClosePattern = /closeLbug\s*\(\s*\)/; expect(source).not.toMatch(blanketClosePattern); }); + + it('group impact requires --target and --repo', () => { + const c = runGroup(['create', 'impcli']); + expect(c.status).toBe(0); + const r = runGroup(['impact', 'impcli']); + expect(r.status).not.toBe(0); + }); + + it('group impact runs with Issue #794 style flags (fixture-backed home)', () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-cli-impact-')); + try { + const gd = path.join(home, 'groups', 'test-group'); + fs.mkdirSync(gd, { recursive: true }); + fs.copyFileSync( + path.join(repoRoot, 'test', 'fixtures', 'group', 'group.yaml'), + path.join(gd, 'group.yaml'), + ); + const r = spawnSync( + process.execPath, + [ + '--import', + tsxImportUrl, + cliEntry, + 'group', + 'impact', + 'test-group', + '--target', + 'health', + '--repo', + 'app/backend', + '--json', + ], + { + cwd: repoRoot, + encoding: 'utf8', + timeout: 20000, + stdio: ['pipe', 'pipe', 'pipe'], + env: { ...process.env, GITNEXUS_HOME: home }, + }, + ); + expect(r.status).not.toBe(0); + const msg = `${r.stderr}\n${r.stdout}`; + expect(msg).toMatch(/error|indexed|not found|repository/i); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); }); diff --git a/gitnexus/test/integration/group/group-impact.test.ts b/gitnexus/test/integration/group/group-impact.test.ts new file mode 100644 index 000000000..50331cc90 --- /dev/null +++ b/gitnexus/test/integration/group/group-impact.test.ts @@ -0,0 +1,74 @@ +/** + * Group impact: exercise GroupService.groupImpact with fixture-backed group config + * and a stubbed port (no LadybugDB / bridge required when local impact yields no UIDs). + */ +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import os from 'node:os'; +import { GroupService, type GroupToolPort } from '../../../src/core/group/service.js'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const fixturesDir = path.resolve(__dirname, '../../fixtures/group'); + +let tmpHome: string; + +beforeAll(() => { + tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-grp-impact-int-')); + const groupDir = path.join(tmpHome, 'groups', 'test-group'); + fs.mkdirSync(groupDir, { recursive: true }); + fs.copyFileSync(path.join(fixturesDir, 'group.yaml'), path.join(groupDir, 'group.yaml')); +}); + +afterAll(() => { + if (tmpHome) fs.rmSync(tmpHome, { recursive: true, force: true }); +}); + +function stubPort(): GroupToolPort { + return { + resolveRepo: vi.fn(async () => ({ + id: 'stub', + name: 'stub', + repoPath: '/tmp/repo', + storagePath: '/tmp/.gitnexus', + })), + impact: vi.fn(async () => ({ + target: {}, + byDepth: {}, + summary: { direct: 0, processes_affected: 0, modules_affected: 0 }, + risk: 'LOW', + })), + query: vi.fn(), + impactByUid: vi.fn(), + context: vi.fn(), + }; +} + +describe('group impact integration', () => { + it('returns validation error when parameters are incomplete', async () => { + const svc = new GroupService(stubPort()); + const r = (await svc.groupImpact({ name: 'x', direction: 'upstream' })) as { error: string }; + expect(r.error).toMatch(/repo is required|target is required/); + }); + + it('runs happy-path stub against fixture group (stops before bridge when no symbol UIDs)', async () => { + const prev = process.env.GITNEXUS_HOME; + process.env.GITNEXUS_HOME = tmpHome; + try { + const svc = new GroupService(stubPort()); + const r = (await svc.groupImpact({ + name: 'test-group', + repo: 'app/backend', + target: 'health', + direction: 'upstream', + })) as { group?: string; error?: string; cross?: unknown[] }; + expect(r.error).toBeUndefined(); + expect(r.group).toBe('test-group'); + expect(Array.isArray(r.cross)).toBe(true); + } finally { + if (prev === undefined) delete process.env.GITNEXUS_HOME; + else process.env.GITNEXUS_HOME = prev; + } + }); +}); diff --git a/gitnexus/test/unit/group/cross-impact.test.ts b/gitnexus/test/unit/group/cross-impact.test.ts new file mode 100644 index 000000000..3d78ff1cf --- /dev/null +++ b/gitnexus/test/unit/group/cross-impact.test.ts @@ -0,0 +1,196 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import * as os from 'node:os'; +import { + validateGroupImpactParams, + runGroupImpact, + MAX_SUPPORTED_CROSS_DEPTH, + DEFAULT_LOCAL_IMPACT_TIMEOUT_MS, + collectImpactSymbolUids, + fileMatchesServicePrefix, +} from '../../../src/core/group/cross-impact.js'; +import type { GroupToolPort } from '../../../src/core/group/service.js'; +import { writeBridgeMeta } from '../../../src/core/group/bridge-db.js'; +import { BRIDGE_SCHEMA_VERSION } from '../../../src/core/group/bridge-schema.js'; + +function tmpGroup(): { tmpDir: string; groupDir: string; cleanup: () => void } { + const tmpDir = path.join(os.tmpdir(), `gitnexus-ci-${Date.now()}-${Math.random()}`); + const groupDir = path.join(tmpDir, 'groups', 'g1'); + fs.mkdirSync(groupDir, { recursive: true }); + fs.writeFileSync( + path.join(groupDir, 'group.yaml'), + `version: 1 +name: g1 +description: "" +repos: + app/backend: reg-be + app/frontend: reg-fe +links: [] +packages: {} +detect: + http: true + grpc: true + topics: true + shared_libs: true + embedding_fallback: true +matching: + bm25_threshold: 0.7 + embedding_threshold: 0.65 + max_candidates_per_step: 3 +`, + ); + return { + tmpDir, + groupDir, + cleanup: () => fs.rmSync(tmpDir, { recursive: true, force: true }), + }; +} + +describe('cross-impact', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it('test_validateGroupImpactParams_rejects_bad_direction', () => { + const r = validateGroupImpactParams({ + name: 'g', + repo: 'a', + target: 't', + direction: 'sideways', + }); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.error).toContain('direction'); + }); + + it('test_validateGroupImpactParams_clamps_crossDepth_and_warns', () => { + const r = validateGroupImpactParams({ + name: 'g', + repo: 'a', + target: 't', + direction: 'upstream', + crossDepth: 99, + }); + expect(r.ok).toBe(true); + if (r.ok) { + expect(r.crossDepth).toBe(MAX_SUPPORTED_CROSS_DEPTH); + expect(r.crossDepthWarning).toBeDefined(); + } + }); + + it('test_validateGroupImpactParams_default_timeout', () => { + const r = validateGroupImpactParams({ + name: 'g', + repo: 'a', + target: 't', + direction: 'downstream', + }); + expect(r.ok).toBe(true); + if (r.ok) expect(r.timeoutMs).toBe(DEFAULT_LOCAL_IMPACT_TIMEOUT_MS); + }); + + it('test_collectImpactSymbolUids_respects_service_prefix', () => { + const local = { + target: { id: 'a', filePath: 'services/auth/x.ts' }, + byDepth: { + 1: [{ id: 'b', filePath: 'other/y.ts' }], + }, + }; + const uids = collectImpactSymbolUids(local, 'services/auth').uids; + expect(uids).toContain('a'); + expect(uids).not.toContain('b'); + }); + + it('test_fileMatchesServicePrefix', () => { + expect(fileMatchesServicePrefix('services/auth/a.ts', 'services/auth')).toBe(true); + expect(fileMatchesServicePrefix('services/aut', 'services/auth')).toBe(false); + }); + + it('test_runGroupImpact_local_timeout_returns_truncation', async () => { + const { tmpDir, cleanup } = tmpGroup(); + vi.stubEnv('GITNEXUS_HOME', tmpDir); + try { + let impactCalls = 0; + const port: GroupToolPort = { + resolveRepo: vi.fn(async () => ({ + id: 'be', + name: 'reg-be', + repoPath: '/r', + storagePath: '/r/.gitnexus', + })), + impact: vi.fn(async () => { + impactCalls++; + await new Promise((r) => setTimeout(r, 200)); + return { summary: { direct: 1 }, byDepth: { 1: [{ id: 'x' }] } }; + }), + query: vi.fn(), + impactByUid: vi.fn(), + context: vi.fn(), + }; + const r = await runGroupImpact( + { port, gitnexusDir: tmpDir }, + { + name: 'g1', + repo: 'app/backend', + target: 'Sym', + direction: 'upstream', + timeoutMs: 15, + }, + ); + expect(impactCalls).toBe(1); + expect('error' in r).toBe(false); + if (!('error' in r)) { + expect(r.truncationReason).toBe('timeout'); + expect(r.truncated).toBe(true); + } + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); + + it('test_runGroupImpact_bridge_schema_mismatch_returns_error', async () => { + const { tmpDir, groupDir, cleanup } = tmpGroup(); + vi.stubEnv('GITNEXUS_HOME', tmpDir); + await writeBridgeMeta(groupDir, { + version: BRIDGE_SCHEMA_VERSION + 9, + generatedAt: new Date().toISOString(), + missingRepos: [], + }); + try { + const port: GroupToolPort = { + resolveRepo: vi.fn(async () => ({ + id: 'be', + name: 'reg-be', + repoPath: '/r', + storagePath: '/r/.gitnexus', + })), + impact: vi.fn(async () => ({ + target: { id: 'u1', filePath: 'src/a.ts' }, + summary: { direct: 1, processes_affected: 0, modules_affected: 0 }, + byDepth: { 1: [{ id: 'u1', filePath: 'src/a.ts' }] }, + risk: 'LOW', + })), + query: vi.fn(), + impactByUid: vi.fn(), + context: vi.fn(), + }; + const r = await runGroupImpact( + { port, gitnexusDir: tmpDir }, + { + name: 'g1', + repo: 'app/backend', + target: 'Sym', + direction: 'upstream', + }, + ); + expect('error' in r).toBe(true); + if ('error' in r) { + expect(r.error).toContain('schema'); + } + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); +}); diff --git a/gitnexus/test/unit/group/group-path-utils.test.ts b/gitnexus/test/unit/group/group-path-utils.test.ts new file mode 100644 index 000000000..0f57e0adc --- /dev/null +++ b/gitnexus/test/unit/group/group-path-utils.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect } from 'vitest'; +import { + fileMatchesServicePrefix, + normalizeServicePrefix, + repoInSubgroup, +} from '../../../src/core/group/group-path-utils.js'; + +describe('group-path-utils', () => { + describe('normalizeServicePrefix', () => { + it('returns undefined for null/undefined/empty', () => { + expect(normalizeServicePrefix(undefined)).toBeUndefined(); + expect(normalizeServicePrefix(null)).toBeUndefined(); + expect(normalizeServicePrefix('')).toBeUndefined(); + expect(normalizeServicePrefix(' ')).toBeUndefined(); + }); + + it('strips trailing slashes', () => { + expect(normalizeServicePrefix('services/auth/')).toBe('services/auth'); + expect(normalizeServicePrefix('services/auth///')).toBe('services/auth'); + }); + + it('normalizes Windows-style backslashes to POSIX', () => { + expect(normalizeServicePrefix('services\\auth')).toBe('services/auth'); + expect(normalizeServicePrefix('app\\backend\\')).toBe('app/backend'); + }); + }); + + describe('fileMatchesServicePrefix', () => { + it('returns true when prefix is empty/undefined', () => { + expect(fileMatchesServicePrefix('any/file.ts', undefined)).toBe(true); + expect(fileMatchesServicePrefix('any/file.ts', '')).toBe(true); + }); + + it('returns false when filePath is missing but prefix is set', () => { + expect(fileMatchesServicePrefix(undefined, 'services/auth')).toBe(false); + }); + + it('matches exact prefix and descendants', () => { + expect(fileMatchesServicePrefix('services/auth', 'services/auth')).toBe(true); + expect(fileMatchesServicePrefix('services/auth/a.ts', 'services/auth')).toBe(true); + }); + + it('rejects partial-segment matches', () => { + expect(fileMatchesServicePrefix('services/aut', 'services/auth')).toBe(false); + expect(fileMatchesServicePrefix('services/authz/a.ts', 'services/auth')).toBe(false); + }); + + it('matches Windows-style file paths against POSIX prefix', () => { + expect(fileMatchesServicePrefix('services\\auth\\a.ts', 'services/auth')).toBe(true); + expect(fileMatchesServicePrefix('services\\authz\\a.ts', 'services/auth')).toBe(false); + }); + }); + + describe('repoInSubgroup', () => { + it('matches every repo when subgroup is empty/undefined', () => { + expect(repoInSubgroup('any/repo', undefined)).toBe(true); + expect(repoInSubgroup('any/repo', '')).toBe(true); + expect(repoInSubgroup('any/repo', ' ')).toBe(true); + }); + + it('matches exact path and descendants by default', () => { + expect(repoInSubgroup('app/backend', 'app/backend')).toBe(true); + expect(repoInSubgroup('app/backend/sub', 'app/backend')).toBe(true); + expect(repoInSubgroup('app/frontend', 'app/backend')).toBe(false); + }); + + it('strips trailing slashes from subgroup', () => { + expect(repoInSubgroup('app/backend', 'app/backend/')).toBe(true); + expect(repoInSubgroup('app/backend/x', 'app/backend///')).toBe(true); + }); + + it('with exact=true matches only the exact repo', () => { + expect(repoInSubgroup('app/backend', 'app/backend', true)).toBe(true); + expect(repoInSubgroup('app/backend/sub', 'app/backend', true)).toBe(false); + }); + + it('rejects partial-segment matches', () => { + expect(repoInSubgroup('app/backendz', 'app/backend')).toBe(false); + }); + + it('normalizes Windows-style paths on both sides', () => { + expect(repoInSubgroup('app\\backend', 'app/backend')).toBe(true); + expect(repoInSubgroup('app/backend/x', 'app\\backend')).toBe(true); + expect(repoInSubgroup('app\\backend\\sub', 'app\\backend', true)).toBe(false); + }); + }); +}); diff --git a/gitnexus/test/unit/group/group-service-group-mode.test.ts b/gitnexus/test/unit/group/group-service-group-mode.test.ts new file mode 100644 index 000000000..ebd0ee0ba --- /dev/null +++ b/gitnexus/test/unit/group/group-service-group-mode.test.ts @@ -0,0 +1,129 @@ +/** + * Documents MCP → GroupService mapping: callers use `name` + concrete params; + * the "@group" string is interpreted only in LocalBackend.callTool (Issue #794). + */ +import { describe, it, expect, vi } from 'vitest'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import * as os from 'node:os'; +import { + GroupService, + type GroupToolPort, + type GroupRepoHandle, +} from '../../../src/core/group/service.js'; + +function makeTmpGroup(): { tmpDir: string; cleanup: () => void } { + const tmpDir = path.join(os.tmpdir(), `gitnexus-gmode-${Date.now()}`); + const groupDir = path.join(tmpDir, 'groups', 'test-group'); + fs.mkdirSync(groupDir, { recursive: true }); + fs.writeFileSync( + path.join(groupDir, 'group.yaml'), + `version: 1 +name: test-group +repos: + app/backend: test-backend + app/frontend: test-frontend +`, + ); + return { tmpDir, cleanup: () => fs.rmSync(tmpDir, { recursive: true, force: true }) }; +} + +function makePort(overrides: Partial = {}): GroupToolPort { + return { + resolveRepo: vi.fn( + async (name?: string): Promise => ({ + id: name || 'test', + name: name || 'test', + repoPath: '/tmp/repo', + storagePath: '/tmp/repo/.gitnexus', + }), + ), + impact: vi.fn(async () => ({ target: {}, byDepth: {} })), + query: vi.fn(async () => ({ + processes: [{ id: 'p1', heuristicLabel: 'Proc' }], + process_symbols: [ + { id: 's1', process_id: 'p1', filePath: 'services/auth/a.ts' }, + { id: 's2', process_id: 'p1', filePath: 'other/b.ts' }, + ], + })), + impactByUid: vi.fn(async () => null), + context: vi.fn(async () => ({ + status: 'found', + symbol: { filePath: 'services/auth/x.ts', uid: 'u1', name: 'X' }, + })), + ...overrides, + }; +} + +describe('GroupService group-mode API surface', () => { + it('groupQuery uses name (never @-repo) and optional service filters processes', async () => { + const { tmpDir, cleanup } = makeTmpGroup(); + vi.stubEnv('GITNEXUS_HOME', tmpDir); + try { + const query = vi.fn(async () => ({ + processes: [{ id: 'p1' }], + process_symbols: [ + { id: 's1', process_id: 'p1', filePath: 'services/auth/a.ts' }, + { id: 's2', process_id: 'p1', filePath: 'other/b.ts' }, + ], + })); + const svc = new GroupService(makePort({ query })); + const r = (await svc.groupQuery({ + name: 'test-group', + query: 'oauth', + service: 'services/auth', + })) as { results: Array<{ id?: string }> }; + expect(query).toHaveBeenCalled(); + expect(r.results.every((row) => row.id === 'p1')).toBe(true); + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); + + it('groupQuery rejects empty service string', async () => { + const { tmpDir, cleanup } = makeTmpGroup(); + vi.stubEnv('GITNEXUS_HOME', tmpDir); + try { + const svc = new GroupService(makePort()); + const r = await svc.groupQuery({ name: 'test-group', query: 'x', service: ' ' }); + expect(r).toEqual({ error: 'service must not be an empty string' }); + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); + + it('groupContext uses name + target (MCP maps @group to name)', async () => { + const { tmpDir, cleanup } = makeTmpGroup(); + vi.stubEnv('GITNEXUS_HOME', tmpDir); + try { + const svc = new GroupService(makePort()); + const r = await svc.groupContext({ name: 'test-group', target: 'MySym' }); + expect(r.group).toBe('test-group'); + expect(r.results).toHaveLength(2); + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); + + it('groupImpact with mock port returns structured result without @ in params', async () => { + const { tmpDir, cleanup } = makeTmpGroup(); + vi.stubEnv('GITNEXUS_HOME', tmpDir); + try { + const svc = new GroupService(makePort()); + const r = (await svc.groupImpact({ + name: 'test-group', + repo: 'app/backend', + target: 't', + direction: 'upstream', + })) as { group?: string; error?: string }; + expect(r.error).toBeUndefined(); + expect(r.group).toBe('test-group'); + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); +}); diff --git a/gitnexus/test/unit/group/group-tools.test.ts b/gitnexus/test/unit/group/group-tools.test.ts index e58077442..85ba45f0a 100644 --- a/gitnexus/test/unit/group/group-tools.test.ts +++ b/gitnexus/test/unit/group/group-tools.test.ts @@ -2,16 +2,10 @@ import { describe, it, expect } from 'vitest'; import { GITNEXUS_TOOLS } from '../../../src/mcp/tools.js'; -const GROUP_TOOL_NAMES = [ - 'group_list', - 'group_sync', - 'group_contracts', - 'group_query', - 'group_status', -]; +const GROUP_TOOL_NAMES = ['group_list', 'group_sync']; describe('Group MCP tools', () => { - it('all 5 group tools are registered', () => { + it('group_list and group_sync are registered', () => { for (const name of GROUP_TOOL_NAMES) { const tool = GITNEXUS_TOOLS.find((t) => t.name === name); expect(tool, `tool ${name} should be registered`).toBeDefined(); diff --git a/gitnexus/test/unit/group/service.test.ts b/gitnexus/test/unit/group/service.test.ts index e4b10443c..8c5c0ed6d 100644 --- a/gitnexus/test/unit/group/service.test.ts +++ b/gitnexus/test/unit/group/service.test.ts @@ -44,6 +44,10 @@ function makePort(overrides: Partial = {}): GroupToolPort { impact: vi.fn(async () => ({ symbols: [] })), query: vi.fn(async () => ({ processes: [] })), impactByUid: vi.fn(async () => null), + context: vi.fn(async () => ({ + status: 'found', + symbol: { filePath: 'services/auth/x.ts', uid: 'u1', name: 'X' }, + })), ...overrides, }; } @@ -233,6 +237,46 @@ describe('GroupService', () => { cleanup(); } }); + + it('test_groupContracts_skips_corrupt_contract_rows', async () => { + const { groupDir, cleanup, tmpDir } = makeTmpGroup(); + try { + vi.stubEnv('GITNEXUS_HOME', tmpDir); + const badJson = `{ + "version": 1, + "generatedAt": "2026-01-01T00:00:00.000Z", + "repoSnapshots": {}, + "missingRepos": [], + "contracts": [ + { "not": "a-contract" }, + { + "contractId": "http::GET::/ok", + "type": "http", + "repo": "app/backend", + "role": "provider", + "symbolUid": "u", + "symbolRef": { "filePath": "a.ts", "name": "f" }, + "symbolName": "f", + "confidence": 1, + "meta": {} + } + ], + "crossLinks": [] + }`; + fs.writeFileSync(path.join(groupDir, 'contracts.json'), badJson, 'utf-8'); + + const svc = new GroupService(makePort()); + const result = (await svc.groupContracts({ name: 'test-group' })) as { + contracts: unknown[]; + skippedCorrupt?: number; + }; + expect(result.contracts).toHaveLength(1); + expect(result.skippedCorrupt).toBe(1); + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); }); describe('groupSync', () => { @@ -328,6 +372,135 @@ describe('GroupService', () => { cleanup(); } }); + + it('test_groupQuery_subgroupExact_skips_descendant_member_paths', async () => { + const tmpDir = path.join(os.tmpdir(), `gitnexus-svc-nest-${Date.now()}`); + const groupDir = path.join(tmpDir, 'groups', 'nest-group'); + fs.mkdirSync(groupDir, { recursive: true }); + fs.writeFileSync( + path.join(groupDir, 'group.yaml'), + `version: 1 +name: nest-group +repos: + app/frontend: fe-root + app/frontend/mobile: fe-nested + app/backend: be1 +`, + ); + try { + vi.stubEnv('GITNEXUS_HOME', tmpDir); + const query = vi.fn(async () => ({ processes: [{ name: 'p1' }] })); + const port = makePort({ query }); + const svc = new GroupService(port); + + const prefixOnly = (await svc.groupQuery({ + name: 'nest-group', + query: 'x', + subgroup: 'app/frontend', + })) as { per_repo: Array<{ repo: string }> }; + expect(prefixOnly.per_repo.map((r) => r.repo).sort()).toEqual([ + 'app/frontend', + 'app/frontend/mobile', + ]); + + const exact = (await svc.groupQuery({ + name: 'nest-group', + query: 'x', + subgroup: 'app/frontend', + subgroupExact: true, + })) as { per_repo: Array<{ repo: string }> }; + expect(exact.per_repo).toHaveLength(1); + expect(exact.per_repo[0].repo).toBe('app/frontend'); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + }); + + describe('groupImpact', () => { + it('test_groupImpact_returns_validation_error', async () => { + const svc = new GroupService(makePort()); + const r = (await svc.groupImpact({})) as { error: string }; + expect(r.error).toContain('name'); + }); + }); + + describe('groupContext', () => { + it('test_groupContext_requires_target_or_uid', async () => { + const svc = new GroupService(makePort()); + const r = await svc.groupContext({ name: 'test-group' }); + expect(r.error).toContain('target'); + }); + + it('test_groupContext_iterates_repos', async () => { + const { cleanup, tmpDir } = makeTmpGroup(); + try { + vi.stubEnv('GITNEXUS_HOME', tmpDir); + const port = makePort(); + const svc = new GroupService(port); + const r = await svc.groupContext({ name: 'test-group', target: 'MySym' }); + expect(r.group).toBe('test-group'); + expect(r.results).toHaveLength(2); + expect(port.context).toHaveBeenCalledTimes(2); + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); + + it('test_groupContext_subgroupExact_skips_descendant_member_paths', async () => { + const tmpDir = path.join(os.tmpdir(), `gitnexus-ctx-nest-${Date.now()}`); + const groupDir = path.join(tmpDir, 'groups', 'nest-group'); + fs.mkdirSync(groupDir, { recursive: true }); + fs.writeFileSync( + path.join(groupDir, 'group.yaml'), + `version: 1 +name: nest-group +repos: + app/frontend: fe-root + app/frontend/mobile: fe-nested +`, + ); + try { + vi.stubEnv('GITNEXUS_HOME', tmpDir); + const port = makePort(); + const svc = new GroupService(port); + await svc.groupContext({ + name: 'nest-group', + target: 'X', + subgroup: 'app/frontend', + subgroupExact: true, + }); + expect(port.context).toHaveBeenCalledTimes(1); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it('test_groupContext_service_prefix_filters_payload', async () => { + const { cleanup, tmpDir } = makeTmpGroup(); + try { + vi.stubEnv('GITNEXUS_HOME', tmpDir); + const port = makePort({ + context: vi.fn(async () => ({ + status: 'found', + symbol: { filePath: 'other/path/x.ts', uid: 'u1', name: 'X' }, + })), + }); + const svc = new GroupService(port); + const r = await svc.groupContext({ + name: 'test-group', + target: 'MySym', + service: 'services/auth', + }); + expect(r.results.every((x) => Object.keys(x.payload as object).length === 0)).toBe(true); + } finally { + vi.unstubAllEnvs(); + cleanup(); + } + }); }); describe('groupStatus', () => { diff --git a/gitnexus/test/unit/mcp/group-repo-routing.test.ts b/gitnexus/test/unit/mcp/group-repo-routing.test.ts new file mode 100644 index 000000000..ddf7d03a5 --- /dev/null +++ b/gitnexus/test/unit/mcp/group-repo-routing.test.ts @@ -0,0 +1,230 @@ +/** + * LocalBackend.callTool routes impact/query/context to GroupService when repo starts with "@". + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import * as os from 'node:os'; + +const { lbugMocks } = vi.hoisted(() => ({ + lbugMocks: { + initLbug: vi.fn().mockResolvedValue(undefined), + executeQuery: vi.fn().mockResolvedValue([]), + executeParameterized: vi.fn().mockResolvedValue([]), + closeLbug: vi.fn().mockResolvedValue(undefined), + isLbugReady: vi.fn().mockReturnValue(true), + }, +})); + +vi.mock('../../../src/core/lbug/pool-adapter.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, ...lbugMocks }; +}); + +vi.mock('../../../src/mcp/core/lbug-adapter.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, ...lbugMocks }; +}); + +vi.mock('../../../src/storage/repo-manager.js', () => ({ + listRegisteredRepos: vi.fn().mockResolvedValue([]), + cleanupOldKuzuFiles: vi.fn().mockResolvedValue({ found: false, needsReindex: false }), +})); + +vi.mock('../../../src/core/search/bm25-index.js', () => ({ + searchFTSFromLbug: vi.fn().mockResolvedValue([]), +})); + +vi.mock('../../../src/mcp/core/embedder.js', () => ({ + embedQuery: vi.fn().mockResolvedValue([]), + getEmbeddingDims: vi.fn().mockReturnValue(384), +})); + +import { LocalBackend } from '../../../src/mcp/local/local-backend.js'; +import { GroupService } from '../../../src/core/group/service.js'; + +describe('LocalBackend @group repo routing', () => { + let tmpDir: string; + let groupSpyQuery: ReturnType; + let groupSpyImpact: ReturnType; + let groupSpyContext: ReturnType; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-atgrp-')); + const groupDir = path.join(tmpDir, 'groups', 'g1'); + fs.mkdirSync(groupDir, { recursive: true }); + fs.writeFileSync( + path.join(groupDir, 'group.yaml'), + `version: 1 +name: g1 +repos: + app/backend: test-backend + app/frontend: test-frontend +`, + ); + vi.stubEnv('GITNEXUS_HOME', tmpDir); + groupSpyQuery = vi + .spyOn(GroupService.prototype, 'groupQuery') + .mockResolvedValue({ via: 'query' }); + groupSpyImpact = vi + .spyOn(GroupService.prototype, 'groupImpact') + .mockResolvedValue({ via: 'impact' }); + groupSpyContext = vi.spyOn(GroupService.prototype, 'groupContext').mockResolvedValue({ + group: 'g1', + results: [], + }); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('routes query to groupQuery with default member path (first sorted repos key)', async () => { + const backend = new LocalBackend(); + const out = await backend.callTool('query', { repo: '@g1', query: 'login' }); + expect(out).toEqual({ via: 'query' }); + expect(groupSpyQuery).toHaveBeenCalledWith( + expect.objectContaining({ name: 'g1', query: 'login' }), + ); + const arg = groupSpyQuery.mock.calls[0][0] as Record; + expect(arg).not.toHaveProperty('repo'); + }); + + it('routes query with explicit member path as exact subgroup (no descendant repo bleed)', async () => { + const backend = new LocalBackend(); + await backend.callTool('query', { repo: '@g1/app/frontend', query: 'x' }); + expect(groupSpyQuery).toHaveBeenCalledWith( + expect.objectContaining({ + name: 'g1', + query: 'x', + subgroup: 'app/frontend', + subgroupExact: true, + }), + ); + }); + + it('routes impact to groupImpact with resolved repo member path', async () => { + const backend = new LocalBackend(); + const out = await backend.callTool('impact', { + repo: '@g1', + target: 'Sym', + direction: 'upstream', + }); + expect(out).toEqual({ via: 'impact' }); + expect(groupSpyImpact).toHaveBeenCalledWith( + expect.objectContaining({ + name: 'g1', + repo: 'app/backend', + target: 'Sym', + direction: 'upstream', + }), + ); + }); + + it('routes context to groupContext', async () => { + const backend = new LocalBackend(); + await backend.callTool('context', { repo: '@g1', target: 'Sym' }); + expect(groupSpyContext).toHaveBeenCalledWith( + expect.objectContaining({ name: 'g1', target: 'Sym' }), + ); + }); + + it('maps MCP symbol name to groupContext target (does not overwrite group name)', async () => { + const backend = new LocalBackend(); + await backend.callTool('context', { repo: '@g1', name: 'MyClass' }); + expect(groupSpyContext).toHaveBeenCalledWith( + expect.objectContaining({ name: 'g1', target: 'MyClass' }), + ); + }); + + it('returns error for unknown group name', async () => { + const backend = new LocalBackend(); + const out = await backend.callTool('query', { repo: '@no-such-group', query: 'x' }); + expect(out).toHaveProperty('error'); + expect(String((out as { error: string }).error)).toMatch( + /not found|no such|unknown|exist|ENOENT/i, + ); + }); + + it('returns error for unknown member path', async () => { + const backend = new LocalBackend(); + const out = await backend.callTool('query', { repo: '@g1/not-a-member', query: 'x' }); + expect(out).toHaveProperty('error'); + expect(String((out as { error: string }).error)).toMatch(/Unknown member path/i); + }); + + it('rejects empty service without calling group tools', async () => { + const backend = new LocalBackend(); + const out = await backend.callTool('query', { repo: '@g1', query: 'x', service: '' }); + expect(out).toEqual({ error: 'service must not be an empty string' }); + expect(groupSpyQuery).not.toHaveBeenCalled(); + }); + + it('unknown group_* tools mention removal', async () => { + const backend = new LocalBackend(); + await expect(backend.callTool('group_query', { name: 'g1', query: 'x' })).rejects.toThrow( + /Removed tools/, + ); + }); + + it('removed group_contracts mentions migration', async () => { + const backend = new LocalBackend(); + await expect(backend.callTool('group_contracts', { name: 'g1' })).rejects.toThrow( + /Removed tools/, + ); + }); + + it('removed group_status mentions migration', async () => { + const backend = new LocalBackend(); + await expect(backend.callTool('group_status', { name: 'g1' })).rejects.toThrow(/Removed tools/); + }); + + describe('Issue #794 manual smoke checklist (automated)', () => { + beforeEach(() => { + const groupDir = path.join(tmpDir, 'groups', 'myproduct'); + fs.mkdirSync(groupDir, { recursive: true }); + fs.writeFileSync( + path.join(groupDir, 'group.yaml'), + `version: 1 +name: myproduct +repos: + app/backend: test-backend + app/frontend: test-frontend +`, + ); + }); + + it.each([ + { + method: 'impact', + params: { repo: '@myproduct', target: 'UserService.login', service: 'app/backend' }, + spy: () => groupSpyImpact, + }, + { + method: 'query', + params: { repo: '@myproduct', query: 'login', service: 'app/backend' }, + spy: () => groupSpyQuery, + }, + { + method: 'context', + params: { repo: '@myproduct', target: 'UserService.login', service: 'app/backend' }, + spy: () => groupSpyContext, + }, + ])( + '$method with repo "@myproduct" routes to GroupService and forwards service', + async ({ method, params, spy }) => { + const backend = new LocalBackend(); + await backend.callTool(method, params); + expect(spy()).toHaveBeenCalledWith( + expect.objectContaining({ name: 'myproduct', service: 'app/backend' }), + ); + const callArg = spy().mock.calls[0][0] as Record; + expect( + typeof callArg.repo === 'string' ? (callArg.repo as string).startsWith('@') : false, + ).toBe(false); + }, + ); + }); +}); diff --git a/gitnexus/test/unit/resources.test.ts b/gitnexus/test/unit/resources.test.ts index 6b203c969..ccd8461f1 100644 --- a/gitnexus/test/unit/resources.test.ts +++ b/gitnexus/test/unit/resources.test.ts @@ -12,6 +12,7 @@ import { describe, it, expect, vi } from 'vitest'; import { getResourceDefinitions, getResourceTemplates, + parseResourceUri, readResource, } from '../../src/mcp/resources.js'; @@ -36,6 +37,12 @@ function createMockBackend(overrides: Partial> = {}): any { queryProcessDetail: vi .fn() .mockResolvedValue(overrides.processDetail ?? { error: 'Not found' }), + readGroupContractsResource: vi + .fn() + .mockResolvedValue(overrides.groupContractsBody ?? 'contracts: []\n'), + readGroupStatusResource: vi + .fn() + .mockResolvedValue(overrides.groupStatusBody ?? 'group: mock\n'), ...overrides, }; } @@ -73,12 +80,12 @@ describe('getResourceDefinitions', () => { }); describe('getResourceTemplates', () => { - it('returns 6 dynamic templates', () => { + it('returns 8 dynamic templates', () => { const templates = getResourceTemplates(); - expect(templates).toHaveLength(6); + expect(templates).toHaveLength(8); }); - it('includes context, clusters, processes, schema, cluster detail, process detail', () => { + it('includes context, clusters, processes, schema, cluster detail, process detail, group contracts/status', () => { const templates = getResourceTemplates(); const uris = templates.map((t) => t.uriTemplate); expect(uris).toContain('gitnexus://repo/{name}/context'); @@ -87,6 +94,8 @@ describe('getResourceTemplates', () => { expect(uris).toContain('gitnexus://repo/{name}/schema'); expect(uris).toContain('gitnexus://repo/{name}/cluster/{clusterName}'); expect(uris).toContain('gitnexus://repo/{name}/process/{processName}'); + expect(uris).toContain('gitnexus://group/{name}/contracts'); + expect(uris).toContain('gitnexus://group/{name}/status'); }); it('each template has uriTemplate, name, description, mimeType', () => { @@ -99,6 +108,61 @@ describe('getResourceTemplates', () => { }); }); +describe('parseResourceUri', () => { + it('parses group contracts without query', () => { + const p = parseResourceUri('gitnexus://group/acme/contracts'); + expect(p).toEqual({ + kind: 'group', + groupName: 'acme', + resourceType: 'contracts', + contractsFilter: {}, + }); + }); + + it('parses nested group name and contracts query params', () => { + const p = parseResourceUri( + 'gitnexus://group/acme/billing/contracts?type=http&repo=app%2Fapi&unmatchedOnly=true', + ); + expect(p.kind).toBe('group'); + if (p.kind !== 'group' || p.resourceType !== 'contracts') throw new Error('unexpected'); + expect(p.groupName).toBe('acme/billing'); + expect(p.contractsFilter).toEqual({ + type: 'http', + repo: 'app/api', + unmatchedOnly: true, + }); + }); + + it('coerces unmatchedOnly false from string', () => { + const p = parseResourceUri('gitnexus://group/g1/contracts?unmatchedOnly=false'); + expect(p.kind).toBe('group'); + if (p.kind !== 'group' || p.resourceType !== 'contracts') throw new Error('unexpected'); + expect(p.contractsFilter.unmatchedOnly).toBe(false); + }); + + it('parses group status', () => { + const p = parseResourceUri('gitnexus://group/my/product/status'); + expect(p).toEqual({ + kind: 'group', + groupName: 'my/product', + resourceType: 'status', + }); + }); + + it('round-trips repo URI like legacy regex', () => { + const p = parseResourceUri('gitnexus://repo/my%20project/schema'); + expect(p).toEqual({ + kind: 'repo', + repoName: 'my project', + resourceType: 'schema', + }); + }); + + it('rejects unknown group resource tail', () => { + expect(() => parseResourceUri('gitnexus://group/foo/bar')).toThrow('Unknown group resource'); + }); +}); + // ─── readResource URI parsing ──────────────────────────────────────── describe('readResource', () => { @@ -149,6 +213,22 @@ describe('readResource', () => { expect(result).toContain('No repositories indexed'); }); + it('routes group contracts resource through backend', async () => { + const backend = createMockBackend(); + const uri = 'gitnexus://group/g1/contracts?type=http&unmatchedOnly=true'; + await readResource(uri, backend); + expect(backend.readGroupContractsResource).toHaveBeenCalledWith('g1', { + type: 'http', + unmatchedOnly: true, + }); + }); + + it('routes group status resource through backend', async () => { + const backend = createMockBackend(); + await readResource('gitnexus://group/acme/status', backend); + expect(backend.readGroupStatusResource).toHaveBeenCalledWith('acme'); + }); + it('routes gitnexus://repo/{name}/context correctly', async () => { const backend = createMockBackend({ context: { diff --git a/gitnexus/test/unit/tools.test.ts b/gitnexus/test/unit/tools.test.ts index 4274716a7..231f55e3c 100644 --- a/gitnexus/test/unit/tools.test.ts +++ b/gitnexus/test/unit/tools.test.ts @@ -2,7 +2,7 @@ * Unit Tests: MCP Tool Definitions * * Tests: GITNEXUS_TOOLS from tools.ts - * - All 16 tools are defined (per-repo + group_*) + * - All 13 tools are defined (per-repo + group_list/group_sync) * - Each tool has valid name, description, inputSchema * - Required fields are correct * - Optional repo parameter is present on tools that need it @@ -10,17 +10,11 @@ import { describe, it, expect } from 'vitest'; import { GITNEXUS_TOOLS } from '../../src/mcp/tools.js'; -const GROUP_TOOLS = new Set([ - 'group_list', - 'group_sync', - 'group_contracts', - 'group_query', - 'group_status', -]); +const GROUP_TOOLS = new Set(['group_list', 'group_sync']); describe('GITNEXUS_TOOLS', () => { - it('exports all tools (7 base + 3 route/tool/shape + 1 api_impact + 5 group)', () => { - expect(GITNEXUS_TOOLS).toHaveLength(16); + it('exports all tools (7 base + 3 route/tool/shape + 1 api_impact + 2 group)', () => { + expect(GITNEXUS_TOOLS).toHaveLength(13); }); it('contains all expected tool names', () => { @@ -101,23 +95,29 @@ describe('GITNEXUS_TOOLS', () => { } }); - it('group_contracts has optional repo filter', () => { - const groupContracts = GITNEXUS_TOOLS.find((t) => t.name === 'group_contracts')!; - expect(groupContracts.inputSchema.properties).toHaveProperty('repo'); - expect(groupContracts.inputSchema.required).not.toContain('repo'); - }); - it('group tools without backend repo param omit repo property', () => { - for (const name of ['group_list', 'group_status', 'group_sync', 'group_query'] as const) { + for (const name of ['group_list', 'group_sync'] as const) { const tool = GITNEXUS_TOOLS.find((t) => t.name === name)!; expect(tool.inputSchema.properties).not.toHaveProperty('repo'); } }); - it('group_query requires name and query', () => { - const groupQuery = GITNEXUS_TOOLS.find((t) => t.name === 'group_query')!; - expect(groupQuery.inputSchema.required).toContain('name'); - expect(groupQuery.inputSchema.required).toContain('query'); + it('impact, query, and context expose optional service with minLength', () => { + for (const n of ['impact', 'query', 'context'] as const) { + const tool = GITNEXUS_TOOLS.find((t) => t.name === n)!; + const svc = tool.inputSchema.properties.service; + expect(svc, n).toBeDefined(); + expect(svc!.minLength).toBe(1); + } + }); + + it('impact schema bounds match cross-impact validation ranges', () => { + const impact = GITNEXUS_TOOLS.find((t) => t.name === 'impact')!; + expect(impact.inputSchema.properties.maxDepth.minimum).toBe(1); + expect(impact.inputSchema.properties.maxDepth.maximum).toBe(32); + expect(impact.inputSchema.properties.minConfidence.minimum).toBe(0); + expect(impact.inputSchema.properties.minConfidence.maximum).toBe(1); + expect(impact.inputSchema.properties.timeoutMs.maximum).toBe(3600000); }); it('detect_changes scope has correct enum values', () => {