From 6eb729af0d64074ca83c36bf756844283ea1fe37 Mon Sep 17 00:00:00 2001 From: carlos-alm Date: Fri, 7 Aug 2026 17:03:59 -0600 Subject: [PATCH] fix(cli): derive config from the target dir/--db instead of a cwd-pinned singleton (#2137) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ctx.config was a process-wide singleton, lazily resolved exactly once from process.cwd(), regardless of any dir positional or --db flag a command received. This silently ignored the target project's own .codegraphrc.json for `embed`'s embeddings.provider/model (the whole v3.16.0 remote embedding feature did nothing when invoked from elsewhere), coChange tuning, and query.excludeTests across every command using resolveNoTests()/resolveQueryOpts() (~38 call sites) — returning different rows, not just different formatting. audit.ts and complexity.ts additionally passed the stale ctx.config straight through, short-circuiting the already-correct resolveDbConfig(customDbPath) fallback at the feature layer added for issues #1881/#2017. Fix: embed.ts, co-change.ts, and resolveNoTests() in src/cli/shared/options.ts now call resolveDbConfig(opts.db, or the resolved [dir] positional for embed) directly, matching the pattern already established for read-only queries. audit.ts/complexity.ts drop their config pass-through so the feature layer's own fallback runs. check.ts's already-dead config pass-through is removed too, since it was a loaded gun for the same regression. models.ts is left on the cwd singleton — it has no target directory to derive from. No README/CLAUDE.md/ROADMAP.md changes — internal CLI config-resolution plumbing, no new commands, flags, or architecture. docs check acknowledged. Impact: 13 functions changed, 0 affected --- src/cli/commands/audit.ts | 7 +- src/cli/commands/check.ts | 8 +- src/cli/commands/co-change.ts | 9 ++- src/cli/commands/complexity.ts | 6 +- src/cli/commands/embed.ts | 23 ++++-- src/cli/shared/options.ts | 16 +++- ...i-shared-options-config-resolution.test.ts | 78 +++++++++++++++++++ tests/unit/embed-command.test.ts | 76 +++++++++--------- tests/unit/withrepo-config-resolution.test.ts | 2 +- 9 files changed, 168 insertions(+), 57 deletions(-) create mode 100644 tests/unit/cli-shared-options-config-resolution.test.ts diff --git a/src/cli/commands/audit.ts b/src/cli/commands/audit.ts index 0571ad62d..55780407c 100644 --- a/src/cli/commands/audit.ts +++ b/src/cli/commands/audit.ts @@ -2,7 +2,6 @@ import { collectFile } from '../../db/query-builder.js'; import { EVERY_SYMBOL_KIND } from '../../domain/queries.js'; import { audit } from '../../presentation/audit.js'; import { explain } from '../../presentation/queries-cli.js'; -import { config } from '../shared/options.js'; import type { CommandDefinition } from '../types.js'; export const command: CommandDefinition = { @@ -36,13 +35,17 @@ export const command: CommandDefinition = { }); return; } + // No `config` field here — auditData()/resolveThresholds() already derive + // it correctly from opts.db via resolveDbConfig() (issue #1881). Passing + // the process.cwd()-pinned CLI singleton here would short-circuit that + // fallback and silently reintroduce the cwd-vs-target-project bug + // resolveDbConfig was built to fix (issue #2137). audit(target!, opts.db, { depth: parseInt(opts.depth as string, 10), file: opts.file, kind: opts.kind, noTests: qOpts.noTests, json: qOpts.json, - config, }); }, }; diff --git a/src/cli/commands/check.ts b/src/cli/commands/check.ts index 9bac0c693..382dbb179 100644 --- a/src/cli/commands/check.ts +++ b/src/cli/commands/check.ts @@ -1,7 +1,6 @@ import { collectFile } from '../../db/query-builder.js'; import { EVERY_SYMBOL_KIND } from '../../domain/queries.js'; import { ConfigError } from '../../shared/errors.js'; -import { config } from '../shared/options.js'; import type { CommandDefinition, CommandOpts } from '../types.js'; function validateKind(kind: CommandOpts): void { @@ -65,7 +64,12 @@ export const command: CommandDefinition = { depth: opts.depth ? parseInt(opts.depth as string, 10) : undefined, noTests: qOpts.noTests, json: qOpts.json, - config, + // No `config` field here — presentation/check.ts already omits it from + // the object it forwards, so features/check.ts resolves correctly from + // opts.db via loadConfig(repoRoot). Passing the process.cwd()-pinned + // CLI singleton here would be a loaded gun: harmless only until some + // future forward-through of this field reintroduces the + // cwd-vs-target-project bug (issue #2137). }); if (opts.rules) { diff --git a/src/cli/commands/co-change.ts b/src/cli/commands/co-change.ts index c74a478e6..434a7ba83 100644 --- a/src/cli/commands/co-change.ts +++ b/src/cli/commands/co-change.ts @@ -1,3 +1,4 @@ +import { resolveDbConfig } from '../../db/index.js'; import { AnalysisError } from '../../shared/errors.js'; import type { CommandDefinition } from '../types.js'; @@ -25,8 +26,12 @@ export const command: CommandDefinition = { ); const { formatCoChange, formatCoChangeTop } = await import('../../presentation/cochange.js'); + // Derive coChange.* from opts.db (issue #2137) rather than the + // process.cwd()-pinned ctx.config singleton, so `--db /other/repo/...` + // reads that repo's own tuning config instead of the invoking + // directory's. if (opts.analyze) { - const coChangeConfig = ctx.config.coChange; + const coChangeConfig = resolveDbConfig(opts.db).coChange; const result = analyzeCoChanges(opts.db, { since: opts.since || coChangeConfig?.since, minSupport: opts.minSupport @@ -48,7 +53,7 @@ export const command: CommandDefinition = { return; } - const coChangeConfig = ctx.config.coChange; + const coChangeConfig = resolveDbConfig(opts.db).coChange; const queryOpts = { limit: parseInt(opts.limit as string, 10), offset: opts.offset ? parseInt(opts.offset as string, 10) : undefined, diff --git a/src/cli/commands/complexity.ts b/src/cli/commands/complexity.ts index c5c9613db..07671390d 100644 --- a/src/cli/commands/complexity.ts +++ b/src/cli/commands/complexity.ts @@ -42,7 +42,11 @@ export const command: CommandDefinition = { noTests: ctx.resolveNoTests(opts), json: opts.json, ndjson: opts.ndjson, - config: ctx.config, + // No `config` field here — complexityData() already derives it + // correctly from opts.db via resolveDbConfig() (issue #1881). Passing + // the process.cwd()-pinned CLI singleton would short-circuit that + // fallback and silently reintroduce the cwd-vs-target-project bug + // resolveDbConfig was built to fix (issue #2137). }); }, }; diff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.ts index c4b00e2e7..9040dc29b 100644 --- a/src/cli/commands/embed.ts +++ b/src/cli/commands/embed.ts @@ -1,5 +1,5 @@ import path from 'node:path'; -import { openReadonlyOrFail, resolveBusyTimeoutMs } from '../../db/index.js'; +import { openReadonlyOrFail, resolveBusyTimeoutMs, resolveDbConfig } from '../../db/index.js'; import { getEmbeddingMeta } from '../../db/repository/embeddings.js'; import { buildEmbeddings, @@ -49,28 +49,36 @@ export const command: CommandDefinition = { ], ['-d, --db ', 'Path to graph.db (default: /.codegraph/graph.db)'], ], - validate([_dir], opts, ctx) { + validate([dir], opts) { if (!(EMBEDDING_STRATEGIES as readonly string[]).includes(opts.strategy)) { return `Unknown strategy: ${opts.strategy}. Available: ${EMBEDDING_STRATEGIES.join(', ')}`; } - const provider = ctx.config.embeddings?.provider ?? null; + // Derive config from the target project (opts.db, else the resolved + // [dir] positional) rather than the process.cwd()-pinned ctx.config + // singleton — otherwise `codegraph embed /other/project` invoked from a + // different cwd silently ignores that project's embeddings.provider + // (issue #2137). + const root = path.resolve(dir || '.'); + const config = resolveDbConfig(opts.db ?? root); + const provider = config.embeddings?.provider ?? null; if (provider && provider !== 'openai') { return ( `Unsupported embeddings.provider "${provider}". Currently supported: "openai" ` + '(any OpenAI-compatible /embeddings endpoint, including self-hosted servers).' ); } - if (provider && !opts.model && !ctx.config.embeddings?.model) { + if (provider && !opts.model && !config.embeddings?.model) { return ( `embeddings.provider is set to "${provider}" but no model is configured. ` + 'Set embeddings.model to the model identifier your endpoint expects, or pass --model.' ); } }, - async execute([dir], opts, ctx) { + async execute([dir], opts) { const root = path.resolve(dir || '.'); const dbPath = opts.db as string | undefined; - const embeddingsConfig = ctx.config.embeddings; + const config = resolveDbConfig(dbPath ?? root); + const embeddingsConfig = config.embeddings; const provider = embeddingsConfig?.provider ?? null; const flagModel = opts.model as string | undefined; const configModel = (embeddingsConfig?.model as string | null | undefined) ?? null; @@ -96,8 +104,7 @@ export const command: CommandDefinition = { } } - const remote = - provider === 'openai' ? resolveRemoteEmbeddingOptions(ctx.config, model) : undefined; + const remote = provider === 'openai' ? resolveRemoteEmbeddingOptions(config, model) : undefined; await buildEmbeddings(root, model, dbPath, { strategy: opts.strategy, remote }); }, }; diff --git a/src/cli/shared/options.ts b/src/cli/shared/options.ts index e500f2dd5..94f552050 100644 --- a/src/cli/shared/options.ts +++ b/src/cli/shared/options.ts @@ -1,4 +1,5 @@ import type { Command } from 'commander'; +import { resolveDbConfig } from '../../db/index.js'; import { loadConfig } from '../../infrastructure/config.js'; import type { CodegraphConfig } from '../../types.js'; import type { CommandOpts } from '../types.js'; @@ -6,6 +7,14 @@ import type { CommandOpts } from '../types.js'; // Deferred so global --user-config / --no-user-config flags are parsed // before config is first accessed (Commander parses flags before any command // action runs, but module-level code executes at import time). +// +// This singleton is only correct for commands with no project-specific +// `dir`/`--db` target (e.g. `models`) — it is pinned to process.cwd() once +// and never revisited. Any command that receives its own target directory +// or `--db` path must resolve config via resolveDbConfig(opts.db) instead, +// the way resolveNoTests() below does, so `codegraph /other/project` +// invoked from a different cwd reads *that* project's .codegraphrc.json +// rather than the invoking directory's (issue #2137). let _config: CodegraphConfig | undefined; const config: CodegraphConfig = new Proxy({} as CodegraphConfig, { get(_t, prop: string) { @@ -34,12 +43,15 @@ export function applyQueryOpts(cmd: Command): Command { * Resolve the effective noTests value: CLI flag > config > false. * Commander sets opts.tests to false when --no-tests is passed. * When --include-tests is passed, always return false (include tests). - * Otherwise, fall back to config.query.excludeTests. + * Otherwise, fall back to the target project's query.excludeTests — derived + * from opts.db (issue #2137) rather than the process.cwd()-pinned `config` + * singleton, so `codegraph --db /other/project/.codegraph/graph.db` + * reads that project's own config instead of the invoking directory's. */ export function resolveNoTests(opts: CommandOpts): boolean { if (opts.includeTests) return false; if (opts.tests === false) return true; - return config.query?.excludeTests || false; + return resolveDbConfig(opts.db).query?.excludeTests || false; } /** diff --git a/tests/unit/cli-shared-options-config-resolution.test.ts b/tests/unit/cli-shared-options-config-resolution.test.ts new file mode 100644 index 000000000..69a4b7ffa --- /dev/null +++ b/tests/unit/cli-shared-options-config-resolution.test.ts @@ -0,0 +1,78 @@ +/** + * Regression tests for issue #2137: `src/cli/shared/options.ts`'s + * `resolveNoTests()` (and everything that calls it — `resolveQueryOpts()`, + * plus every command using `applyQueryOpts()`, ~38 call sites) read + * `query.excludeTests` from a process-wide `config` singleton resolved + * exactly once from `process.cwd()`. A command invoked with `--db + * /other/project/.codegraph/graph.db` from a different cwd silently read + * the WRONG project's `.codegraphrc.json` (or none at all) for this value, + * changing which rows a query returns — not just display formatting. + * + * The fix: `resolveNoTests()` now derives config via + * `resolveDbConfig(opts.db)`, mirroring the pattern already used at the + * data-query layer for issues #1881/#2017, so it reads the *target* + * project's config regardless of the invoking directory. + */ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { resolveNoTests } from '../../src/cli/shared/options.js'; + +const CUSTOM_EXCLUDE_TESTS = true; + +let projectDir: string; +let cwdDir: string; +let dbPath: string; + +beforeAll(() => { + projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cli-options-project-')); + fs.mkdirSync(path.join(projectDir, '.git')); + fs.mkdirSync(path.join(projectDir, '.codegraph')); + dbPath = path.join(projectDir, '.codegraph', 'graph.db'); + fs.writeFileSync(dbPath, ''); + fs.writeFileSync( + path.join(projectDir, '.codegraphrc.json'), + JSON.stringify({ query: { excludeTests: CUSTOM_EXCLUDE_TESTS } }), + ); + + // cwd is a different, config-less directory — resolveNoTests() reading + // config from process.cwd() instead of opts.db would silently miss the + // custom value above and fall back to the false default. + cwdDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cli-options-cwd-')); +}); + +afterAll(() => { + fs.rmSync(projectDir, { recursive: true, force: true }); + fs.rmSync(cwdDir, { recursive: true, force: true }); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('resolveNoTests (#2137)', () => { + it('reads query.excludeTests from the opts.db project, not process.cwd()', () => { + vi.spyOn(process, 'cwd').mockReturnValue(cwdDir); + expect(resolveNoTests({ db: dbPath })).toBe(true); + }); + + it('falls back to process.cwd() config when no opts.db is given (commands with no --db target)', () => { + vi.spyOn(process, 'cwd').mockReturnValue(projectDir); + expect(resolveNoTests({})).toBe(true); + }); + + it('--no-tests (opts.tests === false) always wins regardless of config', () => { + vi.spyOn(process, 'cwd').mockReturnValue(cwdDir); + expect(resolveNoTests({ db: dbPath, tests: false })).toBe(true); + }); + + it('--include-tests always wins over a project config with excludeTests: true', () => { + expect(resolveNoTests({ db: dbPath, includeTests: true })).toBe(false); + }); + + it('defaults to false when neither a flag nor a project config sets excludeTests', () => { + vi.spyOn(process, 'cwd').mockReturnValue(cwdDir); + expect(resolveNoTests({})).toBe(false); + }); +}); diff --git a/tests/unit/embed-command.test.ts b/tests/unit/embed-command.test.ts index 82476a327..25bacf077 100644 --- a/tests/unit/embed-command.test.ts +++ b/tests/unit/embed-command.test.ts @@ -10,73 +10,71 @@ vi.mock('../../src/db/index.js', () => ({ throw new Error('no db in this test'); }), resolveBusyTimeoutMs: vi.fn(() => 5000), + resolveDbConfig: vi.fn(), })); vi.mock('../../src/db/repository/embeddings.js', () => ({ getEmbeddingMeta: vi.fn() })); const { command } = await import('../../src/cli/commands/embed.js'); const { buildEmbeddings } = await import('../../src/domain/search/index.js'); -const { openReadonlyOrFail } = await import('../../src/db/index.js'); - -function fakeCtx(embeddings: Record, llm: Record = {}) { - return { - config: { - embeddings: { model: null, llmProvider: null, provider: null, ...embeddings }, - llm: { - provider: null, - model: null, - baseUrl: null, - apiKey: null, - apiKeyCommand: null, - ...llm, - }, +const { openReadonlyOrFail, resolveDbConfig } = await import('../../src/db/index.js'); + +// embed.ts derives config via resolveDbConfig(opts.db ?? root) (issue #2137) +// rather than a ctx.config singleton, so tests configure the mocked +// resolveDbConfig's return value directly instead of building a fake ctx. +function mockConfig(embeddings: Record, llm: Record = {}) { + vi.mocked(resolveDbConfig).mockReturnValue({ + embeddings: { model: null, llmProvider: null, provider: null, ...embeddings }, + llm: { + provider: null, + model: null, + baseUrl: null, + apiKey: null, + apiKeyCommand: null, + ...llm, }, - } as never; + } as never); } +const fakeCtx = {} as never; + describe('embed command validate()', () => { it('rejects an unknown strategy', () => { - const err = command.validate!([undefined], { strategy: 'bogus' } as never, fakeCtx({})); + mockConfig({}); + const err = command.validate!([undefined], { strategy: 'bogus' } as never, fakeCtx); expect(err).toMatch(/Unknown strategy/); }); it('rejects an unsupported embeddings.provider', () => { - const err = command.validate!( - [undefined], - { strategy: 'structured' } as never, - fakeCtx({ provider: 'anthropic' }), - ); + mockConfig({ provider: 'anthropic' }); + const err = command.validate!([undefined], { strategy: 'structured' } as never, fakeCtx); expect(err).toMatch(/Unsupported embeddings.provider/); }); it('rejects provider "openai" with no model configured', () => { - const err = command.validate!( - [undefined], - { strategy: 'structured' } as never, - fakeCtx({ provider: 'openai' }), - ); + mockConfig({ provider: 'openai' }); + const err = command.validate!([undefined], { strategy: 'structured' } as never, fakeCtx); expect(err).toMatch(/no model is configured/); }); it('accepts provider "openai" with a config model', () => { - const err = command.validate!( - [undefined], - { strategy: 'structured' } as never, - fakeCtx({ provider: 'openai', model: 'text-embedding-3-small' }), - ); + mockConfig({ provider: 'openai', model: 'text-embedding-3-small' }); + const err = command.validate!([undefined], { strategy: 'structured' } as never, fakeCtx); expect(err).toBeUndefined(); }); it('accepts provider "openai" with a --model flag', () => { + mockConfig({ provider: 'openai' }); const err = command.validate!( [undefined], { strategy: 'structured', model: 'text-embedding-3-small' } as never, - fakeCtx({ provider: 'openai' }), + fakeCtx, ); expect(err).toBeUndefined(); }); it('accepts no provider at all', () => { - const err = command.validate!([undefined], { strategy: 'structured' } as never, fakeCtx({})); + mockConfig({}); + const err = command.validate!([undefined], { strategy: 'structured' } as never, fakeCtx); expect(err).toBeUndefined(); }); }); @@ -92,12 +90,12 @@ describe('embed command execute()', () => { }); it('passes a resolved remote config through to buildEmbeddings when provider is "openai"', async () => { - const ctx = fakeCtx( + mockConfig( { provider: 'openai', model: 'text-embedding-3-small' }, { baseUrl: 'http://localhost:8080/v1', apiKey: 'sk-test', requestTimeoutMs: 5000 }, ); - await command.execute!([undefined], { strategy: 'structured' } as never, ctx); + await command.execute!([undefined], { strategy: 'structured' } as never, fakeCtx); expect(buildEmbeddings).toHaveBeenCalledTimes(1); const [, model, , options] = vi.mocked(buildEmbeddings).mock.calls[0]!; @@ -111,9 +109,9 @@ describe('embed command execute()', () => { }); it('does not build a remote config when no provider is set', async () => { - const ctx = fakeCtx({ model: 'minilm' }); + mockConfig({ model: 'minilm' }); - await command.execute!([undefined], { strategy: 'structured' } as never, ctx); + await command.execute!([undefined], { strategy: 'structured' } as never, fakeCtx); expect(buildEmbeddings).toHaveBeenCalledTimes(1); const [, , , options] = vi.mocked(buildEmbeddings).mock.calls[0]!; @@ -121,10 +119,10 @@ describe('embed command execute()', () => { }); it('resolves the sticky-model DB lookup and buildEmbeddings against the positional dir, not cwd (#1869)', async () => { - const ctx = fakeCtx({}); + mockConfig({}); const targetDir = path.join('some', 'other', 'project'); - await command.execute!([targetDir], { strategy: 'structured' } as never, ctx); + await command.execute!([targetDir], { strategy: 'structured' } as never, fakeCtx); // resolveStickyModel() must open the DB relative to the resolved dir, not // whatever the process's cwd happens to be. diff --git a/tests/unit/withrepo-config-resolution.test.ts b/tests/unit/withrepo-config-resolution.test.ts index 160381b61..86e438af4 100644 --- a/tests/unit/withrepo-config-resolution.test.ts +++ b/tests/unit/withrepo-config-resolution.test.ts @@ -69,7 +69,7 @@ beforeAll(() => { dbPath = path.join(tmpDir, '.codegraph', 'graph.db'); // Project config lives next to the DB, not at cwd — proves rootDir is - // derived from `--db`, matching resolveConfigForDbPath()'s contract. + // derived from `--db`, matching resolveDbConfig()'s contract. fs.writeFileSync( path.join(tmpDir, '.codegraphrc.json'), JSON.stringify({