From 0418699126ddc81f7a6b8758bb8851827e663a4e Mon Sep 17 00:00:00 2001 From: Joseph Shenton Date: Tue, 24 Nov 2026 08:39:05 +1100 Subject: [PATCH] Organize + librarian: the brain sorts itself (0.6.0) Lint only reported rot; nothing fixed it. Two routines now come with every brain: - organize (daily, upkeep, on): fixes what has exactly one right answer and commits it. Misfiled records move to their type's folder; unsigned shared notes are signed from evidence (agent folder, import note, Agent: trailer, or the commit that added them, skipping bulk commits and bots); [[person/x]] links become [[people/x]] in bodies and links:, and a broken record link is pointed at the one record with that id. Ambiguous cases are listed, not touched; tags, other frontmatter and code are never rewritten; it won't commit over someone else's staged work. Also `brainium organize [--apply]` and the brain_organize tool. - librarian (daily, prompt, off and in shadow until approved): links new notes to their records (creating records two notes need), moves notes where they belong with a pointer, merges duplicates, signs notes whose author is clear and messages owners of stale records. Never deletes. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + bin/brainium.mjs | 13 ++ cli/lib/mcp.mjs | 10 + cli/lib/organize.mjs | 265 +++++++++++++++++++++++++++ cli/lib/records.mjs | 8 +- cli/lib/routines.mjs | 8 +- cli/templates/mcp-instructions.md | 2 +- cli/test/context.test.mjs | 2 +- cli/test/organize.test.mjs | 78 ++++++++ cli/test/routines.test.mjs | 3 +- docs/CONTEXT-SYSTEM.md | 25 +++ docs/TEAMS-AND-ROUTINES.md | 2 +- package.json | 2 +- scaffold/brain/routines/librarian.md | 23 +++ scaffold/brain/routines/organize.md | 9 + 15 files changed, 441 insertions(+), 10 deletions(-) create mode 100644 cli/lib/organize.mjs create mode 100644 cli/test/organize.test.mjs create mode 100644 scaffold/brain/routines/librarian.md create mode 100644 scaffold/brain/routines/organize.md diff --git a/README.md b/README.md index b0fcfee..7ea616b 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Portable **git-backed agent memory**: session logs, failures, learnings, and pro | **Claude Code** | `.claude/skills/brainium/` + `CLAUDE.md` section | | **Generic** | `AGENTS.md` + [prompt snippet](./agents/generic/prompts/closeout-system.md) | | **Personal brain** | `brainium init-personal` → `~/Brainium` (sessions, memories, learnings, **agents/** cards…) | +| **Organize + librarian** | Every brain tidies itself. A daily `organize` job makes the one-right-answer fixes (misfiled records, unsigned notes with evidence, old or broken links), and a `librarian` AI routine (shadow first) links notes to their records, moves misplaced notes, merges duplicates and flags stale records | | **Preflight** | Before any work, `brain_preflight` (or the Claude Code session-start hook, or `brainium preflight`) fast-forwards the repos `.brainium.json` lists and tells the agent which rule files changed since it last looked — no more "pull first" reminders | | **MCP server** | `brainium mcp` — `brain_search`, `brain_log`, `agent_card_save`, `brain_pending`… | | **Capture** | Claude Code `SessionEnd` hook → redacted, private queue → filed by your AI or a summarizer | diff --git a/bin/brainium.mjs b/bin/brainium.mjs index a3cda4a..c8fcb2a 100755 --- a/bin/brainium.mjs +++ b/bin/brainium.mjs @@ -47,6 +47,9 @@ Routines (scheduled prompts, upkeep jobs and shell commands in a brain's routine brainium scheduler install|uninstall|status brainium preflight [--agent NAME] [--no-pull] Before any work: fast-forward the repos .brainium.json lists and list rule files changed since this agent last looked + brainium organize [--brain NAME] [--apply] [--agent NAME] + Fix what lint finds that has one right answer (misfiled records, + unsigned notes with evidence, old or broken links); dry run by default brainium lint [--brain NAME] [--write] [--stale-days N] Check for context rot; --write saves shared/health.md brainium record get FOLDER/ID [--brain NAME] @@ -298,6 +301,16 @@ async function main() { return; } + case "organize": { + const { organizeBrain, organizeReport } = await import("../cli/lib/organize.mjs"); + const { brainRoots, pickBrain, defaultBrainName } = await import("../cli/lib/brain.mjs"); + const roots = brainRoots(config, process.cwd()); + const name = pickBrain(roots, typeof args.brain === "string" ? args.brain : "auto", defaultBrainName(config)); + const r = organizeBrain(roots, name, { apply: !!args.apply, agent: typeof args.agent === "string" ? args.agent : "" }); + print(args, r, organizeReport); + return; + } + case "lint": { const { lintBrain, lintReport, writeHealth } = await import("../cli/lib/records.mjs"); const { brainRoots, pickBrain, defaultBrainName } = await import("../cli/lib/brain.mjs"); diff --git a/cli/lib/mcp.mjs b/cli/lib/mcp.mjs index 260d780..5d63224 100644 --- a/cli/lib/mcp.mjs +++ b/cli/lib/mcp.mjs @@ -163,6 +163,11 @@ export const TOOLS = [ description: "Call this FIRST, before any other work: brings the project's rules and brain up to date (fast-forward pulls of the repos its .brainium.json lists) and lists the rule files that changed since you last looked. Reread every file it lists and follow the new version. If it reports a repo it couldn't update, say so before relying on that repo.", inputSchema: { type: "object", properties: { agent: str("Your agent name (changes are tracked per agent)") } }, }, + { + name: "brain_organize", + description: "Tidy a brain: fix what lint finds that has exactly one right answer — move misfiled records to their type's folder, sign unsigned shared notes from evidence (their agent folder, an import note, the commit that added them), rewrite old [[person/x]] links to [[people/x]] and point broken record links at the one record with that id. Dry run unless apply is true; ambiguous cases are listed, not touched.", + inputSchema: { type: "object", properties: { brain: str("Which brain (default auto)"), apply: { type: "boolean", description: "Make the fixes and commit them (default false: just report)" }, agent: str("Your agent name, for the commit") } }, + }, { name: "brain_pending", description: "List captured sessions waiting to be filed. When any are waiting, read each with brain_pending_get and file it with brain_resolve — you are the summarizer.", @@ -252,6 +257,11 @@ export async function callTool(name, args = {}, { cwd = process.cwd(), env = pro } return lintReport(lintBrain(rs, name, opts)); } + case "brain_organize": { + const { organizeBrain, organizeReport } = await import("./organize.mjs"); + const name = pickBrain(roots(), args.brain || "auto", defaultBrain); + return organizeReport(organizeBrain(roots(), name, { apply: !!args.apply, agent: args.agent || "" })); + } case "brain_preflight": { const { preflight } = await import("./preflight.mjs"); const r = preflight(config, { cwd: args.project || env.BRAINIUM_PROJECT || cwd, agent: args.agent || env.BRAINIUM_AGENT || "" }); diff --git a/cli/lib/organize.mjs b/cli/lib/organize.mjs new file mode 100644 index 0000000..08d8fa4 --- /dev/null +++ b/cli/lib/organize.mjs @@ -0,0 +1,265 @@ +// Organize: the mechanical half of the librarian. Lint finds rot; this fixes +// the parts that have exactly one right answer, so a brain stays tidy without +// anyone sorting it by hand: +// +// misfiled a record whose `type` says another kind → moved to that kind's folder +// unsigned a shared note with no author → signed from evidence: the agent folder +// it sits in, an "added by NAME" import note, or the first git commit +// that added it (bulk commits and sync bots don't count) +// links [[person/sam]] → [[people/sam]]; a link to a record that doesn't exist +// is pointed at the one record with that id, if there's exactly one +// +// Anything ambiguous is left alone and listed as skipped, for a person or the +// librarian routine (an AI prompt routine) to judge. Dry run by default. + +import { execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { dirname, join, relative, sep } from "node:path"; +import { sharedRoot } from "./brain.mjs"; +import { LINK, RECORD_TYPES, SIGNATURE, folderRef, lintBrain, listRecords, markdownFiles, parseFrontmatter, parseRef, prose } from "./records.mjs"; +import { slugify } from "./fsutil.mjs"; + +const BULK_COMMIT_FILES = 40; // a commit touching more files than this is a move or an import, not an author +const NOT_AUTHORS = /^(brain sync|brainium|github-actions|dependabot|renovate|.*\[bot\])$/i; + +function git(root, args) { + return execFileSync("git", ["-c", "submodule.recurse=false", ...args], { cwd: root, stdio: ["ignore", "pipe", "pipe"], encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }).trim(); +} + +const real = (p) => { + try { return realpathSync(p); } catch { return p; } +}; + +function repoRoot(dir) { + try { + return real(git(dir, ["rev-parse", "--show-toplevel"])); + } catch { + return null; + } +} + +/** Every agent slug in this brain (agents// and teams//agents//). */ +function agentSlugs(root) { + const out = new Set(); + for (const f of markdownFiles(root)) { + const parts = relative(root, f).split(sep); + const i = parts.indexOf("agents"); + if (i >= 0 && parts.length > i + 2 && !parts[i + 1].startsWith("_")) out.add(parts[i + 1]); + } + return out; +} + +/** The agent folder a file sits in, if any. */ +function agentOfPath(rel) { + const m = /(?:^|\/)agents\/([a-z0-9][a-z0-9-]*)\//.exec(rel); + return m ? m[1] : null; +} + +/** Who first added `file`, from git, ignoring bulk commits and bots. */ +function gitAuthor(repo, file) { + let log; + try { + log = git(repo, ["log", "--follow", "--reverse", "--format=%H%x09%an", "--", relative(repo, real(file))]); + } catch { + return null; + } + for (const line of log.split("\n").filter(Boolean)) { + const [sha, name] = line.split("\t"); + if (!name || NOT_AUTHORS.test(name.trim())) continue; + let files = 0; + try { + files = git(repo, ["show", "--format=", "--name-only", sha]).split("\n").filter(Boolean).length; + } catch { continue; } + if (files > BULK_COMMIT_FILES) continue; + // An "Agent:" (or "-Agent:") trailer names the agent better than the git author does. + try { + const msg = git(repo, ["show", "-s", "--format=%B", sha]); + const t = /^(?:[\w-]+-)?agent:\s*(.+)$/im.exec(msg); + if (t) return t[1].trim(); + } catch { /* fall back to the author */ } + return name.trim(); + } + return null; +} + +/** Add `key: value` to a note's frontmatter (creating it if there is none). */ +export function addFrontmatterField(text, key, value) { + const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text); + if (m) return `---\n${m[1]}\n${key}: ${value}\n---\n${text.slice(m[0].length)}`; + return `---\n${key}: ${value}\n---\n\n${text}`; +} + +/** + * Work out (and with apply, make) the mechanical fixes for brain `name`. + * Returns { brain, fixes: [{ kind, path, detail }], skipped: [{ kind, path, detail }], commit }. + */ +export function organizeBrain(roots, name, { apply: wantApply = false, agent = "", now = new Date() } = {}) { + let apply = wantApply; + const root = roots[name]; + if (!root) throw new Error(`No brain called "${name}".`); + const repo = repoRoot(root); + const rel = (p) => relative(root, p).split(sep).join("/"); + const lint = lintBrain(roots, name, { now }); + // Don't sweep up someone else's half-staged work into our commit. + const stagedBefore = apply && repo ? git(repo, ["diff", "--cached", "--name-only"]) : ""; + if (stagedBefore) apply = false; + const fixes = []; + const skipped = []; + const touched = new Set(); + const write = (abs, text) => { + if (apply) writeFileSync(abs, text); + touched.add(abs); + }; + + // 1. Misfiled records → their type's folder. + const records = listRecords(root); + for (const r of records) { + const want = r.meta.type && RECORD_TYPES[String(r.meta.type).toLowerCase()]; + if (!want || r.meta.type === r.type) continue; + const dest = join(sharedRoot(root), want.folder, `${r.id}.md`); + if (existsSync(dest)) { + skipped.push({ kind: "misfiled", path: rel(r.path), detail: `${want.folder}/${r.id}.md already exists; merge them by hand` }); + continue; + } + fixes.push({ kind: "misfiled", path: rel(r.path), detail: `moved to ${rel(dest)}` }); + if (apply) { + mkdirSync(dirname(dest), { recursive: true }); + if (repo) git(repo, ["mv", relative(repo, real(r.path)), relative(repo, join(real(dirname(dest)), `${r.id}.md`))]); + else writeFileSync(dest, readFileSync(r.path)); // no git: copy (the old file stays for a person to delete) + } + touched.add(r.path).add(dest); + } + + // 2. Unsigned shared notes → signed from evidence. + const agents = agentSlugs(root); + for (const issue of lint.issues.filter((i) => i.kind === "unsigned")) { + const abs = join(root, issue.path); + if (!existsSync(abs)) continue; + const text = readFileSync(abs, "utf8"); + if (SIGNATURE.test(text)) continue; + let who = agentOfPath(issue.path); + let how = who ? "the agent folder it's in" : ""; + if (!who) { + const added = //i.exec(text); + if (added) { who = added[1].trim(); how = "its import note"; } + } + if (!who && repo) { + const a = gitAuthor(repo, abs); + if (a) { who = a; how = "the commit that added it"; } + } + if (!who) { + skipped.push({ kind: "unsigned", path: issue.path, detail: "no evidence of who wrote it" }); + continue; + } + const slug = slugify(who); + // A known agent signs as agent:; anyone else (a person, an outside tool) as author:. + const short = [...agents].find((a) => slug === a || slug.startsWith(`${a}-`)); + const key = short ? "agent" : "author"; + const value = short || slug; + fixes.push({ kind: "unsigned", path: issue.path, detail: `${key}: ${value} (from ${how})` }); + write(abs, addFrontmatterField(text, key, value)); + } + + // 3. Links: folder form, and broken record links with exactly one candidate. + // Where each record is once the moves above are made. + const moved = new Map(fixes.filter((f) => f.kind === "misfiled").map((f) => [f.path, f.detail.replace(/^moved to shared\//, "").split("/")[0]])); + const folderOf = (r) => moved.get(rel(r.path)) || RECORD_TYPES[r.type].folder; + const byId = new Map(); + for (const r of records) byId.set(r.id, [...new Set([...(byId.get(r.id) || []), folderOf(r)])]); + const known = new Set(records.map((r) => `${folderOf(r)}/${r.id}`)); + const nested = Object.values(roots).filter((r) => r !== root && r.startsWith(root + sep)); + for (const f of markdownFiles(root)) { + if (nested.some((n) => f.startsWith(n + sep))) continue; + const text = readFileSync(f, "utf8"); + const { body } = parseFrontmatter(text); + const proseBody = prose(body); + let out = text; + const changes = []; + for (const m of proseBody.matchAll(LINK)) { + const whole = m[0]; + let ref; + try { ref = parseRef(whole); } catch { continue; } + if (ref.brain) continue; + const folder = RECORD_TYPES[ref.type].folder; + let target = `${folder}/${ref.id}`; + if (!known.has(target)) { + const options = byId.get(ref.id) || []; + if (options.length !== 1) continue; + target = `${options[0]}/${ref.id}`; + } + const current = `${m[2]}/${m[3]}`; + if (current === target) continue; + const fixed = whole.replace(`${m[2]}/${m[3]}`, target); + if (out.includes(whole)) { + out = out.split(whole).join(fixed); + changes.push(`${current} → ${target}`); + } + } + // Frontmatter links: only the links: field (tags like team/dev are not record links). + const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(out); + if (fm) { + const lines = fm[1].split("\n"); + let inLinks = false; + const fixRef = (all, open, brain, type, id, close) => { + if (brain || !RECORD_TYPES[type]) return all; + const ref = folderRef(`${type}/${id}`); + changes.push(`${type}/${id} → ${ref}`); + return `${open}${ref}${close}`; + }; + const refRe = /(\[\[|^|[\s\[,"'])([a-z0-9-]+:)?([a-z]+)\/([a-z0-9][a-z0-9._-]*)(\]\]|(?=[\s\],"']|$))/g; + for (let k = 0; k < lines.length; k++) { + const kv = /^links\s*:(.*)$/i.exec(lines[k]); + if (kv) { inLinks = true; lines[k] = "links:" + kv[1].replace(refRe, fixRef); continue; } + if (inLinks && /^\s*-\s/.test(lines[k])) { lines[k] = lines[k].replace(refRe, fixRef); continue; } + inLinks = false; + } + const block = lines.join("\n"); + if (block !== fm[1]) out = out.replace(fm[1], block); + } + if (out !== text) { + fixes.push({ kind: "links", path: rel(f), detail: [...new Set(changes)].join(", ") }); + write(f, out); + } + } + + let commit = stagedBefore ? "skipped: other changes are already staged in this repo; commit or unstage them, then run again" : "dry-run"; + if (apply && touched.size && repo) { + const existing = [...touched].filter((p) => existsSync(p)).map((p) => relative(repo, real(p))); + try { + if (existing.length) git(repo, ["add", "-A", "--", ...existing]); + const staged = git(repo, ["diff", "--cached", "--name-only"]); + if (staged) { + const who = agent ? `\n\nagent: ${agent}` : ""; + git(repo, ["-c", "user.name=" + (process.env.GIT_AUTHOR_NAME || "Brainium"), "-c", "user.email=" + (process.env.GIT_AUTHOR_EMAIL || "brainium@localhost"), "commit", "-q", "-m", `brainium: organize ${name} (${fixes.length} fix${fixes.length === 1 ? "" : "es"})${who}`]); + commit = "committed"; + } else commit = "unchanged"; + } catch (e) { + commit = `failed: ${String(e.stderr || e.message).trim().split("\n").pop()}`; + } + } else if (apply) commit = touched.size ? "no-repo" : "unchanged"; + + return { brain: name, applied: apply, fixes, skipped, commit }; +} + +export function organizeReport(r) { + const lines = [`# Organize ${r.brain}${r.applied ? "" : " (dry run)"}`, ""]; + const kinds = ["misfiled", "unsigned", "links"]; + if (!r.fixes.length) lines.push("Nothing to fix."); + for (const k of kinds) { + const f = r.fixes.filter((x) => x.kind === k); + if (!f.length) continue; + lines.push(`## ${k} (${f.length})`); + for (const x of f.slice(0, 50)) lines.push(`- \`${x.path}\`: ${x.detail}`); + if (f.length > 50) lines.push(`- … ${f.length - 50} more`); + lines.push(""); + } + if (r.skipped.length) { + lines.push(`## Left for a person or the librarian (${r.skipped.length})`); + for (const x of r.skipped.slice(0, 30)) lines.push(`- \`${x.path}\`: ${x.kind}, ${x.detail}`); + if (r.skipped.length > 30) lines.push(`- … ${r.skipped.length - 30} more`); + lines.push(""); + } + if (r.applied) lines.push(`Commit: ${r.commit}`); + else if (r.fixes.length) lines.push("Run again with --apply to make these fixes."); + return lines.join("\n").trim(); +} diff --git a/cli/lib/records.mjs b/cli/lib/records.mjs index 7d0b262..1d91ce8 100644 --- a/cli/lib/records.mjs +++ b/cli/lib/records.mjs @@ -79,7 +79,7 @@ function renderFrontmatter(meta) { // [[type/id]] with an optional brain: prefix, and Obsidian's #heading and |alias. // Either the type (person) or its folder (people) works; Brainium writes the // folder form, which Obsidian resolves as a path. -const LINK = /\[\[([a-z0-9-]+:)?([a-z]+)\/([a-z0-9][a-z0-9._-]*?)(?:\.md)?(?:#[^\]|\n]*)?(?:\|[^\]\n]*)?\]\]/g; +export const LINK = /\[\[([a-z0-9-]+:)?([a-z]+)\/([a-z0-9][a-z0-9._-]*?)(?:\.md)?(?:#[^\]|\n]*)?(?:\|[^\]\n]*)?\]\]/g; /** "people/x", "[[person/x|X]]" or "brain:project/x" -> { brain, type, id } (type may be a folder name). */ export function parseRef(ref) { @@ -105,7 +105,7 @@ function recordPath(root, type, id) { } /** Body text without fenced code blocks and `inline code`, where [[links]] are examples, not links. */ -function prose(body) { +export function prose(body) { return String(body).replace(/^(```|~~~)[\s\S]*?^\1/gm, "").replace(/`[^`\n]*`/g, ""); } @@ -205,7 +205,7 @@ export function getRecord(roots, ref, { brain = "auto", defaultBrain = "personal // --------------------------------------------------------------------------- // Lint -function markdownFiles(root, out = []) { +export function markdownFiles(root, out = []) { for (const e of readdirSync(root, { withFileTypes: true })) { if (e.name.startsWith(".") || e.name === "node_modules") continue; const p = join(root, e.name); @@ -215,7 +215,7 @@ function markdownFiles(root, out = []) { return out; } -const SIGNATURE = /^(agent|persona|from|author|created_by)\s*:|_agent: [^_]+_|_\([^)]*agent: [^)]+\)_|^\s*\**agent\**\s*:/im; +export const SIGNATURE = /^(agent|persona|from|author|created_by)\s*:|_agent: [^_]+_|_\([^)]*agent: [^)]+\)_|^\s*\**agent\**\s*:/im; /** * Check a brain. Returns { brain, checked, issues: [{ kind, path, detail }] }. diff --git a/cli/lib/routines.mjs b/cli/lib/routines.mjs index 8855865..85f4528 100644 --- a/cli/lib/routines.mjs +++ b/cli/lib/routines.mjs @@ -25,7 +25,7 @@ import { commitPaths, findRepoRoot, remoteUrl } from "./git.mjs"; export const TYPES = ["prompt", "upkeep", "shell"]; export const APPS = ["claude-code", "codex"]; -export const JOBS = ["sync", "distill", "digest", "lint"]; +export const JOBS = ["sync", "distill", "digest", "lint", "organize"]; export const STAGES = ["shadow", "limited", "full"]; // When a run is written to the brain as a session entry. "failures" logs the // first failure and the recovery after it, not every quiet success, so an @@ -756,6 +756,12 @@ async function execUpkeep(r, config, { env, since, now }) { const summary = Object.entries(counts).map(([k, n]) => `${k}: ${n}`).join(", "); return { exit: 0, output: `${h.records} records, ${h.checked} shared files checked. ${h.issues.length ? summary : "No issues."}\nReport: ${h.path}`, timedOut: false }; } + if (r.job === "organize") { + const { organizeBrain, organizeReport } = await import("./organize.mjs"); + const { brainRoots } = await import("./brain.mjs"); + const o = organizeBrain(brainRoots(config, null), r.brain, { apply: true, agent: r.agent || "librarian", now }); + return { exit: String(o.commit).startsWith("failed") ? 1 : 0, output: organizeReport(o), timedOut: false }; + } if (r.job === "distill") { const { distill } = await import("./capture.mjs"); const results = await distill(config, {}); diff --git a/cli/templates/mcp-instructions.md b/cli/templates/mcp-instructions.md index 30a51b0..6b3c643 100644 --- a/cli/templates/mcp-instructions.md +++ b/cli/templates/mcp-instructions.md @@ -3,5 +3,5 @@ Brainium is the user's second brain: git-backed memory that survives switching a - Before any work at all: call brain_preflight (pass agent) and reread every rule file it lists; it pulls the latest rules and brain. Then call brain_pending; if captured sessions are waiting, read them (brain_pending_get) and file each as a concise session entry (brain_resolve). Search (brain_search) when prior context may matter. - Projects, people, teams, customers, meetings and documents are records: record_get folder/id (e.g. projects/launch) (it follows links one hop) before searching; record_save to create or update one rather than writing a new note about it. - Before saying done on substantive work: brain_log a session; incidents as failure (+learning); preferences as memory; new/changed agent instructions via agent_card_save. -- Sign everything: pass agent: "" so every note names who wrote it. brain_lint shows what has rotted (unsigned, stale, broken links). +- Sign everything: pass agent: "" so every note names who wrote it. brain_lint shows what has rotted (unsigned, stale, broken links); brain_organize fixes what has one right answer. - Do this without being asked. Never store secrets. diff --git a/cli/test/context.test.mjs b/cli/test/context.test.mjs index 274c077..3e1dc0a 100644 --- a/cli/test/context.test.mjs +++ b/cli/test/context.test.mjs @@ -26,7 +26,7 @@ function team() { test("a new brain comes with record folders, factory templates and a weekly health check", () => { const { mojo, restore } = team(); try { - for (const f of ["shared/projects/_template.md", "shared/people/README.md", "shared/meetings/_template.md", "shared/customers/_template.md", "shared/documents/_template.md", "shared/teams/README.md", "agents/_template/prompts/_template.md", "agents/_template/evals/_template.md", "routines/brain-health.md"]) { + for (const f of ["shared/projects/_template.md", "shared/people/README.md", "shared/meetings/_template.md", "shared/customers/_template.md", "shared/documents/_template.md", "shared/teams/README.md", "agents/_template/prompts/_template.md", "agents/_template/evals/_template.md", "routines/brain-health.md", "routines/organize.md", "routines/librarian.md"]) { assert.ok(existsSync(join(mojo, f)), f); } } finally { restore(); } diff --git a/cli/test/organize.test.mjs b/cli/test/organize.test.mjs new file mode 100644 index 0000000..a8ea3fa --- /dev/null +++ b/cli/test/organize.test.mjs @@ -0,0 +1,78 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { sandbox, put, useEnv } from "./helpers.mjs"; +import { initBrain, initPersonal } from "../lib/personal.mjs"; +import { brainRoots } from "../lib/brain.mjs"; +import { addBrain, loadConfig, setConfig } from "../lib/config.mjs"; +import { lintBrain } from "../lib/records.mjs"; +import { organizeBrain, organizeReport, addFrontmatterField } from "../lib/organize.mjs"; + +const git = (cwd, ...a) => execFileSync("git", a, { cwd, stdio: "pipe", encoding: "utf8" }).trim(); + +function brain() { + const s = sandbox(); + const restore = useEnv(s.env); + initPersonal(s.personal); + const mojo = join(s.root, "mojo"); + initBrain(mojo); + addBrain("mojo", mojo, s.env); + setConfig("personalBrain", s.personal, s.env); + setConfig("rawStore", s.raw, s.env); + const commit = (msg, author = "Test ") => { git(mojo, "add", "-A"); git(mojo, "commit", "-qm", msg, "--author", author); }; + return { ...s, mojo, restore, commit, roots: () => brainRoots(loadConfig(s.env), null) }; +} + +test("organize fixes what has one right answer and leaves the rest", () => { + const { mojo, restore, commit, roots } = brain(); + try { + put(join(mojo, "agents", "tess", "card.md"), "---\nagent: tess\n---\n# Tess\n"); + // A person record filed under customers. + put(join(mojo, "shared", "customers", "sam.md"), "---\ntype: person\nrole: PM\nagent: ops\n---\n# Sam\n"); + put(join(mojo, "shared", "customers", "acme.md"), "---\ntype: customer\nstatus: active\nagent: ops\n---\n# Acme\n"); + // Old link forms and a link to the wrong folder; tags must not change. + put(join(mojo, "shared", "learnings", "a.md"), "---\nagent: ops\nlinks: [person/sam, \"[[customer/acme]]\"]\ntags: [team/qa]\n---\n# a\n\nSee [[person/sam|Sam]], [[projects/acme]] and `[[person/example]]`.\n"); + // Unsigned notes: one with an import note, one added by an agent's commit trailer, one with no evidence. + put(join(mojo, "shared", "learnings", "b.md"), "\n# b\n"); + commit("setup"); + put(join(mojo, "shared", "learnings", "c.md"), "# c\n"); + commit("add c\n\nDibble-Agent: Tess", "Some Human "); + put(join(mojo, "shared", "learnings", "d.md"), "# d\n"); + for (let i = 0; i < 45; i++) put(join(mojo, "shared", "notes", `bulk-${i}.md`), `---\nagent: ops\n---\n# ${i}\n`); + commit("bulk import"); + + const dry = organizeBrain(roots(), "mojo"); + assert.equal(dry.applied, false); + assert.ok(existsSync(join(mojo, "shared", "customers", "sam.md")), "dry run moves nothing"); + const byKind = (k) => dry.fixes.filter((f) => f.kind === k); + assert.deepEqual(byKind("misfiled").map((f) => f.detail), ["moved to shared/people/sam.md"]); + assert.deepEqual(byKind("unsigned").map((f) => [f.path, f.detail]).sort(), [ + ["shared/learnings/b.md", "agent: tess (from its import note)"], + ["shared/learnings/c.md", "agent: tess (from the commit that added it)"], + ]); + assert.ok(dry.skipped.some((s) => s.path === "shared/learnings/d.md"), "d.md came in a bulk commit: no evidence"); + assert.match(organizeReport(dry), /Run again with --apply/); + + const done = organizeBrain(roots(), "mojo", { apply: true, agent: "librarian" }); + assert.equal(done.commit, "committed"); + assert.ok(existsSync(join(mojo, "shared", "people", "sam.md")) && !existsSync(join(mojo, "shared", "customers", "sam.md"))); + const a = readFileSync(join(mojo, "shared", "learnings", "a.md"), "utf8"); + assert.match(a, /links: \[people\/sam, "\[\[customers\/acme\]\]"\]/); + assert.match(a, /tags: \[team\/qa\]/, "tags are left alone"); + assert.match(a, /\[\[people\/sam\|Sam\]\]/); + assert.match(a, /\[\[customers\/acme\]\]/, "a link to the wrong folder points at the one record with that id"); + assert.match(a, /`\[\[person\/example\]\]`/, "code is left alone"); + assert.match(readFileSync(join(mojo, "shared", "learnings", "b.md"), "utf8"), /^---\nagent: tess\n---/); + assert.match(git(mojo, "log", "-1", "--format=%B"), /organize mojo .*\n\nagent: librarian/); + const after = lintBrain(roots(), "mojo").issues; + assert.ok(!after.some((i) => i.kind === "misfiled" || i.kind === "broken-link")); + assert.equal(organizeBrain(roots(), "mojo").fixes.length, 0, "a second pass finds nothing"); + } finally { restore(); } +}); + +test("addFrontmatterField adds to existing frontmatter or creates it", () => { + assert.equal(addFrontmatterField("---\na: 1\n---\nbody\n", "agent", "x"), "---\na: 1\nagent: x\n---\nbody\n"); + assert.equal(addFrontmatterField("# t\n", "author", "y"), "---\nauthor: y\n---\n\n# t\n"); +}); diff --git a/cli/test/routines.test.mjs b/cli/test/routines.test.mjs index 3f53263..58862d2 100644 --- a/cli/test/routines.test.mjs +++ b/cli/test/routines.test.mjs @@ -67,7 +67,7 @@ test("listing finds routines per brain and reports problems", () => { put(join(mojo, "routines", "bad.md"), "---\nname: Bad\nschedule: soon\ntype: launch\n---\n"); newRoutine(config(), { brain: "mojo", name: "Brief" }); const rs = listRoutines(config()); - assert.deepEqual(rs.map((r) => r.ref), ["mojo/bad", "mojo/brain-health", "mojo/brief"]); // README and _template are skipped; brain-health comes with every brain + assert.deepEqual(rs.map((r) => r.ref), ["mojo/bad", "mojo/brain-health", "mojo/brief", "mojo/librarian", "mojo/organize"]); // README and _template are skipped; brain-health, organize and librarian come with every brain assert.match(rs[0].errors.join(" "), /type must be/); assert.match(rs[0].errors.join(" "), /schedule:/); assert.equal(rs[2].enabled, false); @@ -113,6 +113,7 @@ test("tick: waits for the first slot, starts what's due once, skips unapproved a approveRoutine(config(), "mojo/brief", env); setEnabled(config(), "mojo/brief", true); setEnabled(config(), "mojo/unapproved", true); + setEnabled(config(), "mojo/organize", false); // every brain's daily organize would be due too; this test is about the ones above const started = []; const start = (ref, when) => started.push([ref, when.toISOString()]); diff --git a/docs/CONTEXT-SYSTEM.md b/docs/CONTEXT-SYSTEM.md index 7b3a9a1..4a15a6f 100644 --- a/docs/CONTEXT-SYSTEM.md +++ b/docs/CONTEXT-SYSTEM.md @@ -78,6 +78,31 @@ Every entry the Brainium tools write names its agent (`_agent: name_` on notes, The report goes to `shared/health.md`. Team brains are checked by their own health routine. +## Organize and the librarian: the brain sorts itself + +Lint only reports rot. Two routines that come with every brain fix it, so nobody sorts notes by hand: + +**Organize** (`routines/organize.md`, daily 06:30, upkeep, on by default) makes the fixes that have exactly one right answer, then commits them: + +| Fix | How it knows | +|---|---| +| A misfiled record moves to its type's folder | its own `type:` field (it won't overwrite a record already there) | +| An unsigned shared note gets `agent:` (or `author:` for a person) | the agent folder it sits in, an `` note, an `Agent:`/`-Agent:` commit trailer, or the commit that added it (bulk commits of 40+ files and sync bots don't count) | +| `[[person/sam]]` becomes `[[people/sam]]`, in the body and in `links:` | the record folders | +| A link to a record that doesn't exist points at the one record with that id | only when there is exactly one | + +Anything ambiguous is listed as left over, not touched. Code spans, tags and other frontmatter fields are never rewritten. Run it yourself with `brainium organize [--brain NAME]` (dry run) and `--apply`, or the `brain_organize` tool. If other changes are already staged in the repo, it reports them and makes no commit. + +**Librarian** (`routines/librarian.md`, daily 07:00, a prompt routine as agent `librarian`) handles what needs judgement: + +- links each new note to the records it's about, creating a record once two notes need it +- moves notes to where they belong (an agent's private note the team needs goes to the team's `shared/`; a note in the wrong team goes to the right one), leaving a pointer behind +- merges duplicates +- signs notes whose author is clear from their content +- messages the owners of stale records + +It never deletes content. It comes off and in **shadow** stage: approve and enable it on one machine (`brainium routines approve /librarian`, then `enable`). It then only proposes changes until you move it to `stage: limited` (at most `limit` changes a run) and then `full`. + ## Routines: triggers and stages ```markdown diff --git a/docs/TEAMS-AND-ROUTINES.md b/docs/TEAMS-AND-ROUTINES.md index 831ed2b..7dbea5d 100644 --- a/docs/TEAMS-AND-ROUTINES.md +++ b/docs/TEAMS-AND-ROUTINES.md @@ -85,7 +85,7 @@ Read yesterday's shared sessions and write a short brief of what needs attention |---|---|---| | `prompt` | The prompt through Claude Code or Codex, headless, in the profile you name, as the agent | Yes | | `shell` | The first ```` ``` ```` block (or the body) with your login shell | Yes | -| `upkeep` | `job: sync` (git pull --rebase, then push this brain), `distill` (file captured sessions), `digest` (what each agent and `shared/` wrote since the last run) | No | +| `upkeep` | `job: sync` (git pull --rebase, then push this brain), `distill` (file captured sessions), `digest` (what each agent and `shared/` wrote since the last run), `lint` (health report), `organize` (mechanical tidy-up, see CONTEXT-SYSTEM.md) | No | ```bash brainium routines # next/last run, approval, problems diff --git a/package.json b/package.json index 81ac65a..b3a7d7a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "brainium", - "version": "0.5.0", + "version": "0.6.0", "description": "Git-backed agent memory for Cursor, Claude Code, Claude Desktop, Grok Bot and generic agents — project, personal and team brains with per-agent notes, scheduled routines, an MCP server, and session capture.", "type": "module", "bin": { diff --git a/scaffold/brain/routines/librarian.md b/scaffold/brain/routines/librarian.md new file mode 100644 index 0000000..ebbd07f --- /dev/null +++ b/scaffold/brain/routines/librarian.md @@ -0,0 +1,23 @@ +--- +name: Librarian +schedule: "0 7 * * *" +type: prompt +agent: librarian +stage: shadow +limit: 10 +enabled: false +--- + +You are this brain's librarian. Your job is to keep it organised so every agent finds what it needs: one place for each thing, everything linked to what it's about, nothing duplicated, nothing rotting. The daily Organize routine has already made the mechanical fixes. You handle what needs judgement. + +Start with `brain_preflight` (agent "librarian"), then `brain_lint` and `brain_organize` (dry run) to see what's left. Look at what changed since your last run: the files in `BRAINIUM_CHANGED` if it's set, or the notes dated since your last session. + +For each new or changed note: + +1. **Link it to its records.** Work out which projects, people, customers, meetings and documents it is about (`record_get folder/id`). Add `[[folder/id]]` links to the note and the note to the record (`record_save` with links). If something has no record yet but two or more notes are about it, create the record with its required fields. +2. **Put it where it belongs.** A note in an agent's own folder that the whole team needs goes to the team's `shared/`; one in the wrong team goes to the right team; a record-shaped note (about one customer, say) becomes, or merges into, that record. Move with `git mv` and leave a one-line pointer at the old path. +3. **Merge duplicates.** Notes that say the same thing become one: keep the oldest path, fold in anything new from the others, and replace them with pointers. +4. **Sign what you can.** An unsigned note whose author is clear from its content gets `agent:` (or `author:` for a person). Never guess. +5. **Flag what's stale.** A live record untouched for a month, or past `review_by`: message its owner (`shared/messages//inbox/`). Don't close it yourself. + +Rules: never delete content (merge, move or point instead). Never move a note into another team's area without saying why in its pointer. Sign everything `agent: librarian`. Finish with one session entry listing what you changed and what you left for a person, with paths. diff --git a/scaffold/brain/routines/organize.md b/scaffold/brain/routines/organize.md new file mode 100644 index 0000000..948c3b4 --- /dev/null +++ b/scaffold/brain/routines/organize.md @@ -0,0 +1,9 @@ +--- +name: Organize +schedule: "30 6 * * *" +type: upkeep +job: organize +enabled: true +--- + +Daily mechanical tidy-up: fixes the parts of the lint report that have exactly one right answer, then commits them. It moves misfiled records to their type's folder, signs unsigned shared notes from evidence (their agent folder, an import note, an `Agent:` commit trailer or the commit that added them), and rewrites old or broken record links. Anything ambiguous is left for the librarian. Upkeep jobs need no approval.