Skip to content

armgit / Ix

Public Imported from GitHub
0

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

40.0 KB
Raw Blame
// Copyright 2026 Ix Infrastructure Inc.

import { isPreConnectionFailure, RESET_RECONCILIATION_ERROR } from "./transport.js";
import { Limiter, RequestMemo } from "./request-memo.js";
import { CORRELATION_ID_HEADER, debugRequest, nextCorrelationId } from "./correlation.js";
import type {
  IngestResult,
  StructuredContext,
  GraphNode,
  HealthResponse,
  PatchSummary,
  GraphPatchPayload,
  PatchCommitResult,
  CapabilitiesResponse,
} from "./types.js";

export interface ListSubsystemsOptions {
  detailed?: boolean;
  limit?: number;
  offset?: number;
  regions?: string;
  edgeCap?: number;
  memberFileCap?: number;
}

/**
 * How a client created for ONE query command talks to the backend. Off by
 * default: every existing caller sends exactly the requests it did.
 */
export interface IxClientOptions {
  /**
   * Answer a repeated read (same method, path and body) from the first
   * response instead of asking again. See `request-memo.ts` for why this is
   * per-command only and never for a long-lived client.
   */
  shareReads?: boolean;
  /** At most this many requests in flight at once. */
  maxInFlight?: number;
  /** Sent as `Authorization: Bearer <token>` on every request (see `getLocalToken`). */
  token?: string;
  /**
   * Reads (GETs, and the POSTs in `SHARED_READ_PREFIXES`) fail once this many
   * ms have passed since the client was created or since its last write
   * through `post` finished: a whole-command bound on a hung backend, which the
   * 2-minute per-request timeout is not. Writes are never cut off by it, and
   * the time a write takes is not charged to the reads after it (`ix
   * subsystems --list` scores, which can take minutes, then reads the scores).
   * 0 or absent: no such bound.
   */
  readDeadlineMs?: number;
  /**
   * Retry a read once, after a short random wait, when the connection was
   * refused or reset before it carried anything, or the answer was 502/503/504.
   * Writes are never retried.
   */
  retryReads?: boolean;
}

/** Statuses a proxy or a restarting backend answers with, for which one retry is worth it. */
const RETRYABLE_READ_STATUS = /^(502|503|504):/;

/**
 * A connection dropped mid-request. Not safe to repeat for a write, which may
 * have been applied; a read can simply be asked again.
 */
const DROPPED_CONNECTION_CODES = new Set(["ECONNRESET", "EPIPE", "UND_ERR_SOCKET"]);

function hasCode(err: unknown, codes: ReadonlySet<string>): boolean {
  for (let e: unknown = err, hops = 0; e && hops < 5; hops++) {
    const code = (e as { code?: unknown }).code;
    if (typeof code === "string" && codes.has(code)) return true;
    e = (e as { cause?: unknown }).cause;
  }
  return false;
}

/**
 * The reads `shareReads` may answer from an earlier response: lookups whose
 * answer cannot change because of anything the same command does.
 */
const SHARED_READ_PREFIXES = [
  "/v1/expand", "/v1/search", "/v1/context", "/v1/list",
  "/v1/entity/", "/v1/provenance/", "/v1/resolve-prefix/",
];

function isSharedRead(path: string): boolean {
  return SHARED_READ_PREFIXES.some((prefix) => path.startsWith(prefix));
}

export class IxClient {
  private readonly memo?: RequestMemo<SuccessBody>;
  private readonly limiter?: Limiter;
  private readonly token?: string;
  private readonly readDeadlineMs?: number;
  /** When reads stop being sent (epoch ms); moved on by each write. */
  private readDeadlineAt?: number;
  private readonly retryReads: boolean;

  // An optional deadline signal shared across every request this client makes.
  // `ix map` sets it to a hard wall-clock budget so that, even when the backend
  // is unhealthy and individual requests would otherwise sit on their long
  // per-request timeouts (5-30 min each), the whole operation aborts and the
  // process exits instead of grinding for hours and stacking with re-launches.
  constructor(
    // readonly so callers can ask which endpoint a response came FROM, rather
    // than being handed a second string that is only equal by inspection.
    public readonly endpoint: string = "http://localhost:8090",
    private deadlineSignal?: AbortSignal,
    options: IxClientOptions = {},
  ) {
    if (options.shareReads) this.memo = new RequestMemo();
    if (options.maxInFlight !== undefined) this.limiter = new Limiter(options.maxInFlight);
    if (options.token) this.token = options.token;
    if (options.readDeadlineMs && options.readDeadlineMs > 0) {
      this.readDeadlineMs = options.readDeadlineMs;
      this.readDeadlineAt = Date.now() + options.readDeadlineMs;
    }
    this.retryReads = options.retryReads === true;
  }

  /**
   * The headers of every request: the JSON content type when there is a body,
   * the bearer token when the client has one, and a fresh X-Correlation-Id
   * (see correlation.ts). The one place any of them is set, so no request can
   * go out without the token. Under IX_DEBUG the request and its id are
   * written to stderr, to match against the backend's logs.
   */
  private headers(json: boolean, method: string, path: string): Record<string, string> {
    const headers: Record<string, string> = {};
    if (json) headers["Content-Type"] = "application/json";
    if (this.token) headers.Authorization = `Bearer ${this.token}`;
    const id = nextCorrelationId();
    headers[CORRELATION_ID_HEADER] = id;
    debugRequest(method, path, id);
    return headers;
  }

  /** Reads answered from `shareReads` instead of the backend, for diagnostics and tests. */
  get sharedReadHits(): number {
    return this.memo?.hits ?? 0;
  }

  // Combine a per-request timeout with the optional shared deadline, and for a
  // read with the client's read deadline. Whichever fires first aborts the
  // fetch. AbortSignal.any propagates the first abort.
  private signalFor(perRequestMs: number, read = false): AbortSignal {
    const signals = [AbortSignal.timeout(perRequestMs)];
    if (this.deadlineSignal) signals.push(this.deadlineSignal);
    // AbortSignal.timeout is unref'd by Node, so it never holds a finished
    // process open.
    if (read && this.readDeadlineAt !== undefined) {
      signals.push(AbortSignal.timeout(Math.max(0, this.readDeadlineAt - Date.now())));
    }
    return signals.length === 1 ? signals[0]! : AbortSignal.any(signals);
  }

  async query(
    question: string,
    opts?: { asOfRev?: number; depth?: string }
  ): Promise<StructuredContext> {
    return this.post("/v1/context", { query: question, ...opts });
  }

  /**
   * Context centred on a node we have already resolved.
   *
   * `query()` sends a NAME and makes the backend re-derive seeds by string
   * search. That is the single most expensive call the CLI makes — measured at
   * 10.6 s against 0.06 s for this form on the same graph — and it is not just
   * slow, it can centre the bundle on a different node: `README.md` resolved to
   * one id and came back seeded on `mcp/node_modules/serve-static/README.md`,
   * with the resolved id in neither the seeds nor the returned nodes.
   *
   * The id is already in hand by the time this is called, so send it. `depth` is
   * passed through rather than pinned to `full`, so `--depth` still means what it
   * says: compact and standard return the summarized graph (which `buildBundle`
   * reads), full returns whole nodes plus claims.
   */
  async contextForNode(
    nodeId: string,
    opts?: { asOfRev?: number; depth?: string; hops?: number }
  ): Promise<StructuredContext> {
    const { hops = 1, ...rest } = opts ?? {};
    return this.post("/v1/context", {
      slices: [{ type: "nodes", nodeIds: [nodeId], expand: true, hops }],
      ...rest,
    });
  }

  async ingest(path: string, recursive?: boolean, force?: boolean): Promise<IngestResult> {
    const resp = await fetch(`${this.endpoint}/v1/ingest`, {
      method: "POST",
      headers: this.headers(true, "POST", "/v1/ingest"),
      body: JSON.stringify({ path, recursive, force: force || undefined }),
      signal: this.signalFor(30 * 60 * 1000), // 30 minute timeout for large repos
    });
    if (!resp.ok) {
      const text = await resp.text();
      throw httpError(resp.status, text);
    }
    return resp.json() as Promise<IngestResult>;
  }

  async decide(
    title: string,
    rationale: string,
    opts?: { intentId?: string }
  ): Promise<{ status: string; nodeId: string; rev: number }> {
    return this.post("/v1/decide", { title, rationale, ...opts });
  }

  async search(
    term: string,
    opts?: { limit?: number; kind?: string; language?: string; asOfRev?: number; nameOnly?: boolean; workspaceId?: string; systemId?: string; scope?: string }
  ): Promise<GraphNode[]> {
    return this.post("/v1/search", {
      term,
      limit: opts?.limit,
      kind: opts?.kind,
      language: opts?.language,
      asOfRev: opts?.asOfRev,
      nameOnly: opts?.nameOnly,
      workspaceId: opts?.workspaceId,
      systemId: opts?.systemId,
      // A source_uri substring the backend applies BEFORE its limit
      // (Ix-memory ≥ 1.0.31, case-insensitive). Older backends decode the
      // request with a derived circe decoder and drop the unknown field, so
      // sending it is always safe; callers keep their own filter as well.
      scope: opts?.scope,
    });
  }

  // Vector-similarity search. The backend (POST /v1/search/semantic) embeds the
  // term and returns nodes already ordered by similarity, so callers must NOT
  // re-rank. Requires the extraction service to be configured (cloud); otherwise
  // the backend returns 503. The request field is `term` (not `query`), and this
  // endpoint does not accept a `language` filter — only term/limit/kind/scoping.
  async semanticSearch(
    term: string,
    opts?: { limit?: number; kind?: string; workspaceId?: string; systemId?: string }
  ): Promise<GraphNode[]> {
    return this.post("/v1/search/semantic", {
      term,
      limit: opts?.limit,
      kind: opts?.kind,
      workspaceId: opts?.workspaceId,
      systemId: opts?.systemId,
    });
  }

  async listByKind(
    kind: string,
    opts?: { limit?: number; workspaceId?: string; scope?: string; systemId?: string }
  ): Promise<GraphNode[]> {
    return this.post("/v1/list", {
      kind,
      limit: opts?.limit,
      workspaceId: opts?.workspaceId,
      scope: opts?.scope,
      systemId: opts?.systemId,
    });
  }

  async listDecisions(opts?: { limit?: number; topic?: string }): Promise<GraphNode[]> {
    return this.post("/v1/decisions", { limit: opts?.limit, topic: opts?.topic });
  }

  async resolvePrefix(prefix: string): Promise<string> {
    const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    if (uuidPattern.test(prefix)) return prefix;

    const result = await this.get<{ id?: string; error?: string; matches?: string[] }>(
      `/v1/resolve-prefix/${encodeURIComponent(prefix)}`
    );
    if (result.id) return result.id;
    if (result.error === "ambiguous") {
      throw new Error(`Ambiguous prefix "${prefix}" — matches: ${result.matches?.join(", ")}`);
    }
    throw new Error(`No entity found for prefix: ${prefix}`);
  }

  async entity(id: string): Promise<{
    node: GraphNode;
    claims: unknown[];
    edges: unknown[];
  }> {
    return this.get(`/v1/entity/${encodeURIComponent(id)}`);
  }

  async expandByName(
    name: string,
    opts?: { direction?: string; predicates?: string[]; kinds?: string[]; timeoutMs?: number }
  ): Promise<{ nodes: any[]; edges: any[] }> {
    return this.post("/v1/expand-by-name", {
      name,
      direction: opts?.direction ?? "both",
      predicates: opts?.predicates,
      kinds: opts?.kinds,
    }, opts?.timeoutMs);
  }

  async expand(
    id: string,
    opts?: { direction?: string; predicates?: string[]; hops?: number; limit?: number }
  ): Promise<{ nodes: any[]; edges: any[] }> {
    return this.post("/v1/expand", {
      nodeId: id,
      direction: opts?.direction ?? "both",
      predicates: opts?.predicates,
      hops: opts?.hops ?? 1,
      // Only when asked for, so every existing caller sends the body it did.
      ...(opts?.limit !== undefined ? { limit: opts.limit } : {}),
    });
  }

  async listGoals(): Promise<GraphNode[]> {
    return this.get("/v1/truth");
  }

  async createGoal(
    statement: string,
    parentGoal?: string
  ): Promise<{ status: string; nodeId: string; rev: number }> {
    return this.post("/v1/truth", { statement, parentIntent: parentGoal });
  }

  async listTruth(): Promise<GraphNode[]> {
    return this.get("/v1/truth");
  }

  async createTruth(
    statement: string,
    parentIntent?: string
  ): Promise<{ status: string; nodeId: string; rev: number }> {
    return this.post("/v1/truth", { statement, parentIntent });
  }

  async listPatches(opts?: { limit?: number }): Promise<PatchSummary[]> {
    const params = new URLSearchParams();
    if (opts?.limit) params.set("limit", String(opts.limit));
    const qs = params.toString();
    return this.get(`/v1/patches${qs ? `?${qs}` : ""}`);
  }

  async getPatch(id: string): Promise<unknown> {
    return this.get(`/v1/patches/${encodeURIComponent(id)}`);
  }

  /**
   * Many nodes in one read, at the latest revision (Ix-memory 1.0.33+). Only
   * live nodes come back; `missing` names the other ids. At most 1000 ids per
   * call (the backend answers 413 above that). `fields: "full"` returns whole
   * nodes, attrs and provenance included.
   */
  async nodes(
    ids: string[],
    fields?: "full",
  ): Promise<{ rev: number; nodes: GraphNode[]; missing: string[] }> {
    return this.post("/v1/nodes", fields ? { ids, fields } : { ids });
  }

  /**
   * The backend's head revision: every committed patch, in any workspace,
   * advances it. One indexed lookup on the backend, so it is cheap enough to
   * ask on every `ix map`.
   *
   * The body is the head's revision record when the backend has one, and the
   * bare revision number when it does not; both are returned as-is.
   */
  async currentRevision(timeoutMs?: number): Promise<unknown> {
    return this.get("/v1/revisions/current", timeoutMs);
  }

  async diff(
    fromRev: number,
    toRev: number,
    opts?: { entityId?: string; summary?: boolean; limit?: number; workspaceId?: string }
  ): Promise<unknown> {
    return this.post("/v1/diff", {
      fromRev,
      toRev,
      entityId: opts?.entityId,
      summary: opts?.summary,
      limit: opts?.limit,
      // The backend reads `workspace_id` like its other reads: an id scopes
      // the diff to that workspace, `*` (or none) means every workspace.
      workspace_id: opts?.workspaceId,
    });
  }

  async conflicts(): Promise<unknown[]> {
    return this.get("/v1/conflicts");
  }

  async provenance(entityId: string): Promise<unknown> {
    return this.post(`/v1/provenance/${encodeURIComponent(entityId)}`, {});
  }

  async commitPatch(patch: GraphPatchPayload): Promise<PatchCommitResult> {
    const resp = await fetch(`${this.endpoint}/v1/patch`, {
      method: 'POST',
      headers: this.headers(true, "POST", "/v1/patch"),
      body: JSON.stringify(patch),
      signal: this.signalFor(5 * 60 * 1000), // 5 min — matches commitPatchBulk
    });
    if (!resp.ok) {
      const text = await resp.text();
      throw httpError(resp.status, text, resp.headers);
    }
    return resp.json() as Promise<PatchCommitResult>;
  }

  async hasIngestBaseline(): Promise<boolean> {
    const result = await this.get<{ exists: boolean }>('/v1/source-hashes/exists');
    return result.exists;
  }

  async commitPatchBatch(patches: GraphPatchPayload[]): Promise<PatchCommitResult[]> {
    return this.post("/v1/patches/batch", patches);
  }

  // Workspace-scoped baseline lookup (Ix#225). Returns one row per (workspace_id, uri)
  // so the caller can match each file against its OWN workspace's hash, instead of a
  // bare uri->hash map that collides across workspaces sharing a relative path. Passing
  // workspaceIds bounds the query server-side. workspaceId is null for legacy patches.
  async getSourceHashes(
    filePaths: string[],
    workspaceIds?: string[],
  ): Promise<Array<{ workspaceId: string | null; uri: string; hash: string }>> {
    return this.post('/v1/source-hashes', { uris: filePaths, workspaceIds });
  }

  // Path-2 separate-ingest stitcher (Ix#225). Registers this workspace's published
  // packages (provides) + production-dep external imports (consumes), then the
  // backend joins them bidirectionally against other workspaces and writes the
  // cross-repo IMPORTS edges. Returns how many edges were stitched.
  async stitch(payload: {
    workspaceId: string;
    provides: Array<{ name: string; entryNodeId: string; entryUri?: string }>;
    consumes: Array<{ name: string; consumerNodeId: string }>;
    exports?: Array<{ name: string; nodeId: string }>;
    symbolConsumes?: Array<{ symbol: string; callerNodeId: string; pkg?: string }>;
  }): Promise<{ stitched: number; systemId?: string | null; edges: Array<{ src: string; dst: string; name: string }> }> {
    return this.post('/v1/stitch', payload);
  }

  // Path-2 grouping (Ix#225 Half B): the system_id a workspace currently belongs
  // to (null if a singleton). Lets `ix map <repo>` scope to its stitched system.
  //
  // Only a 404 (an older backend without the endpoint) means "no system". Any
  // other failure -- backend down, timeout, 5xx, a non-JSON body -- is not an
  // answer and is thrown: `ensureReadScope` persists what this returns with no
  // TTL, so turning an outage into `null` pinned every later read in a stitched
  // workspace to the single repo until the next map.
  async workspaceSystem(workspaceId: string): Promise<{ systemId: string | null }> {
    try { return await this.get(`/v1/stitch/system/${encodeURIComponent(workspaceId)}`); }
    catch (err) {
      if (err instanceof Error && err.message.startsWith("404:")) return { systemId: null };
      throw err;
    }
  }

  async map(opts?: { full?: boolean; workspaceId?: string; systemId?: string }): Promise<any> {
    // /v1/map reads snake_case keys (full, branch_id, workspace_id, system_id) off the raw JSON body.
    const body: Record<string, unknown> = { full: opts?.full ?? false };
    if (opts?.workspaceId) body.workspace_id = opts.workspaceId;
    if (opts?.systemId) body.system_id = opts.systemId;
    const resp = await fetch(`${this.endpoint}/v1/map`, {
      method: "POST",
      headers: this.headers(true, "POST", "/v1/map"),
      body: JSON.stringify(body),
      signal: this.signalFor(30 * 60 * 1000), // 30 minute timeout
    });
    if (!resp.ok) {
      const text = await resp.text();
      throw httpError(resp.status, text);
    }
    return resp.json();
  }

  async commitPatchBulk(patches: GraphPatchPayload[]): Promise<PatchCommitResult> {
    const resp = await fetch(`${this.endpoint}/v1/patches/bulk`, {
      method: 'POST',
      headers: this.headers(true, "POST", "/v1/patches/bulk"),
      body: JSON.stringify({ patches }),
      signal: this.signalFor(5 * 60 * 1000), // 5 min — prevents hang when k8s ingress closes idle connections
    });
    if (!resp.ok) {
      const text = await resp.text();
      throw httpError(resp.status, text, resp.headers);
    }
    return resp.json() as Promise<PatchCommitResult>;
  }

  async runSmells(opts?: {
    orphanMaxConnections?: number;
    godModuleChunks?: number;
    godModuleFan?: number;
    weakMaxNeighbors?: number;
    workspaceId?: string;
    systemId?: 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);
    if (opts?.systemId)                           params.set("system_id",               opts.systemId);
    const qs = params.toString();
    return this.post(qs ? `/v1/smells?${qs}` : "/v1/smells", {});
  }

  async listSmells(opts?: { workspaceId?: string; systemId?: string }): Promise<any> {
    const params = new URLSearchParams();
    if (opts?.workspaceId) params.set("workspace_id", opts.workspaceId);
    if (opts?.systemId)    params.set("system_id",    opts.systemId);
    const qs = params.toString();
    return this.get(`/v1/smells${qs ? `?${qs}` : ""}`);
  }

  async scoreSubsystems(opts?: { workspaceId?: string; systemId?: string }): Promise<any> {
    const params = new URLSearchParams();
    if (opts?.workspaceId) params.set("workspace_id", opts.workspaceId);
    if (opts?.systemId)    params.set("system_id",    opts.systemId);
    const qs = params.toString();
    return this.post(`/v1/subsystems/score${qs ? `?${qs}` : ""}`, {});
  }

  async listSubsystems(opts?: ListSubsystemsOptions & { workspaceId?: string; systemId?: string }): Promise<any> {
    const params = new URLSearchParams();
    if (opts?.detailed) params.set("detailed", "true");
    if (opts?.limit !== undefined) params.set("limit", String(opts.limit));
    if (opts?.offset !== undefined) params.set("offset", String(opts.offset));
    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);
    if (opts?.systemId) params.set("system_id", opts.systemId);
    const qs = params.toString();
    return this.get(`/v1/subsystems${qs ? `?${qs}` : ""}`);
  }

  async getSubsystemMap(opts?: { target?: string; pick?: number; workspaceId?: string; systemId?: 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);
    if (opts?.systemId) params.set("system_id", opts.systemId);
    const qs = params.toString();
    return this.get(`/v1/subsystems/map${qs ? `?${qs}` : ""}`);
  }

  async reset(): Promise<{ ok: boolean; message: string }> {
    return this.runReset(
      "/v1/reset/async",
      "/v1/reset",
      "Graph reset. All nodes and edges deleted.",
    );
  }

  async resetCode(): Promise<{ ok: boolean; message: string }> {
    return this.runReset(
      "/v1/reset/code/async",
      "/v1/reset/code",
      "Code graph reset. Planning artifacts (goals, plans, tasks, bugs, decisions) preserved.",
    );
  }

  // Delete all nodes/edges/patches under a single workspace_id (Ix#225 gap 2: clean up
  // the orphans left when a workspace's id is migrated to the path-based id). Scoped to
  // exactly that id server-side; other workspaces are untouched.
  async deleteWorkspace(workspaceId: string): Promise<void> {
    await this.post("/v1/reset/workspace", { workspaceId });
  }

  // True when the configured endpoint is a local memory-layer. A local
  // backend has no proxy in front of it, so the sync reset path connects
  // directly and returns in milliseconds — there is nothing to fix there.
  private isLocalEndpoint(): boolean {
    try {
      const host = new URL(this.endpoint).hostname.toLowerCase();
      return host === "localhost" || host === "127.0.0.1" || host === "0.0.0.0" || host === "::1";
    } catch {
      return false;
    }
  }

  // Reset can take minutes on a large graph. Against a cloud deployment a
  // single sync request outlives the GCLB stream timeout → spurious 502
  // even though the truncate succeeded. So for a remote endpoint we drive
  // the async endpoint — begin returns immediately, then poll for status.
  //
  // For a local endpoint there is no proxy and the truncate is near-instant,
  // so we keep the original sync request unchanged — identical behavior for
  // OSS and Pro users running against a local memory-layer.
  //
  // If a remote backend predates the async endpoints (404 on begin), fall
  // back to the sync request so old deployments still work.
  private async runReset(
    asyncPath: string,
    syncPath: string,
    doneMessage: string,
  ): Promise<{ ok: boolean; message: string }> {
    if (this.isLocalEndpoint()) {
      return this.runResetSync(syncPath);
    }

    let beginResp: Response;
    try {
      beginResp = await fetch(`${this.endpoint}${asyncPath}`, {
        method: "POST",
        // A redirect can replay a destructive POST or hide an accepted reset
        // behind a later connection failure/404. Inspect the first response.
        redirect: "manual",
        headers: this.headers(true, "POST", asyncPath),
        body: JSON.stringify({}),
        signal: AbortSignal.timeout(30 * 1000),
      });
    } catch (error) {
      // A refused connection or unresolved host proves the request never left
      // this machine, so nothing was deleted and nothing needs reconciling.
      // Rethrowing lets renderCliError give its actionable "backend not
      // reachable" message instead of a data-integrity warning — which would
      // otherwise fire on the most common failure of a fresh install.
      if (isPreConnectionFailure(error)) throw error;
      throw this.resetReconciliationError("The start response was unavailable.", undefined, error);
    }

    if (beginResp.status >= 300 && beginResp.status < 400) {
      await beginResp.body?.cancel().catch(() => {});
      throw this.resetRedirectError("start route", beginResp);
    }
    if (beginResp.status === 404) {
      return this.runResetSync(syncPath);
    }
    if (!beginResp.ok) {
      const text = await beginResp.text();
      throw httpError(beginResp.status, text);
    }

    if (beginResp.status !== 202) {
      throw this.resetReconciliationError(`Unexpected start response (${beginResp.status}).`);
    }
    let begin: unknown;
    try { begin = await beginResp.json(); }
    catch { throw this.resetReconciliationError("The start acknowledgment was unreadable."); }
    if (!begin || typeof begin !== "object" || !("opId" in begin) ||
        typeof begin.opId !== "string" ||
        !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(begin.opId)) {
      throw this.resetReconciliationError("The start acknowledgment had no valid operation ID.");
    }
    const opId = begin.opId;
    const deadlineMs = Date.now() + 15 * 60 * 1000;

    while (Date.now() < deadlineMs) {
      let statusResp: Response;
      try {
        statusResp = await fetch(`${this.endpoint}/v1/reset/status/${opId}`, {
          method: "GET",
          redirect: "manual",
          headers: this.headers(false, "GET", `/v1/reset/status/${opId}`),
          signal: AbortSignal.timeout(30 * 1000),
        });
      } catch (error) {
        // NOT treated as pre-connection like the start call above: the reset
        // was already accepted (202) and is running server-side, so losing the
        // status poll is ambiguous no matter why it failed.
        throw this.resetReconciliationError("The status response was unavailable.", opId, error);
      }
      // Missing process-local status does not prove the reset did not run.
      // A new reset could delete writes created after the original operation.
      if (statusResp.status === 404) {
        throw this.resetReconciliationError("The status is unavailable or inaccessible.", opId);
      }
      if (statusResp.status !== 200) {
        await statusResp.body?.cancel().catch(() => {});
        throw this.resetReconciliationError(`Status request returned ${statusResp.status}.`, opId);
      }
      let status: unknown;
      try { status = await statusResp.json(); }
      catch { throw this.resetReconciliationError("The status response was unreadable.", opId); }
      if (!status || typeof status !== "object" || !("opId" in status) || status.opId !== opId ||
          !("state" in status) || typeof status.state !== "string" ||
          !["running", "done", "failed"].includes(status.state)) {
        throw this.resetReconciliationError("The status did not identify this operation and a valid state.", opId);
      }
      if (status.state === "done") {
        return { ok: true, message: doneMessage };
      }
      if (status.state === "failed") {
        const detail = "error" in status && typeof status.error === "string" ? status.error : "unknown error";
        throw this.resetReconciliationError(`Reset reported failure: ${detail}.`, opId);
      }
      await new Promise((resolve) => setTimeout(resolve, 2000));
    }
    throw this.resetReconciliationError("Completion was not confirmed within 15 minutes.", opId);
  }

  private resetReconciliationError(reason: string, opId?: string, cause?: unknown, hint?: string): Error {
    const operation = opId ? ` (operation ${opId})` : "";
    // Carry `cause` so IX_DEBUG=1 can still show the underlying transport
    // failure — swallowing it left no way to tell these outcomes apart.
    const error = new Error(
      `${reason}${operation} Graph or pipeline changes may already have occurred. ` +
      "Do not repeat the reset until an administrator has reconciled its effects and operation records." +
      (hint ? ` ${hint}` : ""),
      cause === undefined ? undefined : { cause });
    // Marked so error rendering does not reclassify this by its cause and
    // print "start the backend, then retry" over a do-not-repeat warning.
    error.name = RESET_RECONCILIATION_ERROR;
    return error;
  }

  // The backend never redirects, so a 3xx almost always comes from a proxy in
  // front of it (typically http:// upgraded to https://), and every other
  // command follows it silently. Say so, or the endpoint looks healthy
  // everywhere except reset. Only origins are shown: a Location path or query
  // (and endpoint userinfo) may carry credentials.
  private resetRedirectError(route: string, resp: Response): Error {
    let target = "";
    try {
      const location = resp.headers.get("location");
      const origin = location ? new URL(location, resp.url || this.endpoint).origin : "null";
      if (origin !== "null") target = ` to ${origin}`;
    } catch { /* unparseable Location: omit the target */ }
    let endpoint = this.endpoint;
    try { endpoint = new URL(this.endpoint).origin; } catch { /* keep as configured */ }
    return this.resetReconciliationError(
      `The ${route} redirected (${resp.status}${target}).`, undefined, undefined,
      `The Ix backend does not send redirects, so a proxy at ${endpoint} most likely did. ` +
      "Set IX_ENDPOINT (or `endpoint` in ~/.ix/config.yaml) to the backend's direct URL.");
  }

  private async runResetSync(syncPath: string): Promise<{ ok: boolean; message: string }> {
    const resp = await fetch(`${this.endpoint}${syncPath}`, {
      method: "POST",
      redirect: "manual",
      headers: this.headers(true, "POST", syncPath),
      body: JSON.stringify({}),
      signal: AbortSignal.timeout(10 * 60 * 1000),
    });
    if (resp.status >= 300 && resp.status < 400) {
      await resp.body?.cancel().catch(() => {});
      throw this.resetRedirectError("synchronous reset route", resp);
    }
    if (!resp.ok) {
      const text = await resp.text();
      throw httpError(resp.status, text);
    }
    return resp.json() as Promise<{ ok: boolean; message: string }>;
  }

  async savings(detail?: boolean): Promise<any> {
    const qs = detail ? "?detail=true" : "";
    return this.get(`/v1/savings${qs}`);
  }

  async savingsReset(): Promise<any> {
    const resp = await fetch(`${this.endpoint}/v1/savings`, {
      method: "DELETE",
      headers: this.headers(false, "DELETE", "/v1/savings"),
    });
    if (!resp.ok) {
      const text = await resp.text();
      throw httpError(resp.status, text);
    }
    return resp.json();
  }

  async stats(opts?: { workspaceId?: string; systemId?: string; timeoutMs?: number }): Promise<any> {
    const params = new URLSearchParams();
    if (opts?.workspaceId) params.set("workspace_id", opts.workspaceId);
    if (opts?.systemId)    params.set("system_id",    opts.systemId);
    const qs = params.toString();
    // `timeoutMs` bounds a probe (the graph-health check) that must never hold
    // up the answer it rides along with; the request is aborted, not abandoned,
    // so a slow backend does not keep a finished CLI process alive either.
    return this.get(`/v1/stats${qs ? `?${qs}` : ""}`, opts?.timeoutMs);
  }

  /** `timeoutMs` bounds a probe that must answer in seconds; the default is unchanged. */
  async health(timeoutMs?: number): Promise<HealthResponse> {
    return this.get("/v1/health", timeoutMs);
  }

  async capabilities(): Promise<CapabilitiesResponse> {
    try {
      return await this.fetchCapabilities();
    } catch (err) {
      // A refused token is not "an older backend": say so rather than guess.
      if (err instanceof LocalTokenRequiredError) throw err;
      // Backend doesn't support capabilities yet — fall back to local mode.
      return {};
    }
  }

  /** `/v1/capabilities`, with every failure thrown (for `ix doctor`). */
  async fetchCapabilities(): Promise<CapabilitiesResponse> {
    return this.get<CapabilitiesResponse>("/v1/capabilities");
  }

  /** Whether this client sends a bearer token. */
  get sendsToken(): boolean {
    return this.token !== undefined;
  }

  private async post<T>(path: string, body: unknown, timeoutMs = 2 * 60 * 1000): Promise<T> {
    const payload = JSON.stringify(body);
    return this.read<T>("POST", path, payload, () =>
      fetch(`${this.endpoint}${path}`, {
        method: "POST",
        headers: this.headers(true, "POST", path),
        body: payload,
        // These small reads/writes (source-hashes, stitch, list, ...) had no
        // timeout, so a stalled connection could hang the process indefinitely.
        // 2 min per request unless the caller bounds it, also bounded by the
        // shared deadline when set, and by the read deadline when this POST is
        // a read.
        signal: this.signalFor(timeoutMs, isSharedRead(path)),
      }));
  }

  private async get<T>(path: string, timeoutMs = 2 * 60 * 1000): Promise<T> {
    return this.read<T>("GET", path, "", () =>
      fetch(`${this.endpoint}${path}`, {
        headers: this.headers(false, "GET", path),
        signal: this.signalFor(timeoutMs, true),
      }));
  }

  /**
   * Whether a failed read is worth one more try: the request never reached a
   * backend (refused, unresolvable), the connection dropped under it, or a
   * proxy or a restarting backend answered 502/503/504. Never once a deadline
   * has fired.
   */
  private shouldRetry(err: unknown): boolean {
    if (!this.retryReads) return false;
    if (this.deadlineSignal?.aborted) return false;
    if (this.readDeadlineAt !== undefined && Date.now() >= this.readDeadlineAt) return false;
    if (isPreConnectionFailure(err) || hasCode(err, DROPPED_CONNECTION_CODES)) return true;
    return err instanceof Error && RETRYABLE_READ_STATUS.test(err.message);
  }

  /**
   * One request whose body is JSON: sent under the in-flight limit when there
   * is one, shared with an identical earlier request when `shareReads` is on
   * and the path is a read, and parsed per caller either way.
   */
  private async read<T>(method: string, path: string, payload: string, send: () => Promise<Response>): Promise<T> {
    const isRead = method === "GET" || isSharedRead(path);
    const fetchBody = async (): Promise<SuccessBody> => {
      const once = async (): Promise<SuccessBody> => {
        const resp = await send();
        const text = await resp.text();
        if (!resp.ok) throw httpError(resp.status, text);
        return { status: resp.status, text };
      };
      const run = async (): Promise<SuccessBody> => {
        try {
          return await once();
        } catch (err) {
          if (!isRead || !this.shouldRetry(err)) throw err;
          // 100-300 ms, so a burst of reads that all hit one restart does not
          // come back in lockstep.
          await new Promise((resolve) => setTimeout(resolve, 100 + Math.random() * 200));
          return once();
        }
      };
      return this.limiter ? this.limiter.run(run) : run();
    };
    if (!isRead) {
      try {
        return parseOrThrowWithStatus<T>(await fetchBody());
      } finally {
        // The reads after a write get the whole read deadline again.
        if (this.readDeadlineMs !== undefined) this.readDeadlineAt = Date.now() + this.readDeadlineMs;
      }
    }
    const body = this.memo && isSharedRead(path)
      ? await this.memo.run(`${method} ${path} ${payload}`, fetchBody)
      : await fetchBody();
    return parseOrThrowWithStatus<T>(body);
  }
}

/**
 * The backend refused a request for want of its local bearer token (a 401
 * with code `local_token_required`, from the loopback guard). The message keeps
 * the `401: <body>` shape every other HTTP failure has, so code that reads an
 * error code back out of a message still sees it; `renderCliError` recognises
 * the class and says how to fix it.
 */
export class LocalTokenRequiredError extends Error {
  readonly code = "local_token_required";
  constructor(body: string) {
    super(`401: ${errorBodyForMessage(body)}`);
    this.name = "LocalTokenRequiredError";
  }
}

/** What `httpError` adds to its Error when it is handed the response headers. */
export interface HttpErrorDetail {
  /** The HTTP status, the same number the message starts with. */
  readonly status?: number;
  /** The raw `Retry-After` header, when the response carried one. */
  readonly retryAfter?: string;
}

/**
 * The error for a non-2xx response: `<status>: <body>`, or a typed one we can explain.
 *
 * With `headers`, the Error also carries `status` and, when the response had
 * one, `retryAfter` (see `HttpErrorDetail`), both non-enumerable. The message
 * is the same either way: many callers read the status and the error code back
 * out of it, so it must not change shape. Only the commit routes pass headers,
 * for the ingest's transient-status retry (`cli/commit-retry.ts`).
 */
export function httpError(status: number, body: string, headers?: Pick<Headers, "get">): Error {
  if (status === 401) {
    try {
      const parsed = JSON.parse(body) as { code?: unknown } | null;
      if (parsed?.code === "local_token_required") return new LocalTokenRequiredError(body);
    } catch { /* not the guard's JSON: a plain 401 */ }
  }
  const err = new Error(`${status}: ${errorBodyForMessage(body)}`);
  if (headers !== undefined) {
    Object.defineProperty(err, "status", { value: status, enumerable: false });
    const retryAfter = headers.get("retry-after");
    if (retryAfter !== null) Object.defineProperty(err, "retryAfter", { value: retryAfter, enumerable: false });
  }
  return err;
}

/**
 * An error response body as it goes into an Error message. A JSON body is kept
 * whole: callers read its error code back out of the message. Anything else,
 * such as a proxy's HTML page, is cut to 300 characters, so a multi-megabyte
 * page never becomes a message, a log line or an MCP tool result.
 */
export function errorBodyForMessage(text: string, max = 300): string {
  const trimmed = text.trim();
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
    try {
      JSON.parse(trimmed);
      return text;
    } catch {
      // not JSON after all: truncate below
    }
  }
  return text.length > max ? `${text.slice(0, max)}… (${text.length - max} more characters)` : text;
}

interface SuccessBody {
  status: number;
  text: string;
}

/**
 * Read a 2xx body as JSON, keeping the status in the error if it will not parse.
 *
 * A bare `resp.json()` rejects with a `SyntaxError` that says nothing about
 * what the server answered, so a caller could only infer "it must have been a
 * 2xx, because a non-2xx would have thrown above" -- an inference this codebase
 * has no business making, since the whole premise of Ix#528 and Ix#568 is that
 * whatever proxy sits in front spells things the way it likes, up to and
 * including a 200 with an HTML error page. Stating the status turns that
 * inference into a fact the error carries, and it matches the `${status}: ...`
 * shape every other failure here already uses.
 */
function parseOrThrowWithStatus<T>({ status, text }: SuccessBody): T {
  try {
    return JSON.parse(text) as T;
  } catch {
    const preview = text.length > 200 ? `${text.slice(0, 200)}…` : text;
    throw new Error(`${status}: response body is not JSON: ${preview}`);
  }
}