Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(doctor): distinguish the workspace cwd matched from the default it fell back to (#519)
KageBinary090b229a02ff
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6c136819..d32681cf 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -250,13 +250,23 @@ jobs:working-directory: ix-clirun: |set -euo pipefail- IX="node dist/cli/main.js"+ # Absolute, because doctor is run from the mapped directory below.+ IX="node $PWD/dist/cli/main.js"+ FIXTURE="$PWD/test/fixtures/sample_project"echo "::group::status"; $IX status; echo "::endgroup::"- echo "::group::map fixture"; $IX map test/fixtures/sample_project --silent; echo "::endgroup::"+ echo "::group::map fixture"; $IX map "$FIXTURE" --silent; echo "::endgroup::"echo "::group::search"; $IX search BillingService --format json | tee search.json; echo "::endgroup::"node -e "const r=require('./search.json');const n=(r.results||r).length||0;if(!n){console.error('no search results after map');process.exit(1)}console.log('search returned',n,'results')"- echo "::group::doctor"; $IX doctor --format json | tee doctor.json; echo "::endgroup::"+ # From the directory the fixture was mapped into. doctor answers for+ # its own cwd (#518), and `ix-cli` is not a registered workspace — a+ # healthy result there would mean doctor was quoting some other graph.+ echo "::group::doctor"; (cd "$FIXTURE" && $IX doctor --format json) | tee doctor.json; echo "::endgroup::"node -e "const d=require('./doctor.json');if(!d.healthy){console.error('doctor not healthy');process.exit(1)}"+ # The converse, and the regression guard for #518: in a directory no+ # workspace covers, doctor must say so instead of passing every check+ # against whichever workspace happens to be the default.+ echo "::group::doctor (unmapped cwd)"; (cd "$RUNNER_TEMP" && $IX doctor --format json) | tee doctor-unmapped.json; echo "::endgroup::"+ node -e "const d=require('./doctor-unmapped.json');const c=(d.checks||[]).find(c=>c.name==='Workspace for this directory');if(!c){console.error('no workspace check in doctor output');process.exit(1)}if(c.ok||d.healthy){console.error('doctor reported healthy in a directory with no workspace');process.exit(1)}console.log('unmapped cwd reported:',c.detail)"- name: Backend logs on failureif: failure()diff --git a/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts b/ix-cli/src/cli/__tests__/doctor-stats-once.test.tsindex 287995ff..961c02b3 100644--- a/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts+++ b/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts@@ -1,9 +1,20 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Command } from "commander";+type FakeWorkspace = { workspace_id: string; workspace_name: string; root_path: string; default: boolean };++// The workspace cwd belongs to, and an unrelated one that happens to be the+// registered default. Keeping both named makes it visible in the assertions+// which repo a count was taken from.+const CURRENT: FakeWorkspace =+ { workspace_id: "workspace-current", workspace_name: "current-repo", root_path: "/repos/current", default: false };+const OTHER: FakeWorkspace =+ { workspace_id: "workspace-other", workspace_name: "other-repo", root_path: "/repos/other", default: true };+const statsCalls: Array<{ workspaceId?: string; systemId?: string } | undefined> = [];const scope = {- workspaceId: "workspace-current" as string | undefined,+ matched: undefined as FakeWorkspace | undefined,+ fallback: undefined as FakeWorkspace | undefined,systemId: undefined as string | undefined,};@@ -14,10 +25,11 @@ vi.mock("../../client/api.js", () => ({// Both ids undefined is the unscoped call, not a match on a scope that// happens to be unset — compare only ids that are actually present, or// `undefined === undefined` silently answers with the workspace figure.- const scoped =- (opts?.workspaceId !== undefined && opts.workspaceId === scope.workspaceId) ||- (opts?.systemId !== undefined && opts.systemId === scope.systemId);- if (scoped) return { nodes: { total: 3457 }, edges: { total: 10365 } };+ if (opts?.systemId !== undefined) return { nodes: { total: 3457 }, edges: { total: 10365 } };+ if (opts?.workspaceId === CURRENT.workspace_id) return { nodes: { total: 3457 }, edges: { total: 10365 } };+ // Deliberately distinct so a count sourced from the wrong workspace cannot+ // coincide with the right one's.+ if (opts?.workspaceId === OTHER.workspace_id) return { nodes: { total: 7717 }, edges: { total: 16983 } };return { nodes: { total: 22969 }, edges: { total: 10365 } };}async conflicts() { return []; }@@ -25,9 +37,14 @@ vi.mock("../../client/api.js", () => ({},}));-vi.mock("../bootstrap.js", async (orig) => ({- ...(await orig<typeof import("../bootstrap.js")>()),- resolveWorkspaceId: () => scope.workspaceId,+// Mocked at the config layer, not at `resolveWorkspaceId`. Stubbing that helper+// is what let #518 through: it returns one id for both "cwd matched this+// workspace" and "cwd matched nothing, so here is the default", so a test that+// replaces it can never exercise the difference.+vi.mock("../config.js", async (orig) => ({+ ...(await orig<typeof import("../config.js")>()),+ findWorkspaceForCwd: () => scope.matched,+ getDefaultWorkspace: () => scope.fallback,}));vi.mock("../resolve.js", async (orig) => ({@@ -56,7 +73,8 @@ let savedEndpoint: string | undefined;beforeEach(() => {vi.resetModules();statsCalls.length = 0;- scope.workspaceId = "workspace-current";+ scope.matched = CURRENT;+ scope.fallback = undefined;scope.systemId = undefined;// 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.@@ -102,7 +120,13 @@ describe("ix doctor", () => {const lines = await runDoctor();expect(statsCalls).toEqual([{ workspaceId: "workspace-current", systemId: undefined }]);- expect(lines).toContain('check name="Graph has nodes" status=ok detail="3457 nodes in this workspace"');+ expect(lines).toContain(`check name="Graph has nodes" status=ok detail="3457 nodes in workspace 'current-repo'"`);+ });++ it("names the workspace cwd resolved to", async () => {+ const lines = await runDoctor();++ expect(lines).toContain(`check name="Workspace for this directory" status=ok detail="workspace 'current-repo'"`);});it("uses the active system scope for a co-ingested workspace", async () => {@@ -117,10 +141,51 @@ describe("ix doctor", () => {it("says the count is unscoped when no workspace is registered", async () => {// A count of everything is not wrong here, but it is the one case where// naming a scope would be — there is no active workspace to name.- scope.workspaceId = undefined;+ scope.matched = undefined;+ scope.fallback = undefined;const lines = await runDoctor();expect(lines).toContain('check name="Graph has nodes" status=ok detail="22969 nodes in all workspaces"');+ expect(lines).toContain(+ 'check name="Workspace for this directory" status=warn detail="none registered yet — run `ix map`"',+ );+ });++ describe("a directory no workspace is registered for (#518)", () => {+ // cwd matches nothing, and an unrelated repo holds `default: true`.+ beforeEach(() => {+ scope.matched = undefined;+ scope.fallback = OTHER;+ });++ it("does not report the run as healthy", async () => {+ const lines = await runDoctor();++ // The whole of #518: this said healthy=true, so "All checks passed" is+ // what a reader acted on.+ expect(lines[0]).toContain("healthy=false");+ // cwd reaches the assertion through the llm format's quoting, which+ // escapes `\`. A Windows path therefore renders as `D:\\a\\Ix`, not as the+ // raw `process.cwd()` — escape it here rather than compare against the+ // unescaped string, which passes on POSIX and fails on Windows for a+ // reason that has nothing to do with the check under test.+ const cwd = process.cwd().replace(/\\/g, "\\\\");+ expect(lines).toContain(+ 'check name="Workspace for this directory" status=fail detail="no workspace registered for ' ++ `${cwd} — reads here answer from workspace 'other-repo' instead. ` ++ 'Run `ix map` in this directory."',+ );+ });++ it("attributes the counts to the workspace they came from, not to this directory", async () => {+ const lines = await runDoctor();++ expect(lines).toContain(`check name="Graph has nodes" status=ok detail="7717 nodes in workspace 'other-repo'"`);+ expect(lines).toContain(`check name="Graph has edges" status=ok detail="16983 edges in workspace 'other-repo'"`);+ // The deictic phrasing is the misleading part — it must not survive for a+ // directory that resolved to someone else's graph.+ expect(lines.join("\n")).not.toContain("in this workspace");+ });});});diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.tsindex 8c0ae63d..f782c37b 100644--- a/ix-cli/src/cli/commands/doctor.ts+++ b/ix-cli/src/cli/commands/doctor.ts@@ -2,8 +2,7 @@ import type { Command } from "commander";import chalk from "chalk";import { renderSection, renderSuccess, renderError } from "../ui.js";import { IxClient } from "../../client/api.js";-import { getEndpoint } from "../config.js";-import { resolveWorkspaceId } from "../bootstrap.js";+import { findWorkspaceForCwd, getDefaultWorkspace, getEndpoint } from "../config.js";import { resolveReadSystemId } from "../resolve.js";import { llmLine, printLlmLines } from "../llm.js";import { existsSync, readFileSync } from "node:fs";@@ -132,8 +131,19 @@ export function registerDoctorCommand(program: Command): void {// less self-evident: "0 nodes" against a backend holding thousands reads// as a broken install until it says whose nodes it counted. The scope// travels with the count so the check explains itself.- let statsOnce: Promise<{ stats: any; scope: string }> | undefined;- const sharedStats = (): Promise<{ stats: any; scope: string }> => (statsOnce ??= (async () => {+ // Resolved here rather than through `resolveWorkspaceId()`, which answers a+ // directory that matches no workspace by substituting whichever one carries+ // `default: true`. That collapses two states doctor has to tell apart — cwd+ // matched THIS workspace, and cwd matched nothing so here is an unrelated+ // one — into a single id. Reporting the second as "this workspace" is how a+ // never-ingested directory passed every check while quoting another repo's+ // graph (#518). Local, so it still answers when the backend is unreachable.+ const cwd = process.cwd();+ const matchedWorkspace = findWorkspaceForCwd(cwd);+ const substitutedWorkspace = matchedWorkspace ? undefined : getDefaultWorkspace();++ let statsOnce: Promise<{ stats: any; scope: string; systemId?: string }> | undefined;+ const sharedStats = (): Promise<{ stats: any; scope: string; systemId?: string }> => (statsOnce ??= (async () => {// Scoped the same way `ix stats` scopes, because doctor disagreeing with// stats about the size of the graph is the whole of #510. Not a// tombstone fix: /v1/stats filters `deleted_rev == null` in every one of@@ -142,12 +152,19 @@ export function registerDoctorCommand(program: Command): void {// some other workspace on the same backend, which is how a freshly// reset workspace still looked like a 17k-node graph.const systemId = await resolveReadSystemId(client);- const workspaceId = systemId ? undefined : resolveWorkspaceId();- const stats = await client.stats({ workspaceId, systemId });- // Undefined on both means no workspace is registered yet, and the- // request really was unscoped — say that rather than name a scope.- const scope = systemId ? "this system" : workspaceId ? "this workspace" : "all workspaces";- return { stats, scope };+ const workspace = systemId ? undefined : (matchedWorkspace ?? substitutedWorkspace);+ const stats = await client.stats({ workspaceId: workspace?.workspace_id, systemId });+ // Named, not deictic. "this workspace" is only true when cwd actually+ // matched one, and the case where it has not is exactly the case where+ // the reader most needs to know whose count they are being shown.+ // No workspace at all means the request really was unscoped — say that+ // rather than name a scope.+ const scope = systemId+ ? "this system"+ : workspace+ ? `workspace '${workspace.workspace_name}'`+ : "all workspaces";+ return { stats, scope, systemId };})());const checks: Check[] = [@@ -164,6 +181,38 @@ export function registerDoctorCommand(program: Command): void {}},},+ {+ name: "Workspace for this directory",+ run: async () => {+ // A system scope supersedes the per-directory workspace, so ask what+ // the read path resolved to before judging cwd. Best-effort: if the+ // backend is unreachable the local answer below is still the right+ // one, and "Server reachable" already reports the outage.+ let systemScoped = false;+ try {+ systemScoped = Boolean((await sharedStats()).systemId);+ } catch { /* fall through to the local answer */ }++ if (systemScoped) return { ok: true, detail: "scoped to the active system" };+ if (matchedWorkspace) return { ok: true, detail: `workspace '${matchedWorkspace.workspace_name}'` };+ if (substitutedWorkspace) {+ return {+ ok: false,+ detail:+ `no workspace registered for ${cwd} — reads here answer from ` ++ `workspace '${substitutedWorkspace.workspace_name}' instead. ` ++ "Run `ix map` in this directory.",+ };+ }+ // Nothing registered anywhere: honest and self-explanatory, and the+ // graph checks below already fail on the empty count. Warn rather+ // than fail so a fresh install reports one problem, not three.+ // `{ ok: false, warn: true }` is the shape a warning takes — `warn`+ // is read on the not-ok branch, so `ok: true` here would render as a+ // clean pass and say nothing.+ return { ok: false, warn: true, detail: "none registered yet — run `ix map`" };+ },+ },{name: "Graph has nodes",run: async () => {