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
feat(workspace): workspace isolation — scoped node identity + read filtering (client) (#224)
Joseph Mikhail89e8127456e2
diff --git a/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts b/core-ingestion/src/__tests__/patchBuilder.resolution.test.tsindex 1a4aae1e..4f16ec9a 100644--- a/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts+++ b/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts@@ -95,7 +95,7 @@ describe('buildPatchWithResolution', () => {},];- const patch = buildPatchWithResolution(result, 'test-hash', resolvedEdges);+ const patch = buildPatchWithResolution(result, 'test-hash', '', resolvedEdges);const callEdges = patch.ops.filter(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS');expect(callEdges).toHaveLength(2);@@ -139,7 +139,7 @@ struct Trajectory {};confidence: 0.9,});- const patch = buildPatchWithResolution(importer!, 'test-hash', resolvedEdges);+ const patch = buildPatchWithResolution(importer!, 'test-hash', '', resolvedEdges);const importEdge = patch.ops.find((op) => op.type === 'UpsertEdge' && op.predicate === 'IMPORTS',);diff --git a/core-ingestion/src/patch-builder.ts b/core-ingestion/src/patch-builder.tsindex 890e388d..1cbfefd9 100644--- a/core-ingestion/src/patch-builder.ts+++ b/core-ingestion/src/patch-builder.ts@@ -22,17 +22,35 @@ function normalizePath(filePath: string): string {return filePath.replace(/\\/g, '/').toLowerCase();}-function nodeId(filePath: string, name: string): string {- return deterministicId(`${normalizePath(filePath)}:${name}`);-}+/**+ * Identity helpers bound to a single workspace. Folding `workspaceId` into every+ * id keeps the same relative path in two different workspaces from colliding on+ * a shared backend, while staying stable within a workspace. Binding it once via+ * a factory means every call site below is scoped automatically (no per-call+ * threading to forget). `workspaceId` is empty only for callers that have not+ * adopted workspace-scoped identity yet.+ */+function makeIds(workspaceId: string) {+ const ns = workspaceId ? `${workspaceId}:` : '';+ return {+ nodeId: (filePath: string, name: string): string =>+ deterministicId(`${ns}${normalizePath(filePath)}:${name}`),-function edgeId(filePath: string, src: string, dst: string, predicate: string): string {- return deterministicId(`${normalizePath(filePath)}:${src}:${dst}:${predicate}`);-}+ edgeId: (filePath: string, src: string, dst: string, predicate: string): string =>+ deterministicId(`${ns}${normalizePath(filePath)}:${src}:${dst}:${predicate}`),++ // Chunk id is keyed on file + kind + name + start line to survive minor edits.+ chunkId: (filePath: string, chunkKind: string, name: string | null, startLine: number): string =>+ deterministicId(`${ns}${normalizePath(filePath)}:chunk:${chunkKind}:${name ?? 'file_body'}:${startLine}`),++ // patchId for a (filePath, sourceHash, extractorVersion) triple.+ computePatchId: (filePath: string, sourceHash: string, extractor: string): string =>+ deterministicId(`${ns}${normalizePath(filePath)}:${sourceHash}:${extractor}`),-/** Deterministic ID for a chunk — keyed on file + kind + name + start line to survive minor edits. */-function chunkId(filePath: string, chunkKind: string, name: string | null, startLine: number): string {- return deterministicId(`${normalizePath(filePath)}:chunk:${chunkKind}:${name ?? 'file_body'}:${startLine}`);+ // Legacy patchId (pre-1.1 scheme, no extractor suffix).+ legacyPatchId: (filePath: string, sourceHash: string): string =>+ deterministicId(`${ns}${filePath}:${sourceHash}`),+ };}// ---------------------------------------------------------------------------@@ -57,15 +75,8 @@ export function extractorName(): string {/** Previous extractor versions — their patches are superseded when re-ingesting. */export const PREVIOUS_EXTRACTORS = ['tree-sitter/1.20', 'tree-sitter/1.19', 'tree-sitter/1.18', 'tree-sitter/1.17', 'tree-sitter/1.16', 'tree-sitter/1.15', 'tree-sitter/1.14', 'tree-sitter/1.13', 'tree-sitter/1.12', 'tree-sitter/1.11', 'tree-sitter/1.10', 'tree-sitter/1.9', 'tree-sitter/1.8', 'tree-sitter/1.7', 'tree-sitter/1.6', 'tree-sitter/1.5', 'tree-sitter/1.4', 'tree-sitter/1.3', 'tree-sitter/1.2', 'tree-sitter/1.1'];-/** Compute a patchId for a (filePath, sourceHash, extractorVersion) triple. */-function computePatchId(filePath: string, sourceHash: string, extractor: string): string {- return deterministicId(`${normalizePath(filePath)}:${sourceHash}:${extractor}`);-}--/** Compute the legacy patchId (pre-1.1 scheme, no extractor suffix). */-function legacyPatchId(filePath: string, sourceHash: string): string {- return deterministicId(`${filePath}:${sourceHash}`);-}+// nodeId / edgeId / chunkId / computePatchId / legacyPatchId are produced by+// makeIds(workspaceId) above so every id is scoped to its workspace.// ---------------------------------------------------------------------------// Build a GraphPatchPayload from a FileParseResult@@ -74,9 +85,11 @@ function legacyPatchId(filePath: string, sourceHash: string): string {export function buildPatch(result: FileParseResult,sourceHash: string,+ workspaceId: string,previousSourceHash?: string): GraphPatchPayload {const { filePath, entities, chunks, relationships } = result;+ const { nodeId, edgeId, chunkId, computePatchId, legacyPatchId } = makeIds(workspaceId);const ops: PatchOp[] = [];// Build a qualified-key map so that same-named entities in different@@ -259,6 +272,7 @@ export function buildPatch(sourceHash,extractor,sourceType: sourceType(filePath),+ workspaceId,},baseRev: 0,ops,@@ -275,6 +289,7 @@ export function buildPatch(export function buildPatchWithResolution(result: FileParseResult,sourceHash: string,+ workspaceId: string,resolvedEdges: ResolvedEdge[],previousSourceHash?: string,): GraphPatchPayload {@@ -291,6 +306,7 @@ export function buildPatchWithResolution(}const { filePath, entities, chunks, relationships } = result;+ const { nodeId, edgeId, chunkId, computePatchId, legacyPatchId } = makeIds(workspaceId);const ops: PatchOp[] = [];const entityQKey = new Map<ParsedEntity, string>();@@ -453,6 +469,7 @@ export function buildPatchWithResolution(sourceHash,extractor,sourceType: sourceType(filePath),+ workspaceId,},baseRev: 0,ops,diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.tsindex f30036bc..081f86a4 100644--- a/ix-cli/src/cli/bootstrap.ts+++ b/ix-cli/src/cli/bootstrap.ts@@ -5,7 +5,7 @@ import { randomUUID } from "node:crypto";import { execFileSync } from "node:child_process";import chalk from "chalk";import { IxClient } from "../client/api.js";-import { getEndpoint, loadConfig, saveConfig, type WorkspaceConfig } from "./config.js";+import { getEndpoint, loadConfig, saveConfig, findWorkspaceForCwd, getDefaultWorkspace, type WorkspaceConfig } from "./config.js";export interface BootstrapResult {createdConfig: boolean;@@ -30,24 +30,49 @@ export function ensureLocalConfig(): boolean {* Ensure the current directory (or given path) is registered as a workspace.* Returns the workspace name. Does nothing if already registered.*/-export function ensureWorkspaceRegistered(cwd = process.cwd()): { registered: boolean; name: string } {+function getOrCreateWorkspace(cwd: string): { ws: WorkspaceConfig; created: boolean } {const rootPath = resolve(cwd);- const name = basename(rootPath);const config = loadConfig();const existing = (config.workspaces ?? []).find(w => w.root_path === rootPath);- if (existing) return { registered: false, name: existing.workspace_name };+ if (existing) return { ws: existing, created: false };const workspaces = config.workspaces ?? [];const hasDefault = workspaces.some(w => w.default);- const newWs: WorkspaceConfig = {+ const ws: WorkspaceConfig = {workspace_id: randomUUID().slice(0, 8),- workspace_name: name,+ workspace_name: basename(rootPath),root_path: rootPath,default: !hasDefault,};- config.workspaces = [...workspaces, newWs];+ config.workspaces = [...workspaces, ws];saveConfig(config);- return { registered: true, name };+ return { ws, created: true };+}++export function ensureWorkspaceRegistered(cwd = process.cwd()): { registered: boolean; name: string } {+ const { ws, created } = getOrCreateWorkspace(cwd);+ return { registered: created, name: ws.workspace_name };+}++/**+ * Resolve the stable workspace id for a root, registering the workspace (and+ * persisting a fresh id) on first use. This id is folded into node identity by+ * core-ingestion, so it must be stable for a given workspace root and distinct+ * across roots — that is what keeps two workspaces with the same relative layout+ * from colliding on a shared backend.+ */+export function ensureWorkspaceId(cwd = process.cwd()): string {+ return getOrCreateWorkspace(cwd).ws.workspace_id;+}++/**+ * Resolve the workspace id for a READ, without creating one. Returns the id of the+ * nearest registered workspace containing cwd, else the default workspace, else+ * undefined — meaning an unscoped/global read, preserving back-compat for callers+ * run outside any registered workspace.+ */+export function resolveWorkspaceId(cwd = process.cwd()): string | undefined {+ return (findWorkspaceForCwd(cwd) ?? getDefaultWorkspace())?.workspace_id;}/**diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex e80511bb..a9090851 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -14,6 +14,7 @@ import { getEndpoint, resolveWorkspaceRoot } from '../config.js';import { resolveGitHubToken } from '../github/auth.js';import { parseGitHubRepo, fetchGitHubData } from '../github/fetch.js';import { loadIngestionModules } from './ingestion-loader.js';+import { ensureWorkspaceId } from '../bootstrap.js';import {deterministicId,transformIssue,@@ -403,13 +404,14 @@ export async function ingestFiles(//// The backend used to dereference provenance.source_uri against the host// filesystem (via a broad HOME bind mount). We now emit workspace-relative- // paths as the canonical source_uri, and pass a workspace_id derived from- // the workspace root's absolute path. The backend treats both as opaque- // strings; it never reads host files.+ // paths as the canonical source_uri, plus a stable workspace_id (persisted in+ // ~/.ix/config.yaml, NOT derived from the absolute path) that core-ingestion+ // folds into every node id so two workspaces with the same relative layout do+ // not collide. The backend treats both as opaque strings; it never reads host files.const workspaceRoot = fs.statSync(resolvedPath).isDirectory()? resolvedPath: nodePath.dirname(resolvedPath);- const workspaceId = crypto.createHash('sha256').update(workspaceRoot).digest('hex');+ const workspaceId = ensureWorkspaceId(workspaceRoot);const toWorkspaceRelative = (absPath: string): string => {// Force workspace-local POSIX separators so IDs are stable across OS.const rel = nodePath.relative(workspaceRoot, absPath);@@ -420,8 +422,8 @@ export async function ingestFiles(// Schema-version check forces a clean re-ingest when the backend's graph// format has changed in a way that invalidates existing node IDs (e.g. the- // absolute→relative source_uri migration).- const CLIENT_EXPECTED_SCHEMA_VERSION = 2;+ // absolute→relative source_uri migration, or folding workspace_id into ids).+ const CLIENT_EXPECTED_SCHEMA_VERSION = 3;try {const health = await client.health();const serverVersion = (health as any)?.schema_version;@@ -785,13 +787,10 @@ export async function ingestFiles(for (let j = 0; j < batch.length; j++) {const { parsed: p, hash, previousHash } = batch[j];try {- let patch = buildPatchFn!(p, hash, batchEdgesByFile.get(p.filePath) ?? emptyEdges, previousHash);+ let patch = buildPatchFn!(p, hash, workspaceId, batchEdgesByFile.get(p.filePath) ?? emptyEdges, previousHash);if (mapMode) patch = stripMapModeOps(patch);- // Tag every patch with the workspace_id. The backend stores this- // as an opaque attribute. The source.uri has already been set to- // the workspace-relative path upstream in buildPatch (because we- // passed the relative path to parseFile).- if (patch?.source) patch.source.workspaceId = workspaceId;+ // source.uri (workspace-relative) and source.workspaceId are set+ // inside buildPatch; the backend stores both as opaque attributes.preparedPatches.push(makePreparedPatch(patch, j + 1, p.filePath));} catch (err) {parseErrors++;@@ -856,10 +855,9 @@ export async function ingestFiles(for (let j = 0; j < allParsed.length; j++) {const { parsed: p, hash, previousHash } = allParsed[j];try {- let patch = buildPatchFn!(p, hash, edgesByFile.get(p.filePath) ?? emptyEdges, previousHash);+ let patch = buildPatchFn!(p, hash, workspaceId, edgesByFile.get(p.filePath) ?? emptyEdges, previousHash);if (mapMode) patch = stripMapModeOps(patch);- // Tag with workspace_id (see flushBatch).- if (patch?.source) patch.source.workspaceId = workspaceId;+ // source.uri and source.workspaceId are set inside buildPatch (see flushBatch).preparedPatches.push(makePreparedPatch(patch, j + 1, p.filePath));} catch (err) {parseErrors++;diff --git a/ix-cli/src/cli/commands/ingestion-loader.ts b/ix-cli/src/cli/commands/ingestion-loader.tsindex a02eaf58..1859173b 100644--- a/ix-cli/src/cli/commands/ingestion-loader.ts+++ b/ix-cli/src/cli/commands/ingestion-loader.ts@@ -9,8 +9,8 @@ type IngestionModule = {};type PatchBuilderModule = {- buildPatch: (parsed: any, hash: string, previousSourceHash?: string) => any;- buildPatchWithResolution: (parsed: any, hash: string, resolvedEdges: any[], previousSourceHash?: string) => any;+ buildPatch: (parsed: any, hash: string, workspaceId: string, previousSourceHash?: string) => any;+ buildPatchWithResolution: (parsed: any, hash: string, workspaceId: string, resolvedEdges: any[], previousSourceHash?: string) => any;};type LanguagesModule = {diff --git a/ix-cli/src/cli/commands/inventory.ts b/ix-cli/src/cli/commands/inventory.tsindex a9066f52..724c1c19 100644--- a/ix-cli/src/cli/commands/inventory.ts+++ b/ix-cli/src/cli/commands/inventory.ts@@ -2,6 +2,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";+import { resolveWorkspaceId } from "../bootstrap.js";import { relativePath } from "../format.js";export function registerInventoryCommand(program: Command): void {@@ -25,7 +26,7 @@ Examples:const client = new IxClient(getEndpoint());const limit = parseInt(opts.limit, 10);- let nodes = await client.listByKind(opts.kind, { limit });+ let nodes = await client.listByKind(opts.kind, { limit, workspaceId: resolveWorkspaceId() });if (opts.path) {nodes = nodes.filter((n) => {diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.tsindex c4fafaa2..5df3e50a 100644--- a/ix-cli/src/cli/commands/map.ts+++ b/ix-cli/src/cli/commands/map.ts@@ -4,7 +4,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { roundFloat } from "../format.js";-import { bootstrap } from "../bootstrap.js";+import { bootstrap, resolveWorkspaceId } from "../bootstrap.js";import { formatFetchError } from "../errors.js";import { ingestFiles } from "./ingest.js";import { getRemoteRunner, isCloudReady } from "../remote.js";@@ -206,7 +206,7 @@ Examples:let result: MapResult;try {- result = await client.map({ full: opts.full }) as MapResult;+ result = await client.map({ full: opts.full, workspaceId: resolveWorkspaceId(cwd) }) as MapResult;} catch (err: any) {if (mapInterval) { clearInterval(mapInterval); process.stderr.write('\r' + ' '.repeat(60) + '\r'); }console.error(chalk.red("Error:"), formatFetchError(err));diff --git a/ix-cli/src/cli/commands/rank.ts b/ix-cli/src/cli/commands/rank.tsindex cf37f2f7..8306eb6e 100644--- a/ix-cli/src/cli/commands/rank.ts+++ b/ix-cli/src/cli/commands/rank.ts@@ -2,6 +2,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";+import { resolveWorkspaceId } from "../bootstrap.js";type Metric = "dependents" | "callers" | "importers" | "members";@@ -153,7 +154,7 @@ export function registerRankCommand(program: Command): void {const diagnostics: string[] = [];// 1. Fetch all entities of the given kind- const allNodes = await client.listByKind(opts.kind, { limit: 2000 });+ const allNodes = await client.listByKind(opts.kind, { limit: 2000, workspaceId: resolveWorkspaceId() });if (allNodes.length === 0) {if (isJson) {diff --git a/ix-cli/src/cli/commands/search.ts b/ix-cli/src/cli/commands/search.tsindex 4760d047..518cad71 100644--- a/ix-cli/src/cli/commands/search.ts+++ b/ix-cli/src/cli/commands/search.ts@@ -2,6 +2,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getActiveWorkspaceRoot, getEndpoint } from "../config.js";+import { resolveWorkspaceId } from "../bootstrap.js";import { formatNodes, relativePath } from "../format.js";import { scoreCandidate } from "../resolve.js";import { applyRoleFilter, roleHint } from "../role-filter.js";@@ -125,6 +126,7 @@ Examples:kind: opts.kind,language: opts.language,asOfRev: opts.asOf ? parseInt(opts.asOf, 10) : undefined,+ workspaceId: resolveWorkspaceId(),});const nodes = effectivePathFilter? rawNodes.filter((node: any) => {diff --git a/ix-cli/src/cli/commands/smells.ts b/ix-cli/src/cli/commands/smells.tsindex ab732291..e168936a 100644--- a/ix-cli/src/cli/commands/smells.ts+++ b/ix-cli/src/cli/commands/smells.ts@@ -2,6 +2,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";+import { resolveWorkspaceId } from "../bootstrap.js";interface SmellCandidate {file_id: string;@@ -62,7 +63,7 @@ Examples:if (opts.list) {let result: any;try {- result = await client.listSmells();+ result = await client.listSmells({ workspaceId: resolveWorkspaceId() });} catch (err: any) {console.error(chalk.red("Error:"), err.message);process.exitCode = 1;@@ -105,6 +106,7 @@ Examples:godModuleChunks: parseInt(opts.godModuleChunks, 10),godModuleFan: parseInt(opts.godModuleFan, 10),weakMaxNeighbors: parseInt(opts.weakMaxNeighbors, 10),+ workspaceId: resolveWorkspaceId(),}) as SmellReport;} catch (err: any) {console.error(chalk.red("Error:"), err.message);diff --git a/ix-cli/src/cli/commands/stats.ts b/ix-cli/src/cli/commands/stats.tsindex 62a1e861..5b8cd9ec 100644--- a/ix-cli/src/cli/commands/stats.ts+++ b/ix-cli/src/cli/commands/stats.ts@@ -2,6 +2,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";+import { resolveWorkspaceId } from "../bootstrap.js";export function registerStatsCommand(program: Command): void {program@@ -10,7 +11,7 @@ export function registerStatsCommand(program: Command): void {.option("--format <fmt>", "Output format (text|json)", "text").action(async (opts: { format: string }) => {const client = new IxClient(getEndpoint());- const result = await client.stats();+ const result = await client.stats({ workspaceId: resolveWorkspaceId() });if (opts.format === "json") {console.log(JSON.stringify(result, null, 2));diff --git a/ix-cli/src/cli/commands/subsystems.ts b/ix-cli/src/cli/commands/subsystems.tsindex 7e835d08..f59d1ce1 100644--- a/ix-cli/src/cli/commands/subsystems.ts+++ b/ix-cli/src/cli/commands/subsystems.ts@@ -2,6 +2,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient, type ListSubsystemsOptions } from "../../client/api.js";import { getEndpoint } from "../config.js";+import { resolveWorkspaceId } from "../bootstrap.js";import { roundFloat } from "../format.js";import { renderMapText, type MapResult } from "./map.js";import {@@ -155,7 +156,7 @@ Examples:result = await loadSubsystemScores(client, detailedQuery.value ?? {});// Auto-trigger scoring if no persisted scores exist yetif (result.scores.length === 0) {- await client.scoreSubsystems();+ await client.scoreSubsystems({ workspaceId: resolveWorkspaceId() });result = await loadSubsystemScores(client, detailedQuery.value ?? {});}} catch (err: any) {@@ -200,6 +201,7 @@ Examples:result = await client.getSubsystemMap({target: target.value,pick: pick.value,+ workspaceId: resolveWorkspaceId(),}) as MapResult;} catch (err: any) {const body = parseErrorBody(err);@@ -227,9 +229,9 @@ Examples:let scoreResult: { scores?: SubsystemScore[] };try {- scoreResult = await client.listSubsystems();+ scoreResult = await client.listSubsystems({ workspaceId: resolveWorkspaceId() });if ((scoreResult.scores ?? []).length === 0) {- scoreResult = await client.scoreSubsystems();+ scoreResult = await client.scoreSubsystems({ workspaceId: resolveWorkspaceId() });}} catch (err: any) {console.error(chalk.red("Error:"), err.message);@@ -418,7 +420,7 @@ async function loadSubsystemScores(query: ListSubsystemsOptions,): Promise<SubsystemListResult> {if (!query.detailed) {- const result = await client.listSubsystems();+ const result = await client.listSubsystems({ workspaceId: resolveWorkspaceId() });return { scores: result.scores ?? [], autoPaginated: false };}diff --git a/ix-cli/src/cli/commands/watch.ts b/ix-cli/src/cli/commands/watch.tsindex 3eec6e4a..5b067551 100644--- a/ix-cli/src/cli/commands/watch.ts+++ b/ix-cli/src/cli/commands/watch.ts@@ -5,7 +5,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint, resolveWorkspaceRoot } from "../config.js";-import { bootstrap } from "../bootstrap.js";+import { bootstrap, ensureWorkspaceId } from "../bootstrap.js";import { loadWatchIngestionModules } from "./ingestion-loader.js";import { readFileContent } from "./watch-utils.js";const SUPPORTED_EXTENSIONS = new Set([@@ -46,15 +46,6 @@ function toWorkspaceRelative(root: string, absPath: string): string {return path.relative(root, absPath).split(path.sep).join("/");}-/**- * Derive the workspace id from the workspace root's absolute path. Matches the- * value `ix ingest` stamps onto every patch (sha256 of the workspace root) so- * the two ingest paths agree on source identity.- */-function workspaceIdFor(root: string): string {- return crypto.createHash("sha256").update(root).digest("hex");-}-export function registerWatchCommand(program: Command): void {program.command("watch")@@ -70,7 +61,7 @@ export function registerWatchCommand(program: Command): void {}const root = resolveWorkspaceRoot(opts.root);- const workspaceId = workspaceIdFor(root);+ const workspaceId = ensureWorkspaceId(root);const watchPath = opts.path? path.resolve(root, opts.path): root;@@ -124,8 +115,7 @@ export function registerWatchCommand(program: Command): void {console.log(`${chalk.dim("[watch]")} skipped (unsupported): ${relPath}`);return;}- const patch = buildPatch(parsed, hash);- if (patch?.source) patch.source.workspaceId = workspaceId;+ const patch = buildPatch(parsed, hash, workspaceId);const result = await client.commitPatch(patch);lastHash.set(filePath, hash);console.log(`${chalk.cyan("[watch]")} ingested: ${chalk.bold(relPath)} → rev ${result.rev}`);@@ -187,7 +177,7 @@ async function pollMode(client: IxClient): Promise<void> {const [{ parseFile }, { buildPatch }] = await loadWatchIngestionModules();- const workspaceId = workspaceIdFor(root);+ const workspaceId = ensureWorkspaceId(root);const mtimes = new Map<string, number>();function collectFiles(dir: string): string[] {@@ -244,8 +234,7 @@ async function pollMode(const parsed = parseFile(relPath, content);if (!parsed) continue;const hash = hashContent(content);- const patch = buildPatch(parsed, hash);- if (patch?.source) patch.source.workspaceId = workspaceId;+ const patch = buildPatch(parsed, hash, workspaceId);const result = await client.commitPatch(patch);console.log(`${chalk.cyan("[watch]")} ingested: ${chalk.bold(relPath)} → rev ${result.rev}`);} catch (err: any) {diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.tsindex da7baade..9343fb13 100644--- a/ix-cli/src/client/api.ts+++ b/ix-cli/src/client/api.ts@@ -53,7 +53,7 @@ export class IxClient {async search(term: string,- opts?: { limit?: number; kind?: string; language?: string; asOfRev?: number; nameOnly?: boolean }+ opts?: { limit?: number; kind?: string; language?: string; asOfRev?: number; nameOnly?: boolean; workspaceId?: string }): Promise<GraphNode[]> {return this.post("/v1/search", {term,@@ -62,16 +62,18 @@ export class IxClient {language: opts?.language,asOfRev: opts?.asOfRev,nameOnly: opts?.nameOnly,+ workspaceId: opts?.workspaceId,});}async listByKind(kind: string,- opts?: { limit?: number }+ opts?: { limit?: number; workspaceId?: string }): Promise<GraphNode[]> {return this.post("/v1/list", {kind,limit: opts?.limit,+ workspaceId: opts?.workspaceId,});}@@ -208,11 +210,14 @@ export class IxClient {return new Map(Object.entries(result));}- async map(opts?: { full?: boolean }): Promise<any> {+ async map(opts?: { full?: boolean; workspaceId?: string }): Promise<any> {+ // /v1/map reads snake_case keys (full, branch_id, workspace_id) off the raw JSON body.+ const body: Record<string, unknown> = { full: opts?.full ?? false };+ if (opts?.workspaceId) body.workspace_id = opts.workspaceId;const resp = await fetch(`${this.endpoint}/v1/map`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify(opts ?? {}),+ body: JSON.stringify(body),signal: AbortSignal.timeout(30 * 60 * 1000), // 30 minute timeout});if (!resp.ok) {@@ -241,25 +246,29 @@ export class IxClient {godModuleChunks?: number;godModuleFan?: number;weakMaxNeighbors?: number;+ workspaceId?: string;}): Promise<any> {const params = new URLSearchParams();if (opts?.orphanMaxConnections !== undefined) params.set("orphan-max-connections", String(opts.orphanMaxConnections));if (opts?.godModuleChunks !== undefined) params.set("god-module-chunks", String(opts.godModuleChunks));if (opts?.godModuleFan !== undefined) params.set("god-module-fan", String(opts.godModuleFan));if (opts?.weakMaxNeighbors !== undefined) params.set("weak-max-neighbors", String(opts.weakMaxNeighbors));+ if (opts?.workspaceId) params.set("workspace_id", opts.workspaceId);const qs = params.toString();return this.post(qs ? `/v1/smells?${qs}` : "/v1/smells", {});}- async listSmells(): Promise<any> {- return this.get("/v1/smells");+ async listSmells(opts?: { workspaceId?: string }): Promise<any> {+ const qs = opts?.workspaceId ? `?workspace_id=${encodeURIComponent(opts.workspaceId)}` : "";+ return this.get(`/v1/smells${qs}`);}- async scoreSubsystems(): Promise<any> {- return this.post("/v1/subsystems/score", {});+ async scoreSubsystems(opts?: { workspaceId?: string }): Promise<any> {+ const qs = opts?.workspaceId ? `?workspace_id=${encodeURIComponent(opts.workspaceId)}` : "";+ return this.post(`/v1/subsystems/score${qs}`, {});}- async listSubsystems(opts?: ListSubsystemsOptions): Promise<any> {+ async listSubsystems(opts?: ListSubsystemsOptions & { workspaceId?: string }): Promise<any> {const params = new URLSearchParams();if (opts?.detailed) params.set("detailed", "true");if (opts?.limit !== undefined) params.set("limit", String(opts.limit));@@ -267,14 +276,16 @@ export class IxClient {if (opts?.regions) params.set("regions", opts.regions);if (opts?.edgeCap !== undefined) params.set("edge_cap", String(opts.edgeCap));if (opts?.memberFileCap !== undefined) params.set("member_file_cap", String(opts.memberFileCap));+ if (opts?.workspaceId) params.set("workspace_id", opts.workspaceId);const qs = params.toString();return this.get(`/v1/subsystems${qs ? `?${qs}` : ""}`);}- async getSubsystemMap(opts?: { target?: string; pick?: number }): Promise<any> {+ async getSubsystemMap(opts?: { target?: string; pick?: number; workspaceId?: string }): Promise<any> {const params = new URLSearchParams();if (opts?.target) params.set("target", opts.target);if (opts?.pick !== undefined) params.set("pick", String(opts.pick));+ if (opts?.workspaceId) params.set("workspace_id", opts.workspaceId);const qs = params.toString();return this.get(`/v1/subsystems/map${qs ? `?${qs}` : ""}`);}@@ -402,8 +413,9 @@ export class IxClient {return resp.json();}- async stats(): Promise<any> {- return this.get("/v1/stats");+ async stats(opts?: { workspaceId?: string }): Promise<any> {+ const qs = opts?.workspaceId ? `?workspace_id=${encodeURIComponent(opts.workspaceId)}` : "";+ return this.get(`/v1/stats${qs}`);}async health(): Promise<HealthResponse> {