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
15.3 KB
Raw Blame
/**
 * Brain general atomic batch write surface: `brain_write_batch`.
 *
 * The second consumer of the atomic write-batch core (kernel 2). One
 * ordered list of typed operations is committed all-or-nothing: the first
 * invalid operation aborts with a typed error naming the operation index
 * and no disk write happens. The operation vocabulary is create note,
 * update note (body and/or frontmatter), append note, apply evidence, and
 * append log line - each mapped onto an existing core writer.
 *
 * This layer only maps request params onto the core's typed operations
 * (no MCP shapes reach the core) and maps the typed WriteBatchError onto a
 * structured INVALID_PARAMS. Single-operation batches here produce the
 * same result as the dedicated brain_create_note / brain_update_note /
 * brain_append_note tools.
 */

import { resolveAgentName } from "../../core/config.ts";
import { normalizeAgentArgument } from "../../core/agent-identity.ts";
import { BRAIN_ROLES } from "../../core/brain/trust/role.ts";
import type { BrainApplyOutcome, BrainApplyResult } from "../../core/brain/types.ts";
import {
  applyWriteBatch,
  MAX_BATCH_OPERATIONS,
  WRITE_BATCH_RECEIPT_STATUS,
  type WriteBatchReceipt,
  type WriteBatchResult,
  type WriteOperation,
} from "../../core/brain/write-batch.ts";
import {
  IdempotencyKeyError,
  IdempotencyPayloadMismatchError,
} from "../../core/brain/idempotency-ledger.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { noteWriteResult, parseFrontmatterArg, writeBatchErrorToMcp } from "./notes-tools.ts";
import { refuseAgentClaim } from "./agent-claim.ts";
import { readableAtContextReach } from "./reach-readable.ts";
import { toolPath } from "./device-path.ts";
import { unknownOperationError } from "../coerce.ts";
import { PENDING_STAGED_DIAGNOSTIC_CODE } from "../../core/brain/pending/pending-lanes.ts";
import { nextCommandField } from "../../core/brain/next-step.ts";
import { WRITE_PATH_ADVISORY_KEY } from "../../core/brain/write-path-advisory.ts";

/** Recognised batch operation discriminators. */
const OP_KINDS = [
  "create_note",
  "update_note",
  "append_note",
  "apply_evidence",
  "append_log_line",
] as const;

function requireStr(raw: Record<string, unknown>, key: string, opLabel: string): string {
  const value = raw[key];
  if (typeof value !== "string" || value.trim() === "") {
    throw new MCPError(INVALID_PARAMS, `brain_write_batch: ${opLabel} requires a string '${key}'`);
  }
  return value;
}

function optionalStr(raw: Record<string, unknown>, key: string): string | undefined {
  const value = raw[key];
  if (value === undefined || value === null) return undefined;
  if (typeof value !== "string") {
    throw new MCPError(INVALID_PARAMS, `brain_write_batch: '${key}' must be a string`);
  }
  return value;
}

function optionalBool(raw: Record<string, unknown>, key: string): boolean | undefined {
  const value = raw[key];
  if (value === undefined || value === null) return undefined;
  if (typeof value !== "boolean") {
    throw new MCPError(INVALID_PARAMS, `brain_write_batch: '${key}' must be a boolean`);
  }
  return value;
}

/**
 * Map one untrusted request operation object onto a typed
 * {@link WriteOperation}. `resolveAgent` supplies the caller identity for
 * the log-writing operations (apply_evidence, append_log_line).
 */
function mapOperation(
  raw: unknown,
  index: number,
  resolveAgent: (override?: string) => string,
): WriteOperation {
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
    throw new MCPError(INVALID_PARAMS, `brain_write_batch: operations[${index}] must be an object`);
  }
  const obj = raw as Record<string, unknown>;
  const op = obj["op"];
  switch (op) {
    case "create_note":
      return {
        kind: "create_note",
        path: requireStr(obj, "path", "create_note"),
        ...(obj["frontmatter"] !== undefined
          ? { frontmatter: parseFrontmatterArg(obj["frontmatter"], "brain_write_batch")! }
          : {}),
        ...(optionalStr(obj, "content") !== undefined
          ? { content: optionalStr(obj, "content")! }
          : {}),
      };
    case "update_note": {
      const frontmatter = parseFrontmatterArg(obj["frontmatter"], "brain_write_batch");
      const content = optionalStr(obj, "content");
      const allowEmpty = optionalBool(obj, "allow_empty");
      if (frontmatter === undefined && content === undefined) {
        throw new MCPError(
          INVALID_PARAMS,
          `brain_write_batch: operations[${index}] update_note requires frontmatter or content`,
        );
      }
      return {
        kind: "update_note",
        path: requireStr(obj, "path", "update_note"),
        ...(frontmatter !== undefined ? { frontmatter } : {}),
        ...(content !== undefined ? { body: content } : {}),
        ...(allowEmpty !== undefined ? { allowEmpty } : {}),
      };
    }
    case "append_note":
      return {
        kind: "append_note",
        path: requireStr(obj, "path", "append_note"),
        content: requireStr(obj, "content", "append_note"),
      };
    case "apply_evidence": {
      const outcome = optionalStr(obj, "outcome");
      const note = optionalStr(obj, "note");
      return {
        kind: "apply_evidence",
        input: {
          pref_id: requireStr(obj, "pref_id", "apply_evidence"),
          artifact: requireStr(obj, "artifact", "apply_evidence"),
          result: requireStr(obj, "result", "apply_evidence") as BrainApplyResult,
          agent: resolveAgent(optionalStr(obj, "agent")),
          ...(outcome !== undefined ? { outcome: outcome as BrainApplyOutcome } : {}),
          ...(note !== undefined ? { note } : {}),
        },
        options: { role: BRAIN_ROLES.applier },
      };
    }
    case "append_log_line":
      return {
        kind: "append_log_line",
        input: {
          text: requireStr(obj, "text", "append_log_line"),
          agent: resolveAgent(optionalStr(obj, "agent")),
        },
      };
    default:
      throw unknownOperationError(
        `brain_write_batch: operations[${index}].op must be one of ${OP_KINDS.join(", ")}`,
      );
  }
}

/**
 * Serialize one core op result, mapping absolute log paths to
 * vault-relative form so the response never leaks the machine root. A
 * STAGED create (review gate on) carries its pending id and the queue
 * command that publishes it, so an agent sees the review boundary
 * rather than reading `created: false` as a refusal.
 */
function serializeResult(
  ctx: ServerContext,
  result: WriteBatchResult["results"][number],
): Record<string, unknown> {
  if (result.kind === "apply_evidence" || result.kind === "append_log_line") {
    return {
      kind: result.kind,
      logged_at: result.logged_at,
      log_path: toolPath(ctx, result.log_path),
    };
  }
  if (result.kind === "create_note" && result.created === false) {
    return {
      kind: result.kind,
      path: result.path,
      created: false,
      staged: true,
      pending_id: result.pending_id,
      ...(result[WRITE_PATH_ADVISORY_KEY] !== undefined
        ? { [WRITE_PATH_ADVISORY_KEY]: result[WRITE_PATH_ADVISORY_KEY] }
        : {}),
      ...nextCommandField(PENDING_STAGED_DIAGNOSTIC_CODE),
    };
  }
  return { ...result };
}

/**
 * The note ops that actually put bytes on disk: a create always wrote,
 * while an update or append whose flag says `false` skipped a
 * byte-identical target and carries a path but no commit. The receipt's
 * lint reads only the committed half.
 */
function committedNotePage(
  result: WriteBatchResult["results"][number],
): result is Extract<WriteBatchResult["results"][number], { readonly path: string }> {
  return (
    (result.kind === "create_note" && result.created) ||
    (result.kind === "update_note" && result.updated) ||
    (result.kind === "append_note" && result.appended)
  );
}

/**
 * The receipt half of the response. A `payload_conflict` also says in
 * words what the status means for the caller: the writes landed, so the
 * batch must not be sent again under a new ID.
 */
function receiptFields(receipt: WriteBatchReceipt): Record<string, unknown> {
  return {
    request_id: receipt.requestId,
    receipt: receipt.status,
    ...(receipt.status === WRITE_BATCH_RECEIPT_STATUS.payload_conflict
      ? {
          receipt_note:
            `The writes of this call landed (see results). request_id '${receipt.requestId}' ` +
            "was recorded concurrently for a different payload, so this call's receipt was not " +
            "recorded; do not resend this batch under a new request_id.",
        }
      : {}),
  };
}

async function toolBrainWriteBatch(
  ctx: ServerContext,
  args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  const rawOps = args["operations"];
  if (!Array.isArray(rawOps)) {
    throw new MCPError(INVALID_PARAMS, "brain_write_batch: 'operations' must be an array");
  }
  // The log-writing ops stamp their agent attribution from the caller's
  // override, then the config. A token caller claims neither: the
  // mismatch is refused, and the identity fills the absent override
  // (write-side-trust, Task 7).
  const resolveAgent = (override?: string): string => {
    refuseAgentClaim(ctx.requestIdentity, override ?? null, "brain_write_batch");
    return (
      normalizeAgentArgument(override ?? null) ??
      ctx.requestIdentity?.agent ??
      resolveAgentName(ctx.configPath ?? undefined)
    );
  };
  const operations = rawOps.map((raw, index) => mapOperation(raw, index, resolveAgent));
  const requestId = optionalStr(args, "request_id");

  // An update or append whose target the caller may not read at its
  // reach is refused exactly as a missing one. The transport-minted
  // identity rides as the batch's subject (write-side-trust, Task 7),
  // covering the owner gate and the deny-only document consult on the
  // update and append ops.
  const baseOpts = {
    readable: readableAtContextReach(ctx),
    ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),
    ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),
  };
  let batch: WriteBatchResult;
  // Set exactly when a request ID was supplied: the core's receipted
  // overload always carries the status, so nothing here invents one.
  let receipt: WriteBatchReceipt | undefined;
  try {
    if (requestId === undefined) {
      batch = applyWriteBatch(ctx.vault, operations, baseOpts);
    } else {
      const receipted = applyWriteBatch(ctx.vault, operations, { ...baseOpts, requestId });
      batch = receipted;
      receipt = receipted.receipt;
    }
  } catch (err) {
    // A reused request ID with a different payload, or an ID the ledger
    // cannot store (blank, over-long), is the caller's mistake, not the
    // server's: INVALID_PARAMS with the ledger's own explanation, the same
    // mapping the checkpoint tools use. Both are raised before any write.
    if (err instanceof IdempotencyPayloadMismatchError || err instanceof IdempotencyKeyError) {
      throw new MCPError(INVALID_PARAMS, `brain_write_batch: request_id: ${err.message}`);
    }
    throw writeBatchErrorToMcp(err, "brain_write_batch");
  }
  // The pages this batch committed, in commit order. Log-writing ops name
  // no note path: their line is machine-composed, not authored, so there
  // is nothing for the page lint to judge. A byte-identical rewrite that
  // skipped wrote nothing either, so it names no page - the same rule the
  // single-write receipts follow. One report covers the whole batch, with
  // the basename index and schema pack built ONCE.
  // A duplicate wrote nothing: its results are the retained receipt of the
  // call that committed, read back from the synced ledger, so it names no
  // page as one this call wrote and nothing is linted.
  const writtenPages =
    receipt?.status === WRITE_BATCH_RECEIPT_STATUS.duplicate
      ? []
      : batch.results.filter(committedNotePage).map((r) => r.path);
  return noteWriteResult(ctx, writtenPages, {
    applied: batch.applied,
    results: batch.results.map((r) => serializeResult(ctx, r)),
    done: true,
    ...(receipt !== undefined ? receiptFields(receipt) : {}),
  });
}

export const WRITE_BATCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
  {
    name: "brain_write_batch",
    kind: "write",
    description:
      "Apply an ordered batch of Brain write operations atomically. Ops: create_note, update_note, append_note, apply_evidence, append_log_line. Validated first; the first invalid op aborts with a typed error naming its index and nothing is written. Note ops honour the declared write binding.",
    inputSchema: {
      type: "object",
      properties: {
        operations: {
          type: "array",
          maxItems: MAX_BATCH_OPERATIONS,
          description:
            "Ordered operations; each has an `op` discriminator plus that op's params. Committed all-or-nothing.",
          items: {
            type: "object",
            properties: {
              op: {
                type: "string",
                enum: [...OP_KINDS],
                description: "Operation kind.",
              },
              path: {
                type: "string",
                description: "Vault-relative .md path (create_note, update_note, append_note).",
              },
              frontmatter: {
                type: "object",
                description:
                  "Frontmatter map to write or merge (create_note, update_note). Values: string, number, boolean, or string array.",
                additionalProperties: { type: ["string", "number", "boolean", "array"] },
              },
              content: {
                type: "string",
                description:
                  "Note body: create_note/update_note replacement, or append_note appended text.",
              },
              allow_empty: {
                type: "boolean",
                description:
                  "update_note only: allow empty or whitespace-only content to clear the note. Default false; a blank body over a note that has text is refused.",
              },
              pref_id: { type: "string", description: "Preference id for apply_evidence." },
              artifact: { type: "string", description: "Artifact wikilink for apply_evidence." },
              result: {
                type: "string",
                enum: ["applied", "violated", "outdated"],
                description: "Evidence result for apply_evidence.",
              },
              outcome: {
                type: "string",
                enum: ["success", "failure", "unknown"],
                description: "Optional downstream outcome for apply_evidence.",
              },
              note: { type: "string", description: "Optional one-line note for apply_evidence." },
              text: { type: "string", description: "Narrative line for append_log_line." },
              agent: {
                type: "string",
                description: "Optional identity override for apply_evidence / append_log_line.",
              },
            },
            required: ["op"],
            additionalProperties: false,
          },
        },
        request_id: {
          type: "string",
          description: `Optional request ID for exactly-once writes: a repeat with the same operations returns receipt "${WRITE_BATCH_RECEIPT_STATUS.duplicate}" and writes nothing; other operations are refused.`,
        },
      },
      required: ["operations"],
      additionalProperties: false,
    },
    handler: toolBrainWriteBatch,
  },
]);