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
23.1 KB
Raw Blame
/**
 * Note lifecycle MCP tool: `brain_note_lifecycle` (B2, t_9571a47f).
 *
 * One tool dispatching on `action` - rename, move, archive, delete for a
 * note FILE, move-folder and rename-folder for a whole FOLDER - in the
 * shape `brain_lifecycle` established. The sibling name is deliberate and
 * so is the separation: `brain_lifecycle` is the BELIEF lifecycle
 * (tombstone, supersede, temporal-replace), which marks a memory's status
 * in frontmatter and never moves a byte. This one moves and removes
 * files. Merging them would put "mark this claim superseded" and "delete
 * this file" behind one `action` key, where a mistyped value is the
 * difference between an annotation and a deletion.
 *
 * The handler coerces arguments, owns the dispatch and renders the
 * result; every guard - the path envelope on BOTH paths, the
 * confirmation ladder, the count guard, the recovery point and its
 * verdict - lives in the core (`notes/lifecycle.ts` for the file
 * actions, `notes/folder-lifecycle.ts` for the folder ones, which is
 * where a folder action runs), so the CLI verb beside it cannot drift
 * into a different set of rules.
 *
 * Refusals carry their typed `code` in `data` rather than only in prose,
 * because the three an agent must branch on - a missing source, an
 * occupied destination, an unconfirmed delete - each have a different
 * next move.
 */

import {
  noteLifecycle,
  NoteLifecycleError,
  NOTE_LIFECYCLE_ACTIONS,
  isNoteLifecycleAction,
  type NoteLifecycleResult,
  type NoteReferenceReport,
} from "../../core/brain/notes/lifecycle.ts";
import {
  folderLifecycle,
  isFolderLifecycleAction,
  type FolderLifecycleResult,
} from "../../core/brain/notes/folder-lifecycle.ts";
import {
  DANGLING_SCAN_DEFAULT_LIMIT,
  listDanglingTargets,
  scaffoldStub,
  ScaffoldStubError,
} from "../../core/brain/notes/scaffold-stub.ts";
import { CountGuardError } from "../../core/brain/count-guard.ts";
import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
import { pageSlice } from "../../core/brain/offset-cursor.ts";
import {
  CreateNoteError,
  CREATE_NOTE_IF_EXISTS,
  type CreateNoteIfExists,
} from "../../core/brain/notes/create-note.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import { COUNT_GUARD_WIRE_CODE, TOOL_ERROR_CODE } from "../tool-error-codes.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { coerceBoolOptional, coerceStr, unknownOperationError } from "../coerce.ts";
import { coerceNonNegativeInteger, readCountGuardArgs } from "./shared.ts";
import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { cursorOffsetArg, CURSOR_SCHEMA } from "./pagination.ts";

const TOOL = "brain_note_lifecycle";

/**
 * The reference report, identical on both lifecycle machines - the folder
 * result carries the same {@link NoteReferenceReport} the file result
 * does, so the projection is written once.
 */
function renderReferences(refs: NoteReferenceReport): Record<string, unknown> {
  return {
    files_scanned: refs.filesScanned,
    inbound_files: [...refs.inboundFiles],
    files_rewritten: refs.filesRewritten,
    rewritten_spellings: refs.rewrittenSpellings.map((s) => ({
      from: s.from,
      to: s.to,
    })),
    // Non-empty means the operation is half-applied: the note is at
    // `to` and these files still name `from`. Rendered on every
    // response, empty included, so a caller reading the field is
    // reading an answer rather than guessing from its absence.
    rewrite_failures: refs.rewriteFailures.map((f) => ({
      path: f.path,
      reason: f.reason,
    })),
    basename: refs.basename,
    index: {
      state: refs.index.state,
      last_indexed_at: refs.index.lastIndexedAt,
      next_command: refs.index.nextCommand,
    },
    // `claimed` says a detached refresh run is IN FLIGHT, never that it
    // has landed; every other value names why nothing was started, and
    // `refresh_reason` spells that reason - the freshen machinery's own
    // skip token, or the error it raised - so `not_claimed` is never
    // the whole answer a caller receives. Read from THIS call's own
    // decision, never from state another vault could have written.
    refresh: refs.refresh,
    refresh_reason: refs.refreshReason,
  };
}

/** Project the frozen core result into the tool's snake_cased response. */
function renderResult(res: NoteLifecycleResult): Record<string, unknown> {
  return {
    action: res.action,
    from: res.from,
    to: res.to,
    applied: res.applied,
    recoverability: {
      state: res.recoverability.state,
      coverage: [...res.recoverability.coverage],
      blockers: [...res.recoverability.blockers],
    },
    snapshot:
      res.snapshot === null ? null : { run_id: res.snapshot.runId, path: res.snapshot.path },
    references: renderReferences(res.references),
    // `null` when no cascade was asked for, which is a different answer
    // from a cascade that found nothing. Rendered on every response so a
    // caller reads the distinction rather than inferring it from an
    // absent key.
    cascade:
      res.cascade === null
        ? null
        : {
            deletion_set: [...res.cascade.deletionSet],
            reported_files: [...res.cascade.reportedFiles],
            scanned_scope: res.cascade.scannedScope,
          },
  };
}

/**
 * Project the folder result into the same snake_cased response shape,
 * with the move report in the folder module's own style: the list of
 * what relocated, and the per-file list of what did not and why.
 */
function renderFolderResult(res: FolderLifecycleResult): Record<string, unknown> {
  return {
    action: res.action,
    from: res.from,
    to: res.to,
    applied: res.applied,
    moved: res.moved.map((m) => ({ from: m.from, to: m.to })),
    move_failures: res.moveFailures.map((f) => ({ path: f.path, reason: f.reason })),
    // Absent-when-empty: a move that emptied its source folder carried
    // nothing through, so the key's presence is the signal.
    ...(res.leftBehind.length > 0 ? { left_behind: [...res.leftBehind] } : {}),
    // Absent-when-empty: the moved notes' relative Markdown links and
    // images whose target stayed behind, named per note and target. The
    // wikilink pass repairs [[path]] spellings only, so without this a
    // files_rewritten: 0 would read as "nothing broke" while every
    // relative embed in the moved notes pointed at nothing.
    ...(res.danglingRelativeLinks.length > 0
      ? {
          dangling_relative_links: res.danglingRelativeLinks.map((l) => ({
            note: l.note,
            target: l.target,
          })),
        }
      : {}),
    recoverability: {
      state: res.recoverability.state,
      coverage: [...res.recoverability.coverage],
      blockers: [...res.recoverability.blockers],
    },
    // Always null on this surface: a relocation destroys nothing, so no
    // recovery point is taken (the rewrite's risk is the verdict's).
    snapshot: null,
    references: renderReferences(res.references),
  };
}

async function toolBrainNoteLifecycle(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  const action = coerceStr(args, "action", true)!;
  if (!isNoteLifecycleAction(action)) {
    // Refused rather than defaulted: a caller that asked for a
    // disposition this tool does not have must never be told its request
    // succeeded under a different one.
    throw unknownOperationError(
      `${TOOL}: 'action' must be one of ${NOTE_LIFECYCLE_ACTIONS.join(", ")}`,
    );
  }
  const path = coerceStr(args, "path", true)!;
  const to = coerceStr(args, "to", false) ?? undefined;
  const apply = coerceBoolOptional(args, "apply");
  const confirm = coerceBoolOptional(args, "confirm");
  const deleteLinked = coerceBoolOptional(args, "delete_linked");
  const { expect, strict } = readCountGuardArgs(args);

  try {
    // The surface owns the dispatch: one vocabulary, two machines. A
    // folder action sent to the file module would be refused
    // `wrong_action` - the action exists and the caller named it
    // correctly, so it runs where it lives.
    if (isFolderLifecycleAction(action)) {
      // Refused rather than dropped, the file surface's own rule for a
      // flag whose action cannot honour it: a folder action is never a
      // delete, so neither flag has anything to extend - honouring them
      // silently would tell a caller that asked for a cascade that it
      // got one.
      if (confirm !== undefined || deleteLinked !== undefined) {
        throw new MCPError(
          INVALID_PARAMS,
          `${TOOL}: ${action} takes neither confirm nor delete_linked: a folder action is never a delete`,
          { code: "cascade_forbidden" },
        );
      }
      const res = await folderLifecycle(ctx.vault, {
        action,
        path,
        ...(to !== undefined ? { to } : {}),
        ...(apply !== undefined ? { apply } : {}),
        expect,
        strict,
        // A folder holding a note the caller may not read at its reach
        // is refused exactly as a missing one - the folder lifecycle
        // judges its move set by the same predicate the file surface
        // judges its subject by.
        readable: readableAtContextReach(ctx),
        ...(ctx.configPath !== null ? { refreshConfigPath: ctx.configPath } : {}),
      });
      return renderFolderResult(res);
    }
    const res = await noteLifecycle(ctx.vault, {
      action,
      path,
      ...(to !== undefined ? { to } : {}),
      ...(apply !== undefined ? { apply } : {}),
      ...(confirm !== undefined ? { confirm } : {}),
      ...(deleteLinked !== undefined ? { deleteLinked } : {}),
      expect,
      strict,
      // A note the caller may not read at its reach is refused exactly
      // as a missing one.
      readable: readableAtContextReach(ctx),
      // The post-write refresh resolves through the server's own config
      // path, like every other search-resolving call in this file.
      ...(ctx.configPath !== null ? { refreshConfigPath: ctx.configPath } : {}),
    });
    return renderResult(res);
  } catch (err) {
    // The three typed refusals reach the caller as the caller's fault,
    // each keeping the code it decides on. A count-guard mismatch also
    // carries the number it measured, because "you said 5, it is 1" is
    // the whole of the remedy.
    if (err instanceof NoteLifecycleError) {
      throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, { code: err.code });
    }
    if (err instanceof CreateNoteError) {
      throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, { code: err.code });
    }
    if (err instanceof CountGuardError) {
      throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, {
        code: COUNT_GUARD_WIRE_CODE,
        matched: err.matched,
        expected: err.expected,
      });
    }
    if (err instanceof MCPError) throw err;
    throw new MCPError(
      INTERNAL_ERROR,
      `${TOOL}: ${err instanceof Error ? err.message : String(err)}`,
    );
  }
}

/**
 * The two things a caller can do about an unresolved wikilink target
 * (B3): find out which ones there are, and materialise one.
 *
 * A separate tool from {@link TOOL} rather than a fifth action on it, and
 * the reason is the subject. Every note-lifecycle action names an
 * EXISTING note by path; a dangling target has no path yet - that is what
 * makes it dangling. Folding them together would give one required
 * parameter two meanings and one vocabulary two shapes.
 */
const STUB_TOOL = "brain_scaffold_stub";

export const STUB_SCAFFOLD_ACTION = Object.freeze({
  /** Read the vault's unresolved targets from the index, or say why not. */
  list: "list",
  /** Materialise a stub for one target. */
  write: "write",
} as const);

/** Closed union over {@link STUB_SCAFFOLD_ACTION}. */
export type StubScaffoldAction = (typeof STUB_SCAFFOLD_ACTION)[keyof typeof STUB_SCAFFOLD_ACTION];

/** Membership list, read before write. */
export const STUB_SCAFFOLD_ACTIONS: ReadonlyArray<StubScaffoldAction> = Object.freeze(
  Object.values(STUB_SCAFFOLD_ACTION),
);

/** See {@link isNoteLifecycleAction} for why the parameter is `unknown`. */
export function isStubScaffoldAction(value: unknown): value is StubScaffoldAction {
  return (
    typeof value === "string" && (STUB_SCAFFOLD_ACTIONS as ReadonlyArray<string>).includes(value)
  );
}

/**
 * Which arguments belong to which action, so one sent to the other is
 * refused rather than dropped.
 *
 * `brain_scaffold_stub` dispatches on `action` and its two actions share
 * one flat argument list, so `{"action":"list","target":"Foo","apply":true}`
 * used to return a normal `state: "measured", targets: []` envelope - an
 * agent holding a stale `action` reads that as a write that happened.
 * `argument-guard.ts` calls a silently ignored argument "the worst kind
 * of fallback", and the sibling tool in this file has taken the other
 * road since it shipped: `to` on an archive or a delete is a typed
 * `destination_forbidden`, not a no-op.
 */
const STUB_ACTION_ARGUMENTS: Readonly<Record<StubScaffoldAction, ReadonlyArray<string>>> =
  Object.freeze({
    [STUB_SCAFFOLD_ACTION.list]: Object.freeze(["limit", "cursor"]),
    [STUB_SCAFFOLD_ACTION.write]: Object.freeze([
      "target",
      "path",
      "sources",
      "if_exists",
      "apply",
    ]),
  });

/**
 * Refuse every argument that belongs to the OTHER action. `action`
 * itself is the dispatch key and belongs to both; anything the schema
 * does not declare at all is already refused upstream by the
 * unknown-argument gate, so this reads the declared vocabulary only.
 */
function assertArgumentsMatchAction(
  args: Record<string, unknown>,
  action: StubScaffoldAction,
): void {
  const mine = STUB_ACTION_ARGUMENTS[action];
  const foreign = STUB_SCAFFOLD_ACTIONS.flatMap((other) =>
    other === action ? [] : [...STUB_ACTION_ARGUMENTS[other]],
  )
    .filter((name) => !mine.includes(name))
    .filter((name) => args[name] !== undefined && args[name] !== null)
    .toSorted();
  if (foreign.length === 0) return;
  throw new MCPError(
    INVALID_PARAMS,
    `${STUB_TOOL}: action=${action} takes none of ${foreign.join(", ")}; ` +
      `it reads ${mine.join(", ")}`,
    { code: TOOL_ERROR_CODE.argumentForbidden, action, forbidden: foreign, accepted: [...mine] },
  );
}

/** Read an optional string array argument, refusing a non-array. */
function coerceStringArray(args: Record<string, unknown>, field: string): string[] {
  const raw = args[field];
  if (raw === undefined || raw === null) return [];
  if (!Array.isArray(raw) || !raw.every((item) => typeof item === "string")) {
    throw new MCPError(INVALID_PARAMS, `${STUB_TOOL}: ${field} must be an array of strings`);
  }
  return raw as string[];
}

async function toolBrainScaffoldStub(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  const action = coerceStr(args, "action", true)!;
  if (!isStubScaffoldAction(action)) {
    throw unknownOperationError(
      `${STUB_TOOL}: 'action' must be one of ${STUB_SCAFFOLD_ACTIONS.join(", ")}`,
    );
  }

  assertArgumentsMatchAction(args, action);

  if (action === STUB_SCAFFOLD_ACTION.list) {
    const limit = coerceNonNegativeInteger(STUB_TOOL, "limit", args["limit"]);
    const offset = cursorOffsetArg(STUB_TOOL, args);
    // `sources` are vault-relative document paths and `target` is the
    // link spelling, so an unscoped listing published both for a note
    // this caller may not read (a-label-is-not-a-boundary, U3).
    // A source the caller may not read at its reach is dropped like one
    // outside its owner scope. The full filtered set is read (the scan's
    // own cap applied wide) and one page is cut here, so `total` counts
    // every dangling target across pages and `next_cursor` continues
    // the walk (null when exhausted).
    const readable = readableAtContextReachOrUndefined(ctx);
    const scan = await listDanglingTargets(ctx.vault, {
      limit: Number.MAX_SAFE_INTEGER,
      ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,
      ...(readable !== undefined ? { readable } : {}),
    });
    // The schema admits `limit: 0` and the pre-cursor surface answered it
    // with an empty list, so a schema-valid zero keeps that meaning: an
    // empty page with the walk already exhausted. `pageSlice` only takes
    // a positive limit, and letting its OffsetCursorError escape would
    // surface as INTERNAL_ERROR - an internal failure for a request the
    // schema calls well-formed. Absent `limit`, the page is the scan's
    // own historical default (DANGLING_SCAN_DEFAULT_LIMIT) - an
    // unpaginated list used to answer 100 targets and reach a cursor,
    // not every dangling target in one unbounded answer.
    const page =
      limit === 0
        ? { items: [], total: scan.targets.length, next_cursor: null as string | null }
        : pageSlice(scan.targets, offset, limit ?? DANGLING_SCAN_DEFAULT_LIMIT);
    return {
      action,
      state: scan.state,
      total: page.total,
      targets: page.items.map((t) => ({ target: t.target, sources: [...t.sources] })),
      detail: scan.detail,
      next_command: scan.nextCommand,
      next_cursor: page.next_cursor,
    };
  }

  const target = coerceStr(args, "target", true)!;
  const path = coerceStr(args, "path", false) ?? undefined;
  const ifExists = coerceStr(args, "if_exists", false) ?? undefined;
  if (ifExists !== undefined && !CREATE_NOTE_IF_EXISTS.includes(ifExists as CreateNoteIfExists)) {
    throw new MCPError(
      INVALID_PARAMS,
      `${STUB_TOOL}: if_exists must be one of ${CREATE_NOTE_IF_EXISTS.join(", ")}`,
    );
  }
  const apply = coerceBoolOptional(args, "apply");

  // A source the caller may not read is refused as a missing one, and an
  // occupied-target refusal names no note it may not read.
  const readable = readableAtContextReachOrUndefined(ctx);
  try {
    const res = scaffoldStub(ctx.vault, {
      ...(readable !== undefined ? { readable } : {}),
      target,
      ...(path !== undefined ? { path } : {}),
      sources: coerceStringArray(args, "sources"),
      ...(ifExists !== undefined ? { ifExists: ifExists as CreateNoteIfExists } : {}),
      ...(apply !== undefined ? { apply } : {}),
      ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),
    });
    return {
      action,
      target: res.target,
      path: res.path,
      applied: res.applied,
      outcome: res.outcome,
      sources: [...res.sources],
    };
  } catch (err) {
    if (err instanceof ScaffoldStubError) {
      throw new MCPError(INVALID_PARAMS, `${STUB_TOOL}: ${err.message}`, {
        code: err.code,
        ...(err.candidates.length > 0 ? { candidates: [...err.candidates] } : {}),
      });
    }
    if (err instanceof CreateNoteError) {
      throw new MCPError(INVALID_PARAMS, `${STUB_TOOL}: ${err.message}`, { code: err.code });
    }
    if (err instanceof MCPError) throw err;
    throw new MCPError(
      INTERNAL_ERROR,
      `${STUB_TOOL}: ${err instanceof Error ? err.message : String(err)}`,
    );
  }
}

export const LIFECYCLE_FILE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
  {
    name: TOOL,
    kind: "write",
    description:
      "Note lifecycle: rename, move, archive, delete take a note file; move-folder/rename-folder run the folder lifecycle. Dry-run unless apply; delete needs confirm. Rewrites inbound [[wikilinks]] minimally so they still resolve; applied writes claim the detached refresh (claimed, not landed).",
    inputSchema: {
      type: "object",
      properties: {
        action: {
          type: "string",
          enum: [...NOTE_LIFECYCLE_ACTIONS],
          description: "Which lifecycle operation to run on the note file.",
        },
        path: {
          type: "string",
          description:
            "Vault-relative path of the subject: a note file (must end in .md) for the file actions, a folder for move-folder/rename-folder; stays inside the vault.",
        },
        to: {
          type: "string",
          description:
            "rename/move: vault-relative destination. move-folder: the DIRECTORY the folder lands in; rename-folder: the new single-segment name. Forbidden for archive and delete.",
        },
        apply: {
          type: "boolean",
          description:
            "Perform the operation. Absent means a dry run that reports the blast radius and writes nothing.",
        },
        confirm: {
          type: "boolean",
          description:
            "delete: explicit confirmation. Without it an applied delete is refused, because no archive covers a user-authored note.",
        },
        delete_linked: {
          type: "boolean",
          description:
            "delete only: also remove Brain files whose frontmatter names this note as their source and traces SOLELY to it. A prose mention is reported, never deleted.",
        },
        expect: {
          type: "integer",
          minimum: 0,
          description:
            "Assert the count before any write: the deletion set under delete_linked, otherwise the files holding an inbound reference. A mismatch aborts.",
        },
        strict: {
          type: "boolean",
          description: "Refuse a mutation that carries no expect guard.",
        },
      },
      required: ["action", "path"],
      additionalProperties: false,
    },
    previewBudget: MCP_PREVIEW_BUDGET,
    handler: toolBrainNoteLifecycle,
  },
  {
    name: STUB_TOOL,
    kind: "write",
    description:
      "Unresolved wikilink targets. action: list reads them from the search index and refuses with a state and a next_command when that index is missing or partly resolved, rather than reporting zero; write materialises a stub for one target, its body linking back to the sources. Dry-run unless apply.",
    inputSchema: {
      type: "object",
      properties: {
        action: {
          type: "string",
          enum: [...STUB_SCAFFOLD_ACTIONS],
          description: "list reads the dangling targets; write materialises one.",
        },
        target: {
          type: "string",
          description: "write: the unresolved wikilink target, e.g. Projects/Foo or Foo.",
        },
        path: {
          type: "string",
          description:
            "write: explicit vault-relative destination. Absent derives <target>.md, the path the link itself named.",
        },
        sources: {
          type: "array",
          items: { type: "string" },
          description:
            "write: vault-relative paths that referenced the target; they become the stub's body wikilinks.",
        },
        if_exists: {
          type: "string",
          enum: [...CREATE_NOTE_IF_EXISTS],
          description:
            "write: occupied-destination policy. Default refuse; skip returns outcome=skipped, never created.",
        },
        apply: {
          type: "boolean",
          description:
            "write: materialise the stub. Absent means a dry run that reports the destination and writes nothing.",
        },
        limit: {
          type: "integer",
          minimum: 0,
          description: "list: maximum targets returned.",
        },
        cursor: CURSOR_SCHEMA,
      },
      required: ["action"],
      additionalProperties: false,
    },
    previewBudget: MCP_PREVIEW_BUDGET,
    handler: toolBrainScaffoldStub,
  },
]);