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.
TypeScript agent-memoryai-agentsanthropicclaude-codecursorgitknowledge-baseknowledge-graphllmmarkdownmcpmcp-servermodel-context-protocolnote-takingobsidianpkmragsecond-brainself-hostedzettelkasten
P6 harness: brain_capture — rough dump auto-filed into the right note
Ronalds Palacise1565a637f39
diff --git a/app/api/capture/route.ts b/app/api/capture/route.tsnew file mode 100644index 0000000..d48edbd--- /dev/null+++ b/app/api/capture/route.ts@@ -0,0 +1,13 @@+import { captureNote } from "@/lib/harness";++export const dynamic = "force-dynamic";++export async function POST(req: Request) {+ const { text } = await req.json().catch(() => ({}));+ if (!text || typeof text !== "string") return Response.json({ error: "text required" }, { status: 400 });+ try {+ return Response.json(await captureNote(text));+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: 500 });+ }+}diff --git a/components/sidebar.tsx b/components/sidebar.tsxindex d2e2390..2d408b8 100644--- a/components/sidebar.tsx+++ b/components/sidebar.tsx@@ -4,7 +4,7 @@ import useSWR, { useSWRConfig } from "swr";import Link from "next/link";import { usePathname, useRouter } from "next/navigation";import { useState } from "react";-import { Search, Network, FilePlus } from "lucide-react";+import { Search, Network, FilePlus, Zap } from "lucide-react";import { fetcher, type TreeNode } from "@/lib/client";import { Tree } from "./tree";import { ThemeToggle } from "./theme-toggle";@@ -18,8 +18,18 @@ export function Sidebar() {const router = useRouter();const [creating, setCreating] = useState(false);const [name, setName] = useState("");+ const [capturing, setCapturing] = useState(false);+ const [dump, setDump] = useState("");+ const [busy, setBusy] = useState(false);+ const [err, setErr] = useState("");const activePath = pathname.startsWith("/n/") ? decodeURIComponent(pathname.slice(3)) : undefined;+ function refreshTo(path?: string) {+ mutate("/api/tree");+ mutate("/api/notes");+ if (path) router.push(`/n/${path}`);+ }+async function create() {const p = name.trim();if (!p) {@@ -35,19 +45,44 @@ export function Sidebar() {const d = await res.json().catch(() => ({}));setCreating(false);setName("");- if (d.path) {- mutate("/api/tree");- mutate("/api/notes");- router.push(`/n/${d.path}`);+ if (d.path) refreshTo(d.path);+ }++ async function capture() {+ const t = dump.trim();+ if (!t) return;+ setBusy(true);+ setErr("");+ try {+ const res = await fetch("/api/capture", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ text: t }),+ });+ const d = await res.json();+ if (res.ok && d.path) {+ setCapturing(false);+ setDump("");+ refreshTo(d.path);+ } else {+ setErr(d.error || "capture failed");+ }+ } catch {+ setErr("capture failed");+ } finally {+ setBusy(false);}}+ const iconBtn = "inline-flex size-8 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:text-foreground";+return (<aside className="flex h-dvh w-64 shrink-0 flex-col border-r border-border bg-sidebar"><div className="flex h-12 shrink-0 items-center gap-2 px-3"><div className="size-2 rounded-full bg-primary" /><span className="text-sm font-medium tracking-tight">{APP_NAME}</span></div>+<div className="flex gap-1 px-2 pb-2"><buttononClick={() => (window as unknown as { __openPalette?: () => void }).__openPalette?.()}@@ -56,21 +91,17 @@ export function Sidebar() {<Search size={13} /> Search<kbd className="ml-auto font-mono text-[10px] opacity-60">⌘K</kbd></button>- <button- onClick={() => setCreating((c) => !c)}- title="New note"- className="inline-flex size-8 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:text-foreground"- >+ <button onClick={() => { setCapturing((c) => !c); setCreating(false); }} title="Quick capture" className={iconBtn}>+ <Zap size={14} />+ </button>+ <button onClick={() => { setCreating((c) => !c); setCapturing(false); }} title="New note" className={iconBtn}><FilePlus size={14} /></button>- <Link- href="/graph"- title="Graph"- className="inline-flex size-8 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:text-foreground"- >+ <Link href="/graph" title="Graph" className={iconBtn}><Network size={14} /></Link></div>+{creating && (<div className="px-2 pb-2"><input@@ -79,16 +110,42 @@ export function Sidebar() {onChange={(e) => setName(e.target.value)}onKeyDown={(e) => {if (e.key === "Enter") create();- if (e.key === "Escape") {- setCreating(false);- setName("");- }+ if (e.key === "Escape") { setCreating(false); setName(""); }}}placeholder="folder/name.md"className="w-full rounded-md border border-border bg-background px-2 py-1.5 text-xs outline-none placeholder:text-muted-foreground"/></div>)}++ {capturing && (+ <div className="px-2 pb-2">+ <textarea+ autoFocus+ value={dump}+ onChange={(e) => setDump(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) capture();+ if (e.key === "Escape") { setCapturing(false); setDump(""); setErr(""); }+ }}+ placeholder="Dump a rough note — the brain files it into the right place…"+ rows={4}+ className="scrollbar-none w-full resize-none rounded-md border border-border bg-background px-2 py-1.5 text-xs outline-none placeholder:text-muted-foreground"+ />+ <div className="mt-1 flex items-center gap-2">+ <button+ onClick={capture}+ disabled={busy}+ className="rounded-md bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground disabled:opacity-50"+ >+ {busy ? "Filing…" : "File it"}+ </button>+ <span className="text-[10px] text-muted-foreground">⌘↵</span>+ {err && <span className="truncate text-[10px] text-destructive">{err}</span>}+ </div>+ </div>+ )}+<nav className="scrollbar-none flex-1 overflow-y-auto px-1">{data ? (<Tree tree={data.tree} activePath={activePath} />@@ -96,6 +153,7 @@ export function Sidebar() {<div className="px-3 py-2 text-xs text-muted-foreground">Loading…</div>)}</nav>+<div className="flex items-center justify-end border-t border-border px-2 py-1.5"><ThemeToggle /></div>diff --git a/lib/config.ts b/lib/config.tsindex cb59e2f..3054335 100644--- a/lib/config.ts+++ b/lib/config.ts@@ -35,3 +35,7 @@ export const AUTH_DISABLED = process.env.AUTH_DISABLED === "true";/** When true, the git-sync loop commits + pushes vault changes to the remote. */export const GIT_SYNC_ENABLED = process.env.GIT_SYNC_ENABLED === "true";++/** Anthropic key for the brain_capture harness (rough dump -> filed note). Optional. */+export const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY ?? "";+export const CAPTURE_MODEL = process.env.CAPTURE_MODEL ?? "claude-haiku-4-5-20251001";diff --git a/lib/harness.ts b/lib/harness.tsnew file mode 100644index 0000000..eb9e44b--- /dev/null+++ b/lib/harness.ts@@ -0,0 +1,69 @@+import { ANTHROPIC_API_KEY, CAPTURE_MODEL } from "@/lib/config";+import { getTree, listNotes, readVaultFile } from "@/lib/vault/store";+import { writeNote } from "@/lib/vault/write";++export interface CaptureResult {+ path: string;+ title: string;+ reasoning?: string;+}++/** 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. */+export async function captureNote(rough: string): Promise<CaptureResult> {+ if (!ANTHROPIC_API_KEY) throw new Error("ANTHROPIC_API_KEY not set — brain_capture is disabled");+ 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 res = await fetch("https://api.anthropic.com/v1/messages", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-api-key": ANTHROPIC_API_KEY,+ "anthropic-version": "2023-06-01",+ },+ body: JSON.stringify({+ model: CAPTURE_MODEL,+ 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");++ const savedPath = await writeNote(parsed.path, parsed.body ?? "", parsed.frontmatter ?? {});+ return {+ path: savedPath,+ title: (parsed.frontmatter?.title as string) ?? savedPath,+ reasoning: parsed.reasoning,+ };+}diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex f70c0b6..1506fc3 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -15,6 +15,7 @@ import {writeNote,writeNoteRaw,} from "@/lib/vault/write";+import { captureNote } from "@/lib/harness";// eslint-disable-next-line @typescript-eslint/no-explicit-anytype Args = Record<string, any>;@@ -137,6 +138,13 @@ export const TOOLS: Tool[] = [inputSchema: { type: "object", properties: { path: s("folder path") }, required: ["path"] },handler: async ({ path }) => ({ ok: true, path: await createFolder(String(path)) }),},+ {+ name: "brain_capture",+ 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.",+ inputSchema: { type: "object", properties: { text: s("the rough note / brain dump to file") }, required: ["text"] },+ handler: async ({ text }) => await captureNote(String(text ?? "")),+ },{name: "brain_delete",description: "Delete a note from the working copy (recoverable via git history).",