From b394d2bf72bfaeac2fd5eb7f879e05df00cf2257 Mon Sep 17 00:00:00 2001 From: azizur100389 Date: Mon, 28 Sep 2026 18:53:01 +0100 Subject: [PATCH] feat(cli): support custom AI context file path --- gitnexus/src/cli/ai-context.ts | 50 +++++++------- gitnexus/src/cli/analyze-options.ts | 6 +- gitnexus/src/cli/analyze-watch.ts | 1 + gitnexus/src/cli/analyze.ts | 27 ++++++-- gitnexus/src/cli/context-file-target.ts | 49 ++++++++++++++ gitnexus/src/cli/help-i18n.ts | 1 + gitnexus/src/cli/i18n/en.ts | 4 +- gitnexus/src/cli/i18n/zh-CN.ts | 4 +- gitnexus/src/cli/index.ts | 10 ++- gitnexus/src/core/run-analyze.ts | 4 ++ gitnexus/test/unit/ai-context.test.ts | 65 +++++++++++++++++++ gitnexus/test/unit/analyze-gitnexusrc.test.ts | 26 +++++++- .../unit/analyze-self-commit-bridge.test.ts | 16 +++++ 13 files changed, 222 insertions(+), 41 deletions(-) create mode 100644 gitnexus/src/cli/context-file-target.ts diff --git a/gitnexus/src/cli/ai-context.ts b/gitnexus/src/cli/ai-context.ts index 89bf912f0..ca759a7c1 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; /** @@ -656,27 +658,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)'); @@ -726,8 +723,8 @@ export async function generateAIContextFiles( } /** - * Refresh only the `base_ref: "..."` value inside the GitNexus block of an - * already-generated AGENTS.md / CLAUDE.md, in place (#1996 tri-review P2). + * Refresh only the `base_ref: "..."` value inside an already-generated + * context file, in place (#1996 tri-review P2). * * The `alreadyUpToDate` analyze fast path returns before the normal * {@link generateAIContextFiles} call, so a changed `.gitnexusrc` defaultBranch @@ -743,13 +740,14 @@ 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 replacement = `base_ref: ${JSON.stringify(markdownSafeBranch(defaultBranch))}`; 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..152eed843 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,8 +63,8 @@ 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 + * 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 neither exists, neither changed, or the commit step itself * fails (e.g. no git identity configured). See #2639. */ 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 00e9a9d62..e941fb307 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, @@ -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, @@ -1613,9 +1629,7 @@ const analyzeCommandImpl = async ( // 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) { @@ -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 */ @@ -1669,7 +1683,7 @@ const analyzeCommandImpl = async ( // #2639: opt-in self-commit of any AGENTS.md/CLAUDE.md 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,6 +1756,7 @@ 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 @@ -1765,7 +1780,7 @@ const analyzeCommandImpl = async ( // 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 e24e5a928..167052866 100644 --- a/gitnexus/src/cli/i18n/en.ts +++ b/gitnexus/src/cli/i18n/en.ts @@ -283,9 +283,11 @@ export const en = { '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.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 AGENTS.md and CLAUDE.md', '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': diff --git a/gitnexus/src/cli/i18n/zh-CN.ts b/gitnexus/src/cli/i18n/zh-CN.ts index 3092b9c5e..abd140128 100644 --- a/gitnexus/src/cli/i18n/zh-CN.ts +++ b/gitnexus/src/cli/i18n/zh-CN.ts @@ -259,9 +259,11 @@ export const zhCN = { '根据检测到的社区生成仓库专属 skill 文件(同时设置 --index-only 时无效)。', 'help.option.analyze.skipAgentsMd': '跳过更新 AGENTS.md 和 CLAUDE.md 中的 gitnexus 区块。不会跳过 .claude/skills 或 .agents/skills 下的标准 skill;如需跳过那些请使用 --skip-skills。--skills 生成的社区 skill 不受影响。', + 'help.option.analyze.contextFile': + '将 GitNexus 上下文区块写入一个仓库相对路径文件,而不是根目录的 AGENTS.md 和 CLAUDE.md。', 'help.option.analyze.noStats': '从 AGENTS.md 和 CLAUDE.md 中省略易变的文件/符号计数', '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)', diff --git a/gitnexus/src/cli/index.ts b/gitnexus/src/cli/index.ts index 9141c9d85..f37189749 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 8d302c913..0421ba95a 100644 --- a/gitnexus/src/core/run-analyze.ts +++ b/gitnexus/src/core/run-analyze.ts @@ -471,6 +471,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/. */ @@ -2466,6 +2468,7 @@ async function runFullAnalysisInner( undefined, { skipAgentsMd: options.skipAgentsMd, + contextFile: options.contextFile, skipSkills: options.skipSkills, noStats: options.noStats, defaultBranch: options.defaultBranch, @@ -5034,6 +5037,7 @@ async function runFullAnalysisInner( undefined, { skipAgentsMd: options.skipAgentsMd, + contextFile: options.contextFile, skipSkills: options.skipSkills, noStats: options.noStats, defaultBranch: options.defaultBranch, diff --git a/gitnexus/test/unit/ai-context.test.ts b/gitnexus/test/unit/ai-context.test.ts index a7174e674..caa9a8975 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,70 @@ 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('base_ref: "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('base_ref: "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('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('omits volatile counts when noStats option is set (#1477)', async () => { // Distinct subdir per case so we can assert on a clean slate. const subDir = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-no-stats-test-')); diff --git a/gitnexus/test/unit/analyze-gitnexusrc.test.ts b/gitnexus/test/unit/analyze-gitnexusrc.test.ts index 081b3664c..286a5524c 100644 --- a/gitnexus/test/unit/analyze-gitnexusrc.test.ts +++ b/gitnexus/test/unit/analyze-gitnexusrc.test.ts @@ -190,12 +190,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(); } @@ -216,6 +219,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',