diff --git a/src/cli.ts b/src/cli.ts index da9f14f0ed..13c5812e4c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -43,6 +43,7 @@ import { canAutoFix, doctorPromptsAllowed, dryRunPlan, + failureReport, parseEnvFile, type Diagnostic, type DiagnosticFixResult, @@ -104,6 +105,7 @@ import { bearerHeaders, resolveClientSecret } from "./secret-store.js"; import { assertComposePortsFree, composeCall, composeRegistryFailureMessage, composeStateRegistryFailure, composeWorkerFailureSummary, ownedComposeProject, readComposeLogFromOffset, startComposeDaemon, writeComposeState, type ComposeStatus } from "./cli/compose-control.js"; import { COMPOSE_WORKER_VERSIONS, composeDownTimeoutMs, composeNamespace } from "./cli/compose-project.js"; import { legacyDockerStateMessage, type LegacyDockerEngineState } from "./cli/legacy-docker-state.js"; +import { DEFAULT_START_COMMAND, engineOnlyLines, probeWorkerConnection, shellArg, tcpPortOpen, unrecognizedServiceLines, type WorkerConnection } from "./cli/worker-connection.js"; import { NO_HOOK_CAPTURE, hookCaptureMissing } from "./functions/status.js"; import type { CaptureStatus } from "./functions/capture.js"; @@ -1842,6 +1844,61 @@ async function apiFetch(base: string, path: string, timeoutMs = 500 } } +function recoveryTargetArgs(): string { + const parts: string[] = []; + if (hasInstanceArgument) parts.push(`--instance ${selectedInstance}`); + if (portValue || (!hasInstanceArgument && getRestPort() !== 3111)) parts.push(`--port ${getRestPort()}`); + const dataDir = cliArgValue("--data-dir"); + if (dataDir) parts.push(`--data-dir ${shellArg(dataDir)}`); + return parts.map((part) => ` ${part}`).join(""); +} + +function recoveryStartCommand(): string { + return `${DEFAULT_START_COMMAND}${recoveryTargetArgs()}`; +} + +function workerEnginePort(): number { + const workerUrl = process.env["III_URL"]; + if (!process.env["III_ENGINE_URL"] && workerUrl) { + try { + const parsed = new URL(workerUrl).port; + if (parsed) return parseInt(parsed, 10); + } catch {} + } + return getEnginePort(); +} + +function probeTargetWorker(base: string): Promise { + return probeWorkerConnection(base, { + headers: bearerHeaders(base), + engineBusReachable: async () => tcpPortOpen(new URL(base).hostname.replace(/^\[|\]$/g, ""), workerEnginePort()), + }); +} + +async function savedComposeFailure(state: ComposeEngineState): Promise { + if (!state.composePid || !pidAlive(state.composePid)) return null; + try { + const composeStatus = await composeCall({ + engineUrl: state.engineUrl, + namespace: state.namespace, + functionId: "compose::status", + file: state.file, + }); + return composeWorkerFailureSummary(ownedComposeProject(composeStatus, state.file)); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + p.log.warn(`Worker Compose status unavailable: ${message}`); + return null; + } +} + +function exitWithComposeFailure(state: ComposeEngineState, failure: string, unavailable: string): never { + p.log.error(`Worker Compose failed after exhausting restart attempts; ${unavailable}.`); + p.log.error(failure); + p.log.info(`Inspect ${state.logFile}, then run agentmemory stop before retrying.`); + process.exit(1); +} + async function runStatus() { const base = getBaseUrl(); p.intro("agentmemory status"); @@ -1854,32 +1911,29 @@ async function runStatus() { const up = await isEngineRunning(); if (!up) { - if (savedState?.kind === "compose" && savedState.composePid && pidAlive(savedState.composePid)) { - try { - const composeStatus = await composeCall({ - engineUrl: savedState.engineUrl, - namespace: savedState.namespace, - functionId: "compose::status", - file: savedState.file, - }); - const project = ownedComposeProject(composeStatus, savedState.file); - const failure = composeWorkerFailureSummary(project); - if (failure) { - p.log.error(`Worker Compose failed after exhausting restart attempts; REST is unavailable at ${base}.`); - p.log.error(failure); - p.log.info(`Inspect ${savedState.logFile}, then run agentmemory stop before retrying.`); - process.exit(1); - } - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - p.log.warn(`Worker Compose status unavailable: ${message}`); - } + if (savedState?.kind === "compose") { + const failure = await savedComposeFailure(savedState); + if (failure) exitWithComposeFailure(savedState, failure, `REST is unavailable at ${base}`); } p.log.error(`Not running — no response at ${base}`); p.log.info("Start with: npx @agentmemory/agentmemory"); process.exit(1); } + const connection = await probeTargetWorker(base); + const workerMissing = connection !== "connected"; + const composeExplainsMissingRoutes = workerMissing + && savedState?.kind === "compose" + && (await savedComposeFailure(savedState)) !== null; + if (workerMissing && !composeExplainsMissingRoutes) { + let lines: string[]; + if (connection === "engine-only") lines = engineOnlyLines(base, recoveryStartCommand()); + else if (connection === "unrecognized") lines = unrecognizedServiceLines(base); + else lines = [`A server answers at ${base}, but /agentmemory/livez and /agentmemory/health did not respond.`, "Check the agentmemory logs, then run status again."]; + p.log.error(lines.join("\n")); + process.exit(1); + } + try { const [healthRes, sessionsRes, graphRes, memoriesRes, flagsRes, followupRes] = await Promise.all([ apiFetch(base, "health"), @@ -2072,9 +2126,17 @@ function buildDoctorContext(): DoctorContext { pidfilePath: readEngineState()?.kind === "compose" ? engineStatePath() : enginePidfilePath(), enginePath: engineStatePath(), pinnedVersion: IIPINNED_VERSION, + startCommand: recoveryStartCommand(), + targetArgs: recoveryTargetArgs(), }; } +function doctorTargetsManagedCompose(): boolean { + const state = readEngineState(); + const remoteTarget = shouldUseAgentmemoryUrl() && process.env["AGENTMEMORY_URL"]; + return state?.kind === "compose" && state.restPort === getRestPort() && !remoteTarget; +} + function buildDoctorEffects(): DoctorEffects { return { envFileExists: () => existsSync(doctorEnvPath()), @@ -2109,11 +2171,11 @@ function buildDoctorEffects(): DoctorEffects { return state?.kind === "compose" ? state.binPath : privateIiiPath(); }, iiiBinaryVersion: (binPath: string) => iiiBinVersion(binPath), - externalEngineRunning: async () => { - const state = readEngineState(); - const remoteTarget = shouldUseAgentmemoryUrl() && process.env["AGENTMEMORY_URL"]; - const managed = state?.kind === "compose" && state.restPort === getRestPort() && !remoteTarget; - return !managed && await isEngineRunning(); + externalEngineRunning: async () => !doctorTargetsManagedCompose() && await isEngineRunning(), + workerConnection: async () => { + const connection = await probeTargetWorker(getBaseUrl()); + if (connection === "connected" || connection === "unreachable") return connection; + return doctorTargetsManagedCompose() ? "managed-worker-down" : connection; }, viewerReachable: async (timeoutMs = 2000) => { try { @@ -2421,16 +2483,15 @@ async function runDoctor() { continue; } failed++; - p.log.warn(`${d.id} ✗ ${status.detail ?? ""}`.trim()); + const report = failureReport(d, status); + p.log.warn(report.problem); + p.log.info(report.fix); if (!canAutoFix(d, status)) { - p.log.info(`manual fix: ${status.manualFix ?? d.fixPreview}`); skipped++; continue; } - p.log.info(`why: ${d.fixPreview}`); - if (applyAll) { const r = await applyFixWithReport(d, ctx, false); if (r.ok) fixed++; diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts index b7bea3868f..3063f49fe9 100644 --- a/src/cli/doctor-diagnostics.ts +++ b/src/cli/doctor-diagnostics.ts @@ -24,6 +24,7 @@ import { llmOptInHint, parseEnvContent, } from "../config.js"; +import { DEFAULT_START_COMMAND, ENGINE_ONLY_DOCKER_GUIDE, engineOnlyFix, UNRECOGNIZED_DOCKER_NOTE, UNRECOGNIZED_SERVICE_FIX, type WorkerConnection } from "./worker-connection.js"; export type DiagnosticStatus = { ok: boolean; @@ -50,8 +51,12 @@ export type DoctorContext = { enginePath: string; /** Pinned engine version. */ pinnedVersion: string; + startCommand?: string; + targetArgs?: string; }; +export type DoctorWorkerConnection = WorkerConnection | "managed-worker-down"; + export type Diagnostic = { /** Stable id. Used in --json and tests. */ id: string; @@ -73,6 +78,13 @@ export function canAutoFix(d: Diagnostic, status?: DiagnosticStatus): boolean { return !d.manualOnly && !status?.manualFix; } +export function failureReport(d: Diagnostic, status: DiagnosticStatus): { problem: string; fix: string } { + return { + problem: `${d.id} ✗ ${d.message}${status.detail ? ` (${status.detail})` : ""}`, + fix: `${canAutoFix(d, status) ? "fix" : "manual fix"}: ${status.manualFix ?? d.fixPreview}`, + }; +} + export function doctorPromptsAllowed( env: NodeJS.ProcessEnv, stdinIsTTY: boolean | undefined, @@ -87,6 +99,7 @@ export const DIAGNOSTIC_IDS = [ "no-llm-provider-key", "embedding-provider-not-chosen", "engine-version-mismatch", + "worker-not-connected", "viewer-unreachable", "stale-pidfile", "env-placeholder-keys", @@ -143,6 +156,7 @@ export type DoctorEffects = { /** Run `iii --version`; null if it fails. */ iiiBinaryVersion: (binPath: string) => string | null; externalEngineRunning: () => Promise; + workerConnection: () => Promise; /** Probe the viewer URL; true if it returns OK within timeoutMs. */ viewerReachable: (timeoutMs?: number) => Promise; /** Run init logic (copies .env.example). */ @@ -289,6 +303,47 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { return effects.runStart(); }, }, + { + id: "worker-not-connected", + message: "The server answers, but the agentmemory worker routes return 404.", + fixPreview: engineOnlyFix(), + moreInfo: + "The REST port answers, but /agentmemory/livez and /agentmemory/health return 404. " + + "Only the agentmemory worker registers those routes, so the engine runs alone: status shows " + + "no version and no health, and the viewer is not served. Old Docker images from the legacy " + + "CLI Docker mode ran only the engine. Migration guide: " + + ENGINE_ONLY_DOCKER_GUIDE, + manualOnly: true, + check: async (ctx) => { + const connection = await effects.workerConnection(); + const startCommand = ctx.startCommand ?? DEFAULT_START_COMMAND; + const targetArgs = ctx.targetArgs ?? ""; + if (connection === "engine-only") { + return { + ok: false, + detail: `engine at ${ctx.baseUrl} has no agentmemory routes (404)`, + manualFix: engineOnlyFix(startCommand), + }; + } + if (connection === "managed-worker-down") { + return { + ok: false, + detail: `managed Worker Compose engine at ${ctx.baseUrl} has no agentmemory routes (404)`, + manualFix: `Run agentmemory status${targetArgs} to see the Worker Compose failure report, then run agentmemory stop${targetArgs} and start again with: ${startCommand}.`, + }; + } + if (connection === "unrecognized") { + return { + ok: false, + detail: `server at ${ctx.baseUrl} returns 404 for the agentmemory routes and the iii engine port does not answer`, + manualFix: `${UNRECOGNIZED_SERVICE_FIX} ${UNRECOGNIZED_DOCKER_NOTE}`, + }; + } + if (connection === "unreachable") return { ok: true, detail: "server not reachable (see Server reachable)" }; + return { ok: true }; + }, + fix: async (ctx) => ({ ok: false, message: engineOnlyFix(ctx.startCommand) }), + }, { id: "viewer-unreachable", message: "Viewer port not reachable.", @@ -357,14 +412,16 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { { id: "iii-on-path-not-local-bin", message: - "iii is on PATH but agentmemory's private install is absent or mismatched.", + "agentmemory's own iii at ~/.agentmemory/bin/iii is missing or a different version, and another iii is on your PATH.", fixPreview: - "Install the pinned version to ~/.agentmemory/bin — won't touch your PATH.", + "Run npx -y @agentmemory/agentmemory@latest. It installs the pinned iii to ~/.agentmemory/bin/iii and does not change your PATH or the other iii.", moreInfo: - "agentmemory installs its pinned engine to ~/.agentmemory/bin/iii so a " + + "agentmemory keeps its pinned engine at ~/.agentmemory/bin/iii so a " + "user-managed iii on PATH (homebrew, cargo, manual install) stays untouched. " + - "When agentmemory needs the pin and PATH doesn't have it, it falls back to the " + - "private install. If neither exists, run the installer.", + "When that copy is missing or has a different version, startup uses the iii on PATH " + + "if it matches the pin. If the PATH iii has a different version, startup installs the " + + "pinned copy into ~/.agentmemory/bin first. The engine-version-mismatch check shows " + + "which version each binary reports.", manualOnly: true, check: async (ctx) => { const bin = effects.findIiiBinary(); @@ -378,7 +435,17 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] { detail: `private install pinned; PATH iii at ${bin} stays untouched`, }; } - return { ok: false, detail: `iii at: ${bin}` }; + const pathVersion = effects.iiiBinaryVersion(bin); + const detail = `PATH iii at ${bin} is ${pathVersion ?? "an unknown version"} (pinned ${ctx.pinnedVersion})`; + if (pathVersion === ctx.pinnedVersion) { + return { + ok: false, + detail, + manualFix: + "The PATH iii is the pinned version, so startup can use it and no action is needed. To give agentmemory its own copy in ~/.agentmemory/bin, run npx -y @agentmemory/agentmemory@latest upgrade and accept the iii-engine install step.", + }; + } + return { ok: false, detail }; }, fix: async () => effects.runIiiInstaller().then((r) => ({ diff --git a/src/cli/worker-connection.ts b/src/cli/worker-connection.ts new file mode 100644 index 0000000000..b3f535b536 --- /dev/null +++ b/src/cli/worker-connection.ts @@ -0,0 +1,109 @@ +import { createConnection } from "node:net"; + +export type WorkerConnection = "connected" | "engine-only" | "unrecognized" | "unreachable"; + +type FetchLike = (url: string, init: { signal: AbortSignal; headers: Record }) => Promise<{ + status: number; + body?: { cancel(): Promise } | null; +}>; + +export type WorkerProbeOptions = { + headers?: Record; + timeoutMs?: number; + fetchImpl?: FetchLike; + engineBusReachable?: () => Promise; +}; + +async function routeStatus( + url: string, + headers: Record, + timeoutMs: number, + fetchImpl: FetchLike, +): Promise { + try { + const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), headers }); + void res.body?.cancel().catch(() => {}); + return res.status; + } catch { + return null; + } +} + +export async function tcpPortOpen(host: string, port: number, timeoutMs = 1000): Promise { + return await new Promise((resolve) => { + const socket = createConnection({ host, port }); + const done = (open: boolean) => { + socket.destroy(); + resolve(open); + }; + socket.setTimeout(timeoutMs); + socket.once("connect", () => done(true)); + socket.once("timeout", () => done(false)); + socket.once("error", () => done(false)); + }); +} + +export async function probeWorkerConnection( + base: string, + options: WorkerProbeOptions = {}, +): Promise { + const headers = options.headers ?? {}; + const timeoutMs = options.timeoutMs ?? 2000; + const fetchImpl = options.fetchImpl ?? (fetch as unknown as FetchLike); + const [livez, health] = await Promise.all([ + routeStatus(`${base}/agentmemory/livez`, headers, timeoutMs, fetchImpl), + routeStatus(`${base}/agentmemory/health`, headers, timeoutMs, fetchImpl), + ]); + if (livez === null && health === null) return "unreachable"; + const answered = (status: number | null) => status !== null && status !== 404; + if (answered(livez) || answered(health)) return "connected"; + const busReachable = options.engineBusReachable + ? await options.engineBusReachable().catch(() => false) + : false; + return busReachable ? "engine-only" : "unrecognized"; +} + +export const DEFAULT_START_COMMAND = "npx -y @agentmemory/agentmemory@latest"; + +export const ENGINE_ONLY_DOCKER_GUIDE = + "https://github.com/rohitg00/agentmemory/blob/main/deploy/README.md#migrating-from-the-legacy-cli-docker-mode"; + +export function engineOnlyFix(startCommand = DEFAULT_START_COMMAND): string { + return `Stop the process that owns this port (an old Docker container or an iii you started yourself), then start agentmemory with: ${startCommand}. For Docker, run the current image instead.`; +} + +export function shellArg(value: string, platform: NodeJS.Platform = process.platform): string { + if (platform === "win32") { + const trimmed = /^[A-Za-z]:[\\/]$/.test(value) ? value : value.replace(/[\\/]+$/, "") || value; + if (/^[A-Za-z0-9._:\\/-]+$/.test(trimmed)) return trimmed; + if (!/[$`%"]/.test(trimmed)) return `"${trimmed}"`; + return `'${trimmed.replace(/'/g, "''")}'`; + } + if (/^[A-Za-z0-9._:/@%+=,-]+$/.test(value)) return value; + return `'${value.replace(/'/g, `'"'"'`)}'`; +} + +export const UNRECOGNIZED_DOCKER_NOTE = + `Old Docker images from the legacy CLI Docker mode keep the engine port inside the container and also show this state. Docker migration: ${ENGINE_ONLY_DOCKER_GUIDE}`; + +export const UNRECOGNIZED_SERVICE_FIX = + `Check that AGENTMEMORY_URL or --port points at agentmemory. If another program owns this port, start agentmemory on a free port with: ${DEFAULT_START_COMMAND} --port .`; + +export function engineOnlyLines(base: string, startCommand = DEFAULT_START_COMMAND): string[] { + return [ + `The iii engine is running at ${base}, but the agentmemory worker is not connected to it.`, + "The engine returns 404 for /agentmemory/livez and /agentmemory/health. Version, health and the viewer stay unavailable until the worker connects.", + "Old Docker images from the legacy CLI Docker mode ran only the engine and show this state.", + `Fix: ${engineOnlyFix(startCommand)}`, + `Docker migration: ${ENGINE_ONLY_DOCKER_GUIDE}`, + ]; +} + +export function unrecognizedServiceLines(base: string): string[] { + return [ + `A server answers at ${base}, but agentmemory does not.`, + "It returns 404 for /agentmemory/livez and /agentmemory/health, and the iii engine port does not answer. It can be another program on this port, or a remote iii engine without the agentmemory worker.", + UNRECOGNIZED_DOCKER_NOTE, + `Fix: ${UNRECOGNIZED_SERVICE_FIX}`, + ]; +} diff --git a/test/cli-doctor-fixes.test.ts b/test/cli-doctor-fixes.test.ts index 37428eebac..50b09dc268 100644 --- a/test/cli-doctor-fixes.test.ts +++ b/test/cli-doctor-fixes.test.ts @@ -13,6 +13,7 @@ import { doctorPromptsAllowed, DIAGNOSTIC_IDS, dryRunPlan, + failureReport, parseEnvFile, placeholderProviderKeys, realProviderKeys, @@ -43,6 +44,7 @@ function stubEffects(overrides: Partial = {}): DoctorEffects { localBinIiiPath: () => "/Users/test/.local/bin/iii", iiiBinaryVersion: () => III_PINNED_VERSION, externalEngineRunning: async () => false, + workerConnection: async () => "connected", viewerReachable: async () => true, runInit: async () => ({ ok: true, message: "wrote .env" }), openEditor: async () => ({ ok: true, message: "saved" }), @@ -63,6 +65,7 @@ describe("doctor v2 diagnostic catalog", () => { expect(DIAGNOSTIC_IDS).toContain("stale-pidfile"); expect(DIAGNOSTIC_IDS).toContain("env-placeholder-keys"); expect(DIAGNOSTIC_IDS).toContain("iii-on-path-not-local-bin"); + expect(DIAGNOSTIC_IDS).toContain("worker-not-connected"); }); it("every diagnostic has check, fix, message, and fixPreview", () => { @@ -483,6 +486,107 @@ describe("doctor v2 diagnostic catalog", () => { expect(lines[0]).toContain("All checks passing"); }); + it("worker-not-connected fails when the engine runs without the agentmemory worker", async () => { + const diagnostics = buildDiagnostics(stubEffects({ workerConnection: async () => "engine-only" })); + const check = diagnostics.find((d) => d.id === "worker-not-connected")!; + const status = await check.check(stubCtx()); + expect(status.ok).toBe(false); + expect(status.detail).toContain("http://localhost:3111"); + expect(canAutoFix(check, status)).toBe(false); + expect(check.fixPreview).toContain("npx -y @agentmemory/agentmemory@latest"); + expect(check.moreInfo).toContain("Docker"); + }); + + it("worker-not-connected keeps the selected port in the recovery command", async () => { + const diagnostics = buildDiagnostics(stubEffects({ workerConnection: async () => "engine-only" })); + const check = diagnostics.find((d) => d.id === "worker-not-connected")!; + const startCommand = "npx -y @agentmemory/agentmemory@latest --port 4111"; + const status = await check.check({ ...stubCtx(), baseUrl: "http://localhost:4111", startCommand }); + expect(status.manualFix).toContain(`start agentmemory with: ${startCommand}.`); + expect(failureReport(check, status).fix).toContain("--port 4111"); + }); + + it("worker-not-connected points a managed Compose engine at the Compose failure report", async () => { + const diagnostics = buildDiagnostics(stubEffects({ workerConnection: async () => "managed-worker-down" })); + const check = diagnostics.find((d) => d.id === "worker-not-connected")!; + const status = await check.check(stubCtx()); + expect(status.ok).toBe(false); + expect(status.detail).toContain("managed Worker Compose"); + expect(status.manualFix).toContain("agentmemory status"); + expect(status.manualFix).not.toContain("Stop the process"); + }); + + it("worker-not-connected keeps the selected instance in the managed Compose recovery commands", async () => { + const diagnostics = buildDiagnostics(stubEffects({ workerConnection: async () => "managed-worker-down" })); + const check = diagnostics.find((d) => d.id === "worker-not-connected")!; + const status = await check.check({ ...stubCtx(), targetArgs: " --instance 1", startCommand: "npx -y @agentmemory/agentmemory@latest --instance 1" }); + expect(status.manualFix).toContain("agentmemory status --instance 1 "); + expect(status.manualFix).toContain("agentmemory stop --instance 1 "); + expect(status.manualFix).toContain("start again with: npx -y @agentmemory/agentmemory@latest --instance 1."); + }); + + it("worker-not-connected does not call an unrecognized service an engine", async () => { + const diagnostics = buildDiagnostics(stubEffects({ workerConnection: async () => "unrecognized" })); + const check = diagnostics.find((d) => d.id === "worker-not-connected")!; + const status = await check.check(stubCtx()); + expect(status.ok).toBe(false); + expect(status.detail).toContain("iii engine port does not answer"); + expect(status.manualFix).toContain("AGENTMEMORY_URL"); + expect(status.manualFix).not.toContain("Stop the process"); + const report = failureReport(check, status); + expect(report.problem).not.toContain("iii engine is running"); + expect(report.fix).toContain("legacy CLI Docker mode"); + }); + + it("worker-not-connected passes when the worker answers or the server is down", async () => { + for (const connection of ["connected", "unreachable"] as const) { + const diagnostics = buildDiagnostics(stubEffects({ workerConnection: async () => connection })); + const check = diagnostics.find((d) => d.id === "worker-not-connected")!; + expect((await check.check(stubCtx())).ok).toBe(true); + } + }); + + it("iii-on-path-not-local-bin explains which iii is used and how to fix it", async () => { + const privatePath = "/Users/test/.agentmemory/bin/iii"; + const diagnostics = buildDiagnostics(stubEffects({ + findIiiBinary: () => "/opt/homebrew/bin/iii", + localBinIiiPath: () => privatePath, + iiiBinaryVersion: (bin) => (bin === privatePath ? null : "0.99.99"), + })); + const check = diagnostics.find((d) => d.id === "iii-on-path-not-local-bin")!; + const status = await check.check(stubCtx()); + expect(status.detail).toContain("/opt/homebrew/bin/iii"); + expect(status.detail).toContain("0.99.99"); + expect(check.message).toContain("PATH"); + expect(check.message).toContain("~/.agentmemory/bin/iii"); + const report = failureReport(check, status); + expect(report.problem).toContain(check.message); + expect(report.fix).toContain("manual fix:"); + expect(report.fix).toContain("npx -y @agentmemory/agentmemory@latest"); + }); + + it("iii-on-path-not-local-bin says no action is needed when the PATH iii is the pinned version", async () => { + const privatePath = "/Users/test/.agentmemory/bin/iii"; + const diagnostics = buildDiagnostics(stubEffects({ + findIiiBinary: () => "/opt/homebrew/bin/iii", + localBinIiiPath: () => privatePath, + iiiBinaryVersion: (bin) => (bin === privatePath ? null : III_PINNED_VERSION), + })); + const check = diagnostics.find((d) => d.id === "iii-on-path-not-local-bin")!; + const status = await check.check(stubCtx()); + expect(status.ok).toBe(false); + expect(status.manualFix).toContain("no action is needed"); + expect(failureReport(check, status).fix).toContain("upgrade"); + }); + + it("failureReport gives every failing diagnostic its message and a fix hint", () => { + for (const diagnostic of buildDiagnostics(stubEffects())) { + const report = failureReport(diagnostic, { ok: false, detail: "stub fail" }); + expect(report.problem).toBe(`${diagnostic.id} ✗ ${diagnostic.message} (stub fail)`); + expect(report.fix).toMatch(/^(manual fix|fix): \S/); + } + }); + it("dryRunPlan labels manual-only diagnostics without promising automatic fixes", () => { const diagnostic = buildDiagnostics(stubEffects()) .find((d) => d.id === "iii-on-path-not-local-bin")!; diff --git a/test/cli-worker-connection.test.ts b/test/cli-worker-connection.test.ts new file mode 100644 index 0000000000..f71cc597c4 --- /dev/null +++ b/test/cli-worker-connection.test.ts @@ -0,0 +1,174 @@ +import { createServer, type Server } from "node:net"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + engineOnlyLines, + probeWorkerConnection, + shellArg, + tcpPortOpen, + unrecognizedServiceLines, +} from "../src/cli/worker-connection.js"; + +function fakeFetch(routes: Record) { + return vi.fn(async (url: string) => { + const path = new URL(url).pathname; + const result = routes[path]; + if (result instanceof Error || result === undefined) throw result ?? new Error("connection refused"); + return { status: result, body: null }; + }); +} + +const busUp = async () => true; +const busDown = async () => false; + +describe("probeWorkerConnection", () => { + const base = "http://localhost:3111"; + + it("reports engine-only when both routes return 404 and the engine bus answers", async () => { + const fetchImpl = fakeFetch({ "/agentmemory/livez": 404, "/agentmemory/health": 404 }); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl, engineBusReachable: busUp })).toBe("engine-only"); + }); + + it("reports an unrecognized service when both routes return 404 and no engine bus answers", async () => { + const fetchImpl = fakeFetch({ "/agentmemory/livez": 404, "/agentmemory/health": 404 }); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl, engineBusReachable: busDown })).toBe("unrecognized"); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl })).toBe("unrecognized"); + }); + + it("reports an unrecognized service when the engine bus check throws", async () => { + const fetchImpl = fakeFetch({ "/agentmemory/livez": 404, "/agentmemory/health": 404 }); + const engineBusReachable = async () => { throw new Error("bad url"); }; + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl, engineBusReachable })).toBe("unrecognized"); + }); + + it("reports connected when the worker answers", async () => { + const fetchImpl = fakeFetch({ "/agentmemory/livez": 200, "/agentmemory/health": 200 }); + const engineBusReachable = vi.fn(busUp); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl, engineBusReachable })).toBe("connected"); + expect(engineBusReachable).not.toHaveBeenCalled(); + }); + + it("treats an auth rejection as a connected worker", async () => { + const fetchImpl = fakeFetch({ "/agentmemory/livez": 401, "/agentmemory/health": 401 }); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl })).toBe("connected"); + }); + + it("does not report engine-only when only one route is missing", async () => { + const fetchImpl = fakeFetch({ "/agentmemory/livez": 404, "/agentmemory/health": 200 }); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl, engineBusReachable: busUp })).toBe("connected"); + }); + + it("checks the engine bus when one route returns 404 and the other request fails", async () => { + for (const routes of [ + { "/agentmemory/livez": 404 }, + { "/agentmemory/health": 404 }, + ]) { + const fetchImpl = fakeFetch(routes); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl, engineBusReachable: busUp })).toBe("engine-only"); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl, engineBusReachable: busDown })).toBe("unrecognized"); + } + }); + + it("reports connected when one route answers and the other request fails", async () => { + for (const routes of [ + { "/agentmemory/livez": 200 }, + { "/agentmemory/health": 200 }, + ]) { + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl: fakeFetch(routes) })).toBe("connected"); + } + }); + + it("reports unreachable when nothing answers", async () => { + const fetchImpl = fakeFetch({}); + expect(await probeWorkerConnection(base, { timeoutMs: 500, fetchImpl })).toBe("unreachable"); + }); + + it("sends the given headers to both routes", async () => { + const fetchImpl = fakeFetch({ "/agentmemory/livez": 200, "/agentmemory/health": 200 }); + await probeWorkerConnection(base, { headers: { Authorization: "Bearer x" }, timeoutMs: 500, fetchImpl }); + expect(fetchImpl).toHaveBeenCalledTimes(2); + for (const call of fetchImpl.mock.calls as unknown as Array<[string, { headers: Record }]>) { + expect(call[1].headers).toEqual({ Authorization: "Bearer x" }); + } + }); +}); + +describe("tcpPortOpen", () => { + let server: Server | null = null; + + afterEach(async () => { + await new Promise((resolve) => (server ? server.close(() => resolve()) : resolve())); + server = null; + }); + + it("reports an open and a closed port", async () => { + server = createServer((socket) => socket.destroy()); + await new Promise((resolve) => server!.listen(0, "127.0.0.1", () => resolve())); + const port = (server.address() as { port: number }).port; + expect(await tcpPortOpen("127.0.0.1", port, 500)).toBe(true); + await new Promise((resolve) => server!.close(() => resolve())); + server = null; + expect(await tcpPortOpen("127.0.0.1", port, 500)).toBe(false); + }); +}); + +describe("engineOnlyLines", () => { + it("explains the state, the start command and old Docker images", () => { + const text = engineOnlyLines("http://localhost:3111").join("\n"); + expect(text).toContain("iii engine is running at http://localhost:3111"); + expect(text).toContain("agentmemory worker is not connected"); + expect(text).toContain("npx -y @agentmemory/agentmemory@latest"); + expect(text).toContain("Docker"); + }); + + it("uses the given start command so recovery keeps the selected port", () => { + const text = engineOnlyLines("http://localhost:4111", "npx -y @agentmemory/agentmemory@latest --port 4111").join("\n"); + expect(text).toContain("start agentmemory with: npx -y @agentmemory/agentmemory@latest --port 4111."); + }); +}); + +describe("unrecognizedServiceLines", () => { + it("does not claim an iii engine and does not tell the user to stop the service", () => { + const text = unrecognizedServiceLines("http://localhost:3111").join("\n"); + expect(text).toContain("A server answers at http://localhost:3111, but agentmemory does not."); + expect(text).not.toContain("iii engine is running"); + expect(text).not.toContain("Stop the process"); + expect(text).toContain("--port "); + }); + + it("points old Docker images that keep the engine port internal at the migration guide", () => { + const text = unrecognizedServiceLines("http://localhost:3111").join("\n"); + expect(text).toContain("legacy CLI Docker mode"); + expect(text).toContain("#migrating-from-the-legacy-cli-docker-mode"); + }); +}); + +describe("shellArg", () => { + it("leaves plain paths unquoted", () => { + expect(shellArg("/home/alice/data", "linux")).toBe("/home/alice/data"); + expect(shellArg("C:\\Users\\alice\\data", "win32")).toBe("C:\\Users\\alice\\data"); + }); + + it("quotes apostrophes, backslashes, spaces and dollar signs for POSIX shells", () => { + expect(shellArg("/home/alice/O'Reilly", "darwin")).toBe(`'/home/alice/O'"'"'Reilly'`); + expect(shellArg("/tmp/a b", "linux")).toBe("'/tmp/a b'"); + expect(shellArg("/tmp/a\\b", "linux")).toBe("'/tmp/a\\b'"); + expect(shellArg("/tmp/$HOME", "linux")).toBe("'/tmp/$HOME'"); + }); + + it("double-quotes Windows paths so Command Prompt and PowerShell keep spaces and metacharacters literal", () => { + expect(shellArg("C:\\my data", "win32")).toBe(`"C:\\my data"`); + expect(shellArg("C:\\Users\\O'Reilly\\a & calc & rem", "win32")).toBe(`"C:\\Users\\O'Reilly\\a & calc & rem"`); + }); + + it("single-quotes Windows paths with dollar signs so PowerShell keeps them literal", () => { + expect(shellArg("C:\\data\\$archive", "win32")).toBe(`'C:\\data\\$archive'`); + expect(shellArg("C:\\O'Reilly\\$x", "win32")).toBe(`'C:\\O''Reilly\\$x'`); + }); + + it("drops trailing Windows separators so no backslash precedes a closing quote", () => { + expect(shellArg("C:\\my data\\", "win32")).toBe(`"C:\\my data"`); + expect(shellArg("C:\\data\\", "win32")).toBe("C:\\data"); + expect(shellArg("C:\\", "win32")).toBe("C:\\"); + expect(shellArg("C:/", "win32")).toBe("C:/"); + }); +});