From b0a7cc96a3e866cb7853f624568800588881f7cf Mon Sep 17 00:00:00 2001 From: Dmitrii Zhukov Date: Fri, 16 Oct 2026 21:39:18 +0000 Subject: [PATCH 1/6] fix(doctor): judge the LLM provider the way the daemon does The no-llm-provider-key check counted six key names on its own, while the daemon decides through detectLlmProviderKind. With OPENAI_API_KEY and OPENAI_API_KEY_FOR_LLM=false doctor reported the key as found although the daemon runs in noop mode, and with AGENTMEMORY_ALLOW_AGENT_SDK=true and no key it failed and opened the editor while the daemon had an LLM. Drop placeholder keys from the env file, pass the rest to detectLlmProviderKind and list only the keys it would use for the LLM. Doctor now parses the env file with the daemon's parser, so a line uncommented from .env.example keeps its trailing comment out of the value in both. On the same .env doctor reaches the daemon's verdict, except that placeholder keys still count as missing. Signed-off-by: Dmitrii Zhukov --- src/cli/doctor-diagnostics.ts | 44 +++++++++++++++------------------ src/config.ts | 9 ++++--- test/cli-doctor-fixes.test.ts | 46 +++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 28 deletions(-) diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts index 78705d60c8..c11b900fc8 100644 --- a/src/cli/doctor-diagnostics.ts +++ b/src/cli/doctor-diagnostics.ts @@ -16,6 +16,8 @@ // agentmemory doctor --all # apply every available fix without prompting (CI) // agentmemory doctor --dry-run # show what each fix WOULD do; execute nothing +import { detectLlmProviderKind, parseEnvContent } from "../config.js"; + export type DiagnosticStatus = { ok: boolean; /** Short status detail (one line). Shown alongside the check name. */ @@ -95,26 +97,7 @@ const PROVIDER_KEY_NAMES = [ "MINIMAX_API_KEY", ] as const; -export function parseEnvFile(content: string): Record { - const out: Record = {}; - for (const rawLine of content.split(/\r?\n/)) { - const line = rawLine.trim(); - if (!line || line.startsWith("#")) continue; - const eq = line.indexOf("="); - if (eq < 0) continue; - const key = line.slice(0, eq).trim(); - let value = line.slice(eq + 1).trim(); - // Strip surrounding quotes. - if ( - (value.startsWith('"') && value.endsWith('"')) || - (value.startsWith("'") && value.endsWith("'")) - ) { - value = value.slice(1, -1); - } - out[key] = value; - } - return out; -} +export const parseEnvFile = parseEnvContent; /** Returns the list of provider keys that look real (non-placeholder). */ export function realProviderKeys(env: Record): string[] { @@ -199,16 +182,27 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { moreInfo: "Set at least one of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, " + "OPENROUTER_API_KEY, MINIMAX_API_KEY. The daemon picks the first that resolves " + - "to a real (non-placeholder) value at startup.", + "to a real (non-placeholder) value at startup. OPENAI_API_KEY counts only while " + + "OPENAI_API_KEY_FOR_LLM is not false, and AGENTMEMORY_ALLOW_AGENT_SDK=true needs no key.", check: async () => { if (!effects.envFileExists()) { return { ok: false, detail: "env file missing (run env-missing fix first)" }; } - const env = effects.readEnvFile(); - const real = realProviderKeys(env); + const env = { ...effects.readEnvFile() }; + for (const k of placeholderProviderKeys(env)) delete env[k]; + if (detectLlmProviderKind(env) !== "llm") { + return { ok: false, detail: "no provider key set" }; + } + const real = realProviderKeys(env).filter( + (k) => + detectLlmProviderKind({ + [k]: env[k], + OPENAI_API_KEY_FOR_LLM: env.OPENAI_API_KEY_FOR_LLM, + }) === "llm", + ); return { - ok: real.length > 0, - detail: real.length > 0 ? `found: ${real.join(", ")}` : "no provider key set", + ok: true, + detail: real.length > 0 ? `found: ${real.join(", ")}` : "agent-sdk fallback, no API key", }; }, fix: (ctx) => effects.openEditor(ctx.envPath), diff --git a/src/config.ts b/src/config.ts index 649917f9d4..a123e15a49 100644 --- a/src/config.ts +++ b/src/config.ts @@ -43,7 +43,11 @@ function loadEnvFile(): Record { envFileCache = {}; return envFileCache; } - const content = readFileSync(ENV_FILE, "utf-8"); + envFileCache = parseEnvContent(readFileSync(ENV_FILE, "utf-8")); + return envFileCache; +} + +export function parseEnvContent(content: string): Record { const vars: Record = {}; for (const line of content.split("\n")) { const trimmed = line.trim(); @@ -62,8 +66,7 @@ function loadEnvFile(): Record { } vars[key] = val; } - envFileCache = vars; - return envFileCache; + return vars; } // Test hook: clears the memoized .env so the next loadEnvFile() re-reads disk diff --git a/test/cli-doctor-fixes.test.ts b/test/cli-doctor-fixes.test.ts index f7d671fb07..92b1c0d7d0 100644 --- a/test/cli-doctor-fixes.test.ts +++ b/test/cli-doctor-fixes.test.ts @@ -112,6 +112,52 @@ describe("doctor v2 diagnostic catalog", () => { expect(status.ok).toBe(true); }); + it("no-llm-provider-key passes when the agent-sdk fallback is enabled without a key", async () => { + const diagnostics = buildDiagnostics( + stubEffects({ + readEnvFile: () => parseEnvFile("AGENTMEMORY_ALLOW_AGENT_SDK=true # opt in\n"), + }), + ); + const check = diagnostics.find((d) => d.id === "no-llm-provider-key")!; + const status = await check.check(stubCtx()); + expect(status.ok).toBe(true); + expect(status.detail).toContain("agent-sdk"); + }); + + it("no-llm-provider-key fails when OPENAI_API_KEY is reserved for embeddings", async () => { + const diagnostics = buildDiagnostics( + stubEffects({ + readEnvFile: () => + parseEnvFile( + "OPENAI_API_KEY=sk-real-openai-key\n" + + "OPENAI_API_KEY_FOR_LLM=false # Skip OpenAI auto-detection for LLM; key stays active for embeddings\n", + ), + }), + ); + const check = diagnostics.find((d) => d.id === "no-llm-provider-key")!; + const status = await check.check(stubCtx()); + expect(status.ok).toBe(false); + }); + + it("no-llm-provider-key reports only the keys the daemon uses for the LLM", async () => { + const statusFor = async (env: Record) => { + const diagnostics = buildDiagnostics(stubEffects({ readEnvFile: () => env })); + const check = diagnostics.find((d) => d.id === "no-llm-provider-key")!; + return check.check(stubCtx()); + }; + expect(await statusFor({ OPENAI_API_KEY: "sk-real-openai-key" })).toEqual({ + ok: true, + detail: "found: OPENAI_API_KEY", + }); + expect( + await statusFor({ + ANTHROPIC_API_KEY: "sk-ant-real-key-value", + OPENAI_API_KEY: "sk-real-openai-key", + OPENAI_API_KEY_FOR_LLM: "false", + }), + ).toEqual({ ok: true, detail: "found: ANTHROPIC_API_KEY" }); + }); + it("engine-version-mismatch fails when iii reports the wrong version", async () => { const diagnostics = buildDiagnostics( stubEffects({ iiiBinaryVersion: () => "0.99.99" }), From 360da3b82f1117d68d4b0929c64c300b6a2aea22 Mon Sep 17 00:00:00 2001 From: Dmitrii Zhukov Date: Sat, 17 Oct 2026 09:04:46 +0000 Subject: [PATCH 2/6] fix(doctor): let the process environment override the env file The daemon resolves provider keys through getMergedEnv(), where process.env wins over ~/.agentmemory/.env. The provider check read the file only, so an exported key, or OPENAI_API_KEY_FOR_LLM=false in the shell, made doctor report the opposite of what the daemon does. The check now merges the environment over the file. It takes the environment from before hydrateProcessEnvFromFile() copied the file into process.env: the copied values go stale once the file is edited, so merging live process.env would keep a pasted key failing on re-check after the editor fix. Keys found only in the environment are marked in the detail, since a daemon started elsewhere does not see them. Signed-off-by: Dmitrii Zhukov --- src/cli.ts | 3 ++- src/cli/doctor-diagnostics.ts | 17 ++++++++----- src/config.ts | 6 ++++- test/cli-doctor-fixes.test.ts | 45 +++++++++++++++++++++++++++++++++++ test/env-loader.test.ts | 10 ++++++++ 5 files changed, 73 insertions(+), 8 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index dd0f843bc8..79796d18b6 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -130,7 +130,7 @@ const IS_RESET = args.includes("--reset"); // (getRestPort/getBaseUrl/getStreamPort/getEnginePort) or the --port / // --instance / --tools handlers below. Only-if-unset, so a real // process.env value — including one just set by a CLI flag — still wins. -hydrateProcessEnvFromFile(); +const shellEnv = hydrateProcessEnvFromFile(); // --version / -V early exit. Print VERSION + exit before any side effects // (engine boot, env load, dir mkdir). `-v` is taken by --verbose so we @@ -2514,6 +2514,7 @@ function buildDoctorEffects(): DoctorEffects { return {}; } }, + processEnv: () => shellEnv, pidfileExists: () => existsSync(enginePidfilePath()), pidfilePidIsAlive: () => { const pid = readEnginePidfile(); diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts index c11b900fc8..8b020a6465 100644 --- a/src/cli/doctor-diagnostics.ts +++ b/src/cli/doctor-diagnostics.ts @@ -134,6 +134,8 @@ export type DoctorEffects = { envFileExists: () => boolean; /** Read ~/.agentmemory/.env and return parsed key=value pairs. */ readEnvFile: () => Record; + /** Process environment, which takes precedence over the file as in getMergedEnv(). */ + processEnv: () => Record; /** Is the iii engine PID in the pidfile still alive? */ pidfilePidIsAlive: () => boolean | null; /** Does the pidfile exist on disk? */ @@ -177,18 +179,20 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { }, { id: "no-llm-provider-key", - message: "No LLM provider API key found in ~/.agentmemory/.env.", + message: "No LLM provider API key found in ~/.agentmemory/.env or the environment.", fixPreview: "Open ~/.agentmemory/.env in $EDITOR and paste your key, then re-check.", moreInfo: "Set at least one of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, " + - "OPENROUTER_API_KEY, MINIMAX_API_KEY. The daemon picks the first that resolves " + - "to a real (non-placeholder) value at startup. OPENAI_API_KEY counts only while " + - "OPENAI_API_KEY_FOR_LLM is not false, and AGENTMEMORY_ALLOW_AGENT_SDK=true needs no key.", + "OPENROUTER_API_KEY, MINIMAX_API_KEY. Placeholder values count as missing. " + + "OPENAI_API_KEY counts only while OPENAI_API_KEY_FOR_LLM is not false, and " + + "AGENTMEMORY_ALLOW_AGENT_SDK=true needs no key. A value exported in the environment " + + "wins over the file, but only for a daemon started from that environment.", check: async () => { if (!effects.envFileExists()) { return { ok: false, detail: "env file missing (run env-missing fix first)" }; } - const env = { ...effects.readEnvFile() }; + const file = effects.readEnvFile(); + const env = { ...file, ...effects.processEnv() } as Record; for (const k of placeholderProviderKeys(env)) delete env[k]; if (detectLlmProviderKind(env) !== "llm") { return { ok: false, detail: "no provider key set" }; @@ -200,9 +204,10 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { OPENAI_API_KEY_FOR_LLM: env.OPENAI_API_KEY_FOR_LLM, }) === "llm", ); + const named = real.map((k) => (file[k] === env[k] ? k : `${k} (environment)`)); return { ok: true, - detail: real.length > 0 ? `found: ${real.join(", ")}` : "agent-sdk fallback, no API key", + detail: named.length > 0 ? `found: ${named.join(", ")}` : "agent-sdk fallback, no API key", }; }, fix: (ctx) => effects.openEditor(ctx.envPath), diff --git a/src/config.ts b/src/config.ts index a123e15a49..d80f97ed98 100644 --- a/src/config.ts +++ b/src/config.ts @@ -87,10 +87,14 @@ function hasRealValue(v: string | undefined): v is string { // ignored by them. Copy the file's vars into process.env, but only when the // key is currently unset so a real process.env value still wins (this // preserves the {...fileEnv, ...process.env} precedence getMergedEnv uses). -export function hydrateProcessEnvFromFile(): void { +// Returns process.env from before the copy: the hydrated values go stale once +// the file is edited, so a caller that re-reads the file merges over these. +export function hydrateProcessEnvFromFile(): Record { + const beforeHydration = { ...process.env }; for (const [k, v] of Object.entries(loadEnvFile())) { if (process.env[k] === undefined) process.env[k] = v; } + return beforeHydration; } // Warn once when a configured model is in the premium tier and likely to burn diff --git a/test/cli-doctor-fixes.test.ts b/test/cli-doctor-fixes.test.ts index 92b1c0d7d0..d39e6e1a59 100644 --- a/test/cli-doctor-fixes.test.ts +++ b/test/cli-doctor-fixes.test.ts @@ -33,6 +33,7 @@ function stubEffects(overrides: Partial = {}): DoctorEffects { return { envFileExists: () => true, readEnvFile: () => ({ ANTHROPIC_API_KEY: "sk-ant-real-key-value" }), + processEnv: () => ({}), pidfileExists: () => false, pidfilePidIsAlive: () => null, findIiiBinary: () => "/Users/test/.local/bin/iii", @@ -158,6 +159,50 @@ describe("doctor v2 diagnostic catalog", () => { ).toEqual({ ok: true, detail: "found: ANTHROPIC_API_KEY" }); }); + describe("no-llm-provider-key with a process environment", () => { + const statusFor = async ( + file: Record, + processEnv: Record, + ) => { + const diagnostics = buildDiagnostics( + stubEffects({ readEnvFile: () => file, processEnv: () => processEnv }), + ); + const check = diagnostics.find((d) => d.id === "no-llm-provider-key")!; + return check.check(stubCtx()); + }; + + it("lets the environment override the same key in the file, as the daemon does", async () => { + const reservedInFile = { + OPENAI_API_KEY: "sk-real-openai-key", + OPENAI_API_KEY_FOR_LLM: "false", + }; + expect((await statusFor(reservedInFile, {})).ok).toBe(false); + expect((await statusFor(reservedInFile, { OPENAI_API_KEY_FOR_LLM: "true" })).ok).toBe(true); + expect( + (await statusFor({ ANTHROPIC_API_KEY: "sk-ant-real-key-value" }, { ANTHROPIC_API_KEY: "" })) + .ok, + ).toBe(false); + }); + + it("names a key that only the environment provides", async () => { + expect(await statusFor({}, { ANTHROPIC_API_KEY: "sk-ant-real-key-value" })).toEqual({ + ok: true, + detail: "found: ANTHROPIC_API_KEY (environment)", + }); + }); + + it("treats a placeholder exported in the environment as missing, unlike the daemon", async () => { + expect( + ( + await statusFor( + { ANTHROPIC_API_KEY: "sk-ant-real-key-value" }, + { ANTHROPIC_API_KEY: "your-key-here" }, + ) + ).ok, + ).toBe(false); + }); + }); + it("engine-version-mismatch fails when iii reports the wrong version", async () => { const diagnostics = buildDiagnostics( stubEffects({ iiiBinaryVersion: () => "0.99.99" }), diff --git a/test/env-loader.test.ts b/test/env-loader.test.ts index 4c31bebab4..ab2d89fc4b 100644 --- a/test/env-loader.test.ts +++ b/test/env-loader.test.ts @@ -139,6 +139,16 @@ describe("hydrateProcessEnvFromFile", () => { expect(process.env["HYDRATE_WINS"]).toBe("from-process"); }); + it("returns process.env as it was before the file was copied in", async () => { + writeEnv("HYDRATE_ONLY=from-file\nHYDRATE_WINS=from-file"); + process.env["HYDRATE_WINS"] = "from-process"; + const cfg = await freshConfig(); + const before = cfg.hydrateProcessEnvFromFile(); + expect(process.env["HYDRATE_ONLY"]).toBe("from-file"); + expect(before["HYDRATE_ONLY"]).toBeUndefined(); + expect(before["HYDRATE_WINS"]).toBe("from-process"); + }); + it("exposes a .env-only key via getEnvVar and, after hydrate, via raw process.env", async () => { writeEnv("HYDRATE_ONLY=from-file"); const cfg = await freshConfig(); From 500412c468396a288671c9ab97b0bcf690f988b1 Mon Sep 17 00:00:00 2001 From: Dmitrii Zhukov Date: Sat, 17 Oct 2026 09:21:04 +0000 Subject: [PATCH 3/6] fix(doctor): count an exported provider key with no env file getMergedEnv() merges the file under process.env and treats a missing file as empty, so a daemon started with ANTHROPIC_API_KEY exported and no ~/.agentmemory/.env resolves an LLM provider. The provider check returned early on the missing file and reported the opposite. The check now reads the environment regardless; env-missing stays the diagnostic that reports an absent file. With neither a file nor a key the detail still points at the env-missing fix, since the editor fix has nothing to open. Signed-off-by: Dmitrii Zhukov --- src/cli/doctor-diagnostics.ts | 13 ++++++++----- test/cli-doctor-fixes.test.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts index 8b020a6465..b7a5287d74 100644 --- a/src/cli/doctor-diagnostics.ts +++ b/src/cli/doctor-diagnostics.ts @@ -186,16 +186,19 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { "OPENROUTER_API_KEY, MINIMAX_API_KEY. Placeholder values count as missing. " + "OPENAI_API_KEY counts only while OPENAI_API_KEY_FOR_LLM is not false, and " + "AGENTMEMORY_ALLOW_AGENT_SDK=true needs no key. A value exported in the environment " + - "wins over the file, but only for a daemon started from that environment.", + "wins over the file, but only for a daemon started from that environment, and " + + "counts even when the file is absent.", check: async () => { - if (!effects.envFileExists()) { - return { ok: false, detail: "env file missing (run env-missing fix first)" }; - } const file = effects.readEnvFile(); const env = { ...file, ...effects.processEnv() } as Record; for (const k of placeholderProviderKeys(env)) delete env[k]; if (detectLlmProviderKind(env) !== "llm") { - return { ok: false, detail: "no provider key set" }; + return { + ok: false, + detail: effects.envFileExists() + ? "no provider key set" + : "no provider key set (run env-missing fix first)", + }; } const real = realProviderKeys(env).filter( (k) => diff --git a/test/cli-doctor-fixes.test.ts b/test/cli-doctor-fixes.test.ts index d39e6e1a59..765edbb9ab 100644 --- a/test/cli-doctor-fixes.test.ts +++ b/test/cli-doctor-fixes.test.ts @@ -191,6 +191,35 @@ describe("doctor v2 diagnostic catalog", () => { }); }); + it("counts an exported key when no env file exists, as the daemon does", async () => { + const diagnostics = buildDiagnostics( + stubEffects({ + envFileExists: () => false, + readEnvFile: () => ({}), + processEnv: () => ({ ANTHROPIC_API_KEY: "sk-ant-real-key-value" }), + }), + ); + const check = diagnostics.find((d) => d.id === "no-llm-provider-key")!; + expect(await check.check(stubCtx())).toEqual({ + ok: true, + detail: "found: ANTHROPIC_API_KEY (environment)", + }); + }); + + it("points at the env-missing fix when neither the file nor the environment has a key", async () => { + const diagnostics = buildDiagnostics( + stubEffects({ + envFileExists: () => false, + readEnvFile: () => ({}), + processEnv: () => ({}), + }), + ); + const check = diagnostics.find((d) => d.id === "no-llm-provider-key")!; + const status = await check.check(stubCtx()); + expect(status.ok).toBe(false); + expect(status.detail).toContain("env-missing"); + }); + it("treats a placeholder exported in the environment as missing, unlike the daemon", async () => { expect( ( From a711a267c7e6f6f40d602cc0b74bdd1b418fbeab Mon Sep 17 00:00:00 2001 From: Dmitrii Zhukov Date: Sat, 17 Oct 2026 09:34:19 +0000 Subject: [PATCH 4/6] fix(doctor): say in the verdict that an exported key is shell-local The caveat about a daemon started from another environment sat in moreInfo, which runDoctor prints only through the interactive "more" action on a failing check. On a passing one it printed just the detail, so the one configuration the caveat was written for never showed it. The detail now carries it whenever a named key comes from the environment, and a key the environment overrides is marked too, not only one the file lacks. An undefined environment value no longer blanks the file's key. env-missing no longer claims BM25-only when a key is exported, and the key list names GOOGLE_API_KEY, which both detectLlmProviderKind and realProviderKeys already accept. Signed-off-by: Dmitrii Zhukov --- src/cli/doctor-diagnostics.ts | 21 +++++++++------ test/cli-doctor-fixes.test.ts | 48 ++++++++++++++++++++++++++++++++--- 2 files changed, 58 insertions(+), 11 deletions(-) diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts index b7a5287d74..30307a09e5 100644 --- a/src/cli/doctor-diagnostics.ts +++ b/src/cli/doctor-diagnostics.ts @@ -170,7 +170,8 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { fixPreview: "Copy .env.example into ~/.agentmemory/.env (your keys file).", moreInfo: "agentmemory reads provider API keys (Anthropic, OpenAI, Gemini, …) from ~/.agentmemory/.env. " + - "Without this file the daemon falls back to BM25-only search and no LLM-backed enrichment runs.", + "Without this file, and without a provider key exported in the environment, the daemon " + + "falls back to BM25-only search and no LLM-backed enrichment runs.", check: async () => ({ ok: effects.envFileExists(), detail: effects.envFileExists() ? undefined : "no env file", @@ -183,14 +184,17 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { fixPreview: "Open ~/.agentmemory/.env in $EDITOR and paste your key, then re-check.", moreInfo: "Set at least one of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, " + - "OPENROUTER_API_KEY, MINIMAX_API_KEY. Placeholder values count as missing. " + + "GOOGLE_API_KEY, OPENROUTER_API_KEY, MINIMAX_API_KEY. Placeholder values count as missing. " + "OPENAI_API_KEY counts only while OPENAI_API_KEY_FOR_LLM is not false, and " + "AGENTMEMORY_ALLOW_AGENT_SDK=true needs no key. A value exported in the environment " + "wins over the file, but only for a daemon started from that environment, and " + "counts even when the file is absent.", check: async () => { const file = effects.readEnvFile(); - const env = { ...file, ...effects.processEnv() } as Record; + const env: Record = { ...file }; + for (const [k, v] of Object.entries(effects.processEnv())) { + if (v !== undefined) env[k] = v; + } for (const k of placeholderProviderKeys(env)) delete env[k]; if (detectLlmProviderKind(env) !== "llm") { return { @@ -207,11 +211,12 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { OPENAI_API_KEY_FOR_LLM: env.OPENAI_API_KEY_FOR_LLM, }) === "llm", ); - const named = real.map((k) => (file[k] === env[k] ? k : `${k} (environment)`)); - return { - ok: true, - detail: named.length > 0 ? `found: ${named.join(", ")}` : "agent-sdk fallback, no API key", - }; + const fromEnv = real.filter((k) => file[k] !== env[k]); + const named = real.map((k) => (fromEnv.includes(k) ? `${k} (environment)` : k)); + if (named.length === 0) return { ok: true, detail: "agent-sdk fallback, no API key" }; + const caveat = + fromEnv.length > 0 ? "; a daemon started elsewhere will not see it" : ""; + return { ok: true, detail: `found: ${named.join(", ")}${caveat}` }; }, fix: (ctx) => effects.openEditor(ctx.envPath), }, diff --git a/test/cli-doctor-fixes.test.ts b/test/cli-doctor-fixes.test.ts index 765edbb9ab..7d24001301 100644 --- a/test/cli-doctor-fixes.test.ts +++ b/test/cli-doctor-fixes.test.ts @@ -184,13 +184,44 @@ describe("doctor v2 diagnostic catalog", () => { ).toBe(false); }); - it("names a key that only the environment provides", async () => { + it("names a key that only the environment provides, and says a daemon elsewhere misses it", async () => { expect(await statusFor({}, { ANTHROPIC_API_KEY: "sk-ant-real-key-value" })).toEqual({ ok: true, - detail: "found: ANTHROPIC_API_KEY (environment)", + detail: + "found: ANTHROPIC_API_KEY (environment); a daemon started elsewhere will not see it", }); }); + it("marks a key the environment overrides, not just one the file lacks", async () => { + expect( + await statusFor( + { ANTHROPIC_API_KEY: "sk-ant-key-from-file" }, + { ANTHROPIC_API_KEY: "sk-ant-key-from-shell" }, + ), + ).toEqual({ + ok: true, + detail: + "found: ANTHROPIC_API_KEY (environment); a daemon started elsewhere will not see it", + }); + }); + + it("leaves a file key unmarked when only an unrelated flag comes from the environment", async () => { + const status = await statusFor( + { OPENAI_API_KEY: "sk-real-openai-key", OPENAI_API_KEY_FOR_LLM: "false" }, + { OPENAI_API_KEY_FOR_LLM: "true" }, + ); + expect(status.ok).toBe(true); + expect(status.detail).toBe("found: OPENAI_API_KEY"); + }); + + it("ignores an undefined environment value instead of blanking the file key", async () => { + expect( + await statusFor({ ANTHROPIC_API_KEY: "sk-ant-real-key-value" }, { + ANTHROPIC_API_KEY: undefined, + }), + ).toEqual({ ok: true, detail: "found: ANTHROPIC_API_KEY" }); + }); + it("counts an exported key when no env file exists, as the daemon does", async () => { const diagnostics = buildDiagnostics( stubEffects({ @@ -202,7 +233,8 @@ describe("doctor v2 diagnostic catalog", () => { const check = diagnostics.find((d) => d.id === "no-llm-provider-key")!; expect(await check.check(stubCtx())).toEqual({ ok: true, - detail: "found: ANTHROPIC_API_KEY (environment)", + detail: + "found: ANTHROPIC_API_KEY (environment); a daemon started elsewhere will not see it", }); }); @@ -218,6 +250,16 @@ describe("doctor v2 diagnostic catalog", () => { const status = await check.check(stubCtx()); expect(status.ok).toBe(false); expect(status.detail).toContain("env-missing"); + expect(await statusFor({}, {})).toEqual({ ok: false, detail: "no provider key set" }); + }); + + it("keeps the agent-sdk label when the only key is reserved for embeddings", async () => { + expect( + await statusFor( + { OPENAI_API_KEY: "sk-real-openai-key", OPENAI_API_KEY_FOR_LLM: "false" }, + { AGENTMEMORY_ALLOW_AGENT_SDK: "true" }, + ), + ).toEqual({ ok: true, detail: "agent-sdk fallback, no API key" }); }); it("treats a placeholder exported in the environment as missing, unlike the daemon", async () => { From 9a906ff245fc5a8152edb26d379829d3e79f432b Mon Sep 17 00:00:00 2001 From: Dmitrii Zhukov Date: Sun, 18 Oct 2026 11:34:54 +0000 Subject: [PATCH 5/6] refactor(doctor): drop restating comments Signed-off-by: Dmitrii Zhukov --- src/cli/doctor-diagnostics.ts | 1 - src/config.ts | 2 -- 2 files changed, 3 deletions(-) diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts index 30307a09e5..822c57aba6 100644 --- a/src/cli/doctor-diagnostics.ts +++ b/src/cli/doctor-diagnostics.ts @@ -134,7 +134,6 @@ export type DoctorEffects = { envFileExists: () => boolean; /** Read ~/.agentmemory/.env and return parsed key=value pairs. */ readEnvFile: () => Record; - /** Process environment, which takes precedence over the file as in getMergedEnv(). */ processEnv: () => Record; /** Is the iii engine PID in the pidfile still alive? */ pidfilePidIsAlive: () => boolean | null; diff --git a/src/config.ts b/src/config.ts index d80f97ed98..a153327dde 100644 --- a/src/config.ts +++ b/src/config.ts @@ -87,8 +87,6 @@ function hasRealValue(v: string | undefined): v is string { // ignored by them. Copy the file's vars into process.env, but only when the // key is currently unset so a real process.env value still wins (this // preserves the {...fileEnv, ...process.env} precedence getMergedEnv uses). -// Returns process.env from before the copy: the hydrated values go stale once -// the file is edited, so a caller that re-reads the file merges over these. export function hydrateProcessEnvFromFile(): Record { const beforeHydration = { ...process.env }; for (const [k, v] of Object.entries(loadEnvFile())) { From 0d70da3d4503f144eea523d69766ac6f9673db07 Mon Sep 17 00:00:00 2001 From: Dmitrii Zhukov Date: Mon, 26 Oct 2026 09:24:19 +0000 Subject: [PATCH 6/6] fix(doctor): read the env file named by AGENTMEMORY_ENV_FILE The daemon loads AGENTMEMORY_ENV_FILE when it is set, so doctor judged the provider key from a file the daemon does not read. Signed-off-by: Dmitrii Zhukov --- src/cli.ts | 10 ++++-- test/cli-doctor-env-file.test.ts | 55 ++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 test/cli-doctor-env-file.test.ts diff --git a/src/cli.ts b/src/cli.ts index 9ddb858de5..bd32b08e19 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1992,11 +1992,15 @@ function checkClaudeCodeHooks(): CCHooksCheck { // which prompts Fix/Skip/More/Quit per failing check, applies the fix // inline, and re-checks only the affected diagnostic. +function doctorEnvPath(): string { + return process.env["AGENTMEMORY_ENV_FILE"] || join(homedir(), ".agentmemory", ".env"); +} + function buildDoctorContext(): DoctorContext { return { baseUrl: getBaseUrl(), viewerUrl: getViewerUrl(), - envPath: join(homedir(), ".agentmemory", ".env"), + envPath: doctorEnvPath(), pidfilePath: readEngineState()?.kind === "compose" ? engineStatePath() : enginePidfilePath(), enginePath: engineStatePath(), pinnedVersion: IIPINNED_VERSION, @@ -2005,11 +2009,11 @@ function buildDoctorContext(): DoctorContext { function buildDoctorEffects(): DoctorEffects { return { - envFileExists: () => existsSync(join(homedir(), ".agentmemory", ".env")), + envFileExists: () => existsSync(doctorEnvPath()), readEnvFile: () => { try { return parseEnvFile( - readFileSync(join(homedir(), ".agentmemory", ".env"), "utf-8"), + readFileSync(doctorEnvPath(), "utf-8"), ); } catch { return {}; diff --git a/test/cli-doctor-env-file.test.ts b/test/cli-doctor-env-file.test.ts new file mode 100644 index 0000000000..c2656123ea --- /dev/null +++ b/test/cli-doctor-env-file.test.ts @@ -0,0 +1,55 @@ +import { spawn } from "node:child_process"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, beforeEach, expect, it } from "vitest"; + +let home: string; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "doctor-env-file-")); + mkdirSync(join(home, ".agentmemory")); + writeFileSync(join(home, ".agentmemory", ".env"), "# no provider key here\n"); + writeFileSync(join(home, "custom.env"), "ANTHROPIC_API_KEY=sk-ant-real-key-value\n"); +}); + +afterEach(() => { + rmSync(home, { recursive: true, force: true }); +}); + +function doctorDryRun(extraEnv: Record): Promise { + return new Promise((done, reject) => { + const child = spawn(process.execPath, [resolve("dist/cli.mjs"), "doctor", "--dry-run"], { + env: { + PATH: process.env.PATH, + HOME: home, + USERPROFILE: home, + TMPDIR: home, + AGENTMEMORY_URL: "http://127.0.0.1:1", + NO_COLOR: "1", + CI: "1", + ...extraEnv, + }, + timeout: 30000, + }); + let output = ""; + child.stdout.on("data", (data) => { output += data; }); + child.stderr.on("data", (data) => { output += data; }); + child.on("error", reject); + child.on("close", () => done(output)); + }); +} + +it("reads provider keys from AGENTMEMORY_ENV_FILE, the file the daemon loads", async () => { + rmSync(join(home, ".agentmemory", ".env")); + const output = await doctorDryRun({ AGENTMEMORY_ENV_FILE: join(home, "custom.env") }); + expect(output).toContain("Dry-run complete"); + expect(output).not.toContain("[env-missing]"); + expect(output).not.toContain("[no-llm-provider-key]"); +}); + +it("reports no provider key when only the default env file is read", async () => { + const output = await doctorDryRun({}); + expect(output).toContain("Dry-run complete"); + expect(output).toContain("[no-llm-provider-key]"); +});