Skip to content

Self-hosted MCP server + dashboard giving Claude Code, Cursor & Hermes agents shared long-term memory over a git-backed markdown vault. Agent-native, Obsidian-compatible second brain — markdown RAG, no vector DB.

feat(curator): one agent loop, two surfaces

Ronalds Palacis49b33db7f285
diff --git a/app/(app)/settings/page.tsx b/app/(app)/settings/page.tsx
index 64fe188..e686ce0 100644
--- a/app/(app)/settings/page.tsx
+++ b/app/(app)/settings/page.tsx
@@ -17,7 +17,7 @@ type CuratorMode = "off" | "chat" | "full";
const CURATOR_MODES: { id: CuratorMode; label: string; blurb: string }[] = [
{ id: "off", label: "Off", blurb: "Engram never calls a model. A deterministic MCP server and dashboard." },
{ id: "chat", label: "Chat", blurb: "Ask questions of your vault in the dashboard. The model reads; it cannot write." },
- { id: "full", label: "Full", blurb: "Adds brain_capture: an agent hands Engram a rough dump and it files the note. Chat stays read-only." },
+ { id: "full", label: "Full", blurb: "Chat can edit notes, and agents can file rough dumps with brain_capture. Neither can delete." },
];
interface PublicSettings {
diff --git a/lib/agent.ts b/lib/agent.ts
new file mode 100644
index 0000000..cd9370f
--- /dev/null
+++ b/lib/agent.ts
@@ -0,0 +1,262 @@
+import Anthropic from "@anthropic-ai/sdk";
+import { DEFAULT_CURATOR_MODEL, SUPPORTED_MODEL_IDS } from "@/lib/models";
+import { anthropicApiKey } from "@/lib/settings";
+import { TOOLS, type Tool } from "@/lib/mcp/tools";
+import { getNote, readVaultFile, vaultConventions } from "@/lib/vault/store";
+import { normalizeNotePath } from "@/lib/vault/write";
+import { withActor } from "@/lib/actor";
+
+/**
+ * The Curator — one agentic loop, two surfaces.
+ *
+ * chat — a human asks questions in the dashboard (streamed).
+ * capture — an agent hands over a rough dump and the loop files it (blocking, via brain_capture).
+ *
+ * Both run the same tools, the same conventions, and the same safety rules. They differ only in
+ * their prompt and their capability profile, because the trust boundary differs: a human is
+ * watching the chat, and nobody is watching a capture at 2am.
+ *
+ * The tools come straight from lib/mcp/tools.ts rather than being redefined here. When they were
+ * defined twice, the second copy silently rotted — the Curator went months describing a return
+ * shape that no longer existed.
+ */
+export type AgentProfile = "chat" | "capture";
+
+export interface ChatMessage {
+ role: "user" | "assistant";
+ content: string;
+}
+
+/** Everything the loop changed, so a caller who delegated the decision can see what happened. */
+export interface Manifest {
+ created: string[];
+ updated: string[];
+ appended: string[];
+ moved: string[];
+}
+
+export type AgentEvent =
+ | { type: "text"; text: string }
+ | { type: "thinking"; text: string }
+ | { type: "tool"; name: string }
+ | { type: "manifest"; manifest: Manifest }
+ | { type: "done" }
+ | { type: "error"; message: string };
+
+/**
+ * Tools the loop may use.
+ *
+ * `brain_capture` is excluded always — the loop *is* capture, and exposing it to itself invites
+ * an agent calling an agent. `brain_delete` is excluded always: archiving (brain_move) demotes a
+ * note out of search while preserving the reasoning trail, and deletion is a human decision made
+ * in the dashboard where you can see what you are removing.
+ */
+export function loopTools(canWrite: boolean): Tool[] {
+ return TOOLS.filter((t) => {
+ if (t.name === "brain_capture" || t.name === "brain_delete") return false;
+ return canWrite || !t.write;
+ });
+}
+
+const toAnthropicTool = (t: Tool): Anthropic.Tool => ({
+ name: t.name,
+ description: t.description,
+ input_schema: t.inputSchema as Anthropic.Tool.InputSchema,
+});
+
+const SHARED_RULES = `
+Rules that hold on every turn:
+- Ground every claim in the notes. Use brain_search to find them, brain_read to read them. Never invent a fact about this vault; if it isn't written down, say so.
+- Search ranks by keyword relevance, NOT by truth. Every result carries an "authority": authoritative > current > provisional > superseded > archived. Prefer the authoritative note. Never present a superseded, archived, or provisional note as current fact.
+- Compose freely for context and history. But a single-valued fact — a price, a guarantee, a legal entity, a contract term — has exactly one owning note. Do not merge sources for those, and never average two notes that disagree: that is a defect in the vault. Report it.
+- Read a note before you overwrite it. Writing a note you have not read destroys whatever was there.
+- Nothing is ever deleted. When a note stops being true, brain_move it into archive/ and leave a pointer in whatever replaced it.
+`.trim();
+
+const CHAT_PROMPT = `You are the Curator — the resident agent of this markdown "second brain". You help the operator recall, connect, and reason over their own notes.
+
+${SHARED_RULES}
+- Cite notes in wikilink form so the operator can click through, e.g. [[clients/mks/mks|MKS]].
+- Be direct, specific, concise. Lead with the answer, then the supporting detail.`;
+
+const CHAT_READONLY = `\n- You cannot write in this mode. If a change is needed, say exactly what you would change and let the operator make it.`;
+const CHAT_WRITE = `\n- You may edit the vault. The operator is watching, so act when asked — but read a note before you rewrite it, and say what you changed.`;
+
+const CAPTURE_PROMPT = `You file rough notes into a markdown "second brain". You are given a raw dump and must put it where it belongs, cleanly.
+
+${SHARED_RULES}
+
+How to work:
+1. brain_schema first — folder taxonomy, frontmatter conventions, and this vault's actual status vocabulary.
+2. brain_search for what already exists on this subject. Do not skip this: filing a duplicate is worse than filing nothing.
+3. Then decide, deliberately:
+ - Nothing exists → brain_write a new note at a sensible path.
+ - A note covers this already → brain_read it, then brain_append the new material, or brain_edit it with the FULL merged content.
+ - The dump supersedes an existing note → brain_move the old one into archive/ and write the replacement with a pointer to what it replaced.
+4. Prefer passing a \`frontmatter\` object plus a plain \`body\` over hand-writing YAML — it always parses.
+5. Finish with one short sentence saying what you did and why. No preamble.
+
+Never write to a path you have not read when a note already lives there. Never delete.`;
+
+/** Was this tool call a mutation, and of what shape? */
+const MUTATION_KIND: Record<string, keyof Manifest> = {
+ brain_write: "created",
+ brain_edit: "updated",
+ brain_append: "appended",
+ brain_move: "moved",
+};
+
+function noteExists(p: string): boolean {
+ try {
+ return getNote(normalizeNotePath(String(p))) !== null;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Structural read-before-overwrite. Not a size heuristic like the one in write.ts — this refuses
+ * the write outright until the loop has actually opened the note, so a same-size clobber is
+ * caught too. Returns an error message for the model, or null to proceed.
+ */
+export function guardOverwrite(toolName: string, target: string, readPaths: ReadonlySet<string>): string | null {
+ if (toolName !== "brain_write" && toolName !== "brain_edit") return null;
+ if (!target || !noteExists(target) || readPaths.has(target)) return null;
+ return `${target} already exists and you have not read it in this session. Call brain_read("${target}") first, then write back the full content you intend to keep — or use brain_append to add to it.`;
+}
+
+export interface AgentOpts {
+ profile: AgentProfile;
+ /** chat: the conversation. capture: a single user turn holding the rough dump. */
+ messages: ChatMessage[];
+ canWrite: boolean;
+ model?: string;
+ thinking?: boolean;
+ maxTurns?: number;
+ /**
+ * Who to credit for writes in the git log. Bound around each tool call rather than around the
+ * generator: an async generator resumes in the caller's context, so wrapping the whole stream
+ * would lose the actor on the very first `await`.
+ */
+ actor?: string;
+}
+
+/**
+ * Run the loop, yielding events. Chat streams them to the browser; capture drains them and
+ * keeps the manifest.
+ */
+export async function* agentStream(opts: AgentOpts): AsyncGenerator<AgentEvent> {
+ const apiKey = anthropicApiKey();
+ if (!apiKey) {
+ yield { type: "error", message: "No Anthropic API key. Enable the Curator in Settings and add a key." };
+ return;
+ }
+
+ const tools = loopTools(opts.canWrite);
+ const toolMap = new Map(tools.map((t) => [t.name, t]));
+ const model = opts.model && SUPPORTED_MODEL_IDS.has(opts.model) ? opts.model : DEFAULT_CURATOR_MODEL;
+ const client = new Anthropic({ apiKey });
+
+ const manifest: Manifest = { created: [], updated: [], appended: [], moved: [] };
+ /** Paths this run has actually read. The loop may not overwrite a note it hasn't opened. */
+ const readPaths = new Set<string>();
+
+ const system =
+ opts.profile === "capture"
+ ? CAPTURE_PROMPT
+ : CHAT_PROMPT + (opts.canWrite ? CHAT_WRITE : CHAT_READONLY);
+
+ const messages: Anthropic.MessageParam[] = opts.messages
+ .filter((m) => (m.role === "user" || m.role === "assistant") && typeof m.content === "string" && m.content.trim() !== "")
+ .map((m) => ({ role: m.role, content: m.content }));
+ if (messages.length === 0) {
+ yield { type: "error", message: "Nothing to do." };
+ return;
+ }
+
+ /** Run one tool call, enforcing read-before-overwrite and recording what changed. */
+ async function runTool(name: string, input: Record<string, unknown>): Promise<unknown> {
+ const tool = toolMap.get(name);
+ if (!tool) return { error: `unknown or forbidden tool: ${name}` };
+
+ const target = typeof input.path === "string" ? normalizeNotePath(input.path) : "";
+
+ const blocked = guardOverwrite(name, target, readPaths);
+ if (blocked) return { error: blocked };
+
+ const out = await withActor(opts.actor ?? "curator", () => tool.handler(input));
+
+ if (name === "brain_read" && target) readPaths.add(target);
+ const kind = MUTATION_KIND[name];
+ if (kind && out && typeof out === "object" && "path" in out) {
+ const p = String((out as { path: unknown }).path);
+ // brain_write on a path that already existed is an update, not a creation.
+ const bucket: keyof Manifest = name === "brain_write" && readPaths.has(target) ? "updated" : kind;
+ if (!manifest[bucket].includes(p)) manifest[bucket].push(p);
+ readPaths.add(p); // it is now known content
+ }
+ return out;
+ }
+
+ try {
+ const maxTurns = opts.maxTurns ?? 8;
+ for (let turn = 0; turn < maxTurns; turn++) {
+ const stream = client.messages.stream({
+ model,
+ max_tokens: 16000,
+ system,
+ tools: tools.map(toAnthropicTool),
+ messages,
+ ...(opts.thinking ? { thinking: { type: "adaptive", display: "summarized" } } : {}),
+ });
+
+ for await (const event of stream) {
+ if (event.type === "content_block_delta") {
+ if (event.delta.type === "text_delta") yield { type: "text", text: event.delta.text };
+ else if (event.delta.type === "thinking_delta") yield { type: "thinking", text: event.delta.thinking };
+ } else if (event.type === "content_block_start" && event.content_block.type === "tool_use") {
+ yield { type: "tool", name: event.content_block.name };
+ }
+ }
+
+ const message = await stream.finalMessage();
+ if (message.stop_reason !== "tool_use") {
+ yield { type: "manifest", manifest };
+ yield { type: "done" };
+ return;
+ }
+
+ messages.push({ role: "assistant", content: message.content });
+ const results: Anthropic.ToolResultBlockParam[] = [];
+ for (const block of message.content) {
+ if (block.type !== "tool_use") continue;
+ let out: unknown;
+ try {
+ out = await runTool(block.name, (block.input ?? {}) as Record<string, unknown>);
+ } catch (e) {
+ out = { error: e instanceof Error ? e.message : String(e) };
+ }
+ results.push({ type: "tool_result", tool_use_id: block.id, content: JSON.stringify(out).slice(0, 40000) });
+ }
+ messages.push({ role: "user", content: results });
+ }
+ // Ran out of turns — still report what was touched, so nothing is silently half-done.
+ yield { type: "manifest", manifest };
+ yield { type: "done" };
+ } catch (e) {
+ yield { type: "error", message: e instanceof Error ? e.message : String(e) };
+ }
+}
+
+/** Vault context injected into a capture, so the model doesn't have to discover it by tool call. */
+export function captureContext(): string {
+ const schema = readVaultFile("SCHEMA.md") ?? "(no SCHEMA.md)";
+ const c = vaultConventions();
+ return [
+ `Existing folders: ${c.folders.join(", ") || "(none yet)"}`,
+ `Statuses in use: ${c.statusesInUse.map((s) => s.status).join(", ") || "(none)"}`,
+ "",
+ "SCHEMA:",
+ schema,
+ ].join("\n");
+}
diff --git a/lib/curator.ts b/lib/curator.ts
index 15cc036..59b3a5b 100644
--- a/lib/curator.ts
+++ b/lib/curator.ts
@@ -1,145 +1,28 @@
-import Anthropic from "@anthropic-ai/sdk";
-import { DEFAULT_CURATOR_MODEL, SUPPORTED_MODEL_IDS } from "@/lib/models";
-import { anthropicApiKey } from "@/lib/settings";
-import { getBacklinks, getNote, listNotes, readVaultFile, searchNotes } from "@/lib/vault/store";
-import { authorityOf } from "@/lib/vault/authority";
+import { agentStream, type AgentEvent, type ChatMessage } from "@/lib/agent";
+import { curatorMode } from "@/lib/settings";
/**
- * The Curator — the resident chat agent of the brain. It answers questions about the
- * vault, grounded in the actual notes via read tools (search/read/list), streaming over
- * SSE with an interleaved tool loop. Read-only: it helps you think, it doesn't write notes.
- * Uses the official Anthropic SDK so model IDs + adaptive thinking are exact.
+ * The Curator's chat surface — a thin adapter over the shared agent loop (lib/agent.ts).
+ *
+ * Read-only in `chat` mode, write-capable in `full`. The tools, the conventions, and the
+ * safety rules all live in the loop, so this surface cannot drift away from the MCP one.
*/
+export type { ChatMessage };
+export type CuratorEvent = AgentEvent;
-function systemPrompt(): string {
- const schema = readVaultFile("SCHEMA.md");
- return `You are the Curator — the resident agent of this markdown "second brain". You help the operator recall, connect, and reason over their own notes.
-
-Rules:
-- Every note carries an "authority": authoritative > current > provisional > superseded > archived. Search ranks by keyword relevance, not truth, so a superseded note can outrank the live one. Prefer the authoritative note. Never present a superseded, archived, or provisional note as current fact; if that is all you have, say so explicitly.
-- Ground every factual claim about the vault in the notes. Use brain_search to find notes, brain_read to read their full content, brain_list to see what exists. Never invent facts about the vault — if it isn't in the notes, say so plainly.
-- Cite notes in wikilink form so the user can click through, e.g. [[clients/mks/mks|MKS]] or [[decisions/foo-2026-07-09]].
-- Be direct, specific, and concise. Lead with the answer, then the supporting detail.
-- You are READ-ONLY in this chat. You help the user think; you do not create or edit notes.
-${schema ? `\nThe vault's SCHEMA (folder taxonomy + conventions):\n"""\n${schema.slice(0, 4000)}\n"""` : ""}`;
-}
-
-// Anthropic tool definitions — read-only vault access.
-const TOOLS: Anthropic.Tool[] = [
- {
- name: "brain_search",
- description:
- "Keyword search across all notes. Use this first. Returns ranked hits with path, title, folder, status, a snippet, and `authority`. Ranking is by keyword relevance, NOT by truth: a superseded note repeats the query words as often as the live one. Trust `authority` (authoritative > current > provisional > superseded > archived) over rank order.",
- input_schema: { type: "object", properties: { query: { type: "string", description: "search query" } }, required: ["query"] },
- },
- {
- name: "brain_read",
- description:
- "Read a note's full markdown (frontmatter + body) plus its backlinks and `authority`. Path is vault-relative, e.g. 'clients/mks/mks.md'.",
- input_schema: { type: "object", properties: { path: { type: "string", description: "vault-relative path" } }, required: ["path"] },
- },
- {
- name: "brain_list",
- description: "List all notes with metadata (path, title, folder, type, tags, status, authority). Use to discover what exists.",
- input_schema: { type: "object", properties: {} },
- },
-];
-
-function runTool(name: string, input: Record<string, unknown>): unknown {
- if (name === "brain_search") return searchNotes(String(input.query ?? ""));
- if (name === "brain_read") {
- const p = String(input.path ?? "");
- const n = getNote(p);
- if (!n) return { error: `not found: ${p}` };
- return {
- path: p,
- authority: authorityOf(n),
- frontmatter: n.frontmatter,
- content: n.raw,
- backlinks: getBacklinks(p),
- ...(n.frontmatterError ? { warning: `Unparseable frontmatter (${n.frontmatterError}) — this note's status and tags are ignored.` } : {}),
- };
- }
- if (name === "brain_list") return listNotes().map((n) => ({ ...n, authority: authorityOf(n) }));
- return { error: `unknown tool: ${name}` };
-}
-
-export interface ChatMessage {
- role: "user" | "assistant";
- content: string;
-}
-export type CuratorEvent =
- | { type: "text"; text: string }
- | { type: "thinking"; text: string }
- | { type: "tool"; name: string }
- | { type: "done" }
- | { type: "error"; message: string };
-
-/** Stream a Curator turn: yields text/thinking/tool events, runs the vault tool loop server-side. */
export async function* curatorStream(opts: {
messages: ChatMessage[];
model?: string;
thinking?: boolean;
}): AsyncGenerator<CuratorEvent> {
- const apiKey = anthropicApiKey();
- if (!apiKey) {
- yield { type: "error", message: "No Anthropic API key. Enable the Curator in Settings and add a key." };
- return;
- }
- const model = opts.model && SUPPORTED_MODEL_IDS.has(opts.model) ? opts.model : DEFAULT_CURATOR_MODEL;
- const client = new Anthropic({ apiKey });
-
- const messages: Anthropic.MessageParam[] = opts.messages
- .filter((m) => (m.role === "user" || m.role === "assistant") && typeof m.content === "string" && m.content.trim() !== "")
- .map((m) => ({ role: m.role, content: m.content }));
- if (messages.length === 0) {
- yield { type: "error", message: "No message to send." };
- return;
- }
-
- try {
- for (let turn = 0; turn < 8; turn++) {
- const stream = client.messages.stream({
- model,
- max_tokens: 16000,
- system: systemPrompt(),
- tools: TOOLS,
- messages,
- ...(opts.thinking ? { thinking: { type: "adaptive", display: "summarized" } } : {}),
- });
-
- for await (const event of stream) {
- if (event.type === "content_block_delta") {
- if (event.delta.type === "text_delta") yield { type: "text", text: event.delta.text };
- else if (event.delta.type === "thinking_delta") yield { type: "thinking", text: event.delta.thinking };
- } else if (event.type === "content_block_start" && event.content_block.type === "tool_use") {
- yield { type: "tool", name: event.content_block.name };
- }
- }
-
- const message = await stream.finalMessage();
- if (message.stop_reason !== "tool_use") {
- yield { type: "done" };
- return;
- }
- // Echo the assistant turn back (thinking + tool_use blocks unchanged), then run the tools.
- messages.push({ role: "assistant", content: message.content });
- const results: Anthropic.ToolResultBlockParam[] = [];
- for (const block of message.content) {
- if (block.type === "tool_use") {
- let out: unknown;
- try {
- out = runTool(block.name, block.input as Record<string, unknown>);
- } catch (e) {
- out = { error: e instanceof Error ? e.message : String(e) };
- }
- results.push({ type: "tool_result", tool_use_id: block.id, content: JSON.stringify(out).slice(0, 40000) });
- }
- }
- messages.push({ role: "user", content: results });
- }
- yield { type: "done" };
- } catch (e) {
- yield { type: "error", message: e instanceof Error ? e.message : String(e) };
- }
+ // A human is present and every write lands in git, so chat may write once the operator
+ // has chosen `full`. It still never deletes — that is a decision made in the UI.
+ yield* agentStream({
+ profile: "chat",
+ messages: opts.messages,
+ canWrite: curatorMode() === "full",
+ actor: "curator (chat)",
+ model: opts.model,
+ thinking: opts.thinking,
+ });
}
diff --git a/lib/harness.ts b/lib/harness.ts
index 92f8b23..ba65082 100644
--- a/lib/harness.ts
+++ b/lib/harness.ts
@@ -1,87 +1,52 @@
+import { agentStream, captureContext, type Manifest } from "@/lib/agent";
import { anthropicApiKey, captureModel, harnessEnabled } from "@/lib/settings";
-import { getNote, getTree, listNotes, readVaultFile } from "@/lib/vault/store";
-import { normalizeNotePath, writeNote } from "@/lib/vault/write";
+import { currentActor } from "@/lib/actor";
-export interface CaptureResult {
- path: string;
- title: string;
- reasoning?: string;
+export interface CaptureResult extends Manifest {
+ /** One sentence from the loop on what it did and why. */
+ summary: string;
}
-/** True when a note already lives at this path (capture must not clobber it). */
-function noteExists(relPath: string): boolean {
- return getNote(normalizeNotePath(relPath)) !== null;
-}
-
-/** Distinct top-level folders currently in the vault. */
-function folderList(): string[] {
- const set = new Set<string>();
- for (const n of listNotes()) if (n.folder !== "root") set.add(n.folder);
- for (const c of getTree().children ?? []) if (c.type === "dir") set.add(c.name);
- return [...set].sort();
-}
-
-const SYSTEM = `You file rough notes into a markdown "second brain". Given the vault's SCHEMA and its current folders, decide where a rough note belongs and rewrite it as a clean, well-structured note.
-
-Return ONLY a JSON object, no prose, no code fences:
-{"path":"folder/kebab-slug.md","frontmatter":{"title":"...","type":"...","tags":["..."],"status":"...","created":"YYYY-MM-DD"},"body":"markdown body","reasoning":"one short sentence on why this path"}
-
-Rules:
-- Follow the SCHEMA conventions. Prefer an EXISTING folder when it fits; only invent a new folder if clearly needed.
-- kebab-case slug. Dailies -> daily/YYYY-MM-DD.md. Decisions -> decisions/<topic>-YYYY-MM-DD.md. People -> people/<first>[-<org>].md. Clients -> clients/<slug>/<slug>.md.
-- Keep the user's facts; just structure them. Body must NOT repeat the title as a leading H1 and must NOT include frontmatter.`;
-
-function extractJson(text: string): { path: string; frontmatter?: Record<string, unknown>; body?: string; reasoning?: string } {
- const start = text.indexOf("{");
- const end = text.lastIndexOf("}");
- if (start === -1 || end === -1) throw new Error("model returned no JSON");
- return JSON.parse(text.slice(start, end + 1));
-}
-
-/** Take a rough dump, let the model decide the path + frontmatter, and write the note. */
+/**
+ * `brain_capture` — hand over a rough dump and let the vault file it.
+ *
+ * This used to be a single blind model call: pick a path, write the note, overwrite whatever
+ * lived there. It now runs the shared agent loop, which must search before it files, must read
+ * a note before overwriting it, may archive but never delete, and reports a manifest of what it
+ * actually touched — because the caller delegated the decision and deserves to see the outcome.
+ */
export async function captureNote(rough: string): Promise<CaptureResult> {
- const apiKey = anthropicApiKey();
if (!harnessEnabled())
- throw new Error("brain_capture is off — enable the auto-filing harness in Settings (needs an Anthropic API key)");
- if (!apiKey) throw new Error("Anthropic API key not set (Settings → AI capture)");
+ throw new Error("brain_capture is off — set the Curator to Full in Settings (needs an Anthropic API key).");
+ if (!anthropicApiKey()) throw new Error("Anthropic API key not set (Settings → Curator).");
+ if (!rough.trim()) throw new Error("Nothing to capture.");
+
const today = new Date().toISOString().slice(0, 10);
- const schema = readVaultFile("SCHEMA.md") ?? "(no SCHEMA.md)";
- const user = `Today is ${today}.\nExisting folders: ${folderList().join(", ") || "(none yet)"}\n\nSCHEMA:\n${schema}\n\nRough note to file:\n"""\n${rough}\n"""`;
+ const prompt = `Today is ${today}.\n\n${captureContext()}\n\nRough note to file:\n"""\n${rough}\n"""`;
+
+ let summary = "";
+ let manifest: Manifest = { created: [], updated: [], appended: [], moved: [] };
+ let failure = "";
+
+ for await (const ev of agentStream({
+ profile: "capture",
+ messages: [{ role: "user", content: prompt }],
+ canWrite: true,
+ model: captureModel(),
+ maxTurns: 8,
+ // Credit the agent that handed us the dump, not the loop that filed it.
+ actor: `${currentActor()} via capture`,
+ })) {
+ if (ev.type === "text") summary += ev.text;
+ else if (ev.type === "manifest") manifest = ev.manifest;
+ else if (ev.type === "error") failure = ev.message;
+ }
- const res = await fetch("https://api.anthropic.com/v1/messages", {
- method: "POST",
- headers: {
- "content-type": "application/json",
- "x-api-key": apiKey,
- "anthropic-version": "2023-06-01",
- },
- body: JSON.stringify({
- model: captureModel(),
- max_tokens: 2000,
- system: SYSTEM,
- messages: [{ role: "user", content: user }],
- }),
- });
- if (!res.ok) throw new Error(`anthropic ${res.status}: ${await res.text()}`);
- const data = await res.json();
- const text: string = data?.content?.[0]?.text ?? "";
- const parsed = extractJson(text);
- if (!parsed.path) throw new Error("model did not return a path");
+ if (failure) throw new Error(failure);
- // brain_capture files NEW notes. It must never silently overwrite an existing one: the model
- // picks the path, and a bad guess would replace a real note with a rough dump. To update an
- // existing note, an agent reads it and uses brain_edit / brain_append deliberately.
- if (noteExists(parsed.path)) {
- throw new Error(
- `capture chose ${parsed.path}, but a note already exists there. Refusing to overwrite it. ` +
- `Read that note and use brain_edit or brain_append if you meant to update it, or capture under a different path.`,
- );
+ const touched = manifest.created.length + manifest.updated.length + manifest.appended.length + manifest.moved.length;
+ if (touched === 0) {
+ throw new Error(`capture wrote nothing. The model said: ${summary.trim() || "(nothing)"}`);
}
-
- const savedPath = await writeNote(parsed.path, parsed.body ?? "", parsed.frontmatter ?? {});
- return {
- path: savedPath,
- title: (parsed.frontmatter?.title as string) ?? savedPath,
- reasoning: parsed.reasoning,
- };
+ return { ...manifest, summary: summary.trim() };
}
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index d66f276..ccabb00 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -19,7 +19,6 @@ import {
writeNote,
writeNoteRaw,
} from "@/lib/vault/write";
-import { captureNote } from "@/lib/harness";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Args = Record<string, any>;
@@ -280,9 +279,13 @@ export const TOOLS: Tool[] = [
name: "brain_capture",
write: true,
description:
- "Capture a ROUGH note / brain-dump and let the vault file it automatically: it reads SCHEMA.md + the current folders, picks the right folder + filename, writes clean frontmatter, and structures the body. Use when you have unstructured input and don't want to decide the path yourself.",
+ "Hand over a ROUGH note / brain-dump and let the vault file it. An agent loop reads SCHEMA.md, searches for what already exists, then deliberately creates a new note, appends to a matching one, or archives what this supersedes — and returns a manifest of every path it touched. It reads a note before overwriting it, and never deletes. Use when you have unstructured input and don't want to choose the path yourself; use brain_write when you do.",
inputSchema: { type: "object", properties: { text: s("the rough note / brain dump to file") }, required: ["text"] },
- handler: async ({ text }) => await captureNote(String(text ?? "")),
+ // Imported lazily: harness -> agent -> tools would otherwise be a module cycle.
+ handler: async ({ text }) => {
+ const { captureNote } = await import("@/lib/harness");
+ return await captureNote(String(text ?? ""));
+ },
},
{
name: "brain_delete",
diff --git a/lib/settings.ts b/lib/settings.ts
index d5dbb9d..f77ad69 100644
--- a/lib/settings.ts
+++ b/lib/settings.ts
@@ -108,9 +108,8 @@ export function anthropicApiKey(): string {
*
* off — Engram never calls a model. A deterministic MCP server + dashboard.
* chat — a grounded, read-only conversation with the vault, in the dashboard.
- * full — `brain_capture` is exposed over MCP, so an agent can hand Engram a rough dump and
- * let it choose the path and frontmatter. (Chat is read-only in every mode today;
- * write tools arrive with the unified agent loop.)
+ * full — chat may edit notes, and `brain_capture` is exposed over MCP so an agent can hand
+ * Engram a rough dump and let it choose the path. Neither surface can delete.
*
* Note this does NOT govern whether agents can mutate the vault: MCP write tools are
* always available to a token with `write` scope (see lib/tokens.ts). The Curator only
@@ -135,7 +134,7 @@ export function curatorEnabled(): boolean {
return curatorMode() !== "off";
}
-/** The Curator may write on an agent's behalf: brain_capture is exposed over MCP. */
+/** The Curator may write: chat can edit notes, and brain_capture is exposed over MCP. */
export function harnessEnabled(): boolean {
return curatorMode() === "full";
}