Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
10.7 KB
Raw Blame
/**
 * Read-only operational-readability report for the codegraph partner
 * (https://github.com/colbymchenry/codegraph).
 *
 * This surface answers "is a code project in scope, is codegraph indexing
 * it, and - for Rust - which Cargo workspace members were declared" WITHOUT
 * installing, initializing, extracting, or mutating anything. It composes the
 * existing code-project discovery and status helpers with a small structural
 * `Cargo.toml` reader.
 *
 * It deliberately does NOT run `codegraph`/`graphify` extraction and does NOT
 * fabricate `crate_depends_on` edges into the Open Second Brain graph: a missing
 * CLI, a missing index, or a non-Rust project are all honest report states, not
 * errors and not silent no-ops.
 */

import { existsSync, readFileSync, realpathSync } from "node:fs";
import { join } from "node:path";

import {
  CODEGRAPH_CLI,
  codegraphInitCommand,
  defaultRunStatusJson,
  isCodegraphUnanswered,
  defaultWhichCodegraph,
  findCodeProjects,
  type CodegraphStatusResult,
} from "./codegraph.ts";
import { assessGraphHealth, type GraphHealthReport } from "./codegraph-health.ts";

export interface CargoWorkspace {
  readonly manifestPath: string;
  readonly members: string[];
  readonly memberCount: number;
}

export interface CargoWorkspaceResult {
  readonly workspace: CargoWorkspace | null;
  readonly reason: string;
}

/**
 * Structural read of a project's `Cargo.toml` for workspace membership.
 *
 * Parses only the `[workspace]` table's `members = [...]` array - no full TOML
 * evaluation, no dependency resolution. Returns `workspace: null` with an
 * explicit reason when there is no `Cargo.toml` or no `[workspace]` table.
 */
export function readCargoWorkspace(projectDir: string): CargoWorkspaceResult {
  const manifestPath = join(projectDir, "Cargo.toml");
  if (!existsSync(manifestPath)) {
    return { workspace: null, reason: "no Cargo.toml in project root (not a Rust project)" };
  }

  let text: string;
  try {
    text = readFileSync(manifestPath, "utf8");
  } catch (exc) {
    return { workspace: null, reason: `Cargo.toml unreadable: ${(exc as Error).message}` };
  }

  const lines = text.split(/\r?\n/);
  let currentTable: string | null = null;
  let members: string[] | null = null;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]!;
    const stripped = stripComment(line).trim();
    if (stripped.length === 0) continue;

    if (stripped.startsWith("[")) {
      // Any table header changes scope, including `[[array-of-tables]]`
      // (matchTableHeader returns null for those, never "workspace"). The
      // `members` key is only valid directly under the top-level `[workspace]`
      // table, so sub-tables like `[workspace.package]` must not collect it.
      currentTable = matchTableHeader(stripped);
      continue;
    }

    if (currentTable !== "workspace") continue;

    const key = matchKey(stripped);
    if (key !== "members") continue;

    // An unterminated array (malformed manifest) yields what we parsed so far
    // rather than scanning the rest of the file.
    members = collectArray(lines, i).values;
    break;
  }

  if (!inWorkspaceTablePresent(text)) {
    return {
      workspace: null,
      reason: "Cargo.toml present but has no [workspace] table (single-crate project)",
    };
  }

  return {
    workspace: {
      manifestPath,
      members: members ?? [],
      memberCount: (members ?? []).length,
    },
    reason: "ok",
  };
}

function inWorkspaceTablePresent(text: string): boolean {
  for (const raw of text.split(/\r?\n/)) {
    const stripped = stripComment(raw).trim();
    if (matchTableHeader(stripped) === "workspace") return true;
  }
  return false;
}

function stripComment(line: string): string {
  // Structural-only: a `#` outside a string starts a comment. Cargo workspace
  // member entries are simple quoted paths, so we honor quotes minimally.
  let inSingle = false;
  let inDouble = false;
  for (let i = 0; i < line.length; i++) {
    const ch = line[i];
    if (ch === '"' && !inSingle) inDouble = !inDouble;
    else if (ch === "'" && !inDouble) inSingle = !inSingle;
    else if (ch === "#" && !inSingle && !inDouble) return line.slice(0, i);
  }
  return line;
}

function matchTableHeader(stripped: string): string | null {
  if (!stripped.startsWith("[") || stripped.startsWith("[[")) return null;
  const end = stripped.indexOf("]");
  if (end < 0) return null;
  return stripped.slice(1, end).trim();
}

function matchKey(stripped: string): string | null {
  const eq = stripped.indexOf("=");
  if (eq < 0) return null;
  return stripped.slice(0, eq).trim();
}

/** Collect a possibly multi-line `members = [ "a", "b" ]` array as raw strings. */
function collectArray(
  lines: ReadonlyArray<string>,
  startIdx: number,
): { values: string[]; complete: boolean } {
  let buf = "";
  for (let i = startIdx; i < lines.length; i++) {
    buf += stripComment(lines[i]!);
    if (buf.includes("]")) {
      const open = buf.indexOf("[");
      const close = buf.indexOf("]", open + 1);
      if (open >= 0 && close > open) {
        return { values: extractStrings(buf.slice(open + 1, close)), complete: true };
      }
    }
    buf += "\n";
  }
  return { values: extractStrings(buf), complete: false };
}

function extractStrings(inner: string): string[] {
  const out: string[] = [];
  const re = /"([^"]*)"|'([^']*)'/g;
  let m: RegExpExecArray | null;
  while ((m = re.exec(inner)) !== null) {
    out.push(m[1] ?? m[2] ?? "");
  }
  return out;
}

export type CodegraphIndexState = "no_project" | "absent" | "not_indexed" | "indexed" | "error";

export interface CodegraphReport {
  readonly schema_version: 1;
  readonly project: string | null;
  readonly cli: { readonly available: boolean; readonly path: string | null };
  readonly index: {
    readonly state: CodegraphIndexState;
    readonly node_count?: number;
    readonly file_count?: number;
    readonly edge_count?: number;
    readonly reason?: string;
    /**
     * Read-only graph-health gate result. Present only when the index is
     * `indexed` (there is a graph to assess). Findings are non-blocking
     * warnings - a syntactically present graph that is nonetheless an
     * untrustworthy input for labeling/import/recall (empty, edge-collapsed,
     * dangling references, self-loops, or built for a different root).
     */
    readonly health?: GraphHealthReport;
  };
  readonly cargo_workspace: CargoWorkspace | null;
  readonly cargo_workspace_reason: string;
}

export interface CodegraphReportOptions {
  readonly cwd: string;
  readonly vault: string;
  readonly scanExtraPaths?: ReadonlyArray<string>;
  readonly limit?: number;
}

export interface CodegraphReportDeps {
  readonly whichCodegraph?: () => string | null;
  readonly runStatusJson?: (projectPath: string) => CodegraphStatusResult;
  readonly readCargoWorkspace?: (projectDir: string) => CargoWorkspaceResult;
}

/**
 * Build a schema-versioned, read-only partner report. Never throws on the
 * normal "partner absent / not indexed / not Rust" states - those are values,
 * not failures - so CLI and MCP wrappers can render them directly.
 */
export function buildCodegraphReport(
  opts: CodegraphReportOptions,
  deps?: CodegraphReportDeps,
): CodegraphReport {
  const projects = findCodeProjects(opts);
  const whichFn = deps?.whichCodegraph ?? defaultWhichCodegraph;
  const cliPath = whichFn();
  const cli = { available: cliPath !== null, path: cliPath };

  if (projects.length === 0) {
    return {
      schema_version: 1,
      project: null,
      cli,
      index: { state: "no_project", reason: "no code project in scope" },
      cargo_workspace: null,
      cargo_workspace_reason: "no code project in scope",
    };
  }

  const project = projects[0]!;
  const cargoFn = deps?.readCargoWorkspace ?? readCargoWorkspace;
  const cargo = cargoFn(project);

  const index = resolveIndexState(project, cliPath, deps);

  return {
    schema_version: 1,
    project: displayPath(project),
    cli,
    index,
    cargo_workspace: cargo.workspace,
    cargo_workspace_reason: cargo.reason,
  };
}

/**
 * Canonicalize the reported project path so it matches the shape callers
 * already hold. On macOS `/var` is a symlink to `/private/var`, so
 * `realpathSync` resolves temp roots (Node's `tmpdir()` -> `/var/folders/...`)
 * to `/private/var/...`; stripping the `/private` prefix restores the
 * user-facing `/var/...` form. The narrow prefix is deliberate - only the
 * `/var` firmlink is rewritten this way, never an arbitrary `/private/*` path.
 * Display-only: index resolution above runs against the raw `project`.
 */
function displayPath(path: string): string {
  try {
    const real = realpathSync(path);
    return real.startsWith("/private/var/") ? real.slice("/private".length) : real;
  } catch {
    return path.startsWith("/private/var/") ? path.slice("/private".length) : path;
  }
}

function resolveIndexState(
  project: string,
  cliPath: string | null,
  deps?: CodegraphReportDeps,
): CodegraphReport["index"] {
  if (cliPath === null) {
    return { state: "absent", reason: `${CODEGRAPH_CLI.bin} CLI not on PATH (optional partner)` };
  }
  if (!existsSync(join(project, ".codegraph"))) {
    return { state: "not_indexed", reason: `run: ${codegraphInitCommand(project)}` };
  }
  const runFn = deps?.runStatusJson ?? defaultRunStatusJson;
  const status = runFn(project);
  if (isCodegraphUnanswered(status)) {
    // `error` is the closest of the five states, and the reason carries
    // what it cannot: the partner was stopped at its deadline rather than
    // having reported anything. What matters is that this is NOT
    // `not_indexed` - the state whose remediation is `codegraph init`,
    // which is the wrong thing to run at a partner that is still going.
    return {
      state: "error",
      reason:
        `${CODEGRAPH_CLI.bin} ${CODEGRAPH_CLI.statusSubcommand} did not answer within ` +
        `${status.waitedMs}ms and was stopped; nothing is claimed here about this index`,
    };
  }
  if (!status.ok) {
    return { state: "error", reason: status.error };
  }
  if (!status.data.initialized) {
    return { state: "not_indexed", reason: `run: ${codegraphInitCommand(project)}` };
  }
  const nodeCount = status.data.nodeCount ?? 0;
  const edgeCount = status.data.edgeCount ?? 0;
  const health = assessGraphHealth({
    nodeCount,
    edgeCount,
    ...(status.data.danglingRefs !== undefined ? { danglingRefs: status.data.danglingRefs } : {}),
    ...(status.data.selfLoops !== undefined ? { selfLoops: status.data.selfLoops } : {}),
    indexRoot: status.data.worktreeMismatch?.indexRoot ?? status.data.projectPath ?? null,
    worktreeRoot: status.data.worktreeMismatch?.worktreeRoot ?? project,
  });
  return {
    state: "indexed",
    node_count: nodeCount,
    file_count: status.data.fileCount ?? 0,
    edge_count: edgeCount,
    health,
  };
}