Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/cli/commands/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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,
});
},
};
8 changes: 6 additions & 2 deletions src/cli/commands/check.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
9 changes: 7 additions & 2 deletions src/cli/commands/co-change.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { resolveDbConfig } from '../../db/index.js';
import { AnalysisError } from '../../shared/errors.js';
import type { CommandDefinition } from '../types.js';

Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
6 changes: 5 additions & 1 deletion src/cli/commands/complexity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
});
},
};
23 changes: 15 additions & 8 deletions src/cli/commands/embed.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -49,28 +49,36 @@ export const command: CommandDefinition = {
],
['-d, --db <path>', 'Path to graph.db (default: <dir>/.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;
Expand All @@ -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 });
},
};
16 changes: 14 additions & 2 deletions src/cli/shared/options.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
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';

// 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 <cmd> /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) {
Expand Down Expand Up @@ -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 <cmd> --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;
}

/**
Expand Down
78 changes: 78 additions & 0 deletions tests/unit/cli-shared-options-config-resolution.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading