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
feat(curator): three states, one control; refuse silent truncation
Ronalds Palacisdcc1dfb883e4
diff --git a/app/(app)/connect/page.tsx b/app/(app)/connect/page.tsxindex 91f579f..d212b8b 100644--- a/app/(app)/connect/page.tsx+++ b/app/(app)/connect/page.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";import useSWR, { useSWRConfig } from "swr";import { Check, Copy, Trash2 } from "lucide-react";import { fetcher } from "@/lib/client";+import { cn } from "@/lib/utils";function Copyable({ text }: { text: string }) {const [copied, setCopied] = useState(false);@@ -27,10 +28,14 @@ function Copyable({ text }: { text: string }) {);}+/** A read-only token cannot mutate the vault — the write tools are not even listed to it. */+type TokenScope = "read" | "write";+interface TokenMeta {id: string;name: string;created: string;+ scope: TokenScope;}export default function ConnectPage() {@@ -43,6 +48,7 @@ export default function ConnectPage() {const [newName, setNewName] = useState("");const [creating, setCreating] = useState(false);const [justCreated, setJustCreated] = useState<{ name: string; token: string } | null>(null);+ const [scope, setScope] = useState<TokenScope>("write");const mcp = origin ? `${origin}/api/mcp` : "…";const needsToken = feat?.mcpAuthRequired !== false;@@ -58,7 +64,7 @@ export default function ConnectPage() {const res = await fetch("/api/tokens", {method: "POST",headers: { "content-type": "application/json" },- body: JSON.stringify({ name: newName.trim() || "token" }),+ body: JSON.stringify({ name: newName.trim() || "token", scope }),});const d = await res.json();if (d.token) setJustCreated({ name: d.name, token: d.token });@@ -105,6 +111,26 @@ export default function ConnectPage() {placeholder="Token name"className="w-56 rounded-md border border-border bg-background px-2.5 py-1.5 text-sm outline-none placeholder:text-muted-foreground"/>+ <div className="inline-flex shrink-0 rounded-md border border-border p-0.5" role="group" aria-label="Token scope">+ {(["read", "write"] as const).map((sc) => (+ <button+ key={sc}+ type="button"+ onClick={() => setScope(sc)}+ title={+ sc === "read"+ ? "The agent can search and read your notes, but cannot change them."+ : "The agent can create, edit, move and delete notes."+ }+ className={cn(+ "rounded px-3 py-1.5 text-xs font-medium capitalize transition-colors",+ scope === sc ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {sc}+ </button>+ ))}+ </div><buttononClick={create}disabled={creating}@@ -129,6 +155,7 @@ export default function ConnectPage() {<thead><tr className="border-b border-border text-left text-xs text-muted-foreground"><th className="px-3 py-2 font-medium">Name</th>+ <th className="px-3 py-2 font-medium">Scope</th><th className="px-3 py-2 font-medium">Created</th><th className="px-3 py-2 text-right font-medium">Revoke</th></tr>@@ -137,6 +164,11 @@ export default function ConnectPage() {{tokens.map((t) => (<tr key={t.id} className="border-b border-border last:border-0"><td className="px-3 py-2">{t.name}</td>+ <td className="px-3 py-2">+ <span className={cn("text-xs", t.scope === "read" ? "text-muted-foreground" : "text-foreground")}>+ {t.scope === "read" ? "read-only" : "read & write"}+ </span>+ </td><td className="px-3 py-2 text-muted-foreground">{new Date(t.created).toLocaleDateString()}</td><td className="px-3 py-2 text-right"><buttondiff --git a/app/(app)/page.tsx b/app/(app)/page.tsxindex c5e0840..1fe3437 100644--- a/app/(app)/page.tsx+++ b/app/(app)/page.tsx@@ -22,7 +22,7 @@ interface Repo {}interface Settings {gitSyncEnabled: boolean;- harnessEnabledFlag: boolean;+ curatorModeFlag: "off" | "chat" | "full";anthropicApiKeySet: boolean;}interface Stats {@@ -95,7 +95,7 @@ export default function Home() {const router = useRouter();const { mutate } = useSWRConfig();const { data: repos } = useSWR<{ repos: Repo[]; active: Repo | null }>("/api/repos", fetcher);- const { data: feat } = useSWR<{ harness?: boolean; mcpAuthRequired?: boolean; appName?: string }>("/api/features", fetcher);+ const { data: feat } = useSWR<{ curator?: "off" | "chat" | "full"; harness?: boolean; mcpAuthRequired?: boolean; appName?: string }>("/api/features", fetcher);const { data: tok } = useSWR<{ tokens: { id: string }[] }>("/api/tokens", fetcher);const { data: settings } = useSWR<Settings>("/api/settings", fetcher);const { data: activity } = useSWR<{ activity: ActivityEntry[] }>("/api/activity?limit=8", fetcher, { refreshInterval: 15000 });@@ -107,11 +107,11 @@ export default function Home() {// Toggle state mirrors saved settings; hydrate once they arrive.const [gitSyncOn, setGitSyncOn] = useState(false);- const [curatorOn, setCuratorOn] = useState(false);+ const [curatorMode, setCuratorMode] = useState<"off" | "chat" | "full">("off");useEffect(() => {if (!settings) return;setGitSyncOn(settings.gitSyncEnabled);- setCuratorOn(settings.harnessEnabledFlag);+ setCuratorMode(settings.curatorModeFlag);}, [settings]);// Inline search over the vault.@@ -166,16 +166,20 @@ export default function Home() {setGitSyncOn(v);patch({ gitSyncEnabled: v }, "/api/settings", "/api/sync");}+ // The quick toggle only ever reaches "chat" — granting the Curator write access is a+ // deliberate choice, made on the Settings page.function toggleCurator(v: boolean) {- setCuratorOn(v);- patch({ harnessEnabled: v }, "/api/settings", "/api/features");+ const next = v ? "chat" : "off";+ setCuratorMode(next);+ patch({ curatorMode: next }, "/api/settings", "/api/features");}const recent = activity?.activity ?? [];+ const curatorOn = curatorMode !== "off";const curatorNeedsKey = curatorOn && !settings?.anthropicApiKeySet;// ── Nothing set up yet (no vault, Curator off) → focused onboarding. ──- if (!active && !feat?.harness) {+ if (!active && (feat?.curator ?? "off") === "off") {return (<div className="scrollbar-none h-full overflow-y-auto"><div className="mx-auto flex min-h-full max-w-2xl flex-col px-8 py-12">@@ -213,7 +217,7 @@ export default function Home() {title="Curator"ok={false}state={curatorNeedsKey ? "needs API key" : "off · optional"}- desc="An optional chat agent that reads your notes to answer. Turn it on anytime."+ desc="An optional chat agent that reads your notes to answer. Turn it on anytime; it starts read-only."on={curatorOn}onToggle={toggleCurator}footer={@@ -253,10 +257,17 @@ export default function Home() {<Switch size="sm" checked={gitSyncOn} onCheckedChange={toggleGitSync} aria-label="Git sync" /><span>Git sync</span></div>- <div className="flex items-center gap-1.5" title="In-app chat agent grounded in your notes">- <Switch size="sm" checked={curatorOn} onCheckedChange={toggleCurator} aria-label="Curator" />- <span>Curator{curatorNeedsKey && <span className="text-amber-500"> · needs key</span>}</span>- </div>+ <Link+ href="/settings"+ className="inline-flex items-center gap-1.5 transition-colors hover:text-foreground"+ title="Whether Engram itself runs a model. Agents' write access is set per token, on Connect."+ >+ <span>+ Curator ·{" "}+ <span className={curatorOn ? "text-foreground" : undefined}>{feat?.curator ?? curatorMode}</span>+ {curatorNeedsKey && <span className="text-amber-500"> · needs key</span>}+ </span>+ </Link><Link href="/settings" className="inline-flex items-center gap-1 transition-colors hover:text-foreground"><SettingsIcon size={13} /> Settings</Link>diff --git a/app/(app)/settings/page.tsx b/app/(app)/settings/page.tsxindex 2e8b1b1..3386220 100644--- a/app/(app)/settings/page.tsx+++ b/app/(app)/settings/page.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";import useSWR, { useSWRConfig } from "swr";import { Check } from "lucide-react";import { fetcher } from "@/lib/client";+import { cn } from "@/lib/utils";import { CURATOR_MODELS, DEFAULT_CAPTURE_MODEL } from "@/lib/models";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -11,13 +12,21 @@ import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+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: "Chat can write, and agents can file rough dumps with brain_capture." },+];+interface PublicSettings {appName: string;gitSyncEnabled: boolean;gitAuthorName: string;gitAuthorEmail: string;- harnessEnabledFlag: boolean;- harnessEffective: boolean;+ curatorModeFlag: CuratorMode;+ curatorMode: CuratorMode;captureModel: string;anthropicApiKeySet: boolean;githubClientId: string;@@ -42,7 +51,7 @@ export default function SettingsPage() {const [gitSync, setGitSync] = useState(false);const [gitName, setGitName] = useState("");const [gitEmail, setGitEmail] = useState("");- const [harness, setHarness] = useState(false);+ const [curator, setCurator] = useState<CuratorMode>("off");const [model, setModel] = useState<string>(DEFAULT_CAPTURE_MODEL);const [apiKey, setApiKey] = useState("");const [ghId, setGhId] = useState("");@@ -58,7 +67,7 @@ export default function SettingsPage() {setGitSync(data.gitSyncEnabled);setGitName(data.gitAuthorName);setGitEmail(data.gitAuthorEmail);- setHarness(data.harnessEnabledFlag);+ setCurator(data.curatorModeFlag);setModel(data.captureModel);setGhId(data.githubClientId);}, [data]);@@ -72,7 +81,7 @@ export default function SettingsPage() {gitSyncEnabled: gitSync,gitAuthorName: gitName,gitAuthorEmail: gitEmail,- harnessEnabled: harness,+ curatorMode: curator,captureModel: model,githubClientId: ghId,};@@ -155,23 +164,38 @@ export default function SettingsPage() {{/* Curator */}<section className="mt-6 space-y-4 border-t border-border pt-6">- <div className="flex items-center justify-between">- <div>- <h2 className="text-sm font-medium">Curator</h2>- <p className="text-xs text-muted-foreground">- The in-app chat agent that reads your notes to answer, plus auto-filing of rough dumps- (brain_capture). Off by default — runs on your Anthropic key.- </p>- </div>- <Switch checked={harness} onCheckedChange={setHarness} />+ <div>+ <h2 className="text-sm font-medium">Curator</h2>+ <p className="mt-1 text-xs text-muted-foreground">+ Whether Engram itself runs a model. It does <em>not</em> control whether your agents can+ edit the vault — a token's scope does, on the Connect page.+ </p></div>- {harness && (++ <div className="inline-flex rounded-md border border-border p-0.5">+ {CURATOR_MODES.map((m) => (+ <button+ key={m.id}+ type="button"+ onClick={() => setCurator(m.id)}+ className={cn(+ "rounded px-4 py-1.5 text-xs font-medium transition-colors",+ curator === m.id ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {m.label}+ </button>+ ))}+ </div>+ <p className="text-[11px] text-muted-foreground">{CURATOR_MODES.find((m) => m.id === curator)?.blurb}</p>++ {curator !== "off" && (<div className="space-y-3"><Fieldhint={data.anthropicApiKeySet? "A key is set. Type a new value to replace it."- : envHint("anthropicApiKey") ?? "Required to enable the Curator."+ : envHint("anthropicApiKey") ?? "Required — your notes are sent to Anthropic on this key."}><Label htmlFor="apiKey">@@ -192,20 +216,22 @@ export default function SettingsPage() {)}</div></Field>- <Field hint="Model used to auto-file rough dumps (brain_capture). Separate from the model you pick in the chat.">- <Label>Capture model</Label>- <Select value={model} onValueChange={setModel}>- <SelectTrigger className="w-full">- <SelectValue placeholder="Select a model" />- </SelectTrigger>- <SelectContent>- {CURATOR_MODELS.map((m) => (- <SelectItem key={m.id} value={m.id}>{m.label}</SelectItem>- ))}- </SelectContent>- </Select>- </Field>- {harness && !data.anthropicApiKeySet && !apiKey.trim() && (+ {curator === "full" && (+ <Field hint="Model used to auto-file rough dumps (brain_capture). Separate from the model you pick in the chat.">+ <Label>Capture model</Label>+ <Select value={model} onValueChange={setModel}>+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select a model" />+ </SelectTrigger>+ <SelectContent>+ {CURATOR_MODELS.map((m) => (+ <SelectItem key={m.id} value={m.id}>{m.label}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ )}+ {!data.anthropicApiKeySet && !apiKey.trim() && (<p className="text-[11px] text-amber-500">The Curator stays off until an Anthropic key is saved.</p>)}</div>diff --git a/app/api/curator/chat/route.ts b/app/api/curator/chat/route.tsindex 7b94991..0cd2cba 100644--- a/app/api/curator/chat/route.ts+++ b/app/api/curator/chat/route.ts@@ -1,4 +1,5 @@import { curatorStream, type ChatMessage } from "@/lib/curator";+import { curatorEnabled } from "@/lib/settings";export const dynamic = "force-dynamic";export const maxDuration = 300;@@ -11,6 +12,10 @@ export async function POST(req: Request) {} catch {return new Response("invalid JSON", { status: 400 });}+ // The Curator is a real server-side policy, not a client-side switch: refuse when it's off.+ if (!curatorEnabled()) {+ return new Response("The Curator is off. Enable it in Settings (needs an Anthropic API key).", { status: 403 });+ }const messages = Array.isArray(body.messages) ? body.messages : [];const encoder = new TextEncoder();diff --git a/app/api/features/route.ts b/app/api/features/route.tsindex 6b47076..5128ce2 100644--- a/app/api/features/route.ts+++ b/app/api/features/route.ts@@ -1,5 +1,5 @@import { AUTH_DISABLED, AUTH_SECRET, MCP_TOKEN } from "@/lib/config";-import { appName, harnessEnabled } from "@/lib/settings";+import { appName, curatorMode, harnessEnabled } from "@/lib/settings";import { hasAnyToken } from "@/lib/tokens";export const dynamic = "force-dynamic";@@ -7,6 +7,9 @@ export const dynamic = "force-dynamic";export function GET() {return Response.json({appName: appName(),+ /** "off" | "chat" | "full" — whether Engram itself runs a model, and whether it may write. */+ curator: curatorMode(),+ /** Kept for the Connect page: brain_capture is exposed only in "full". */harness: harnessEnabled(),mcpAuthRequired: MCP_TOKEN !== "" || hasAnyToken(),dashboardAuthRequired: !AUTH_DISABLED && AUTH_SECRET !== "",diff --git a/app/api/notes/[...path]/route.ts b/app/api/notes/[...path]/route.tsindex 0f99f78..78dde7d 100644--- a/app/api/notes/[...path]/route.ts+++ b/app/api/notes/[...path]/route.ts@@ -31,8 +31,9 @@ export async function PUT(req: Request, { params }: { params: Promise<{ path: stif (typeof content !== "string") return Response.json({ error: "content (string) required" }, { status: 400 });// Non-strict: a human may autosave half-typed frontmatter. Save it, but tell them it is broken —// otherwise the note silently loses its status and tags. (Agents are refused; see lib/mcp/tools.ts.)+ // allowShrink: a human in the editor can see what they are deleting. Agents cannot.const actor = await actorFor(req);- const saved = await withActor(actor, () => writeNoteRaw(rel, content));+ const saved = await withActor(actor, () => writeNoteRaw(rel, content, { allowShrink: true }));const check = checkFrontmatter(content);return Response.json({ok: true,diff --git a/lib/harness.ts b/lib/harness.tsindex 4b10494..92f8b23 100644--- a/lib/harness.ts+++ b/lib/harness.ts@@ -1,6 +1,6 @@import { anthropicApiKey, captureModel, harnessEnabled } from "@/lib/settings";-import { getTree, listNotes, readVaultFile } from "@/lib/vault/store";-import { writeNote } from "@/lib/vault/write";+import { getNote, getTree, listNotes, readVaultFile } from "@/lib/vault/store";+import { normalizeNotePath, writeNote } from "@/lib/vault/write";export interface CaptureResult {path: string;@@ -8,6 +8,11 @@ export interface CaptureResult {reasoning?: 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>();@@ -63,6 +68,16 @@ export async function captureNote(rough: string): Promise<CaptureResult> {const parsed = extractJson(text);if (!parsed.path) throw new Error("model did not return a path");+ // 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 savedPath = await writeNote(parsed.path, parsed.body ?? "", parsed.frontmatter ?? {});return {path: savedPath,diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex ebb1a32..d66f276 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -51,8 +51,10 @@ async function writeFromArgs(a: Args): Promise<string> {const contentStr = typeof a.content === "string" ? a.content : "";const raw = contentStr.trim() !== "" ? contentStr : !hasFm && bodyStr.trim().startsWith("---") ? bodyStr : "";// strict: an agent that hand-writes unparseable YAML is refused, not silently accepted.- if (raw.trim() !== "") return writeNoteRaw(p, raw, { strict: true });- if (bodyStr.trim() !== "" || hasFm) return writeNote(p, bodyStr, fm);+ // allowShrink: only when the caller explicitly says it means to replace the note.+ const opts = { strict: true, allowShrink: a.overwrite === true };+ if (raw.trim() !== "") return writeNoteRaw(p, raw, opts);+ if (bodyStr.trim() !== "" || hasFm) return writeNote(p, bodyStr, fm, opts);throw new Error("Nothing to write. Pass `body` (markdown, + optional `frontmatter` object) or `content` (full raw markdown incl. frontmatter). Refusing to create an empty note.",);@@ -220,6 +222,7 @@ export const TOOLS: Tool[] = [body: s("markdown body (pair with `frontmatter`)"),frontmatter: { type: "object", description: "YAML frontmatter object: title, type, tags, status, related, ..." },content: s("full raw markdown incl. frontmatter — alternative to body+frontmatter"),+ overwrite: { type: "boolean", description: "confirm you mean to replace an existing note with much shorter content (default false)" },},required: ["path"],},@@ -237,6 +240,7 @@ export const TOOLS: Tool[] = [content: s("full raw markdown incl. frontmatter"),body: s("markdown body (alternative to content; pair with `frontmatter`)"),frontmatter: { type: "object", description: "YAML frontmatter object (with `body`)" },+ overwrite: { type: "boolean", description: "confirm you mean to replace an existing note with much shorter content (default false)" },},required: ["path"],},diff --git a/lib/settings.ts b/lib/settings.tsindex ef1e407..f9a8496 100644--- a/lib/settings.ts+++ b/lib/settings.ts@@ -38,7 +38,9 @@ interface StoredSettings {gitSyncEnabled?: boolean;gitAuthorName?: string;gitAuthorEmail?: string;+ /** Superseded by curatorMode; still read so existing deploys keep their behaviour. */harnessEnabled?: boolean;+ curatorMode?: CuratorMode;captureModel?: string;anthropicApiKeyEnc?: string;githubClientId?: string;@@ -101,10 +103,39 @@ export function anthropicApiKey(): string {return safeDecrypt(load().anthropicApiKeyEnc) || ANTHROPIC_API_KEY;}-/** Effective harness flag — enabled AND a key is available (matches the old env semantics). */+/**+ * What the Curator is allowed to be.+ *+ * off — Engram never calls a model. A deterministic MCP server + dashboard.+ * chat — a grounded, read-only conversation with the vault, in the dashboard.+ * full — chat can write, and `brain_capture` is exposed over MCP.+ *+ * 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+ * governs whether *Engram itself* runs a model.+ */+export type CuratorMode = "off" | "chat" | "full";++/** The operator's chosen mode, migrating the old boolean harness flag. */+export function curatorModeFlag(): CuratorMode {+ const s = load();+ if (s.curatorMode) return s.curatorMode;+ return (s.harnessEnabled ?? HARNESS_ENABLED_ENV) ? "full" : "off";+}++/** Effective mode — a model needs a key, so without one the Curator is off however it's set. */+export function curatorMode(): CuratorMode {+ return anthropicApiKey() === "" ? "off" : curatorModeFlag();+}++/** Chat is available (read-only or better). */+export function curatorEnabled(): boolean {+ return curatorMode() !== "off";+}++/** The Curator may write: chat can edit notes, and brain_capture is exposed over MCP. */export function harnessEnabled(): boolean {- const flag = load().harnessEnabled ?? HARNESS_ENABLED_ENV;- return flag && anthropicApiKey() !== "";+ return curatorMode() === "full";}export function githubClientId(): string {@@ -122,8 +153,8 @@ export interface PublicSettings {gitSyncEnabled: boolean;gitAuthorName: string;gitAuthorEmail: string;- harnessEnabledFlag: boolean; // the raw toggle, independent of key presence- harnessEffective: boolean; // enabled AND a key is present+ curatorModeFlag: CuratorMode; // the raw choice, independent of key presence+ curatorMode: CuratorMode; // effective: "off" unless a key is presentcaptureModel: string;anthropicApiKeySet: boolean;githubClientId: string;@@ -139,8 +170,8 @@ export function publicSettings(): PublicSettings {gitSyncEnabled: gitSyncEnabled(),gitAuthorName: gitAuthor().name,gitAuthorEmail: gitAuthor().email,- harnessEnabledFlag: s.harnessEnabled ?? HARNESS_ENABLED_ENV,- harnessEffective: harnessEnabled(),+ curatorModeFlag: curatorModeFlag(),+ curatorMode: curatorMode(),captureModel: captureModel(),anthropicApiKeySet: anthropicApiKey() !== "",githubClientId: githubClientId(),@@ -168,7 +199,7 @@ export interface SettingsPatch {gitSyncEnabled?: boolean;gitAuthorName?: string;gitAuthorEmail?: string;- harnessEnabled?: boolean;+ curatorMode?: CuratorMode;captureModel?: string;anthropicApiKey?: string;clearAnthropicApiKey?: boolean;@@ -194,7 +225,10 @@ export function updateSettings(patch: SettingsPatch): PublicSettings {setText(s, "githubClientId", patch.githubClientId);if (patch.gitSyncEnabled !== undefined) s.gitSyncEnabled = patch.gitSyncEnabled;- if (patch.harnessEnabled !== undefined) s.harnessEnabled = patch.harnessEnabled;+ if (patch.curatorMode !== undefined) {+ s.curatorMode = patch.curatorMode;+ delete s.harnessEnabled; // the old boolean is fully superseded once a mode is chosen+ }// Secrets: set only when a value is typed; clear only on explicit request.if (patch.clearAnthropicApiKey) delete s.anthropicApiKeyEnc;diff --git a/lib/vault/write.ts b/lib/vault/write.tsindex 138bdc6..3bccc3b 100644--- a/lib/vault/write.ts+++ b/lib/vault/write.ts@@ -38,6 +38,42 @@ export interface WriteOpts {* a half-typed document; they get a warning instead of losing their work.*/strict?: boolean;+ /**+ * Permit a write that destroys most of an existing note. Default false for agents.+ * A human in the editor is looking at what they're deleting; an agent usually is not.+ */+ allowShrink?: boolean;+}++/** An existing note this size or larger is worth protecting from an accidental truncation. */+const SHRINK_FLOOR_BYTES = 400;+/** Replacing a note with less than this fraction of its content looks like an accident. */+const SHRINK_RATIO = 0.3;++/**+ * Refuse to replace a substantial note with a stub.+ *+ * A real incident: an agent was told "replace {{BOOKING_LINK}} in this file", and wrote that+ * *instruction* into the file as its entire contents — destroying a 5.6KB snippet library.+ * `writeNote` overwrites blind, so nothing stopped it. Overwriting is legitimate (an agent+ * reads a note and writes it back), but collapsing 5.6KB to 170 bytes is a mistake worth+ * refusing until someone says they meant it.+ */+async function guardTruncation(abs: string, relPath: string, next: string, allowShrink: boolean): Promise<void> {+ if (allowShrink) return;+ let existing: string;+ try {+ existing = await fsp.readFile(abs, "utf8");+ } catch {+ return; // new note — nothing to destroy+ }+ if (existing.length < SHRINK_FLOOR_BYTES) return;+ if (next.length >= existing.length * SHRINK_RATIO) return;+ throw new Error(+ `Refusing to write ${relPath}: it would shrink from ${existing.length} to ${next.length} bytes, ` ++ `discarding most of the note. Read it first (brain_read) and write back the full content you intend to keep. ` ++ `To append, use brain_append. If you really mean to replace it, pass overwrite: true.`,+ );}/** Write a note from a raw markdown string (frontmatter included). Used by the editor. */@@ -48,6 +84,7 @@ export async function writeNoteRaw(relPath: string, content: string, opts: Writeif (!check.ok) throw new Error(frontmatterErrorMessage(p, check.error!));}const abs = safeAbs(p);+ await guardTruncation(abs, p, content, opts.allowShrink === true);await fsp.mkdir(path.dirname(abs), { recursive: true });await fsp.writeFile(abs, content, "utf8");after(`edit ${p}`, [p]);@@ -59,10 +96,15 @@ export async function writeNoteRaw(relPath: string, content: string, opts: Write* `matter.stringify` serialises the object, so the YAML always parses — this path cannot* produce the corruption that hand-written frontmatter can.*/-export async function writeNote(relPath: string, body: string, frontmatter?: Record<string, unknown>): Promise<string> {+export async function writeNote(+ relPath: string,+ body: string,+ frontmatter?: Record<string, unknown>,+ opts: WriteOpts = {},+): Promise<string> {const content =frontmatter && Object.keys(frontmatter).length > 0 ? matter.stringify(body ?? "", frontmatter) : (body ?? "");- return writeNoteRaw(relPath, content, { strict: true });+ return writeNoteRaw(relPath, content, { ...opts, strict: true });}export async function appendNote(relPath: string, text: string): Promise<string> {