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
8.4 KB
Raw Blame
/**
 * MCP Resources surface (introduced in v0.9.1).
 *
 * Resources let an MCP host pull a piece of Brain state by URI instead
 * of asking the agent to call `brain_query` first. The five URI shapes
 * we ship are:
 *
 *   osb://preferences/active     β€” Brain/active.md (auto-generated by dream)
 *   osb://digest/latest          β€” current `renderDigest({format: "markdown"})`
 *   osb://preference/{id}        β€” Brain/preferences/pref-{id}.md OR
 *                                  Brain/retired/ret-{id}.md when the
 *                                  preferences/ copy is gone
 *   osb://rule-topic/{slug}      β€” synthesized markdown summary of every
 *                                  signal + the current pref / retired
 *                                  for the rule-topic slug (the old name
 *                                  osb://topic/{slug} is an alias for one
 *                                  minor version)
 *   osb://topic/{id}             β€” one topic (design D8) by its id, as
 *                                  its rendered page
 *   osb://log/{date}             β€” Brain/log/<date>.md as-is
 *
 * The first two are concrete resources (returned by `resources/list`).
 * The last three are templates (returned by `resources/templates/list`).
 * `resources/read` accepts both shapes uniformly.
 *
 * Implementation notes:
 *
 *   - All slug / id / date arguments are validated through the existing
 *     `validateSlug` / `validateIsoDate` helpers. A bad value is an
 *     `INVALID_PARAMS` error, NOT a 404 β€” we want client bugs to be
 *     visibly different from genuinely-missing files.
 *   - Read responses are text/markdown. We avoid serializing structured
 *     data here because the rest of the MCP surface already does that
 *     via tools; resources are the "give me the markdown body" channel.
 *   - Missing files produce `INTERNAL_ERROR` with a `not found` message
 *     β€” same shape as `brain_query`'s `BrainNotFoundError` so callers
 *     can treat both surfaces consistently.
 *
 * ## Ownership (a-label-is-not-a-boundary, U3)
 *
 * This surface is `resources/*`, and the isolation matrix's population
 * was `tools/*`. So while every delivery tool learned to ask the
 * ownership rule, `resources/read osb://preference/{id}` still handed
 * back another owner's page in full - frontmatter, `owner:` line and
 * body prose - under the same `integrity.owner_scope_delivery: fail`
 * that made the tool withhold it. A boundary one protocol verb honours
 * and its neighbour ignores is not a boundary.
 *
 * The four templated readers that reach owner-taggable content -
 * `preference/{id}`, `topic/{slug}`, `backlinks/{id}`, `log/{date}` -
 * therefore go through {@link gatedOwnerScopeView}, the same adapter and
 * the same gate the tools use. A withheld artifact is reported with the
 * `not found` message an ABSENT one produces, because a distinguishable
 * refusal would announce the page it is meant to hide.
 *
 * The three digest readers (`preferences/active`, `lessons`,
 * `digest/latest`) render preference records, so each answers with the
 * request view: a record the caller may not see is absent from the
 * digest it is handed. The shared files stay unscoped - they are
 * regenerated unscoped and never rewritten for one reader; the narrowed
 * digest is rendered in memory. `status` returns counts over the whole
 * Brain layer and is not filtered here.
 */

import type {
  ResourceContent,
  ResourceContext,
  ResourceDescriptor,
  ResourceTemplateDescriptor,
} from "./resources-shared.ts";
import { MIME_MARKDOWN, parseUri, requestView } from "./resources-shared.ts";
import {
  readActive,
  readDigestLatest,
  readLessons,
  readStatus,
} from "./resources-digest-readers.ts";
import { readLog, readPreference, readRuleTopic } from "./resources-record-readers.ts";
import { readBacklinks } from "./resources-backlink-readers.ts";
import { readTopicById } from "./resources-topic-readers.ts";

export type {
  ResourceContext,
  ResourceDescriptor,
  ResourceTemplateDescriptor,
  ResourceContent,
} from "./resources-shared.ts";

const CONCRETE: ReadonlyArray<ResourceDescriptor> = [
  {
    uri: "osb://preferences/active",
    name: "Active Brain preferences",
    description:
      "Auto-generated digest of confirmed and quarantined preferences plus the three most recently retired entries. Regenerated at the tail of every dream run.",
    mimeType: MIME_MARKDOWN,
  },
  {
    uri: "osb://lessons",
    name: "Brain lessons digest",
    description:
      "Auto-generated, signed and recency-scored lessons corpus unifying preferences and dead-ends into corroboration-tiered lessons (preferred / tentative / contested / avoid). Regenerated at the tail of every dream run.",
    mimeType: MIME_MARKDOWN,
  },
  {
    uri: "osb://digest/latest",
    name: "Latest Brain digest",
    description: "Same body as `brain_brief` view=digest (default window: last 24h). Markdown.",
    mimeType: MIME_MARKDOWN,
  },
  {
    uri: "osb://status",
    name: "Brain operational status",
    description:
      "Counts (inbox/preferences/retired/log/snapshots), last-activity timestamps, and a sanity flag for signals awaiting dream. Markdown.",
    mimeType: MIME_MARKDOWN,
  },
];

const TEMPLATES: ReadonlyArray<ResourceTemplateDescriptor> = [
  {
    uriTemplate: "osb://preference/{id}",
    name: "Brain preference by id",
    description:
      "The preference with this id (or its retired copy when the active one is gone), as Markdown.",
    mimeType: MIME_MARKDOWN,
  },
  {
    uriTemplate: "osb://rule-topic/{slug}",
    name: "Brain rule-topic summary",
    description:
      "Markdown synthesis of every signal (active + processed), the current preference (or retired), the most recent log mentions, and a deterministic 'Strongest objection' steelman against the current preference for the rule-topic slug. The old name osb://topic/{slug} still answers for one minor version.",
    mimeType: MIME_MARKDOWN,
  },
  {
    uriTemplate: "osb://topic/{id}",
    name: "Brain topic",
    description:
      "One topic by its id (a ULID): the page the human view renders for it (status, goal, milestones, decisions, open questions, log, related), as Markdown.",
    mimeType: MIME_MARKDOWN,
  },
  {
    uriTemplate: "osb://log/{date}",
    name: "Brain daily log",
    description: "The brain log of one day (YYYY-MM-DD), as Markdown.",
    mimeType: MIME_MARKDOWN,
  },
  {
    uriTemplate: "osb://backlinks/{id}",
    name: "Brain backlinks for id",
    description:
      "Inbound references to the given Brain artifact id (preference, retired, or signal). Rendered as a count plus a grouped list of sources.",
    mimeType: MIME_MARKDOWN,
  },
];

export function listResources(): ReadonlyArray<ResourceDescriptor> {
  return CONCRETE;
}

export function listResourceTemplates(): ReadonlyArray<ResourceTemplateDescriptor> {
  return TEMPLATES;
}

export function readResource(ctx: ResourceContext, uri: string): ResourceContent {
  const parsed = parseUri(uri);
  switch (parsed.kind) {
    case "active":
      return readActive(ctx, uri, requestView(ctx));
    case "lessons":
      return readLessons(ctx, uri, requestView(ctx));
    case "digestLatest":
      return readDigestLatest(ctx, uri, requestView(ctx));
    case "status":
      return readStatus(ctx, uri);
    case "preference":
      return readPreference(ctx, uri, parsed.id, requestView(ctx));
    case "ruleTopic":
      return readRuleTopic(ctx, uri, parsed.slug, requestView(ctx));
    case "topic":
      // A ULID-shaped value that names no topic the caller sees is still a
      // rule-topic slug through the old name.
      return (
        readTopicById(ctx, uri, parsed.id) ?? readRuleTopic(ctx, uri, parsed.id, requestView(ctx))
      );
    case "log":
      return readLog(ctx, uri, parsed.date, requestView(ctx));
    case "backlinks":
      return readBacklinks(ctx, uri, parsed.id, requestView(ctx));
  }
}

/**
 * Both rules bound to this request, built once per read.
 *
 * Constructed at the switch rather than inside each reader so a reader
 * added later cannot be the one that forgot: the four templated cases
 * pass it explicitly and the compiler requires it.
 *
 * The two are ANDed rather than folded: ownership and reserved-token
 * visibility are independent questions with independent answers, and a
 * row survives only when both keep it. Which one dropped it is not
 * observable, because neither reports a count - see
 * `src/core/brain/artifact-ref-view.ts`.
 */

// ----- Helpers -------------------------------------------------------------