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
Engram: rebrand from Cortex, dashboard Settings page, SEO README + logo
Ronalds Palacis68ba78aa7da6
diff --git a/.env.example b/.env.exampleindex 07609d5..888b5a1 100644--- a/.env.example+++ b/.env.example@@ -1,22 +1,28 @@-# ── Cortex ──────────────────────────────────────────────────────────────────+# ── Engram ──────────────────────────────────────────────────────────────────# Copy to .env.local for local dev; set the same vars on your host for deploy.+#+# Most runtime behavior below is ALSO editable in the dashboard → Settings (persisted+# under ENGRAM_DATA_DIR). A saved setting OVERRIDES the matching env var and takes effect+# without a redeploy. Vars tagged "(Settings)" are optional here — set them once in the UI+# instead. The Auth block bootstraps login itself, so it must stay in env.-NEXT_PUBLIC_APP_NAME="Cortex"+NEXT_PUBLIC_APP_NAME="Engram" # (Settings) default app name; the UI value wins at runtime# Vault = the markdown source of truth.# local dev (unset): ./sample-vault (bundled)# production: the mounted volume path# VAULT_DIR="/data"-# ── Vault sync ───────────────────────────────────────────────────────────────-# Vault repos are connected in the dashboard (Workspaces) via GitHub OAuth (below) —-# no GIT_REMOTE env needed. Set GIT_SYNC_ENABLED=true to auto commit+push the active repo.+# ── Vault sync ── (Settings) all three are editable in the dashboard ─────────+# Vault repos are connected in the dashboard (Workspaces). Set GIT_SYNC_ENABLED=true to+# auto commit+push the active repo — or just flip it in Settings → Git sync.GIT_SYNC_ENABLED="false"-GIT_AUTHOR_NAME="Cortex"+GIT_AUTHOR_NAME="Engram"GIT_AUTHOR_EMAIL="[email protected]"-# CORTEX_DATA_DIR="/data" # app state + vault clones (on Railway: the volume)+# ENGRAM_DATA_DIR="/data" # app state + vault clones (on Railway: the volume)-# ── Workspaces: GitHub OAuth (connect vault repos from the dashboard) ─────────+# ── Workspaces: GitHub OAuth ── (Settings) editable in Settings → GitHub ─────+# For the "Connect GitHub" repo flow. Optional — the URL+token path needs no OAuth app.GITHUB_CLIENT_ID=""GITHUB_CLIENT_SECRET=""@@ -33,15 +39,16 @@ GOOGLE_CLIENT_SECRET=""# in the dashboard Connect page. The MCP is OPEN when no token exists (local dev).MCP_TOKEN=""# Where per-teammate token hashes persist (kept out of the vault git). Defaults to-# <vault>/.cortex. On Railway put it on the volume, e.g. /data/.cortex.-# CORTEX_STATE_DIR="/data/.cortex"+# <vault>/.engram. On Railway put it on the volume, e.g. /data/.engram.+# ENGRAM_STATE_DIR="/data/.engram"# Local/OSS single-user mode: no Google auth, MCP open. NEVER true in production.AUTH_DISABLED="false"-# ── Harness (brain_capture) — OFF by default ─────────────────────────────────+# ── Harness (brain_capture) — OFF by default ── (Settings) → AI capture ──────# Optional server-side auto-filing of rough dumps. Costs extra tokens; a coding-# agent can do the same over the plain MCP tools for free. Enable both to turn on.+# agent can do the same over the plain MCP tools for free. Easiest to enable in+# the dashboard (Settings → AI capture) — toggle + paste the key there.HARNESS_ENABLED="false"ANTHROPIC_API_KEY=""CAPTURE_MODEL="claude-haiku-4-5-20251001"diff --git a/.gitignore b/.gitignoreindex b0f1ae2..c007f90 100644--- a/.gitignore+++ b/.gitignore@@ -12,9 +12,9 @@ next-env.d.ts.vercel.gstack/# local app state (token hashes, github token, repo clones) — never commit-.cortex/-**/.cortex/-.cortex-data/+.engram/+**/.engram/+.engram-data/sample-vault/.gitignore# local working notes (not part of the OSS repo)HANDOFF.mddiff --git a/DEPLOY.md b/DEPLOY.mdindex 40d4cc0..6d2f036 100644--- a/DEPLOY.md+++ b/DEPLOY.md@@ -1,6 +1,6 @@-# Deploying Cortex+# Deploying Engram-Cortex deploys as one container (this repo). Vault repos are **connected in the dashboard**+Engram deploys as one container (this repo). Vault repos are **connected in the dashboard**(Workspaces) — no repo lives in this repo, and no laptop keeps a vault copy. The activeworkspace is what the dashboard shows and what agents read/write.@@ -15,22 +15,24 @@ Already a git repo — create a remote and push `main`.## 3. Railway1. **New Project → Deploy from GitHub repo** → this repo (builds via root `Dockerfile`).2. **Add a Volume**, mount path `/data`.-3. **Variables:**+3. **Variables** — only these five are required on the host; the rest are optional and+ configurable later in the dashboard **Settings** page (they take effect without a redeploy):| Variable | Value ||---|---|-| `NEXT_PUBLIC_APP_NAME` | e.g. `Klyiro Brain` |-| `CORTEX_DATA_DIR` | `/data` (app state + vault clones live here) |-| `GIT_SYNC_ENABLED` | `true` (auto commit+push the active vault) |-| `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` | commit identity |+| `ENGRAM_DATA_DIR` | `/data` (app state + vault clones live here) || `AUTH_SECRET` | `openssl rand -base64 32`, or Railway "Generate" || `APP_URL` | `https://<your-app>.up.railway.app` || `ALLOWED_EMAILS` | comma-separated team emails (Google login) || `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | from step 2 |-| `ANTHROPIC_API_KEY` + `HARNESS_ENABLED=true` | optional, for `brain_capture` |-| `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` | optional — see step 5 (OAuth path) |-Deploy, then sign in with Google.+Deploy, then sign in with Google. These five bootstrap **auth + infra** — they gate login+itself (or say where state lives), so they can't live behind the login and must be env.++**Configure in the dashboard → Settings instead of env** (all optional; env value, if set, is+just the default): **App name** · **Git sync** (enable + commit author) · **AI capture**+(`brain_capture` toggle + Anthropic key + model) · **GitHub** repo-connect OAuth (client id/secret).+Secrets entered in Settings are stored encrypted at rest (keyed off `AUTH_SECRET`).## 4. Connect a vault repo (in the dashboard → Workspaces)Two ways — pick one:@@ -48,7 +50,8 @@ Each deployment uses **its own** GitHub OAuth app (secrets can't be shared, andhost-specific — so there's no shared central app for self-hosters):1. GitHub → Settings → Developer settings → **OAuth Apps → New OAuth App**.2. **Authorization callback URL:** `https://<your-app>.up.railway.app/api/github/callback`-3. Set `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` in Railway.+3. Paste the Client ID / Secret into the dashboard **Settings → GitHub** (or set+ `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` in Railway — the Settings value wins).Skip this entirely if you use the URL + token path in step 4.@@ -56,10 +59,10 @@ Skip this entirely if you use the URL + token path in step 4.Dashboard → **Connect** → copy the command. Agents always hit the same endpoint and only eversee the **active** vault:```bash-claude mcp add --transport http cortex https://<your-app>.up.railway.app/api/mcp \+claude mcp add --transport http engram https://<your-app>.up.railway.app/api/mcp \--header "Authorization: Bearer <token from the Connect page>"```## Notes- **No auth locally:** leave `AUTH_SECRET` empty (or `AUTH_DISABLED=true`) and the dashboard is open; the MCP is open until a token exists.-- Git tokens are stored **encrypted** at rest (keyed off `AUTH_SECRET`); token hashes and vault clones live under `CORTEX_DATA_DIR`, never in a vault repo.+- Git tokens are stored **encrypted** at rest (keyed off `AUTH_SECRET`); token hashes and vault clones live under `ENGRAM_DATA_DIR`, never in a vault repo.diff --git a/Dockerfile b/Dockerfileindex 22ac759..611dac0 100644--- a/Dockerfile+++ b/Dockerfile@@ -1,4 +1,4 @@-# Cortex — the app is the repo root. The vault is mounted separately at VAULT_DIR.+# Engram — the app is the repo root. The vault is mounted separately at VAULT_DIR.FROM oven/bun:1WORKDIR /appdiff --git a/README.md b/README.mdindex 545be22..317eb0a 100644--- a/README.md+++ b/README.md@@ -1,18 +1,67 @@-# Cortex+<p align="center">+ <img src="assets/logo.png" alt="Engram logo" width="120" height="120" />+</p>-Agent-first, markdown-native second brain. A **dashboard** for humans and an **MCP server**-for agents, over a git-backed folder of markdown notes. No database — the files are the-source of truth, an in-memory index powers search + graph, and git is the durable store.+<h1 align="center">Engram</h1>-Runs on **any** folder of markdown (`VAULT_DIR`). Ships with a `sample-vault/` so it works-out of the box.+<p align="center"><b>The second brain your AI agents read and write.</b></p>-[](https://railway.com/new)-[](https://render.com/deploy?repo=https://github.com/klyiro/cortex)+---++Engram is a self-hosted **MCP server + dashboard** that gives Claude Code, Cursor, Hermes, and any+[Model Context Protocol](https://modelcontextprotocol.io) agent **shared, long-term memory** — over a+plain, **git-backed folder of markdown**. No database:+your notes are the source of truth, an in-memory index powers full-text search and a wikilink+**knowledge graph**, and git is the durable store.++Think **Obsidian, but agent-native** — or **markdown RAG without a vector database**. Point it at any+vault of `.md` files (or the bundled `sample-vault/`) and every agent on your team can search, read,+and write the same knowledge. Humans edit it in a fast dashboard; agents edit it over one MCP endpoint.-> **Not Vercel.** Cortex needs a persistent volume + a long-running process (git-backed vault-> clones, a file watcher, an in-memory index), so serverless hosts won't run it. Use Railway,-> Render, Fly, or any Docker host with a volume.+[](https://railway.com/new)+[](https://render.com/deploy?repo=https://github.com/klyiro/engram)+[](./LICENSE)++> **Why it exists:** autonomous AI agents forget everything between sessions. Engram is the+> **persistent memory layer** — one knowledge base that humans and agents share, versioned in git,+> so your Claude Code / Hermes / Cursor agents remember decisions, context, and everything they learn.++---++## What it's for++- **Long-term memory for Claude Code** and other coding agents — stop re-explaining your project every session.+- **Shared memory for a fleet of AI agents** — one vault, many agents reading and writing concurrently.+- **A team knowledge base agents can actually write to** — meeting notes, decisions, client context, SOPs.+- **A self-hosted, Obsidian-compatible second brain** exposed over MCP — your notes, your server, your git repo.+- **Markdown RAG without the vector database** — full-text search + a link graph over human-readable files.++## Features++- **MCP server** — 13 `brain_*` tools over one bearer-authenticated HTTP endpoint (`POST /api/mcp`,+ streamable HTTP JSON-RPC). Connect any MCP client to a single URL.+- **Human dashboard** — file tree, note viewer with **Obsidian callouts, wikilinks, and backlinks**,+ Preview / Edit / Split editor with autosave, ⌘K command-palette search, and a **force-directed+ knowledge graph**.+- **Markdown-native** — plain `.md` + YAML frontmatter + `[[wikilinks]]`. Drop in an existing+ **Obsidian vault** and it just works.+- **Git-backed** — optional auto commit + push of every change. Full history, no lock-in, your data+ lives in **your** repo.+- **No database** — files are the source of truth; an in-memory MiniSearch index + a ported wikilink+ graph power search and backlinks. Nothing to provision.+- **Multi-workspace** — connect multiple vault repos and switch the active one from the UI.+- **Self-hosted** — one Docker container. Railway / Render / Fly / any host with a volume.+ **Not** serverless (it needs a persistent volume, a file watcher, and a long-running index).+- **Team auth** — Google SSO + email allowlist for the dashboard; per-agent bearer tokens for MCP+ (create/revoke in the UI). Secrets encrypted at rest.+- **Optional AI auto-filing** (`brain_capture`) — dump a rough note and it gets filed into the right+ place, with the right frontmatter, automatically.+- **Runtime Settings page** — flip git-sync, capture, and OAuth on/off without a redeploy.++## Works with++**Claude Code · Claude Desktop · Cursor · Cline · Windsurf · Hermes · any MCP client.**+One endpoint, bearer-token auth — if it speaks the Model Context Protocol, it can use Engram as memory.## Quick start@@ -24,39 +73,74 @@ bun dev # http://localhost:3000 — runs against ./sample-vaultPoint it at your own vault:```bash-VAULT_DIR=/path/to/your/vault bun dev+VAULT_DIR=/path/to/your/obsidian-or-markdown/vault bun dev```-## What it does+## MCP tools++Agents only ever see the active vault — no repo, workspace, or GitHub tools are exposed.++| | Tools |+|---|---|+| **Read** | `brain_search` · `brain_read` · `brain_list` · `brain_tree` · `brain_backlinks` · `brain_graph` · `brain_schema` |+| **Write** | `brain_write` · `brain_edit` · `brain_append` · `brain_move` · `brain_create_folder` · `brain_delete` |-- **Dashboard** — file tree, note viewer (Obsidian callouts + wikilinks + backlinks),- Preview / Edit / Split editor with autosave, ⌘K search, force-directed graph.-- **MCP** — `POST /api/mcp` (streamable HTTP, bearer-token). Tools: `brain_search`,- `brain_read`, `brain_list`, `brain_tree`, `brain_backlinks`, `brain_graph`, `brain_schema`- (read) · `brain_write`, `brain_edit`, `brain_append`, `brain_move`, `brain_create_folder`,- `brain_delete` (write). Any MCP client (Claude Code, Hermes, Cursor) connects to one URL.-- **Git-backed** — set `GIT_SYNC_ENABLED=true` and the app commits + pushes vault changes.+Connect an agent (the dashboard → **Connect** page shows the exact command + token):++```bash+claude mcp add --transport http engram https://<host>/api/mcp \+ --header "Authorization: Bearer <token>"+```## Deploy-Railway / Render / Fly / any Docker host (see the buttons above — **not** serverless). Mount a-volume at `/data`, set `CORTEX_DATA_DIR=/data`, then connect your vault repo(s) **in the-dashboard** (Workspaces) — by URL + token, or GitHub OAuth. Dashboard login is Google.+Runs anywhere you can run a Docker container with a persistent volume — Railway, Render, Fly, or your+own box. **Serverless (Vercel) won't work**: Engram holds a volume, a file watcher, and an in-memory+index that a serverless function can't keep alive.++1. Deploy this repo (root `Dockerfile`), mount a volume at `/data`, set `ENGRAM_DATA_DIR=/data`.+2. Connect your vault repo(s) **in the dashboard** (Workspaces) — by URL + token, or GitHub OAuth.+3. Sign in with Google, create MCP tokens on the **Connect** page, point your agents at the URL.-- **Railway:** New Project → *Deploy from GitHub repo* → add a Volume at `/data`. For a true- one-click, publish a Railway Template from your deploy and swap its URL into the button.+Most runtime config (git-sync, AI capture, GitHub OAuth, app name) is editable in the **Settings**+page — only auth/infra bootstrap vars live on the host. Full setup: **[DEPLOY.md](./DEPLOY.md)**.++- **Railway:** New Project → *Deploy from GitHub repo* → add a Volume at `/data`.- **Render:** one-click via the bundled `render.yaml` (Docker + a `/data` disk).-Full env + Google/GitHub OAuth setup: **[DEPLOY.md](./DEPLOY.md)**.+## FAQ-Connect an agent (dashboard → **Connect** shows the exact command):+**How do I give Claude Code long-term memory?**+Deploy Engram, connect a markdown vault, and `claude mcp add` the endpoint. The `brain_*` tools let+Claude Code search, read, and write persistent notes across sessions.-```bash-claude mcp add --transport http cortex https://<host>/api/mcp \- --header "Authorization: Bearer <token>"-```+**Can multiple AI agents share one knowledge base?**+Yes. Every agent points at the same MCP URL and reads/writes the same active vault — that's the point.+Give each agent its own bearer token.++**Does it work with my Obsidian vault?**+Yes. It reads plain markdown with frontmatter and `[[wikilinks]]`, and renders Obsidian-style callouts+and backlinks. No import step.++**Do I need a vector database?**+No. Engram uses full-text search (MiniSearch) plus a wikilink graph over human-readable markdown —+no embeddings service, no vector store to run.++**Is my data locked in?**+No. It's just `.md` files in a git repo you own. Turn Engram off and you still have every note and its+full history.++**Where does it run / is it self-hosted?**+You host it. One Docker container on Railway / Render / Fly / any VM with a volume. Your keys, your data.## Stack-Next 16 (App Router) · React 19 · TypeScript · Tailwind v4 · shadcn/base-ui · bun ·-MiniSearch · d3-force · MCP SDK. MIT licensed.+Next.js 16 (App Router) · React 19 · TypeScript · Tailwind v4 · shadcn/base-ui · bun · MiniSearch ·+d3-force · MCP SDK. **MIT licensed.**++---++<sub>**Keywords:** MCP server · Model Context Protocol · second brain for AI agents · agent memory ·+long-term memory for Claude Code · shared memory for AI agents · self-hosted knowledge base ·+Obsidian-compatible · markdown · knowledge graph · wikilinks · PKM · Zettelkasten · git-backed notes ·+Hermes agent memory · Cursor memory · RAG without a vector database.</sub>diff --git a/app/(app)/connect/page.tsx b/app/(app)/connect/page.tsxindex 2cf749f..91f579f 100644--- a/app/(app)/connect/page.tsx+++ b/app/(app)/connect/page.tsx@@ -48,8 +48,8 @@ export default function ConnectPage() {const needsToken = feat?.mcpAuthRequired !== false;const tokenForCmd = justCreated?.token ?? "<MCP_TOKEN>";const tokenLine = needsToken || justCreated ? ` \\\n --header "Authorization: Bearer ${tokenForCmd}"` : "";- const claudeCmd = `claude mcp add --transport http cortex ${mcp}${tokenLine}`;- const hermes = `mcp_servers:\n cortex:\n url: ${mcp}\n headers:\n Authorization: "Bearer ${tokenForCmd}"`;+ const claudeCmd = `claude mcp add --transport http engram ${mcp}${tokenLine}`;+ const hermes = `mcp_servers:\n engram:\n url: ${mcp}\n headers:\n Authorization: "Bearer ${tokenForCmd}"`;async function create() {if (creating) return;diff --git a/app/(app)/settings/page.tsx b/app/(app)/settings/page.tsxnew file mode 100644index 0000000..5b49866--- /dev/null+++ b/app/(app)/settings/page.tsx@@ -0,0 +1,282 @@+"use client";++import { useEffect, useState } from "react";+import useSWR, { useSWRConfig } from "swr";+import { Check } from "lucide-react";+import { fetcher } from "@/lib/client";++interface PublicSettings {+ appName: string;+ gitSyncEnabled: boolean;+ gitAuthorName: string;+ gitAuthorEmail: string;+ harnessEnabledFlag: boolean;+ harnessEffective: boolean;+ captureModel: string;+ anthropicApiKeySet: boolean;+ githubClientId: string;+ githubClientSecretSet: boolean;+ envManaged: Record<string, boolean>;+}++const input =+ "w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-sm outline-none placeholder:text-muted-foreground focus:border-ring";+const label = "text-xs font-medium text-muted-foreground";++function Toggle({ on, onChange }: { on: boolean; onChange: (v: boolean) => void }) {+ return (+ <button+ type="button"+ role="switch"+ aria-checked={on}+ onClick={() => onChange(!on)}+ className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${on ? "bg-primary" : "bg-muted"}`}+ >+ <span className={`inline-block size-3.5 rounded-full bg-background transition-transform ${on ? "translate-x-4" : "translate-x-1"}`} />+ </button>+ );+}++function Field({ children, hint }: { children: React.ReactNode; hint?: string }) {+ return (+ <div className="space-y-1">+ {children}+ {hint && <p className="text-[11px] text-muted-foreground">{hint}</p>}+ </div>+ );+}++export default function SettingsPage() {+ const { data } = useSWR<PublicSettings>("/api/settings", fetcher);+ const { mutate } = useSWRConfig();++ const [appNameV, setAppName] = useState("");+ const [gitSync, setGitSync] = useState(false);+ const [gitName, setGitName] = useState("");+ const [gitEmail, setGitEmail] = useState("");+ const [harness, setHarness] = useState(false);+ const [model, setModel] = useState("");+ const [apiKey, setApiKey] = useState("");+ const [ghId, setGhId] = useState("");+ const [ghSecret, setGhSecret] = useState("");++ const [saving, setSaving] = useState(false);+ const [saved, setSaved] = useState(false);++ // Hydrate the form once settings arrive (secrets stay blank — write-only).+ useEffect(() => {+ if (!data) return;+ setAppName(data.appName);+ setGitSync(data.gitSyncEnabled);+ setGitName(data.gitAuthorName);+ setGitEmail(data.gitAuthorEmail);+ setHarness(data.harnessEnabledFlag);+ setModel(data.captureModel);+ setGhId(data.githubClientId);+ }, [data]);++ async function save() {+ if (saving) return;+ setSaving(true);+ setSaved(false);+ const patch: Record<string, unknown> = {+ appName: appNameV,+ gitSyncEnabled: gitSync,+ gitAuthorName: gitName,+ gitAuthorEmail: gitEmail,+ harnessEnabled: harness,+ captureModel: model,+ githubClientId: ghId,+ };+ if (apiKey.trim()) patch.anthropicApiKey = apiKey.trim();+ if (ghSecret.trim()) patch.githubClientSecret = ghSecret.trim();+ try {+ await fetch("/api/settings", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(patch),+ });+ setApiKey("");+ setGhSecret("");+ mutate("/api/settings");+ mutate("/api/features");+ mutate("/api/github/status");+ setSaved(true);+ setTimeout(() => setSaved(false), 2000);+ } finally {+ setSaving(false);+ }+ }++ async function clearSecret(field: "clearAnthropicApiKey" | "clearGithubClientSecret") {+ await fetch("/api/settings", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ [field]: true }),+ });+ mutate("/api/settings");+ mutate("/api/features");+ }++ if (!data) {+ return <div className="px-8 py-10 text-sm text-muted-foreground">Loading…</div>;+ }++ const envHint = (k: string) => (data.envManaged[k] ? "Currently inherited from an env var — saving here overrides it." : undefined);++ return (+ <div className="scrollbar-none h-full overflow-y-auto">+ <div className="mx-auto max-w-3xl px-8 py-10">+ <h1 className="text-2xl font-semibold tracking-tight">Settings</h1>+ <p className="mt-2 max-w-xl text-sm text-muted-foreground">+ Configure runtime behavior here instead of on the host — saved values override the matching+ env var and take effect without a redeploy. Secrets are stored encrypted at rest.+ </p>++ {/* General */}+ <section className="mt-8 space-y-4 border-t border-border pt-6">+ <h2 className="text-sm font-medium">General</h2>+ <Field hint={envHint("appName") ?? "Shown in the sidebar and browser tab."}>+ <span className={label}>App name</span>+ <input value={appNameV} onChange={(e) => setAppName(e.target.value)} placeholder="Engram" className={input} />+ </Field>+ </section>++ {/* Git sync */}+ <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">Git sync</h2>+ <p className="text-xs text-muted-foreground">Auto commit + push the active vault to its remote.</p>+ </div>+ <Toggle on={gitSync} onChange={setGitSync} />+ </div>+ {gitSync && (+ <div className="grid grid-cols-2 gap-3">+ <Field>+ <span className={label}>Commit author name</span>+ <input value={gitName} onChange={(e) => setGitName(e.target.value)} placeholder="Engram" className={input} />+ </Field>+ <Field>+ <span className={label}>Commit author email</span>+ <input value={gitEmail} onChange={(e) => setGitEmail(e.target.value)} placeholder="engram@localhost" className={input} />+ </Field>+ </div>+ )}+ </section>++ {/* AI capture / harness */}+ <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">AI capture (brain_capture)</h2>+ <p className="text-xs text-muted-foreground">+ Server-side auto-filing of rough dumps. Off by default — costs Anthropic tokens.+ </p>+ </div>+ <Toggle on={harness} onChange={setHarness} />+ </div>+ {harness && (+ <div className="space-y-3">+ <Field+ hint={+ data.anthropicApiKeySet+ ? "A key is set. Type a new value to replace it."+ : envHint("anthropicApiKey") ?? "Required to enable capture."+ }+ >+ <span className={label}>+ Anthropic API key {data.anthropicApiKeySet && <span className="text-primary">• set</span>}+ </span>+ <div className="flex gap-2">+ <input+ type="password"+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ placeholder={data.anthropicApiKeySet ? "••••••••••••••••" : "sk-ant-…"}+ className={input}+ />+ {data.anthropicApiKeySet && (+ <button+ onClick={() => clearSecret("clearAnthropicApiKey")}+ className="shrink-0 rounded-md border border-border px-2.5 py-1.5 text-xs text-muted-foreground hover:text-destructive"+ >+ Remove+ </button>+ )}+ </div>+ </Field>+ <Field>+ <span className={label}>Capture model</span>+ <input value={model} onChange={(e) => setModel(e.target.value)} placeholder="claude-haiku-4-5-20251001" className={input} />+ </Field>+ {harness && !data.anthropicApiKeySet && !apiKey.trim() && (+ <p className="text-[11px] text-amber-500">Capture stays off until an Anthropic key is saved.</p>+ )}+ </div>+ )}+ </section>++ {/* GitHub OAuth (repo connect) */}+ <section className="mt-6 space-y-4 border-t border-border pt-6">+ <div>+ <h2 className="text-sm font-medium">GitHub (repo connect)</h2>+ <p className="text-xs text-muted-foreground">+ OAuth app for the “Connect GitHub” flow in Workspaces. Optional — you can also add a repo by+ URL + token. Callback: <code className="rounded bg-muted px-1">{"<app-url>"}/api/github/callback</code>+ </p>+ </div>+ <div className="grid grid-cols-2 gap-3">+ <Field hint={envHint("githubClientId")}>+ <span className={label}>Client ID</span>+ <input value={ghId} onChange={(e) => setGhId(e.target.value)} placeholder="Iv1.…" className={input} />+ </Field>+ <Field hint={data.githubClientSecretSet ? "A secret is set. Type a new value to replace it." : undefined}>+ <span className={label}>+ Client secret {data.githubClientSecretSet && <span className="text-primary">• set</span>}+ </span>+ <div className="flex gap-2">+ <input+ type="password"+ value={ghSecret}+ onChange={(e) => setGhSecret(e.target.value)}+ placeholder={data.githubClientSecretSet ? "••••••••••••••••" : "secret"}+ className={input}+ />+ {data.githubClientSecretSet && (+ <button+ onClick={() => clearSecret("clearGithubClientSecret")}+ className="shrink-0 rounded-md border border-border px-2.5 py-1.5 text-xs text-muted-foreground hover:text-destructive"+ >+ Remove+ </button>+ )}+ </div>+ </Field>+ </div>+ </section>++ {/* Env-only note */}+ <section className="mt-6 border-t border-border pt-6">+ <p className="text-xs text-muted-foreground">+ Set on the host (bootstrap / security): <code className="rounded bg-muted px-1">AUTH_SECRET</code>,{" "}+ <code className="rounded bg-muted px-1">APP_URL</code>, <code className="rounded bg-muted px-1">ALLOWED_EMAILS</code>,{" "}+ <code className="rounded bg-muted px-1">GOOGLE_CLIENT_ID/SECRET</code>,{" "}+ <code className="rounded bg-muted px-1">ENGRAM_DATA_DIR</code>. These gate login itself, so they can’t live behind it.+ </p>+ </section>++ <div className="sticky bottom-0 mt-8 flex items-center gap-3 border-t border-border bg-background/80 py-4 backdrop-blur">+ <button+ onClick={save}+ disabled={saving}+ className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"+ >+ {saved && <Check size={14} />}+ {saving ? "Saving…" : saved ? "Saved" : "Save changes"}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/app/api/features/route.ts b/app/api/features/route.tsindex 6562853..6b47076 100644--- a/app/api/features/route.ts+++ b/app/api/features/route.ts@@ -1,11 +1,13 @@-import { AUTH_DISABLED, AUTH_SECRET, HARNESS_ENABLED, MCP_TOKEN } from "@/lib/config";+import { AUTH_DISABLED, AUTH_SECRET, MCP_TOKEN } from "@/lib/config";+import { appName, harnessEnabled } from "@/lib/settings";import { hasAnyToken } from "@/lib/tokens";export const dynamic = "force-dynamic";export function GET() {return Response.json({- harness: HARNESS_ENABLED,+ appName: appName(),+ harness: harnessEnabled(),mcpAuthRequired: MCP_TOKEN !== "" || hasAnyToken(),dashboardAuthRequired: !AUTH_DISABLED && AUTH_SECRET !== "",});diff --git a/app/api/health/route.ts b/app/api/health/route.tsindex 5b88ca5..2babba9 100644--- a/app/api/health/route.ts+++ b/app/api/health/route.ts@@ -1,5 +1,5 @@export const dynamic = "force-dynamic";export function GET() {- return Response.json({ ok: true, service: "cortex" });+ return Response.json({ ok: true, service: "engram" });}diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.tsindex 3c86a49..038dc28 100644--- a/app/api/mcp/route.ts+++ b/app/api/mcp/route.ts@@ -1,4 +1,5 @@-import { HARNESS_ENABLED, MCP_TOKEN } from "@/lib/config";+import { MCP_TOKEN } from "@/lib/config";+import { harnessEnabled } from "@/lib/settings";import { hasAnyToken, verifyToken } from "@/lib/tokens";import { TOOLS, TOOL_MAP } from "@/lib/mcp/tools";@@ -28,13 +29,13 @@ async function handleMessage(msg: Json): Promise<Json | null> {return rpc(id, {protocolVersion: params?.protocolVersion || PROTOCOL,capabilities: { tools: { listChanged: false } },- serverInfo: { name: "cortex", version: "0.1.0" },+ serverInfo: { name: "engram", version: "0.1.0" },});case "ping":return rpc(id, {});case "tools/list": {// Hide the auto-filing harness unless it's turned on (agents file notes themselves).- const tools = TOOLS.filter((t) => t.name !== "brain_capture" || HARNESS_ENABLED);+ const tools = TOOLS.filter((t) => t.name !== "brain_capture" || harnessEnabled());return rpc(id, {tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),});diff --git a/app/api/settings/route.ts b/app/api/settings/route.tsnew file mode 100644index 0000000..afc99ea--- /dev/null+++ b/app/api/settings/route.ts@@ -0,0 +1,23 @@+import { publicSettings, updateSettings, type SettingsPatch } from "@/lib/settings";++export const dynamic = "force-dynamic";++/** Current settings (secrets redacted to *Set booleans). Behind dashboard auth. */+export function GET() {+ return Response.json(publicSettings());+}++/** Apply a partial update; returns the fresh redacted view. */+export async function PUT(req: Request) {+ let body: SettingsPatch;+ try {+ body = await req.json();+ } catch {+ return Response.json({ error: "invalid JSON" }, { status: 400 });+ }+ try {+ return Response.json(updateSettings(body));+ } catch (e) {+ return Response.json({ error: e instanceof Error ? e.message : "update failed" }, { status: 500 });+ }+}diff --git a/app/apple-icon.png b/app/apple-icon.pngnew file mode 100644index 0000000..866d5b2Binary files /dev/null and b/app/apple-icon.png differdiff --git a/app/icon.png b/app/icon.pngnew file mode 100644index 0000000..6764ec3Binary files /dev/null and b/app/icon.png differdiff --git a/app/layout.tsx b/app/layout.tsxindex a7278ff..6d1d5f1 100644--- a/app/layout.tsx+++ b/app/layout.tsx@@ -3,15 +3,17 @@ import { Geist, Geist_Mono } from "next/font/google";import Script from "next/script";import "./globals.css";import { Providers } from "@/components/providers";-import { APP_NAME } from "@/lib/config";+import { appName } from "@/lib/settings";const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"] });const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"] });-export const metadata: Metadata = {- title: APP_NAME,- description: "Agent-first markdown second brain — dashboard + MCP over a git-backed vault",-};+export function generateMetadata(): Metadata {+ return {+ title: appName(),+ description: "Agent-first markdown second brain — dashboard + MCP over a git-backed vault",+ };+}export const viewport: Viewport = {themeColor: "#0a0a0a",diff --git a/app/login/page.tsx b/app/login/page.tsxindex 9200d29..b727b41 100644--- a/app/login/page.tsx+++ b/app/login/page.tsx@@ -1,4 +1,4 @@-const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME || "Cortex";+const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME || "Engram";export default async function LoginPage({searchParams,diff --git a/assets/logo.png b/assets/logo.pngnew file mode 100644index 0000000..3940361Binary files /dev/null and b/assets/logo.png differdiff --git a/bun.lock b/bun.lockindex dd947d9..2440755 100644--- a/bun.lock+++ b/bun.lock@@ -3,7 +3,7 @@"configVersion": 1,"workspaces": {"": {- "name": "cortex",+ "name": "engram","dependencies": {"@base-ui/react": "^1.5.0","@modelcontextprotocol/sdk": "^1.13.0",diff --git a/components/sidebar.tsx b/components/sidebar.tsxindex 7bfa4a6..199e6ee 100644--- a/components/sidebar.tsx+++ b/components/sidebar.tsx@@ -4,17 +4,18 @@ import useSWR, { useSWRConfig } from "swr";import Link from "next/link";import { usePathname, useRouter } from "next/navigation";import { useState } from "react";-import { Search, Network, FilePlus, Zap, Plug } from "lucide-react";+import { Search, Network, FilePlus, Zap, Plug, Settings } from "lucide-react";import { fetcher, type TreeNode } from "@/lib/client";import { Tree } from "./tree";import { ThemeToggle } from "./theme-toggle";import { WorkspaceSwitcher } from "./workspace-switcher";-const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME || "Cortex";+const FALLBACK_NAME = process.env.NEXT_PUBLIC_APP_NAME || "Engram";export function Sidebar() {const { data } = useSWR<{ tree: TreeNode }>("/api/tree", fetcher, { refreshInterval: 5000 });- const { data: feat } = useSWR<{ harness?: boolean }>("/api/features", fetcher);+ const { data: feat } = useSWR<{ harness?: boolean; appName?: string }>("/api/features", fetcher);+ const appName = feat?.appName || FALLBACK_NAME;const { mutate } = useSWRConfig();const pathname = usePathname();const router = useRouter();@@ -82,7 +83,7 @@ export function Sidebar() {<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>+ <span className="text-sm font-medium tracking-tight">{appName}</span></div><WorkspaceSwitcher />@@ -161,13 +162,22 @@ export function Sidebar() {</nav><div className="flex items-center justify-between border-t border-border px-2 py-1.5">- <Link- href="/connect"- title="Connect an agent"- className="inline-flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground"- >- <Plug size={14} />- </Link>+ <div className="flex items-center gap-1">+ <Link+ href="/connect"+ title="Connect an agent"+ className="inline-flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground"+ >+ <Plug size={14} />+ </Link>+ <Link+ href="/settings"+ title="Settings"+ className="inline-flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground"+ >+ <Settings size={14} />+ </Link>+ </div><ThemeToggle /></div></aside>diff --git a/lib/config.ts b/lib/config.tsindex f3fc4fd..9a056ee 100644--- a/lib/config.ts+++ b/lib/config.ts@@ -1,7 +1,7 @@import path from "node:path";/** Public display name (also exposed to the client via NEXT_PUBLIC_APP_NAME). */-export const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME ?? "Cortex";+export const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME ?? "Engram";/*** Absolute path to the markdown vault (the knowledge, source of truth).@@ -17,9 +17,9 @@ export const VAULT_DIR = process.env.VAULT_DIR* Fixed data dir for app state + managed vault clones (repos.json, tokens.json,* vaults/<id>/). Separate from any vault's content. On Railway set to the volume, e.g. /data.*/-export const DATA_ROOT = process.env.CORTEX_DATA_DIR- ? path.resolve(process.env.CORTEX_DATA_DIR)- : path.resolve(process.cwd(), ".cortex-data");+export const DATA_ROOT = process.env.ENGRAM_DATA_DIR+ ? path.resolve(process.env.ENGRAM_DATA_DIR)+ : path.resolve(process.cwd(), ".engram-data");/** Directory names never treated as vault content (app code, git internals, build output). */export const VAULT_IGNORE = new Set(@@ -58,18 +58,30 @@ export const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET ?? "";export const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID ?? "";export const GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET ?? "";-export const SESSION_COOKIE = "cortex_session";+export const SESSION_COOKIE = "engram_session";-/** When true, the git-sync loop commits + pushes vault changes to the remote. */+/**+ * The values below are ENV FALLBACKS/DEFAULTS. Most are now also configurable at+ * runtime in the dashboard Settings page (persisted under ENGRAM_DATA_DIR). When a+ * setting is saved in the UI it WINS; the env value here is only the default.+ * Resolve them through `lib/settings.ts` (gitSyncEnabled(), gitAuthor(),+ * harnessEnabled(), anthropicApiKey(), captureModel(), appName(), github*()),+ * never by importing these consts directly into feature code.+ */++/** Env default for the git-sync loop (commit + push the active vault). */export const GIT_SYNC_ENABLED = process.env.GIT_SYNC_ENABLED === "true";+/** Env default commit identity for git-sync. */+export const GIT_AUTHOR_NAME = process.env.GIT_AUTHOR_NAME || "Engram";+export const GIT_AUTHOR_EMAIL = process.env.GIT_AUTHOR_EMAIL || "engram@localhost";-/** Anthropic key for the brain_capture harness (rough dump -> filed note). */+/** Env default Anthropic key for the brain_capture harness (rough dump -> filed note). */export const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY ?? "";export const CAPTURE_MODEL = process.env.CAPTURE_MODEL ?? "claude-haiku-4-5-20251001";/**- * Server-side auto-filing harness (brain_capture). OFF by default: a capable coding- * agent can do the filing itself over the plain MCP tools with no extra server tokens.- * Turn on only if you want the vault to file rough dumps on its own.+ * Env default for the server-side auto-filing harness (brain_capture). OFF by default:+ * a capable coding agent can do the filing itself over the plain MCP tools with no extra+ * server tokens. The effective flag also requires an Anthropic key — see harnessEnabled().*/-export const HARNESS_ENABLED = process.env.HARNESS_ENABLED === "true" && ANTHROPIC_API_KEY !== "";+export const HARNESS_ENABLED_ENV = process.env.HARNESS_ENABLED === "true";diff --git a/lib/git.ts b/lib/git.tsindex 2ba64a4..f11376f 100644--- a/lib/git.ts+++ b/lib/git.ts@@ -1,6 +1,6 @@import { simpleGit } from "simple-git";-import { GIT_SYNC_ENABLED } from "@/lib/config";import { activeVaultDir } from "@/lib/repos";+import { gitAuthor, gitSyncEnabled } from "@/lib/settings";let timer: ReturnType<typeof setTimeout> | null = null;let pending: string[] = [];@@ -8,7 +8,7 @@ let running = false;/** Debounced commit + pull --rebase + push of the ACTIVE vault. No-op unless GIT_SYNC_ENABLED. */export function requestSync(reason: string): void {- if (!GIT_SYNC_ENABLED) return;+ if (!gitSyncEnabled()) return;pending.push(reason);if (timer) clearTimeout(timer);timer = setTimeout(runSync, 2500);@@ -31,8 +31,7 @@ async function runSync(): Promise<void> {running = false;return;}- const name = process.env.GIT_AUTHOR_NAME || "Cortex";- const email = process.env.GIT_AUTHOR_EMAIL || "cortex@localhost";+ const { name, email } = gitAuthor();await g.env({...process.env,@@ -60,7 +59,7 @@ async function runSync(): Promise<void> {}export async function syncStatus() {- if (!GIT_SYNC_ENABLED) return { enabled: false as const };+ if (!gitSyncEnabled()) return { enabled: false as const };try {const s = await simpleGit(activeVaultDir()).status();return { enabled: true as const, dirty: s.files.length, ahead: s.ahead, behind: s.behind, branch: s.current };diff --git a/lib/github.ts b/lib/github.tsindex ecad928..2cf9c66 100644--- a/lib/github.ts+++ b/lib/github.ts@@ -1,18 +1,19 @@import fs from "node:fs";import path from "node:path";-import { APP_URL, DATA_ROOT, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET } from "@/lib/config";+import { APP_URL, DATA_ROOT } from "@/lib/config";import { decryptSecret, encryptSecret } from "@/lib/crypto";+import { githubClientId, githubClientSecret } from "@/lib/settings";const GH_FILE = path.join(DATA_ROOT, "github.json");const REDIRECT_URI = () => `${APP_URL}/api/github/callback`;export function githubConfigured(): boolean {- return GITHUB_CLIENT_ID !== "" && GITHUB_CLIENT_SECRET !== "";+ return githubClientId() !== "" && githubClientSecret() !== "";}export function githubAuthUrl(state: string): string {const p = new URLSearchParams({- client_id: GITHUB_CLIENT_ID,+ client_id: githubClientId(),redirect_uri: REDIRECT_URI(),scope: "repo",state,@@ -25,8 +26,8 @@ export async function exchangeGithubCode(code: string): Promise<string | null> {method: "POST",headers: { "content-type": "application/json", accept: "application/json" },body: JSON.stringify({- client_id: GITHUB_CLIENT_ID,- client_secret: GITHUB_CLIENT_SECRET,+ client_id: githubClientId(),+ client_secret: githubClientSecret(),code,redirect_uri: REDIRECT_URI(),}),diff --git a/lib/harness.ts b/lib/harness.tsindex 8c8f118..4b10494 100644--- a/lib/harness.ts+++ b/lib/harness.ts@@ -1,4 +1,4 @@-import { ANTHROPIC_API_KEY, CAPTURE_MODEL, HARNESS_ENABLED } from "@/lib/config";+import { anthropicApiKey, captureModel, harnessEnabled } from "@/lib/settings";import { getTree, listNotes, readVaultFile } from "@/lib/vault/store";import { writeNote } from "@/lib/vault/write";@@ -35,9 +35,10 @@ function extractJson(text: string): { path: string; frontmatter?: Record<string,/** Take a rough dump, let the model decide the path + frontmatter, and write the note. */export async function captureNote(rough: string): Promise<CaptureResult> {- if (!HARNESS_ENABLED)- throw new Error("brain_capture is off — set HARNESS_ENABLED=true and ANTHROPIC_API_KEY to enable the auto-filing harness");- if (!ANTHROPIC_API_KEY) throw new Error("ANTHROPIC_API_KEY not set");+ 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)");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"""`;@@ -46,11 +47,11 @@ export async function captureNote(rough: string): Promise<CaptureResult> {method: "POST",headers: {"content-type": "application/json",- "x-api-key": ANTHROPIC_API_KEY,+ "x-api-key": apiKey,"anthropic-version": "2023-06-01",},body: JSON.stringify({- model: CAPTURE_MODEL,+ model: captureModel(),max_tokens: 2000,system: SYSTEM,messages: [{ role: "user", content: user }],diff --git a/lib/settings.ts b/lib/settings.tsnew file mode 100644index 0000000..4c5c410--- /dev/null+++ b/lib/settings.ts@@ -0,0 +1,207 @@+import fs from "node:fs";+import path from "node:path";+import {+ ANTHROPIC_API_KEY,+ APP_NAME,+ CAPTURE_MODEL,+ DATA_ROOT,+ GIT_AUTHOR_EMAIL,+ GIT_AUTHOR_NAME,+ GIT_SYNC_ENABLED,+ GITHUB_CLIENT_ID,+ GITHUB_CLIENT_SECRET,+ HARNESS_ENABLED_ENV,+} from "@/lib/config";+import { decryptSecret, encryptSecret } from "@/lib/crypto";++/**+ * Runtime settings — the dashboard-editable half of the config.+ *+ * Instead of forcing every operator to set a dozen env vars on the host (and+ * redeploy to flip a toggle), Engram persists an overrides file next to the other+ * app state (tokens.json, repos.json) under ENGRAM_DATA_DIR. A saved override WINS+ * over the matching env var; when unset, the env default (see lib/config.ts) is used.+ * This keeps existing env-only deploys and OSS local dev working unchanged.+ *+ * Secrets (Anthropic key, GitHub client secret) are stored AES-encrypted at rest,+ * keyed off AUTH_SECRET — same as connected git tokens (lib/crypto.ts).+ */++// App state lives in the fixed data dir, separate from any vault content (matches lib/tokens.ts).+const STATE_DIR = process.env.ENGRAM_STATE_DIR || DATA_ROOT;+const SETTINGS_FILE = path.join(STATE_DIR, "settings.json");++/** On-disk shape — only keys the operator has overridden are present. */+interface StoredSettings {+ appName?: string;+ gitSyncEnabled?: boolean;+ gitAuthorName?: string;+ gitAuthorEmail?: string;+ harnessEnabled?: boolean;+ captureModel?: string;+ anthropicApiKeyEnc?: string;+ githubClientId?: string;+ githubClientSecretEnc?: string;+}++let cache: StoredSettings | null = null;++function load(): StoredSettings {+ if (cache) return cache;+ try {+ cache = JSON.parse(fs.readFileSync(SETTINGS_FILE, "utf8"));+ } catch {+ cache = {};+ }+ return cache!;+}++function save(s: StoredSettings): void {+ fs.mkdirSync(STATE_DIR, { recursive: true });+ fs.writeFileSync(SETTINGS_FILE, JSON.stringify(s, null, 2));+ cache = s;+}++/** Decrypt a stored secret, falling back to "" if the key is missing/rotated. */+function safeDecrypt(enc?: string): string {+ if (!enc) return "";+ try {+ return decryptSecret(enc);+ } catch {+ return "";+ }+}++// ── Resolved getters (override ?? env default). Feature code uses THESE. ──────++export function appName(): string {+ return load().appName || APP_NAME;+}++export function gitSyncEnabled(): boolean {+ return load().gitSyncEnabled ?? GIT_SYNC_ENABLED;+}++export function gitAuthor(): { name: string; email: string } {+ const s = load();+ return {+ name: s.gitAuthorName || GIT_AUTHOR_NAME,+ email: s.gitAuthorEmail || GIT_AUTHOR_EMAIL,+ };+}++export function captureModel(): string {+ return load().captureModel || CAPTURE_MODEL;+}++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). */+export function harnessEnabled(): boolean {+ const flag = load().harnessEnabled ?? HARNESS_ENABLED_ENV;+ return flag && anthropicApiKey() !== "";+}++export function githubClientId(): string {+ return load().githubClientId || GITHUB_CLIENT_ID;+}++export function githubClientSecret(): string {+ return safeDecrypt(load().githubClientSecretEnc) || GITHUB_CLIENT_SECRET;+}++// ── Public (redacted) view for the Settings form ─────────────────────────────++export interface PublicSettings {+ appName: string;+ gitSyncEnabled: boolean;+ gitAuthorName: string;+ gitAuthorEmail: string;+ harnessEnabledFlag: boolean; // the raw toggle, independent of key presence+ harnessEffective: boolean; // enabled AND a key is present+ captureModel: string;+ anthropicApiKeySet: boolean;+ githubClientId: string;+ githubClientSecretSet: boolean;+ /** Which fields are currently coming from env (shown as "inherited" hints in the UI). */+ envManaged: Record<string, boolean>;+}++export function publicSettings(): PublicSettings {+ const s = load();+ return {+ appName: appName(),+ gitSyncEnabled: gitSyncEnabled(),+ gitAuthorName: gitAuthor().name,+ gitAuthorEmail: gitAuthor().email,+ harnessEnabledFlag: s.harnessEnabled ?? HARNESS_ENABLED_ENV,+ harnessEffective: harnessEnabled(),+ captureModel: captureModel(),+ anthropicApiKeySet: anthropicApiKey() !== "",+ githubClientId: githubClientId(),+ githubClientSecretSet: githubClientSecret() !== "",+ envManaged: {+ appName: s.appName === undefined && APP_NAME !== "Engram",+ gitSync: s.gitSyncEnabled === undefined && GIT_SYNC_ENABLED,+ anthropicApiKey: s.anthropicApiKeyEnc === undefined && ANTHROPIC_API_KEY !== "",+ githubClientId: s.githubClientId === undefined && GITHUB_CLIENT_ID !== "",+ githubClientSecret: s.githubClientSecretEnc === undefined && GITHUB_CLIENT_SECRET !== "",+ },+ };+}++// ── Update ───────────────────────────────────────────────────────────────────++/**+ * Patch semantics: a present key mutates that override. For text fields, "" clears+ * the override (revert to env/default). Secrets are only touched when a non-empty+ * value is sent, or explicitly cleared via the `clear*` flags. Booleans set an+ * explicit override.+ */+export interface SettingsPatch {+ appName?: string;+ gitSyncEnabled?: boolean;+ gitAuthorName?: string;+ gitAuthorEmail?: string;+ harnessEnabled?: boolean;+ captureModel?: string;+ anthropicApiKey?: string;+ clearAnthropicApiKey?: boolean;+ githubClientId?: string;+ githubClientSecret?: string;+ clearGithubClientSecret?: boolean;+}++function setText(s: StoredSettings, key: keyof StoredSettings, value: string | undefined): void {+ if (value === undefined) return;+ const v = value.trim();+ if (v === "") delete s[key];+ else (s[key] as string) = v;+}++export function updateSettings(patch: SettingsPatch): PublicSettings {+ const s = { ...load() };++ setText(s, "appName", patch.appName);+ setText(s, "gitAuthorName", patch.gitAuthorName);+ setText(s, "gitAuthorEmail", patch.gitAuthorEmail);+ setText(s, "captureModel", patch.captureModel);+ setText(s, "githubClientId", patch.githubClientId);++ if (patch.gitSyncEnabled !== undefined) s.gitSyncEnabled = patch.gitSyncEnabled;+ if (patch.harnessEnabled !== undefined) s.harnessEnabled = patch.harnessEnabled;++ // Secrets: set only when a value is typed; clear only on explicit request.+ if (patch.clearAnthropicApiKey) delete s.anthropicApiKeyEnc;+ else if (patch.anthropicApiKey && patch.anthropicApiKey.trim() !== "")+ s.anthropicApiKeyEnc = encryptSecret(patch.anthropicApiKey.trim());++ if (patch.clearGithubClientSecret) delete s.githubClientSecretEnc;+ else if (patch.githubClientSecret && patch.githubClientSecret.trim() !== "")+ s.githubClientSecretEnc = encryptSecret(patch.githubClientSecret.trim());++ save(s);+ return publicSettings();+}diff --git a/lib/tokens.ts b/lib/tokens.tsindex 17f61a2..4f3d00a 100644--- a/lib/tokens.ts+++ b/lib/tokens.ts@@ -4,7 +4,7 @@ import path from "node:path";import { DATA_ROOT } from "@/lib/config";// App state (token hashes) lives in the fixed data dir, separate from any vault content.-const STATE_DIR = process.env.CORTEX_STATE_DIR || DATA_ROOT;+const STATE_DIR = process.env.ENGRAM_STATE_DIR || DATA_ROOT;const TOKENS_FILE = path.join(STATE_DIR, "tokens.json");interface StoredToken {diff --git a/middleware.ts b/middleware.tsindex ad871ef..9550cdf 100644--- a/middleware.ts+++ b/middleware.ts@@ -1,7 +1,7 @@import { NextResponse, type NextRequest } from "next/server";import { jwtVerify } from "jose";-const SESSION_COOKIE = "cortex_session";+const SESSION_COOKIE = "engram_session";export async function middleware(req: NextRequest) {const secret = process.env.AUTH_SECRET || "";diff --git a/package.json b/package.jsonindex 1ae54d6..5bbdd73 100644--- a/package.json+++ b/package.json@@ -1,8 +1,30 @@{- "name": "cortex",+ "name": "engram","version": "0.1.0","private": true,- "description": "Agent-first markdown second brain — dashboard + MCP over a git-backed vault",+ "description": "Engram — a self-hosted MCP server + dashboard that gives Claude Code, Cursor, and Hermes agents shared long-term memory over a git-backed markdown vault. An agent-native second brain.",+ "keywords": [+ "mcp",+ "mcp-server",+ "model-context-protocol",+ "claude-code",+ "anthropic",+ "ai-agents",+ "agent-memory",+ "llm-memory",+ "second-brain",+ "pkm",+ "personal-knowledge-management",+ "knowledge-base",+ "knowledge-graph",+ "markdown",+ "obsidian",+ "zettelkasten",+ "rag",+ "git",+ "self-hosted",+ "cursor"+ ],"license": "MIT","scripts": {"dev": "next dev",diff --git a/render.yaml b/render.yamlindex 7c25ee7..3d0a99a 100644--- a/render.yaml+++ b/render.yaml@@ -2,21 +2,21 @@# One-click via the "Deploy to Render" button (repo must be public or connected).services:- type: web- name: cortex+ name: engramruntime: dockerplan: starterhealthCheckPath: /api/healthdisk:- name: cortex-data+ name: engram-datamountPath: /datasizeGB: 1envVars:- - key: CORTEX_DATA_DIR+ - key: ENGRAM_DATA_DIRvalue: /data- key: GIT_SYNC_ENABLEDvalue: "true"- key: NEXT_PUBLIC_APP_NAME- value: Cortex+ value: Engram- key: AUTH_SECRETgenerateValue: true # auto-generated on deploy- key: APP_URLdiff --git a/sample-vault/SCHEMA.md b/sample-vault/SCHEMA.mdindex cbba54c..1b30c84 100644--- a/sample-vault/SCHEMA.md+++ b/sample-vault/SCHEMA.md@@ -16,7 +16,7 @@ tags: [alpha, beta]status: active # free textcreated: 2026-01-15related:- - "[[projects/cortex]]"+ - "[[projects/engram]]"---```diff --git a/sample-vault/clients/acme/acme.md b/sample-vault/clients/acme/acme.mdindex 7ff0b46..680003c 100644--- a/sample-vault/clients/acme/acme.md+++ b/sample-vault/clients/acme/acme.md@@ -11,7 +11,7 @@ related:# Acme Corp-Example client note. Referred by [[ada-lovelace]]. Using [[cortex]] as their team brain.+Example client note. Referred by [[ada-lovelace]]. Using [[engram]] as their team brain.| Field | Value ||---|---|@@ -20,4 +20,4 @@ Example client note. Referred by [[ada-lovelace]]. Using [[cortex]] as their tea## Connected to- [[ada-lovelace]] — main contact-- [[cortex]] — what we're building for them+- [[engram]] — what we're building for themdiff --git a/sample-vault/daily/2026-01-15.md b/sample-vault/daily/2026-01-15.mdindex 886c8fa..da723cd 100644--- a/sample-vault/daily/2026-01-15.md+++ b/sample-vault/daily/2026-01-15.md@@ -8,9 +8,9 @@ date: 2026-01-15# 2026-01-15## Top of mind-- Ship the first version of [[cortex]]+- Ship the first version of [[engram]]- Onboard [[acme]]## Notes-- Wrote the [[adopt-cortex-2026-01-15|adoption decision]].+- Wrote the [[adopt-engram-2026-01-15|adoption decision]].- Daily notes are a nice way to see momentum in the graph over time.diff --git a/sample-vault/decisions/adopt-cortex-2026-01-15.md b/sample-vault/decisions/adopt-engram-2026-01-15.mdsimilarity index 82%rename from sample-vault/decisions/adopt-cortex-2026-01-15.mdrename to sample-vault/decisions/adopt-engram-2026-01-15.mdindex f5f1a84..09559b6 100644--- a/sample-vault/decisions/adopt-cortex-2026-01-15.md+++ b/sample-vault/decisions/adopt-engram-2026-01-15.md@@ -5,7 +5,7 @@ tags: [decision, infra]status: activecreated: 2026-01-15related:- - "[[projects/cortex]]"+ - "[[projects/engram]]"---# Adopt a markdown-native second brain@@ -16,10 +16,10 @@ locking anything into a proprietary database.> [!abstract] Decision> Keep knowledge as **plain markdown in git**. Put a dashboard on top for humans and an-> **MCP server** on top for agents. See [[cortex]].+> **MCP server** on top for agents. See [[engram]].> [!warning] Non-goal> Not building a database-backed app. The files win; any index is rebuildable.## Connected to-- [[cortex]] — the implementation+- [[engram]] — the implementationdiff --git a/sample-vault/inbox/welcome.md b/sample-vault/inbox/welcome.mdindex 3b06a3c..5f95b10 100644--- a/sample-vault/inbox/welcome.md+++ b/sample-vault/inbox/welcome.md@@ -1,11 +1,11 @@----title: Welcome to Cortex+title: Welcome to Engramtype: doctags: [getting-started]created: 2026-01-15----# Welcome to Cortex+# Welcome to EngramThis is a **sample vault** so the app works out of the box. Point `VAULT_DIR` at your ownfolder of markdown to use it for real.@@ -15,8 +15,8 @@ folder of markdown to use it for real.> **graph** (sidebar icon) to see how notes connect.## Explore-- [[cortex]] — what this project is-- [[adopt-cortex-2026-01-15]] — the decision behind it+- [[engram]] — what this project is+- [[adopt-engram-2026-01-15]] — the decision behind it- [[acme]] — an example client note- [[ada-lovelace]] — an example person notediff --git a/sample-vault/people/ada-lovelace.md b/sample-vault/people/ada-lovelace.mdindex 6e3eda0..8e2c61d 100644--- a/sample-vault/people/ada-lovelace.md+++ b/sample-vault/people/ada-lovelace.md@@ -8,7 +8,7 @@ created: 2026-01-15# Ada Lovelace-Example person note. Introduced us to [[acme]] and reviews [[cortex]].+Example person note. Introduced us to [[acme]] and reviews [[engram]].> [!note]> Person notes hold contacts, history, and relationships. Wikilinks to their clients anddiff --git a/sample-vault/projects/cortex.md b/sample-vault/projects/engram.mdsimilarity index 80%rename from sample-vault/projects/cortex.mdrename to sample-vault/projects/engram.mdindex e4c214b..1e421c1 100644--- a/sample-vault/projects/cortex.md+++ b/sample-vault/projects/engram.md@@ -1,14 +1,14 @@----title: Cortex+title: Engramtype: projecttags: [project, active]status: activecreated: 2026-01-15related:- - "[[adopt-cortex-2026-01-15]]"+ - "[[adopt-engram-2026-01-15]]"----# Cortex+# EngramAn agent-first, markdown-native second brain: a dashboard for humans and an MCP server foragents, over a git-backed folder of notes.@@ -19,5 +19,5 @@ agents, over a git-backed folder of notes.- Agents ([[ada-lovelace|and humans]]) read and write the same notes.## Connected to-- [[adopt-cortex-2026-01-15]] — why we built it+- [[adopt-engram-2026-01-15]] — why we built it- [[acme]] — first example client