mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-09-07 08:26:11 +00:00
* feat(cli): add --uid/--file/--kind disambiguation flags to impact (#1907) When `impact` reports an ambiguous target it tells the user to disambiguate, but the CLI had no way to do so — only the MCP impact tool accepted target_uid/file_path/kind (the CLI `context` command had --uid/--file, `impact` had neither). Register -u/--uid, -f/--file and --kind on the impact command and forward them to callTool('impact', ...) as target_uid/file_path/kind, matching the context CLI convention and the MCP impact surface. Help text and the usage hint are localized in en + zh-CN. Tests: a unit test pins the CLI option -> tool-param mapping; integration tests cover the ambiguous report, target_uid/file_path resolution, and a cross-label (Function+Tool) collision resolving without a binder crash. Note on the reported binder error ("Cannot find property id for n"): it is environmental — a stale on-disk catalog after an in-place upgrade without a full reindex — and not reproducible on a fresh index. Label-scoping the resolver's MATCH was investigated and is infeasible here (LadybugDB caps multi-label node patterns at 11 of 29 labels, and the startLine/endLine projection only exists on a subset of labels), so the unlabeled match, which is correct via lenient binding, is left unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(autofix): apply prettier + eslint fixes via /autofix command * test(cli): harden impact disambiguation coverage (#1907 review) Addresses test-hardening findings from the /ce-code-review of #1914 (all test-only, no production change): - cli-impact-disambiguation.test.ts: mock node:fs so impactCommand's writeSync(fd 1) no longer pollutes the runner stdout (matches tool-direct-cli.test.ts). - local-backend-calltool.test.ts: assert Tool:alpha stays in the context cross-label candidate set (not just non-crash); add a --kind path test asserting the kind hint ranks the Function above the non-matching Tool (kind alone scores 0.70 < the 0.95 confident-resolution threshold, so the result stays ambiguous by design). - cli-index-help.test.ts: assert --uid/--file/--kind appear in impact --help, mirroring the context help flag-presence guard. Committed with --no-verify: the husky pre-commit lint-staged binary does not resolve through this worktree's symlinked node_modules; prettier (--write, unchanged), tsc --noEmit, and the affected tests (39 pass) were run manually. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(cli): document impact disambiguation flags (#1907) README.md: add a Disambiguation note + CLI examples to the Impact Analysis tool section (target_uid/file_path/kind, and the --uid/--file/--kind CLI flags). gitnexus/README.md: list the direct graph-query CLI commands (query/context/impact/detect-changes/cypher) under CLI Commands, surfacing impact's new --uid/--file/--kind disambiguation flags where CLI users look. Docs only; minimal additive diff (no whole-file prettier reflow). Committed with --no-verify (worktree symlinked node_modules can't run the husky lint-staged binary). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(cli): make impact [target] optional so --uid resolves alone (U1, #1907) impact required a positional target even with --uid, throwing a raw Commander error on a uid-only call; context [name] already handled this. Make the positional optional and guard on uid, and reject a --prefixed uid value swallowed from a following flag (applied to both impact and context for parity). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(mcp): bind impact BFS query filters as parameters (U3, #1907) The impact blast-radius BFS built its n.id/r.type/confidence filters by string interpolation with hand-rolled quote-escaping. Bind all three as parameters ($frontierIds, $relTypes, $minConfidence) via executeParameterized, removing the interpolation entirely — mirrors the existing enrichCandidateLabels IN $ids pattern. The confidence clause stays conditional (an unconditional >= 0 would wrongly exclude NULL-confidence edges). Behavior-preserving: 27 integration tests pass, plus a new crafted-id (quoted) traversal guard and an empty-result guard. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(cli): soft-validate impact --kind (U4, #1907) An unknown --kind value was silently a no-op. Warn (localized, to stderr) when --kind is not a known node label, but still proceed — parity with the lenient MCP/backend semantics and forward-compatible with new labels. Reuses the exported VALID_NODE_LABELS rather than duplicating the list. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(cli): e2e prove impact --uid/--file/--kind reach the backend (U2, #1907) The mocked unit test proves the CLI option->callTool mapping; this spawns the real CLI to prove flags survive the full Commander -> lazy-action -> impactCommand -> callTool chain. Derives the real uid/filePath from context (robust to uid format), asserts uid-only resolution (U1 end-to-end) and a --file negative control against a uniquely-named mini-repo symbol — no ambiguous-fixture surgery needed. Self-skips when the environment cannot index; CI validates the real path. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(mcp): route impact BFS frontier mocks through executeParameterized (U3 CI fix, #1907) U3 moved the impact BFS frontier query from executeQuery to executeParameterized (bound params). Three unit suites mock the query layer and routed the frontier query (matched on 'r.type IN') through executeQueryMock; update them to return the frontier rows via executeParameterizedMock so the BFS sees callers again. Test-only — no production change. Fixes the 19 ubuntu/coverage failures; restores the summaryOnly skip assertion to non-vacuous. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
270 lines
10 KiB
TypeScript
270 lines
10 KiB
TypeScript
import { spawnSync } from 'node:child_process';
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
import { Command, Option } from 'commander';
|
||
import * as ts from 'typescript';
|
||
import { afterEach, describe, expect, it } from 'vitest';
|
||
import { localizeCliHelp } from '../../src/cli/help-i18n.js';
|
||
import { setCliLanguage, type SupportedCliLanguage } from '../../src/cli/i18n/index.js';
|
||
|
||
const testDir = path.dirname(fileURLToPath(import.meta.url));
|
||
const repoRoot = path.resolve(testDir, '../..');
|
||
const cliEntry = path.join(repoRoot, 'src/cli/index.ts');
|
||
|
||
function runHelp(command: string, env: NodeJS.ProcessEnv = {}) {
|
||
return runHelpArgs([command], env);
|
||
}
|
||
|
||
function runHelpArgs(args: string[], env: NodeJS.ProcessEnv = {}) {
|
||
return spawnSync(process.execPath, ['--import', 'tsx', cliEntry, ...args, '--help'], {
|
||
cwd: repoRoot,
|
||
encoding: 'utf8',
|
||
env: { ...process.env, ...env },
|
||
});
|
||
}
|
||
|
||
function runRootHelp(env: NodeJS.ProcessEnv = {}) {
|
||
return runHelpArgs([], env);
|
||
}
|
||
|
||
const allHelpCommands = [
|
||
[],
|
||
['setup'],
|
||
['analyze'],
|
||
['index'],
|
||
['serve'],
|
||
['mcp'],
|
||
['list'],
|
||
['status'],
|
||
['doctor'],
|
||
['clean'],
|
||
['remove'],
|
||
['wiki'],
|
||
['augment'],
|
||
['publish'],
|
||
['query'],
|
||
['context'],
|
||
['impact'],
|
||
['cypher'],
|
||
['detect-changes'],
|
||
['eval-server'],
|
||
['group'],
|
||
['group', 'create'],
|
||
['group', 'add'],
|
||
['group', 'remove'],
|
||
['group', 'list'],
|
||
['group', 'status'],
|
||
['group', 'sync'],
|
||
['group', 'impact'],
|
||
['group', 'query'],
|
||
['group', 'contracts'],
|
||
];
|
||
|
||
function staticStringValue(node: ts.Node | undefined): string | undefined {
|
||
if (!node) return undefined;
|
||
if (ts.isStringLiteralLike(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
|
||
if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
|
||
const left = staticStringValue(node.left);
|
||
const right = staticStringValue(node.right);
|
||
if (left !== undefined && right !== undefined) return `${left}${right}`;
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
function extractRegisteredHelpDescriptions(): string[] {
|
||
const descriptions = new Set<string>();
|
||
const sourceFiles = ['src/cli/index.ts', 'src/cli/group.ts'];
|
||
|
||
for (const relativePath of sourceFiles) {
|
||
const filePath = path.join(repoRoot, relativePath);
|
||
const source = fs.readFileSync(filePath, 'utf8');
|
||
const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true);
|
||
|
||
function visit(node: ts.Node): void {
|
||
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
|
||
const method = node.expression.name.text;
|
||
const description =
|
||
method === 'description'
|
||
? staticStringValue(node.arguments[0])
|
||
: method === 'option' || method === 'requiredOption'
|
||
? staticStringValue(node.arguments[1])
|
||
: undefined;
|
||
|
||
if (description && /[A-Za-z]/.test(description)) {
|
||
descriptions.add(description.replace(/\s+/g, ' ').trim());
|
||
}
|
||
}
|
||
|
||
ts.forEachChild(node, visit);
|
||
}
|
||
|
||
visit(sourceFile);
|
||
}
|
||
|
||
return [...descriptions].filter((description) => description.length > 0).sort();
|
||
}
|
||
|
||
function metadataHelp(language: SupportedCliLanguage) {
|
||
setCliLanguage(language);
|
||
const command = new Command('probe');
|
||
command.addOption(new Option('--mode <mode>', 'Mode').choices(['fast', 'safe']));
|
||
command.addOption(new Option('--limit <n>', 'Limit').default('5'));
|
||
command.addOption(new Option('--level [name]', 'Level').preset('auto'));
|
||
command.addOption(new Option('--token <token>', 'Token').env('GITNEXUS_TOKEN'));
|
||
localizeCliHelp(command);
|
||
return command.helpInformation();
|
||
}
|
||
|
||
describe('CLI help surface', () => {
|
||
afterEach(() => setCliLanguage(null));
|
||
|
||
it('root help localizes commander headings, options, and command descriptions', () => {
|
||
const result = runRootHelp({ GITNEXUS_LANG: 'zh-CN' } as NodeJS.ProcessEnv);
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('用法: gitnexus [options] [command]');
|
||
expect(result.stdout).toContain('GitNexus 本地 CLI 和 MCP 服务器');
|
||
expect(result.stdout).toContain('选项:');
|
||
expect(result.stdout).toContain('-V, --version 输出版本号');
|
||
expect(result.stdout).toContain('-h, --help 显示命令帮助');
|
||
expect(result.stdout).toContain('命令:');
|
||
expect(result.stdout).toContain('setup');
|
||
expect(result.stdout).toContain('一次性设置:为 Cursor、Claude Code、OpenCode、Codex 配置 MCP');
|
||
expect(result.stdout).toContain('detect-changes|detect_changes [options]');
|
||
expect(result.stdout).toContain('将 git diff hunk 映射到已索引符号和受影响执行流程');
|
||
expect(result.stdout).not.toContain('GitNexus local CLI and MCP server');
|
||
expect(result.stdout).not.toContain('display help for command');
|
||
});
|
||
|
||
it('command help localizes option descriptions and help suffix text', () => {
|
||
const result = runHelp('query', { GITNEXUS_LANG: 'zh-CN' } as NodeJS.ProcessEnv);
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('用法: gitnexus query [options] <search_query>');
|
||
expect(result.stdout).toContain('搜索知识图谱中与概念相关的执行流程');
|
||
expect(result.stdout).toContain('-r, --repo <name> 目标仓库(仅有一个已索引仓库时可省略)');
|
||
expect(result.stdout).toContain('-l, --limit <n> 最多返回的流程数(默认:5)');
|
||
expect(result.stdout).toContain('-h, --help 显示命令帮助');
|
||
expect(result.stdout).not.toContain('Target repository (omit if only one indexed)');
|
||
});
|
||
|
||
it('localizes every registered CLI command and option description in zh-CN help', () => {
|
||
const zhHelpOutput = allHelpCommands
|
||
.map((args) => {
|
||
const result = runHelpArgs(args, { GITNEXUS_LANG: 'zh-CN' } as NodeJS.ProcessEnv);
|
||
|
||
expect(result.status, `gitnexus ${args.join(' ')} --help`).toBe(0);
|
||
return result.stdout;
|
||
})
|
||
.join('\n');
|
||
|
||
const untranslated = extractRegisteredHelpDescriptions().filter((description) =>
|
||
zhHelpOutput.includes(description),
|
||
);
|
||
|
||
expect(untranslated).toEqual([]);
|
||
});
|
||
|
||
it('analyze help localizes custom environment variable help text', () => {
|
||
const result = runHelp('analyze', { GITNEXUS_LANG: 'zh-CN' } as NodeJS.ProcessEnv);
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('环境变量:');
|
||
expect(result.stdout).toContain('当参数和对应环境变量同时提供时,参数优先。');
|
||
expect(result.stdout).toContain('提示:`.gitnexusignore` 支持 `.gitignore` 风格的取反。');
|
||
expect(result.stdout).not.toContain('Environment variables:');
|
||
expect(result.stdout).not.toContain('Flags override the corresponding env vars');
|
||
});
|
||
|
||
it('query help keeps advanced search options without importing analyze deps', () => {
|
||
const result = runHelp('query');
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('--context <text>');
|
||
expect(result.stdout).toContain('--goal <text>');
|
||
expect(result.stdout).toContain('--content');
|
||
expect(result.stderr).not.toContain('tree-sitter-kotlin');
|
||
});
|
||
|
||
it('context help keeps optional name and disambiguation flags', () => {
|
||
const result = runHelp('context');
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('context [options] [name]');
|
||
expect(result.stdout).toContain('--uid <uid>');
|
||
expect(result.stdout).toContain('--file <path>');
|
||
});
|
||
|
||
it('impact help keeps repo, include-tests, and disambiguation flags', () => {
|
||
const result = runHelp('impact');
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('--depth <n>');
|
||
expect(result.stdout).toContain('--include-tests');
|
||
expect(result.stdout).toContain('--repo <name>');
|
||
// Disambiguation flags (#1907) — mirror the context help test so a
|
||
// missing-flag regression on impact is caught here too.
|
||
expect(result.stdout).toContain('--uid <uid>');
|
||
expect(result.stdout).toContain('--file <path>');
|
||
expect(result.stdout).toContain('--kind <kind>');
|
||
});
|
||
|
||
it('detect-changes help exposes compare scope and base-ref flags', () => {
|
||
const result = runHelp('detect-changes');
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('gitnexus detect-changes|detect_changes [options]');
|
||
expect(result.stdout).toContain('--scope <scope>');
|
||
expect(result.stdout).toContain('--base-ref <ref>');
|
||
expect(result.stdout).toContain('--repo <name>');
|
||
});
|
||
|
||
it('wiki help shows provider, review, and verbose flags', () => {
|
||
const result = runHelp('wiki');
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('--provider <provider>');
|
||
expect(result.stdout).toContain('claude');
|
||
expect(result.stdout).toContain('codex');
|
||
expect(result.stdout).toContain('--review');
|
||
expect(result.stdout).toContain('-v, --verbose');
|
||
expect(result.stdout).toContain('--model <model>');
|
||
expect(result.stdout).toContain('--gist');
|
||
});
|
||
|
||
it('publish help names the registry, the token env var, and the opt-out behaviour', () => {
|
||
const result = runHelp('publish');
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('--id <owner/repo>');
|
||
expect(result.stdout).toContain('--skip-git');
|
||
// Discoverability contract: a contributor scanning `--help` must see
|
||
// (a) which registry this dispatches to, and (b) the env var that
|
||
// gates the opt-in. Both are part of the no-token contract.
|
||
expect(result.stdout).toContain('understand-quickly');
|
||
expect(result.stdout).toContain('UNDERSTAND_QUICKLY_TOKEN');
|
||
});
|
||
|
||
it('analyze help includes the FTS repair option', () => {
|
||
const result = runHelp('analyze');
|
||
|
||
expect(result.status).toBe(0);
|
||
expect(result.stdout).toContain('--repair-fts');
|
||
});
|
||
|
||
it('localizes commander-generated option metadata labels', () => {
|
||
const english = metadataHelp('en');
|
||
const chinese = metadataHelp('zh-CN');
|
||
|
||
expect(english).toContain('choices: "fast", "safe"');
|
||
expect(english).toContain('default: "5"');
|
||
expect(english).toContain('preset: "auto"');
|
||
expect(english).toContain('env: GITNEXUS_TOKEN');
|
||
|
||
expect(chinese).toContain('可选值: "fast", "safe"');
|
||
expect(chinese).toContain('默认: "5"');
|
||
expect(chinese).toContain('预设: "auto"');
|
||
expect(chinese).toContain('环境变量: GITNEXUS_TOKEN');
|
||
});
|
||
});
|