Skip to content
dtoolkit

dcontext — Context

dcontext is the bridge between dbrain and your AI coding CLI. It hooks into the native lifecycle of each supported CLI to inject persistent memory at session start and save transcripts before compaction discards them.

Without dcontext, every new session starts from zero. With it, your agent knows who you are, what you are working on, and what it learned yesterday.

dcontext operates at two points in the CLI lifecycle:

  1. Session start — Before the agent sees your first message, dcontext injects a context block into the CLI’s instruction file. This block contains your identity, personality traits, project facts, and relevant memories retrieved from dbrain.

  2. Pre-compaction — When a CLI is about to compact (summarize and discard) its conversation history, dcontext intercepts the transcript and sends it to dbrain for storage. This prevents knowledge loss across long sessions.

The result is a continuous memory loop:

Session N transcript → dbrain (save) → Session N+1 context (inject) → ...

At session start, dcontext builds a ContextBlock[] payload from dbrain and writes it into the CLI’s native instruction file. The injected context includes:

SectionSourceDescription
Identitydbrain entityName, role, communication style, personality traits
User profiledbrain entityWho you are, preferences, working hours, language
Project factsdbrain factsActive decisions, architecture notes, conventions for the current repo
Relevant memoriesdbrain recallHot and warm memories ranked by relevance to the current workspace
Session historydbrain conversationsSummary of recent sessions for continuity

The exact content depends on what you have stored in dbrain. A fresh brain with no facts produces a minimal injection. A well-populated brain produces rich, targeted context.

dcontext supports four AI coding CLIs, each through its native hook system:

CLIHook mechanismInstruction fileConfig file
Claude Codesettings.json hooksCLAUDE.md.claude/settings.json
Gemini CLIsettings.json hooksGEMINI.md.gemini/settings.json
Codex CLIconfig.toml hooksAGENTS.md.codex/config.toml
OpenCodenpm plugin systemAGENTS.mdOpenCode plugin config

Each adapter is implemented in its own package (@dtoolkit/adapter-claude, @dtoolkit/adapter-gemini, etc.) and exposes a DcontextTarget interface that dcontext uses to read and write the correct files.

There are two ways to set up dcontext. Both achieve the same result.

  1. Install dcontext globally

    install
    pnpm add -g @dtoolkit/dcontext
  2. Initialize configuration

    Run the init wizard. It will ask which CLI you use and where your dbrain instance is running.

    terminal
    dcontext init
  3. Install hooks into your CLI

    This registers the session-start and pre-compaction hooks with your chosen CLI.

    terminal
    dcontext install
  4. Verify the installation

    terminal
    dcontext status

    You should see your CLI listed with hooks registered and dbrain connection confirmed.

If you already have dbrain running, the connect command handles dcontext setup for you.

terminal
dbrain connect claude

This installs dcontext hooks for Claude Code and configures the connection to your local brain in one step. Replace claude with gemini, codex, or opencode as needed.

CommandDescription
dcontext initInteractive setup wizard. Configures which CLI to hook into and the dbrain endpoint.
dcontext installRegisters hooks with the target CLI. Writes to the CLI’s config file.
dcontext uninstallRemoves hooks from the target CLI. Cleans up config and instruction file sections.
dcontext statusShows current hook registration, dbrain connectivity, and last injection timestamp.
dcontext exploreOpens an interactive browser of what dcontext would inject for the current workspace. Useful for debugging context quality.

Check what context would be injected for the current directory:

terminal
dcontext explore

Remove hooks from Gemini CLI:

terminal
dcontext uninstall --target gemini

Each CLI has a different mechanism for running code at session boundaries. dcontext adapts to each one.

Config file: .claude/settings.json Instruction file: CLAUDE.md

Claude Code supports hooks in settings.json under the hooks key. dcontext registers two hooks:

  • PreToolUse (session start) — Runs before the first tool call. dcontext queries dbrain, builds the context payload, and writes it into a <!-- dcontext:start --> section in your project’s CLAUDE.md.
  • PostToolUse (pre-compaction) — Fires when the session is about to compact. dcontext extracts the transcript and sends it to dbrain via the /conversations endpoint.
.claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "dcontext inject --target claude"
}
]
}
]
}
}

The adapter uses the shared writeDcontextMdSection() helper from @dtoolkit/core to write the delimited block in CLAUDE.md without disturbing your existing content.

dcontext is built as a thin orchestration layer. It owns no data and stores no state beyond a small config file. All persistent data lives in dbrain.

┌─────────────┐ ┌──────────────┐ ┌──────────────┐
│ CLI hooks │────▶│ dcontext │────▶│ dbrain │
│ (native) │ │ (inject / │ │ (REST API) │
│ │◀────│ save) │◀────│ :7878 │
└─────────────┘ └──────────────┘ └──────────────┘
│ │
▼ ▼
CLAUDE.md / SQLite + FTS5
GEMINI.md / (entities, facts,
AGENTS.md conversations)

Key design decisions:

  • No daemon — dcontext runs only when triggered by CLI hooks. No background process, no port, no resource consumption at rest.
  • Adapter pattern — Each CLI adapter implements the DcontextTarget interface from its adapter package. dcontext calls inject() and save() without knowing CLI-specific details.
  • Idempotent writes — The writeDcontextMdSection() helper replaces the delimited block in-place. Running inject twice produces the same result as running it once.
  • ContextBlock contract — All context flows through the ContextBlock[] type defined in @dtoolkit/core. This is the same contract used by dproxy and other dtoolkit packages.

Context not appearing in sessions

Run dcontext status to verify hooks are registered and dbrain is reachable. Then run dcontext explore to see what would be injected. If the output is empty, your dbrain likely has no facts for the current workspace.

Stale context after dbrain changes

Context is injected at session start. Changes to dbrain during a session will not appear until the next session. Restart your CLI session to pick up new facts.

Hook conflicts with existing settings

dcontext merges its hooks into your existing config file. If you have custom hooks, dcontext appends to the hooks array rather than replacing it. Check your config file to verify both your hooks and dcontext hooks are present.

terminal
dcontext status --verbose

This shows the raw hook configuration and any detected conflicts.

  • dbrain — The memory server that dcontext reads from and writes to
  • dwork — AI-native project manager, works alongside dcontext for project awareness
  • MCP tools reference — Full reference for dbrain MCP tools used by dcontext
  • CLI reference — Complete CLI reference for all dtoolkit packages