diff --git a/docs/cli-reference.md b/docs/cli-reference.md index a387b7241..5c6e06c3d 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -54,7 +54,7 @@ Watch mode accepts `--debounce`, `--workers`, `--worker-timeout`, `--max-file-size`, `--max-processes`, `--max-process-branching`, `--max-process-trace-depth`, `--max-entry-point-candidates`, `--branch`, `--pdg`, `--skip-fts`, `--name`, `--allow-duplicate-name`, and `--verbose`. Explicit one-shot options such as `--force`, `--repair-fts`, -embedding flags, `--skills`, `--self-commit`, `--index-only`, and `--skip-git` +embedding flags, `--skills`, `--context-file`, `--self-commit`, `--index-only`, and `--skip-git` are rejected. Unsupported defaults from `.gitnexusrc` are ignored with a warning rather than making an otherwise valid repository unwatchable. @@ -78,6 +78,21 @@ The token may be set in the shell, `.env.local`, or `.env` in the working direct ## All analyze flags +`--context-file ` replaces the default root `AGENTS.md` and `CLAUDE.md` +destinations with one repository-relative file, leaving the root files unchanged. +Missing parent directories are created; paths outside the repository or through +symlinked components are rejected. Existing prompt text outside the GitNexus block +is preserved. Even when the index is already up to date, a newly selected missing +file or prompt file without a block receives one; existing generated blocks keep +their community-skill rows during the surgical default-branch refresh. + +`--skip-agents-md` suppresses custom-target updates too. `--index-only` suppresses +all context and skill injection. `--no-stats` omits volatile counts when generating +the selected target; `--self-commit` applies only to the selected target and does +not include pre-existing user edits. This option is CLI-only, is not a +`.gitnexusrc` key, and cannot be combined with `--watch`. Pinned non-primary branch +indexes do not write context files. + ```bash gitnexus analyze --force # Full graph + FTS rebuild (reuses unchanged parser output) gitnexus analyze --no-parse-cache # Full rebuild that re-parses every source file @@ -87,6 +102,7 @@ gitnexus analyze --skills # Generate repo-specific skill files from detec gitnexus analyze --skip-embeddings # Skip embedding generation (faster) gitnexus analyze --embeddings [limit] # Enable embedding generation (slower, better search) gitnexus analyze --skip-agents-md # Preserve custom AGENTS.md/CLAUDE.md gitnexus section edits +gitnexus analyze --context-file .claude/CLAUDE.md # Use one repo-relative context file instead of both root files gitnexus analyze --skip-skills # Skip installing standard skill files under .claude/skills/ and .agents/skills/ gitnexus analyze --skip-git # Index folders that are not Git repositories gitnexus analyze --default-branch develop # Branch used in the generated regression-compare example (base_ref) diff --git a/gitnexus/README.md b/gitnexus/README.md index 373b64e35..5e6eee539 100644 --- a/gitnexus/README.md +++ b/gitnexus/README.md @@ -275,6 +275,7 @@ gitnexus embeddings install # Fetch the optional local embedding stack on d gitnexus analyze --skills # Generate repo-specific skill files from detected communities gitnexus analyze --skip-agents-md # Preserve custom AGENTS.md/CLAUDE.md gitnexus section edits (does not skip standard skills; use --skip-skills; community --skills files are unaffected) gitnexus analyze --skip-skills # Skip installing standard .claude/skills/gitnexus-* skill files +gitnexus analyze --context-file .claude/CLAUDE.md # Generate one context target instead of both root files gitnexus analyze --skip-git # Index folders that are not Git repositories gitnexus analyze --workers # Parse worker pool size (>=1; default: cores-1, capped at 16) gitnexus analyze --max-processes # Process-detection process cap (replaces dynamic max(20, round(symbols/10))) @@ -337,7 +338,7 @@ Watch mode accepts `--debounce`, `--workers`, `--worker-timeout`, `--max-process-trace-depth`, `--max-entry-point-candidates`, `--branch`, `--pdg`, `--name`, `--allow-duplicate-name`, and `--verbose`. Explicit one-shot options such as `--force`, `--repair-fts`, embedding flags, `--skills`, `--default-branch`, `--skip-agents-md`, -`--skip-skills`, `--no-stats`, `--self-commit`, `--index-only`, and `--skip-git` +`--skip-skills`, `--context-file`, `--no-stats`, `--self-commit`, `--index-only`, and `--skip-git` are rejected. Unsupported defaults from `.gitnexusrc` are ignored with a warning. POSIX requests clone-first copy-and-swap publication when the live index has no diff --git a/gitnexus/src/cli/ai-context.ts b/gitnexus/src/cli/ai-context.ts index 7440829b5..df9eb2cdb 100644 --- a/gitnexus/src/cli/ai-context.ts +++ b/gitnexus/src/cli/ai-context.ts @@ -15,6 +15,7 @@ import { type GeneratedSkillInfo } from './generated-skill.js'; import { STANDARD_SKILL_CATALOG } from './standard-skills.js'; import { isEnoent } from './editor-targets.js'; import { logger } from '../core/logger.js'; +import { assertContextFileTargetSafe, resolveContextFileTarget } from './context-file-target.js'; // ESM equivalent of __dirname const __filename = fileURLToPath(import.meta.url); @@ -31,6 +32,7 @@ interface RepoStats { export interface AIContextOptions { skipAgentsMd?: boolean; + contextFile?: string; noStats?: boolean; skipSkills?: boolean; /** @@ -647,6 +649,24 @@ Use GitNexus tools to accomplish this task. }; } +/** Whether a selected target needs its initial GitNexus block on an up-to-date run. */ +export async function contextFileNeedsGeneration( + repoPath: string, + contextFile: string, +): Promise { + const { relative, absolute } = resolveContextFileTarget(repoPath, contextFile); + await assertContextFileTargetSafe(repoPath, relative); + let content: string; + try { + content = await fs.readFile(absolute, 'utf-8'); + } catch (err) { + if (isEnoent(err)) return true; + throw err; + } + const start = findSectionMarkerIndex(content, GITNEXUS_START_MARKER); + return start === -1 || findSectionMarkerIndex(content, GITNEXUS_END_MARKER, start) === -1; +} + /** * Generate AI context files after indexing */ @@ -701,27 +721,22 @@ export async function generateAIContextFiles( const createdFiles: string[] = []; if (!options?.skipAgentsMd) { - // Create AGENTS.md (standard for Cursor, Windsurf, OpenCode, Cline, etc.) - const agentsPath = path.join(repoPath, 'AGENTS.md'); - const agentsResult = await upsertGitNexusSection( - agentsPath, - content, - projectName, - stats, - options?.noStats, - ); - createdFiles.push(`AGENTS.md (${agentsResult})`); - - // Create CLAUDE.md (for Claude Code) - const claudePath = path.join(repoPath, 'CLAUDE.md'); - const claudeResult = await upsertGitNexusSection( - claudePath, - content, - projectName, - stats, - options?.noStats, - ); - createdFiles.push(`CLAUDE.md (${claudeResult})`); + const targets = options?.contextFile ? [options.contextFile] : ['AGENTS.md', 'CLAUDE.md']; + for (const target of targets) { + const { relative, absolute } = resolveContextFileTarget(repoPath, target); + if (options?.contextFile) { + await assertContextFileTargetSafe(repoPath, relative); + await fs.mkdir(path.dirname(absolute), { recursive: true }); + } + const result = await upsertGitNexusSection( + absolute, + content, + projectName, + stats, + options?.noStats, + ); + createdFiles.push(`${relative} (${result})`); + } } else { createdFiles.push('AGENTS.md (skipped via --skip-agents-md)'); createdFiles.push('CLAUDE.md (skipped via --skip-agents-md)'); @@ -772,7 +787,7 @@ export async function generateAIContextFiles( /** * Refresh the regression-review target inside the GitNexus block of an - * already-generated AGENTS.md / CLAUDE.md, in place (#1996 P2, #3509). + * already-generated context file, in place (#1996 P2, #3509). * * The `alreadyUpToDate` analyze fast path returns before the normal * {@link generateAIContextFiles} call, so a changed `.gitnexusrc` defaultBranch @@ -790,12 +805,13 @@ export async function generateAIContextFiles( export async function refreshBaseRefLine( repoPath: string, defaultBranch: string, - options?: { skipAgentsMd?: boolean }, + options?: { skipAgentsMd?: boolean; contextFile?: string }, ): Promise<{ files: string[] }> { if (options?.skipAgentsMd) return { files: [] }; const updated: string[] = []; - for (const name of ['AGENTS.md', 'CLAUDE.md']) { - const filePath = path.join(repoPath, name); + for (const target of options?.contextFile ? [options.contextFile] : ['AGENTS.md', 'CLAUDE.md']) { + const { relative: name, absolute: filePath } = resolveContextFileTarget(repoPath, target); + if (options?.contextFile) await assertContextFileTargetSafe(repoPath, name); if (!(await fileExists(filePath))) continue; let content: string; try { diff --git a/gitnexus/src/cli/analyze-options.ts b/gitnexus/src/cli/analyze-options.ts index d548484e0..23d8db916 100644 --- a/gitnexus/src/cli/analyze-options.ts +++ b/gitnexus/src/cli/analyze-options.ts @@ -42,6 +42,8 @@ export interface AnalyzeOptions { verbose?: boolean; /** Skip AGENTS.md and CLAUDE.md gitnexus block updates. */ skipAgentsMd?: boolean; + /** Repo-relative replacement for the default AGENTS.md and CLAUDE.md context targets. */ + contextFile?: string; /** * Build the control-flow-graph / PDG substrate (#2081 M1). Opt-in; off by * default. Threaded to both the worker (CFG build) and scope-resolution @@ -61,9 +63,9 @@ export interface AnalyzeOptions { */ stats?: boolean; /** - * Opt-in auto-commit of any AGENTS.md/CLAUDE.md changes this `analyze` run - * makes. Scoped to only those two files (never `git add -A`); no-ops - * silently if neither exists, neither changed, or the commit step itself + * Opt-in auto-commit of generated context changes this `analyze` run + * makes. Scoped to only the selected context target(s) (never `git add -A`); no-ops + * silently if no selected targets exist, none changed, or the commit step itself * fails (e.g. no git identity configured). See #2639. */ selfCommit?: boolean; diff --git a/gitnexus/src/cli/analyze-watch.ts b/gitnexus/src/cli/analyze-watch.ts index 88080bd06..67696f863 100644 --- a/gitnexus/src/cli/analyze-watch.ts +++ b/gitnexus/src/cli/analyze-watch.ts @@ -116,6 +116,7 @@ export async function resolveWatchOptions( ['--skills', cli.skills], ['--default-branch', cli.defaultBranch], ['--skip-agents-md', cli.skipAgentsMd], + ['--context-file', cli.contextFile], ['--skip-skills', cli.skipSkills], ['--no-stats', cli.stats === false], ['--self-commit', cli.selfCommit], diff --git a/gitnexus/src/cli/analyze.ts b/gitnexus/src/cli/analyze.ts index 483b889de..3ce5c042a 100644 --- a/gitnexus/src/cli/analyze.ts +++ b/gitnexus/src/cli/analyze.ts @@ -43,6 +43,7 @@ import { snapshotSelfCommitSafety, } from '../storage/git.js'; import { IndexLockTimeoutError, isIndexLockGuardTimeout } from '../storage/index-lock.js'; +import { assertContextFileTargetSafe, resolveContextFileTarget } from './context-file-target.js'; import { loadAnalyzeConfig, mergeAnalyzeOptions, @@ -881,10 +882,10 @@ export type { AnalyzeOptions }; * * The gated block does two things in sequence: (1) generates the community * skill files from `--skills`, and (2) re-runs `generateAIContextFiles` so - * AGENTS.md/CLAUDE.md can reference the freshly written skills. Both are + * the selected context files can reference the freshly written skills. Both are * suppressed together — `--index-only` drops the entire step, not just the * community-skill write. Name retained for the test contract; see call site - * in `analyzeCommand` for the AGENTS.md/CLAUDE.md re-generation it also gates. + * in `analyzeCommand` for the context-file re-generation it also gates. * * Kept as a pure helper so the `--index-only --skills` contract is unit-tested * without booting the full analyze pipeline (#742 review). @@ -1002,6 +1003,20 @@ const analyzeCommandImpl = async ( ); } + let contextFile: string | undefined; + if (cliOptions?.contextFile !== undefined) { + try { + const target = resolveContextFileTarget(repoPath, cliOptions.contextFile); + await assertContextFileTargetSafe(repoPath, target.relative); + contextFile = target.relative; + } catch (err) { + cliError(` ${err instanceof Error ? err.message : String(err)}\n`); + process.exitCode = 1; + return; + } + } + const contextFiles = contextFile ? [contextFile] : ['AGENTS.md', 'CLAUDE.md']; + // Validate an explicit `--default-branch` up front so its errors are // attributed to the flag (with a CLI-specific recovery hint) rather than to // `.gitnexusrc`, which the user may not even have (#1996 tri-review). @@ -1554,6 +1569,7 @@ const analyzeCommandImpl = async ( verbose: options.verbose, skipGit: options.skipGit, skipAgentsMd, + contextFile, skipSkills, // CFG/PDG substrate opt-in (#2081 M1) — threaded to both sinks downstream. pdg: options.pdg === true, @@ -1607,15 +1623,13 @@ const analyzeCommandImpl = async ( const bootstrapArgs: [] | [AnalyzerRunnerIdentity] = runnerIdentityAtBootstrap ? [runnerIdentityAtBootstrap] : []; - // #2639 review round 2: snapshot which of AGENTS.md/CLAUDE.md are safe to + // #2639 review round 2: snapshot which selected context files are safe to // auto-commit BEFORE runFullAnalysis (and the --skills regeneration // further down) writes to them, so selfCommitContextFiles can tell a // pre-existing unstaged user edit apart from this run's stats refresh // and refuse to sweep the former into the latter's commit. const selfCommitSafety = - options.selfCommit === true - ? snapshotSelfCommitSafety(repoPath, ['AGENTS.md', 'CLAUDE.md']) - : undefined; + options.selfCommit === true ? snapshotSelfCommitSafety(repoPath, contextFiles) : undefined; const result = await runFullAnalysis(repoPath, runOptions, runCallbacks, ...bootstrapArgs); if (result.alreadyUpToDate) { @@ -1626,13 +1640,13 @@ const analyzeCommandImpl = async ( await assertAnalysisFinalized(repoPath, result.storagePath); // The fast path skips context regeneration, but a changed `.gitnexusrc` // defaultBranch / `--default-branch` must still take effect. Surgically - // refresh just the `base_ref` line in AGENTS.md/CLAUDE.md in place, + // refresh just the `base_ref` line in the selected context files in place, // preserving the rest of the block (incl. --skills community rows). No-op // when the value already matches, so a routine up-to-date run is silent // (#1996 tri-review P2). - // Only refresh the repo-root AGENTS.md/CLAUDE.md base_ref for the flat + // Only refresh the selected context files' base_ref for the flat // WORKSPACE index (#2106 R2, #2354). A pinned --branch sub-index's - // up-to-date analyze must not churn the committed AGENTS.md — this + // up-to-date analyze must not churn committed context files — this // mirrors the in-pipeline `if (!placement.branch)` gate around // generateAIContextFiles. let baseRefRefreshed: string[] = []; @@ -1640,7 +1654,7 @@ const analyzeCommandImpl = async ( try { const { refreshBaseRefLine } = await import('./ai-context.js'); baseRefRefreshed = ( - await refreshBaseRefLine(repoPath, resolvedDefaultBranch, { skipAgentsMd }) + await refreshBaseRefLine(repoPath, resolvedDefaultBranch, { skipAgentsMd, contextFile }) ).files; } catch { /* best-effort — never fail the fast path over a context refresh */ @@ -1666,10 +1680,10 @@ const analyzeCommandImpl = async ( ` Updated regression-review target to "${resolvedDefaultBranch}" in ${baseRefRefreshed.join(', ')}\n`, ); } - // #2639: opt-in self-commit of any AGENTS.md/CLAUDE.md churn from this + // #2639: opt-in self-commit of any selected context-file churn from this // fast path (e.g. a base_ref refresh above). Best-effort — never throws. if (options.selfCommit === true && selfCommitSafety) { - selfCommitContextFiles(repoPath, ['AGENTS.md', 'CLAUDE.md'], selfCommitSafety); + selfCommitContextFiles(repoPath, contextFiles, selfCommitSafety); } // Safe to return without process.exit(0) — the early-return path in // runFullAnalysis never opens LadybugDB, so no native handles prevent exit. @@ -1742,9 +1756,10 @@ const analyzeCommandImpl = async ( skillResult.skills, { skipAgentsMd, + contextFile, skipSkills, // Same resolved branch as the main run (#243) so the --skills - // re-generation of AGENTS.md/CLAUDE.md does not revert base_ref + // re-generation of the selected context files does not revert base_ref // to "main". defaultBranch: resolvedDefaultBranch, // Mirror runFullAnalysis `noStats` bridge (#1477) — same expression; @@ -1760,12 +1775,12 @@ const analyzeCommandImpl = async ( } } - // #2639: opt-in self-commit of any AGENTS.md/CLAUDE.md churn written by + // #2639: opt-in self-commit of any selected context-file churn written by // this run (the primary generateAIContextFiles call inside // runFullAnalysis, and/or the --skills regeneration above). Best-effort // — never throws, so a missing git identity etc. can't fail `analyze`. if (options.selfCommit === true && selfCommitSafety) { - selfCommitContextFiles(repoPath, ['AGENTS.md', 'CLAUDE.md'], selfCommitSafety); + selfCommitContextFiles(repoPath, contextFiles, selfCommitSafety); } const totalTime = ((Date.now() - t0) / 1000).toFixed(1); diff --git a/gitnexus/src/cli/context-file-target.ts b/gitnexus/src/cli/context-file-target.ts new file mode 100644 index 000000000..c2bc4ea96 --- /dev/null +++ b/gitnexus/src/cli/context-file-target.ts @@ -0,0 +1,49 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; + +export function resolveContextFileTarget( + repoPath: string, + contextFile: string, +): { relative: string; absolute: string } { + const normalized = contextFile.replace(/\\/g, '/'); + if ( + !normalized.trim() || + normalized !== normalized.trim() || + /[\x00-\x1f\x7f]/.test(normalized) || + path.isAbsolute(normalized) || + path.win32.isAbsolute(contextFile) || + /^[A-Za-z]:/.test(contextFile) + ) { + throw new Error('--context-file must be a repo-relative file path.'); + } + + const absolute = path.resolve(repoPath, normalized); + const relative = path.relative(repoPath, absolute); + if ( + !relative || + relative === '..' || + relative.startsWith(`..${path.sep}`) || + path.isAbsolute(relative) + ) { + throw new Error('--context-file must stay inside the repository.'); + } + return { relative: relative.replace(/\\/g, '/'), absolute }; +} + +export async function assertContextFileTargetSafe( + repoPath: string, + relative: string, +): Promise { + let current = repoPath; + for (const segment of relative.split('/')) { + current = path.join(current, segment); + try { + if ((await fs.lstat(current)).isSymbolicLink()) { + throw new Error('--context-file must not use a symlinked path.'); + } + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') break; + throw err; + } + } +} diff --git a/gitnexus/src/cli/help-i18n.ts b/gitnexus/src/cli/help-i18n.ts index d8543a62a..772bd1a86 100644 --- a/gitnexus/src/cli/help-i18n.ts +++ b/gitnexus/src/cli/help-i18n.ts @@ -60,6 +60,7 @@ const OPTION_DESCRIPTION_KEYS = { 'analyze|--drop-embeddings': 'help.option.analyze.dropEmbeddings', 'analyze|--skills': 'help.option.analyze.skills', 'analyze|--skip-agents-md': 'help.option.analyze.skipAgentsMd', + 'analyze|--context-file ': 'help.option.analyze.contextFile', 'analyze|--no-stats': 'help.option.analyze.noStats', 'analyze|--self-commit': 'help.option.analyze.selfCommit', 'analyze|--skip-skills': 'help.option.analyze.skipSkills', diff --git a/gitnexus/src/cli/i18n/en.ts b/gitnexus/src/cli/i18n/en.ts index 8cedc843f..3dc043a0d 100644 --- a/gitnexus/src/cli/i18n/en.ts +++ b/gitnexus/src/cli/i18n/en.ts @@ -284,14 +284,17 @@ export const en = { 'help.option.analyze.skills': 'Generate repo-specific skill files from detected communities (no-op when --index-only is also set).', 'help.option.analyze.skipAgentsMd': - 'Skip updating the gitnexus section in AGENTS.md and CLAUDE.md. Does not skip standard skills in .claude/skills or .agents/skills; use --skip-skills for those. Community skills from --skills are unaffected.', - 'help.option.analyze.noStats': 'Omit volatile file/symbol counts from AGENTS.md and CLAUDE.md', + 'Skip updating the gitnexus section in the selected context file(s), including --context-file. Does not skip standard skills in .claude/skills or .agents/skills; use --skip-skills for those. Community skills from --skills are unaffected.', + 'help.option.analyze.contextFile': + 'Write the GitNexus context block to one repo-relative file instead of root AGENTS.md and CLAUDE.md.', + 'help.option.analyze.noStats': + 'Omit volatile file/symbol counts from the selected context file(s)', 'help.option.analyze.selfCommit': - 'Auto-commit AGENTS.md/CLAUDE.md changes after analyze (opt-in, off by default). Scoped to only those two files (never `git add -A`); no-ops if neither exists, neither changed, or the repo has no git identity configured.', + 'Auto-commit generated context file changes after analyze (opt-in, off by default). Scoped to the selected context target(s) (never `git add -A`); no-ops if none exist, none changed, or the repo has no git identity configured.', 'help.option.analyze.skipSkills': 'Skip installing standard GitNexus skill files directly under .claude/skills/ and .agents/skills/. Does not suppress community skills from --skills (those use .claude/skills/gitnexus-area-*). Use --index-only to skip all AI-context file injection.', 'help.option.analyze.indexOnly': - 'Pure index mode: skip all file injection (AGENTS.md, CLAUDE.md, skills)', + 'Pure index mode: skip all file injection (default/custom context files and skills)', 'help.option.skipGit': 'Treat the provided path/cwd as the index root and skip parent git-root discovery', 'help.option.analyze.name': diff --git a/gitnexus/src/cli/i18n/zh-CN.ts b/gitnexus/src/cli/i18n/zh-CN.ts index f333188b7..a4a73dd9f 100644 --- a/gitnexus/src/cli/i18n/zh-CN.ts +++ b/gitnexus/src/cli/i18n/zh-CN.ts @@ -260,13 +260,15 @@ export const zhCN = { 'help.option.analyze.skills': '根据检测到的社区生成仓库专属 skill 文件(同时设置 --index-only 时无效)。', 'help.option.analyze.skipAgentsMd': - '跳过更新 AGENTS.md 和 CLAUDE.md 中的 gitnexus 区块。不会跳过 .claude/skills 或 .agents/skills 下的标准 skill;如需跳过那些请使用 --skip-skills。--skills 生成的社区 skill 不受影响。', - 'help.option.analyze.noStats': '从 AGENTS.md 和 CLAUDE.md 中省略易变的文件/符号计数', + '跳过更新选定上下文文件中的 gitnexus 区块(包括 --context-file 指定的文件)。不会跳过 .claude/skills 或 .agents/skills 下的标准 skill;如需跳过那些请使用 --skip-skills。--skills 生成的社区 skill 不受影响。', + 'help.option.analyze.contextFile': + '将 GitNexus 上下文区块写入一个仓库相对路径文件,而不是根目录的 AGENTS.md 和 CLAUDE.md。', + 'help.option.analyze.noStats': '从选定的上下文文件中省略易变的文件/符号计数', 'help.option.analyze.selfCommit': - '在 analyze 后自动提交 AGENTS.md/CLAUDE.md 的变更(默认关闭,需显式开启)。仅限这两个文件(绝不使用 `git add -A`);若两者均不存在、均未变更,或仓库未配置 git 身份,则不执行任何操作。', + '在 analyze 后自动提交生成的上下文文件变更(默认关闭,需显式开启)。仅限选定的上下文文件(绝不使用 `git add -A`);若没有上下文文件存在、没有文件变更,或仓库未配置 git 身份,则不执行任何操作。', 'help.option.analyze.skipSkills': '跳过直接安装在 .claude/skills/ 和 .agents/skills/ 下的标准 GitNexus skill 文件。不抑制 --skills 生成的社区 skill(位于 .claude/skills/gitnexus-area-*)。使用 --index-only 可跳过所有 AI 上下文文件注入。', - 'help.option.analyze.indexOnly': '纯索引模式:跳过所有文件注入(AGENTS.md、CLAUDE.md、skills)', + 'help.option.analyze.indexOnly': '纯索引模式:跳过所有文件注入(默认或自定义上下文文件、skills)', 'help.option.skipGit': '将提供的路径/cwd 视为索引根目录,并跳过向上查找 git 根目录', 'help.option.analyze.name': '在 ~/.gitnexus/registry.json 中使用自定义名称注册该仓库(用于区分路径 basename 相同的仓库,例如两个不同的 .../app 目录)', diff --git a/gitnexus/src/cli/index.ts b/gitnexus/src/cli/index.ts index 37dfe1ddb..e5a6a941f 100644 --- a/gitnexus/src/cli/index.ts +++ b/gitnexus/src/cli/index.ts @@ -102,6 +102,10 @@ program '--skip-agents-md', 'Skip updating the gitnexus section in AGENTS.md and CLAUDE.md. Does not skip standard skills in .claude/skills or .agents/skills; use --skip-skills for those. Community skills from --skills are unaffected.', ) + .option( + '--context-file ', + 'Write the GitNexus context block to one repo-relative file instead of root AGENTS.md and CLAUDE.md.', + ) .option( '--pdg', 'Build the control-flow-graph / PDG substrate (BasicBlock nodes + CFG edges) ' + @@ -121,9 +125,9 @@ program .option('--no-stats', 'Omit volatile file/symbol counts from AGENTS.md and CLAUDE.md') .option( '--self-commit', - 'Auto-commit AGENTS.md/CLAUDE.md changes after analyze (opt-in, off by default). ' + - 'Scoped to only those two files (never `git add -A`); no-ops if neither exists, ' + - 'neither changed, or the repo has no git identity configured.', + 'Auto-commit generated context file changes after analyze (opt-in, off by default). ' + + 'Scoped to the selected context target(s) (never `git add -A`); no-ops if none exist, ' + + 'none changed, or the repo has no git identity configured.', ) .option( '--skip-skills', diff --git a/gitnexus/src/core/run-analyze.ts b/gitnexus/src/core/run-analyze.ts index 7cec865c2..fe64dc7b3 100644 --- a/gitnexus/src/core/run-analyze.ts +++ b/gitnexus/src/core/run-analyze.ts @@ -166,6 +166,8 @@ import { loadMeta, ensureGitNexusIgnored, registerRepo, + readRegistry, + findRegistryEntryByRepoPath, setShareOptOut, adoptFlatBranchLabel, isReadOnlyFilesystemError, @@ -291,7 +293,7 @@ import { type CachedEmbeddingsSnapshot, } from './embeddings/embedding-restore-spill.js'; import { assertUniqueEmbeddingKeys, EmbeddingIntegrityError } from './embeddings/embedding-keys.js'; -import { generateAIContextFiles } from '../cli/ai-context.js'; +import { contextFileNeedsGeneration, generateAIContextFiles } from '../cli/ai-context.js'; import { formatRejectedBranchForLog, sanitizeDetectedBranch } from './git-ref.js'; import { EMBEDDING_TABLE_NAME, @@ -499,6 +501,8 @@ export interface AnalyzeOptions { skipGit?: boolean; /** Skip AGENTS.md and CLAUDE.md gitnexus block updates. */ skipAgentsMd?: boolean; + /** Repo-relative replacement for the default generated context files. */ + contextFile?: string; /** Omit volatile symbol/relationship counts from AGENTS.md and CLAUDE.md. */ noStats?: boolean; /** Skip installing standard GitNexus skill files directly under .claude/skills/. */ @@ -2673,6 +2677,15 @@ async function runFullAnalysisInner( if (!dirty && !indexedContentChanged && !healUnregistered) { const processDetectionStamp = existingMeta.processDetection ?? toProcessDetectionStamp(processDetectionBudget); + const registeredContextName = + options.contextFile && !options.registryName + ? findRegistryEntryByRepoPath(await readRegistry(), repoPath)?.name + : undefined; + const repoName = + options.registryName ?? + registeredContextName ?? + getInferredRepoName(repoPath) ?? + path.basename(resolveRepoIdentityRoot(repoPath)); if (options.registryName) { await registerRepo(repoPath, existingMeta, { name: options.registryName, @@ -2682,16 +2695,26 @@ async function runFullAnalysisInner( branch: placement.branch, storagePath, }); - if (!placement.branch) { - try { + } + if (!placement.branch) { + try { + // A new target needs an initial block even without --name. Existing + // blocks stay on the CLI's surgical refresh path to preserve skill rows. + if ( + options.registryName || + (!options.skipAgentsMd && + options.contextFile && + (await contextFileNeedsGeneration(repoPath, options.contextFile))) + ) { await generateAIContextFiles( repoPath, storagePath, - options.registryName, + repoName, existingMeta.stats ?? {}, undefined, { skipAgentsMd: options.skipAgentsMd, + contextFile: options.contextFile, skipSkills: options.skipSkills, noStats: options.noStats, defaultBranch: options.defaultBranch, @@ -2701,9 +2724,9 @@ async function runFullAnalysisInner( hasSpringActuator: existingMeta.springActuator?.enabled === true, }, ); - } catch { - /* best-effort — never fail the fast path over a context refresh */ } + } catch { + /* best-effort — never fail the fast path over a context refresh */ } } // ── #2354: restamp the workspace label on a same-commit branch flip ── @@ -2769,10 +2792,7 @@ async function runFullAnalysisInner( // `resolveRepoIdentityRoot` collapses worktree roots to the // canonical repo basename (#1259) but leaves arbitrary subdirs // and `--skip-git` paths unchanged (#1232/#1233 intent preserved). - repoName: - options.registryName ?? - getInferredRepoName(repoPath) ?? - path.basename(resolveRepoIdentityRoot(repoPath)), + repoName, repoPath, storagePath, stats: existingMeta.stats ?? {}, @@ -5591,6 +5611,7 @@ async function runFullAnalysisInner( undefined, { skipAgentsMd: options.skipAgentsMd, + contextFile: options.contextFile, skipSkills: options.skipSkills, noStats: options.noStats, defaultBranch: options.defaultBranch, diff --git a/gitnexus/src/storage/git.ts b/gitnexus/src/storage/git.ts index f4e26b99c..9a124a684 100644 --- a/gitnexus/src/storage/git.ts +++ b/gitnexus/src/storage/git.ts @@ -152,7 +152,7 @@ export const isWorkingTreePristine = (repoPath: string): boolean => { /** * Snapshot, per candidate file, whether it is safe for `selfCommitContextFiles` - * to auto-commit — call this BEFORE `analyze` writes AGENTS.md/CLAUDE.md. + * to auto-commit — call this BEFORE `analyze` writes the selected context files. * A file is safe when it does not exist yet (first-time creation, the normal * case) or is currently clean (`git status --porcelain` reports nothing for * it). A file that already has an uncommitted user edit is unsafe: without @@ -172,12 +172,16 @@ export const snapshotSelfCommitSafety = ( continue; } try { - const status = execFileSync('git', ['status', '--porcelain', '--', name], { - cwd: repoPath, - stdio: ['ignore', 'pipe', 'ignore'], - windowsHide: true, - encoding: 'utf8', - }); + const status = execFileSync( + 'git', + ['--literal-pathspecs', 'status', '--porcelain', '--', name], + { + cwd: repoPath, + stdio: ['ignore', 'pipe', 'ignore'], + windowsHide: true, + encoding: 'utf8', + }, + ); safety.set(name, status.trim().length === 0); } catch { safety.set(name, false); @@ -187,13 +191,13 @@ export const snapshotSelfCommitSafety = ( }; /** - * Best-effort auto-commit for the AGENTS.md/CLAUDE.md files `analyze --self-commit` + * Best-effort auto-commit for the selected context files `analyze --self-commit` * just (re)wrote. Filters `candidateFiles` down to the ones that actually exist * under `repoPath` AND were marked safe by `snapshotSelfCommitSafety` — a file * that already had an uncommitted edit before this run is skipped (logged), * never swept into the generated commit. Never `git add -A`. `git status * --porcelain` (not `diff --quiet`) is deliberate: a first-time `analyze` run - * creates AGENTS.md/CLAUDE.md fresh, and untracked files never show up in + * creates the selected context files fresh, and untracked files never show up in * `git diff`, only in `git status` — the same reason `isWorkingTreeDirty` * above uses `--porcelain`. If `git commit` fails after `git add` already * staged the safe files (e.g. missing git identity), the staged files are @@ -221,19 +225,23 @@ export const selfCommitContextFiles = ( if (safe.length === 0) return; try { - const status = execFileSync('git', ['status', '--porcelain', '--', ...safe], { - cwd: repoPath, - stdio: ['ignore', 'pipe', 'ignore'], - windowsHide: true, - encoding: 'utf8', - }); + const status = execFileSync( + 'git', + ['--literal-pathspecs', 'status', '--porcelain', '--', ...safe], + { + cwd: repoPath, + stdio: ['ignore', 'pipe', 'ignore'], + windowsHide: true, + encoding: 'utf8', + }, + ); if (status.trim().length === 0) return; // nothing to commit } catch { return; // git failed (not a repo, git missing, etc.) — nothing to do } try { - execFileSync('git', ['add', '--', ...safe], { + execFileSync('git', ['--literal-pathspecs', 'add', '--', ...safe], { cwd: repoPath, stdio: 'ignore', windowsHide: true, @@ -246,7 +254,14 @@ export const selfCommitContextFiles = ( try { execFileSync( 'git', - ['commit', '-m', 'chore(gitnexus): refresh index stats [skip ci]', '--', ...safe], + [ + '--literal-pathspecs', + 'commit', + '-m', + 'chore(gitnexus): refresh index stats [skip ci]', + '--', + ...safe, + ], { cwd: repoPath, stdio: 'ignore', windowsHide: true }, ); } catch (err) { @@ -255,7 +270,7 @@ export const selfCommitContextFiles = ( // files rather than leaving them silently staged — `analyze` reporting // "success" must not leave the user's index mutated. try { - execFileSync('git', ['reset', '--', ...safe], { + execFileSync('git', ['--literal-pathspecs', 'reset', '--', ...safe], { cwd: repoPath, stdio: 'ignore', windowsHide: true, diff --git a/gitnexus/test/unit/ai-context.test.ts b/gitnexus/test/unit/ai-context.test.ts index 6030e9eca..462ccbd90 100644 --- a/gitnexus/test/unit/ai-context.test.ts +++ b/gitnexus/test/unit/ai-context.test.ts @@ -8,6 +8,7 @@ import { refreshBaseRefLine, markdownSafeBranch, } from '../../src/cli/ai-context.js'; +import { resolveContextFileTarget } from '../../src/cli/context-file-target.js'; import { _captureLogger } from '../../src/core/logger.js'; describe('generateAIContextFiles', () => { @@ -51,6 +52,125 @@ describe('generateAIContextFiles', () => { expect(content).toContain('TestProject'); }); + it('writes only a nested custom context file and refreshes its base_ref', async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-context-file-')); + const storage = path.join(dir, '.gitnexus'); + const target = path.join(dir, '.claude', 'CLAUDE.md'); + try { + await fs.mkdir(storage); + await fs.writeFile(path.join(dir, 'AGENTS.md'), 'root agents\n'); + await fs.writeFile(path.join(dir, 'CLAUDE.md'), 'root claude\n'); + const options = { + contextFile: '.claude/CLAUDE.md', + defaultBranch: 'main', + skipSkills: true, + }; + const first = await generateAIContextFiles( + dir, + storage, + 'CustomProject', + {}, + undefined, + options, + ); + expect(first.files).toContain('.claude/CLAUDE.md (created)'); + expect(await fs.readFile(target, 'utf-8')).toContain('fetch target branch "main"'); + await generateAIContextFiles(dir, storage, 'CustomProject', {}, undefined, options); + expect((await fs.readFile(target, 'utf-8')).match(//g)).toHaveLength( + 1, + ); + + expect( + (await refreshBaseRefLine(dir, 'develop', { contextFile: options.contextFile })).files, + ).toEqual(['.claude/CLAUDE.md']); + expect(await fs.readFile(target, 'utf-8')).toContain('fetch target branch "develop"'); + expect(await fs.readFile(path.join(dir, 'AGENTS.md'), 'utf-8')).toBe('root agents\n'); + expect(await fs.readFile(path.join(dir, 'CLAUDE.md'), 'utf-8')).toBe('root claude\n'); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }); + + it.each(['\n', '\r\n'] as const)( + 'preserves custom context line endings %j during generation and refresh', + async (eol) => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-context-eol-')); + const contextFile = '.claude/CLAUDE.md'; + const target = path.join(dir, contextFile); + const prompt = ['# Project instructions', 'Keep this prompt.', ''].join(eol); + try { + await fs.mkdir(path.dirname(target), { recursive: true }); + await fs.writeFile(target, prompt); + await generateAIContextFiles(dir, path.join(dir, '.gitnexus'), 'CustomEol', {}, undefined, { + contextFile, + skipSkills: true, + defaultBranch: 'main', + }); + const generated = await fs.readFile(target, 'utf-8'); + expect(generated.startsWith(prompt)).toBe(true); + expect(generated.replaceAll(eol, '')).not.toMatch(/[\r\n]/); + expect(generated).toContain('fetch target branch "main"'); + + expect((await refreshBaseRefLine(dir, 'develop', { contextFile })).files).toEqual([ + contextFile, + ]); + const refreshed = await fs.readFile(target, 'utf-8'); + expect(refreshed.startsWith(prompt)).toBe(true); + expect(refreshed.replaceAll(eol, '')).not.toMatch(/[\r\n]/); + expect(refreshed).toContain('fetch target branch "develop"'); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }, + ); + + it('rejects custom paths outside the repo or through symlinks', async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-context-target-')); + const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-context-outside-')); + try { + for (const invalid of ['../outside.md', path.join(outside, 'CLAUDE.md'), 'C:\\outside.md']) { + expect(() => resolveContextFileTarget(dir, invalid)).toThrow(); + } + await fs.symlink( + outside, + path.join(dir, '.claude'), + process.platform === 'win32' ? 'junction' : 'dir', + ); + await expect( + generateAIContextFiles(dir, path.join(dir, '.gitnexus'), 'Unsafe', {}, undefined, { + contextFile: '.claude/CLAUDE.md', + skipSkills: true, + }), + ).rejects.toThrow(/symlinked path/); + await expect(fs.access(path.join(outside, 'CLAUDE.md'))).rejects.toThrow(); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + await fs.rm(outside, { recursive: true, force: true }); + } + }); + + it('keeps a trailing-space dot component inside the repo without overwriting its sibling', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-context-space-')); + const repo = path.join(root, 'repo'); + const outside = path.join(root, '.gitnexus-outside', 'context.md'); + const contextFile = '.. /.gitnexus-outside/context.md'; + try { + await fs.mkdir(repo); + await fs.mkdir(path.dirname(outside)); + await fs.writeFile(outside, 'outside-sentinel'); + await generateAIContextFiles(repo, path.join(repo, '.gitnexus'), 'SpacePath', {}, undefined, { + contextFile, + skipSkills: true, + }); + const target = resolveContextFileTarget(repo, contextFile).absolute; + expect(await fs.realpath(target)).toBe(path.join(await fs.realpath(repo), contextFile)); + expect(await fs.readFile(target, 'utf-8')).toContain(''); + expect(await fs.readFile(outside, 'utf-8')).toBe('outside-sentinel'); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }); + it('tells agents to preview with rename dry_run, not a separate rename_preview tool', async () => { await generateAIContextFiles(tmpDir, storagePath, 'TestProject', { nodes: 50, diff --git a/gitnexus/test/unit/analyze-gitnexusrc.test.ts b/gitnexus/test/unit/analyze-gitnexusrc.test.ts index e7fe6224c..65238ee45 100644 --- a/gitnexus/test/unit/analyze-gitnexusrc.test.ts +++ b/gitnexus/test/unit/analyze-gitnexusrc.test.ts @@ -132,6 +132,24 @@ describe('analyzeCommand .gitnexusrc wiring (#243)', () => { expect(opts.skipSkills).toBe(true); }); + it('indexOnly suppresses a selected custom context file', async () => { + const { analyzeCommand } = await import('../../src/cli/analyze.js'); + + await analyzeCommand(dir, { indexOnly: true, contextFile: '.claude/CLAUDE.md' }); + + expect(runFullAnalysisMock).toHaveBeenCalledTimes(1); + expect(runFullAnalysisMock.mock.calls[0][1]).toMatchObject({ + contextFile: '.claude/CLAUDE.md', + skipAgentsMd: true, + skipSkills: true, + }); + expect(refreshBaseRefLineMock.mock.calls[0][2]).toMatchObject({ skipAgentsMd: true }); + expect(generateAIContextFilesMock).not.toHaveBeenCalled(); + await expect(fs.readFile(path.join(dir, '.claude/CLAUDE.md'))).rejects.toMatchObject({ + code: 'ENOENT', + }); + }); + it('uses .gitnexusrc defaultBranch for generated context', async () => { await writeRc({ defaultBranch: 'develop' }); const { analyzeCommand } = await import('../../src/cli/analyze.js'); @@ -194,12 +212,15 @@ describe('analyzeCommand .gitnexusrc wiring (#243)', () => { try { const { analyzeCommand } = await import('../../src/cli/analyze.js'); - await analyzeCommand(dir, { skills: true }); + await analyzeCommand(dir, { skills: true, contextFile: '.claude/CLAUDE.md' }); expect(generateSkillFilesMock).toHaveBeenCalledTimes(1); expect(generateAIContextFilesMock).toHaveBeenCalledTimes(1); const aiCtxOpts = generateAIContextFilesMock.mock.calls[0]![5]; - expect(aiCtxOpts).toMatchObject({ defaultBranch: 'develop' }); + expect(aiCtxOpts).toMatchObject({ + defaultBranch: 'develop', + contextFile: '.claude/CLAUDE.md', + }); } finally { exitSpy.mockRestore(); } @@ -220,6 +241,25 @@ describe('analyzeCommand .gitnexusrc wiring (#243)', () => { ); }); + it('passes --context-file to analysis and the up-to-date refresh', async () => { + const { analyzeCommand } = await import('../../src/cli/analyze.js'); + await analyzeCommand(dir, { contextFile: '.claude/CLAUDE.md' }); + + expect(runFullAnalysisMock.mock.calls[0][1].contextFile).toBe('.claude/CLAUDE.md'); + expect(refreshBaseRefLineMock.mock.calls[0][2]).toMatchObject({ + contextFile: '.claude/CLAUDE.md', + }); + }); + + it('rejects an escaping --context-file before analysis', async () => { + const { analyzeCommand } = await import('../../src/cli/analyze.js'); + await analyzeCommand(dir, { contextFile: '../outside.md' }); + + expect(process.exitCode).toBe(1); + expect(runFullAnalysisMock).not.toHaveBeenCalled(); + expect(cliErrorMock).toHaveBeenCalledWith(expect.stringMatching(/--context-file/)); + }); + it('does not auto-detect the branch when config skips context generation (#1996)', async () => { await writeRc({ skipAgentsMd: true }); const { analyzeCommand } = await import('../../src/cli/analyze.js'); diff --git a/gitnexus/test/unit/analyze-self-commit-bridge.test.ts b/gitnexus/test/unit/analyze-self-commit-bridge.test.ts index d8c69dcb9..612b49af5 100644 --- a/gitnexus/test/unit/analyze-self-commit-bridge.test.ts +++ b/gitnexus/test/unit/analyze-self-commit-bridge.test.ts @@ -128,6 +128,22 @@ describe('analyzeCommand --self-commit bridge (#2639)', () => { ); }); + it('scopes --self-commit to the custom context file', async () => { + const { analyzeCommand } = await import('../../src/cli/analyze.js'); + + await analyzeCommand(undefined, { + selfCommit: true, + contextFile: '.claude/CLAUDE.md', + }); + + expect(snapshotSelfCommitSafetyMock).toHaveBeenCalledWith('/repo', ['.claude/CLAUDE.md']); + expect(selfCommitContextFilesMock).toHaveBeenCalledWith( + '/repo', + ['.claude/CLAUDE.md'], + expect.any(Map), + ); + }); + it('calls selfCommitContextFiles on the primary (non-fast-path) analyze run', async () => { runFullAnalysisMock.mockResolvedValueOnce({ repoName: 'repo', diff --git a/gitnexus/test/unit/cli-i18n.test.ts b/gitnexus/test/unit/cli-i18n.test.ts index 12a432630..9f0dfd410 100644 --- a/gitnexus/test/unit/cli-i18n.test.ts +++ b/gitnexus/test/unit/cli-i18n.test.ts @@ -46,4 +46,11 @@ describe('cli i18n', () => { expect(Object.keys(messages).sort(), language).toEqual(englishKeys); } }); + + it('qualifies self-commit no-ops across all selected context files in Chinese', () => { + setCliLanguage('zh-CN'); + const help = t('help.option.analyze.selfCommit'); + expect(help).toContain('没有上下文文件存在'); + expect(help).toContain('没有文件变更'); + }); }); diff --git a/gitnexus/test/unit/git-utils.test.ts b/gitnexus/test/unit/git-utils.test.ts index b1e00d727..8f787c21a 100644 --- a/gitnexus/test/unit/git-utils.test.ts +++ b/gitnexus/test/unit/git-utils.test.ts @@ -475,6 +475,71 @@ describe('selfCommitContextFiles', () => { } }); + it.each(process.platform === 'win32' ? ['context[1].md'] : ['context[1].md', '*.md'])( + 'self-commits the literal target %s without touching unrelated staged or unstaged edits', + async (target) => { + const { selfCommitContextFiles, snapshotSelfCommitSafety } = + await import('../../src/storage/git.js'); + const { generateAIContextFiles } = await import('../../src/cli/ai-context.js'); + const repoDir = initRepo(); + const git = (args: string[]) => + execFileSync(gitExecutable, args, { cwd: repoDir, encoding: 'utf8' }); + try { + fs.writeFileSync(path.join(repoDir, 'context1.md'), 'original\n'); + fs.writeFileSync(path.join(repoDir, 'README.md'), 'original\n'); + git(['add', '.']); + git(['commit', '-q', '-m', 'initial']); + fs.writeFileSync(path.join(repoDir, 'context1.md'), 'staged user edit\n'); + git(['add', 'context1.md']); + fs.writeFileSync(path.join(repoDir, 'context1.md'), 'unstaged user edit\n'); + fs.writeFileSync(path.join(repoDir, 'README.md'), 'unstaged README edit\n'); + const staged = git(['diff', '--cached']); + const unstaged = git(['diff']); + const safety = snapshotSelfCommitSafety(repoDir, [target]); + expect(safety.get(target)).toBe(true); + await generateAIContextFiles( + repoDir, + path.join(repoDir, '.gitnexus'), + 'Literal', + {}, + undefined, + { + contextFile: target, + skipSkills: true, + }, + ); + selfCommitContextFiles(repoDir, [target], safety); + expect(commitCount(repoDir)).toBe(2); + expect(git(['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD']).trim()).toBe( + target, + ); + expect(git(['diff', '--cached'])).toBe(staged); + expect(git(['diff'])).toBe(unstaged); + + // Status must also be literal: a matching dirty sibling must not make + // the clean selected file unsafe, nor hide edits to that selected file. + expect(snapshotSelfCommitSafety(repoDir, [target]).get(target)).toBe(true); + fs.appendFileSync(path.join(repoDir, target), '\nuser note\n'); + expect(snapshotSelfCommitSafety(repoDir, [target]).get(target)).toBe(false); + + git(['--literal-pathspecs', 'add', '--', target]); + git(['--literal-pathspecs', 'commit', '-q', '-m', 'save prompt', '--', target]); + const beforeFailure = snapshotSelfCommitSafety(repoDir, [target]); + fs.appendFileSync(path.join(repoDir, target), '\ngenerated update\n'); + // An invalid local signing program fails commit after staging. + git(['config', 'commit.gpgsign', 'true']); + git(['config', 'gpg.program', path.join(repoDir, 'missing-signing-program')]); + selfCommitContextFiles(repoDir, [target], beforeFailure); + expect(commitCount(repoDir)).toBe(3); + expect(git(['diff', '--cached'])).toBe(staged); + expect(git(['--literal-pathspecs', 'diff', '--cached', '--', target])).toBe(''); + expect(fs.readFileSync(path.join(repoDir, target), 'utf8')).toContain('generated update'); + } finally { + fs.rmSync(repoDir, { recursive: true, force: true }); + } + }, + ); + it('no-ops (no new commit) when neither candidate file changed', async () => { const { selfCommitContextFiles } = await import('../../src/storage/git.js'); const repoDir = initRepo(); diff --git a/gitnexus/test/unit/incremental-orchestration.test.ts b/gitnexus/test/unit/incremental-orchestration.test.ts index cd17b01b8..061c367d4 100644 --- a/gitnexus/test/unit/incremental-orchestration.test.ts +++ b/gitnexus/test/unit/incremental-orchestration.test.ts @@ -613,6 +613,116 @@ describe('runFullAnalysis — incremental orchestration', () => { } }, 300_000); + it.each(['missing', 'prompt-only', 'generated', 'missing-alias', 'prompt-only-alias'] as const)( + 'selects a %s custom context target on the same-commit fast path without --name', + async (state) => { + const repo = await setupMiniRepo(); + const contextFile = '.claude/CLAUDE.md'; + const target = path.join(repo.dbPath, contextFile); + const skillRow = '| custom-skill | Keep this community skill |'; + const prompt = '# Project instructions\n'; + const registryName = state.endsWith('-alias') + ? `context-${path.basename(repo.dbPath)}` + : undefined; + try { + const { runFullAnalysis } = await import('../../src/core/run-analyze.js'); + const { generateGitNexusContent, refreshBaseRefLine } = + await import('../../src/cli/ai-context.js'); + let initial = prompt; + if (state === 'generated') { + initial += + '\n' + + generateGitNexusContent( + 'ExistingName', + { nodes: 42 }, + { defaultBranch: 'main' }, + ).replace('', `${skillRow}\n`); + } + if (state !== 'missing' && state !== 'missing-alias') { + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, initial); + gitCommitAll(repo.dbPath, 'existing prompt'); + } + const first = await runFullAnalysis( + repo.dbPath, + { skipAgentsMd: true, skipSkills: true, registryName }, + { onProgress: () => {} }, + ); + const second = await runFullAnalysis( + repo.dbPath, + { contextFile, skipSkills: true }, + { onProgress: () => {} }, + ); + expect(second.alreadyUpToDate).toBe(true); + expect(second.repoName).toBe(first.repoName); + const content = await readFile(target, 'utf-8'); + expect(content.match(//g)).toHaveLength(1); + if (state === 'generated') { + expect(content).toBe(initial); + await refreshBaseRefLine(repo.dbPath, 'develop', { contextFile }); + const refreshed = await readFile(target, 'utf-8'); + expect(refreshed).toContain(skillRow); + expect(refreshed).toContain('fetch target branch "develop"'); + } else { + expect(content).toContain(first.repoName); + if (state.startsWith('prompt-only')) expect(content).toContain(prompt); + if (registryName) expect(content).toContain(registryName); + } + await expect(readFile(path.join(repo.dbPath, 'AGENTS.md'))).rejects.toMatchObject({ + code: 'ENOENT', + }); + await expect( + readFile(path.join(repo.dbPath, '.claude/skills/gitnexus-guide/SKILL.md')), + ).rejects.toMatchObject({ code: 'ENOENT' }); + } finally { + await repo.cleanup(); + } + }, + 300_000, + ); + + it.each(['skip-agents', 'pinned-branch'] as const)( + 'does not create a selected context target on a %s fast path', + async (mode) => { + const repo = await setupMiniRepo(); + try { + const { runFullAnalysis } = await import('../../src/core/run-analyze.js'); + const branch = mode === 'pinned-branch' ? 'context-feature' : undefined; + await runFullAnalysis( + repo.dbPath, + { skipAgentsMd: true, skipSkills: true }, + { onProgress: () => {} }, + ); + if (branch) { + execSync(`git checkout -b ${branch}`, { cwd: repo.dbPath, stdio: 'pipe' }); + await runFullAnalysis( + repo.dbPath, + { branch, skipAgentsMd: true, skipSkills: true }, + { onProgress: () => {} }, + ); + } + const result = await runFullAnalysis( + repo.dbPath, + { + branch, + contextFile: '.claude/CLAUDE.md', + skipAgentsMd: mode === 'skip-agents', + skipSkills: true, + }, + { onProgress: () => {} }, + ); + expect(result.alreadyUpToDate).toBe(true); + expect(result.isPrimaryBranch).toBe(mode !== 'pinned-branch'); + await expect(readFile(path.join(repo.dbPath, '.claude/CLAUDE.md'))).rejects.toMatchObject({ + code: 'ENOENT', + }); + } finally { + await repo.cleanup(); + } + }, + 300_000, + ); + it('useParseCache:false bypasses the alreadyUpToDate fast path without --force', async () => { const repo = await setupMiniRepo(); try { diff --git a/gitnexus/test/unit/watch-paths.test.ts b/gitnexus/test/unit/watch-paths.test.ts index 5dc5ce3f9..747e701d8 100644 --- a/gitnexus/test/unit/watch-paths.test.ts +++ b/gitnexus/test/unit/watch-paths.test.ts @@ -151,6 +151,7 @@ describe('watch path selection', () => { [{ embeddings: true }, '--embeddings'], [{ defaultBranch: 'develop' }, '--default-branch'], [{ skipAgentsMd: true }, '--skip-agents-md'], + [{ contextFile: '.claude/CLAUDE.md' }, '--context-file'], [{ skipSkills: true }, '--skip-skills'], [{ stats: false }, '--no-stats'], [{ springActuator: './actuator' }, '--spring-actuator'],