Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(cli): status and doctor stop vouching for what they did not check (CL-17)

KageBinaryd24b80cbb3cf
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 63aa92d8..8e2712f6 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -422,7 +422,7 @@ Two deliberate exceptions remain:
answer and which `text` only implied through warning lines:
```
- status backend=ok endpoint=http://localhost:8090 graph_complete=true map_complete=false rev=2467 last_ingest_at=2026-08-29T01:38:43.341Z stale_files=0 stale=false
+ status backend=ok endpoint=http://localhost:8090 graph_health=ok graph_complete=true map_complete=false rev=2467 last_ingest_at=2026-08-29T01:38:43.341Z stale_files=0 stale=false
```
`graph_complete` and `map_complete` are two different questions and a
@@ -433,6 +433,13 @@ Two deliberate exceptions remain:
`graph_complete`, not `map_complete`: it is a claim about files having
changed, and a missing hierarchy does not make a file out of date.
+ `graph_health` is a third, separate question: whether the graph the backend
+ holds for this workspace is whole (`ok`), has nodes but lost their edges
+ (`degraded`, followed by a `graph` record with the fix), holds nothing
+ (`empty`), or could not be checked (`unverified`: no workspace here, an older
+ backend, a slow stats read). `stale=false` says no file changed since the
+ last ingest; it does not vouch for the graph.
+
Still routing to `text`: `diff --content` (verbatim hunks) and `ingest`, a
hidden implementation-detail command whose output is a completion summary.
diff --git a/ix-cli/src/cli/__tests__/backend-container-inspection.test.ts b/ix-cli/src/cli/__tests__/backend-container-inspection.test.ts
index 8dc4421c..a7ba2ccf 100644
--- a/ix-cli/src/cli/__tests__/backend-container-inspection.test.ts
+++ b/ix-cli/src/cli/__tests__/backend-container-inspection.test.ts
@@ -38,7 +38,7 @@ describe("inspectBackendContainer", () => {
throw new Error(`unexpected docker invocation: ${args.join(" ")}`);
});
- expect(checkBackendImage()).toMatchObject({
+ expect(checkBackendImage("http://localhost:8090")).toMatchObject({
kind: "ok",
container: {
containerId: "backend-id",
@@ -66,9 +66,30 @@ describe("inspectBackendContainer", () => {
throw new Error(`unexpected docker invocation: ${args.join(" ")}`);
});
- expect(inspectBackendContainer()).toMatchObject({
+ expect(inspectBackendContainer("http://localhost:8090")).toMatchObject({
containerId: "local-id",
imageRef: "ix-memory-layer-dev:latest",
});
});
+
+ it("inspects the container publishing the configured endpoint's port, not 8090", () => {
+ execFileSync.mockImplementation((_command: string, args: string[]) => {
+ if (args[0] === "info") return "ok";
+ if (args[0] === "ps" && args.includes("publish=8190")) return "other-id";
+ if (args[0] === "ps") return "default-id";
+ if (args[0] === "inspect" && args[1] === "other-id") {
+ return "sha256:other|::|ix-memory-layer-dev:latest|::||::|";
+ }
+ if (args[0] === "image" && args[2] === "sha256:other") return "[]";
+ throw new Error(`unexpected docker invocation: ${args.join(" ")}`);
+ });
+
+ expect(inspectBackendContainer("http://127.0.0.1:8190")).toMatchObject({ containerId: "other-id" });
+ });
+
+ it("does not inspect any container for a remote endpoint", () => {
+ expect(inspectBackendContainer("https://ix.example.com")).toBeNull();
+ expect(checkBackendImage("https://ix.example.com")).toEqual({ kind: "remote" });
+ expect(execFileSync).not.toHaveBeenCalled();
+ });
});
diff --git a/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts b/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts
index 446fc774..f6b3afaa 100644
--- a/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts
+++ b/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts
@@ -2,6 +2,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Command } from "commander";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
type FakeWorkspace = { workspace_id: string; workspace_name: string; root_path: string; default: boolean };
@@ -21,6 +24,7 @@ const scope = {
sourceBaseline: true,
mapCompleted: true,
cloudReady: false,
+ databaseDown: false,
};
vi.mock("../../client/api.js", () => ({
@@ -95,10 +99,16 @@ vi.mock("../backend-status.js", async (orig) => ({
vi.mock("../commands/upgrade.js", async (orig) => ({
...(await orig<typeof import("../commands/upgrade.js")>()),
- readBackendHealth: async () => ({ status: "ok", schema_version: 3 }),
+ // A current backend reports its database; a 503 with a health body is that
+ // backend saying ArangoDB is down.
+ readBackendHealth: async () => {
+ if (scope.databaseDown) throw new Error('503: {"status":"degraded","database":"unreachable","schema_version":3}');
+ return { status: "ok", schema_version: 3, database: "reachable" };
+ },
}));
let savedEndpoint: string | undefined;
+let savedHome: string | undefined;
let savedExitCode: number | string | undefined;
beforeEach(() => {
@@ -110,10 +120,14 @@ beforeEach(() => {
scope.sourceBaseline = true;
scope.mapCompleted = true;
scope.cloudReady = false;
+ scope.databaseDown = false;
// Belt and braces with the mocks above: nothing in this test may depend on a
// backend being reachable, or on how quickly a given OS refuses a connection.
savedEndpoint = process.env.IX_ENDPOINT;
process.env.IX_ENDPOINT = "http://127.0.0.1:9";
+ // "Config file parses" reads $IX_HOME/config.yaml: never the developer's.
+ savedHome = process.env.IX_HOME;
+ process.env.IX_HOME = mkdtempSync(join(tmpdir(), "ix-doctor-"));
savedExitCode = process.exitCode;
process.exitCode = undefined;
});
@@ -121,6 +135,9 @@ beforeEach(() => {
afterEach(() => {
if (savedEndpoint === undefined) delete process.env.IX_ENDPOINT;
else process.env.IX_ENDPOINT = savedEndpoint;
+ rmSync(process.env.IX_HOME!, { recursive: true, force: true });
+ if (savedHome === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = savedHome;
process.exitCode = savedExitCode;
});
@@ -175,6 +192,18 @@ describe("ix doctor", () => {
);
});
+ it("fails, naming the database, when the backend reports ArangoDB unreachable", async () => {
+ scope.databaseDown = true;
+
+ const lines = await runDoctor();
+
+ expect(lines[0]).toContain("healthy=false");
+ expect(process.exitCode).toBe(1);
+ // The server answered, so it is reachable; the database is what is down.
+ expect(lines).toContain('check name="Server reachable" status=ok detail="http://127.0.0.1:9 → degraded"');
+ expect(lines.find((l) => l.includes('name="Database reachable"'))).toMatch(/status=fail .*cannot reach ArangoDB/);
+ });
+
it("does not report a partial graph as healthy when no completed baseline exists", async () => {
scope.sourceBaseline = false;
scope.mapCompleted = false;
diff --git a/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts b/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts
new file mode 100644
index 00000000..b5db9395
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts
@@ -0,0 +1,204 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { createServer, type Server } from "node:http";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Command } from "commander";
+
+/**
+ * CL-17: `ix status` said "Graph is up to date" on the evidence of file mtimes
+ * alone, `ix search` in a workspace with no nodes said "try part of the name",
+ * and `ix doctor` passed with the database dead. Each now reports only what it
+ * checked.
+ */
+
+// A backend whose /v1/stats answer each test sets.
+let stats: unknown = { nodes: { total: 0 }, edges: { total: 0 } };
+let rev = 1;
+let server: Server;
+let endpoint: string;
+
+beforeAll(async () => {
+ server = createServer((req, res) => {
+ req.resume();
+ req.on("end", () => {
+ const url = req.url ?? "";
+ const send = (status: number, body: unknown) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(body));
+ };
+ if (url.startsWith("/v1/health")) return send(200, { status: "ok", schema_version: 3, database: "reachable" });
+ if (url.startsWith("/v1/revisions/current")) return send(200, { rev });
+ if (url.startsWith("/v1/stats")) return send(200, stats);
+ if (url.startsWith("/v1/stitch/system/")) return send(404, { error: "not_found" });
+ if (url.startsWith("/v1/search")) return send(200, []);
+ send(404, { error: "not_found" });
+ });
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ const addr = server.address();
+ endpoint = `http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : 0}`;
+});
+
+afterAll(async () => {
+ await new Promise<void>((r) => server.close(() => r()));
+});
+
+let home: string;
+let repo: string;
+let saved: Record<string, string | undefined>;
+let cwd: string;
+let out: string[];
+
+beforeEach(() => {
+ vi.resetModules();
+ rev += 1; // a new backend revision: no cached graph verdict carries over
+ home = mkdtempSync(join(tmpdir(), "ix-honest-"));
+ repo = join(home, "repo");
+ mkdirSync(repo);
+ saved = { IX_HOME: process.env.IX_HOME, IX_ENDPOINT: process.env.IX_ENDPOINT, IX_GRAPH_HEALTH: process.env.IX_GRAPH_HEALTH };
+ process.env.IX_HOME = home;
+ process.env.IX_ENDPOINT = endpoint;
+ delete process.env.IX_GRAPH_HEALTH;
+ cwd = process.cwd();
+ process.chdir(repo);
+ out = [];
+ vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => { out.push(a.join(" ")); });
+ vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { out.push(a.join(" ")); });
+ vi.spyOn(process.stderr, "write").mockImplementation((s: string | Uint8Array) => { out.push(String(s)); return true; });
+ vi.spyOn(process.stdout, "write").mockImplementation((s: string | Uint8Array) => { out.push(String(s)); return true; });
+});
+
+afterEach(() => {
+ process.chdir(cwd);
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ vi.restoreAllMocks();
+ rmSync(home, { recursive: true, force: true });
+});
+
+function registerRepo(): void {
+ writeFileSync(join(home, "config.yaml"),
+ `endpoint: ${endpoint}\nformat: text\nworkspaces:\n - workspace_id: "ws1"\n workspace_name: repo\n root_path: ${repo}\n default: true\n`);
+}
+
+async function run(register: (p: Command) => void, args: string[]): Promise<string> {
+ const program = new Command().exitOverride();
+ register(program);
+ await program.parseAsync(args, { from: "user" });
+ return out.join("\n");
+}
+
+const HOLLOW = {
+ nodes: { total: 400, byKind: [{ kind: "file", count: 20 }, { kind: "function", count: 380 }] },
+ edges: { total: 10, byPredicate: [{ predicate: "CALLS", count: 10 }] },
+};
+
+describe("ix status", () => {
+ async function status(...args: string[]): Promise<string> {
+ vi.doMock("../stale.js", async (orig) => ({
+ ...(await orig<typeof import("../stale.js")>()),
+ detectStaleFiles: () => ({
+ graphCompleted: true, mapCompleted: true, currentRev: 7, lastIngestAt: null,
+ staleFiles: 0, sampleChangedFiles: [], replayedFiles: [], parseTimeouts: [],
+ }),
+ }));
+ const { registerStatusCommand } = await import("../commands/status.js");
+ return run(registerStatusCommand, ["status", ...args]);
+ }
+
+ it("says what it checked: no files changed, and the graph is degraded", async () => {
+ registerRepo();
+ stats = HOLLOW;
+ const text = await status();
+ expect(text).not.toMatch(/Graph is up to date/);
+ expect(text).toMatch(/No files changed since the last ingest/);
+ expect(text).toMatch(/Graph:\s+degraded/);
+ expect(text).toMatch(/ix reset --workspace --yes --ingest/);
+ });
+
+ it("adds graphHealth to JSON, keeping the existing fields", async () => {
+ registerRepo();
+ stats = HOLLOW;
+ const json = JSON.parse(await status("--format", "json"));
+ expect(json.graphCompleted).toBe(true);
+ expect(json.mapCompleted).toBe(true);
+ expect(json.graphHealth).toMatchObject({ status: "degraded", reason: "hollow" });
+ });
+
+ it("reports graph_health and the graph record in llm", async () => {
+ registerRepo();
+ stats = { nodes: { total: 0 }, edges: { total: 0 } };
+ const llm = await status("--format", "llm");
+ expect(llm).toMatch(/^status .*graph_health=empty/m);
+ expect(llm).toMatch(/^graph status=empty reason=no_nodes/m);
+ });
+
+ it("says unverified, not ok, when the directory is in no workspace", async () => {
+ stats = HOLLOW;
+ const json = JSON.parse(await status("--format", "json"));
+ expect(json.graphHealth.status).toBe("unverified");
+ });
+});
+
+describe("ix search in a workspace with no nodes", () => {
+ it("says the workspace is empty instead of suggesting another term", async () => {
+ registerRepo();
+ stats = { nodes: { total: 0 }, edges: { total: 0 } };
+ const { registerSearchCommand } = await import("../commands/search.js");
+ const json = JSON.parse(await run(registerSearchCommand, ["search", "greet", "--format", "json"]));
+ const codes = json.diagnostics.map((d: { code: string }) => d.code);
+ expect(codes).toContain("workspace_empty");
+ expect(json.diagnostics.find((d: { code: string }) => d.code === "no_results").message).toMatch(/ix map/);
+ });
+
+ it("keeps the usual hint when the workspace has nodes", async () => {
+ registerRepo();
+ stats = { nodes: { total: 50, byKind: [], }, edges: { total: 60, byPredicate: [] } };
+ const { registerSearchCommand } = await import("../commands/search.js");
+ const llm = await run(registerSearchCommand, ["search", "greet", "--format", "llm"]);
+ expect(llm).not.toMatch(/workspace_empty/);
+ expect(llm).toMatch(/hint text="No entity name matches/);
+ });
+});
+
+describe("doctor checks", () => {
+ it("Database reachable: from the backend's own report, else from a read that touches it", async () => {
+ const { assessDatabase } = await import("../commands/doctor.js");
+ const never = async () => { throw new Error("must not probe"); };
+ expect(await assessDatabase({ status: "ok", database: "reachable" }, never)).toMatchObject({ ok: true });
+ expect(await assessDatabase({ status: "degraded", database: "unreachable" }, never))
+ .toMatchObject({ ok: false, detail: expect.stringMatching(/ArangoDB/) });
+ expect(await assessDatabase(new Error("fetch failed"), never)).toMatchObject({ ok: true, detail: expect.stringMatching(/skipped/) });
+ // An older backend: health says nothing about the database.
+ expect(await assessDatabase({ status: "ok" }, async () => ({ rev: 3 }))).toMatchObject({ ok: true });
+ expect(await assessDatabase({ status: "ok" }, async () => { throw new Error("500: arango connection refused"); }))
+ .toMatchObject({ ok: false, detail: expect.stringMatching(/could not read its database: 500/) });
+ });
+
+ it("a 503 health body is an answer, anything else is not", async () => {
+ const { healthFromError } = await import("../commands/doctor.js");
+ expect(healthFromError(new Error('503: {"status":"degraded","database":"unreachable"}')))
+ .toEqual({ status: "degraded", database: "unreachable" });
+ expect(healthFromError(new Error("503: <html>bad gateway</html>"))).toBeNull();
+ expect(healthFromError(new Error('500: {"status":"x"}'))).toBeNull();
+ });
+
+ it("Config file parses", async () => {
+ const { assessConfigFile } = await import("../commands/doctor.js");
+ expect(assessConfigFile("c.yaml", () => null)).toMatchObject({ ok: true, detail: expect.stringMatching(/defaults/) });
+ expect(assessConfigFile("c.yaml", () => "endpoint: http://localhost:8090\n")).toMatchObject({ ok: true });
+ expect(assessConfigFile("c.yaml", () => "endpoint: [unclosed\n")).toMatchObject({ ok: false, detail: expect.stringMatching(/does not parse/) });
+ expect(assessConfigFile("c.yaml", () => "- a\n- b\n")).toMatchObject({ ok: false });
+ });
+
+ it("ripgrep on PATH warns, never fails", async () => {
+ const { checkRipgrep } = await import("../commands/doctor.js");
+ expect(checkRipgrep(() => "ripgrep 15.1.0\n")).toEqual({ ok: true, detail: "ripgrep 15.1.0" });
+ expect(checkRipgrep(() => { throw new Error("ENOENT"); })).toMatchObject({ ok: false, warn: true });
+ });
+});
diff --git a/ix-cli/src/cli/backend-status.ts b/ix-cli/src/cli/backend-status.ts
index 76e9c013..6a034f89 100644
--- a/ix-cli/src/cli/backend-status.ts
+++ b/ix-cli/src/cli/backend-status.ts
@@ -18,10 +18,10 @@ import { execFileSync, spawnSync } from "node:child_process";
import { join } from "node:path";
import { homedir } from "node:os";
import type { IxClient } from "../client/api.js";
-import { fetchBackendHealth } from "./backend-version.js";
+import { fetchBackendHealth, isLocalEndpoint } from "./backend-version.js";
+import { getEndpoint } from "./config.js";
export const BACKEND_IMAGE = "ghcr.io/ix-infrastructure/ix-memory-layer";
-const BACKEND_PORT = "8090";
const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");
const STANDARD_BACKEND_DIR = join(IX_HOME, "backend");
@@ -96,10 +96,28 @@ function isReleasedBackendRef(imageRef: string): boolean {
imageRef.startsWith(`${BACKEND_IMAGE}@`);
}
-/** Inspect the backend reached through the container publishing its port. */
-export function inspectBackendContainer(): BackendContainer | null {
+/**
+ * The host port a container publishes to serve `endpoint`, or null when the
+ * endpoint is not on this machine and no local container can be serving it.
+ * Taken from the configured endpoint, not a fixed 8090: with IX_ENDPOINT on
+ * another port, a fixed 8090 inspected some other stack on the same host.
+ */
+export function backendPortFor(endpoint: string): string | null {
+ if (!isLocalEndpoint(endpoint)) return null;
+ try {
+ const url = new URL(endpoint);
+ return url.port || (url.protocol === "https:" ? "443" : "80");
+ } catch {
+ return null;
+ }
+}
+
+/** Inspect the backend reached through the container publishing the endpoint's port. */
+export function inspectBackendContainer(endpoint: string = getEndpoint()): BackendContainer | null {
+ const port = backendPortFor(endpoint);
+ if (!port) return null;
const publisherIds = containerIds(
- docker(["ps", "--filter", `publish=${BACKEND_PORT}`, "--format", "{{.ID}}"]),
+ docker(["ps", "--filter", `publish=${port}`, "--format", "{{.ID}}"]),
);
if (publisherIds.length === 0) return null;
@@ -109,7 +127,7 @@ export function inspectBackendContainer(): BackendContainer | null {
const directBackend = publishers.find((container) => isReleasedBackendRef(container.imageRef));
if (directBackend) return directBackend;
- // A hardened compose may publish 8090 through nginx while the memory layer
+ // A hardened compose may publish the port through nginx while the memory layer
// stays on an internal network. Follow the publisher's compose project to
// the service whose role is the backend instead of comparing nginx to GHCR.
for (const publisher of publishers) {
@@ -243,6 +261,7 @@ export type BackendImageStatus =
| { kind: "digest-mismatch"; container: BackendContainer; latestImageId: string }
| { kind: "latest-not-pulled"; container: BackendContainer }
| { kind: "not-running" }
+ | { kind: "remote" }
| { kind: "docker-unavailable" };
/**
@@ -250,9 +269,11 @@ export type BackendImageStatus =
* `:latest` image. Conclusions only when we can prove a mismatch; an
* inconclusive state (latest not pulled, docker down) never reports a problem.
*/
-export function checkBackendImage(): BackendImageStatus {
+export function checkBackendImage(endpoint: string = getEndpoint()): BackendImageStatus {
+ // A remote endpoint is served by no container on this machine.
+ if (!backendPortFor(endpoint)) return { kind: "remote" };
if (!dockerAvailable()) return { kind: "docker-unavailable" };
- const container = inspectBackendContainer();
+ const container = inspectBackendContainer(endpoint);
if (!container) return { kind: "not-running" };
const latestImageId = docker(["image", "inspect", `${BACKEND_IMAGE}:latest`, "--format", "{{.Id}}"]);
diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.ts
index a68adba7..509fa81e 100644
--- a/ix-cli/src/cli/commands/doctor.ts
+++ b/ix-cli/src/cli/commands/doctor.ts
@@ -20,6 +20,8 @@ import { resolveReadSystemId } from "../resolve.js";
import { assessGraphStats } from "../graph-health.js";
import { llmLine, printLlmLines } from "../llm.js";
import { existsSync, readFileSync } from "node:fs";
+import { execFileSync } from "node:child_process";
+import { parse as parseYaml } from "yaml";
import { join as pathJoin, resolve as resolvePath, win32 as winPath } from "node:path";
import { homedir } from "node:os";
import {
@@ -35,7 +37,7 @@ import { loadIngestBaseline } from "../ingest-baseline.js";
import { isCloudReady } from "../remote.js";
import { hasCompletedMapBaseline } from "../stale.js";
import { printJson } from "../format.js";
-import type { CapabilitiesResponse } from "../../client/types.js";
+import type { CapabilitiesResponse, HealthResponse } from "../../client/types.js";
interface CheckResult {
ok: boolean;
@@ -239,6 +241,71 @@ export function assessLocalAuth(
};
}
+/**
+ * A health answer, including the 503 a backend sends while it cannot reach its
+ * database: that is a server that answered, and the body says what is wrong.
+ * Thrown for anything else.
+ */
+export function healthFromError(err: unknown): HealthResponse | null {
+ const m = /^503:\s*(\{.*\})\s*$/s.exec((err as Error)?.message ?? "");
+ if (!m) return null;
+ try {
+ const body = JSON.parse(m[1]!) as HealthResponse;
+ return typeof body?.status === "string" ? body : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * "Database reachable" from the health answer. A backend that reports
+ * `database` says so itself; an older one never touched the database for
+ * health, so `probe` asks a route that does (`/v1/revisions/current`).
+ */
+export async function assessDatabase(
+ health: HealthResponse | Error,
+ probe: () => Promise<unknown>,
+): Promise<CheckResult> {
+ if (health instanceof Error) return { ok: true, detail: "backend unreachable (skipped)" };
+ if (health.database === "reachable") return { ok: true, detail: "reachable (backend health)" };
+ if (health.database === "unreachable") {
+ return { ok: false, detail: "the memory layer cannot reach ArangoDB — check 'ix docker status' and 'ix docker logs'" };
+ }
+ try {
+ await probe();
+ return { ok: true, detail: "reachable (read the current revision)" };
+ } catch (e) {
+ const msg = (e as Error)?.message ?? String(e);
+ return { ok: false, detail: `the backend could not read its database: ${msg.slice(0, 200)}` };
+ }
+}
+
+/** "Config file parses": a config.yaml Ix cannot read is otherwise silently replaced by defaults. */
+export function assessConfigFile(configPath: string, read: (p: string) => string | null): CheckResult {
+ const raw = read(configPath);
+ if (raw === null) return { ok: true, detail: "no config file (defaults)" };
+ try {
+ const parsed = parseYaml(raw);
+ if (parsed !== null && parsed !== undefined && (typeof parsed !== "object" || Array.isArray(parsed))) {
+ return { ok: false, detail: `${configPath} is not a mapping of settings` };
+ }
+ return { ok: true, detail: configPath };
+ } catch (e) {
+ const first = ((e as Error)?.message ?? String(e)).split("\n")[0];
+ return { ok: false, detail: `${configPath} does not parse, so Ix runs on defaults: ${first}` };
+ }
+}
+
+/** "ripgrep on PATH": `ix text` needs it; everything else works without it. */
+export function checkRipgrep(run: () => string = () => execFileSync("rg", ["--version"], { encoding: "utf-8", timeout: 5000 })): CheckResult {
+ try {
+ const first = run().split("\n")[0]?.trim();
+ return { ok: true, detail: first || "rg found" };
+ } catch {
+ return { ok: false, warn: true, detail: "rg not found on PATH — 'ix text' needs ripgrep" };
+ }
+}
+
export function registerDoctorCommand(program: Command): void {
program
.command("doctor")
@@ -294,6 +361,16 @@ export function registerDoctorCommand(program: Command): void {
return { stats, scope, systemId };
})());
+ // One /v1/health for "Server reachable" and "Database reachable". A 503
+ // with a health body is the backend reporting a dead database, so it is
+ // an answer, not a failure to reach the server.
+ let healthOnce: Promise<HealthResponse> | undefined;
+ const health = (): Promise<HealthResponse> => (healthOnce ??= readBackendHealth(client).catch((e: unknown) => {
+ const degraded = healthFromError(e);
+ if (degraded) return degraded;
+ throw e;
+ }));
+
const checks: Check[] = [
{
name: "Server reachable",
@@ -301,8 +378,10 @@ export function registerDoctorCommand(program: Command): void {
try {
// Records what the backend says it is running; see
// backend-version.ts. Free — this response is already needed.
- const h = await readBackendHealth(client);
- return { ok: h.status === "ok", detail: `${endpoint} → ${h.status}` };
+ const h = await health();
+ // A degraded answer is still a server that answered; the
+ // database check below names what is wrong with it.
+ return { ok: h.status === "ok" || h.status === "degraded", detail: `${endpoint} → ${h.status}` };
} catch (e: any) {
// An unreachable backend is where a fatal Arango boot loop hides:
// the container restarts forever, memory-layer never leaves
@@ -310,7 +389,7 @@ export function registerDoctorCommand(program: Command): void {
// indistinguishable from "not started yet". Say what the stack
// actually reported. Ix#614.
const base = e.message ?? "unreachable";
- const failure = dockerAvailable() ? diagnoseBackendStack() : null;
+ const failure = isLocalEndpoint(endpoint) && dockerAvailable() ? diagnoseBackendStack() : null;
if (!failure) return { ok: false, detail: base };
const parts = [`${base} — ${failure.service} is ${failure.state}`];
if (failure.lastError) parts.push(` last log: ${failure.lastError}`);
@@ -319,6 +398,18 @@ export function registerDoctorCommand(program: Command): void {
}
},
},
+ {
+ name: "Database reachable",
+ run: async () => {
+ let h: HealthResponse | Error;
+ try {
+ h = await health();
+ } catch (e) {
+ h = e instanceof Error ? e : new Error(String(e));
+ }
+ return assessDatabase(h, () => client.currentRevision());
+ },
+ },
{
name: "Backend token",
run: async () => {
@@ -479,7 +570,7 @@ export function registerDoctorCommand(program: Command): void {
// Ix#270: trust the running container, not the version stamp.
name: "Backend is the released image",
run: async () => {
- const status = checkBackendImage();
+ const status = checkBackendImage(endpoint);
switch (status.kind) {
case "ok": {
if (isNonStandardBackend(status.container)) {
@@ -505,7 +596,9 @@ export function registerDoctorCommand(program: Command): void {
case "latest-not-pulled":
return { ok: true, warn: true, detail: `can't verify — ${BACKEND_IMAGE}:latest not pulled locally` };
case "not-running":
- return { ok: true, detail: "no backend container on :8090 (skipped)" };
+ return { ok: true, detail: `no backend container for ${endpoint} (skipped)` };
+ case "remote":
+ return { ok: true, detail: "remote endpoint, no local container (skipped)" };
case "docker-unavailable":
return { ok: true, detail: "docker unavailable (skipped)" };
}
@@ -528,6 +621,17 @@ export function registerDoctorCommand(program: Command): void {
},
];
+ checks.push(
+ {
+ name: "Config file parses",
+ run: async () => assessConfigFile(
+ pathJoin(ixHome(), "config.yaml"),
+ (p) => { try { return readFileSync(p, "utf-8"); } catch { return null; } },
+ ),
+ },
+ { name: "ripgrep on PATH", run: async () => checkRipgrep() },
+ );
+
// Windows-only: a launcher pointing at a CLI the upgrade moved (Ix#385).
if (process.platform === "win32") {
checks.push({
@@ -571,7 +675,7 @@ export function registerDoctorCommand(program: Command): void {
console.log();
if (hasFailure) {
- renderError("Some checks failed. Run with --format json for details.");
+ renderError("Some checks failed.");
} else if (hasWarning) {
renderSuccess("All checks passed (with warnings).");
} else {
diff --git a/ix-cli/src/cli/commands/search.ts b/ix-cli/src/cli/commands/search.ts
index 5aff7e16..d1bd283c 100644
--- a/ix-cli/src/cli/commands/search.ts
+++ b/ix-cli/src/cli/commands/search.ts
@@ -12,6 +12,7 @@ import { stderr } from "../stderr.js";
import { llmLine } from "../llm.js";
import { isQuiet, projectRow } from "../output-shape.js";
import { normalizePathSeparators } from "../path-match.js";
+import { checkGraphHealth } from "../graph-health.js";
/** One `ix search` row as the llm renderer takes it. */
export interface SearchLlmRow {
@@ -80,6 +81,10 @@ export function emptySearchHint(term: string, opts: { kind?: string; path?: stri
return `No entity name matches. Try part of the name, ${drop}or use ix text for a literal string.`;
}
+/** Said instead of {@link emptySearchHint} when the scope holds no nodes at all. */
+export const WORKSPACE_EMPTY_MESSAGE =
+ "The graph for this workspace has no nodes, so no search can match. Run ix map to build it.";
+
/** Structural kinds that should rank higher than incidental matches. */
const STRUCTURAL_KINDS = new Set([
"class", "trait", "object", "interface", "function", "method", "module", "file",
@@ -476,6 +481,17 @@ Examples:
// Taken after every push, not before: `test_candidates_hidden` is the
// one diagnostic here that names rows the caller CANNOT see, and it is
// added below the `unfiltered_search` push.
+ // Nothing came back at all: before suggesting a better term, ask whether
+ // there is anything to search. An empty workspace answered "No entity
+ // name matches. Try part of the name" to every term. One cached stats
+ // read, only on this path.
+ if (rawNodes.length === 0 && (workspaceId || systemId)) {
+ const graph = await checkGraphHealth(client, { workspaceId, systemId });
+ if (graph.status === "empty") {
+ diagnostics.push({ code: "workspace_empty", message: WORKSPACE_EMPTY_MESSAGE });
+ }
+ }
+ const workspaceEmpty = diagnostics.some((d) => d.code === "workspace_empty");
const llmDiagnostics = diagnostics.filter((d) => d.code !== "unfiltered_search");
if (opts.format === "llm") {
@@ -488,7 +504,7 @@ Examples:
score: tierRelevance(s.rank.tier),
match: s.rank.tier >= NON_NAME_TIER ? s.rank.matchSource : undefined,
}));
- const hint = emptySearchHint(term, opts);
+ const hint = workspaceEmpty ? undefined : emptySearchHint(term, opts);
for (const line of renderSearchLlm(rows, rawNodes.length, llmDiagnostics, hint)) console.log(line);
return;
}
@@ -511,12 +527,14 @@ Examples:
totalCandidates: rawNodes.length,
},
diagnostics: ranked.length === 0
- ? [...diagnostics, { code: "no_results", message: emptySearchHint(term, opts) }]
+ ? [...diagnostics, { code: "no_results", message: workspaceEmpty ? WORKSPACE_EMPTY_MESSAGE : emptySearchHint(term, opts) }]
: diagnostics,
});
} else {
formatNodes(ranked, opts.format);
- if (ranked.length === 0 && !isQuiet()) stderr(chalk.dim(emptySearchHint(term, opts)));
+ if (ranked.length === 0 && !isQuiet()) {
+ stderr(chalk.dim(workspaceEmpty ? WORKSPACE_EMPTY_MESSAGE : emptySearchHint(term, opts)));
+ }
if (pathWindowLimited) stderr(chalk.dim(diagnostics.find(d => d.code === "path_search_truncated")!.message));
const hint = roleHint(hiddenTestCount);
if (hint) stderr(chalk.dim(hint));
diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.ts
index bcd5eeeb..d96ce0a9 100644
--- a/ix-cli/src/cli/commands/status.ts
+++ b/ix-cli/src/cli/commands/status.ts
@@ -4,12 +4,22 @@ import type { Command } from "commander";
import { renderSection, renderKeyValue, renderWarning, renderNote, renderSuccess } from "../ui.js";
import { createClient } from "../../client/factory.js";
import { readBackendHealth } from "./upgrade.js";
-import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
+import { findWorkspaceForCwd, getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { detectStaleFiles } from "../stale.js";
import { llmError, llmLine, printLlmLines } from "../llm.js";
import { backendUnreachableError, isBackendUnreachable } from "../errors.js";
import { printJson } from "../format.js";
-import { describeReplayedChanges } from "../graph-health.js";
+import {
+ checkGraphHealth,
+ describeReplayedChanges,
+ graphHealthJson,
+ graphHealthLlmFields,
+ graphHealthProse,
+ isUnhealthy,
+ type GraphHealth,
+ type GraphHealthScope,
+} from "../graph-health.js";
+import { detectSystem } from "../system.js";
interface StatusStaleInfo {
graphCompleted: boolean;
@@ -39,10 +49,12 @@ export function renderStatusLlm(
backend: string,
endpoint: string,
staleInfo: StatusStaleInfo | null,
+ graph?: GraphHealth,
): string[] {
const lines = [llmLine("status", [
["backend", backend],
["endpoint", endpoint],
+ ["graph_health", graph ? graphHealthWord(graph) : null],
["graph_complete", staleInfo ? String(staleInfo.graphCompleted) : null],
["map_complete", staleInfo ? String(staleInfo.mapCompleted) : null],
["rev", staleInfo ? String(staleInfo.currentRev) : null],
@@ -55,6 +67,7 @@ export function renderStatusLlm(
|| (staleInfo.parseTimeouts?.length ?? 0) > 0 ? "true" : "false")
: null],
])];
+ if (graph && isUnhealthy(graph)) lines.push(llmLine("graph", graphHealthLlmFields(graph)));
for (const f of staleInfo?.sampleChangedFiles ?? []) {
lines.push(llmLine("changed", [["path", f]]));
}
@@ -67,6 +80,27 @@ export function renderStatusLlm(
return lines;
}
+/**
+ * The graph verdict as `ix status` says it. "unknown" reads as "unverified":
+ * the check could not run (no workspace here, an old backend, a slow stats
+ * probe), which is not the same as a graph that was checked and is fine.
+ */
+export function graphHealthWord(graph: GraphHealth): string {
+ return graph.status === "unknown" ? "unverified" : graph.status;
+}
+
+/**
+ * The read scope for the status root: its system when it is in one, else the
+ * workspace containing it. None when the root is in no registered workspace,
+ * so the graph check answers "unverified" rather than judging another repo.
+ */
+export function statusGraphScope(root: string): GraphHealthScope | undefined {
+ const systemId = detectSystem(root)?.systemId;
+ if (systemId) return { systemId };
+ const workspaceId = findWorkspaceForCwd(root)?.workspace_id;
+ return workspaceId ? { workspaceId } : undefined;
+}
+
/** The `ix status` warning for files the last run skipped on the parse budget. */
function describeStatusParseTimeouts(files: readonly string[], sample = 5): string {
const shown = files.slice(0, sample).join(", ");
@@ -86,6 +120,13 @@ export function registerStatusCommand(program: Command): void {
try {
const health = await readBackendHealth(client);
const root = resolveWorkspaceRoot(opts.root);
+ // "No files changed" is about mtimes; whether the graph behind them is
+ // whole is a separate question, asked of the backend. Cached per
+ // backend revision, bounded, and never throws.
+ const scope = statusGraphScope(root);
+ const graphCheck: Promise<GraphHealth> = scope
+ ? checkGraphHealth(client, scope)
+ : Promise.resolve({ status: "unknown" });
// Detect stale files
let staleInfo;
@@ -95,8 +136,10 @@ export function registerStatusCommand(program: Command): void {
staleInfo = null;
}
+ const graph = await graphCheck;
+
if (opts.format === "llm") {
- printLlmLines(renderStatusLlm(health.status, getEndpoint(), staleInfo ?? null));
+ printLlmLines(renderStatusLlm(health.status, getEndpoint(), staleInfo ?? null, graph));
} else if (opts.format === "json") {
const result: any = {
backend: health.status,
@@ -108,12 +151,14 @@ export function registerStatusCommand(program: Command): void {
sampleChangedFiles: staleInfo?.sampleChangedFiles ?? [],
replayedFiles: staleInfo?.replayedFiles ?? [],
parseTimeouts: staleInfo?.parseTimeouts ?? [],
+ graphHealth: { ...graphHealthJson(graph), status: graphHealthWord(graph) },
};
printJson(result);
} else {
renderSection("Status");
renderKeyValue("Ix Memory", health.status);
renderKeyValue("Endpoint", getEndpoint());
+ renderKeyValue("Graph", graphHealthWord(graph));
if (staleInfo) {
renderKeyValue("Revision", String(staleInfo.currentRev));
if (staleInfo.lastIngestAt) {
@@ -137,7 +182,9 @@ export function registerStatusCommand(program: Command): void {
}
renderNote("Run ix map to update.");
} else if (staleInfo.parseTimeouts.length === 0) {
- renderSuccess("Graph is up to date.");
+ // Only what was checked: no file's mtime moved. The graph's own
+ // state is the "Graph" line above and the warning below.
+ renderSuccess("No files changed since the last ingest.");
}
if (staleInfo.graphCompleted && staleInfo.parseTimeouts.length > 0) {
// Beside the other states, not instead of them: another map
@@ -149,6 +196,7 @@ export function registerStatusCommand(program: Command): void {
renderNote("Source graph reads remain available, but hierarchy views may be incomplete.");
}
}
+ if (isUnhealthy(graph)) renderWarning(graphHealthProse(graph));
}
} catch (err) {
// Only a transport failure is "not reachable". Anything else — a 500
diff --git a/ix-cli/src/client/types.ts b/ix-cli/src/client/types.ts
index 21890c45..5f7eb698 100644
--- a/ix-cli/src/client/types.ts
+++ b/ix-cli/src/client/types.ts
@@ -189,6 +189,10 @@ export interface HealthResponse {
// you are" and the wrong one to "what are you really", which is what
// checkBackendImage's digest comparison is for.
release_version?: string;
+ // Whether the memory layer can reach its database (Ix-memory 1.0.33+). With
+ // it unreachable the backend answers 503 and `status: "degraded"`. Absent
+ // from older backends, whose health never touched the database.
+ database?: "reachable" | "unreachable";
}
export interface PatchSource {