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
W2-W4: dashboard-managed GitHub workspaces (multi-repo, switchable, agent-transparent)
Ronalds Palacis10b48e18613b
diff --git a/.env.example b/.env.exampleindex b9d24ec..07609d5 100644--- a/.env.example+++ b/.env.example@@ -8,14 +8,17 @@ NEXT_PUBLIC_APP_NAME="Cortex"# production: the mounted volume path# VAULT_DIR="/data"-# ── Git-backed vault (production) ────────────────────────────────────────────-# The app clones + syncs this remote vault repo into VAULT_DIR — the real vault-# lives remotely; no machine keeps a local copy.-# GIT_REMOTE="https://github.com/youruser/your-vault.git"+# ── 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.GIT_SYNC_ENABLED="false"-GIT_TOKEN="" # token with push access to the vault repoGIT_AUTHOR_NAME="Cortex"GIT_AUTHOR_EMAIL="[email protected]"+# CORTEX_DATA_DIR="/data" # app state + vault clones (on Railway: the volume)++# ── Workspaces: GitHub OAuth (connect vault repos from the dashboard) ─────────+GITHUB_CLIENT_ID=""+GITHUB_CLIENT_SECRET=""# ── Auth ────────────────────────────────────────────────────────────────────# Dashboard: Google sign-in restricted to an email allowlist.diff --git a/app/(app)/workspaces/page.tsx b/app/(app)/workspaces/page.tsxnew file mode 100644index 0000000..909ad1a--- /dev/null+++ b/app/(app)/workspaces/page.tsx@@ -0,0 +1,162 @@+"use client";++import useSWR, { useSWRConfig } from "swr";+import { useState } from "react";+import { GitBranch, Trash2 } from "lucide-react";+import { fetcher } from "@/lib/client";++interface Repo {+ id: string;+ name: string;+ fullName?: string;+ active: boolean;+ addedAt: string;+}+interface GhRepo {+ fullName: string;+ name: string;+ cloneUrl: string;+ private: boolean;+ defaultBranch: string;+}++function refresh(mutate: (key: string) => unknown) {+ for (const k of ["/api/repos", "/api/tree", "/api/notes"]) mutate(k);+}++export default function WorkspacesPage() {+ const { data: gh } = useSWR<{ connected: boolean; login?: string; configured: boolean }>("/api/github/status", fetcher);+ const { data: reposData } = useSWR<{ repos: Repo[] }>("/api/repos", fetcher);+ const { data: ghRepos } = useSWR<{ repos: GhRepo[] }>(gh?.connected ? "/api/github/repos" : null, fetcher);+ const { mutate } = useSWRConfig();+ const [busy, setBusy] = useState<string | null>(null);+ const [err, setErr] = useState("");++ const repos = reposData?.repos ?? [];+ const addedNames = new Set(repos.map((r) => r.fullName));++ async function add(r: GhRepo) {+ setBusy(r.fullName);+ setErr("");+ try {+ const res = await fetch("/api/repos", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ fullName: r.fullName, cloneUrl: r.cloneUrl, branch: r.defaultBranch }),+ });+ const d = await res.json();+ if (!res.ok) setErr(d.error || "add failed");+ else refresh(mutate);+ } finally {+ setBusy(null);+ }+ }+ async function switchTo(id: string) {+ await fetch("/api/repos/active", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id }) });+ refresh(mutate);+ }+ async function remove(id: string) {+ await fetch(`/api/repos/${id}`, { method: "DELETE" });+ refresh(mutate);+ }++ 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">Workspaces</h1>+ <p className="mt-2 max-w-xl text-sm text-muted-foreground">+ Each workspace is a GitHub repo of markdown. The <span className="text-foreground">active</span> one is what the+ dashboard shows and what agents read/write — agents never see the others.+ </p>++ <section className="mt-8 space-y-2">+ <h2 className="text-sm font-medium">GitHub</h2>+ {!gh?.configured ? (+ <p className="text-sm text-muted-foreground">GitHub OAuth isn't configured on this server (set GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET).</p>+ ) : gh?.connected ? (+ <p className="text-sm text-muted-foreground">+ Connected as <span className="text-foreground">{gh.login}</span>.+ </p>+ ) : (+ <a+ href="/api/github/login?next=/workspaces"+ className="inline-flex items-center gap-2 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground"+ >+ <GitBranch size={15} /> Connect GitHub+ </a>+ )}+ </section>++ <section className="mt-8 space-y-2">+ <h2 className="text-sm font-medium">Your workspaces</h2>+ {repos.length > 0 ? (+ <div className="overflow-hidden rounded-lg border border-border">+ <table className="w-full text-sm">+ <tbody>+ {repos.map((r) => (+ <tr key={r.id} className="border-b border-border last:border-0">+ <td className="px-3 py-2">+ {r.name}+ {r.active && <span className="ml-2 rounded bg-accent px-1.5 py-0.5 text-[10px] text-foreground">active</span>}+ </td>+ <td className="px-3 py-2 text-right">+ {!r.active && (+ <button onClick={() => switchTo(r.id)} className="mr-2 rounded-md border border-border px-2 py-1 text-xs transition-colors hover:bg-accent">+ Switch+ </button>+ )}+ <button+ onClick={() => remove(r.id)}+ title="Remove"+ className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-destructive"+ >+ <Trash2 size={14} />+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <p className="text-xs text-muted-foreground">No workspaces yet — add a repo below. Until then, the dashboard shows the bundled sample vault.</p>+ )}+ </section>++ {gh?.connected && (+ <section className="mt-8 space-y-2">+ <h2 className="text-sm font-medium">Add a repo</h2>+ {err && <p className="text-xs text-destructive">{err}</p>}+ <div className="scrollbar-none max-h-96 overflow-y-auto overflow-hidden rounded-lg border border-border">+ <table className="w-full text-sm">+ <tbody>+ {(ghRepos?.repos ?? []).map((r) => (+ <tr key={r.fullName} className="border-b border-border last:border-0">+ <td className="px-3 py-2">+ {r.fullName}+ {r.private && <span className="ml-2 text-[10px] text-muted-foreground">private</span>}+ </td>+ <td className="px-3 py-2 text-right">+ {addedNames.has(r.fullName) ? (+ <span className="text-xs text-muted-foreground">added</span>+ ) : (+ <button+ disabled={busy === r.fullName}+ onClick={() => add(r)}+ className="rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground disabled:opacity-50"+ >+ {busy === r.fullName ? "Adding…" : "Add"}+ </button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </section>+ )}+ </div>+ </div>+ );+}diff --git a/app/api/github/callback/route.ts b/app/api/github/callback/route.tsnew file mode 100644index 0000000..5ee05c0--- /dev/null+++ b/app/api/github/callback/route.ts@@ -0,0 +1,29 @@+import { connectGithub, exchangeGithubCode } from "@/lib/github";++export const dynamic = "force-dynamic";++function parseCookies(header: string): Record<string, string> {+ const out: Record<string, string> = {};+ for (const part of header.split(";")) {+ const i = part.indexOf("=");+ if (i > -1) out[part.slice(0, i).trim()] = part.slice(i + 1).trim();+ }+ return out;+}+const redirect = (p: string) => new Response(null, { status: 302, headers: { location: p } });++// GitHub is used ONLY to connect vault repos (an admin task). Dashboard login is Google.+export async function GET(req: Request) {+ const url = new URL(req.url);+ const code = url.searchParams.get("code");+ const state = url.searchParams.get("state");+ const cookies = parseCookies(req.headers.get("cookie") || "");+ if (!code || !state || cookies.gh_state !== state) return redirect("/workspaces?error=state");++ const token = await exchangeGithubCode(code);+ if (!token) return redirect("/workspaces?error=github");+ await connectGithub(token);++ const next = cookies.gh_next ? decodeURIComponent(cookies.gh_next) : "/workspaces";+ return redirect(next.startsWith("/") ? next : "/workspaces");+}diff --git a/app/api/github/login/route.ts b/app/api/github/login/route.tsnew file mode 100644index 0000000..623ea4b--- /dev/null+++ b/app/api/github/login/route.ts@@ -0,0 +1,17 @@+import { APP_URL } from "@/lib/config";+import { githubAuthUrl, githubConfigured } from "@/lib/github";++export const dynamic = "force-dynamic";++export function GET(req: Request) {+ if (!githubConfigured()) {+ return Response.json({ error: "GitHub OAuth not configured (set GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET)" }, { status: 500 });+ }+ const next = new URL(req.url).searchParams.get("next") || "/";+ const state = crypto.randomUUID();+ const flag = APP_URL.startsWith("https") ? "; Secure" : "";+ const headers = new Headers({ location: githubAuthUrl(state) });+ headers.append("set-cookie", `gh_state=${state}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600${flag}`);+ headers.append("set-cookie", `gh_next=${encodeURIComponent(next)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600${flag}`);+ return new Response(null, { status: 302, headers });+}diff --git a/app/api/github/repos/route.ts b/app/api/github/repos/route.tsnew file mode 100644index 0000000..692bade--- /dev/null+++ b/app/api/github/repos/route.ts@@ -0,0 +1,7 @@+import { listGithubRepos } from "@/lib/github";++export const dynamic = "force-dynamic";++export async function GET() {+ return Response.json({ repos: await listGithubRepos() });+}diff --git a/app/api/github/status/route.ts b/app/api/github/status/route.tsnew file mode 100644index 0000000..c300cfa--- /dev/null+++ b/app/api/github/status/route.ts@@ -0,0 +1,7 @@+import { githubStatus } from "@/lib/github";++export const dynamic = "force-dynamic";++export function GET() {+ return Response.json(githubStatus());+}diff --git a/app/api/repos/[id]/route.ts b/app/api/repos/[id]/route.tsnew file mode 100644index 0000000..6582778--- /dev/null+++ b/app/api/repos/[id]/route.ts@@ -0,0 +1,11 @@+import { removeRepo } from "@/lib/repos";+import { rebuildIndex } from "@/lib/vault/store";++export const dynamic = "force-dynamic";++export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params;+ removeRepo(id);+ rebuildIndex();+ return Response.json({ ok: true });+}diff --git a/app/api/repos/active/route.ts b/app/api/repos/active/route.tsnew file mode 100644index 0000000..4b9b496--- /dev/null+++ b/app/api/repos/active/route.ts@@ -0,0 +1,12 @@+import { setActive } from "@/lib/repos";+import { rebuildIndex } from "@/lib/vault/store";++export const dynamic = "force-dynamic";++export async function POST(req: Request) {+ const { id } = await req.json().catch(() => ({}));+ if (!id) return Response.json({ error: "id required" }, { status: 400 });+ setActive(id);+ rebuildIndex();+ return Response.json({ ok: true });+}diff --git a/app/api/repos/route.ts b/app/api/repos/route.tsnew file mode 100644index 0000000..7a66d89--- /dev/null+++ b/app/api/repos/route.ts@@ -0,0 +1,29 @@+import { addRepo, getActive, listRepos } from "@/lib/repos";+import { githubToken } from "@/lib/github";+import { rebuildIndex } from "@/lib/vault/store";++export const dynamic = "force-dynamic";++export function GET() {+ return Response.json({ repos: listRepos(), active: getActive() });+}++export async function POST(req: Request) {+ const { fullName, cloneUrl, branch, setActive } = await req.json().catch(() => ({}));+ const url = cloneUrl || (fullName ? `https://github.com/${fullName}.git` : "");+ if (!url) return Response.json({ error: "cloneUrl or fullName required" }, { status: 400 });+ try {+ const repo = await addRepo({+ name: fullName || url,+ fullName,+ url,+ token: githubToken() ?? undefined,+ branch,+ setActive,+ });+ rebuildIndex();+ return Response.json({ ok: true, repo });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: 500 });+ }+}diff --git a/components/sidebar.tsx b/components/sidebar.tsxindex 51f898a..7bfa4a6 100644--- a/components/sidebar.tsx+++ b/components/sidebar.tsx@@ -8,6 +8,7 @@ import { Search, Network, FilePlus, Zap, Plug } 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";@@ -84,6 +85,8 @@ export function Sidebar() {<span className="text-sm font-medium tracking-tight">{APP_NAME}</span></div>+ <WorkspaceSwitcher />+<div className="flex gap-1 px-2 pb-2"><buttononClick={() => (window as unknown as { __openPalette?: () => void }).__openPalette?.()}diff --git a/components/workspace-switcher.tsx b/components/workspace-switcher.tsxnew file mode 100644index 0000000..1325568--- /dev/null+++ b/components/workspace-switcher.tsx@@ -0,0 +1,65 @@+"use client";++import useSWR, { useSWRConfig } from "swr";+import Link from "next/link";+import { useState } from "react";+import { Check, ChevronsUpDown, Settings2 } from "lucide-react";+import { fetcher } from "@/lib/client";++interface Repo {+ id: string;+ name: string;+ active: boolean;+}++export function WorkspaceSwitcher() {+ const { data } = useSWR<{ repos: Repo[]; active: Repo | null }>("/api/repos", fetcher);+ const { mutate } = useSWRConfig();+ const [open, setOpen] = useState(false);++ const repos = data?.repos ?? [];+ const activeName = data?.active?.name ?? "Sample vault";++ async function switchTo(id: string) {+ await fetch("/api/repos/active", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id }) });+ for (const k of ["/api/repos", "/api/tree", "/api/notes"]) mutate(k);+ setOpen(false);+ }++ return (+ <div className="relative px-2 pb-2">+ <button+ onClick={() => setOpen((o) => !o)}+ className="flex w-full items-center gap-2 rounded-md border border-border px-2 py-1.5 text-xs"+ >+ <span className="flex-1 truncate text-left text-foreground">{activeName}</span>+ <ChevronsUpDown size={13} className="shrink-0 text-muted-foreground" />+ </button>+ {open && (+ <>+ <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />+ <div className="absolute left-2 right-2 z-20 mt-1 rounded-md border border-border bg-popover p-1 shadow-lg">+ {repos.length === 0 && <div className="px-2 py-1.5 text-xs text-muted-foreground">Sample vault (no repos yet)</div>}+ {repos.map((r) => (+ <button+ key={r.id}+ onClick={() => switchTo(r.id)}+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-accent"+ >+ <Check size={12} className={r.active ? "opacity-100" : "opacity-0"} />+ <span className="truncate">{r.name}</span>+ </button>+ ))}+ <Link+ href="/workspaces"+ onClick={() => setOpen(false)}+ className="mt-1 flex items-center gap-2 border-t border-border px-2 pb-1 pt-2 text-xs text-muted-foreground transition-colors hover:text-foreground"+ >+ <Settings2 size={12} /> Manage workspaces+ </Link>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/lib/auth.ts b/lib/auth.tsindex 1c52a9b..468f2be 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -1,11 +1,5 @@import { SignJWT, jwtVerify } from "jose";-import {- ALLOWED_EMAILS,- APP_URL,- AUTH_SECRET,- GOOGLE_CLIENT_ID,- GOOGLE_CLIENT_SECRET,-} from "@/lib/config";+import { ALLOWED_EMAILS, APP_URL, AUTH_SECRET, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET } from "@/lib/config";const key = () => new TextEncoder().encode(AUTH_SECRET);diff --git a/lib/config.ts b/lib/config.tsindex 7767124..f3fc4fd 100644--- a/lib/config.ts+++ b/lib/config.ts@@ -38,6 +38,12 @@ export const ALLOWED_EMAILS = (process.env.ALLOWED_EMAILS ?? "").map((s) => s.trim().toLowerCase()).filter(Boolean);+/** GitHub usernames allowed to sign in (dashboard auth is GitHub-only). */+export const ALLOWED_GITHUB_LOGINS = (process.env.ALLOWED_GITHUB_LOGINS ?? "")+ .split(",")+ .map((s) => s.trim().toLowerCase())+ .filter(Boolean);+/** Single-user / local mode: no Google auth, MCP open. For OSS local dev only. */export const AUTH_DISABLED = process.env.AUTH_DISABLED === "true";diff --git a/lib/github.ts b/lib/github.tsnew file mode 100644index 0000000..ecad928--- /dev/null+++ b/lib/github.ts@@ -0,0 +1,124 @@+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 { decryptSecret, encryptSecret } from "@/lib/crypto";++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 !== "";+}++export function githubAuthUrl(state: string): string {+ const p = new URLSearchParams({+ client_id: GITHUB_CLIENT_ID,+ redirect_uri: REDIRECT_URI(),+ scope: "repo",+ state,+ });+ return `https://github.com/login/oauth/authorize?${p.toString()}`;+}++export async function exchangeGithubCode(code: string): Promise<string | null> {+ const res = await fetch("https://github.com/login/oauth/access_token", {+ method: "POST",+ headers: { "content-type": "application/json", accept: "application/json" },+ body: JSON.stringify({+ client_id: GITHUB_CLIENT_ID,+ client_secret: GITHUB_CLIENT_SECRET,+ code,+ redirect_uri: REDIRECT_URI(),+ }),+ });+ if (!res.ok) return null;+ const d = await res.json();+ return d.access_token ?? null;+}++interface GhState {+ tokenEnc: string;+ login?: string;+ connectedAt: string;+}+function loadGh(): GhState | null {+ try {+ return JSON.parse(fs.readFileSync(GH_FILE, "utf8"));+ } catch {+ return null;+ }+}++export async function connectGithub(token: string): Promise<void> {+ let login: string | undefined;+ try {+ const u = await fetch("https://api.github.com/user", { headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" } });+ if (u.ok) login = (await u.json()).login;+ } catch {+ /* ignore */+ }+ fs.mkdirSync(DATA_ROOT, { recursive: true });+ fs.writeFileSync(GH_FILE, JSON.stringify({ tokenEnc: encryptSecret(token), login, connectedAt: new Date().toISOString() }, null, 2));+}++export async function getGithubUser(token: string): Promise<{ login: string; email?: string } | null> {+ try {+ const u = await fetch("https://api.github.com/user", {+ headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" },+ });+ if (!u.ok) return null;+ const d = await u.json();+ return { login: d.login as string, email: (d.email as string) ?? undefined };+ } catch {+ return null;+ }+}++export function githubToken(): string | null {+ const s = loadGh();+ if (!s) return null;+ try {+ return decryptSecret(s.tokenEnc);+ } catch {+ return null;+ }+}++export function githubStatus(): { connected: boolean; login?: string; configured: boolean } {+ const s = loadGh();+ return { connected: !!s, login: s?.login, configured: githubConfigured() };+}++export function disconnectGithub(): void {+ try {+ fs.rmSync(GH_FILE);+ } catch {+ /* ignore */+ }+}++export interface GithubRepo {+ fullName: string;+ name: string;+ cloneUrl: string;+ private: boolean;+ defaultBranch: string;+}++export async function listGithubRepos(): Promise<GithubRepo[]> {+ const token = githubToken();+ if (!token) return [];+ const res = await fetch(+ "https://api.github.com/user/repos?per_page=100&sort=updated&affiliation=owner,collaborator,organization_member",+ { headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" } },+ );+ if (!res.ok) return [];+ const arr = (await res.json()) as Array<Record<string, unknown>>;+ return arr.map((r) => ({+ fullName: r.full_name as string,+ name: r.name as string,+ cloneUrl: r.clone_url as string,+ private: r.private as boolean,+ defaultBranch: (r.default_branch as string) || "main",+ }));+}