From 61026767a805e1396eacca6a13b50dbc3f86d52a Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 15:45:59 +1100 Subject: [PATCH 1/2] fix(cli): let --database-url win in stash eql preflight A user who passed --database-url to stash eql preflight from inside a project whose stash.config.ts set a literal databaseUrl got the report for the config's database, not the one they named. The only sign was one warning line, which went to stderr in --json mode. They could then choose column types that the database they meant cannot support. Preflight now resolves the URL the way stash eql verify and stash eql install already do: an explicit --database-url skips config loading. With no flag, it still uses the config's databaseUrl if it finds a stash.config.ts, and otherwise the DATABASE_URL chain. Both callers of resolveDiagnosticDatabaseUrl now let the flag win, so the flagWins option and the config-precedence warning it guarded are removed rather than kept with one value. Refs #1966 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- .changeset/cli-preflight-flag-wins.md | 12 ++ .../__tests__/preflight-database-url.test.ts | 107 ++++++++++++++++++ .../packages/cli/src/commands/db/preflight.ts | 12 +- .../src/commands/db/resolve-diagnostic-url.ts | 42 +++---- .../packages/cli/src/commands/eql/verify.ts | 2 - skills/stash-cli/SKILL.md | 4 +- 6 files changed, 139 insertions(+), 40 deletions(-) create mode 100644 .changeset/cli-preflight-flag-wins.md create mode 100644 languages/typescript/packages/cli/src/commands/db/__tests__/preflight-database-url.test.ts diff --git a/.changeset/cli-preflight-flag-wins.md b/.changeset/cli-preflight-flag-wins.md new file mode 100644 index 0000000000..934c566b30 --- /dev/null +++ b/.changeset/cli-preflight-flag-wins.md @@ -0,0 +1,12 @@ +--- +"stash": patch +--- + +`stash eql preflight --database-url ` now probes the database you name, +even when a `stash.config.ts` in the current folder or a folder above it sets a +literal `databaseUrl`. Before, preflight probed the config's database instead +and printed only a warning, so you could read the capabilities of the wrong +database. Preflight now matches `stash eql verify` and `stash eql install`, +where an explicit `--database-url` already wins. With no flag, nothing changes: +preflight uses the config's `databaseUrl` if it finds a `stash.config.ts`, and +otherwise the usual `DATABASE_URL` chain. diff --git a/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-database-url.test.ts b/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-database-url.test.ts new file mode 100644 index 0000000000..24dfbe13a0 --- /dev/null +++ b/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-database-url.test.ts @@ -0,0 +1,107 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { PreflightResult } from '@/installer/index.js' + +// Which database `stash eql preflight` probes, with and without +// `--database-url`, when a stash.config.ts sets a literal `databaseUrl` (#1966). +// The config file is real and loaded through the real loader; only the +// database is faked, by recording the URL the installer is built with. + +const probedUrls: string[] = [] + +const CAPABLE: PreflightResult = { + currentUser: 'postgres', + isSuperuser: true, + memberOfPostgres: true, + hasDatabaseCreate: true, + hasPublicCreate: true, + pgcryptoInstalled: true, + pgcryptoSchema: 'extensions', + eqlV3SchemaPresent: false, + eqlV3InternalSchemaPresent: false, + canDropEqlV3Schema: null, + canDropEqlV3InternalSchema: null, + canCreateOperatorClass: true, + missing: [], + ok: true, +} + +vi.mock('@clack/prompts', () => ({ + intro: vi.fn(), + outro: vi.fn(), + note: vi.fn(), + spinner: () => ({ start: vi.fn(), stop: vi.fn() }), + log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), step: vi.fn() }, +})) +vi.mock('@/installer/index.js', () => ({ + EQLInstaller: class { + constructor({ databaseUrl }: { databaseUrl: string }) { + probedUrls.push(databaseUrl) + } + preflight = () => Promise.resolve(CAPABLE) + }, +})) + +const CONFIG_URL = 'postgres://config-host/config_db' +const FLAG_URL = 'postgres://flag-host/flag_db' +const ENV_URL = 'postgres://env-host/env_db' + +let projectDir: string + +function writeLiteralConfig(): void { + fs.writeFileSync( + path.join(projectDir, 'stash.config.ts'), + `export default { databaseUrl: '${CONFIG_URL}' }\n`, + ) +} + +beforeEach(() => { + probedUrls.length = 0 + projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'stash-preflight-')) + vi.spyOn(process, 'cwd').mockReturnValue(projectDir) + vi.stubEnv('DATABASE_URL', ENV_URL) +}) + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + fs.rmSync(projectDir, { recursive: true, force: true }) +}) + +describe('stash eql preflight database URL', () => { + it('probes the --database-url database, not the config literal', async () => { + writeLiteralConfig() + const { preflightCommand } = await import('../preflight.js') + await preflightCommand({ databaseUrl: FLAG_URL }) + expect(probedUrls).toEqual([FLAG_URL]) + }) + + it('probes the --database-url database in --json mode, with no warning', async () => { + writeLiteralConfig() + const stdout = vi.spyOn(console, 'log').mockImplementation(() => {}) + const stderr = vi + .spyOn(process.stderr, 'write') + .mockImplementation(() => true) + const { preflightCommand } = await import('../preflight.js') + await preflightCommand({ databaseUrl: FLAG_URL, json: true }) + expect(probedUrls).toEqual([FLAG_URL]) + expect(stderr).not.toHaveBeenCalled() + expect(String(stdout.mock.calls[0]?.[0])).toContain('"status":"ok"') + }) + + it('probes the config literal when no flag is given', async () => { + writeLiteralConfig() + const { preflightCommand } = await import('../preflight.js') + await preflightCommand({}) + expect(probedUrls).toEqual([CONFIG_URL]) + }) + + it('falls back to DATABASE_URL when there is no flag and no config', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + const { preflightCommand } = await import('../preflight.js') + await preflightCommand({ json: true }) + expect(probedUrls).toEqual([ENV_URL]) + }) +}) diff --git a/languages/typescript/packages/cli/src/commands/db/preflight.ts b/languages/typescript/packages/cli/src/commands/db/preflight.ts index b60c533973..85ea083756 100644 --- a/languages/typescript/packages/cli/src/commands/db/preflight.ts +++ b/languages/typescript/packages/cli/src/commands/db/preflight.ts @@ -5,17 +5,15 @@ import { EQLInstaller, type PreflightResult } from '@/installer/index.js' import { describeOreCreatable, ORE_FALLBACK_REMEDY } from '@/installer/ore.js' import { resolveDiagnosticDatabaseUrl } from './resolve-diagnostic-url.js' -/** See {@link resolveDiagnosticDatabaseUrl} — preflight keeps config-wins. */ +/** + * An explicit `--database-url` wins over a stash.config.ts literal, as it + * does in `eql verify`. See {@link resolveDiagnosticDatabaseUrl}. + */ function resolvePreflightDatabaseUrl( databaseUrlFlag: string | undefined, json: boolean, ): Promise { - return resolveDiagnosticDatabaseUrl({ - databaseUrlFlag, - json, - flagWins: false, - verb: 'Probing', - }) + return resolveDiagnosticDatabaseUrl({ databaseUrlFlag, json }) } /** diff --git a/languages/typescript/packages/cli/src/commands/db/resolve-diagnostic-url.ts b/languages/typescript/packages/cli/src/commands/db/resolve-diagnostic-url.ts index e1629d07ea..830bf1eb31 100644 --- a/languages/typescript/packages/cli/src/commands/db/resolve-diagnostic-url.ts +++ b/languages/typescript/packages/cli/src/commands/db/resolve-diagnostic-url.ts @@ -1,4 +1,3 @@ -import * as p from '@clack/prompts' import { resolveDatabaseUrl } from '@/config/database-url.js' import { findConfigFile, loadStashConfig } from '@/config/index.js' @@ -12,27 +11,23 @@ import { findConfigFile, loadStashConfig } from '@/config/index.js' * and failures come out as the shared `{ status: 'error', code, message }` * envelope (`jsonErrors`). * - * The two commands differ on one deliberate point, `flagWins`: + * An explicit `--database-url` always wins. It bypasses config loading + * entirely, as it does for `stash eql install --database-url …`, so the + * database the user named is the database that gets judged. A hand-set + * literal `databaseUrl` in a stash.config.ts found up the directory tree must + * not redirect a diagnostic to a different database: preflight would then + * report the capabilities of a database the user did not name, and the user + * would choose column types from that answer (#1966). * - * - `false` (preflight): mirrors `installCommand`'s config-loading path — a - * hand-set literal `databaseUrl` in stash.config.ts beats `--database-url`. - * Surprising enough to say out loud, to stderr in json mode. - * - `true` (verify): mirrors `installCommand`'s one-shot path — an explicit - * `--database-url` bypasses config loading entirely, so the database the - * user named is the database that gets judged. Verify pairs with one-shot - * installs (`stash eql install --database-url …`), and a config literal - * found up the directory tree silently redirecting the verdict to a - * different database would defeat the flag's whole purpose. + * With no flag, the order is: the config's `databaseUrl` if a stash.config.ts + * is found, else the DATABASE_URL resolution chain. */ export async function resolveDiagnosticDatabaseUrl(options: { databaseUrlFlag: string | undefined json: boolean - flagWins: boolean - /** Present-participle for the config-precedence warning, e.g. `Probing`. */ - verb: string }): Promise { - const { databaseUrlFlag, json, flagWins, verb } = options - if (flagWins && databaseUrlFlag !== undefined) { + const { databaseUrlFlag, json } = options + if (databaseUrlFlag !== undefined) { return resolveDatabaseUrl({ databaseUrlFlag, quiet: json, @@ -42,21 +37,10 @@ export async function resolveDiagnosticDatabaseUrl(options: { const configPath = findConfigFile(process.cwd()) if (configPath) { const config = await loadStashConfig( - { databaseUrlFlag, quiet: json, jsonErrors: json }, + { quiet: json, jsonErrors: json }, configPath, ) - if ( - databaseUrlFlag !== undefined && - config.databaseUrl !== databaseUrlFlag.trim() - ) { - const warning = `Ignoring --database-url: ${configPath} sets an explicit databaseUrl that takes precedence. ${verb} the config's database.` - if (json) { - process.stderr.write(`${warning}\n`) - } else { - p.log.warn(warning) - } - } return config.databaseUrl } - return resolveDatabaseUrl({ databaseUrlFlag, quiet: json, jsonErrors: json }) + return resolveDatabaseUrl({ quiet: json, jsonErrors: json }) } diff --git a/languages/typescript/packages/cli/src/commands/eql/verify.ts b/languages/typescript/packages/cli/src/commands/eql/verify.ts index d26afad275..c63bc90185 100644 --- a/languages/typescript/packages/cli/src/commands/eql/verify.ts +++ b/languages/typescript/packages/cli/src/commands/eql/verify.ts @@ -38,8 +38,6 @@ export async function verifyCommand( const databaseUrl = await resolveDiagnosticDatabaseUrl({ databaseUrlFlag: options.databaseUrl, json, - flagWins: true, - verb: 'Verifying', }) const s = json ? null : p.spinner() diff --git a/skills/stash-cli/SKILL.md b/skills/stash-cli/SKILL.md index 4ea65c39ca..45c89ebfad 100644 --- a/skills/stash-cli/SKILL.md +++ b/skills/stash-cli/SKILL.md @@ -156,7 +156,7 @@ First hit wins: 4. Interactive prompt — skipped under CI / non-TTY 5. Hard fail, naming the sources it tried -`stash.config.ts` is **not** a separate tier: the scaffolded config calls this same resolver, and the `--database-url` flag still wins. The one exception is a hand-edited config assigning a literal `databaseUrl` string — that bypasses the resolver entirely and beats both flag and env. +`stash.config.ts` is **not** a separate tier: the scaffolded config calls this same resolver, and the `--database-url` flag still wins. The one exception is a hand-edited config assigning a literal `databaseUrl` string — that bypasses the resolver entirely and beats both flag and env. `eql install`, `eql preflight`, and `eql verify` are the exceptions to that exception: an explicit `--database-url` skips config loading in those three, so the flag wins there. The resolved URL is returned in memory only. It is never written to disk or into `process.env`. @@ -377,7 +377,7 @@ Membership of `postgres` is reported but never blocks: `eql install` handles a n | Flag | Description | |---|---| | `--json` | Machine-readable result instead of the table. Stdout is pure JSON even on failure: success is `{ status: 'ok', ... }`, blockers are `{ status: 'blocked', ... }` (exit 1), and failures — including a missing/malformed DATABASE_URL — are the shared `{ status: 'error', code, message }` envelope | -| `--database-url ` | Probe that database (no config needed). A hand-set literal `databaseUrl` in stash.config.ts still wins, with a warning (stderr in `--json` mode) | +| `--database-url ` | One-shot, like `eql verify`'s: bypasses config loading entirely, so the database you name is the database that gets probed, even when a stash.config.ts sets a literal `databaseUrl`. With no flag, preflight uses the config's `databaseUrl` if it finds a stash.config.ts, else the usual `DATABASE_URL` chain | #### `eql install` From 967d4f8e9bfcef9b3d714cd32f253bfbe81ee331 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 16:11:22 +1100 Subject: [PATCH 2/2] fix(cli): describe preflight's --database-url precedence in its help The preflight help used the shared --database-url text, which says a literal databaseUrl in stash.config.ts wins. After the previous commit that is wrong for preflight, so it now has its own description, as verify does. The stash-cli skill now also names eql repair, which never loads the config and so lets the flag win too. Also from review: call resolveDiagnosticDatabaseUrl directly from preflight instead of through a forwarding wrapper, share the CAPABLE preflight fixture between the two test files, and make the no-config test name a stray stash.config.ts above the temporary folder rather than fail on a URL mismatch. Refs #1966 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- .../packages/cli/src/cli/registry.ts | 8 ++++- .../__tests__/preflight-database-url.test.ts | 24 ++++---------- .../db/__tests__/preflight-fixtures.ts | 19 ++++++++++++ .../commands/db/__tests__/preflight.test.ts | 19 +----------- .../packages/cli/src/commands/db/preflight.ts | 31 +++++++------------ skills/stash-cli/SKILL.md | 2 +- 6 files changed, 46 insertions(+), 57 deletions(-) create mode 100644 languages/typescript/packages/cli/src/commands/db/__tests__/preflight-fixtures.ts diff --git a/languages/typescript/packages/cli/src/cli/registry.ts b/languages/typescript/packages/cli/src/cli/registry.ts index 26e45bdfde..6d2a6c01e9 100644 --- a/languages/typescript/packages/cli/src/cli/registry.ts +++ b/languages/typescript/packages/cli/src/cli/registry.ts @@ -336,7 +336,13 @@ export const registry: CommandGroup[] = [ description: 'Emit the machine-readable preflight result instead of the table.', }, - DATABASE_URL_FLAG, + { + name: '--database-url', + value: '', + description: + "One-shot, like `eql verify`'s: bypasses config loading entirely, so the database you name is the database that gets probed, even when stash.config.ts sets a literal databaseUrl.", + env: 'DATABASE_URL', + }, ], }, { diff --git a/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-database-url.test.ts b/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-database-url.test.ts index 24dfbe13a0..10639f39e1 100644 --- a/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-database-url.test.ts +++ b/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-database-url.test.ts @@ -2,7 +2,8 @@ import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PreflightResult } from '@/installer/index.js' +import { findConfigFile } from '@/config/index.js' +import { CAPABLE } from './preflight-fixtures.js' // Which database `stash eql preflight` probes, with and without // `--database-url`, when a stash.config.ts sets a literal `databaseUrl` (#1966). @@ -11,23 +12,6 @@ import type { PreflightResult } from '@/installer/index.js' const probedUrls: string[] = [] -const CAPABLE: PreflightResult = { - currentUser: 'postgres', - isSuperuser: true, - memberOfPostgres: true, - hasDatabaseCreate: true, - hasPublicCreate: true, - pgcryptoInstalled: true, - pgcryptoSchema: 'extensions', - eqlV3SchemaPresent: false, - eqlV3InternalSchemaPresent: false, - canDropEqlV3Schema: null, - canDropEqlV3InternalSchema: null, - canCreateOperatorClass: true, - missing: [], - ok: true, -} - vi.mock('@clack/prompts', () => ({ intro: vi.fn(), outro: vi.fn(), @@ -99,6 +83,10 @@ describe('stash eql preflight database URL', () => { }) it('falls back to DATABASE_URL when there is no flag and no config', async () => { + // findConfigFile walks up to the filesystem root, so a stray + // stash.config.ts above the temporary folder would break this case. Name + // it here rather than fail on a confusing URL mismatch. + expect(findConfigFile(projectDir)).toBeUndefined() vi.spyOn(console, 'log').mockImplementation(() => {}) const { preflightCommand } = await import('../preflight.js') await preflightCommand({ json: true }) diff --git a/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-fixtures.ts b/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-fixtures.ts new file mode 100644 index 0000000000..7b5e95c734 --- /dev/null +++ b/languages/typescript/packages/cli/src/commands/db/__tests__/preflight-fixtures.ts @@ -0,0 +1,19 @@ +import type { PreflightResult } from '@/installer/index.js' + +/** A preflight result for a role that can install EQL with no gaps. */ +export const CAPABLE: PreflightResult = { + currentUser: 'postgres', + isSuperuser: true, + memberOfPostgres: true, + hasDatabaseCreate: true, + hasPublicCreate: true, + pgcryptoInstalled: true, + pgcryptoSchema: 'extensions', + eqlV3SchemaPresent: false, + eqlV3InternalSchemaPresent: false, + canDropEqlV3Schema: null, + canDropEqlV3InternalSchema: null, + canCreateOperatorClass: true, + missing: [], + ok: true, +} diff --git a/languages/typescript/packages/cli/src/commands/db/__tests__/preflight.test.ts b/languages/typescript/packages/cli/src/commands/db/__tests__/preflight.test.ts index dbdf788557..e6c2cbb97a 100644 --- a/languages/typescript/packages/cli/src/commands/db/__tests__/preflight.test.ts +++ b/languages/typescript/packages/cli/src/commands/db/__tests__/preflight.test.ts @@ -1,23 +1,6 @@ import { describe, expect, it } from 'vitest' -import type { PreflightResult } from '@/installer/index.js' import { renderPreflightReport } from '../preflight.js' - -const CAPABLE: PreflightResult = { - currentUser: 'postgres', - isSuperuser: true, - memberOfPostgres: true, - hasDatabaseCreate: true, - hasPublicCreate: true, - pgcryptoInstalled: true, - pgcryptoSchema: 'extensions', - eqlV3SchemaPresent: false, - eqlV3InternalSchemaPresent: false, - canDropEqlV3Schema: null, - canDropEqlV3InternalSchema: null, - canCreateOperatorClass: true, - missing: [], - ok: true, -} +import { CAPABLE } from './preflight-fixtures.js' describe('renderPreflightReport', () => { it('renders every row, with no annotations for a capable role', () => { diff --git a/languages/typescript/packages/cli/src/commands/db/preflight.ts b/languages/typescript/packages/cli/src/commands/db/preflight.ts index 85ea083756..2fffaac13f 100644 --- a/languages/typescript/packages/cli/src/commands/db/preflight.ts +++ b/languages/typescript/packages/cli/src/commands/db/preflight.ts @@ -5,17 +5,6 @@ import { EQLInstaller, type PreflightResult } from '@/installer/index.js' import { describeOreCreatable, ORE_FALLBACK_REMEDY } from '@/installer/ore.js' import { resolveDiagnosticDatabaseUrl } from './resolve-diagnostic-url.js' -/** - * An explicit `--database-url` wins over a stash.config.ts literal, as it - * does in `eql verify`. See {@link resolveDiagnosticDatabaseUrl}. - */ -function resolvePreflightDatabaseUrl( - databaseUrlFlag: string | undefined, - json: boolean, -): Promise { - return resolveDiagnosticDatabaseUrl({ databaseUrlFlag, json }) -} - /** * `stash eql preflight` — read-only "will `eql install` work here, and if not, * why" report. Runs the same catalogue query the installer runs at the head of @@ -25,15 +14,19 @@ function resolvePreflightDatabaseUrl( * Exit code: 1 when a blocking gap is present (`result.ok === false`), else 0. * Membership of `postgres` is reported but never blocks — the installer * skips the optional owner-scoped Supabase grants for non-member roles. + * + * An explicit `--database-url` wins over a literal `databaseUrl` in + * stash.config.ts, as it does in `eql verify`. See + * {@link resolveDiagnosticDatabaseUrl}. */ export async function preflightCommand( options: { databaseUrl?: string; json?: boolean } = {}, ): Promise { if (options.json) { - const databaseUrl = await resolvePreflightDatabaseUrl( - options.databaseUrl, - true, - ) + const databaseUrl = await resolveDiagnosticDatabaseUrl({ + databaseUrlFlag: options.databaseUrl, + json: true, + }) const installer = new EQLInstaller({ databaseUrl }) let result: PreflightResult try { @@ -54,10 +47,10 @@ export async function preflightCommand( // Resolve the URL before any spinner exists: tier 4 of the resolver is an // interactive prompt, and a live spinner would redraw over it. - const databaseUrl = await resolvePreflightDatabaseUrl( - options.databaseUrl, - false, - ) + const databaseUrl = await resolveDiagnosticDatabaseUrl({ + databaseUrlFlag: options.databaseUrl, + json: false, + }) const s = p.spinner() s.start('Probing database role capability...') diff --git a/skills/stash-cli/SKILL.md b/skills/stash-cli/SKILL.md index 45c89ebfad..f95aeb8716 100644 --- a/skills/stash-cli/SKILL.md +++ b/skills/stash-cli/SKILL.md @@ -156,7 +156,7 @@ First hit wins: 4. Interactive prompt — skipped under CI / non-TTY 5. Hard fail, naming the sources it tried -`stash.config.ts` is **not** a separate tier: the scaffolded config calls this same resolver, and the `--database-url` flag still wins. The one exception is a hand-edited config assigning a literal `databaseUrl` string — that bypasses the resolver entirely and beats both flag and env. `eql install`, `eql preflight`, and `eql verify` are the exceptions to that exception: an explicit `--database-url` skips config loading in those three, so the flag wins there. +`stash.config.ts` is **not** a separate tier: the scaffolded config calls this same resolver, and the `--database-url` flag still wins. The one exception is a hand-edited config assigning a literal `databaseUrl` string — that bypasses the resolver entirely and beats both flag and env. `eql install`, `eql preflight`, `eql repair`, and `eql verify` are the exceptions to that exception: an explicit `--database-url` skips config loading in those four, so the flag wins there. The resolved URL is returned in memory only. It is never written to disk or into `process.env`.