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
13 changes: 9 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ const IS_RESET = args.includes("--reset");
// (getRestPort/getBaseUrl/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();
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

// --version / -V early exit. Print VERSION + exit before any side effects
// (engine boot, env load, dir mkdir). `-v` is taken by --verbose so we
Expand Down Expand Up @@ -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(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Custom env paths retain default-file guidance

With AGENTMEMORY_ENV_FILE set, checks read the custom file, but diagnostic messages and fix previews still name ~/.agentmemory/.env. Users can follow instructions for a different file.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

pidfilePath: readEngineState()?.kind === "compose" ? engineStatePath() : enginePidfilePath(),
enginePath: engineStatePath(),
pinnedVersion: IIPINNED_VERSION,
Expand All @@ -2005,16 +2009,17 @@ function buildDoctorContext(): DoctorContext {

function buildDoctorEffects(): DoctorEffects {
return {
envFileExists: () => existsSync(join(homedir(), ".agentmemory", ".env")),
envFileExists: () => existsSync(doctorEnvPath()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Missing custom env file remains unfixed

When AGENTMEMORY_ENV_FILE points to a missing file, env-missing fails but its fix creates the default file. runInit ignores the custom path, so doctor reports a successful fix while the custom file remains missing.

Learn more

The env-missing check now inspects the path selected by AGENTMEMORY_ENV_FILE. Its fix invokes runInit, but runInit always targets the default file. As a result, the fix can create an unrelated file, or do nothing when that default file already exists, and the re-check still fails.

Example: Set AGENTMEMORY_ENV_FILE=/tmp/agent.env with neither /tmp/agent.env nor ~/.agentmemory/.env present. Choose Fix for env-missing. Doctor creates ~/.agentmemory/.env, then reports that /tmp/agent.env is still missing.

Recommended fix: Pass ctx.envPath to the env-missing fix and copy the template to that path with the same exclusive-create behavior as runInit; keep standalone init's default-path behavior unchanged.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

readEnvFile: () => {
try {
return parseEnvFile(
readFileSync(join(homedir(), ".agentmemory", ".env"), "utf-8"),
readFileSync(doctorEnvPath(), "utf-8"),
);
} catch {
return {};
}
},
processEnv: () => shellEnv,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
pidfileExists: () => {
const state = readEngineState();
return state?.kind === "compose" ? Boolean(state.composePid) : existsSync(enginePidfilePath());
Expand Down
70 changes: 38 additions & 32 deletions src/cli/doctor-diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -95,26 +97,7 @@ const PROVIDER_KEY_NAMES = [
"MINIMAX_API_KEY",
] as const;

export function parseEnvFile(content: string): Record<string, string> {
const out: Record<string, string> = {};
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, string>): string[] {
Expand Down Expand Up @@ -151,6 +134,7 @@ export type DoctorEffects = {
envFileExists: () => boolean;
/** Read ~/.agentmemory/.env and return parsed key=value pairs. */
readEnvFile: () => Record<string, string>;
processEnv: () => Record<string, string | undefined>;
/** Is the iii engine PID in the pidfile still alive? */
pidfilePidIsAlive: () => boolean | null;
/** Does the pidfile exist on disk? */
Expand Down Expand Up @@ -185,7 +169,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",
Expand All @@ -194,22 +179,43 @@ 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.",
"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 () => {
if (!effects.envFileExists()) {
return { ok: false, detail: "env file missing (run env-missing fix first)" };
const file = effects.readEnvFile();
const env: Record<string, string> = { ...file };
for (const [k, v] of Object.entries(effects.processEnv())) {
if (v !== undefined) env[k] = v;
}
const env = effects.readEnvFile();
const real = realProviderKeys(env);
return {
ok: real.length > 0,
detail: real.length > 0 ? `found: ${real.join(", ")}` : "no provider key set",
};
for (const k of placeholderProviderKeys(env)) delete env[k];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Placeholder Gemini key masks valid alias

With placeholder GEMINI_API_KEY and real GOOGLE_API_KEY, no-llm-provider-key passes after dropping the placeholder. The daemon's detectProvider selects GEMINI_API_KEY first, so Gemini calls use the placeholder instead.

Learn more

The provider check removes placeholder values from its copy of the merged environment. The actual detectProvider does not remove them: it treats any nonempty value as a real key and prefers GEMINI_API_KEY over its GOOGLE_API_KEY alias. As a result the doctor's positive result does not correspond to the key the daemon will send to Gemini. The same discrepancy can affect which provider wins when a higher-priority provider has a placeholder.

Example: Put GEMINI_API_KEY=your-key-here and GOOGLE_API_KEY=real-google-key in the file. Doctor says found: GOOGLE_API_KEY; the worker builds its Gemini provider with your-key-here and requests fail.

Recommended fix: Check the actual selected provider and its selected credential against placeholder values, rather than deleting placeholder keys before provider selection. Account for the Gemini alias precedence and the priority order in detectProvider.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Main gives the same verdict for this env (found: GOOGLE_API_KEY). The placeholder is picked on the daemon side, src/providers/index.ts:98 (GEMINI_API_KEY || GOOGLE_API_KEY), which this PR does not touch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The daemon side is now #1588: a placeholder GEMINI_API_KEY no longer shadows a real GOOGLE_API_KEY, and doctor and the daemon share one placeholder rule.

if (detectLlmProviderKind(env) !== "llm") {
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) =>
detectLlmProviderKind({
[k]: env[k],
OPENAI_API_KEY_FOR_LLM: env.OPENAI_API_KEY_FOR_LLM,
}) === "llm",
);
Comment on lines +206 to +212

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Unused provider keys reported as active

When several keys exist, no-llm-provider-key reports each as usable despite the daemon selecting only one. detectProvider stops at the first provider, so the verdict misidentifies the active key.

Learn more

The provider-kind helper answers whether a given configuration has any LLM route; it does not say which route wins. Running it once per key treats all valid keys as used, even though detectProvider selects the first provider in its priority order. The result is misleading when debugging which credential a running worker uses, especially when one key exists only in the shell.

Example: With OPENAI_API_KEY=sk-openai-real and ANTHROPIC_API_KEY=sk-ant-real, doctor reports both as found. The worker picks OpenAI; it never uses the Anthropic key for its primary provider.

Recommended fix: Derive the displayed active key from the same provider-selection priority and alias logic as detectProvider, while retaining a separate check for whether any working route exists.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Main prints the same list for this env (found: ANTHROPIC_API_KEY, OPENAI_API_KEY); this PR does not change what the detail lists. Naming only the key detectProvider picks would be a separate change.

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),
},
Expand Down
13 changes: 9 additions & 4 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ function loadEnvFile(): Record<string, string> {
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<string, string> {
const vars: Record<string, string> = {};
for (const line of content.split("\n")) {
const trimmed = line.trim();
Expand All @@ -67,8 +71,7 @@ function loadEnvFile(): Record<string, string> {
}
vars[key] = val;
}
envFileCache = vars;
return envFileCache;
return vars;
}

// Test hook: clears the memoized .env so the next loadEnvFile() re-reads disk
Expand All @@ -89,10 +92,12 @@ 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 {
export function hydrateProcessEnvFromFile(): Record<string, string | undefined> {
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
Expand Down
55 changes: 55 additions & 0 deletions test/cli-doctor-env-file.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>): Promise<string> {
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]");
});
Loading
Loading