fix(cli): check the effective database target in doctor (#17847)

<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/51/changes/paperclip/51
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip runs with embedded or external PostgreSQL.
> - The CLI checks the database before it starts the server.
> - The server uses `DATABASE_URL` before the saved connection string.
> - Doctor checked only the saved database configuration.
> - A valid environment-only setup could fail before startup.
> - This change probes the effective server target instead.
> - Operators can keep database credentials in the environment.

## Linked Issues or Issue Description

Fixes: #11598

Refs: #11612. That predecessor is closed and unmerged. The defect
remains on current master at `0cb3fc7db5`. This PR adds current
precedence coverage, including a saved embedded mode and explicitly
empty environment values.

## What Changed

- Resolve the effective URL with the same nullish environment-first rule
as the server.
- Probe external PostgreSQL when the environment selects it, even if the
saved mode is embedded.
- Keep an explicitly empty environment value distinct from an unset
value. Do not trim or replace the selected URL.
- Add eight mocked transport regressions. Keep the three embedded
storage checks.

## Verification

- `node node_modules/vitest/vitest.mjs run --config cli/vitest.config.ts
cli/src/__tests__/database-check.test.ts` — 11 passed.
- Six new cases failed before the original fix.
- Review exposed one ambient worktree-mode failure in the new embedded
fallback test. That test now sets its worktree flag explicitly.
- Both `env -u PAPERCLIP_IN_WORKTREE node node_modules/vitest/vitest.mjs
run --config cli/vitest.config.ts
cli/src/__tests__/database-check.test.ts` and
`PAPERCLIP_IN_WORKTREE=true node node_modules/vitest/vitest.mjs run
--config cli/vitest.config.ts cli/src/__tests__/database-check.test.ts`
pass all 11 cases.
- Tests cover environment-only configuration, environment precedence,
embedded override, saved fallback, empty values, unchanged URL
forwarding, and a failed effective-target probe.
- The database factory and transport are mocked. No database is started
or contacted.
- PR CI passed full typecheck, build, and broad tests on the exact
reviewed head. Broad local checks were not repeated while a separate
live qualification run owned local resources.

- Fresh Greptile review is 5/5 at
`a042fb4a28f2e1574972798ed80de2e616daf9fc`. All review threads are
resolved. All 55 successful checks for this exact head are green. Two
conditional checks are skipped, and one review check is neutral. No
checks are pending or failed.

## Risks

- Doctor now probes the database that server startup will use, instead
of an ignored saved target.
- Empty `DATABASE_URL` follows the existing server rule. It masks a
saved URL in Postgres mode and leaves embedded mode selected when no
effective URL exists.
- No schema, migration, startup resolver, or provider behavior changes.
Existing environment support is already documented in the implementation
spec and developing guide.

## Model Used

OpenAI `gpt-6.1-sol`, with repository inspection, code editing, and
offline test tools. No model or provider call was used in the
regression.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-05 02:41:54 -08:00
1 parent 0da786fdc3
commit c1c2f7e73d
2 files changed
+67 -4

No files matched your search

+62 -1
View File
@@ -1,10 +1,19 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { databaseCheck } from "../checks/database-check.js";
import type { PaperclipConfig } from "../config/schema.js";
const database = vi.hoisted(() => ({ createDb: vi.fn(), execute: vi.fn() }));
vi.mock("@paperclipai/db", () => ({ createDb: database.createDb }));
beforeEach(() => {
vi.stubEnv("DATABASE_URL", undefined);
database.createDb.mockReset().mockReturnValue({ execute: database.execute });
database.execute.mockReset().mockResolvedValue([]);
});
const created: string[] = [];
const ORIGINAL_IN_WORKTREE = process.env.PAPERCLIP_IN_WORKTREE;
@@ -26,6 +35,7 @@ function embeddedConfig(dataDir: string): PaperclipConfig {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
if (ORIGINAL_IN_WORKTREE === undefined) delete process.env.PAPERCLIP_IN_WORKTREE;
else process.env.PAPERCLIP_IN_WORKTREE = ORIGINAL_IN_WORKTREE;
while (created.length > 0) {
@@ -77,3 +87,54 @@ describe("databaseCheck — embedded postgres temp-dir guard", () => {
expect(result.status).toBe("pass");
});
});
describe("databaseCheck effective PostgreSQL target", () => {
const savedUrl = "postgres://saved:synthetic@db.example/saved";
const environmentUrl = "postgres://environment:synthetic@db.example/environment";
const postgres = (connectionString?: string) => ({ database: { mode: "postgres", connectionString } }) as PaperclipConfig;
it("checks an environment-only PostgreSQL URL", async () => {
vi.stubEnv("DATABASE_URL", environmentUrl);
expect(await databaseCheck(postgres())).toMatchObject({ status: "pass", message: "PostgreSQL connection successful" });
expect(database.createDb).toHaveBeenCalledExactlyOnceWith(environmentUrl);
expect(database.execute).toHaveBeenCalledExactlyOnceWith("SELECT 1");
});
it("uses the environment target before the saved target", async () => {
vi.stubEnv("DATABASE_URL", environmentUrl);
expect((await databaseCheck(postgres(savedUrl))).status).toBe("pass");
expect(database.createDb).toHaveBeenCalledExactlyOnceWith(environmentUrl);
});
it("checks external PostgreSQL even when the saved mode is embedded", async () => {
vi.stubEnv("DATABASE_URL", environmentUrl);
const dataDir = path.join(makeBase(), "not-created");
expect((await databaseCheck(embeddedConfig(dataDir))).message).toBe("PostgreSQL connection successful");
expect(database.createDb).toHaveBeenCalledExactlyOnceWith(environmentUrl);
expect(fs.existsSync(dataDir)).toBe(false);
});
it("uses the saved PostgreSQL target when DATABASE_URL is unset", async () => {
expect((await databaseCheck(postgres(savedUrl))).status).toBe("pass");
expect(database.createDb).toHaveBeenCalledExactlyOnceWith(savedUrl);
});
it("does not fall back to a saved URL when DATABASE_URL is explicitly empty", async () => {
vi.stubEnv("DATABASE_URL", "");
expect(await databaseCheck(postgres(savedUrl))).toMatchObject({ status: "fail", message: "PostgreSQL mode selected but no connection string configured" });
expect(database.createDb).not.toHaveBeenCalled();
});
it("keeps embedded storage when DATABASE_URL is empty", async () => {
vi.stubEnv("DATABASE_URL", "");
vi.stubEnv("PAPERCLIP_IN_WORKTREE", "false");
expect((await databaseCheck(embeddedConfig(path.join(makeBase(), "db")))).status).toBe("pass");
expect(database.createDb).not.toHaveBeenCalled();
});
it("passes the environment value unchanged, as the server does", async () => {
vi.stubEnv("DATABASE_URL", ` ${environmentUrl} `);
await databaseCheck(postgres(savedUrl));
expect(database.createDb).toHaveBeenCalledExactlyOnceWith(` ${environmentUrl} `);
});
it("reports a failed probe of the effective target instead of checking the saved target", async () => {
vi.stubEnv("DATABASE_URL", environmentUrl);
database.execute.mockRejectedValue(new Error("Synthetic connection refused"));
expect(await databaseCheck(postgres(savedUrl))).toMatchObject({ status: "fail", message: "Cannot connect to PostgreSQL: Synthetic connection refused" });
expect(database.createDb).toHaveBeenCalledExactlyOnceWith(environmentUrl);
});
});
+5 -3
View File
@@ -12,8 +12,10 @@ function isInsideOsTmpDir(targetPath: string): boolean {
}
export async function databaseCheck(config: PaperclipConfig, configPath?: string): Promise<CheckResult> {
if (config.database.mode === "postgres") {
if (!config.database.connectionString) {
const connectionString = process.env.DATABASE_URL
?? (config.database.mode === "postgres" ? config.database.connectionString : undefined);
if (connectionString || config.database.mode === "postgres") {
if (!connectionString) {
return {
name: "Database",
status: "fail",
@@ -25,7 +27,7 @@ export async function databaseCheck(config: PaperclipConfig, configPath?: string
try {
const { createDb } = await import("@paperclipai/db");
const db = createDb(config.database.connectionString);
const db = createDb(connectionString);
await db.execute("SELECT 1");
return {
name: "Database",