Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Cerebro is human-centric. The cortex is yours. It’s plain markdown you can read, edit, and open in any tool. AI integration is optional, not a requirement.

The problem

You have side projects. Maybe 3, maybe 10. You work on them in bursts: a flurry of commits, then months of silence.

When you return, the question is always the same:

“Wait, what work was in progress? Where did things leave off?”

You scroll through git history. You grep for TODO comments. You search your notes. By the time you remember, you’ve already lost 20 minutes.

The solution

Cerebro watches your development activity and builds a personal mission control dashboard. It aggregates:

  1. AI sessions: your AI pair-programming history with OpenCode, Pi, or both
  2. Git activity: commits, branches, and file changes
  3. TODOs: TODO, Needs Fixing, Hack, and Placeholder comments in your code
  4. Manual notes: your status, next actions, and goals

When you return to a dormant project, your dashboard answers the question in seconds.

How it works

Cerebro uses a two-repo architecture:

flowchart LR
    subgraph "Sources"
        G[Git repos]
        O[AI sessions]
    end

    subgraph "cerebro (CLI)"
        C[cerebro build]
    end

    subgraph "cortex (your data directory)"
        CT[content/ generated md]
        NB[content/notes/ manual]
        BK[book/ rendered HTML]
    end

    subgraph "cerebro-mcp"
        MS[MCP server]
    end

    subgraph "cerebro-tui"
        TUI[Terminal UI]
    end

    subgraph "Consumers"
        TERM[Terminal user]
        MDB[mdbook]
        OC[OpenCode]
    end

    G -->|scrape| C
    O -->|scrape| C
    C -->|writes| CT
    NB -. manual .-> CT
    CT -->|mdbook| BK
    NB -->|mdbook| BK
    MS -->|reads| CT
    MS -->|reads| NB
    OC <-->|JSON-RPC| MS
    TUI -->|reads| CT
    TUI -->|reads| NB
    TERM <-->|interactive| TUI

The two repos

RepoPurpose
~/Projects/cerebroSource code: command-line tool, MCP, Terminal User Interface, shared types
~/Projects/<name>Your cortex: config, generated content, manual notes, rendered HTML

The three binaries

BinaryPurposeUsed by
cerebroCommand-line tool: scrape repos, generate markdownYou, cron
cerebro-mcpMCP server: answer questions about projectsAny MCP client
cerebro-tuiTerminal UI: browse projects interactivelyYou

Content boundaries

Your cortex’s content/ has a clear split:

PathGenerated byEdit?
content/index.mdcerebroNo
content/projects/*.mdcerebroNo
content/journal/cerebroNo
content/today.mdcerebroNo
content/this-week.mdcerebroNo
content/intent/HumanYes
content/notes/HumanYes
content/SUMMARY.mdHumanYes

An AGENTS.md file in your cortex enforces the boundary. AI agents shouldn’t edit manual content.

Why it works

Cerebro succeeds when it reduces context-switching friction. You’ll notice it when:

  • You return to a project you haven’t touched in weeks
  • You have too many projects to track mentally
  • You use AI assistants and want to remember what you worked on

Key concepts

TermMeaning
CollectorA source of data: git, OpenCode, todos, or notes
GeneratorCreates output files from collected data
ProjectA repo + notes + activity you’re tracking
DashboardThe generated markdown output
CortexYour data directory: config, content, rendered book
Terminal User InterfaceTerminal UI for interactive browsing

Architecture

Cerebro is a Rust workspace with four crates:

  • cerebro: the command-line tool. It coordinates collectors and generators and manages the cache
  • cerebro-core: shared types, traits, collector implementations, and query operations
  • cerebro-mcp: an MCP server for OpenCode integration
  • cerebro-tui: a Ratatui terminal UI for browsing projects interactively

Next steps

  1. Quick start: get running in 5 minutes
  2. Dashboard guide: understand the output
  3. Configuration: customize for your projects
  4. Definition of done: the criteria 1.0.0 is meant to meet, and the two that fail today

Quick start

Get your dashboard running in 5 minutes.

1. Install

cargo install --path crates/cerebro

2. Create config

Place config.toml at the XDG default location. That’s $XDG_CONFIG_HOME/cerebro/config.toml, or ~/.config/cerebro/config.toml when XDG_CONFIG_HOME is unset. The location is the same on every platform:

[settings]
output_dir = "~/Projects/cortex/content"

[[projects]]
name = "my-project"
repo_path = "~/Projects/my-project"
active = true

Override the path with --config <file>, or set CORTEX_PATH and put config.toml in the cortex data dir. See Configuration.

3. Build

cerebro build

This generates your dashboard in the output_dir from your config. The default is ~/Projects/cortex/content/.

4. Serve

cd ~/Projects/cortex && mdbook serve --port 3456

Open http://localhost:3456 to see your dashboard.

Your first win

After a few days of use, come back to a dormant project. Instead of:

“Wait, what work was in progress? Where did things leave off?”

Your dashboard shows:

  • Last activity: 3 days ago: “feat: add user authentication”
  • OpenCode session: “Debugging JWT token refresh”
  • TODOs left: src/auth.rs:42 has “TODO: handle expired tokens”
  • Next action: from your notes, “Test the login flow”

That’s the moment cerebro earns its place in your workflow.

Next steps

Definition of done

Cerebro generates the whole fleet dashboard, cron rebuilds it three times a day (crontab -l lists 0 5,9 * * * and 59 23 * * *), and agents answer questions from that output over MCP. No file in this repository says what “done” would look like. Issue #121 records the gap, and issue #120 records the version consequence. This page is the exit predicate for 1.0.0.

Accepted by the maintainer on 2026-11-24, which makes it the standard, not a suggestion. Accepting the definition and meeting it are different acts: two criteria below fail, so cerebro-v1.0.0 cannot be cut yet and no version number moved. Each criterion below carries the command that checks it, because a criterion without a measurement is a wish. Where the definition needs judgement rather than a number, the question sits in Open questions for the maintainer instead of being answered here.

Premise

The claim cerebro makes about itself is small and testable. It says a journal page tells you what you did that day. Everything else the dashboard prints, the project pages, the statistics, the TODO list, the TUI, reads from the same collectors, so the definition anchors on the journal rather than on a feature count.

Two facts about the commit collector make that anchor the right one:

  • crates/cerebro-core/src/storage.rs:120 keeps the 20 newest commits from HEAD and drops the rest, and storage.rs:128 stores the committer instant rather than the author instant.
  • crates/cerebro/src/generators/journal.rs:40 regenerates each day page from whatever the collector returns on the day the build runs.

Put together, those mean a day page describes the moment it was built instead of the day it names. Issue #114 is open on exactly that. A definition of done that skips this fact describes a demo, not a record.

What 1.0.0 means

1.0.0 means the journal tells you what you actually did.

One sentence, six criteria, and a command beside each one. Criteria 3 and 5 fail today. Criterion 6 is partial. Criteria 1, 2, and 4 pass, each with a caveat recorded next to it, and this page says which is which.

Release predicate. A 1.0.0 tag is cut by hand, by the maintainer, on a machine where every criterion passes against his own cortex. It is never a side effect of a commit marker. See Version policy.

Criteria

Each criterion lists the command that checks it and the result of running that command on this machine on 2026-11-23. The build under test is main at 822cab9, the installed binary is cerebro 0.5.0, and the live configuration is ~/.config/cerebro/config.toml with timezone = "America/New_York" and output_dir = "/Users/ryan/Projects/cortex/content".

The lab recipes write only under a temporary directory and run with HOME pointed inside it, so they cannot write to the live cortex or the shared cache at ~/Library/Caches/cerebro/cache.json. Never run any recipe here against the real configuration with --fresh. That rewrites recorded days.

1. One page holds one local calendar day

A day page names the zone it buckets in, and every entry on it belongs to that civil day in that zone.

Measure.

page="$HOME/Projects/cortex/content/journal/2026/11/21.md"
head -2 "$page"                                    # the bucketing comment
grep -c '5040e67' "$page"                          # the 19:11 probe commit
awk '/^## /{p=$2} /^- `/{split($0,a,"`"); print p, a[2]}' "$page" |
  while read -r p h; do
    TZ=America/New_York git -C "$HOME/Projects/$p" show -s \
      --date=format-local:%Y-%m-%d --pretty=%cd "$h"
  done | sort -u

The first command must print <!-- days bucketed in America/New_York -->, which day_bucket_note() in crates/cerebro-core/src/time.rs writes into every generated day page. The second must find 5040e67, committed at 19:11 local on 21 November, which is 2026-11-22 00:11 UTC. The UTC frame that issue #113 removed filed it under 22 November. The third block resolves every hash on the page back to its stored day, and it must print one date. The last command assumes a project’s directory name matches its config name, which holds for this cortex.

Result. Pass. The comment is present, grep -c returns 1, and the last block printed a single line, 2026-11-21, for all 27 commits on the page. A clean sandbox build of a repository with commits at 14:02 and 19:11 on 21 November put both of them on journal/2026/11/21.md.

Frame caveat. Cerebro buckets the committer instant. Three activitypub-habits commits authored on 22 November sit on the 21 November page because their committer instants land there. Counting 21 November by author date gives 63 commits across 9 repositories, and by committer date gives 65. Which instant owns a day is a decision, not a bug, so it goes to Open questions.

2. Every reader finds the page the generator wrote

cerebro journal read and the MCP read_journal tool return the bytes the generator wrote, from the shipped configuration, with no per-command path argument.

Measure.

page="$HOME/Projects/cortex/content/journal/2026/11/21.md"
cerebro journal read 2026-11-21 | jq -j .content > /tmp/cli-page.md
cmp /tmp/cli-page.md "$page" && echo "CLI IDENTICAL"
printf '%s\n' \
  '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"check","version":"0"}}}' \
  '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
  '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"read_journal","arguments":{"date":"2026-11-21"}}}' |
  cerebro mcp 2>/dev/null | grep '"id"' | tail -1 |
  jq -r '.result.content[0].text' | jq -j .content > /tmp/mcp-page.md
cmp /tmp/mcp-page.md "$page" && echo "MCP IDENTICAL"

cerebro journal read 2026-11-21 must report "exists": true. A false answer here is issue #116 coming back.

Result. Pass on the configuration in use. jq -r .exists returned true, and both cmp runs reported the page byte for byte, 2672 bytes each.

Resolution caveat. The two readers agree because they apply the same rule, not because they follow settings.output_dir. The command resolves the parent of output_dir and then joins the literal content (content_root_of_config in crates/cerebro/src/main.rs, then crates/cerebro-core/src/queries/journal.rs), and the MCP server joins content under CORTEX_PATH. Both hold while output_dir ends in a directory named content, which is the documented default and this machine’s setting. A configuration that names anything else splits the generator from its readers.

Measure the split.

SB=$(mktemp -d)/split; mkdir -p "$SB/repo" "$SB/pages" "$SB/home"
printf 'work\n' > "$SB/repo/w.txt"
git -C "$SB/repo" init -q
git -C "$SB/repo" add -A
git -C "$SB/repo" -c user.name=t -c user.email=t@e.invalid commit -qm first
cat > "$SB/config.toml" <<TOML
[settings]
output_dir = "$SB/pages"
timezone = "America/New_York"

[[projects]]
name = "split"
repo_path = "$SB/repo"
active = true
TOML
HOME="$SB/home" cerebro -c "$SB/config.toml" build --fresh
find "$SB/pages/journal" -name '*.md'   # the generator wrote here
HOME="$SB/home" cerebro -c "$SB/config.toml" journal read "$(date +%F)"

Result. The build writes $SB/pages/journal/2026/11/23.md, and the read command answers "exists": false, because it looks in $SB/content. The same mismatch is a narrower form of #116 and the MCP server behaves the same way. Whether 1.0.0 owes a fix or a documented constraint is an open question.

3. A day’s contents do not depend on when the page was built

Rebuild the same day twice, with no change to that day’s history, and the page must say the same thing.

This criterion fails today. It is the one that blocks 1.0.0.

Measure the field case. Issue #114 recorded one Saturday, 2026-11-21, against real history of 60 commits in 9 repositories. Same page, same underlying day, read three times in one day.

timebuilt bypage claimed
11:2xcerebro build --fresh9 projects / 57 commits
~22:0xread again8 projects / 47 commits
23:59the 59 23 * * * cron8 projects / 27 commits

Nothing about Saturday changed between those readings. The clock moved, so the record got smaller.

Measure it yourself. The live page for the same day has not recovered.

grep -m1 '^\*\*Activity' "$HOME/Projects/cortex/content/journal/2026/11/21.md"

Result. **Activity:** 8 projects | 0 sessions | 27 commits. Other builds on this machine rewrote that page twice while this document was being written, at 08:00:09 and at 09:13:29, and both rewrites printed the same claim. The day holds 63 commits authored in the configured zone (see criterion 5 for that recipe). Two of the commits the #113 investigation pinned, 2d849d3 in zine-planner at 20:51 and dbde4c4 in listsome at 18:59, are ancestors of their HEAD and appear on no page anywhere under content/. grep -rl 2d849d3 "$HOME/Projects/cortex/content/" returns nothing.

Reproduce it in a sandbox. This is the check that does not depend on shared state. It adds five commits dated Saturday, builds, then adds seventeen commits dated Monday and builds again. Nothing about Saturday changes in between.

SB=$(mktemp -d)/cap; mkdir -p "$SB/repo" "$SB/content" "$SB/home"
cd "$SB/repo" && git init -q
git config user.name probe && git config user.email probe@example.invalid
put() { echo "$2" >> work.txt; git add -A
        GIT_AUTHOR_DATE="$1" GIT_COMMITTER_DATE="$1" git commit -qm "$2"; }
for i in 1 2 3 4 5; do put "$(printf '2026-11-21T10:%02d:00-05:00' "$i")" "saturday work $i"; done
cat > "$SB/config.toml" <<TOML
[settings]
output_dir = "$SB/content"
timezone = "America/New_York"

[[projects]]
name = "probe"
repo_path = "$SB/repo"
active = true
TOML
HOME="$SB/home" cerebro -c "$SB/config.toml" build --fresh
grep -m1 '^\*\*Activity' "$SB/content/journal/2026/11/21.md"
for i in $(seq -w 1 17); do put "$(printf '2026-11-23T10:%s:00-05:00' "$i")" "monday work $i"; done
HOME="$SB/home" cerebro -c "$SB/config.toml" build --fresh
grep -m1 '^\*\*Activity' "$SB/content/journal/2026/11/21.md"

Result. The first build prints 1 projects | 0 sessions | 5 commits. The second prints 1 projects | 0 sessions | 3 commits, while git log --pretty=%ad --date=format-local:%Y-%m-%d | grep -cx 2026-11-21 still answers 5. A busy day is also capped at 20 no matter when it is built, which is why zine-planner’s 21 commits on 2026-11-21 could never all appear.

There is a second mode, and it is worse for a record. Keep adding Monday commits until the collector returns nothing for Saturday, then build. The Saturday page is not rewritten and not pruned. It keeps the total from an earlier build, so the number on disk describes a build that no longer happened.

cd "$SB/repo"
for i in $(seq -w 1 20); do put "$(printf '2026-11-23T14:%s:00-05:00' "$i")" "monday afternoon $i"; done
stat -f '%Sm %N' -t '%F %T' "$SB/content/journal/2026/11/21.md"
HOME="$SB/home" cerebro -c "$SB/config.toml" build --fresh
stat -f '%Sm %N' -t '%F %T' "$SB/content/journal/2026/11/21.md"
grep -m1 '^\*\*Activity' "$SB/content/journal/2026/11/21.md"

Result. Both stat lines printed 2026-11-23 08:18:57, the modification time of the earlier build, and the page still claimed 3 commits after the current build found none for that day. Fixing #114 stops new loss. It does not restore pages that older builds already shrank, so the recorded history needs a decision of its own. See Open questions.

4. Hand-written notes reach the page intact

A second-level heading in a manual note survives the fold into the generated project page.

Measure. Reuse the sandbox from criterion 3.

mkdir -p "$SB/content/notes/projects"
printf '# probe\n\n## Roadmap\n\nCut the exit predicate.\n\n## Catalog\n\nNot a journal.\n' > "$SB/content/notes/projects/probe.md"
HOME="$SB/home" cerebro -c "$SB/config.toml" build --fresh
grep -n '^##\|^Cut the exit\|^Not a journal' "$SB/content/projects/probe.md"

Result. Pass for the unknown heading. The generated page carries ## Roadmap inside the Status section with its body under it, which is the fix issue #112 asked for. The grep line numbers put ## Roadmap before the body it names.

One shape is still lossy. A heading that matches a routing keyword by substring is consumed, because parse_manual_notes tests contains rather than an exact heading. The ## Catalog section in that same note moves its prose under ## Journal and loses its own label, which the same grep shows. Not a journal. sits below a ## Journal heading, and no ## Catalog heading exists in the output. The live cortex cannot show that case, because the notes named in the #112 report were rewritten by hand before the fix landed. content/notes/projects/posty.md now carries those sections at third level.

5. Answering “what did I work on yesterday” needs no re-derivation

The dashboard must be the first place you look, and the answer must stand.

Measure. Compare what the page claims to what git says about the day.

DAY=2026-11-21
total=0; repos=0
while IFS= read -r p; do
  n=$(TZ=America/New_York git -C "$p" log --pretty=%ad --date=format-local:%Y-%m-%d 2>/dev/null |
      grep -cx "$DAY")
  if [ "$n" -gt 0 ]; then repos=$((repos + 1)); total=$((total + n)); printf '%4d  %s\n' "$n" "$(basename "$p")"; fi
done <<< "$(python3 -c 'import tomllib,os
c = tomllib.load(open(os.path.expanduser("~/.config/cerebro/config.toml"), "rb"))
print("\n".join(os.path.expanduser(x["repo_path"]) for x in c["projects"] if x.get("active", True)))')"
echo "git: $total commits across $repos repos for $DAY"
grep -m1 '^\*\*Activity' "$HOME/Projects/cortex/content/journal/2026/11/21.md"

Result. Fail. git answers 63 commits across 9 repositories and the page answers 8 projects and 27 commits. The gap is uneven, so no single correction factor fixes it.

repositoryauthored on 2026-11-21on the page
zine-planner212
fretsome112
listsome11section absent
activitypub-habits69
cortex66
cerebro33
following-function22
project-plan22
yourPalRyan11

activitypub-habits reads high for the same reason the others read low. The collector sorts by the committer instant, so work committed later lands on a different day than the day it was authored. The audit that produced issue #114 counted 60 commits for that Saturday and this recipe prints 63 today, which is the same instability seen from the other side. Ground truth moves when branches move, and the page moves when the clock moves.

6. Coverage is stated honestly

Every directory cerebro discover classifies as unregistered is registered, denied by name, or written down as out of scope. Nothing sits in the gap between “the dashboard ignores it” and “nobody decided that was fine”.

Measure.

cerebro status | grep -A 4 'Project coverage'
cerebro discover | grep -A 8 'Unregistered, proposed'

Result. Partial, and the gap is small enough to name in one sitting.

Config registers 134 projects; 203 directories under /Users/ryan/Projects
Unregistered directories: 72 (5 proposed, 17 upstream clones without your commits, 26 worktrees, 15 empty, 9 denied, 0 name conflicts)
Stale config entries (path gone): 3 (cerebro-ci, cerebro-fix, rpdc.fix-logging-env-hardening)

The 17 upstream clones, 26 worktrees, 15 empty repositories, and 9 denied names are classified by ADR-0015 and each one has a reason attached, so those are honest. The 5 proposed directories and the 3 stale entries are not. None of the five are git repositories, which is why they stay proposals rather than registrations, and the three stale entries are config lines pointing at paths that no longer exist.

Coverage numbers move between runs. The audit behind issue #121 measured 207 directories, 74 unregistered, 4 proposed, 29 worktrees, and 1 stale entry, and this run measures 203, 72, 5, 26, and 3. Worktrees appear and disappear as branches are cut and removed. That is the reason this criterion is a command and not a quoted figure.

What is known to fail

  • Criterion 3, in full. Day pages are a function of build time. Issue #114 is open, the 20-commit cap is still on main at crates/cerebro-core/src/storage.rs:120, and the loss compounds because every rebuild overwrites an accurate page with one that holds fewer commits.
  • Criterion 5. The 2026-11-21 page claims 27 commits for a day that holds 63, and the numbers had to be re-derived with git log to write this page.
  • Criterion 6, in part. Five proposed directories and three stale config entries are classified but not resolved.
  • Criterion 2, in the general case. It passes on the shipped shape and breaks for an output_dir that does not end in content.
  • Issue #111, latent. discover cannot see two independent clones of one repository registered as two projects. Measured today there are no duplicate remote URLs in the config, so this is an undetected class rather than a live error. It still contradicts the coverage promise in criterion 6, because “0 name conflicts” is a true answer to the wrong question.

Criteria 1, 2, and 4 pass. Each carries a caveat that belongs to the maintainer rather than to this document.

Explicit non-goals

This definition covers the journal, the readers of the journal, the note fold, and coverage reporting. It does not cover:

  • The TUI. cerebro tui reads the same generated tree, so criterion 3 reaches it, but no criterion here tests rendering or navigation.
  • cerebro serve and mdbook. Serving is a convenience. Whether the pages are right is the predicate.
  • cerebro discover --sync-config. Criterion 6 asks whether coverage is stated honestly, not whether the apply path is safe to run unattended.
  • MCP breadth. Criterion 2 checks one read tool against the file it claims to read. It does not check the other six tools.
  • Stats, TODO accuracy, and AI session collection. No criterion measures them, so no criterion claims them.
  • Acceptance. The definition is accepted; the milestone is not met. Two criteria fail.
  • The day frame. America/New_York, permanently. Cerebro serves one operator, in Eastern time, and settings.timezone exists to pin that frame down so a build on another machine cannot silently re-date the record. It is not an invitation to treat which day work belongs to as a matter of taste. Nothing in this definition or in #114’s fix should widen that.

If any of those belong under the same predicate, that is a scope decision. It is listed below rather than folded in silently.

Open questions for the maintainer

  1. Is 1.0.0 gated on criterion 3 alone, since #114 is the only open bug among them, or on all six criteria passing together?
  2. Should the author instant or the committer instant own a day? Issue #113 deferred it and issue #114 lists it as fix option 3. The measured difference for 2026-11-21 is 63 authored commits against 65 committed ones.
  3. Do the TUI, cerebro serve, and cerebro discover belong under the same exit predicate, or does 1.0.0 describe the generator and its readers only?
  4. Is “output_dir ends in a directory named content” a supported-shape contract that the docs should state, or should the readers follow settings.output_dir exactly and take criterion 2’s general form?
  5. Does 1.0.0 require repairing recorded history? Fixing #114 protects future days. Pages that older builds already shrank, including 2026-11-21 at 27 commits against 63, stay wrong unless something backfills them, and a backfill needs the fix first.
  6. What does “documented as out of scope” mean for coverage? Registering the 5 proposed directories, naming them in settings.discovery_deny, and writing a sentence in the cortex notes are three different answers with the same effect on cerebro status.
  7. Is the accuracy bar exact equality with git log, or a stated bound? One workable bound is a day page that lists every commit the collector read and names the cap when the cap binds, which is fix option 2 of #114. That option prints the cap and keeps the loss.
  8. Should --fresh prune day pages it can no longer source, or is an orphan page that reports a stale total acceptable? Criterion 3’s second failure mode depends on this answer.
  9. Who cuts the tag, and with what opt-in, once #120’s clamp lands? This page proposes that the answer is a deliberate command, not a commit marker.

Version policy

The rule that pairs with this document lives in issue #120 and in Release process: below 1.0.0 a ! in a commit subject is an incompatibility notice, not a major. Cargo’s convention turns 0.5.0 plus ! into 0.6.0, and a major stays a human act.

The gap is measurable right now.

just release-status      # run from the repository root

It reports 0.5.0 as current and 1.0.0 as proposed. The proposal is a major because fix(deps)!: migrate chrono to jiff carries a !. Until #120’s clamp lands, just release would cut a 1.0.0 tag for a change that has nothing to do with the journal being right. That is the accident this page and that fix are meant to prevent together. The definition says what 1.0.0 means, and the clamp keeps a commit marker from meaning it.

Dashboard guide

What cerebro generates, and how to read it.

Output structure

{cerebro-dashboard}/
├── index.md                    # Your mission control
├── today.md                    # Today's activity
├── this-week.md              # This week's activity
├── projects/
│   └── {name}.md            # Per-project pages
└── journal/
    └── {year}/
        └── {mm}/
            └── {dd}.md      # Daily journal pages

Index.md: your mission control

Activity overview

The main dashboard summarizes:

SignalDetail
Projects at a glanceWhich have recent activity
Git commit countsHow much you’ve shipped
AI-assisted sessionsHow many sessions your AI coding tools logged, from OpenCode and Pi. Only shown if configured
TODO totalsWork waiting

Project cards

Each project card shows:

FieldDetail
Last activityWhen you last worked on it
Recent commitsWhat you shipped
AI-assisted sessionsSession counts logged by your AI tools
TODOsOutstanding items
StatusFrom your notes, such as “paused” or “actively developing”
Next actionYour stated next step

Projects/{name}.md: deep dive

Click any project card to see full context:

  • Repository path
  • Last activity timestamp
  • Status badge

Your notes

Whatever you’ve written in notes/projects/{name}.md:

## Status
building: integrating Stripe API

## Next
- Test webhook endpoints locally
- Deploy to staging

Git activity

Recent commits with messages, dates, and files changed.

AI-assisted sessions

AI-assisted work sessions with titles and timestamps.

TODOs

List of TODO, Needs Fixing, Hack, and Placeholder items found in code:

- TODO: handle expired JWT tokens (src/auth.rs:42)
- FIXME: race condition in cache (src/cache.rs:18)
- HACK: temporary rate limiting (src/api.rs:103)

Today.md: daily pulse

Today’s activity: the projects, sessions, and commits whose day is today in the configured time zone.

This-week.md: weekly review

This week’s activity, scoped to 7 days.

Journal/{date}.md: historical record

Daily pages with all activity for that date. A date here is a civil day, read in the time zone [settings] timezone names (this machine’s zone when the key is unset), and every page carries a comment saying which one was used. Useful for:

  • Reviewing what you accomplished
  • Identifying patterns in your work
  • Keeping a dated record of your progress

Using the dashboard

For context switching

When returning to a project:

  1. Open the dashboard
  2. Find your project by searching or clicking
  3. Read: status → next → TODOs → recent activity

For daily standup

  • Check today.md for today’s work
  • Review this-week.md for the week’s progress

For planning

  • Read your notes in each project
  • Review TODOs to see what’s left

Customization

The dashboard is just markdown. You can:

  • Add it to git for version control
  • Deploy it to a static host
  • Customize the templates in generators/
  • Add your own data sources

Terminal User Interface guide

Launch the terminal UI with:

cerebro tui

Or run the standalone binary directly:

cerebro-tui

The Terminal User Interface puts all your project activity data in one place: sessions, commits, TODOs, journal entries, and manual notes.

Layout

┌─────────────────────────────────────────────────────┐
│ Cerebro TUI                                         │
├──────────┬──────────────────────────────────────────┤
│ Dashboard│  [Content area: changes per view]       │
│ Projects │                                          │
│ Journal  │                                          │
│ TODOs    │                                          │
│ Config   │                                          │
├──────────┴──────────────────────────────────────────┤
│ r refresh  b build  Space leader  q quit  ? help    │
└─────────────────────────────────────────────────────┘

Main views

KeyAction
j / ↓Next item in sidebar
k / ↑Previous item in sidebar
TabCycle focus between sidebar and content
Shift+TabCycle focus backward
EnterSwitch to selected view from sidebar
1 / gDashboard
2Projects
3Journal
4TODOs
5 / GConfig

Leader key

Press Space then a letter to jump directly:

SequenceAction
Space dDashboard
Space pProjects
Space jJournal
Space tTODOs
Space cConfig

The leader key is active everywhere except during text input, such as journal editing, note editing, or form input. Press Esc to cancel a pending leader sequence.

Focus management

KeyAction
Right / lMove focus from sidebar to content
Left / hMove focus from content to sidebar

Views

Dashboard

Summary of all projects with session counts, commit counts, and TODO counts. Press Enter on a project to drill into its detail view.

Projects

Without a selected project, the view shows a list of all projects with activity counts. Navigate with j/k, press Enter to select.

After selecting a project, three tabs appear:

KeyTab
1Sessions
2Commits
3TODOs
TabNext tab
Shift+TabPrevious tab

Within each tab, navigate items with j/k. Press Enter on a TODO to preview its full context. Press e to edit the project’s status/next notes. Press Esc to deselect and return to the project list.

Journal

Shows journal entries from all projects. Date headers, such as ### 2026-04-25, group the entries, or the view shows a single entry per project if no date headers exist.

KeyAction
j / ↓Next entry
k / ↑Previous entry
gFirst entry
GLast entry
EnterView full entry
iEdit journal for the selected project
EscClose preview / cancel edit

Journal entries come from ## Journal sections in your project notes files under content/notes/projects/. If no journal sections exist, the view is empty.

TODOs

Aggregates TODOs from all projects. Navigate with j/k, press Enter to preview the full TODO with file context. Press Esc to close preview.

Config

Toggle project active/inactive status and add new projects. The TUI writes changes to config.toml on disk.

Global commands

KeyAction
rRefresh data from all sources
bRun cerebro build, which generates the dashboard
qQuit
?Toggle help overlay
EscClose overlays, go back

Mouse support

The keyboard is the primary way in. Mouse support is there for the moments where pointing is faster than remembering, and every click does what a key already did.

Click onDoes
A sidebar viewSwitches to it, the same as pressing Enter there
A project row on the DashboardOpens that project, the same as Enter
A tab in the Projects viewSwitches section, the same as 1/2/3
A session, commit, TODO or journal rowSelects it and opens its preview, the same as Enter
The first breadcrumb in a previewGoes back to the list, the same as Esc
A toastDismisses that toast
The help overlay or the build logCloses it

The scroll wheel moves the selection in any list or table under the cursor.

Three things are deliberate:

  • No accidental dismissals. A click lands on whichever layer sits on top, so clicking a toast dismisses that toast rather than selecting the row hiding under it. The note editor ignores clicks entirely, because a stray click outside the panel would throw away what you had typed.
  • Clicking content moves the keyboard there. When you click a list, you reasonably expect j and k to act on it. That follows the same rule l uses.
  • Scrolling is selection, not panning. The wheel moves the highlighted row, and the list scrolls far enough to keep it visible. There’s no free-scroll view of a list you haven’t selected into.

If your terminal forwards the wheel to the shell instead of the app, or you’d rather not have mouse capture at all, every mouse action has a key equivalent. The interface turns capture on when it starts and restores the previous terminal state when it exits.

What the Terminal User Interface does

  • Browse OpenCode sessions, git commits, and TODOs per project
  • View project status and next-session notes
  • Edit status and next notes directly from the TUI
  • Read journal entries from daily logs
  • Toggle project active/inactive status
  • Add new projects to config
  • Refresh data on demand
  • Build the markdown dashboard from the TUI

What the Terminal User Interface doesn’t do yet

Not supported yetDetail
Session message contentSessions show titles and timestamps but not individual messages
Session previewCan’t view the conversation inside a session
Commit diffShows commit messages but not file changes
TODO editingCan view TODOs but not mark them complete, since they’re code comments
Search/filterNo text search across sessions, commits, or TODOs yet
Activity graphNo heatmap or timeline visualization
Multi-project comparisonCan’t view two projects side by side
Git branch infoDoesn’t show current branch or uncommitted changes per project

Configuration

Cerebro reads a config.toml file. The command-line tool and TUI use the XDG default location, $XDG_CONFIG_HOME/cerebro/config.toml, or ~/.config/cerebro/config.toml when XDG_CONFIG_HOME is unset, the same on every platform. The MCP server uses CORTEX_PATH to locate the cortex data directory, falling back to ~/Projects/cortex.

Config lookup order

Cerebro checks these locations in order:

  1. --config <path> command-line flag, an explicit override
  2. XDG config dir at $XDG_CONFIG_HOME/cerebro/config.toml, falling back to $HOME/.config/cerebro/config.toml. This is the default.
  3. CORTEX_PATH env var, a legacy fallback for users who keep their config alongside the cortex data dir
  4. ./config.toml in the current working directory, as a last resort

Example configuration

[settings]
opencode_db_path = "~/.local/share/opencode/opencode.db"
pi_sessions_path = "~/.pi/agent/sessions"
output_dir = "./content"
timezone = "America/New_York"
commit_window_days = 365
max_commits = 5000

[[projects]]
name = "my-project"
repo_path = "~/Projects/my-project"
active = true

Settings

SettingRequiredDescriptionDefault
output_dirNoWhere to write the generated dashboard./content
opencode_db_pathNoPath to OpenCode’s session database. Only needed if you want OpenCode session history.None
pi_sessions_pathNoPath to Pi’s sessions directory. Only needed if you want Pi session history.None
timezoneNoIANA time zone that days are bucketed in. Unset uses this machine’s zone.Machine zone
commit_window_daysNoHow many civil days of commit history a build collects, ending with today.365
max_commitsNoCeiling on the commits one repository may return per build. Reaching it is reported on the page.5000

Time zone

timezone decides which calendar day an activity belongs to. A journal page holds one day of work as you experienced it, so evening work stays on the day’s page. Commit timestamps are stored in UTC, so without a frame of reference the pages cover roughly 19:00 to 19:00 local and evening work lands on the following day. The key fixes exactly that, for the journal/ pages, today.md, this-week.md, and the journal view in the TUI, which all read the same value.

Use an IANA name such as America/New_York or Europe/Berlin. An unknown name stops the run with a message naming the key; cerebro never falls back to UTC quietly, because a silent fallback is the bug this key exists to prevent. Every generated day page carries a comment naming the zone it was bucketed in, so the frame survives the page outliving the config that set it.

Commit window

A journal page is supposed to hold everything that happened on a day, so the collector reads a window of days rather than a count of commits. commit_window_days names that window, counted in civil days in the configured zone and ending with today. Its default, 365, matches the year of pages the journal backfills. Before issue #114 the collector returned the twenty newest commits reachable from HEAD, which meant a day page described the moment it was built: a Saturday with thirty commits on it arrived as twenty, and once a repository’s newest twenty commits were all from Monday, Saturday’s page lost its work entirely.

Set it lower only if you also want fewer journal pages. A window shorter than the pages the journal renders leaves the oldest days empty, which is the same bug in a different place.

max_commits is a guard against one pathological repository stalling a build, not a way to shorten a day: 134 projects walking a year of history each is a few thousand commits read, and an upstream clone with a quarter-million would not be. When a repository reaches the ceiling the collected list is not complete, and the page says so under a Commit history truncated marker rather than reporting a quiet low number. The same marker appears on that project’s page.

Commits are attributed to a day by their author instant. A rebase, an amend, or a merge rewrites the committer instant and leaves the author stamp alone, so a branch that moved on Sunday cannot move Saturday’s work onto Sunday’s page. Both instants are collected; only the author one decides where a commit is filed.

Project configuration

Define each project with:

SettingDescriptionRequired
nameProject nameYes
repo_pathPath to git repositoryYes
activeInclude in dashboard generationYes

Manual notes

Manual notes aren’t configured per-project. They live directly in your cortex:

PathPurposeEdited by
content/intent/Goals for daily, weekly, monthly, or yearly periodsHuman only
content/notes/Evergreen notes and documentationHuman only
content/SUMMARY.mdNavigation structureHuman only

An AGENTS.md file in your cortex defines the boundary between auto-generated and manual content. Cerebro only writes to content/index.md, content/projects/, content/journal/, content/today.md, and content/this-week.md.

Commands

Cerebro provides these commands:

Build commands

cerebro build

Generate the dashboard. Uses cached data where fresh.

cerebro build                    # Build all projects
cerebro build --project my-proj  # Build specific project
cerebro build --fresh            # Force rebuild, ignoring cache

cerebro serve

Serve the generated dashboard locally with mdBook.

cerebro serve              # Default port is 3000
cerebro serve --port 8080  # Custom port

This spawns mdbook in the configured output_dir and exits immediately. For a persistent server, run mdbook serve directly in your cortex.

Status commands

cerebro status

Check cache status for all projects, plus the project coverage signal: how many directories under projects_dir are on disk but not in config, per ADR-0015.

cerebro status

Shows last build time per project, cache TTL remaining, and any stale data.

cerebro discover

Reconcile projects_dir, default ~/Projects, against the config and print the classified difference. Discovery reads only. It writes nothing unless you pass --sync-config.

cerebro discover                  # report: what is on disk that config misses
cerebro discover --sync-config    # append the proposed [[projects]] entries

Discovery reports each directory as one of:

  • registered project
  • proposed: a git repo with commits by your configured git identity, or a non-git content directory
  • worktree of a tracked repository, attributed by the git common dir, never by name
  • upstream clone, skipped by the authorship gate because it has zero commits by you
  • empty repository, reported as informational
  • name in settings.discovery_deny, never proposed and never written
  • name conflict
  • stale config entry whose path no longer exists

--sync-config appends only. It never deletes or rewrites existing lines. Discovery reports stale entries for hand removal, because a deletion isn’t reversible by a diff a human reads. Without a git user.name/user.email configured, discovery stays report-only and refuses to apply.

Query commands

These commands read cortex data and output JSON, so you can script against them or pipe the results into other tools. Whether the answers are trustworthy enough to call the project finished is a separate question, written down in the definition of done.

cerebro projects list

List all tracked projects.

cerebro projects list              # All projects
cerebro projects list --active-only  # Only active projects

cerebro projects read <name>

Read the full context for a specific project.

cerebro projects read my-project

Returns sessions, commits, TODOs, and manual notes for the named project.

cerebro journal read <date>

Read a journal entry for a specific date.

cerebro journal read 2026-05-17

cerebro journal today

Read today’s journal entry.

cerebro journal today

cerebro intent <period> <identifier>

Read intent/goals for a period.

cerebro intent daily 2026-05-17
cerebro intent weekly 2026-W20
cerebro intent monthly 2026-05
cerebro intent yearly 2026

cerebro todos

Search TODO comments across all projects.

cerebro todos                       # All TODOs
cerebro todos --keyword FIXME       # Filter by keyword
cerebro todos --project my-project  # Filter by project

cerebro stats

Get overall cortex statistics.

cerebro stats

Returns project count, session count, commit count, TODO count, and recent activity metrics.

MCP commands

cerebro mcp

Start the MCP server. Works with any MCP-compliant client, including OpenCode, Claude, and Cursor. Reads from the cortex directory containing the config file.

cerebro mcp

Reads CORTEX_PATH to locate the cortex data dir. If unset, it falls back to ~/Projects/cortex. For command-line and TUI configuration, see Configuration.

TUI

cerebro tui

Launch the Terminal User Interface for browsing projects interactively.

cerebro tui

The Terminal User Interface shares data types with the command-line tool and cerebro-core, and reads the same cortex content that mdbook renders. You can also run it independently through the standalone cerebro-tui binary.

MCP tools reference

The cerebro MCP server provides 7 tools that let AI assistants query cortex data. All tools are thin wrappers over cerebro-core query operations.

Tool list

list_projects

List all tracked projects with their metadata.

Parameters:

NameTypeRequiredDescription
active_onlybooleanNoIf true, only return active projects. Default: true

Returns: array of project objects with name, repo_path, active status, and last activity timestamp.


read_project

Read combined generated and manual content for a specific project.

Parameters:

NameTypeRequiredDescription
namestringYesProject name to read

Returns: combined content including project config, sessions, commits, TODOs, and manual notes. It covers status, next actions, and journal excerpts.


read_journal

Read a journal entry for a specific date.

Parameters:

NameTypeRequiredDescription
datestringYesDate in YYYY-MM-DD format

Returns: journal entry content for the specified date, or empty if no entry exists.


read_today

Read today’s journal entry.

Parameters: none

Returns: today’s journal entry content, or empty if no entry exists for today.


read_intent

Read intent/goals for a specific period.

Parameters:

NameTypeRequiredDescription
periodstringYesPeriod type: daily, weekly, monthly, or yearly
identifierstringYesPeriod identifier, such as 2026-04-15 for daily, 2026-W15 for weekly, 2026-04 for monthly, 2026 for yearly

Returns: intent/goals content for the specified period.


search_todos

Search TODO comments across all projects.

Parameters:

NameTypeRequiredDescription
keywordstringNoFilter by keyword type, one of TODO, Needs Fixing, Hack, or Placeholder
projectstringNoFilter by project name

Returns: array of TODO items with path, line number, keyword type, and comment text.


get_stats

Get overall cortex statistics.

Parameters: none

Returns: statistics including project count, total TODO count, session count, commit count, and recent activity metrics.

Configuration

The MCP server reads CORTEX_PATH to locate the cortex data directory. If unset, it falls back to ~/Projects/cortex. Most users with the default layout don’t need to set it.

Start it from any MCP-compliant client. The example below uses OpenCode:

{
  "mcpServers": {
    "cerebro": {
      "command": "cerebro",
      "args": ["mcp"],
      "env": {
        "CORTEX_PATH": "/path/to/cortex"
      }
    }
  }
}

Configure the command and environment variables according to your client’s documentation. The server speaks standard MCP, JSON-RPC, and doesn’t depend on any specific client.

Command-line tool equivalents

Each MCP tool has a matching cerebro command that returns the same data in human-readable form. If you don’t use an AI assistant, run those commands to query your cortex from the terminal.

MCP toolCommand-line tool equivalent
list_projectscerebro projects list
read_projectcerebro projects read <name>
read_journalcerebro journal read <date>
read_todaycerebro journal today
read_intentcerebro intent <period> <identifier>
search_todoscerebro todos
get_statscerebro stats

Troubleshooting

Common issues and solutions.

Installation

“Command not found: cerebro”

The just install-* recipes place the binaries in ~/.local/bin. Make sure it is in your PATH:

export PATH="$HOME/.local/bin:$PATH"

Add this to your shell profile, such as ~/.zshrc or ~/.bashrc, to persist.

“Couldn’t find cerebro”

Cerebro is not published to crates.io: every crate is publish = false and depends on its siblings by path (ADR-0012), so cargo install cerebro finds nothing. Install from a checkout of the repository instead. From the repo root:

just install-all   # CLI, MCP, and TUI into ~/.local/bin, then verifies them

Without just, install the cerebro package by path. The workspace root is a virtual manifest, so cargo install --path . errors with “found a virtual manifest”; point at the crate directory:

cargo install --path crates/cerebro --locked

Configuration

“Config file not found”

Cerebro reads its config from the XDG location by default: $XDG_CONFIG_HOME/cerebro/config.toml, or ~/.config/cerebro/config.toml when XDG_CONFIG_HOME is unset. Create it there:

mkdir -p ~/.config/cerebro
cp config.toml.example ~/.config/cerebro/config.toml

Or create it by hand:

[settings]
opencode_db_path = "~/.local/share/opencode/opencode.db"
pi_sessions_path = "~/.pi/agent/sessions"
output_dir = "./content"

[[projects]]
name = "my-project"
repo_path = "~/Projects/my-project"
active = true

“Couldn’t parse config”

Check your TOML syntax:

  • Use = not :
  • String values need quotes: "path" not path
  • Arrays use brackets: [[projects]] not [projects]

Validate with:

cerebro build

“Repo not found”

Verify repo_path exists:

ls -la ~/Projects/my-project

Build

“No activity found”

Likely causes:

CauseFix
No git commits yetCommit something first
No AI sessionsOnly relevant if you’ve configured opencode_db_path or pi_sessions_path
No TODOsAdd a TODO or Needs Fixing comment

This is normal for new projects. Activity appears as you work.

“Build is slow”

First build can be slow on large repos. Subsequent builds use cache.

Force a fresh build:

cerebro build --fresh

Delete the cache file (cache.json) from the platform cache dir:

rm ~/Library/Caches/cerebro/cache.json   # macOS
rm ~/.cache/cerebro/cache.json           # Linux

“OpenCode database not found”

Set the correct path in config:

opencode_db_path = "~/.local/share/opencode/opencode.db"

Verify the file exists:

ls -la ~/.local/share/opencode/opencode.db

MCP server

“MCP tools not available”

Restart OpenCode after configuring the MCP server.

Set CORTEX_PATH if your cortex data dir isn’t at the default ~/Projects/cortex. Use an expanded path (a leading ~ inside quotes is not expanded by the shell):

export CORTEX_PATH="$HOME/Projects/my-data-dir"

Test the server directly:

cargo run -p cerebro-mcp   # from a source checkout
cerebro mcp                # the installed binary

“No projects found in MCP”

Verify your config includes the project and it’s set to active = true.

Serving

“Port already in use”

Pick a different port:

cerebro serve --port 3001

“Dashboard not updating”

Rebuild with --fresh:

cerebro build --fresh

Then refresh your browser.

General

“Unexpected behavior”

Run with debug logging:

RUST_LOG=debug cargo run -- build

“It’s broken and the cause is unclear”

Clear everything and start fresh:

# Remove the generated content (output_dir from your config)
rm -rf ~/Projects/cortex/content

# Remove cache
rm -rf ~/Library/Caches/cerebro  # macOS
rm -rf ~/.cache/cerebro          # Linux

# Rebuild
cerebro build --fresh

Development setup

Prerequisites

  • Rust 1.85 or later
  • Cargo, included with Rust

Building

# Development build
cargo build

# Release build
cargo build --release

Testing

cargo test

Quality checks

# Format check
cargo fmt --check

# Lint check
cargo clippy -- -D warnings

# All quality checks
cargo check

Workspace structure

cerebro/
├── crates/
│   ├── cerebro/        # CLI tool
│   ├── cerebro-core/   # Shared types
│   ├── cerebro-mcp/    # MCP server
│   └── cerebro-tui/    # Terminal UI
├── docs/              # Documentation
└── book.toml         # mdbook config

Running locally

# Build and run
cargo run -- build

# With arguments
cargo run -- build --project my-project

MCP server

The MCP server lives in crates/cerebro-mcp/ and provides MCP tools for querying cortex data.

Building

cargo build --release -p cerebro-mcp

The binary is output to target/release/cerebro-mcp.

Running

# Via cargo
cargo run -p cerebro-mcp

# Or directly
./target/release/cerebro-mcp

Environment variables

VariableDefaultDescription
CORTEX_PATH~/Projects/cortex for cerebro-mcp, unset for cerebro and cerebro-tuiPath to the cortex data directory. cerebro-mcp reads generated content from it. For cerebro and cerebro-tui it’s a legacy fallback for config lookup. Both prefer the XDG config at ~/.config/cerebro/config.toml and fall through to CORTEX_PATH only if no XDG config exists.
RUST_LOGinfoLog level: debug, info, warn, or error

Testing guide

Cerebro uses a multi-layer testing strategy across its four crates.

Running tests

cargo test --workspace          # All tests
cargo test -p cerebro-core      # Core library only
cargo test -p cerebro-mcp       # MCP server only
cargo test -p cerebro-tui       # TUI only
cargo test -- --nocapture       # Show stdout during tests

Test layers

Unit tests

Each module contains #[cfg(test)] blocks testing individual functions, methods, and state transitions. These are the fastest and most common tests.

Examples:

  • Collector parsing, including TODO regular expression matching and git commit parsing
  • Action enum serialization/deserialization
  • Key binding resolution
  • Input mode state checks
  • Config loading and validation

Integration tests

The TUI crate uses ratatui::backend::TestBackend to render components to an in-memory buffer and assert on the rendered content:

#![allow(unused)]
fn main() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend)?;
// Render component, assert buffer string
}

For full app lifecycle tests, construct Home directly with mock dependencies, call set_cerebro_config() and do_initial_load_sync().await, then render the terminal and assert against it.

Navigation tests verify home.view_name() changes, not just that text appears somewhere in the buffer, since sidebar text is always visible.

Behavior-driven development tests

Write user-facing scenarios in Gherkin with step definitions in tests/cucumber.rs. The BDD workflow:

  1. Write Gherkin scenarios describing user behavior in terms of what the user does and sees
  2. Write step definitions that assert against real component state, such as home.view_name()
  3. Run: must go red before implementation changes
  4. Implement to make it green
  5. Commit only when the full suite passes

Step definitions must never assert against buffer text that happens to match. That produces false positives. Always check component state directly.

System tests with Ghostty

The TUI has system-level tests using Ghostty devtools for:

  • Terminal lifecycle, including startup, shutdown, and panic recovery
  • Layout adaptation on resize
  • UI responsiveness during long operations

These tests run against the actual binary in a real terminal, not a mock backend.

Test coverage by crate

CrateUnitIntegrationBDDSystem
cerebroConfig, cache, generators———
cerebro-coreCollectors, types, queries———
cerebro-mcpServer setup———
cerebro-tuiComponents, actions, key bindingsFull app renderUser scenariosGhostty lifecycle

Adding tests

Adding a new component: add at least one snapshot test using assert_buffer_snapshot! to verify rendered output.

Adding a new function or method: add unit tests for happy path and edge cases.

Fixing a bug: add a regression test that would have caught the bug.

Refactoring: ensure existing tests still pass. Add tests if coverage was zero.

Release process

A cerebro release is a git tag and a Codeberg release page. Nothing goes to crates.io: all four crates are publish = false, they depend on each other by path, and cargo package can’t resolve a path dependency from a registry. That’s the whole story in ADR-0012.

What a release looks like

main  ──▶  just release  ──▶  release PR  ──▶  merge  ──▶  CI publishes
           bump + changelog                  reviewed     tag + release page
           + lockfile

One version covers the whole workspace. All four crates inherit [workspace.package] version, so one tag names one release: cerebro-v0.3.0.

Cutting one

just release-status   # what Cargo.toml says vs. what the commits propose
just release          # branch, changelog section, version bump, one commit

just release needs cargo and git-cliff. Install git-cliff with cargo install git-cliff --locked. It writes nothing to the forge and prints the two commands that follow:

git push -u codeberg release/cerebro-v0.3.0
fj pr create 'chore(release): cerebro-v0.3.0' --base main

One commit goes on that branch, carrying three files: CHANGELOG.md with the new section, Cargo.toml with the version, and Cargo.lock re-resolved to match. All four crates inherit [workspace.package] version, so the lock moves with the manifest or it quietly disagrees with every release tag until someone’s build rewrites it.

Read the changelog section in that diff. It comes from commit subjects, and a subject that needs rewording is cheaper to fix in the release PR than on a published release page.

Once the PR merges, CI publishes on its own. The push to main leaves the manifest ahead of the last tag, so scripts/release.sh publish posts one release with that version’s changelog section as the body, and Codeberg creates the tag pointing at the commit CI built. On any other push to main it prints “already released” and exits 0.

To see what CI would do without doing it:

just release-preview

Version numbers

Commit types decide the bump, since the last cerebro-v* tag:

Commits since the last tagBumpExample
fix:patch0.2.2 → 0.2.3
feat:minor0.2.2 → 0.3.0
feat!: or a BREAKING CHANGE: footer, below 1.0.0minor0.5.0 → 0.6.0
feat!: or a BREAKING CHANGE: footer, from 1.0.0major1.4.2 → 2.0.0
build:, ci:, chore:, style:, test: onlynone0.2.2 → nothing to release

Commit subjects follow conventional commits because they’re the release notes. The commit-msg hook runs cog verify, which enforces the format.

Breaking changes below 1.0.0

SemVer §4 says a 0.x release is initial development: the public API promises no stability, and anything may change in any release. A ! below 1.0.0 is therefore information for consumers, not a claim the tooling is entitled to make on their behalf. scripts/release.sh clamps it: when the current version is 0.x and conventional commits ask for a major, the release is the next minor instead. An unreleased fix(deps)! at 0.5.0 cuts 0.6.0. Only the number moves. cliff.toml stays as it is, so the 0.6.0 section still opens that entry with [**breaking**] and names every affected surface. Clamping a version is not softening a changelog, and just release-status says which number it clamped and why.

A major is still available. It has to be asked for by name, and that is the only way one happens while the current major is 0:

CEREBRO_RELEASE_MAJOR=1 just release   # or: just release-major

release-major is the same command with the variable set, listed by just --list so the escape hatch is not buried in this page.

The variable is an opt-in, not an instruction. It lets through the major git-cliff worked out, and it invents nothing: with no breaking commit in range the proposal is still a patch or a minor. Any other value stops the script with a message instead of guessing, because a typo that quietly published 1.0.0 is the exact failure this rule exists to prevent. From 1.0.0 upward the variable is not needed, and a ! means a major there as it always has.

Releasing by hand

If CI is unavailable, the same API call works from a laptop. It’s the exact request publish makes:

version=$(bash scripts/release.sh version)
notes=$(bash scripts/release.sh notes "$version")

Don’t git push a tag by hand. The forge cuts the tag as it creates the release, which keeps the tag, the release page, and the commit CI tested in agreement.

Tests

bash scripts/release-test.sh

Scratch git repositories, a stubbed curl, and assertions on every decision: which line bump rewrites, what next proposes for each commit type, how the pre-1.0 clamp and its CEREBRO_RELEASE_MAJOR opt-in behave, whether notes stops at the next section, and the publish branches (no-op, publish once, stand down after the tag exists, refuse without notes or a token). It runs in the CI test step and inside just test, so a broken release script can’t merge quietly.

AI workflow audit plan

Based on Dru Knox, Stop Prompting, Start Engineering, YouTube, February 25, 2026.

This document lists the infrastructure changes needed to improve how cerebro manages AI workflows. The goal is to treat AI context and session behavior as observable, measurable systems, not as opaque chat sessions.

Mindset: from individual contributor to tech lead

When using AI agents, the human role shifts from individual contributor to tech lead. The job is no longer writing all the code directly. It’s ensuring the team writes good code by maintaining standards, documentation, and quality gates.

This document notes this shift but requires no tool changes. It’s a framing device for the infrastructure decisions that follow.

Problem: non-deterministic tooling waste

AI agents are non-deterministic. They repeat tasks, thrash between approaches, make unnecessary tool calls, and burn tokens on false paths. Without telemetry, this waste is invisible. Instrument the agent’s behavior to detect and eliminate waste programmatically, not by watching every session.

Audit infrastructure

Session log analysis scripts

OpenCode stores session logs locally in SQLite at ~/.local/share/opencode/opencode.db. Cerebro already reads that database for dashboard rendering. Add analysis scripts to extract waste patterns from session history.

Waste patterns to detect

PatternDescriptionSignal
ThrashingAgent switches approaches repeatedly without progressSame tool called >3x with similar args in one session
Retry loopsAgent retries after failures without changing strategycargo check fails, agent reruns same command
Over-toolingAgent uses tools when direct reasoning sufficesFile read followed by immediate file read of same content
Apology taxAgent apologizes and backtracksAssistant messages containing sorry or you're absolutely right
Token bloatContext window fills with redundant planningRepeated restatement of plan without new information

Proposed script: cerebro audit sessions

A new command-line tool subcommand, or standalone script in scripts/, that:

  1. Queries the opencode database for recent sessions
  2. Parses message history for waste patterns
  3. Outputs a summary report with:
    • Sessions analyzed
    • Waste events detected, grouped by category
    • Estimated token cost of waste
    • Suggested configuration changes

Example output:

Sessions analyzed: 12
Thrashing events: 3 (25% of sessions)
Retry loops: 7 (58% of sessions)
Over-tooling: 2 (17% of sessions)

Top suggestion: Add `cargo check` pre-validation to agent context
  Affected sessions: 5
  Waste pattern: Agent runs `cargo check`, sees error, proposes fix,
                 runs `cargo check` again without applying fix first.

Static analysis for hallucination prevention

As agents perform more divergent and inductive reasoning, the risk of hallucinated APIs, incorrect types, and phantom dependencies increases. Static analysis is the first line of defense: it catches nonsense before it compiles.

The project already enforces clippy::pedantic at the workspace level. This section proposes expanding that enforcement specifically for AI-generated code paths.

Current state

The project already forbids unwrap(), panic!(), and expect() in production code. Keep that rule and extend it to more checks.

Proposed additions

CheckPurposeHow
Import validationPrevent phantom crate referencescargo check in CI must pass before any PR
Type strictnessPrevent inferred-type hallucinationsEnable clippy::pedantic lints that reject implicit conversions
Documentation coverageForce agents to document public APIscargo doc --no-deps must pass without warnings
Dead code detectionCatch abandoned experimentsclippy::dead_code as deny, not warn
TODO/Needs Fixing enforcementPrevent permanent placeholder codeAlready exists. Ensure it runs on AI-generated commits too

Pre-flight hook for agent sessions

Consider a lightweight cargo alias or script that agents run before submitting:

# In .cargo/config.toml or agent context
[alias]
preflight = "fmt --check && clippy --workspace -- -D warnings && check"

Instruct agents to run cargo preflight before declaring a task complete. This catches hallucinations at the agent’s workstation, not in CI.

Configuration to prevent thrashing

OpenCode and similar agents accept configuration that shapes their behavior. Codify anti-thrashing settings in the project’s AGENTS.md and explore opencode configuration options.

Token budget awareness

SettingSuggestionRationale
Context window limitExplicitly state the project’s preferred maxPrevents agents from stuffing irrelevant files into context
Tool call budgetConfigure max sequential tool callsForces agent to reason rather than search
Retry limitCap retries at 2 with forced pausePrevents infinite retry loops on flaky operations

Context hygiene rules

Add to AGENTS.md:

## Agent Efficiency Rules

1. **Run `cargo preflight` before every completion claim.**
2. **If a command fails twice with the same error, stop and ask.**
3. **Do not read a file you already read in this session unless it changed.**
4. **Before using a new crate or API, verify it exists in `Cargo.lock`.**
5. **Keep context focused: only include files relevant to the current task.**

CI/CD integration

The project already runs Woodpecker CI. The audit plan should extend CI to catch AI workflow regressions.

Proposed CI checks

StageCheckTrigger
Lintcargo clippy --workspace -- -D warningsEvery push
Formatcargo fmt --checkEvery push
Doccargo doc --no-depsEvery push
Testcargo test --workspaceEvery push
AuditRun session waste analyzer on last 7 daysWeekly cron, or run manually

The weekly audit stage is lightweight: it queries the local opencode database, or a centralized copy, and posts a summary comment on the PR if waste patterns spike.

Plugin and linter integration

Rather than building custom LLM-as-judge evals, use existing tools and explore opencode plugins that reduce waste.

Tool inventory

ToolCurrent UseAI Workflow Enhancement
clippyLint enforcementAdd lints that catch common AI mistakes, such as unused imports from hallucinated code
cargo-denyLicense checkingCould extend to detect unexpected crate additions
lefthookPre-commit hooksAdd hook that warns if AGENTS.md context is stale
dprintMarkdown formattingEnsure AGENTS.md and context files stay parseable

Opencode plugin opportunities

The opencode ecosystem may support plugins that:

  • Intercept tool calls and cache file reads for the session duration
  • Enforce a “budget” of tool calls per task
  • Auto-run cargo preflight before allowing the agent to report success
  • Summarize session waste and append it to the cortex journal

These are research items. This plan flags them for investigation.

Measurement: tracked metrics

The audit infrastructure collects:

MetricSourceTarget
Session durationopencode.dbReduce median by 20%
Tool calls per sessionopencode.dbReduce median by 30%
cargo check failures before successopencode.db + git logReduce retry rate below 10%
Clippy warnings on AI-generated commitsgit diff + cargo clippyZero warnings
Agent backtracks, such as saying sorry or you're rightopencode.db message textReduce by 50%

Immediate actions

  1. Write the session analyzer script. A standalone Rust binary or Python script that reads opencode.db and outputs waste statistics.
  2. Update AGENTS.md with agent efficiency rules. Codify the anti-thrashing guidelines.
  3. Add cargo preflight alias. Make it trivial for agents to self-check.
  4. Schedule weekly CI audit job. Run the analyzer and surface trends.
  5. Research opencode plugin API. Determine if custom plugins can enforce tool budgets.

Deferred actions

  • Evals / statistical testing. Not pursued. The cost of LLM-as-judge evals outweighs the benefit for this project. The project uses deterministic static analysis instead.
  • Automated context updates via PR scanning. Interesting, but requires a stable context format first. Revisit after the AGENTS.md structure matures.

References

  • Dru Knox, “Stop Prompting, Start Engineering: The ‘Context as Code’ Shift,” YouTube, February 25, 2026
  • Cerebro AGENTS.md, the current agent guidelines
  • Architecture Decision Record 0005, the existing OpenCode integration

Rust-standard alignment wayfinding map

Destination

Cerebro’s quality gates match ~/Projects/rust-standard: every gate defined exactly once in the justfile, mirrored by lefthook and Woodpecker calling those same targets. The lint table is deny/forbid (not warn), the panic classes are denied in production and permitted in tests, the supply chain has a cargo-deny gate with a declared platform promise, the four test layers run in CI, prose is gated at error level, and commit grammar is enforced. Divergences from the standard exist only where an ADR argues for them.

Notes

  • Standard source: ~/Projects/rust-standard/docs/standard/*.md (overview, toolchain, lints, tasks-and-hooks, testing, prose, supply chain, ci-and-release).
  • Cerebro is a 4-crate workspace on Codeberg, Woodpecker CI, nightly toolchain, Rust 2024, MSRV 1.85. See ADR-0002.
  • Standing preference (AGENTS.md): never commit to main; work in worktrees; rebase before PR; no suppressions that cheat the linter; warnings are fixed at root cause. Every phase lands green under just quality.
  • The full gap analysis (tools present / partial / missing) is in the session that produced ADR-0016/0017/0018; the map below is the executable version.
  • Sequencing principle: config-only gates before mass code edits; mechanical reformatting before the big lint PRs; dated toolchain pin before any deny/forbid flip (nursery/pedantic denies are only safe under a pin).

Decisions so far

Ruled 2026-10-26 via T16: all three accepted with adrs status.

  • ADR-0016, keep adr-tools compatible mode; do NOT migrate to the standard’s NextGen/docs/adr. Links stay hand-written.
  • ADR-0017, refactor XDG config to an injected env so the 14 test unsafe blocks disappear, THEN adopt forbid(unsafe_code). Prerequisite gate for the lint-table phase.
  • ADR-0018, do not adopt cargo-dist’s host/CI layer (GitHub-only, upstream #1781 open); close the platform-promise + cross-check gaps with deny.toml [graph].targets + a Woodpecker cross-check step instead.

Closed task findings:

  • T01, dated pin nightly-2026-09-19 live; just rust-roll-forward bumps from the dist release date (version strings report the commit date, one day behind).
  • T07, nursery deny in cerebro-core is 15 findings; pedantic deny was already enforced by CI’s -D warnings. Correction from T08: the “15 total” undercounted: core’s own failure masked the dependent crates; real volume was ~250, and 136 of those are macro-generated trivial_regex in the cucumber harness.
  • T02, rustfmt.toml + clippy.toml live; one-time import-grouping reflow landed on main via #89 (50 files, mechanical commit).
  • T08, deny/forbid table adopted; clippy is clean without any -D flag. Remaining exceptions by plan: missing_docs (T11), unsafe_code (T12), one scoped test-only trivial_regex allow.
  • T12, Env/ProcessEnv seam in cerebro-core; zero-arg public API kept, tests run on injected maps, forbid(unsafe_code) live. Closes the last hold on the T08 table.
  • T09, panic classes denied workspace-wide; the “~460 backlog” was grep noise (test code + unwrap_or shapes), real production fixes were 9 call sites plus a command-line crate-root print allow and four scoped, reason-carrying test allows. exit/todo/dbg had zero findings.
  • T03, cargo-deny live (just deny, pre-push on graph files, CI deny step). Five advisory fixes taken in-range; three unreachable git2 0.19 unsound advisories ignored with reasons, tracked for retirement by T18.
  • T10, indexing/arithmetic/as_conversions denied workspace-wide; ~169 sites fixed at root cause (saturating math, get-with-default on layout rects, slice patterns, usize::from, chrono checked/signed_duration_since). No per-crate split needed. Measurement lesson: a denied lint in a dependency stops the dependents from being linted at all; measure per crate in dependency order.
  • T05, MD013 off by adopting the standard (the cap only ever fired on GSD-generated AGENTS.md lines); rumdl fmt fixed 119 findings, 3 by hand; gate defined once as just md-lint, wired to lefthook *.md and a Woodpecker md-lint step. Scope drift recorded for T13/T06: rumdl gates README+AGENTS, vale still docs-only.
  • T11, missing_docs denied; 309 findings fixed at declaration sites across all four crates, zero suppressions. cargo doc --workspace now builds clean (three pre-existing private-link findings de-linked along the way). Two new doctest examples for core’s pure functions; the doctest layer runs 3 and passes.
  • T06, the justfile defines every gate once: just ci is fmt-check lint test doctest deny docs, lefthook and the Woodpecker steps call those targets, and the clippy --all-targets drift between hook and CI is gone. nextest is the runner with the ADR 11 cucumber shim landed (415 tests, 0 skipped), .config/nextest.toml records retries = 0 and the sixty-second slow-timeout, and the CI test step drops the redundant separate cucumber line. The dead check-cortex hook (root: "Content/", a directory that does not exist; the gate never ran) and lefthook’s duplicate manual command groups are deleted.
  • T04, nextest against the cucumber binary with no shim errors (exit 104), it never silently greens the binary itself; the ADR-11 shim verified working (76/409 scenarios pass, failures flip red) with two gotchas: no libtest count footer in terse output, and the --ignored list pass must return empty or nextest skips the unit and reports green anyway. Baselines: 415 tests, nextest about 25 seconds vs cargo test about 40 seconds, slowest test 12.6 seconds. Feeds T06’s just test shape; doctest layer mandatory (nextest runs 0 doctests).

Not yet specified (fog)

  • Vale error-level findings count today: the gate moves from warning to error; how many findings that hides (and whether any are real) is unmeasured.
  • Whether .adr-dir legacy marker should stay (ADR-0016 says yes for adr-tools consumers), revisit only if a consumer actually breaks.
  • Whether to pin mdbook-mermaid builds alongside mdbook versions: local mdbook build warns the preprocessor was built against 0.5.0 while 0.5.4 calls it. It predates T06 and is harmless today; unmeasured otherwise.

Out of scope

  • Migrating cerebro to the rust-standard template wholesale (cargo-generate).
  • Changing the four-collector data model (ADR-0003/0015), unrelated to gates.
  • mdBook→other doc engine; mdBook stays (ADR-0004).
  • Criterion/PPU benchmarking beyond the standard’s just bench libtest floor.

Tickets (the frontier)

Open, unblocked tickets are the frontier. A ticket is unblocked when every depends_on entry is status: complete.

Roll-up

T01 Pin the toolchain to a dated nightly

Question

Replace rolling channel = "nightly" with a dated nightly pin (the one currently passing CI, from rustc --version) plus components = ["rustfmt", "clippy", "rust-analyzer"], so the nursery and pedantic denies later are safe under a deliberate bump, per the standard’s toolchain.md / ADR 5.

Exit predicate

rust-toolchain.toml names a dated nightly with the three components; just quality (T06 form) is green; rust-roll-forward recipe is updated to bump the date and re-run the gate. No lint-level flips ride in this commit.

Resolution

Done 2026-10-30. rust-toolchain.toml pins nightly-2026-09-19 with components = ["rustfmt", "clippy", "rust-analyzer"], the toolchain on which just quality was re-run and passed in full (fmt, clippy --all-targets, workspace tests, release script suite, vale). CI fetches the same dated artifact; the pipelines on this pull request verify the pin remotely.

just rust-roll-forward now reads the release date from static.rust-lang.org/dist/channel-rust-nightly.toml and rewrites only the channel line, preserving the file’s comments. Discovery along the way: rustc --version reports the commit date, one day behind the release date of the nightly channel: deriving the pin from the version string lands a day-early channel that may not exist. The date is also read via a temp file, not a pipe: awk exits early, which closes the pipe and makes curl fail under pipefail.

No lint-level flips rode in, per the exit predicate. Unblocks T02, T07, and the T08 chain.

T02 Add rustfmt.toml and clippy.toml

Question

Cerebro has neither config. Add:

  • rustfmt.toml with the import and comment knobs that require a nightly rustfmt (imports_granularity = "Module", group_imports = "StdExternalCrate", wrap_comments = true, comment_width = 100, max_width = 100, edition 2024). Then one-time cargo fmt as its own mechanical PR (no other edits) so later lint-fix PRs don’t collide with the reflow.
  • clippy.toml with the four test exceptions: allow-expect-in-tests, allow-unwrap-in-tests, allow-panic-in-tests, allow-indexing-slicing-in-tests (the standard permits the panic classes in tests; ADR 6).

Exit predicate

cargo fmt --check green with the new config; clippy.toml present; the fmt diff is a standalone commit on its worktree branch.

Resolution

Done 2026-10-31 on the pinned nightly (T01).

  • clippy.toml: the four test exceptions (allow-expect-in-tests, allow-unwrap-in-tests, allow-panic-in-tests, allow-indexing-slicing-in-tests). Inert until T09 denies the panic classes in production; lands as its own commit.
  • rustfmt.toml: imports_granularity = "Module", group_imports = "StdExternalCrate", wrap_comments, comment_width = 100, max_width = 100, edition 2024, field-init and try shorthands.
  • One-time cargo fmt --all: 50 files, +252/−163, dominated by import regrouping; committed separately from the config so the reflow diff stays mechanically reviewable. The map’s closed-findings row for T02 is deferred to a later bookkeeping edit on purpose: #88 edits the map right now and this PR avoids the collision by touching only this ticket file.

Gate evidence: cargo fmt --all -- --check clean; just quality fully green under the new configs (clippy --all-targets -D warnings, workspace tests, release-script suite 70/70, vale 0/0).

T03 Add a cargo-deny gate

Question

deny.toml is entirely absent. Add it per the standard’s supply chain page and wire just deny:

  • [bans] wildcards = "deny", exhaustive [licenses] allow list derived from the actual ~447-package graph (run cargo deny check licenses first to enumerate the real licences), workspace crate checked not skipped.
  • [advisories] RustSec scan; [sources] crates.io-only (deny unknown git and registries).
  • [graph].targets, leave a stub pointing at T14, which owns the target list.

Exit predicate

cargo deny check passes; just deny recipe exists and is listed in the T06 gate consolidation; no wildcard deps remain (or an allow-with-reason records each exception).

Resolution

Done 2026-10-31. deny.toml passes all four checks (exit 0) and is wired three places: just deny, a lefthook pre-push command globbed to {Cargo.toml,Cargo.lock,deny.toml} (running the same just target, not a copy), and a CI deny step via binstall.

What the first run found, triaged:

  • Licences: rejections were Unicode-3.0 (ICU, unavoidable via url→idna and every proc-macro’s unicode-ident), MPL-2.0 (only option-ext, via dirs), and Zlib. All OSI-approved permissive/file-copyleft; allow list taken from the rust-standard template’s exhaustive set. Five unused entries warn on purpose: promoting a new licence family is now a config edit with a reason.
  • Wildcards: the four bans FAILED hits were all workspace-internal path deps (version-less by design, publish = false). Skipped by name in [[bans.skip]]; the first attempt carried a reason key, which cargo-deny rejects, so the rationale lives in TOML comments instead.
  • Advisories: seven findings. Every one with an in-range fix was taken as a surgical cargo update -p bump (spin 0.9.8→0.9.9 yanked, anyhow→1.0.104, crossbeam-epoch→0.9.21, tokio→1.54.1, libz-sys→1.1.31, with eyre and crossbeam-utils landing on their patch releases from the same commands); a blanket cargo update was tried first and reverted for touching 169 unrelated deps: too broad for a gate PR. The three remaining are git2 0.19 unsound advisories with no patched version in range; ignored with a reachability comment (cerebro never calls Remote::list, never blame, never dereferences a git2::Buf), and T18 tracks the 0.19→0.21 evaluation that would retire the ignores.
  • [graph].targets: the ticket said “stub it,” but ADR-0018 already made the promise, so the four triples (both arches of apple-darwin and unknown-linux-gnu) went in real; T14 adds the cross-check that enforces it.

multiple-versions = "warn" keeps foldhash/hashbrown duplicates visible without failing: they come from sqlx and icu internals, outside this project’s control.

T04 Research nextest switch, doctest split, cucumber shim

Question

Cerebro runs plain cargo test. The standard’s testing.md wants four layers:

  • nextest (just test) with .config/nextest.toml, retries = 0 written down (ADR 9), slow-timeout warn and stop at 60 seconds.
  • just doctest as its own layer (cargo test --workspace --doc), nextest doesn’t run doctests, so without this the forced examples rot silently (ADR 10).
  • cucumber (tests/cucumber.rs, harness = false) must run under nextest.

The specific unknown to resolve by experiment: nextest speaks libtest’s protocol; harness = false binaries speak their own. Does nextest (a) see cerebro-tui’s cucumber binary as 0 tests and green it, (b) error, or (c) run it via the shim path the standard uses (--list --format terse answered as one unit, then with_default_cli so nextest flags don’t reach cucumber’s parser)? Cerebro currently sidesteps this by running cucumber as a separate cargo test -p cerebro-tui --test cucumber CI step (see ci.yml).

Exit predicate

A cited note here recording nextest’s actual behavior against cerebro’s harness = false binary, and a recommendation: keep the separate cucumber CI step (lowest risk) OR add the nextest shim. Feeds T06’s just test shape. No code changes in this ticket.

Resolution

Answered by experiment 2026-11-09 on cargo-nextest 0.9.151 against cerebro’s own [[test]] harness = false cucumber binary. No code committed (research ticket); the shim below was a throwaway working-copy edit that was run and reverted.

The unknown resolved: (b) error, loudly. Against the current binary with no shim, cargo nextest run -p cerebro-tui --test cucumber exits 104 with creating test list failed ... command <bin> --list --format terse exited with exit code 2 ... unexpected argument '--list' found. It does NOT see 0 tests and green it (a); it fails. So today’s separate cargo test -p cerebro-tui --test cucumber CI step is load-bearing and correct, and a naive nextest switch would break the build until the shim lands.

The shim works, with two gotchas that both defeat a naive implementation. A conforming harness main is:

#[tokio::main]
async fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.iter().any(|a| a == "--list") {
        if !args.iter().any(|a| a == "--ignored") {
            println!("cucumber: test");
        }
        return;
    }
    World::cucumber().with_default_cli().run_and_exit("features/").await;
}

Gotcha 1 (why a naive implementation is silently green, the worst outcome): the first attempt printed the libtest-style \n\n1 test footer and answered both --list calls identically. nextest’s parse_list_lines rejects any line not ending : test/: benchmark (footer = hard error), AND it runs two list passes: --list --format terse and --list --format terse --ignored. If the --ignored pass returns the test, nextest tags it ignored and cargo nextest run skips it and reports green with 0 run (“1 skipped”). That is precisely the silent-green failure the ticket feared, and it needs the empty --ignored output to avoid it. The nextest custom-harness docs and third-party harness fixes both flag this.

Gotcha 2: with_default_cli() (pre-seeds cli::Opts::default()) is what stops nextest’s per-test --nocapture --exact <name> invocation from reaching cucumber’s clap parser. Without it the run pass dies on --exact. Cucumber is kept as one unit (all 76 scenarios run per invocation), not per-scenario, which matches the position written in cucumber-rs#370: the maintainer explains process-per-scenario breaks @serial and re-parses features O(N²).

Verified behaviour of the working shim (this session):

  • cargo nextest list discovers cerebro-tui::cucumber as 1 test.
  • cargo nextest run -p cerebro-tui --test cucumber PASS in 0.6 seconds, the report on standard output shows 10 features / 76 scenarios (76 passed) / 409 steps (409 passed).
  • Failure propagation is real: pointing the harness at a missing features path flips it to FAIL ... exit 100 (“Cancelling due to test failure”), so run_and_exit still fails the binary. Green under nextest is trustworthy.

Full-suite shape for T06’s just test (measured, --workspace):

layercommandresult
unit+integration+cucumbercargo nextest run --workspace415 tests run, 0 skipped, about 25 seconds wall clock including compile
same under cargo testcargo test --workspace415 tests, about 40 seconds, no per-test isolation
doctestscargo test --workspace --docnextest runs 0 of these; 1 core doctest today, grows when T11 forces examples

Slowest real test is journal_entries_from_real_cortex_data at 12.6 seconds (it hits the live cortex), so a nextest slow-timeout warning floor anywhere in the 30-60 second band is safe; the standard’s 60 seconds is fine. The retries default of 0 needs writing down in .config/nextest.toml per the standard (ADR 9), and --all-features is a no-op today (no crate declares features), so just test can drop it until features exist.

Recommendation (feeds T06, no code in this ticket): keep cucumber as its own nextest-discoverable binary by landing the shim recorded here, then make just test = cargo nextest run --workspace (which then includes the whole 415-test set plus the cucumber unit), and add just doctest = cargo test --workspace --doc as a separate gate because nextest cannot run it. In CI, the separate cargo test -p cerebro-tui --test cucumber step in ci.yml becomes redundant once the shim is in and nextest is the runner, but it is lowest risk to keep it for one transition, then delete in T06. The doctest layer belongs in T06’s four-layer wiring, not here. CI runners need cargo-nextest installed (the cargo-binstall path ci.yml already uses).

Sources: the cargo nextest run/list output recorded in this session; the nextest design doc “Custom test harnesses”; nextest#122 and #96 (silent-skip and --format terse parsing); cucumber-rs#370 (single-unit rationale); rust-standard docs/standard/testing.md + ADR 9/10/11.

T05 Decide rumdl MD013 policy and wire the gate

Question

rumdl.toml exists (MD013 line-length 120, SUMMARY excluded) but is never run by any gate, no justfile target, no lefthook command, no CI step, nothing in .woodpecker. The standard’s prose.md disables MD013 entirely (“prose is written in paragraphs, not one sentence per line”).

One decision to put to the human, then a mechanical wire-up:

  1. MD013 policy, adopt the standard (turn line-length off) or keep the existing cap at 120? If kept, which files does the cap gate?
  2. Wire rumdl check into: a just target, a lefthook *.md glob, and a CI step (all three, so the gate is one definition, see T06).

Exit predicate

Human ruling on MD013 recorded in Resolution; rumdl.toml reflects it; rumdl appears in just --list, in lefthook under a *.md guard, and in a Woodpecker docs step; rumdl check docs/ README.md AGENTS.md is green (or its findings fixed at root cause, not suppressed).

Resolution

Ruling (human, 2026-11-11): adopt the standard’s verdict, MD013 off. The measured cost of the cap was the AGENTS.md GSD-generated blocks (37 of 39 findings; those regenerate long every time GSD writes) plus 2 in README.md; the book pages passed either way. A divergence that only ever fires on generated text is not worth an ADR.

Facts the wiring produced:

  • Baseline with MD013 on: 160 findings in 3 files. With MD013 off: 121 in 2 files. rumdl fmt fixed 119 mechanically; 3 fixed by hand at root cause: the CRITICAL banner’s #-comment lines restructured into one H1 with a bullet list (they were seven top-level headings), a duplicated ### Codeberg, Not GitHub heading removed (a real content bug), and the emphasis-only **Cerebro TUI** title paragraph folded into its prose.
  • Gate defined once as just md-lint (rumdl check docs/ README.md AGENTS.md), folded into just quality. lefthook pre-commit runs it under a *.md glob; .woodpecker/docs.yml gained an md-lint step (binstall just + rumdl, then just md-lint). Exit predicate green: rumdl check docs/ README.md AGENTS.md reports 0 issues in 55 files.
  • Durability caveat: the AGENTS.md fixes sit partly inside GSD-generated blocks; a regeneration can reintroduce findings. T17 (AGENTS.md rewrite) owns making the file’s shape stable against its generator.
  • Scope drift for T13/T06 to settle: rumdl now gates README.md + AGENTS.md, while vale still gates docs/ only. Vale on README/AGENTS today reports 77 errors / 36 warnings unmeasured by any CI step; that is T13’s fog, not suppressed here.
  • CI loop evidence: pipeline 596 failed the Vale step because this Resolution contained a spaced em dash, which the CI-pinned Vale 3.17.1 flags and the local 3.26.0 does not. That drift is T13’s fog. Fixed at root cause in 8cf7b07 and re-verified with the pinned binary.

PR: rust-standard alignment branch feature/t05-rumdl-gate.

T06 Consolidate lefthook + Woodpecker onto just targets

Question

The standard’s core claim (ADR 12): every gate is defined exactly once in the justfile, and hooks + CI call that same target, so “red is red once.” Cerebro violates it today:

  • lefthook clippy = cargo clippy --workspace -- -D warnings (no --all-targets)
  • CI clippy = cargo clippy --workspace --all-targets -- -D warnings
  • Both inline their own commands; they’ve already drifted.

Rebuild the justfile so just ci = fmt-check lint test doctest deny docs, init installs the tool set, and lefthook + .woodpecker/ci.yml call those targets. Fold in the gates from T03 (deny), T04 (nextest/doctest), T05 (rumdl), T13 (vale, docs-check) so no gate lives in two places.

Exit predicate

just --list shows one canonical target per gate; lefthook and CI contain just <target> calls, not raw cargo lines; the clippy --all-targets discrepancy is gone. lethook run pre-commit --dry-run and a CI dry run agree.

Resolution

The justfile defines every gate exactly once. just ci is fmt-check lint test doctest deny docs, the composition T04 fed in, plus T03’s deny and T05’s md-lint. lefthook and the Woodpecker steps call those targets, so the clippy --all-targets drift between hook and CI is gone by construction: both run just lint.

Landed pieces:

  • just test is nextest. The ADR 11 shim recorded in T04 landed in crates/cerebro-tui/tests/cucumber.rs, so the BDD binary is discovered as one real unit. Verified: cerebro-tui::cucumber appears in cargo nextest list, and just test reports 415 tests run, 415 passed, 0 skipped. The zero skipped is the proof the --ignored pass answers empty; a naive shim silently greens this unit (T04 gotcha 1).
  • .config/nextest.toml writes the stance down: retries = 0, slow-timeout warns at 60 seconds and terminates (ADR 9). The slowest real test measured 12.6 seconds (T04).
  • The CI test step drops the now-redundant separate cucumber line and runs just test-coverage (llvm-cov nextest, floor 25), just doctest, and just test-release.
  • The docs pipeline collapses to one step calling just docs (docs-lint, md-lint, then a real mdbook build). T13’s docs-check has its named slot inside that target.
  • Deleted: the check-cortex hook ran mdbook build under root: "Content/", a directory this repo does not have. The gate never ran; just docs is the real build gate. Also deleted: lefthook’s manual lint and test command groups, third and fourth copies of the cargo lines.
  • Renamed: the old just check (fmt plus clippy) splits into fmt-check and lint per the standard, and check now means cargo check --workspace --all-targets. quality survives as a private alias to ci until T17 rewrites AGENTS.md.
  • Added: init (binstall the cargo tools, brew the rest, then lefthook install and vale sync), bench as the libtest floor, fmt, and docs.
  • --all-features stays out of the recipes: cerebro declares no crate features, so it is decoration today (T04 measured the same).
  • AGENTS.md had documented the old hook/CI clippy drift as deliberate (“pre-commit stays src-only”). T06 retires that choice, per the exit predicate; T17 updates the prose to match.

Evidence: just --list shows one canonical target per gate with one-line doc comments; fmt-check, lint, test (415/415, 0 skipped), doctest, deny, test-release, and docs all exit zero locally; the Woodpecker validator passes both rewritten files. The PR pipeline itself re-runs every step through the shared targets.

T07 Probe nursery+pedantic deny volume on the pinned toolchain

Question

T08 flips pedantic from warn to deny and adds nursery as deny. Before committing to that PR, measure the blast radius on the dated pin: how many nursery findings exist per crate? Any nursery lint that is unfixable and so needs a reasoned allow?

Exit predicate

A table here: nursery + pedantic finding counts by crate, and the list of any lints that must join the workspace-level reasoned-allows. This sizes T08 and reveals whether T08 must split per crate.

Resolution

Done 2026-10-30 on the pinned nightly-2026-09-19 (T01), command: cargo clippy --workspace --all-targets -- -D clippy::nursery.

Volume: 15 findings, all in cerebro-core; zero in cerebro, cerebro-mcp and cerebro-tui. T08 does not need to split per crate for nursery.

Nursery lintCountWhere
missing_const_for_fn5lib.rs (3), discovery.rs, queries/intent.rs
use_self4queries/intent.rs
option_if_let_else3discovery.rs, queries/intent.rs, queries/journal.rs
too_long_first_doc_paragraph2discovery.rs, collectors/todos.rs
branches_sharing_code1queries/todos.rs

queries/intent.rs alone holds 6 of the 15, so one review pass there covers most of the blast radius.

Pedantic baseline: 0. CI already runs clippy with -D warnings, so a pedantic = deny flip adds nothing that is not already failing; the flip is materialising today’s gate in the manifest (ADR 3), not new work.

No nursery lint needs a reasoned allow: every group is fixable at call sites within one PR. The four workspace reasoned-allows of the standard (module_name_repetitions, must_use_candidate, doc_markdown, redundant_pub_crate) belong to pedantic and ride T08 as config only.

Feeds T08: expect one small PR (15 mechanical fixes in cerebro-core + the manifest table), not a campaign.

T08 Adopt the lint table

Question

Cerebro’s [workspace.lints.clippy] is only pedantic = "warn". Adopt the standard’s lints.md table (levels deny/forbid, never warn):

  • rustc denies: warnings, missing_docs, unreachable_pub, missing_debug_implementations, elided_lifetimes_in_paths, single_use_lifetimes, unused_crate_dependencies; forbid unsafe_code deferred to T12 (the 14 test unsafe blocks).
  • clippy: pedantic and nursery denied as groups with priority = -1.
  • the four workspace reasoned-allows: module_name_repetitions, must_use_candidate, doc_markdown, redundant_pub_crate.

Land in dependency order (cheapest first) so each commit is green. Panic classes (T09/T10) and missing_docs (T11) are separate tickets.

Exit predicate

cargo clippy --workspace --all-targets passes with the deny table in place and no new #[allow] beyond the four reasoned allows + any T07-justified nursery allow. AGENTS.md’s “pedantic lints are warnings” line is corrected (see T17).

Resolution

Done 2026-10-31. [workspace.lints] now carries the standard’s table: rustc denies (warnings, unreachable_pub, missing_debug_implementations, elided_lifetimes_in_paths, single_use_lifetimes, unused_crate_dependencies) and clippy pedantic + nursery denied as groups at priority = -1 with the four reasoned allows. Two exclusions by plan: missing_docs waits for T11 and unsafe_code joins as forbid only with T12 (ADR-0017); the manifest comments record both.

Finding count reality check. T07’s “15 findings, all in core” undercounted because cerebro-core’s own failure stopped clippy from ever linting the dependent crates. True initial volume was roughly 250 across the workspace, of which 136 were macro-generated trivial_regex in tests/cucumber.rs.

Mechanical groups (lifetimes, const, Debug derives, or_fun_call, unreachable_pub, redundant clones) were applied from compiler suggestions via a one-off rustfix script plus targeted edits. Semantic groups (if let/else to map_or/is_some_and, early drop() for async mutex guards) were hand-reviewed; the workspace test suite, doctests, and the cucumber BDD binary all pass, which is the behaviour-preservation evidence.

Structural additions the table forced: Component now requires Send + Debug, HandleRequest gains Debug, and the core Storage/Git/ Database traits gained a Debug supertrait so Arc<dyn _> fields stay printable. All implementors and test mocks derive it.

One deviation from the exit predicate, flagged for review: a single scoped #![allow(clippy::trivial_regex, reason = "cucumber macro-generated step regexes")] in tests/cucumber.rs. The 136 findings have no call site (the #[given]/#[when]/#[then] attributes compile every step string into a Regex), so no fix exists; the allow is test-scoped, carries its reason, and is visible to review, per the standard’s own scoped-allow rule.

Gate: cargo clippy --workspace --all-targets clean with zero -D flags needed (the manifest IS the gate now), just quality green, and cerebro build --project cerebro runs the rewritten generators.

T09 Deny panic classes

Question

The standard denies, individually, the classes of runtime bug ADR 6/7/8 remove at compile time: unwrap_used, expect_used, panic, todo, unimplemented, exit, dbg_macro. Cerebro’s AGENTS.md already says “no unwrap in production” but enforces it by hand-grep in the pre-PR checklist, not mechanically (~460 raw matches, fewer in real production code).

Approach per crate (core → mcp → tui → cerebro):

  • clippy.toml (T02) already permits these in #[cfg(test)].
  • Convert production aborts to Result/eyre propagation.
  • main returns ExitCode instead of exit (ADR 6).
  • print_stdout/print_stderr denied workspace-wide; the binary crates (cerebro, cerebro-mcp, cerebro-tui) carry a crate-level allow for the output they legitimately produce (the library cannot talk to the world, only the binary can, ADR 8).

Exit predicate

cargo clippy --workspace green with the panic classes denied in [workspace .lints.clippy]; production code has no unwrap()/expect()/panic!()/exit() outside tests and the binary-crate print allows. The AGENTS.md grep step becomes redundant (T17 removes it).

Resolution

Done 2026-10-31. The panic classes are denied workspace-wide in [workspace.lints.clippy]: unwrap_used, expect_used, panic, todo, unimplemented, exit, dbg_macro, print_stdout, print_stderr.

The “~460 backlog” estimate was wrong and the map/fog correction matters: a grep of the raw text counts test code that clippy.toml exempts and unwrap_or-shaped calls that no lint fires on. What production actually held:

  • generators/dashboard.rs: 8 writeln!(card, ...).unwrap() on an infallible String target → let _ = (the Result can never be Err).
  • generators/journal.rs: one activity.get(date).unwrap() where dates came from activity.keys(); restructured to iterate entries, making the total absence of the panic structural rather than asserted.
  • cerebro (the command-line binary): 27 print sites → one crate-root #![allow(print_stdout, print_stderr, reason = "ADR 8")] in main.rs. A [lints.clippy] per-crate override is impossible with workspace = true (cargo rejects the merge), discovered the hard way when a manifest error masqueraded as a zero-findings clippy sweep, which is precisely why this ticket’s evidence runs just quality and not piped jq-summary one-liners alone.
  • test code that legitimately prints: two #[cfg(test)] modules (collectors smoke test, TUI journal smoke test) carry a scoped #[allow(print_stderr, reason=…)]; tests/cucumber.rs extends its file allow to unwrap_used/expect_used/panic (BDD steps lack #[test] attributes, so clippy’s test exemptions cannot reach them); tests/integration.rs gets a function-scoped allow on its git() helper.
  • exit, todo!, unimplemented!, dbg!: zero findings; the habit was already gone before the deny made it mandatory.

Gate evidence: cargo clippy --workspace --all-targets clean with the panics denied; just quality green (fmt, clippy, workspace tests, doctests, release suite, vale 0/0); cucumber 76 scenarios / 409 steps pass; cerebro status runs. The AGENTS.md hand-grep pre-PR step is now mechanically redundant; T17 removes it.

T10 Deny indexing/arithmetic/as_conversions

Question

The three bug classes ADR 7 removes at compile time: indexing_slicing (v[i] → v.get(i).ok_or(...)?), arithmetic_side_effects (+/* → checked_*/saturating_*), as_conversions (narrowing as → TryFrom).

This is the largest and most pervasive ticket, because TUI layout math (as_conversions on u16/usize rects, arithmetic on areas) and collector slicing. Likely splits per crate, record the split in the first run rather than guessing now.

Exit predicate

The three classes denied in [workspace.lints.clippy], cargo clippy --workspace green. Any remaining exception is a scoped #[allow] carrying a reason a reviewer can see, never a bare suppression.

Resolution

Done 2026-11-09. indexing_slicing, arithmetic_side_effects and as_conversions are denied in [workspace.lints.clippy]; cargo clippy --workspace --all-targets is clean without a single suppression of these three classes outside two sanctioned mechanisms: clippy.toml’s allow-indexing-slicing-in-tests (already in place since T02) and the cucumber harness’s file-level allow (extended with the two new classes; step functions are test code whose panic IS the failure signal, same reason as T09’s).

The predicted per-crate split was not needed; the predicted geography was wrong. The ticket feared the TUI; reality: ~169 unique sites, in three passes. Measurement lesson: a first clippy pass reported only core’s 14 sites, because core’s deny-errors stopped cargo from compiling the dependent crates at all. Real volumes per crate:

  • cerebro-core: 14 sites. Ten counter/line-number +1s → saturating_add; scanned - registered in unregistered_count → saturating_sub (a real underflow guard: config can register more than disk scans); the two length-check-then-index sites (journal.rs date parse, storage.rs::parse_remote_owner) → slice patterns and split_first, which make the length invariant structural instead of asserted.
  • cerebro-tui: 136 sites (89 arithmetic, 34 indexing, 13 as-conversions). Layout rects: layout[i] → .get(i).copied().unwrap_or_default() (an empty rect renders nothing; the invariant is the constraint count). Area math → saturating_add/sub/mul; percent math keeps the exact truncating semantics via saturating_mul(x) / 100 (division by a nonzero constant literal is not flagged; div_ceil sneaked into one edit and was reverted, because it changed the value). Nav wrap (i+1)%5 → saturating_add(1).rem_euclid(5); the spinner’s const-fn tick became a saturate-then-reset (slice get is not const-callable on the pinned nightly, so current_frame lost const). The 13 as conversions: widening u16→usize → usize::from; SummaryCard took usize at its API instead of callers casting; a test’s [] as [Rect; 0] → Vec::new().
  • cerebro (the command-line crate) and cerebro-tui/tests/cucumber.rs: 19 sites, surfaced only after tui compiled. DateTime - DateTime → signed_duration_since; DateTime/NaiveDate - Duration → checked_sub_signed/checked_add_signed (chrono’s operators expect on overflow, so this closes a panic the panic lint could not see).

Gate evidence: cargo clippy --workspace --all-targets -- -D warnings clean; just quality green (fmt, clippy, workspace tests, doctests, release suite 70 passed, cucumber, vale 0/0); cerebro status runs; cerebro build --fresh from the branch regenerated cortex (journal index.md, today.md, this-week.md re-stamped, day links and activity graph intact); the MCP server answered tools/list and read_journal for both the success path and the invalid-date error path of the rewritten parser.

Prose-gate catch: the CI pipeline pins vale 3.17.1 while this machine runs 3.26.0, and the green local just quality hid findings the pinned version makes (spaced em-dashes, prose abbreviations, the repo vocab missing chrono). The docs pipeline on the pull request caught what the local gate could not; fixed by clearing the style hits and adding [Cc]hrono to .vale/styles/Cerebro/Vocab.yml. The toolchain pin discipline (T01) applies to the prose gate too. The local vale version is not the gate.

T11 Deny missing_docs and document the public API

Question

The standard denies missing_docs, so every public item carries a doc comment, and the doctest layer (T04) turns examples in those comments into tests. Cerebro has ~261 pub items; unknown how many already carry docs. Per crate: add doc comments, and where a public item is worth demonstrating, add a /// example (which the doctest layer then runs).

Exit predicate

missing_docs denied in [workspace.lints.rust]; cargo doc --workspace clean; just doctest (T04) runs examples and passes. Public items that genuinely have no example stay prose-only.

Resolution

missing_docs = "deny" is live in [workspace.lints.rust]; the ticket’s “~261 pub items” guess ran low: rustc reported 309 findings across all targets (lib, bin, and test crate roots). Fixed at the declaration sites, no suppressions:

  • cerebro-core carried 105 (struct fields mostly, plus the four collectors module heads and the crate header). cerebro-tui carried 137, dominated by the 68-finding Action enum; each variant now documents what it does, verified against the app and view handlers. cerebro-mcp carried 33 (JSON-RPC wire semantics in protocol.rs, the handler dispatch surface). The cerebro binary needed crate headers for main.rs and its integration test root; missing_docs fires on every crate root, binary or test, not just libraries.
  • Module docs go on pub mod declarations only where the module file has no //! header. Where both existed, rustdoc concatenated the two into one block and resolved links in the parent scope, which is how [sync_text] and [slugify] came to report “no item in scope”: the declaration-site copy was dropped in favor of the header.
  • Pre-existing rustdoc debt surfaced by the now-clean cargo doc --workspace: three private_intra_doc_links findings (public docs linking the private FALLBACK, VENDORED_DIRS, toast_layout) and one redundant_explicit_links. All four de-linked or reworded, zero allows.
  • Examples: the exit predicate asks for /// examples where an item is worth demonstrating. Two added to cerebro-core’s pure functions (parse_manual_notes, Cache::new); slugify already had one. The doctest layer goes from 1 example to 3, all passing. TUI rendering is snapshot-tested, not doctested; its docs stay prose-only, as the ticket allows.

Evidence: cargo check --workspace --all-targets and cargo clippy --workspace --all-targets -- -D warnings exit zero with the deny active; cargo doc --workspace --no-deps builds with no warnings; just test reports 415 run, 415 passed, 0 skipped; just doctest runs 3 examples, 3 pass; cargo fmt --all --check clean. During the work the cucumber suite caught an attribute an editing session dropped mid-task (View::Todos’s strum serialize), proving the red-green wiring works on this ticket’s own changes.

T12 Implement env-free config resolution (implements ADR-0017)

Question

The 14 unsafe blocks in crates/cerebro-core/src/lib.rs are edition-2024 std::env::set_var/remove_var calls in XDG-config tests, serialized by an ENV_LOCK mutex. Until they’re gone, forbid(unsafe_code) from T08 cannot land.

Refactor config-path resolution to take an injected environment (a small Env lookup: a closure or &BTreeMap<String,String>) instead of reading std::env internally. Production passes a thin std::env adapter (no unsafe, reading var is safe, only the setters are unsafe); tests pass a literal map. The ENV_LOCK and the unsafe setters disappear.

Exit predicate

rg '\bunsafe\s*\{' crates/cerebro-core/src/lib.rs returns nothing; config tests pass without touching process env; then flip forbid(unsafe_code) in [workspace.lints.rust] (closes the T08 defer). ADR-0017 accepted.

Resolution

Done 2026-10-31, implementing ADR-0017 as written.

cerebro-core gained an Env trait (var + home_dir; the latter because dirs::home_dir itself consults $HOME, so injecting only var would leave ambient state in play) and a ProcessEnv production adapter. xdg_config_dir, default_config_path, and resolve_config_path keep their zero-argument public signatures by delegating to new _with variants that take &dyn Env; cerebro, cerebro-tui, and cerebro-mcp call sites are untouched, so the ADR-0014 single-resolution property holds by construction.

The seven ENV_LOCK tests became nine FakeEnv tests over literal maps plus real tempdirs (XDG set / unset / empty-string, home fallback, the joined documented path, explicit override, existing-file preference, CORTEX_PATH fallback, last-resort relative) - coverage is a superset: empty-value-as-unset was never tested before. ENV_LOCK, env_guard, all fourteen unsafe blocks, and the paired-restore discipline are gone; unsafe_code = "forbid" is now live in [workspace.lints.rust] with the T08 hold lifted, and the workspace compiles under it.

Regression guard per Definition of Done: the injected tests would have failed against the old implementation (it reads real env), and cargo test --workspace + just quality + cerebro status all green.

T13 Vale error-gate + mdBook docs-check SUMMARY

Question

Two prose gaps (standard prose.md):

  • Vale gates at warning today (just docs-lint, CI docs.yml). The standard argues a gate that fails on suggestions/warnings gets deleted; only error should gate. Switch --minAlertLevel to error. Measure the current error findings, any that fire are real and get fixed at root cause, not downgraded.
  • No docs-check. Add a docs-check recipe that validates docs/SUMMARY.md against the files on disk both directions: no listed page that doesn’t exist, no disk file the SUMMARY omits. Orphans/dead links fail the gate. (This plan’s own new plans/ tree lives outside the book source on purpose, so it won’t trip the check.)

Exit predicate

just docs-lint uses --minAlertLevel error and passes; a just docs-check (or in-just docs) fails if a page is added to disk without a SUMMARY entry and vice versa; both folded into just ci via T06.

Resolution

To be recorded when the ticket closes.

T14 Cross-check CI step + deny graph targets (implements ADR-0018)

Question

Cerebro declares no platform promise and checks zero non-native targets in CI. Per ADR-0018, close this without cargo-dist (its host/CI layer is GitHub-only; upstream #1781 open).

  • Fill deny.toml [graph].targets (stubbed in T03) with the promise: aarch64/x86_64-apple-darwin, x86_64/aarch64-unknown-linux-gnu.
  • Add a Woodpecker cross-check step building the Linux gnu targets in the container; darwin targets stay checked on the local Mac (the standard’s split).

Exit predicate

deny.toml lists the four targets; cargo deny check validates them; a CI cross-check step builds at least the linux gnu targets green; the target list is declared in one place only. ADR-0018 accepted; the deferred cargo-dist installer work is recorded here as blocked-on-upstream, not dropped.

Resolution

To be recorded when the ticket closes.

T15 Add cog.toml commit grammar

Question

lefthook’s commit-msg runs cog verify -f {1}, but there is no cog.toml, so cocogitto enforces its defaults, not an argued grammar. The standard (ADR 14) fixes the grammar in config: conventional types, capitalised subject, 72-char length, the same structured history that feeds git-cliff’s changelog (ADR-0012).

Exit predicate

cog.toml present declaring the conventional types, capitalised subject, and 72-char cap, matched to cerebro’s actual commit style (a few sample commits show it already leans conventional). A message that can’t feed a changelog is rejected. No change to the git-cliff changelog pipeline itself.

Resolution

To be recorded when the ticket closes.

T16 Accept or reject the three decision ADRs

Question

ADR-0016 (compatible ADR mode), ADR-0017 (env-free config, then forbid(unsafe_code)), and ADR-0018 (target list + cross-check, cargo-dist deferred) are recorded as Proposed. Phases rest on them, so T08/T12 wait on 0017, T14 waits on 0018. A human decides each:

  • 0016, accept, or reverse and plan the NextGen/docs/adr migration instead.
  • 0017, accept the env-injection refactor, or keep scoped test allows and make the lint table’s unsafe_code level deny rather than forbid.
  • 0018, accept the deferral, or adopt the fabricated-source-host workaround now.

Exit predicate

Each ADR set via the command-line tool to accepted/rejected (adrs status update), with docs/decisions/README.md and docs/SUMMARY.md reflecting the outcome; the map moves the corresponding entries from draft decisions to settled, and unblocks T08/T12/T14 or records the alternative route.

Resolution

Ruled 2026-10-26: all three ADRs accepted via adrs status:

  • ADR-0016 accepted. Compatible mode and docs/decisions stay; NextGen migration is off the table for this repo.
  • ADR-0017 accepted with the refactor-then-forbid route (option 1, the recommended one). The scoped-deny fallback was rejected, so forbid(unsafe_code) is the target and T12 lands before T08’s unsafe line.
  • ADR-0018 accepted. deny.toml targets + CI cross-check close the gap; cargo-dist stays deferred until upstream #1781 lands.

Unblocks T08/T12 (0017 settled) and T14 (0018 settled). README/SUMMARY updated.

T17 Rewrite AGENTS.md to match the new gates

Question

AGENTS.md currently encodes the pre-alignment stance and contradicts the adopted gates:

  • “workspace-level clippy::pedantic … warnings during iteration”, false after T08 flips to deny.
  • Pre-PR checklist item 2 greps for unwrap()/panic!()/expect() by hand, made redundant by T09’s mechanical deny.
  • No mention of deny/nextest/doctest/rumdl/MD013/vale-error gates added by T03–T14.

Exit predicate

AGENTS.md’s Quality Enforcement, Pre-Commit, and Pre-PR sections describe the deny/forbid table, the four test layers, and the single-source-of-truth claim (“red is red once”), consistent with the justfile T06 produced. No instruction that the linter now makes impossible remains.

Resolution

To be recorded when the ticket closes.

T18 Evaluate the git2 0.19 to 0.21 upgrade

Question

deny.toml (T03) ignores three unsound advisories for git2 0.19 (RUSTSEC-2026-0008, RUSTSEC-2026-0183, RUSTSEC-2026-0184) on the grounds that cerebro never calls Remote::list, never uses blame, and never dereferences a git2::Buf. The ignores should be temporary. What is the API delta from git2 0.19 to the line that patches those advisories, given cerebro uses git2 only for local-history reads (Repository::open, revwalk, commit and signature reads, remotes()/find_remote().url(), workdir/path) with default-features = false?

Exit predicate

A cited table of breaking changes between 0.19 and the first patched version, a verdict (upgrade in-place, upgrade with listed code changes, or the advisories remain unfixed upstream and the ignores stand), and if actionable: the follow-up implementation ticket. The deny.toml comment points at this ticket; closing it updates or removes that comment.

Resolution

To be recorded when the ticket closes.

T19 Retire the RUSTSEC-2026-0459 sqlite ignore

Question

deny.toml ignores RUSTSEC-2026-0459 (SQLite before 3.54 can leak uninitialized page-cache bytes when a database is opened together with a write-ahead-log file whose page size differs; CVSS 6.8, local vector, needs a crafted db+wal pair from a less-trusted party). The fix is libsqlite3-sys >=0.39 (bundles SQLite 3.54.0/3.54.1), but no released sqlx admits it: sqlx 0.8.6 pins libsqlite3-sys to the 0.30 line and sqlx 0.9.0 pins >=0.30.1, <0.38.0, both below the patched bundling. sqlx’s main branch has already widened the range to <0.40.0, unreleased as of this writing.

When does a released sqlx (0.9.1+ or a 0.8.x backport) allow libsqlite3-sys >=0.39, and does cerebro’s sqlx usage survive the bump?

Exit predicate

cargo update -p libsqlite3-sys lands 0.39+ within the released sqlx range, just quality and just deny stay green without the ignore, and the ignore entry comes out of deny.toml. If the range still excludes the patched version, this ticket stays open with a dated watch note.

Resolution

To be recorded when the ticket closes.

Architecture

Cerebro is a Rust workspace with four crates that share types and read from a common cortex data directory.

System overview

flowchart TB
    subgraph cerebro_repo["~/Projects/cerebro (source code)"]
        CLI_CRATE["crates/cerebro<br/>CLI binary"]
        CORE_CRATE["crates/cerebro-core<br/>shared types"]
        MCP_CRATE["crates/cerebro-mcp<br/>MCP library"]
        TUI_CRATE["crates/cerebro-tui<br/>TUI binary"]
        DOCS["docs/<br/>tool documentation"]
    end

    subgraph cortex_dir["~/Projects/<name> (your cortex)"]
        CFG["config.toml"]
        AUTO["content/ (auto-generated)<br/>index.md, projects/, journal/"]
        MANUAL["content/ (manual)<br/>intent/, notes/, SUMMARY.md"]
        BOOK["book/<br/>rendered HTML"]
        AGENTS["AGENTS.md<br/>edit boundaries"]
    end

    subgraph external["External data sources"]
        GIT["project git repos"]
        OODB["opencode sessions.db"]
    end

    subgraph consumers["Consumers"]
        MDBOOK["mdbook"]
        OPENCODE["OpenCode"]
        TERMINAL["Terminal user"]
    end

    CLI_CRATE -->|scrapes| GIT
    CLI_CRATE -->|queries| OODB
    CLI_CRATE -->|reads| CFG
    CLI_CRATE -->|writes| AUTO

    TUI_CRATE -->|reads same data| AUTO
    TUI_CRATE -->|reads| MANUAL
    TUI_CRATE -->|uses types| CORE_CRATE

    MCP_CRATE -->|reads| AUTO
    MCP_CRATE -->|reads| MANUAL

    MANUAL -. "human edits" .-> MANUAL
    AGENTS -. "defines boundaries" .-> MANUAL

    AUTO -->|mdbook src| MDBOOK
    MANUAL -->|mdbook src| MDBOOK
    MDBOOK -->|renders| BOOK

    OPENCODE <-->|JSON-RPC| MCP_CRATE
    TERMINAL <-->|interactive| TUI_CRATE

    style CLI_CRATE fill:#4a9eff,color:#fff
    style TUI_CRATE fill:#9b59b6,color:#fff
    style MCP_CRATE fill:#ff6b6b,color:#fff
    style AUTO fill:#ff8
    style MANUAL fill:#f8f
    style BOOK fill:#8f8

The two repos

cerebro at ~/Projects/cerebro

The source code repository. Contains:

  • Command-line tool binary at crates/cerebro/: scrapes data sources and generates markdown
  • Shared types at crates/cerebro-core/: Config, ProjectContext, Storage trait, collectors, queries
  • Model Context Protocol, or MCP, server at crates/cerebro-mcp/: exposes JSON-RPC tools to OpenCode
  • Terminal User Interface, or TUI, at crates/cerebro-tui/: a Ratatui terminal UI for interactive browsing
  • Documentation at docs/: mdBook docs about the cerebro tool itself

Your cortex

Your cortex directory, named however you choose. This project calls it cortex. It contains:

  • config.toml: project list and settings, which cerebro reads
  • content/: mdBook source. A mix of auto-generated and manual content.
  • book/: rendered HTML output
  • AGENTS.md: defines edit boundaries for AI agents
  • book.toml: mdBook configuration

The four binaries

cerebro, the command-line tool

cerebro build            # Scrape repos, generate markdown
cerebro build --fresh    # Ignore cache
cerebro build --project X  # Single project
cerebro status           # Show cache status
cerebro serve            # Spawn mdbook in output_dir
cerebro serve --port N   # Custom port
cerebro mcp              # Start MCP server
cerebro tui              # Launch terminal UI

Data flow:

  1. Reads config.toml from your cortex
  2. For each project: scrapes git, queries OpenCode DB, scans TODOs, reads manual notes
  3. Writes markdown to output_dir. The default is ./content.
  4. Stores the cache alongside config to avoid redundant scraping

cerebro-mcp, the Model Context Protocol server

# Started by OpenCode via opencode.json:
#   "command": ["cerebro", "mcp"]
# Or standalone:
cerebro-mcp    # Reads CORTEX_PATH env var; falls back to ~/Projects/cortex

Tools provided:

  • read_project: combined generated and manual content for a project
  • list_projects: all tracked projects with metadata
  • read_journal: journal entry by date
  • read_today: today’s journal entry
  • read_intent: daily, weekly, monthly, or yearly goals for a period
  • search_todos: search TODOs across projects
  • get_stats: overall statistics

Path resolution:

  • CORTEX_PATH env var, optional. Points to the cortex data dir. Without it, cerebro-mcp falls back to ~/Projects/cortex.
  • Reads generated content from {CORTEX_PATH}/content/
  • Reads manual notes from {CORTEX_PATH}/content/notes/ and {CORTEX_PATH}/content/intent/

cerebro-tui, the Terminal UI

Interactive terminal UI for browsing projects without opening a browser. Shares cerebro-core types with the command-line tool and reads the same cortex content that mdbook renders.

Views:

  • Dashboard: project overview with summary cards and a scrollable project table
  • Projects: tabbed Sessions/Commits/TODOs per project, detail modals, and a manual note editor
  • Journal: date-grouped entries with activity indicators and an entry editor
  • TODOs: cross-project table with project/keyword filter cycling and text search
  • Config: project list with active toggle, add-project form, and TOML persistence

See TUI Architecture for the component pattern and data flow.

Content boundaries

The cortex’s content/ has a strict split between auto-generated and manual content:

Auto-generated: cerebro writes, humans don’t edit

FileContent
index.mdDashboard homepage with project cards
projects/{name}.mdPer-project status pages
journal/{year}/{mm}/{dd}.mdDaily activity logs
today.mdLast 24 hours of activity
this-week.mdLast 7 days of activity

Manual: humans write, cerebro doesn’t modify

FileContent
intent/daily/Daily goals
intent/weekly/Weekly goals
intent/monthly/Monthly goals
intent/yearly/Yearly goals
notes/Evergreen notes and documentation
notes/projects/Per-project manual notes
SUMMARY.mdmdBook navigation structure

An AGENTS.md file in your cortex enforces the boundary. It tells AI agents which files are safe to overwrite and which are human-only.

Cron workflow

0 5,9 * * *    cerebro build && mdbook build
59 23 * * *    cerebro build && mdbook build

Runs from your cortex. Scrape → generate → render, three times daily.

Shared type system

All binaries share types from cerebro-core:

ProjectConfig     : Name, repo_path, active flag
ProjectContext    : Full context: commits, sessions, todos, notes
ManualNotes       : Status, next actions, journal excerpt
Config            : Settings + project list
Cache             : Timestamps for incremental scraping

The TUI renders its views with these same types, so what mdbook shows, what the TUI shows, and what OpenCode reads via MCP all stay consistent.

Data flow pipeline

flowchart TD
    subgraph Config["Configuration"]
        C[config.toml]
    end

    subgraph Collect["Collectors"]
        O[OpenCode] --> S[Session history]
        G[Git] --> CMT[Commits, files]
        T[TODOs] --> TC[TODO/FIXME comments]
        N[Notes] --> MN[Manual notes]
    end

    subgraph Generate["Generators"]
        D[Dashboard] --> MD[Markdown]
        J[Journal] --> MJ[Markdown]
        P[Periodic] --> MP[Markdown]
        PR[Project] --> MPR[Markdown]
    end

    subgraph Out["Output"]
        ODIR[content/]
    end

    C --> Collect
    Collect --> Generate
    Generate --> Out

Collection sources

SourceData Collected
OpenCodeSession history, AI interactions
GitCommits, file changes, branch activity
TODOsTODO, FIXME, HACK, XXX comments
Manual NotesStatus, journal entries, intent

Crate details

cerebro

The main command-line tool binary:

  • Parses command-line arguments via clap
  • Coordinates collection and generation
  • Manages the file-based cache
  • Spawns the TUI and MCP server as subcommands
crates/cerebro/src/
├── main.rs          # Entry point, clap subcommands
├── cli.rs           # CLI argument definitions
├── config.rs        # Configuration loading
├── cache.rs         # Cache management
└── generators/      # Output generation (dashboard, project, journal, periodic)

cerebro-core

Shared library used by all other crates. Contains:

  • Types: ProjectConfig, ProjectContext, ManualNotes, Config, Cache
  • Traits: Storage, Git, Database for dependency injection
  • Collectors: collection implementations for OpenCode, Git, TODOs, and manual notes
  • Queries: read operations used by command-line tool subcommands and MCP tools
crates/cerebro-core/src/
├── lib.rs           # Type definitions, re-exports
├── storage.rs       # Storage, Git, Database traits
├── collectors/      # Data collection implementations
└── queries/         # Read operations (projects, journal, todos, intent, stats)

cerebro-mcp

MCP server for OpenCode integration. Provides JSON-RPC tools that let AI assistants query cortex data.

crates/cerebro-mcp/src/
├── server.rs        # MCP server setup and event loop
└── tools/           # Tool implementations (re-export cerebro-core queries)

cerebro-tui

Ratatui terminal UI for interactive project browsing. Uses the Component + Action pattern with an async tokio event loop.

crates/cerebro-tui/src/
├── app.rs           # App struct, initialization
├── action.rs        # Action enum, View, KeyBinding, InputMode
├── tui.rs           # Terminal setup, event loop
├── cli.rs           # TUI-specific CLI args
├── errors.rs        # Error handling
├── lib.rs           # Library re-exports
└── components/      # UI components (home, dashboard, projects, journal, todos, config, sidebar, help, widgets)

Architecture diagrams

Architectural diagrams for cerebro, following the C4 model and Simon Brown’s diagramming principles.

Created with D2. Source files live in diagrams/assets/current/.

For standalone SVG generation, such as for sharing, run just diagrams.

Current architecture

System context, C4 level 1

Shows cerebro, the developer, external systems such as git repos and the OpenCode DB, the cortex data directory, and AI agents connected via MCP.

Note: mdbook is an implementation detail of cortex, rendering content/ to book/, not a consumer. The real consumers are AI agents, such as OpenCode and Pi, via the MCP server, and the developer via the Terminal User Interface.

Source: diagrams/assets/current/01-system-context.d2

Data flow pipeline

4-phase pipeline: scrape, process, store, consume. Shows how data flows from external sources through collectors and generators into the cortex, then to consumers, including AI agents via MCP and the Terminal User Interface.

Source: diagrams/assets/current/02-data-flow.d2

Component structure, C4 level 3

Crate-level overview with module detail layers.

LayerDescription
Crate Overview4 crates + cross-crate dependencies
cerebro modulesCommand-line tool binary module structure
cerebro-core modulesShared types library
cerebro-mcp modulesMCP server module structure
cerebro-tui modulesTerminal User Interface binary module structure

Source: diagrams/assets/current/03-components.d2

Type model

Core types from cerebro-core and their relationships.

Source: diagrams/assets/current/04-data-model.d2

Diagram conventions

All diagrams follow Simon Brown’s principles:

  • Title: Diagram Type: Scope on every diagram
  • Legend: explains shapes, colors, and line styles
  • Directional arrows: one-way only, with specific labels
  • Explicit types: [Person], [Software System], [Container], [Component]
  • Stand-alone: makes sense without a presenter

All diagrams import nord-config.d2 for consistent Nord dark theming via D2’s theme-overrides system.

Terminal User Interface architecture

The cerebro TUI, in crates/cerebro-tui, is a Ratatui-based terminal app for browsing project activity data. It uses the Component + Action architecture pattern from the Ratatui component template.

Architecture pattern

Component trait

All UI components implement the Component trait:

#![allow(unused)]
fn main() {
pub trait Component {
    fn init(&mut self, area: Size) -> Result<()>;
    fn handle_events(&mut self, event: Option<Event>) -> Result<Option<Action>>;
    fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>>;
    fn handle_mouse_event(&mut self, mouse: MouseEvent) -> Result<Option<Action>>;
    fn update(&mut self, action: Action) -> Result<Option<Action>>;
    fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()>;
    fn as_any_mut(&mut self) -> &mut dyn Any;
    fn help_entries(&self) -> Vec<HelpEntry>;
}
}

Each component encapsulates its own state, including scroll positions, filter selections, and text input focus, and communicates with other components through the Action dispatch system.

Action dispatch

The Action enum is the single communication channel between components and the Home orchestrator:

Component ──Action──> Home ──Action──> Component

Actions fall into these categories:

CategoryExamples
LifecycleTick, Render, Resize, Quit, ClearScreen
Data loadingDataLoaded, LoadError, TriggerRefresh, RefreshComplete
NavigationSwitchView, SelectProject, SwitchTab
UI stateShowPreview, ClosePreview, SetInputMode
ConfigToggleProjectActive, SubmitAddProject, ConfigUpdated
BuildTriggerBuild, BuildOutput, BuildComplete, CloseBuildLog
Text inputStartJournalEntry, StartManualNote, SaveInput, CancelInput

Key binding system

A context-based system resolves key bindings to prevent collisions:

ContextKeysPurpose
Globalq, r, b, ?, Space, 1-5Always active: quit, refresh, build, help, leader key, view switching
Sidebarj/k, arrows, Tab, lNavigate sidebar list, switch focus to content
ContentTab, Shift+Tab, hSwitch focus back to sidebar

The leader key, Space, followed by d/p/j/t/c, provides an alternative view switching path.

Component hierarchy

Home (orchestrator)
├── Sidebar (project list, view navigation)
├── Dashboard (summary cards, project table)
├── Projects (tabbed sessions/commits/todos, note editor)
├── Journal (date-grouped entries, entry editor)
├── Todos (filterable table, search)
├── Config (project toggle list, add-project form)
├── Help (keybinding overlay)
└── Widgets (shared)
    ├── Spinner (loading indicator)
    ├── Toast (notifications)
    ├── EmptyState (no-data display)
    ├── SummaryCard (dashboard stats)
    ├── BuildLog (build output modal)
    └── Modal (generic overlay)

Data flow

The TUI follows a Flux-inspired data flow:

1. Home.do_initial_load_sync() collects data from cortex
2. Action::DataLoaded(contexts) dispatched to all components
3. Each component stores relevant data in its own state
4. User interaction → Component.handle_key_event() → Action
5. Home.update() processes Action, may dispatch follow-up Actions
6. Components receive Actions via Component.update()
7. Frame render → Component.draw() reads from local state

Async operations

Long-running operations spawn tokio tasks and report back via Actions:

  • Data refresh: trigger_refresh() spawns collect_all() in a tokio task, sends DataLoaded or LoadError on completion
  • Config writes: spawn_config_toggle() writes TOML via toml_edit, sends ConfigUpdated
  • Build: TriggerBuild spawns cerebro build as a subprocess, streams output via BuildOutput events

Input modes

The TUI supports three input modes tracked by InputMode:

ModeDescriptionActive when
NavigationDefault: keys control UIAlways, except during text editing
JournalEntryMulti-line text editing with ratatui-textareaJournal view, editing an entry
ManualNoteMulti-line text editing with ratatui-textareaProjects view, editing status/next sections

In editing modes, the text input widget intercepts most navigation keys. Escape cancels input and returns to Navigation mode.

Testing strategy

The TUI uses three testing layers:

LayerToolPurpose
Unit tests#[cfg(test)]Component state transitions, action handling, key binding parsing
Integration testsratatui::backend::TestBackendRender full app to buffer, assert on content
BDD testsCucumber, defined in tests/cucumber.rsUser-facing scenarios in Gherkin
System testsGhostty devtoolsTerminal lifecycle, resize, responsiveness

Integration tests construct Home directly, call set_cerebro_config() and do_initial_load_sync().await, then render and assert against the buffer. BDD tests assert against real component state, such as home.view_name(), not buffer text.

Architecture decisions

This directory records the architectural decisions behind Cerebro. Each follows the Nygard ADR format: context, decision, consequences.

Decisions

#TitleStatus
0001Record architecture decisionsAccepted
0002Monorepo structure with four cratesAccepted
0003Four data collectorsAccepted
0004Markdown output with mdbookAccepted
0005MCP server for OpenCodeAccepted
0006Cache strategyAccepted
0007TOML configuration formatAccepted
0008TODO regular expression patternAccepted
0009Storage trait for DIAccepted
0010Why Cerebro uses MCPAccepted
0011XDG as default config locationAccepted
0012Cut releases with git tags and forge releases, not release-plzAccepted
0014The XDG config is the single source of truth for projectsAccepted
0015Project discovery reports, it does not absorbAccepted
0016Keep ADR records in adr-tools compatible modeAccepted
0017Forbid unsafe code workspace-wide with env-free config testsAccepted
0018Close the platform-promise gap with a target list, not cargo-distAccepted
0019Collect commits by date window, and let the author instant own the dayAccepted

1. Record architecture decisions

Date: 2026-04-22

Status

Accepted

Context

Cerebro needs to record its architectural decisions.

Decision

Cerebro uses Architecture Decision Records, as described by Michael Nygard in his article “Documenting Architecture Decisions.”

Consequences

See Michael Nygard’s article, linked in the preceding section. For a lightweight ADR toolset, see Nat Pryce’s adr-tools.

2. Monorepo structure with four crates

Date: 2026-04-22

Status

Accepted

Context

Cerebro needs to support several use cases: building dashboards from the command line, exposing a library for other tools, integrating with OpenCode over MCP, and browsing project data in an interactive terminal UI.

Decision

Cerebro uses a Rust workspace with four crates:

  • cerebro is the command-line tool and main binary.
  • cerebro-core is the library crate holding shared types, traits, collectors, and queries.
  • cerebro-mcp is the binary crate that exposes an MCP server for OpenCode.
  • cerebro-tui is the binary crate with the Ratatui terminal UI for interactive browsing.

Consequences

Pros

  • Clear separation between the command-line tool, library, MCP server, and terminal UI
  • Other tools can reuse cerebro-core as a library
  • Each crate can evolve independently
  • The terminal UI shares types with the command-line tool, so both render data consistently

Cons

  • The workspace adds build complexity
  • More build artifacts to manage

Notes

See the crates/ directory for the actual structure.

3. Four data collectors

Date: 2026-04-22

Status

Accepted

Context

Cerebro generates context from development activity. The design must specify which data sources to collect from.

Decision

Cerebro collects data from four sources:

SourceImplementationData
OpenCodeSQLite via opencode_db_pathSession history
Gitgit2 crateCommits, modified files
TODOsRegex scan on source filesTODO, Needs Fixing, Hack, and Placeholder comments
Manual Notesnotes/projects/{name}.mdStatus, journal, intent

Consequences

Pros

  • Broad coverage of development activity signals
  • Each collector is independent
  • Manual notes provide human context

Cons

  • Git collection can be slow on large repos
  • The TODO regular expression may produce false positives in strings

Notes

The collectors/mod.rs module orchestrates the collectors. Each collector is async and can run in parallel.

4. Markdown output with mdbook serving

Date: 2026-04-22

Status

Accepted

Context

Cerebro generates a personal dashboard. The design must determine the output format and serving method.

Decision

Output is markdown files served via mdbook:

  • Generators produce .md files
  • mdbook is a local web server
  • The output location is configurable via config.toml

Output structure

{dashboard_path}/
├── index.md                    # Overview
├── projects/
│   └── {name}.md            # Per-project pages
├── today.md                  # Today's activity
├── this-week.md              # Weekly activity
└── journal/
    └── {year}/
        └── {mm}/
            └── {dd}.md      # Daily journal

Consequences

Pros

  • Human-readable output
  • Easy to version control
  • mdbook provides search and navigation

Cons

  • Requires mdbook for serving
  • Static generation without live updates

Notes

Default port is 3000. Use cerebro serve --port X to customize.

5. MCP server for OpenCode integration

Date: 2026-04-22

Status

Accepted

Context

OpenCode and other AI assistants should be able to query the dashboard directly. This requires a tool protocol.

Decision

The cerebro-mcp crate implements an MCP server:

Tools exposed

ToolPurpose
read_projectRead project info + generated page
list_projectsList all tracked projects
get_statsOverall statistics
read_journalRead journal entry by date
read_todayRead today’s journal
read_intentRead intent for daily, weekly, monthly, or yearly periods
search_todosSearch TODOs across projects

Configuration

The server reads CORTEX_PATH to locate the cortex data directory and falls back to ~/Projects/cortex if unset. See ADR-0011 for config priority in the command-line tool and TUI.

Consequences

Pros

  • AI assistants can access context directly
  • Supports AI-assisted workflows
  • Uses a standard protocol

Cons

  • Adds an MCP SDK dependency
  • Requires server maintenance

Notes

Binary: target/release/cerebro-mcp. Configure in OpenCode’s opencode.json.

6. Cache strategy for collectors

Date: 2026-04-22

Status

Accepted

Context

The git, OpenCode, and TODO collectors can be expensive. Avoid re-running them on every build.

Decision

Cerebro uses file-based caching:

  • The cache lives in cache.json in the system cache directory
  • Each entry tracks: opencode_last_query, git_last_scan, todo_last_scan
  • The --fresh flag bypasses the cache entirely
  • The --project <name> flag limits the build to a specific project

Cache invalidation

Cerebro invalidates the cache when:

  1. The user passes --fresh to override it
  2. Timestamps in cache.json show the data is stale

cerebro status reports cache state for manual checks.

Consequences

Pros

  • Subsequent builds are fast
  • The --fresh flag respects explicit user intent

Cons

  • Data goes stale if the TTL is too long
  • Relies on the system cache directory

Notes

See cache.rs for the implementation.

7. TOML configuration format

Date: 2026-04-22

Status

Accepted

Context

Cerebro needs a configuration format that users can edit by hand and that scales to multiple projects and settings.

Decision

Cerebro uses TOML with two sections:

[settings]
opencode_db_path = "..."        # Path to AI tool's SQLite DB (optional)
output_dir = "..."             # Dashboard output directory

[[projects]]
name = "project-name"         # Display name
repo_path = "~/Projects/..."   # Git repository path
active = true                  # Include in build

Cerebro reads manual notes from a fixed path derived from the output directory ({output_dir}/notes/projects/{name}.md) rather than a per-project note_path field.

Consequences

Pros

  • TOML is human-readable and well-supported in Rust
  • Clear separation between settings and project definitions
  • Easy to add new fields without breaking existing configs

Cons

  • Requires the toml crate as a dependency
  • ~ path expansion needed

Notes

Cerebro parses config in cerebro-core via the toml crate. ~ expansion happens in config.rs.

8. TODO regular expression pattern and file scanning

Date: 2026-04-22

Status

Accepted

Context

Cerebro must reliably find TODO, Needs Fixing, Hack, and Placeholder comments in source code without false positives.

Decision

Regex pattern:

(?i)\b(TODO|FIXME|HACK|XXX)\b[\s:]*(.*)$

Features:

  • Case-insensitive matching using the (?i) flag
  • Word boundary anchors using \b
  • Captures the keyword plus optional text after : or whitespace

File scanning:

  • Uses ignore::WalkBuilder to respect .gitignore
  • Skips binary and non-source extensions such as png, jpg, pdf, and zip

From highest to lowest, the sort priority is Needs Fixing, TODO, Hack, Placeholder.

Consequences

Pros

  • Case-insensitive catches todo:, TODO:, Todo:
  • Respects gitignore automatically
  • Skips common false positives, such as minified JS and images

Cons

  • Won’t catch multi-line comments
  • Won’t catch TODO in strings without keyword prefix

Notes

See collectors/todos.rs for implementation.

9. Storage trait for dependency injection

Date: 2026-04-22

Status

Accepted

Relates to 17. Forbid unsafe code workspace-wide with env-free config tests

Context

Collectors read files and access the git and OpenCode databases. They also have to work in tests without a real filesystem.

Decision

Cerebro defines traits for dependency injection:

#![allow(unused)]
fn main() {
pub trait Storage: Send + Sync {
    async fn exists(&self, path: &Path) -> bool;
    async fn read_to_string(&self, path: &Path) -> Result<String>;
    // ...
}

pub trait Git: Send + Sync {
    async fn commits(&self, repo_path: &Path) -> Result<Vec<GitCommit>>;
    async fn modified_files(&self, repo_path: &Path) -> Result<Vec<FileChange>>;
}
}

Implementations:

  • TokioStorage uses tokio for async file I/O
  • Git2 uses the git2 crate for git operations and caps commits at 20 per project
  • SqlxDb uses sqlx for OpenCode SQLite queries

Consequences

Pros

  • Tests run without a real filesystem
  • Tests can swap in mock storage
  • Clear abstraction boundaries

Cons

  • Trait indirection overhead
  • More complex DI setup

Notes

See cerebro-core/src/storage.rs.

10. Why Cerebro uses Model Context Protocol, or MCP: the right tool for the job

Date: 2026-06-06

Status

Accepted

Context

The cerebro MCP server solves one problem:

Give AI assistants standard, secure access to cerebro’s aggregated developer activity data, so coding help can draw on what the user has already done.

More specifically:

  • Cerebro collects and processes data from OpenCode sessions, git commits, TODO comments, and manual notes
  • A cortex, located via CORTEX_PATH and defaulting to ~/Projects/cortex, stores this data
  • The value is in access. An assistant that can query this data saves the user context switching
  • Assistants such as OpenCode, Claude Code, and similar tools need this data to give help grounded in the user’s own work

Decision

MCP matches the data access pattern

MCP has three core concepts that align exactly with cerebro’s needs:

Resources, for data exposure:

  • Cerebro’s primary asset is its data store
  • MCP Resources expose it:
    • Project information via the projects resource URI
    • Journal entries via the journal resource URI with a date parameter
    • Intent and goals via the intent resource URI with period and identifier parameters
    • TODO items via the todos resource URI with a project filter
    • Search results via the search resource URI with a query parameter

Tools, for actions:

  • Beyond reading data, users may want to trigger actions:
    • cerebro_build - Trigger a dashboard rebuild
    • add_journal_entry - Add a manual note
    • update_project_status - Mark project as active/inactive
    • refresh_cache - Force data re-collection

Prompts, for predefined interactions:

  • Common query patterns to define:
    • summarize_recent_activity
    • get_project_status
    • find_related_todos

Standards-based integration eliminates custom work

Without MCP, cerebro would need to:

  • Build custom HTTP/WebSocket APIs for each assistant type
  • Document and maintain separate integrations for OpenCode, Claude Code, etc.
  • Handle authentication, rate limiting, and error handling per integration

With MCP:

  • Implement the MCP protocol once
  • Any MCP-compatible assistant can discover and use cerebro’s capabilities
  • OpenCode, Claude Code, and other MCP hosts handle the client-side complexity
  • A single source of truth for what data and actions are available

Security boundaries come with the protocol

MCP draws clear security boundaries:

  • The assistant can only access what the MCP server explicitly exposes
  • No risk of arbitrary database access or unintended side effects
  • Tool invocations require explicit approval, configurable via permissions
  • MCP separates read-only resources from write-capable tools

The server layers on what cerebro already has

Cerebro already had:

  • Data collection logic for OpenCode, git, and TODOs
  • Processing and storage systems
  • Dashboard generation algorithms
  • Query capabilities for the web interface

The MCP server is a thin adaptation layer that:

  • Exposes existing capabilities through standard MCP interfaces
  • Requires minimal new business logic
  • Reuses the existing data processing work
  • Avoids re-implementing core cerebro features

Compatibility with a growing ecosystem

By adopting MCP, cerebro gains:

  • Compatibility with a growing list of MCP-hosted assistants
  • Continued relevance as more tools adopt the standard
  • Benefits from improvements to the MCP ecosystem
  • Less integration work for users trying multiple assistants

Why retrieval-augmented generation doesn’t cover it

A retrieval-augmented generation, or RAG, system could use cerebro’s data. MCP is the better fit because:

RAG is a pattern. MCP is a protocol.

  • RAG describes how to retrieve and use context within a single large language model, or LLM, interaction
  • MCP defines how systems connect to provide that context and more

MCP covers more than retrieval:

  • RAG focuses on fetching relevant information for a prompt
  • MCP also supports invoking actions through tools and defining interaction patterns through prompts
  • Cerebro also writes: assistants may need to trigger a build or add a journal entry

They can work together:

  • An agent can use MCP to discover what cerebro offers
  • Then apply RAG techniques to find the most relevant parts of large datasets
  • Or use MCP resources as the data source for a RAG system

Concrete example: how an assistant uses Cerebro MCP

When a user asks in OpenCode: “What work happened yesterday on the web-project?”

  1. OpenCode, acting as MCP host, connects to the cerebro-mcp server
  2. The server advertises its resources and tools via the MCP protocol
  3. OpenCode sees resources like: cerebro://journal/2026-04-16, cerebro://projects/web-project
  4. OpenCode reads the journal resource for yesterday
  5. Optionally reads project-specific data
  6. Combines this with the user’s question to form a complete prompt for the LLM
  7. The LLM responds with a summary of yesterday’s work on web-project
  8. If the user wants to take action, for example marking this project as inactive, OpenCode can invoke the appropriate MCP tool

Addressing the “RAG-shaped problem” intuition

The intuition is fair: at its core this is about making data available to augment LLM context, which is what RAG does. However:

  • MCP solves the connection and discovery layer: how to get the data to the assistant
  • RAG solves the relevance filtering layer: how to find the right data within a large corpus
  • Cerebro needs both layers:
    • MCP provides standardized access to the cerebro data store
    • RAG-like techniques could help cerebro rank journal entries by relevance, or help the assistant process large result sets

MCP is the right foundational choice because it sets the standard connection mechanism. Whether the assistant then uses simple retrieval, RAG, or another method is a separate concern. MCP doesn’t prescribe it. It makes the data available in a standard way, and stops there.

Consequences

The cerebro MCP server fits the job. MCP’s Resources, Tools, and Prompts map directly onto cerebro’s data access and action needs. The choice is standards-based, secure, uses infrastructure that already exists, and works with more assistants as the standard spreads. It isn’t overkill: it’s the minimum protocol that covers this exact use case. It complements RAG rather than replacing it.

The choice isn’t trend-following. It applies the right tool, MCP, to the right problem: standard AI-assistant access to a structured personal data store.

11. XDG as default config location; CORTEX_PATH becomes a legacy fallback

Date: 2026-06-06

Status

Accepted. Supersedes the implicit decision in 0007: TOML configuration format, which assumed CORTEX_PATH would point at the config.

Context

The cerebro command-line tool and TUI load config.toml via this priority:

CORTEX_PATH env var > --config CLI flag > XDG config dir > ./config.toml

That ordering made CORTEX_PATH the de-facto requirement: a user who didn’t set it would either find an XDG config, if one happened to exist, or fail. The README and getting-started docs reflected this, telling users to place config.toml in their cortex, meaning the directory pointed to by CORTEX_PATH.

In practice, this meant the user had to:

  1. Decide on a cortex location.
  2. Set CORTEX_PATH in their shell startup file.
  3. Restart the shell.
  4. Only then would the binary find the config.

If the user missed a step, the binary either picked up an unintended file, the ./config.toml fallback, or failed. The MCP server kept working because it falls back to ~/Projects/cortex. The cerebro and cerebro-tui binaries didn’t. They sat silently on an absent config.

The principle of least surprise: a freshly installed tool shouldn’t require environment variables to do its job. The XDG base-directory spec already defines a sensible default: $XDG_CONFIG_HOME/cerebro/config.toml, falling back to $HOME/.config/cerebro/config.toml when XDG_CONFIG_HOME is unset. The same path works on every platform, which avoids the surprise of dirs::config_dir() returning ~/Library/Application Support on macOS for users coming from Linux. CORTEX_PATH conflated two unrelated questions, where the config lives and where the data lives, and the conflation was the source of the confusion.

Decision

The command-line tool cerebro and the TUI cerebro-tui use this new resolution order:

  1. --config <path> flag: explicit override, always wins.
  2. XDG config dir, the default: $XDG_CONFIG_HOME/cerebro/config.toml, or $HOME/.config/cerebro/config.toml if XDG_CONFIG_HOME is unset. Users who do nothing get this. Same path on every platform.
  3. CORTEX_PATH env var, a legacy fallback. If CORTEX_PATH already points at a directory containing config.toml, that still works.
  4. ./config.toml in the current working directory, a last-resort fallback, unchanged.

The decision leaves cerebro-mcp unchanged: it still uses CORTEX_PATH to locate the cortex data directory, where generated content/ lives, and falls back to ~/Projects/cortex. This is a separate concern from config and was never the source of confusion.

crates/cerebro/src/main.rs::resolve_config_path and crates/cerebro-tui/src/bin/cerebro-tui.rs::resolve_config_path both implement the new priority. Integration tests in crates/cerebro/tests/integration.rs now pass --config explicitly so they don’t pick up a developer’s real XDG config from their machine.

Consequences

Pros

  • New users: install, run cerebro build, it reads the XDG default. No env vars required.
  • Existing users with CORTEX_PATH set: still work via fallback #3.
  • Power users and scripted runs: --config always wins, no surprises.
  • CORTEX_PATH’s documentation now matches reality: a pointer to the MCP server’s data directory, not a config prerequisite.

Cons

  • A user with both an XDG config and CORTEX_PATH set to a different cortex silently gets the XDG config. This is the desired behavior, but it means CORTEX_PATH no longer wins. Release notes should call it out.
  • Tests now depend on an explicit --config. Future test authors must remember to pass it. This change updated the existing integration tests.
  • This change reworked the example config.toml in the README. External tutorials or screenshots showing the old “put it in your cortex” pattern are now stale.

Migration

For users currently relying on CORTEX_PATH to point at their config:

# Old: config was at $CORTEX_PATH/config.toml
# New: move it to the XDG location
mv "$CORTEX_PATH/config.toml" ~/.config/cerebro/config.toml
# CORTEX_PATH can stay set (MCP still uses it) or be unset if you accept the default

For users with no config at all, run cerebro build once after install and follow the “config not found” error message, which points at the XDG path.

Notes

  • The dirs crate handles home_dir(). The code reads XDG_CONFIG_HOME itself, falling back to $HOME/.config, so the resolution is identical on every platform. Cerebro deliberately doesn’t use dirs::config_dir(), which on macOS returns ~/Library/Application Support and would surprise users coming from Linux.
  • The integration tests previously relied on CORTEX_PATH for config. They now pass --config explicitly. Unit tests in main.rs::tests never depended on a real XDG config, so they needed no changes.
  • This decision deliberately leaves the MCP server’s use of CORTEX_PATH alone: it locates the data directory, not the config.

12. Cut releases with git tags and forge releases, not release-plz

Date: 2026-09-18

Status

Accepted. Supersedes the release automation set up in 0002: Monorepo structure with four crates and every subsequent .release-plz.toml fix. Closes issue #64.

Relates to 18. Close the platform-promise gap without cargo-dist

Context

ci/woodpecker/push/release failed on every push to main. The failure was:

ERROR failed to determine next versions
Caused by:
    0: run cargo package
    1: cargo package failed: "   Packaging cerebro-core v0.2.2 (.../worktree/crates/cerebro-core)
         error: failed to verify manifest at `.../worktree/crates/cerebro-mcp/Cargo.toml`
         Caused by:
           all dependencies must have a version requirement specified when packaging.
           dependency `cerebro-core` does not specify a version"

Issue #64 lists the eight configuration variants tried and discarded on a clean tree: publish_no_verify, allow_dirty, semver_check = false, release = false, git_only = false, dropping the version key from [workspace.dependencies], aligning [workspace.package] version with the tags, deleting the newest tags. Two release-plz versions, 0.3.159 and 0.3.165, fail identically.

None of them could work because this isn’t a configuration problem. Every crate in the workspace is publish = false, and the binaries depend on their siblings by path:

$ cargo package -p cerebro-mcp
error: failed to prepare local package for uploading
Caused by:
  no matching package named `cerebro-core` found
  location searched: crates.io index

cerebro-core, cerebro-tui and cerebro-mcp return 404 on crates.io, and an unrelated crate has taken the name cerebro there. Packaging strips the path from a dependency and resolves it in a registry, so cargo package can’t succeed for any crate in this workspace. It never could. release-plz shells out to cargo package even with git_only = true, which is why the pipeline goes red and why no knob on it helps. Upstream tracks this as release-plz#2595 and #2651, with the actual fix in #2789, which hadn’t merged at the time of writing.

Nobody publishes anything from this workspace. Installation is cargo install --path crates/cerebro, documented in docs/quick-start.md, and a release is a git tag plus a forge page someone can read. The tags were doing that job already:

$ git cat-file -p cerebro-v0.2.3
tag cerebro-v0.2.3
tagger Gitea <gitea@fake.local> 1779942905 +0200

The tagger is the forge, not a person. Creating a release through the API with a tag that doesn’t exist yet makes Codeberg cut the tag itself. So the one release-plz step that worked didn’t need release-plz.

That leaves a tool whose remaining value here is: read conventional commits, propose a semantic version bump, write a changelog. git-cliff does all three, and doesn’t need a registry.

Decision

Drop release-plz. A release is two halves with a human and a merge in between.

Local half, just release. scripts/release.sh prepare asks git-cliff for the next version from the commit types since the last cerebro-v* tag. It inserts the rendered section into CHANGELOG.md, rewrites [workspace.package] version, and refreshes Cargo.lock so the resolved versions move with the manifest. The script commits all three on a release/cerebro-v<version> branch, prints the push and fj pr create commands, and touches nothing remote. It refuses a dirty tree and refuses to re-use a tagged version.

Forge half, CI. .woodpecker/release.yml has one release step, on push to main: scripts/release.sh publish. It reads the version from Cargo.toml. If a matching tag exists, the answer is “already released” and exit 0, which is the normal result of most pushes. Otherwise it takes that version’s CHANGELOG.md section as the body and posts one release to the forge API, which creates the tag pointing at the commit CI just built.

There is no crates.io step, and no publish on a tag event: the forge makes the tag, so a tag-triggered pipeline would be a loop waiting to happen.

cliff.toml owns the section format. [workspace.dependencies] loses the hand-maintained version = "0.2" ranges on the internal crates. Nobody packages this workspace, so a path dependency needs no range. That key is what cargo printed the misleading “does not specify a version” line from.

scripts/release-test.sh drives the script against scratch git repositories with the forge call stubbed. It covers which line bump rewrites, next across patch/minor/major/nothing, and whether notes finds one section and stops at the next. It checks the publish decisions: no-op, publish once, stand down after the tag exists, refuse without notes, refuse without a token, and --dry-run sending nothing. It runs in the CI test step and inside just test.

Consequences

Pros

  • The pipeline is green on pushes that aren’t releases, which is most of them.
  • Reviewers see a release as a pull request before any tag exists. The old flow had the same shape by accident, but its notes came from a tool that couldn’t verify the tree.
  • What CI publishes is the changelog section a human read in the release PR, not a second rendering from a different tool.
  • The version in Cargo.toml and the newest tag can’t drift silently: the tags cerebro-v0.2.2 and cerebro-v0.2.3 both point at the same commit while the manifest read 0.2.2, and no release page exists for either.
  • One tool less in the CI image. The release step needs git, curl, and bash.

Cons

  • Version bumps are no longer automatic on merge. Someone runs just release. That’s a deliberate trade: this repo shipped three tags in five months, and the automation meant to cover it has never once run cleanly end to end.
  • No crates.io presence, so cargo install cerebro from the registry stays unavailable. The registry never had it, and an unrelated crate has the name.
  • Merging a release PR without its changelog section makes CI red rather than publishing something thin. Loud and self-explanatory, but still red.
  • git-cliff is now a required local tool for releasing, where before CI installed it on demand.

Migration

Nothing to do for users. For anyone with a release-plz habit:

just release-status   # current version vs. what the commits propose
just release          # branch + changelog + bump, one commit, nothing remote
just release-preview  # the tag and notes CI would publish, no forge traffic
bash scripts/release-test.sh

The 0.2.2 and 0.2.3 tags stay untouched. Both are older than main, and rewriting published tags to fix a mismatch is a worse trade than leaving a pair of releases unannounced. The next just release moves to 0.3.0, which is what the commits since cerebro-v0.2.3 ask for.

Notes

  • CEREBRO_RELEASE_TOKEN carries the forge token in CI, from the existing API Token secret. Locally release.sh also accepts CODEBERG_ACCESS_TOKEN, which fj already uses.
  • The first release this flow cut, 0.3.0, left Cargo.lock resolving the workspace at 0.2.2, because nothing refreshed it after the manifest bump. prepare now runs cargo metadata --offline and commits the lock with the manifest and changelog. cargo would have rewritten it on the next build, which is why the disagreement is invisible until someone clones a tag.
  • The script accepts environment overrides for every path it reads: CEREBRO_RELEASE_REPO_DIR, CEREBRO_RELEASE_CARGO_TOML, CEREBRO_RELEASE_CHANGELOG, CEREBRO_RELEASE_API, CEREBRO_RELEASE_REPO. The tests need that to point a scratch repo and a stub curl at the script.
  • The script doesn’t use git-cliff --prepend. It re-emits its own header each run, which duplicates the preamble in CHANGELOG.md. prepend_changelog in the script splices the rendered section in before the first existing section, so the preamble belongs to the file.
  • cliff.toml keeps git-cliff’s body template on one line with explicit newlines. With the indented multi-line form, git-cliff 2.14 emits a newline for every loop tag, which renders each bullet as its own one-item list. scripts/release-test.sh asserts against that with loose_bullets.
  • Group names in cliff.toml carry an HTML comment prefix (<!-- 0 -->Features) because group_by sorts keys as strings. striptags removes the prefix, and the prefix is what keeps Features before Bug Fixes.
  • build, ci, chore, style and test commits are skip = true. They’re in the history, they’re how the repo works, and they’re not release notes.

14. The XDG config is the single source of truth for projects

Date: 2026-10-14

Status

Accepted. Amends 0011: XDG as default config location, which settled config resolution for the command-line tool and the TUI but left the MCP server reading a second file, and didn’t confront that the second file is a project list, not a data pointer.

Context

0011 moved the command-line tool and the TUI to an XDG-first resolution order and stated that the MCP server was “unchanged” because CORTEX_PATH there “serves a different purpose (data dir, not config)”. The second half of that sentence is true, the first isn’t. The MCP server does more than find generated content with CORTEX_PATH. Two of its tools read project configuration out of that directory:

crates/cerebro-core/src/queries/projects.rs:70   let config_path = cortex_path.join("config.toml");
crates/cerebro-core/src/queries/todos.rs:49,60   let config_path = cortex_path.join("config.toml");

The server resolves its cortex_path in crates/cerebro-mcp/src/main.rs:12 from CORTEX_PATH, falling back to ~/Projects/cortex. So the command-line tool and the TUI build from ~/.config/cerebro/config.toml while list_projects and search_todos read ~/Projects/cortex/config.toml. Two files, two update paths, two answers to “what are my projects”.

That’s not theoretical. Issue #71’s audit found the two copies disagreed by a factor of three: the cortex copy listed 21 projects, the XDG copy 60 at the time, 69 after the September sync. A consumer calling list_projects over MCP got a third of the world that cerebro build was actually building. Because the cortex copy is a tracked file in the cortex repository, the drift had a second consequence: project truth lived in two repositories, and the one the MCP server read was the one no build step wrote.

The discovery work for #71 makes this load-bearing rather than merely untidy. Discovery has to write its reconciled project list somewhere, and if the command-line tool and the MCP server disagree about where it lives, discovery would fix one view of the world while leaving the other stale. That’s the exact failure the feature exists to remove.

Decision

The XDG config, ~/.config/cerebro/config.toml as resolved by 0011, is the single source of truth for project configuration, for every binary: cerebro, cerebro-tui, and cerebro-mcp.

  1. The MCP server resolves configuration through the same resolver the command-line tool uses, in the same order: the XDG path first, CORTEX_PATH as the legacy fallback, and ./config.toml last. It doesn’t resolve through its cortex data path. Concretely, list_projects and search_todos stop reading cortex_path.join("config.toml") and take a resolved config path instead.
  2. CORTEX_PATH keeps its current, narrow job: locating the cortex data directory, where generated content/ lives. read_project, read_journal, read_today, read_intent, and get_stats read content only: output that cerebro generates, not configuration.
  3. ~/Projects/cortex/config.toml stops being a configuration source. The file may remain in the cortex repository as a copy, but nothing reads it to decide what a project is. It’s no longer authoritative. Don’t edit it to change behavior.
  4. If both an XDG config and a cortex-directory config exist and differ, the XDG config wins and the server logs the divergence at warn! once at startup, naming both paths. Silent precedence would trade one confusion for another.

The three binaries call one resolver instead of carrying three copies of the logic. The function that 0011 added to crates/cerebro/src/main.rs and crates/cerebro-tui/src/bin/cerebro-tui.rs moves into cerebro-core, and all three binaries call it, so the order can’t drift apart again.

Consequences

Pros

  • list_projects over MCP and cerebro build describe the same projects. The 21-vs-60 class of drift becomes impossible by construction rather than by discipline.
  • Project truth lives in exactly one repository. The cortex repository becomes output-only, which is what its name implies.
  • Discovery, the work of #71, has one write target and one read target, so a reconciled project list is immediately consistent across the command-line tool, the TUI, and the MCP server.
  • One resolver in cerebro-core means a future fourth binary inherits the correct behavior instead of copying it.

Cons

  • This is a behavior change for anyone whose cortex-directory config was the one kept current. Their list_projects output changes on upgrade.
  • The resolver moves across a crate boundary (cerebro → cerebro-core), touching both cerebro entry points and the MCP entry point in one change. It’s a small amount of code with a wide blast radius.
  • A stale cortex config left on disk becomes dead weight that looks live. The startup warn! mitigates this but doesn’t delete it.

Migration

Bring the cortex-copy projects into XDG, then let the cortex file fall dormant:

# XDG is canonical; make sure it is the superset.
# Compare the two before deleting anything:
diff <(grep '^name' ~/.config/cerebro/config.toml | sort) \
     <(grep '^name' ~/Projects/cortex/config.toml | sort)

# If the cortex copy has entries XDG lacks, add them to XDG (or run
# `cerebro discover --sync-config` once #71 lands, which reconciles XDG
# against what is actually on disk).

Users who only ever had an XDG config need no change. The expected direction of the merge is XDG-wards: in the audited state XDG already held the larger, more current list.

Notes

  • This decision doesn’t affect get_stats, which counts projects from the generated content/projects/ directory rather than from config. That’s a third, implicit source of “project count” and #71 handles it by making cerebro status report disk-versus-config coverage explicitly.
  • CORTEX_PATH appearing in both a data role and a legacy config role is 0011’s doing. This record leaves it as it is. The point here is only that the authoritative config never lives under the data path.
  • If you keep a cortex-directory config for convenience, generate it from the XDG config rather than hand-editing it. That’s a follow-up, not part of this decision.

15. Project discovery reports, it does not absorb

Date: 2026-10-14

Status

Accepted. Depends on 0014: The XDG config is the single source of truth for projects, which decides where discovery writes a new project. Implements issue #71.

Context

Cerebro has no project discovery. A project exists only if you hand-add it as a [[projects]] table in ~/.config/cerebro/config.toml, and anything absent from that file is invisible to the collectors, the journal, TODO search, stats, and the dashboard:

crates/cerebro-core/src/collectors/mod.rs:28   for project in &config.projects
crates/cerebro/src/main.rs:85                  info!("Building all {} projects", config.projects.len())

The failure mode is silence. Nothing signals that a repository exists on disk and nobody reads it. In the audited state the config hadn’t changed since Jun 7 while cron built three times a day, and on Sep 20 the journal reported 1 projects | 0 sessions | 1 commits on a day with commits in four other repositories. Adding ten active repositories by hand the same day moved that day’s journal to 5 projects | 3 sessions | 42 commits and project pages from 41 to 51. The entire gap was one unmaintained section of a text file. On disk: 95 git repositories under ~/Projects, 65 configured. The other 30, roughly a third, go unseen by every subsystem.

A naive “scan the directory and add everything” isn’t the fix. The same audit produced five ways a discovery pass goes wrong, all observed on this machine rather than theorized:

  1. Worktrees double-count. ~/Projects looks like 101 git repositories, but several are worktrees of projects already tracked (cerebro-*, rpdc-tierA, cortex-theme-refactor, Botface-repairHealthCheck, listsome-example-repair, leptos-jamstack-component-refactor). Treating each as a project counts every commit in the parent more than once.
  2. Upstream clones inflate. Three configured projects were clones with zero commits by the owner: bevy (0 of 9,066), rp-hal-boards (0 of 921), and mdbook-journal (0 of 17). Together they contributed 335 of 857 dashboard TODOs, overwhelmingly upstream (FIXME (15321): solve CI failures…). But basic-harness is a genuine collaboration (7 of 14 commits, the rest another author), so you can’t infer ownership from an absent remote or a single author.
  3. Vendored code lands in the TODO count as if it were yours. The Obsidian vault notes-jbh reported 424 TODOs, and the top offenders were committed third-party bundles: obsidian-shellcommands/main.js (113), an Obsidian plugin’s main.js (66), github-copilot/main.js (52), plus a nested node_modules/@github/copilot/sdk/index.js (23). bevy reports 334 or more that belong to upstream. .gitignore doesn’t help. Committers checked the bundles in.
  4. Non-git directories are a real category, not rot. Thirteen configured entries are plain directories holding content (gemma-notes, health-notes, llm-eval-notes, no-github-notes at 564 MB and 5,933 markdown files, and others). They fail the git collector with could not find repository every build.
  5. Empty repositories are noise, not damage. Seven projects have zero commits and an unborn HEAD (adventOfCode-2025, BevyFace, curator, hello-leptos-trunk, leptos-tutorial, order, rustlings). The collector emits a warn! per build for each, implying malfunction where there is none.

Decision

cerebro gains a discovery pass that reconciles ~/Projects against the XDG config and reports the difference, and only writes when told to.

  1. Scan each immediate subdirectory of a configurable projects_dir (default ~/Projects).
  2. Classify every entry: registered project / unregistered git repository / worktree of a registered repository / non-git directory / stale config entry whose repo_path no longer exists.
  3. Deduplicate worktrees by git rev-parse --git-common-dir, comparing against the canonical repository, and attribute each worktree to its parent project. A fixture verifies the attribution, never directory-name matching.
  4. Gate on authorship, not on shape. Discovery proposes a directory as a project when it has commits by the configured user. Remote owner is a corroborating signal, never a requirement. The absence of a remote and a single author must both still admit a project. basic-harness is the permanent regression fixture for “a genuine collaboration a naive heuristic would discard”, and the three upstream clones are the fixture for the opposite.
  5. Deny vendored paths in the TODO collector as a prerequisite. Discovery multiplies the number of scanned directories, and every wrong one becomes dashboard noise immediately. The collector’s existing git-plumbing deny list (is_git_plumbing(), todos.rs:92, from 507a292) now extends to vendored roots: .obsidian, node_modules, vendor, dist, and target. A regression test records the reason, in the same style as the plumbing fix. This lands before or with discovery, not after.
  6. Non-git directories are first-class. The build accepts a registered non-git directory for note scanning and keeps it out of the git collector, so it no longer fails with could not find repository. no-github-notes is the scale fixture.
  7. Empty repositories are informational, not warnings. Discovery reports an unborn HEAD in its summary, and the build stops warn!ing per project.
  8. Report by default. --sync-config applies. cerebro discover prints the classified diff and writes nothing: unregistered repositories, worktrees with their parents, non-git directories, empty repositories, stale entries. cerebro discover --sync-config appends the accepted entries to the XDG config. An opt-in apply is what keeps scratch directories such as test, llm-test, rig-test, and hello-*, plus archive dumps, out of config.
  9. An explicit deny list prunes both report and apply. Directories named in config are never proposed and never written, whether the exclusion is “archived”, “not mine”, or “scratch”. The list is config-extensible and empty by default, matching this project’s preference for explicit exclusions over inferred ones.
  10. cerebro status reports coverage. It surfaces directories on disk that config doesn’t list, plus stale entries pointing at missing paths, so silent ignorance gets a visible signal.

Consequences

Pros

  • The corpus stops being a subset chosen by whoever last edited a text file. The 30-unregistered-repos gap closes, and recursion has a measurable signal via cerebro status: a new project can no longer sit invisible in the journal.
  • Report-first means discovery is safe to run at any time. Nothing about a read-only run can change what the build produces.
  • Worktree and authorship gating protect the numbers the dashboard already shows: no double-counted commits, no upstream engine dominating a TODO list.
  • The vendored-path fix improves every existing project, not only discovered ones. It’s worth landing even if discovery slips.

Cons

  • Discovery is a new subsystem with its own failure modes, and the interesting ones, worktree attribution and authorship gating, stay invisible until the numbers go wrong. Fixtures are load-bearing, not ceremony.
  • The authorship gate needs a configured user identity. Where discovery can’t determine the user, it falls back to reporting only, never to auto-applying.
  • --sync-config writes to the file that’s now authoritative per 0014. A bug there edits the source of truth. Append-only semantics and a printed diff before writing bound the damage.

Migration

Current behavior needs no changes. Discovery is additive and read-only until you pass --sync-config. The intended first run is:

cerebro discover                 # read-only: what is on disk that config misses
cerebro discover --sync-config   # accept the additions into the XDG config
cerebro status                   # confirm coverage is now 100%

Discovery also reports a rotted config: entries whose paths no longer exist, plus upstream clones with no owner commits. Removing those entries is a manual edit in the first version, because deletion isn’t reversible by a diff a human reads.

Notes

  • Issue #71 also found that the generated markdown is a public interface with at least two consumers, and a format change already broke one silently. The heading ### [name](...) became a bold name plus an [Open project →](...) link, and the activity line and its em-dash separator changed with it. Pinning that contract with a fixture, including hyphenated and mixed-case names such as advent-of-code-2025, AddyHomework, and LLM-on-a-budget, is a separate decision. It’s tracked under the same coverage release but not part of discovery policy.
  • The collector’s assumption that HEAD is refs/heads/main was one of the audit’s early hypotheses. Its author withdrew it after direct inspection: the seven affected projects have zero commits, so revwalk on an unborn HEAD behaves correctly. This policy treats them as informational for that reason and doesn’t “fix” branch detection.
  • Discovery writes to the XDG config and the MCP server reads the XDG config per 0014, so a sync reaches a running list_projects without a second write path.

16. Keep ADR records in adr-tools compatible mode

Date: 2026-10-23

Status

Accepted

Context

The repo carries two ADR tool configs. adrs.toml sets mode = "compatible" and adr_dir = "docs/decisions", producing plain Nygard markdown with no YAML frontmatter. The rust-standard (docs/standard/prose.md) assumes NextGen mode with YAML frontmatter, tags, and link metadata, and puts records inside the mdBook source tree via adr_dir = "docs/adr".

Cerebro diverges from the standard on both axes: it uses compatible mode, and its ADR directory (docs/decisions) already sits inside the mdBook source and is wired into docs/SUMMARY.md under the Decisions section. All fifteen existing records (0001-0015) are compatible-mode Nygard markdown already linked from the book. The rust-standard’s .adr-dir legacy marker is also present, kept for adr-tools-compatible consumers.

The open question from the gap analysis: should cerebro migrate to the standard’s NextGen mode and relocate to docs/adr, or stay as it is? Migration would add YAML frontmatter to every existing record and force a SUMMARY rewrite, for metadata (tags, structured links) that cerebro does not currently use.

Decision

Keep compatible mode. ADR records stay as plain Nygard markdown in docs/decisions/, with no YAML frontmatter and no tags. The .adr-dir file remains for adr-tools consumers. Cerebro does not adopt the standard’s NextGen mode.

The docs/decisions location is retained rather than renamed to the standard’s docs/adr, because the directory is already the mdBook source location and is already enumerated in docs/SUMMARY.md under the Decisions section. Relocating would break existing SUMMARY links and the Pages build for no functional gain.

Where cerebro needs structured links (Supersedes, Amends, Relates to), it uses the standard Nygard convention of a ## Links section with plain markdown bullets, since compatible mode cannot carry link metadata in frontmatter.

Consequences

The existing fifteen records stay valid without editing their headers or rewriting the SUMMARY. The book’s Decisions tree and Codeberg Pages deploy are unaffected.

Cost: cerebro cannot use the adrs MCP update_tags, suggest_tags, or the frontmatter-backed link_adrs graph. Cross-references must be hand-written in a ## Links section. New records follow the Nygard full variant the command-line tool emits by default, keeping the corpus uniform.

The divergence from the rust-standard’s prose section is deliberate and is itself a deviation from the standard; the standard’s NextGen defaults do not apply to this repo. Future template-sync work must not force-migrate the directory.

17. Forbid unsafe code workspace-wide with env-free config tests

Date: 2026-10-23

Status

Accepted

Relates to 9. Storage trait for dependency injection

Context

The rust-standard lint table (docs/standard/lints.md) lists unsafe_code as forbid, a stricter level than deny, “no escape at any level”. Adopting that table as-is would fail the build, because cerebro-core currently contains fourteen unsafe { ... } blocks, all in #[cfg(test)] test code.

The unsafe is real, not vestigial. Since Rust edition 2024, std::env::set_var and std::env::remove_var are unsafe functions. Cerebro’s XDG config resolution reads XDG_CONFIG_HOME and HOME, so its tests manipulate the process environment directly. Each test takes a global ENV_LOCK mutex to serialize against other env-mutating tests, then calls the unsafe setters inside an unsafe block, with a SAFETY comment, and restores the prior value afterward.

This creates two problems. First, adopting the standard’s forbid(unsafe_code) fails immediately. Second, the global-lock pattern is fragile: it relies on every env-touching test acquiring the same mutex, and it mutates process-global state that the library reads through std::env::var. The workspace already favors dependency injection over ambient state (ADR-0009, Storage trait for DI).

Decision

Refactor config-path resolution so tests no longer mutate the process environment. Introduce an explicit environment source in cerebro-core: a function that resolves the XDG config path from an injected key-value lookup (a closure or a &BTreeMap<String, String> implementing a small Env trait) rather than calling std::env::var internally. Production callers pass a thin adapter over std::env; tests pass a literal map, with no set_var, no mutex, and no unsafe.

After the unsafe blocks are gone, adopt the standard’s forbid(unsafe_code) in [workspace.lints.rust]. The forbid then holds with nothing to escape, matching the standard’s intent.

This is sequenced as its own phase in the rust-standard alignment plan, separate from the general lint-table adoption, because the refactor must land and pass before the forbid can be turned on without breaking CI.

Consequences

The test suite loses the ENV_LOCK mutex and the paired-restore discipline, removing a footgun where a forgotten restore poisons later tests. Environment handling becomes injectable and testable without global state, consistent with ADR-0009.

Enabling forbid(unsafe_code) closes the door on future unsafe, including the edition-2024 env functions, so any later need for set_var must route through the injected lookup instead of reintroducing unsafe blocks.

Cost: a small API change in cerebro-core to thread the environment source through the call sites that resolve config and cortex paths. Any code that resolved paths by reading ambient env must switch to the injected form. The refactor is confined to config-path resolution and its tests; collectors that read git/sqlx do not read env this way.

Until the refactor lands, the standard’s full lint table cannot be adopted as written, because the forbid on unsafe_code would fail on the fourteen existing blocks. The alignment plan treats this ADR as a prerequisite gate for the lint-table phase.

18. Close the platform-promise gap without cargo-dist

Date: 2026-10-23

Status

Accepted

Relates to 12. Cut releases with git tags and forge releases, not release-plz

Context

Cerebro ships three binaries, cerebro, cerebro-mcp, and cerebro-tui, and ADR-0012 cut the release flow to git-cliff plus a Codeberg forge release made by the API. The rust-standard (docs/standard/ci-and-release.md) pairs binary shipping with cargo-dist (dist-workspace.toml), a platform-promise target list agreed with deny.toml [graph].targets, and a CI cross-check step. The gap analysis flagged no dist config, no declared target list, and no cross-check, and proposed adopting cargo-dist.

Checking the current dist docs before recording that decision contradicts the easy version of it. Two claims matter. First, dist’s generated CI supports only github as a backend, and its host/announce steps create a GitHub Release and derive installer artifact URLs from a Source Host that is “currently … only … github.com”, a check that explicitly “does not respect publish=false or dist=false”. The Codeberg/Forgejo work is open upstream (axodotdev/cargo-dist#1781, no timeline), and the only path today is the manual workaround the issue itself describes: point the repository URL at a fabricated GitHub link, run dist init, rename .github, and strip the fabrication before publishing. That re-couples the release flow to a fake GitHub identity, which is precisely what ADR-0012 removed.

Second, the release-plz blocker that ADR-0012 recorded does not by itself rule dist in or out: cargo dist build uses cargo build and packaging, not cargo package, so a publish = false path-dependency workspace builds fine. The blocker is the hosting and installers, not the compilation.

So the three gaps split. A declared platform promise and a cross-check CI step are forge-neutral and can land without dist. Reproducible multi-target tarballs with generated curl | sh installers cannot be honestly wired to a Codeberg release page until dist supports the forge.

Decision

Adopt the forge-neutral half of the standard’s release layer now, and defer the part that depends on cargo-dist’s forge support.

Close the platform-promise and cross-check gaps directly, with no dist dependency: declare the target list once in deny.toml [graph].targets, mirroring the standard’s cross-check split. A new .woodpecker/ci.yml cross-check step builds the Linux gnu targets in a container; the darwin targets stay checked on the local development Mac. These are the two gaps the standard’s cross-check actually enforces, and neither needs dist.

Do not adopt cargo-dist as the release host or CI generator. Its announce and installer pipeline is GitHub-only and would require the fabricated-source-host workaround that ADR-0012 explicitly removed. Keep git-cliff and the Codeberg forge release (ADR-0012) as the release path; ship source via the existing tags, and point users at the documented cargo install --path crates/cerebro flow rather than a generated curl | sh installer that cannot resolve against Codeberg.

Revisit cargo-dist only when upstream #1781 (Gitea/Forgejo hosting) merges. If at that point dist’s build layer still adds value, adopt it as a local artifact-packing job feeding the existing forge upload, never as a self-hosting CI generator. Until then record this deferral in the wayfinding map as an open, blocked ticket rather than a silent omission.

Consequences

The two gaps that do not need cargo-dist, a declared platform promise and a cross-target check, close immediately and stay forge-neutral. The target list lives once in deny.toml [graph].targets and is read by the CI cross-check step, matching the standard’s single-source rule without importing dist.

The third gap, reproducible tarballs and installers, stays open by decision rather than oversight. It is blocked on cargo-dist gaining Codeberg/Forgejo hosting (upstream #1781), and a curl | sh installer cannot be generated honestly until installers resolve against Codeberg’s real release-asset URLs.

Recorded cost of the status quo: cerebro’s release page links source tarballs the forge makes (git tags exist) but no per-platform prebuilt binaries or installers, so users follow the documented cargo install --path flow. That is acceptable for three internal binaries and matches ADR-0012’s cargo install install story.

This ADR does not amend or supersede ADR-0012. The tag-and-forge-release model and the git-cliff changelog both stand unchanged; the only thing this record changes from the gap analysis is rejecting the earlier assumption that cargo-dist slots into release.yml, which the docs contradict.

19. Collect commits by date window, and let the author instant own the day

Date: 2026-11-24

Status

Accepted

Relates to 9. Storage trait for DI, 15. Project discovery reports, it does not absorb

Context

The journal claims that a day page holds what happened that day. The git collector could not deliver that. Git::commits walked 20 commits from HEAD and returned the timestamps git orders by, the committer instants. Two failures followed, and issue #114 measured both on 2026-11-21.

A day with more than twenty commits arrived with twenty. Worse, a finished day shrank as newer work landed: the same Saturday page read 57 commits, then 47, then 27 across one day of builds, with no change to Saturday. One repository fell off its own page once its newest twenty commits were all dated the next day.

The second failure was quieter. Git orders a history walk by committer time, and a rebase, amend, or merge rewrites the committer stamp while leaving the author stamp alone. Bucketing by the committer instant therefore filed Saturday’s rebased work on Sunday. Rebase enough of a branch and the record moves days.

Both failures come from one substitution: a count stood in for a date range, and a landing stamp stood in for the moment the work was written.

Decision

Make the collector answer a question about dates.

Git::commits takes a CommitWindow of instants instead of returning a fixed number of commits, and returns a CommitScan. The window is settings.commit_window_days civil days ending with today, default 365, which is how far back the journal writes pages. One number feeds both, so a page can never be built for a day the collector refused to read. settings.max_commits defaults to 5000 and bounds the work per repository.

GitCommit carries both authored_at and committed_at. Every site that decides which day a commit belongs to reads authored_at. The committer instant stays because it is the only honest key for the walk, not because a page needs it.

The walk breaks on committed_at and filters on authored_at, inside a floor padded 30 days past the window start. Ordering and stopping must agree, and git2::Sort::TIME orders by committer time. Breaking on the author instant would stop the walk exactly where rebased history begins, dropping the commits the bug is about. The pad covers the reverse case, a commit whose author stamp sits ahead of its committer stamp; measured across the 134-project registry, the largest such gap is about an hour, so 30 days is margin rather than a guess. CommitScan::scanned records how many commits the walk inspected, so “did the early exit fire” is measured rather than assumed.

A guard that binds in silence is the original bug at a smaller scale, so max_commits reports itself. CommitScan::truncated reaches ProjectContext::git_truncated, and a day page or project page built from a truncated list carries a visible marker.

Consequences

Day pages stop depending on the clock. Rebuilding 2026-11-21 after a commit lands on 2026-11-24 changes nothing about that Saturday, which is the claim in the issue title and now an assertion in the tests.

Counts rise. A project page reports a year of history instead of twenty commits, and the dashboard’s fleet total moves from a capped figure to whatever happened. That is the fix arriving, not a regression, and the PR says so. Two pages keep their own scope rather than inheriting the window: a project page lists the newest 50 commits and states how many more the window holds, and this-week.md counts the commits authored in the week it names.

cerebro build --fresh becomes corrective rather than destructive. While the count stood, a fresh rebuild could only shrink recorded days. Issue #123, where an existing day page is skipped instead of rewritten, is unchanged here and becomes safely repairable on its own.

The public shape changes: GitCommit.time is gone, the Git trait takes a window, and ProjectContext gained a field. Every consumer moved in the same commit, so nothing half-migrated survives. Cache files needed no migration; the scan cache stores timestamps only.