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
7.5 KB
Raw Blame
/**
 * What one caller may see, over the REFERENCES a report row carries
 * rather than over a ranked search result.
 *
 * Extracted from `./owner-scope-view.ts` when a second rule - the
 * transport-reach visibility boundary - needed the same adapter. The
 * ownership rule and the visibility rule are different questions with
 * different answers, but the plumbing between "a row names `[[pref-x]]`"
 * and "here is the vault-relative path of `pref-x`" is one piece of
 * machinery, and a second copy of it would be a second place for a
 * directory to go missing.
 *
 * Neither this module nor its bindings is a registry: each one delegates
 * the per-PATH decision to the single place that rule meets the
 * filesystem (`isPathOwnerVisible` / `isPathReadableAtReach`, both in
 * `src/core/search/result-filters.ts`), so a report-shaped surface and a
 * ranked one cannot drift on what "hidden" means - including the
 * unreadable-file verdict, which an empty frontmatter map cannot express.
 *
 * ## Two conventions every binding inherits
 *
 * FAIL CLOSED, in whichever direction its rule fails closed. A page whose
 * file cannot be read has an unknowable answer, and an unreadable claim
 * is not the absence of one.
 *
 * IDENTICAL TO ABSENT. A withheld row is dropped and nothing counts it: a
 * count would tell the caller that a row it may not see exists, which is
 * the existence leak the search side already avoids. So no surface using
 * one of these views reports how many rows it withheld.
 */

import { resolve } from "node:path";

import { pathIsInside } from "../path-safety.ts";
import type { FrontmatterCache } from "../search/result-filters.ts";
import { resolveArtifactRef } from "./artifact-ref-resolve.ts";

/**
 * A reference a report row carries: either a vault-relative path
 * (`Brain/preferences/pref-x.md`, `notes/y.md`), an extensionless
 * vault-page spelling of one (`Brain/notes/private`, the conventional
 * Obsidian wikilink body), or a bare Brain artifact id (`pref-x`,
 * `ret-y`, `sig-2026-05-01-z`), optionally spelled as a wikilink
 * (`[[pref-x]]`, `[[notes/y.md]]`).
 *
 * `null` / `undefined` / empty are accepted and read as "this row names
 * nothing here", which is visible: a row with no subject cannot disclose
 * one.
 */
export type ArtifactRef = string | null | undefined;

/** One rule, bound to one vault, asked over references. */
export interface ArtifactRefView {
  /**
   * True when this view cannot hide anything, so a caller may skip the
   * work of asking it.
   *
   * It exists for the surfaces whose filtered form is not byte-identical
   * to their unfiltered one - a rendered log day is split on its event
   * headings and rejoined - and that must stay verbatim when no rule is
   * live. Read as "is there anything to ask", never as "is the caller
   * entitled": the decision is always {@link ArtifactRefView.visible}.
   */
  readonly filtersNothing: boolean;
  /**
   * True when the caller is below local reach, so records of the store's
   * `private` partition that carry no reference of their own (log events)
   * are withheld from it. Absent means false.
   */
  readonly withholdsPrivate?: boolean;
  /** May the caller see the artifact or page this reference names? */
  readonly visible: (ref: ArtifactRef) => boolean;
  /**
   * May the caller see a row that names ALL of these? One hidden
   * reference hides the row: a row survives only when every artifact it
   * would disclose is one the caller may already see.
   */
  readonly row: (...refs: ReadonlyArray<ArtifactRef>) => boolean;
  /** Drop the rows whose references are not all visible. */
  readonly keep: <T>(
    rows: ReadonlyArray<T>,
    refsOf: (row: T) => ReadonlyArray<ArtifactRef>,
  ) => ReadonlyArray<T>;
}

/** A view that hides nothing, allocated once. */
export const UNFILTERED_ARTIFACT_REFS: ArtifactRefView = Object.freeze({
  filtersNothing: true,
  visible: () => true,
  row: () => true,
  keep: <T>(rows: ReadonlyArray<T>) => rows,
});

/**
 * Bind one per-path rule to one vault, as a reference-shaped view.
 *
 * `pathVisible` is handed the shared per-response frontmatter cache, the
 * same sharing `search()` gives its filter stages, so a response that
 * names the same artifact from several rows parses it once.
 */
export function artifactRefView(
  vault: string,
  pathVisible: (rel: string, cache: FrontmatterCache) => boolean,
): ArtifactRefView {
  const cache: FrontmatterCache = new Map();
  // Per-response memo over the REFERENCE, beside the one over the path.
  // Rows name the same artifact repeatedly - a log day's events about one
  // preference, a backlink list's sources - and `artifactPath` costs one
  // `existsSync` per Brain directory for every id-shaped string that
  // resolves to nothing, which is the common case now that the whole
  // payload is offered rather than four named keys.
  const verdicts = new Map<string, boolean>();
  const visible = (ref: ArtifactRef): boolean => {
    if (ref === null || ref === undefined || ref.length === 0) return true;
    const memo = verdicts.get(ref);
    if (memo !== undefined) return memo;
    // A bare id with no artifact on disk names nothing that could be
    // hidden - see `artifact-ref-resolve.ts` for why that reading is only
    // true while its directory list is complete.
    const rel = resolveArtifactRef(vault, ref);
    // A reference that resolves outside the vault names no page anyone
    // could be shown, and is hidden before the rule reads anything: log
    // bodies carry strings an earlier caller wrote.
    const verdict =
      rel === null ? true : pathIsInside(resolve(vault, rel), vault) && pathVisible(rel, cache);
    verdicts.set(ref, verdict);
    return verdict;
  };
  return Object.freeze({
    filtersNothing: false,
    visible,
    row: (...refs: ReadonlyArray<ArtifactRef>) => refs.every(visible),
    keep: <T>(rows: ReadonlyArray<T>, refsOf: (r: T) => ReadonlyArray<ArtifactRef>) =>
      rows.filter((r) => refsOf(r).every(visible)),
  });
}

/**
 * One view that keeps a reference only when every constituent does.
 *
 * The rules are ANDed rather than folded: they are independent questions
 * with independent answers, and which one dropped a row is not
 * observable, because none of them reports a count.
 */
export function everyArtifactRefView(...views: ReadonlyArray<ArtifactRefView>): ArtifactRefView {
  const live = views.filter((v) => !v.filtersNothing);
  if (live.length === 0) return UNFILTERED_ARTIFACT_REFS;
  const visible = (ref: ArtifactRef): boolean => live.every((v) => v.visible(ref));
  return Object.freeze({
    filtersNothing: false,
    ...(live.some((v) => v.withholdsPrivate === true) ? { withholdsPrivate: true } : {}),
    visible,
    row: (...refs: ReadonlyArray<ArtifactRef>) => refs.every(visible),
    keep: <T>(rows: ReadonlyArray<T>, refsOf: (r: T) => ReadonlyArray<ArtifactRef>) =>
      rows.filter((r) => refsOf(r).every(visible)),
  });
}

/**
 * The reference view a per-reader render asks: unfiltered when the caller
 * passed no path predicate and is at local reach, the predicate bound to
 * `vault` otherwise. `withholdsPrivate`: the caller is below local reach,
 * so events of the store's `private` partition are withheld from it
 * (`ArtifactRefView.withholdsPrivate`).
 */
export function readerRefView(
  vault: string,
  readable: ((rel: string) => boolean) | undefined,
  withholdsPrivate = false,
): ArtifactRefView {
  if (readable === undefined && !withholdsPrivate) return UNFILTERED_ARTIFACT_REFS;
  const view = artifactRefView(vault, (rel) => readable?.(rel) ?? true);
  return withholdsPrivate ? Object.freeze({ ...view, withholdsPrivate: true }) : view;
}