import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { type MigrationPlan, parseFlags, type ResolvedChxConfig, type SchemaDefinition, } from '@chkit/core' import { saveCredentials } from './auth/credentials' import { isObsessionDBHost, obsessiondb, resolveStripBehavior, rewriteSharedEngines, stripSharedPrefix, } from './index' import { saveServiceAlias } from './service/storage' function makeConfig(url?: string): ResolvedChxConfig { return { schema: ['schema/**/*.ts'], outDir: '.chkit', migrationsDir: 'migrations', metaDir: '.chkit/meta', plugins: [], check: { unusedTables: true, unusedColumns: true }, safety: { allowDestructive: false }, ...(url ? { clickhouse: { url, username: 'default', password: '', database: 'default', secure: false, }, } : {}), } } function makeTable( name: string, engine: string, settings?: Record, ): SchemaDefinition { return { kind: 'table', database: 'default', name, columns: [{ name: 'id', type: 'UInt64' }], engine, primaryKey: ['id'], orderBy: ['id'], ...(settings ? { settings } : {}), } } function makeView(name: string): SchemaDefinition { return { kind: 'view', database: 'default', name, as: 'SELECT 1', } } function makeMaterializedView(name: string): SchemaDefinition { return { kind: 'materialized_view', database: 'default', name, to: { database: 'default', name: 'target' }, as: 'SELECT 1', } } describe('isObsessionDBHost', () => { test('matches obsessiondb.com subdomains', () => { expect(isObsessionDBHost('https://my-cluster.obsessiondb.com:8443')).toBe( true, ) expect(isObsessionDBHost('https://app.obsessiondb.com')).toBe(true) expect(isObsessionDBHost('https://obsessiondb.com')).toBe(true) }) test('matches numia-dev.com hosts', () => { expect(isObsessionDBHost('https://obsession.numia-dev.com:8443')).toBe(true) expect(isObsessionDBHost('https://ch.obsession.numia-dev.com')).toBe(true) }) test('does not match regular ClickHouse hosts', () => { expect(isObsessionDBHost('http://localhost:8123')).toBe(false) expect(isObsessionDBHost('https://clickhouse.example.com:8443')).toBe(false) expect(isObsessionDBHost('https://notobsessiondb.com')).toBe(false) }) test('returns false for invalid URLs', () => { expect(isObsessionDBHost('not-a-url')).toBe(false) expect(isObsessionDBHost('')).toBe(false) }) }) describe('stripSharedPrefix', () => { test('strips Shared prefix from engine names', () => { expect(stripSharedPrefix('SharedReplacingMergeTree(ingested_at)')).toBe( 'ReplacingMergeTree(ingested_at)', ) expect(stripSharedPrefix('SharedMergeTree')).toBe('MergeTree') expect(stripSharedPrefix('SharedAggregatingMergeTree')).toBe( 'AggregatingMergeTree', ) }) test('leaves non-Shared engines unchanged', () => { expect(stripSharedPrefix('MergeTree')).toBe('MergeTree') expect(stripSharedPrefix('ReplacingMergeTree(ts)')).toBe( 'ReplacingMergeTree(ts)', ) expect(stripSharedPrefix('Log')).toBe('Log') }) }) describe('rewriteSharedEngines', () => { test('rewrites Shared engines on tables', () => { const definitions: SchemaDefinition[] = [ makeTable('events', 'SharedReplacingMergeTree(ingested_at)'), makeTable('users', 'SharedMergeTree'), ] const result = rewriteSharedEngines(definitions) expect(result.count).toBe(2) expect((result.definitions[0] as { engine: string }).engine).toBe( 'ReplacingMergeTree(ingested_at)', ) expect((result.definitions[1] as { engine: string }).engine).toBe( 'MergeTree', ) }) test('skips views and materialized views', () => { const definitions: SchemaDefinition[] = [ makeTable('events', 'SharedMergeTree'), makeView('events_view'), makeMaterializedView('events_mv'), ] const result = rewriteSharedEngines(definitions) expect(result.count).toBe(1) expect(result.definitions).toHaveLength(3) expect(result.definitions[1]).toEqual(makeView('events_view')) expect(result.definitions[2]).toEqual(makeMaterializedView('events_mv')) }) test('skips tables without Shared prefix', () => { const definitions: SchemaDefinition[] = [ makeTable('events', 'MergeTree'), makeTable('users', 'ReplacingMergeTree(ts)'), ] const result = rewriteSharedEngines(definitions) expect(result.count).toBe(0) expect(result.definitions).toEqual(definitions) }) test('handles empty definitions', () => { const result = rewriteSharedEngines([]) expect(result.count).toBe(0) expect(result.definitions).toEqual([]) }) test('handles mix of Shared and non-Shared tables', () => { const definitions: SchemaDefinition[] = [ makeTable('events', 'SharedReplacingMergeTree(ts)'), makeTable('users', 'MergeTree'), makeTable('logs', 'SharedMergeTree'), ] const result = rewriteSharedEngines(definitions) expect(result.count).toBe(2) expect((result.definitions[0] as { engine: string }).engine).toBe( 'ReplacingMergeTree(ts)', ) expect((result.definitions[1] as { engine: string }).engine).toBe( 'MergeTree', ) expect((result.definitions[2] as { engine: string }).engine).toBe( 'MergeTree', ) }) test('strips storage_policy from table settings', () => { const definitions: SchemaDefinition[] = [ makeTable('events', 'MergeTree', { storage_policy: "'s3'", index_granularity: 8192, }), ] const result = rewriteSharedEngines(definitions) expect(result.strippedSettings).toEqual(['storage_policy']) const table = result.definitions[0] as { settings?: Record } expect(table.settings).toEqual({ index_granularity: 8192 }) }) test('removes settings entirely when storage_policy is the only setting', () => { const definitions: SchemaDefinition[] = [ makeTable('events', 'MergeTree', { storage_policy: "'s3'" }), ] const result = rewriteSharedEngines(definitions) expect(result.strippedSettings).toEqual(['storage_policy']) const table = result.definitions[0] as { settings?: Record } expect(table.settings).toBeUndefined() }) test('strips storage_policy and Shared engine together', () => { const definitions: SchemaDefinition[] = [ makeTable('events', 'SharedMergeTree', { storage_policy: "'s3'", index_granularity: 4096, }), ] const result = rewriteSharedEngines(definitions) expect(result.count).toBe(1) expect(result.strippedSettings).toEqual(['storage_policy']) const table = result.definitions[0] as { engine: string settings?: Record } expect(table.engine).toBe('MergeTree') expect(table.settings).toEqual({ index_granularity: 4096 }) }) test('does not strip non-cloud settings', () => { const definitions: SchemaDefinition[] = [ makeTable('events', 'MergeTree', { index_granularity: 8192 }), ] const result = rewriteSharedEngines(definitions) expect(result.strippedSettings).toEqual([]) expect(result.definitions).toEqual(definitions) }) }) describe('resolveStripBehavior', () => { test('--force-shared-engines prevents stripping', () => { const config = makeConfig('http://localhost:8123') expect(resolveStripBehavior(config, { '--force-shared-engines': true })).toBe( false, ) }) test('--no-shared-engines forces stripping', () => { const config = makeConfig('https://my-cluster.obsessiondb.com:8443') expect(resolveStripBehavior(config, { '--no-shared-engines': true })).toBe( true, ) }) test('--force-shared-engines takes precedence over --no-shared-engines', () => { const config = makeConfig('http://localhost:8123') expect( resolveStripBehavior(config, { '--force-shared-engines': true, '--no-shared-engines': true, }), ).toBe(false) }) test('reads the overrides under the keys the CLI flag parser produces', () => { // The CLI parses argv with the flag definitions the plugin registers, so // resolve through that parser rather than hand-written keys: the plugin // once read `flags['force-shared-engines']` and both overrides were ignored. const flagDefs = obsessiondb().plugin.extendCommands[0]?.flags ?? [] expect( resolveStripBehavior( makeConfig('http://localhost:8123'), parseFlags(['--force-shared-engines'], flagDefs), ), ).toBe(false) expect( resolveStripBehavior( makeConfig('https://my-cluster.obsessiondb.com:8443'), parseFlags(['--no-shared-engines'], flagDefs), ), ).toBe(true) }) test('auto-detects ObsessionDB host and keeps Shared engines', () => { const config = makeConfig('https://my-cluster.obsessiondb.com:8443') expect(resolveStripBehavior(config, {})).toBe(false) }) test('auto-detects regular ClickHouse and strips Shared engines', () => { const config = makeConfig('http://localhost:8123') expect(resolveStripBehavior(config, {})).toBe(true) }) test('strips when no clickhouse config is present', () => { const config = makeConfig() expect(resolveStripBehavior(config, {})).toBe(true) }) }) describe('obsessiondb plugin', () => { test('registers extendCommands for generate, migrate, status, drift, check, snapshot', () => { const registration = obsessiondb() const ext = registration.plugin.extendCommands[0] expect(ext?.command).toEqual([ 'generate', 'migrate', 'status', 'drift', 'check', 'snapshot', ]) expect(ext?.flags).toHaveLength(2) expect(ext?.flags[0]?.name).toBe('--force-shared-engines') expect(ext?.flags[1]?.name).toBe('--no-shared-engines') }) test('describes the override flags by the setting they control and where they apply', () => { // Core canonicalization writes the standard engine name for every target, // so the flags only decide whether storage_policy is stripped, and only // generate and snapshot rebuild run that rewrite. The help once claimed // --force-shared-engines kept Shared engines. const flags = obsessiondb().plugin.extendCommands[0]?.flags ?? [] expect(flags).toHaveLength(2) for (const flag of flags) { expect(flag.description).toContain('storage_policy') expect(flag.description).toContain('generate and snapshot rebuild') expect(flag.description).not.toMatch(/Shared engine/i) } }) test('onSchemaLoaded strips Shared engines for regular ClickHouse', () => { const registration = obsessiondb() const definitions: SchemaDefinition[] = [ makeTable('events', 'SharedReplacingMergeTree(ts)'), makeTable('users', 'MergeTree'), makeView('events_view'), ] const result = registration.plugin.hooks.onSchemaLoaded({ config: makeConfig('http://localhost:8123'), flags: {}, definitions, }) expect(result).toBeDefined() expect(result).toHaveLength(3) expect((result?.[0] as { engine: string }).engine).toBe( 'ReplacingMergeTree(ts)', ) expect((result?.[1] as { engine: string }).engine).toBe('MergeTree') expect(result?.[2]).toEqual(makeView('events_view')) }) test('onSchemaLoaded honors parsed override flags for storage_policy', () => { const registration = obsessiondb() const flagDefs = registration.plugin.extendCommands[0]?.flags ?? [] const definitions: SchemaDefinition[] = [ makeTable('events', 'MergeTree', { storage_policy: "'hot_cold'" }), ] const kept = registration.plugin.hooks.onSchemaLoaded({ config: makeConfig('http://localhost:8123'), flags: parseFlags(['--force-shared-engines'], flagDefs), definitions, }) // Kept as written: not a recognized ObsessionDB host, so no storage_policy rules apply. expect(kept).toBeUndefined() const stripped = registration.plugin.hooks.onSchemaLoaded({ config: makeConfig('https://my-cluster.obsessiondb.com:8443'), flags: parseFlags(['--no-shared-engines'], flagDefs), definitions, }) expect( (stripped?.[0] as { settings?: Record }).settings, ).toBeUndefined() }) test('onSchemaLoaded keeps Shared engines for ObsessionDB hosts', () => { const registration = obsessiondb() const definitions: SchemaDefinition[] = [ makeTable('events', 'SharedReplacingMergeTree(ts)'), ] const result = registration.plugin.hooks.onSchemaLoaded({ config: makeConfig('https://my-cluster.obsessiondb.com:8443'), flags: {}, definitions, }) expect((result?.[0] as { engine: string }).engine).toBe('SharedReplacingMergeTree(ts)') }) // ObsessionDB writes storage_policy = 's3' into every Shared table, so pull // reads it back; on ObsessionDB the schema and the snapshot both carry it (#466). test("an ObsessionDB target gives every MergeTree table storage_policy = 's3', in the schema and the snapshot", () => { const registration = obsessiondb() const definitions: SchemaDefinition[] = [ makeTable('events', 'MergeTree', { index_granularity: '8192' }), makeTable('pulled', 'MergeTree', { storage_policy: "'s3'" }), makeTable('hot', 'MergeTree', { storage_policy: "'hot_cold'" }), ] const settingsOf = (result: SchemaDefinition[] | undefined) => result?.map((def) => (def as { settings?: Record }).settings) const obsession = makeConfig('https://my-cluster.obsessiondb.com:8443') const expected = [ { index_granularity: '8192', storage_policy: "'s3'" }, { storage_policy: "'s3'" }, { storage_policy: "'hot_cold'" }, ] expect(settingsOf(registration.plugin.hooks.onSchemaLoaded({ config: obsession, flags: {}, definitions }))).toEqual(expected) expect(settingsOf(registration.plugin.hooks.onSnapshotLoaded({ config: obsession, flags: {}, definitions }))).toEqual(expected) // Regular ClickHouse strips every storage_policy, on both sides. const local = makeConfig('http://localhost:8123') expect(settingsOf(registration.plugin.hooks.onSnapshotLoaded({ config: local, flags: {}, definitions }))).toEqual([ { index_granularity: '8192' }, undefined, undefined, ]) // --force-shared-engines on another host may be a self-hosted server with its own policies: kept as is. const forced = { config: local, flags: { '--force-shared-engines': true }, definitions } expect(settingsOf(registration.plugin.hooks.onSnapshotLoaded(forced))).toEqual(settingsOf(definitions)) }) test('an ObsessionDB target rejects a plan that changes storage_policy', () => { const registration = obsessiondb() const plan = { operations: [ { type: 'alter_table_modify_setting', key: 'table:app.events:setting:storage_policy', risk: 'caution', sql: "ALTER TABLE app.events MODIFY SETTING storage_policy = 'default';" }, ], riskSummary: { safe: 0, caution: 1, danger: 0 }, } as unknown as MigrationPlan const run = (url: string) => () => registration.plugin.hooks.onPlanCreated({ config: makeConfig(url), flags: {}, plan }) expect(run('https://my-cluster.obsessiondb.com:8443')).toThrow('app.events cannot change storage_policy') expect(run('http://localhost:8123')()).toBeUndefined() }) test('onSchemaLoaded returns undefined when no Shared engines exist', () => { const registration = obsessiondb() const definitions: SchemaDefinition[] = [makeTable('events', 'MergeTree')] const result = registration.plugin.hooks.onSchemaLoaded({ config: makeConfig('http://localhost:8123'), flags: {}, definitions, }) expect(result).toBeDefined() expect(result).toHaveLength(1) }) }) describe('Distributed tables on ObsessionDB (#279)', () => { const OBSESSIONDB_URL = 'https://my-cluster.obsessiondb.com:8443' const distributed = makeTable('events', "Distributed('cluster', 'default', 'events_local', rand())") const message = 'Table default.events uses the Distributed engine, which ObsessionDB does not support: ObsessionDB has no shards, so every replica already reads the same shared storage. Remove the Distributed table from the schema and query or insert into its local table directly.' test('onSchemaLoaded rejects a Distributed table when targeting ObsessionDB', () => { const { hooks } = obsessiondb().plugin const load = (url: string, flags: Record = {}) => () => hooks.onSchemaLoaded({ config: makeConfig(url), flags, definitions: [distributed] }) expect(load(OBSESSIONDB_URL)).toThrow(message) expect(load('http://localhost:8123', { '--force-shared-engines': true })).toThrow(message) }) test('onSchemaLoaded keeps a Distributed table for regular ClickHouse', () => { const result = obsessiondb().plugin.hooks.onSchemaLoaded({ config: makeConfig('http://localhost:8123'), flags: {}, definitions: [distributed], }) expect(result).toEqual([distributed]) }) test('onCheck reports Distributed tables in the schema only for ObsessionDB', async () => { const dir = await mkdtemp(join(tmpdir(), 'chkit-obsessiondb-distributed-')) try { await writeFile(join(dir, 'schema.ts'), `export const events = ${JSON.stringify(distributed)}\n`) const configPath = join(dir, 'clickhouse.config.ts') const check = (url: string) => obsessiondb().plugin.hooks.onCheck({ config: { ...makeConfig(url), schema: ['schema.ts'] }, configPath, flags: {}, }) expect(await check(OBSESSIONDB_URL)).toEqual({ plugin: 'obsessiondb', evaluated: true, ok: false, findings: [{ code: 'obsessiondb_distributed_unsupported', message, severity: 'error' }], }) expect(await check('http://localhost:8123')).toBeUndefined() } finally { await rm(dir, { recursive: true, force: true }) } }) }) describe('obsessiondb onInit', () => { let tempDir: string let originalXdg: string | undefined const originalFetch = globalThis.fetch afterEach(async () => { globalThis.fetch = originalFetch if (originalXdg !== undefined) { process.env.XDG_CONFIG_HOME = originalXdg } else { delete process.env.XDG_CONFIG_HOME } if (tempDir) { await rm(tempDir, { recursive: true, force: true }) } }) async function setupAuth() { tempDir = await mkdtemp(join(tmpdir(), 'chkit-obd-')) originalXdg = process.env.XDG_CONFIG_HOME process.env.XDG_CONFIG_HOME = tempDir await saveCredentials({ access_token: 'test-tok', base_url: 'https://api.test.com', }) } test('prints the overridden service when --service is provided', async () => { await setupAuth() globalThis.fetch = mock( async () => new Response( JSON.stringify({ json: { organizations: [ { id: 'org-1', name: 'Org', slug: 'org', services: [ { id: 'svc-prod', name: 'prod', status: 'running', tier: 1, nodes: 1, connectionUrl: null, connectionUsername: null, desiredStatus: 'running', desiredTier: 1, desiredNodes: 1, createdAt: '2026-03-29T00:00:00Z', managed: true, }, ], }, ], }, }), { status: 200, headers: { 'content-type': 'application/json' } }, ), ) as typeof fetch const log = spyOn(console, 'log').mockImplementation(() => {}) const plugin = obsessiondb().plugin await plugin.hooks.onInit({ command: 'query', configPath: '/fake/clickhouse.config.ts', isInteractive: false, jsonMode: false, flags: { '--service': 'prod' }, }) expect(log.mock.calls.flat().join('\n')).toContain('using service "prod"') log.mockRestore() }) test('warns "no service selected" when authenticated with no service and no clickhouse target (#38)', async () => { await setupAuth() const log = spyOn(console, 'log').mockImplementation(() => {}) const plugin = obsessiondb().plugin await plugin.hooks.onInit({ command: 'status', configPath: join(tempDir, 'clickhouse.config.ts'), isInteractive: false, jsonMode: false, flags: {}, }) expect(log.mock.calls.flat().join('\n')).toContain('authenticated but no service selected') log.mockRestore() }) test('suppresses the "no service selected" notice when a direct clickhouse target is configured (#38)', async () => { await setupAuth() const log = spyOn(console, 'log').mockImplementation(() => {}) const plugin = obsessiondb().plugin await plugin.hooks.onInit({ command: 'status', configPath: join(tempDir, 'clickhouse.config.ts'), isInteractive: false, jsonMode: false, flags: {}, config: { clickhouse: { url: 'https://x', username: 'u', password: 'p', database: 'd' }, } as never, }) // ObsessionDB was layered in from a global login, not chosen for this // project, so the reminder is noise for a user with their own target. expect(log.mock.calls.flat().join('\n')).not.toContain('authenticated but no service selected') log.mockRestore() }) }) describe('obsessiondb getContext', () => { let tempDir: string let originalXdg: string | undefined const originalFetch = globalThis.fetch afterEach(async () => { globalThis.fetch = originalFetch if (originalXdg !== undefined) { process.env.XDG_CONFIG_HOME = originalXdg } else { delete process.env.XDG_CONFIG_HOME } if (tempDir) { await rm(tempDir, { recursive: true, force: true }) } }) async function setupAuth() { tempDir = await mkdtemp(join(tmpdir(), 'chkit-obd-')) originalXdg = process.env.XDG_CONFIG_HOME process.env.XDG_CONFIG_HOME = tempDir await saveCredentials({ access_token: 'test-tok', base_url: 'https://api.test.com', }) } test('query reports an actionable error when authenticated without selected service', async () => { await setupAuth() const plugin = obsessiondb().plugin await expect( plugin.hooks.getContext({ config: makeConfig(), configPath: join(tempDir, 'chkit', 'clickhouse.config.ts'), command: 'query', flags: {}, defaults: {}, }), ).rejects.toThrow(/service select/) }) test('resolves --service through a saved alias', async () => { await setupAuth() const configPath = join(tempDir, 'project', 'clickhouse.config.ts') await saveServiceAlias(configPath, 'prod', { service_slug: 'svc-prod', service_name: 'production', }) globalThis.fetch = mock( async () => new Response( JSON.stringify({ json: { organizations: [ { id: 'org-1', name: 'Org', slug: 'org', services: [ { id: 'svc-other', name: 'other', status: 'running', tier: 1, nodes: 1, connectionUrl: null, connectionUsername: null, desiredStatus: 'running', desiredTier: 1, desiredNodes: 1, createdAt: '2026-03-29T00:00:00Z', managed: true, }, ], }, ], }, }), { status: 200, headers: { 'content-type': 'application/json' } }, ), ) as typeof fetch const plugin = obsessiondb().plugin const context = await plugin.hooks.getContext({ config: makeConfig(), configPath, command: 'query', flags: { '--service': 'prod' }, defaults: {}, }) expect(context).toBeDefined() }) }) describe('onBeforePluginCommand — backfill interception', () => { let tempDir: string let originalXdg: string | undefined const originalFetch = globalThis.fetch afterEach(async () => { globalThis.fetch = originalFetch if (originalXdg !== undefined) { process.env.XDG_CONFIG_HOME = originalXdg } else { delete process.env.XDG_CONFIG_HOME } if (tempDir) { await rm(tempDir, { recursive: true, force: true }) } }) function makeHookContext(overrides: Record = {}) { const printed: unknown[] = [] return { context: { targetPlugin: 'backfill', command: 'status', config: {}, configPath: '/fake/clickhouse.config.ts', jsonMode: false, args: [], flags: { '--job-id': 'job-123' }, options: {}, print: (v: unknown) => printed.push(v), ...overrides, }, printed, } } async function setupAuth() { tempDir = await mkdtemp(join(tmpdir(), 'chkit-obd-')) originalXdg = process.env.XDG_CONFIG_HOME process.env.XDG_CONFIG_HOME = tempDir await saveCredentials({ access_token: 'test-tok', base_url: 'https://api.test.com', }) } test('intercepts backfill commands when authenticated', async () => { await setupAuth() const jobDetail = { id: 'job-123', serviceId: 'svc-1', type: 'backfill', target: 'my_table', status: 'running', concurrency: 4, totalTasks: 10, completedTasks: 3, failedTasks: 0, createdAt: '2026-03-29T00:00:00Z', updatedAt: '2026-03-29T01:00:00Z', workflowId: null, metadata: null, tasks: [], } globalThis.fetch = mock( async () => new Response(JSON.stringify({ json: jobDetail }), { status: 200, headers: { 'content-type': 'application/json' }, }), ) as typeof fetch const { context, printed } = makeHookContext() const plugin = obsessiondb().plugin const result = await plugin.hooks.onBeforePluginCommand( context as Parameters[0], ) expect(result.handled).toBe(true) expect(result.exitCode).toBe(0) expect(printed[0]).toContain('Backfill job job-123 (my_table): running') }) test('requires login when not authenticated', async () => { tempDir = await mkdtemp(join(tmpdir(), 'chkit-obd-')) originalXdg = process.env.XDG_CONFIG_HOME process.env.XDG_CONFIG_HOME = tempDir const { context, printed } = makeHookContext({ command: 'status', flags: { '--job-id': 'job-1' }, }) const plugin = obsessiondb().plugin const result = await plugin.hooks.onBeforePluginCommand( context as Parameters[0], ) expect(result.handled).toBe(true) expect(result.exitCode).toBe(1) expect(printed[0]).toContain('chkit obsessiondb login') }) test('falls through with --local flag even when authenticated', async () => { await setupAuth() const { context } = makeHookContext({ flags: { '--local': true } }) const plugin = obsessiondb().plugin const result = await plugin.hooks.onBeforePluginCommand( context as Parameters[0], ) expect(result.handled).toBe(false) }) test('falls through for non-backfill plugins', async () => { await setupAuth() const { context } = makeHookContext({ targetPlugin: 'codegen' }) const plugin = obsessiondb().plugin const result = await plugin.hooks.onBeforePluginCommand( context as Parameters[0], ) expect(result.handled).toBe(false) }) }) describe('command extensions register against the right command keys', () => { const extensions = obsessiondb().plugin.extendCommands const targetsOf = (flagName: string): string[] => { const ext = extensions.find((e) => e.flags.some((f) => f.name === flagName)) return ext ? (Array.isArray(ext.command) ? ext.command : [ext.command]) : [] } test('every extension targets a top-level command name (no two-word subcommand targets)', () => { // The registry keys plugin extensions by top-level command name // (byName.get(target)); a two-word target like "backfill run" never matches, // so the flag would silently never register and the CLI rejects it as unknown. const allTargets = extensions.flatMap((e) => Array.isArray(e.command) ? e.command : [e.command], ) expect(allTargets.length).toBeGreaterThan(0) for (const target of allTargets) { expect(target).not.toContain(' ') } }) test('--service override is offered on pull', () => { expect(targetsOf('--service')).toContain('pull') }) test('--local is registered against the backfill command', () => { expect(targetsOf('--local')).toContain('backfill') }) })