Generated banner for honcho
Generated logo for honcho

honcho

Memory frameworkOfficial Plastic Labs project

Created by Plastic Labs

Published in plastic-labs/honcho. Publisher page

8,063 GitHub stars

What it is

Memory library for building stateful agents
— the description by Plastic Labs

AutoGineer overview, from the brain’s own files

Honcho is a memory infrastructure layer designed to give AI agents persistent, reasoning-first memory. It operates on a peer-centric model where users, agents, and groups are tracked as entities that evolve. By processing conversations and events in the background, Honcho extracts conclusions and maintains representations that can be queried to provide context-aware, personalized responses. It supports multi-peer sessions and provides a unified interface for agents to store, reason about, and retrieve information, helping to build data moats and improve agent trust.

How it works

Memory model: Hybrid

AutoGineer overview, from the brain’s own files

Honcho functions as a memory loop: it stores messages and events in sessions, processes them asynchronously in the background to update peer representations, and allows agents to query this context. It uses a hybrid storage approach with Postgres for relational data and vector databases for semantic search. The system is accessible via a FastAPI server, client SDKs for Python and TypeScript, and various agent-specific plugins that integrate with tools like Claude Code and Cursor.

Folders
FolderRoleFiles
.claudeagent-config1
.githubagent-config24
assetsattachments1
docsdocs175
examplesexamples35
scriptsscripts17
skillsagent-instructions12
srcsource-code175
teststests417
.agentsfolder1
.cursor-pluginfolder1
.vscodefolder2
databasefolder1
dockerfolder3
harness-plugin-corefolder12
hermes-plugin-honchofolder62
honcho-clifolder57
integrationsfolder24
kilo-honchofolder37
mcpfolder37
migrationsfolder50
sandboxfolder11
schemasfolder1
sdksfolder87
typingsfolder1

The agent reads

The agent writes

Requirements

Apps: Docker

Runtimes: Python >=3.13

Databases: Chroma, LanceDB, PostgreSQL, Qdrant, Redis

API keys (by name): AUTH_JWT_SECRET, HONCHO_API_KEY, LANGFUSE_SECRET_KEY, LLM_ANTHROPIC_API_KEY, LLM_GEMINI_API_KEY, LLM_OPENAI_API_KEY, VECTOR_STORE_CHROMA_API_KEY, VECTOR_STORE_QDRANT_API_KEY, VECTOR_STORE_TURBOPUFFER_API_KEY, WEBHOOK_SECRET

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Google Antigravity, Kiro, OpenCode, Amp, Roo Code, Cline, JetBrains Junie, Devin (ex-Windsurf)

Set it up

  1. This brain runs code automatically: 3 hooks (claude-code), 3 scripts. Review honcho-cli/src/honcho_cli/commands/install.py, honcho-cli/src/honcho_cli/commands/setup.py, honcho-cli/src/honcho_cli/local/setup.py, integrations/cursor/hooks/hooks.json before opening the folder in Claude Code. No step below turns a hook on for you.

    • honcho-cli/src/honcho_cli/commands/install.py: python honcho-cli/src/honcho_cli/commands/install.py
    • honcho-cli/src/honcho_cli/commands/setup.py: python honcho-cli/src/honcho_cli/commands/setup.py
    • honcho-cli/src/honcho_cli/local/setup.py: python honcho-cli/src/honcho_cli/local/setup.py
    • integrations/cursor/hooks/hooks.json: bun run ${CURSOR_PLUGIN_ROOT}/dist/hook.js session-start
    • integrations/cursor/hooks/hooks.json: bun run ${CURSOR_PLUGIN_ROOT}/dist/hook.js before-submit-prompt
    • integrations/cursor/hooks/hooks.json: bun run ${CURSOR_PLUGIN_ROOT}/dist/hook.js after-agent-response
  2. Not scanned by AutoGineerThe author’s README also describes installing it from a clone of its repository. Read its install section: AutoGineer did not scan that path. https://github.com/plastic-labs/honcho/blob/fae27192ac153a035b245e7b5217628f04bc23df/README.md#quick-start-from-source-docker
  3. Created by Plastic Labs. Published in plastic-labs/honcho. Licence: GNU Affero General Public License v3.0 only.

Usage

AutoGineer overview, from the brain’s own files

  • Store interaction history across sessions
  • Query peer-specific representations or workspace-wide context
  • Inject prompt-ready context into LLM calls
  • Perform hybrid search using BM25 and vector embeddings
  • Manage multi-peer conversation sessions
  • Inspect background processing and queue status
“What learning styles does the user respond to best?”
The agent retrieves the peer representation from Honcho to provide a personalized answer based on historical interactions.
“Get context for the current session.”
The agent fetches a summary and relevant tokens from the session to inject into an LLM completion request.

Documentation by Plastic Labs

<!-- markdownlint-disable MD033 -->

<div align="center"> <a href="https://app.honcho.dev" target="_blank"> <img src="assets/honcho.svg" alt="Honcho" width="400"> </a> </div> <!-- markdownlint-enable MD033 -->


Image: Static Badge Image: PyPI version Image: NPM version Image: CLI Image: Discord

Honcho is memory infrastructure for building stateful agents that understand changing people, agents, groups, projects, and ideas over time.

Store messages and events, let Honcho reason in the background, then query peer representations, session context, search results, or natural-language insights from any model or framework. Use it managed at api.honcho.dev, run a local stack with honcho start, or self-host the FastAPI server yourself.

Using Honcho as your memory system will earn your agents higher retention, more trust, and help you build data moats to out-compete incumbents.

Honcho has defined the Pareto Frontier of Agent Memory. Watch the video, check out our evals page, and read the blog post for more detail.

Contents

  • Start Here

  • Why Honcho

  • The Honcho Loop

  • Quickstart

  • What Honcho Gives You

  • Integrations

  • CLI

  • Core Concepts

  • Benchmarks & Evals

  • Self-hosting

  • Configuration

  • Architecture

  • SDKs

  • Learn More

  • Contributing

  • License

The Honcho project is split between several repositories, with this one hosting the core service logic — implemented as a FastAPI server. Client SDKs for Python and TypeScript live in the sdks/ directory. The honcho-cli package lives here too.

Start Here

I want to...PathGet started
Give my coding agent persistent memoryClaude Code, Cursor, Grok Bot, OpenCode, Kilo Code, OpenClaw, Hermes, or any MCP clientIntegrations
Add memory to my productPython or TypeScript SDKQuickstart
Run Honcho locallyInstall CLI, then honcho start --setupCLI
Inspect a deploymenthoncho workspace inspect, honcho doctorCLI
Self-host from sourceDocker Compose or local developmentSelf-hosting

Why Honcho

CapabilityWhat it means
Reasoning-first memoryExtracts conclusions from conversations and events, not just matching chunks.
Peer-centric modelTracks users, agents, groups, projects, and ideas as entities that change over time.
Multi-peer perspectiveModels what one peer knows about another when configured.
Managed or self-hostedUse api.honcho.dev, honcho start locally, or run the FastAPI server yourself.
Agent-tool integrationsMCP, Claude Code, Cursor, Grok Bot, OpenCode, Kilo Code, OpenClaw, Hermes.

The Honcho Loop

  1. Store conversations, events, documents, or tool traces as messages on a session.

  2. Reason — Honcho processes the queue in the background and updates peer representations.

  3. Query — ask Honcho for context, search results, peer representations, or a natural-language answer.

  4. Inject — drop the result into any LLM call or agent framework.

Concretely: workspaces hold peers, peers participate in sessions, messages live on sessions, and Honcho builds a per-peer representation that you query through the Chat Endpoint or directly.

Quickstart

Get an API key at app.honcho.dev — when you sign up you'll be prompted to join an organization, which gets its own dedicated Honcho instance. Or install the CLI and run honcho start --setup, then point the SDK at http://localhost:8000.

Python
pip install honcho-ai
# or: uv add honcho-ai
# or: poetry add honcho-ai
import os
from honcho import Honcho

# Managed service uses api.honcho.dev by default. For self-hosted, pass
# base_url="http://localhost:8000" or set HONCHO_URL.
honcho = Honcho(
    workspace_id="my-app-testing",
    api_key=os.environ["HONCHO_API_KEY"],
)

# 1. Store: peers and messages on a session
alice = honcho.peer("alice")
tutor = honcho.peer("tutor")
session = honcho.session("session-1")
session.add_messages([
    alice.message("Hey there — can you help me with my math homework?"),
    tutor.message("Absolutely. Send me your first problem!"),
])

# 2. Reason: happens asynchronously in the background.

# 3. Query: ask Honcho what it knows, or pull prompt-ready context.
answer = alice.chat("What learning styles does the user respond to best?")
context = session.context(summary=True, tokens=10_000)

# 4. Inject: hand the context to your model of choice.
from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
    model=os.environ.get("OPENAI_MODEL", "gpt-4o-mini"),
    messages=context.to_openai(assistant=tutor),
)
TypeScript
npm install @honcho-ai/sdk
# or: bun add @honcho-ai/sdk
import { Honcho } from "@honcho-ai/sdk";
import OpenAI from "openai";

const honcho = new Honcho({
  workspaceId: "my-app-testing",
  apiKey: process.env.HONCHO_API_KEY,
});

const alice = await honcho.peer("alice");
const tutor = await honcho.peer("tutor");
const session = await honcho.session("session-1");
await session.addMessages([
  alice.message("Hey there — can you help me with my math homework?"),
  tutor.message("Absolutely. Send me your first problem!"),
]);

const answer = await alice.chat(
  "What learning styles does the user respond to best?",
);
const context = await session.context({ summary: true, tokens: 10_000 });

const openai = new OpenAI();
const completion = await openai.chat.completions.create({
  model: process.env.OPENAI_MODEL ?? "gpt-4o-mini",
  messages: context.toOpenAI({ assistant: tutor }),
});

Note: background reasoning is asynchronous. Newly-added messages may take a moment to be reflected in chat/representation responses; for low-latency reads, use the representation endpoint.

What Honcho Gives You

NeedAPI
Save interaction historysession.add_messages(...)
Ask what Honcho knows about a peerpeer.chat(...)
Ask across the whole workspacehoncho.chat(...) / honcho.chat_stream(...)
Get prompt-ready contextsession.context(...).to_openai(...) / .to_anthropic(...)
Hybrid search (BM25 + vector)peer.search(...), session.search(...), honcho.search(...)
Low-latency static representationspeer.representation(...), session.representation(...)
Import documentssession.upload_file(...)
Inspect background processinghoncho.queue_status(...)

See the full SDK Reference and API Reference.

Integrations

Honcho ships a first-party memory plugin for every major coding agent. They all read the same ~/.honcho/config.json, so one key configures all of them — and pointing two at the same workspace gives them one shared memory.

AgentInstallSource
Claude Code/plugin marketplace add plastic-labs/claude-honchoclaude-honcho
Codexnpm install -g @honcho-ai/codex-honchocodex-honcho
CursorInstall Honcho from the Cursor Marketplaceintegrations/cursor
Grok BotAdd to Grok Bot from the Honcho plugin pageintegrations/cursor
DeepSeek Harnessdsh plugin --profile <name> add @honcho-ai/dsh-honchodsh-honcho
OpenCodeopencode plugin "@honcho-ai/opencode-honcho" --globalopencode-honcho
Kilo Codekilo plugin @honcho-ai/kilo-honcho --globalkilo-honcho
OpenClawopenclaw plugins install @honcho-ai/openclaw-honchoopenclaw-honcho
Hermeshermes memory setupbuilt in upstream
Any MCP clientclaude mcp add honcho --transport http ...MCP guide

Get a key at app.honcho.dev, then honcho init (or uv tool install honcho-cli && honcho init) writes it to ~/.honcho/config.json once for every integration. Cursor and Grok Bot are the exception: the marketplace plugin signs in with OAuth, and honcho init is optional there (in Cursor it turns on automatic capture).

Claude Code

Two ways, depending on how deep you want to go:

Plugin (richer integration — recommended for Claude Code users):

/plugin marketplace add plastic-labs/claude-honcho
/plugin install honcho@honcho

Raw MCP (works in any MCP client — Cursor, Cline, Windsurf, etc.):

claude mcp add honcho \
  --transport http \
  --url "https://mcp.honcho.dev" \
  --header "Authorization: Bearer hch-your-key-here" \
  --header "X-Honcho-User-Name: YourName"

Details: Claude Code guide · MCP guide · repo.

Codex
npm install -g @honcho-ai/codex-honcho
codex-honcho install      # registers hooks + MCP + skill in ~/.codex

Restart Codex to load the hooks. Details: Codex guide · repo.

Cursor and Grok Bot

One Cursor Marketplace listing serves both. In Cursor, open Customize, install Honcho, authenticate the honcho MCP server, then run /honcho-setup once. In Grok Bot, add Honcho under Connect apps (or Add to Grok Bot from the plugin page) and ask a Bot to set up Honcho. The plugin connects to the hosted MCP server over OAuth and ships the skills that drive the memory loop, so nothing runs locally. Details: Cursor guide · Grok Bot guide · source.

DeepSeek Harness
dsh plugin --profile <name> add @honcho-ai/dsh-honcho

A native Cordis plugin. It injects memory into the system prompt and captures new information from the session event feed. The model gets three tools — honcho_search, honcho_chat, and honcho_remember — and you can run /honcho to check status. Details: DeepSeek Harness guide · repo.

OpenCode
opencode plugin "@honcho-ai/opencode-honcho" --global

Details: OpenCode guide · repo.

Kilo Code
kilo plugin @honcho-ai/kilo-honcho --global

One install covers the Kilo CLI, the VS Code extension, and the JetBrains plugin, since all three run the same Kilo server. Details: Kilo Code guide · source.

OpenClaw
openclaw plugins install @honcho-ai/openclaw-honcho
openclaw honcho setup
openclaw gateway --force

openclaw honcho setup prompts for your API key, writes the config, and optionally migrates legacy MEMORY.md / USER.md / IDENTITY.md files into Honcho (non-destructive — originals are never deleted). Details: OpenClaw guide · repo.

Hermes
hermes memory setup   # select "honcho", point at api.honcho.dev or your local server

Details: Hermes guide.

Add Honcho to your own codebase (agent skill)

For wiring the Honcho SDK into an existing application, install the integration skill — it explores your codebase, asks about integration preferences, generates the SDK setup, and verifies it works:

npx skills add plastic-labs/honcho

Then invoke /honcho-integration in Claude Code (or /honcho-dev:integrate via the plugin marketplace). The same command also installs the memory skills — honcho-memory (concepts: the recall/record loop, session and peer strategy, plus how to connect and drive an MCP-connected Honcho) and honcho-cli (inspecting a deployment, or running a local stack with honcho start). Details: agentic development guide.

Other MCP clients

The same claude mcp add form (or its client-specific equivalent) works in any MCP-compatible client. See MCP guide.

CLI

honcho-cli inspects a Honcho deployment from the terminal, or runs a personal local stack with Docker.

uv tool install honcho-cli
honcho init                 # Honcho API key or browser login + server URL
honcho start --setup basic  # local stack: LLM provider key + Docker
honcho doctor

honcho init authenticates the CLI against a Honcho server. honcho start --setup is a separate step: it writes the LLM provider key the local deriver needs and starts API + deriver + Postgres + Redis.

Full commands and local-stack details: CLI reference · honcho-cli/README.md. To develop the server from source, see Self-hosting.

Core Concepts

Honcho organises everything around peers — humans and AI agents alike are first-class entities. The peer model enables:

  • Multi-participant sessions with mixed human and AI agents

  • Configurable observation settings (which peers observe which others)

  • Flexible identity management for all participants

  • Support for complex multi-agent interactions

Peers exchange messages within sessions; Honcho reasons over those messages to build a representation of each peer that you can query.

  • Workspace (formerly App): top-level container; isolates data between use cases.

  • Peer (formerly User): any participant — human user or AI agent.

  • Session: a conversation context; many-to-many with peers.

  • Scope: a named grouping of sessions that bounds recall (chat, representation, search) to those members.

  • Message: an atomic data unit (peer-to-peer communication or ingested document chunk).

What you query out of Honcho:

  • Conclusions — what Honcho has extracted about a peer (deductive and inductive). Exposed via the conclusions API.

  • Representations — static, low-latency snapshots of what Honcho knows about a peer (optionally session-scoped).

  • Peer Cards — compact identity summaries.

  • Session context / summaries — prompt-ready bundles for long-running conversations.

<!-- markdownlint-disable MD033 -->

<details> <summary>Internal storage (Collections &amp; Documents)</summary>

Internally, Honcho stores peer-related observations in collections of vector-embedded documents. Collections are keyed by (observer, observed) peer pairs — the same mechanism powers self-representation (observer == observed) and cross-peer modelling (peer X's understanding of peer Y). These primitives are not exposed directly; the Conclusions API is the public surface.

</details> <!-- markdownlint-enable MD033 -->

<!-- TODO(vineeth/marketing): write the "Honcho vs RAG / vector DB / memory-only" comparison. Audit recommendation referenced; copy intentionally deferred to avoid inventing positioning claims unsupported by primary sources. -->

Benchmarks & Evals

Honcho's evals span LongMemEval, LoCoMo, and other long-conversation benchmarks. See the evals page, the research blog post, and the Pareto-frontier announcement video for methodology and reproducible results.

Self-hosting

Honcho is open source under AGPL-3.0. To run a personal instance, install the CLI (uv tool install honcho-cli) and then honcho start --setup. The paths below are for building from source, contributing, or deploying without the CLI.

Quick start (from source, Docker)
git clone https://github.com/plastic-labs/honcho.git
cd honcho
cp docker-compose.yml.example docker-compose.yml
cp .env.template .env       # set LLM_OPENAI_API_KEY (see "LLM provider" below for OpenRouter etc.)
docker compose up

Then point the SDKs at it:

honcho = Honcho(workspace_id="my-app-testing", base_url="http://localhost:8000")
# or: export HONCHO_URL=http://localhost:8000

<!-- markdownlint-disable MD033 -->

<details> <summary>Without Docker (manual setup)</summary>

Everything below runs directly on the host — no Docker required. You need:

  • uv (it installs the required Python, 3.13+, for you)

  • PostgreSQL with the pgvector extension, local or managed

  • An API key for one LLM provider

Redis is optional; caching is off by default (CACHE_ENABLED=false).

  1. Clone and install

git clone https://github.com/plastic-labs/honcho.git
cd honcho
uv sync
  1. Set up PostgreSQL with pgvector

Install Postgres and pgvector natively, then create a honcho role and database and enable the extensions in it as a superuser.

On Ubuntu/Debian:

# Postgres and pgvector majors must match the distro's packaged version.
# Ubuntu 24.04:
sudo apt install postgresql-16 postgresql-16-pgvector
# Debian 12:
sudo apt install postgresql-15 postgresql-15-pgvector
# Other versions: add the PostgreSQL APT repo (apt.postgresql.org) first.

sudo -u postgres psql -c "CREATE ROLE honcho LOGIN PASSWORD 'honcho';"
sudo -u postgres createdb -O honcho honcho
sudo -u postgres psql -d honcho -c "CREATE EXTENSION IF NOT EXISTS vector;"
sudo -u postgres psql -d honcho -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;"  # optional, speeds up message search

On macOS, Homebrew makes your login user the superuser, so drop the sudo -u postgres:

brew install postgresql@17 pgvector
brew services start postgresql@17

psql -d postgres -c "CREATE ROLE honcho LOGIN PASSWORD 'honcho';"
createdb -O honcho honcho
psql -d honcho -c "CREATE EXTENSION IF NOT EXISTS vector;"
psql -d honcho -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;"

A managed Postgres that offers pgvector (Supabase, Neon, RDS, and so on) works too. Enable the same extensions in its database.

  1. Configure .env

cp .env.template .env

Only two settings are required:

DB_CONNECTION_URI=postgresql+psycopg://honcho:honcho@localhost:5432/honcho
LLM_OPENAI_API_KEY=sk-...

DB_CONNECTION_URI must use the postgresql+psycopg prefix (a SQLAlchemy requirement).

LLM provider. You need one key, not one per vendor. Every feature defaults to openai / gpt-5.4-mini, and embeddings default to openai / text-embedding-3-small. To use OpenRouter or another OpenAI-compatible endpoint (Together, Fireworks, vLLM, Ollama, LiteLLM), put that provider's key in LLM_OPENAI_API_KEY and set the model and base URL on each feature in .env:

LLM_OPENAI_API_KEY=sk-or-v1-...
DERIVER_MODEL_CONFIG__MODEL=google/gemini-2.5-flash
DERIVER_MODEL_CONFIG__OVERRIDES__BASE_URL=https://openrouter.ai/api/v1
# ...repeat for DIALECTIC_LEVELS__*, SUMMARY_*, DREAM_*

Models must support tool calling. If your provider doesn't serve embeddings, point EMBEDDING_MODEL_CONFIG__* at one that does. See .env.template for every per-feature line, and the configuration guide for direct Anthropic/Gemini keys and mixing providers.

Auth. Auth is off by default (AUTH_USE_AUTH=false). Turn it on before exposing the server to a network. Enabling it requires a JWT secret, which you can generate with:

python scripts/generate_jwt_secret.py

This will generate a JWT secret and print it to the console. You can then set the AUTH_JWT_SECRET environment variable. This is required for AUTH_USE_AUTH:

AUTH_JWT_SECRET=<generated_secret>

Once auth is enabled, use scripts/generate_jwt.py to mint tokens for local development and scripting:

# Admin token (full access, no expiry)
uv run python scripts/generate_jwt.py --admin

# Admin token expiring in 24 hours
uv run python scripts/generate_jwt.py --admin --expires 24h

# Admin token for a tenant -- required when MULTI_TENANT is enabled, since a
# token with no tenant claim is rejected for every caller, admin included
uv run python scripts/generate_jwt.py --admin --tenant acme

# Workspace-scoped token
uv run python scripts/generate_jwt.py --workspace my-workspace --expires 30d

# Capture a token for use in curl/scripts
TOKEN=$(uv run python scripts/generate_jwt.py --admin --print-only)
curl -H "Authorization: Bearer $TOKEN" http://localhost:8000/v3/workspaces

Duration units: s (seconds), m (minutes), h (hours), d (days), w (weeks), y (years).

  1. Run database migrations

uv run alembic upgrade head

Migrations hold a session-level advisory lock, so they need a session-mode connection (direct Postgres or a session pooler), not a transaction-mode pooler. A Supabase-style :6543 port is rewritten to :5432 automatically.

  1. Launch Honcho

Two processes need to run alongside the database.

Start the API server:

uv run fastapi dev src/main.py                  # local development, reloads on code changes
uv run fastapi run --host 0.0.0.0 src/main.py   # on a server

Start a background worker (deriver):

In a separate terminal, run:

uv run python -m src.deriver

The deriver generates representations, summaries, peer cards, and manages dreaming tasks. You can increase the number of derivers to improve runtime efficiency.

For verification steps and production notes, see Self-hosting docs → Manual Setup.

</details> <!-- markdownlint-enable MD033 -->

Contributors: install the git hooks with uv run pre-commit install --hook-type pre-commit --hook-type commit-msg --hook-type pre-push. Tests only run at push time, so a clean commit is not a clean push. Deploying to Fly.io: see Self-hosting docs → Deploying on Fly.io.

Multi-tenant mode

MULTI_TENANT=true makes one Honcho serve many tenants on one database, with row-level security scoping every query to the tenant bound on the connection. Honcho does not create the roles itself; the startup validator checks them and refuses to boot otherwise. The database needs these roles (the first and the last may be one role):

  • the migration role (DB_OWNER_CONNECTION_URI, falling back to DB_CONNECTION_URI when unset), which owns the schema and runs alembic upgrade head, created WITH LOGIN BYPASSRLS. Message search runs through a SECURITY DEFINER function owned by this role: the full-text and ILIKE operators are not leakproof, so under RLS the content indexes cannot serve them, and the function reads as its owner, pinned to the bound tenant. If the function was created by a role without BYPASSRLS, boot fails with the repair: ALTER FUNCTION message_text_matches_page(...) OWNER TO <the BYPASSRLS role> (the full signature is in the error);

  • the app role (DB_CONNECTION_URI), an ordinary role with no BYPASSRLS, which every tenant-scoped query runs as. It needs GRANT EXECUTE ON FUNCTION message_text_matches_page(...) TO <app role>, which alembic upgrade head grants with the flag on: EXECUTE is revoked from PUBLIC so no other role can reach the function's RLS bypass, and boot fails with the exact statement when the grant is missing;

  • the service role (DB_SERVICE_CONNECTION_URI), WITH LOGIN BYPASSRLS, for the cross-tenant background work (the deriver claim, the reconciler).

Every tenant table needs ENABLE and FORCE ROW LEVEL SECURITY, a policy USING (tenant_id = current_setting('app.tenant', true)) WITH CHECK (...), and SELECT, INSERT, UPDATE, DELETE granted to the app and service roles. With the flag on, alembic upgrade head applies all of that itself after the revisions run, so a release that adds a tenant table needs nothing by hand; the roles come from DB_CONNECTION_URI and DB_SERVICE_CONNECTION_URI. The connection must not go through a transaction-mode pooler. Self-hosted single-tenant installs leave the flag off; none of this applies then.

A single-tenant instance can still name the tenant that owns its data with TENANT_ID, with the flag off.

Configuration

Honcho uses a flexible configuration system that supports both TOML files and environment variables. Configuration values are loaded in priority order: environment variables > .env file > config.toml > defaults.

Copy the example file to get started:

cp config.toml.example config.toml

The file is organized by subsystem — [app], [db], [auth], [cache], [llm], [deriver], [dialectic], [summary], [dream], [peer_card], [webhook], [metrics], [telemetry], [vector_store], and [sentry]. Any value can be overridden by an environment variable named {SECTION}_{KEY}, using __ for nesting (DIALECTIC_LEVELS__low__MODEL_CONFIG__MODEL), or just {KEY} for app-level settings.

See the configuration reference for every available option, and .env.template for an annotated list of environment variables.

Architecture

Honcho splits into two services: Storage (workspaces, peers, sessions, scopes, messages, internal collections) and Insights (reasoning, conclusions, representations, summaries, the chat endpoint). Storage is synchronous via the API; Insights is asynchronous via a background queue consumed by the deriver worker process.

Key features:

  • Rich Reasoning System — multiple implementation methods that extract conclusions from interactions and build comprehensive representations of peers

  • Chat Endpoint — reasoning-informed responses that integrate conclusions with current context

  • Background Processing — asynchronous processing pipeline for expensive operations like representation updates and session summarization

  • Multi-Provider Support — configurable LLM providers for different use cases

<!-- markdownlint-disable MD033 MD001 -->

<details> <summary>Storage primitives in detail</summary>

Honcho contains several different primitives used for storing application and peer data. This data is used for managing conversations, modeling peer identity, building RAG applications, and more.

The philosophy behind Honcho is to provide a platform that is peer-centric and easily scalable from a single user to a million.

Below is a mapping of the different primitives and their relationships.

Workspaces
├── Peers ←──────────────────┐
│   ├── Sessions             │
│   └── (internal collections, keyed by observer/observed peer pair)
│                            │
├── Scopes ←─────────────────┤ (many-to-many with sessions)
│                            │
└── Sessions ←───────────────┤ (many-to-many with peers)
    ├── Peers ───────────────┘
    └── Messages (session-level)

Relationship Details:

  • A Workspace contains multiple Peers and Scopes.

  • Peers and Sessions have a many-to-many relationship (peers can participate in multiple sessions, sessions can have multiple peers).

  • Scopes and Sessions have a many-to-many relationship (a session can belong to several scopes; a scope groups many sessions).

  • Messages belong to a session and are labelled by their source peer.

  • Internal collections of vector-embedded documents are keyed by (observer, observed) peer pairs. They are not directly exposed via the API; the observations stored in them are exposed as Conclusions.

Users familiar with APIs such as the OpenAI Assistants API will be familiar with much of the mapping here.

Workspaces

This is the top level construct of Honcho. Developers can register different Workspaces for different assistants, agents, AI enabled features, etc. It is a way to isolate data between use cases and provide multi-tenant capabilities.

Peers

Within a Workspace everything revolves around a Peer. The Peer object represents any participant in the system — whether human users or AI agents. This unified model enables complex multi-participant interactions.

Sessions

The Session object represents a set of interactions between Peers within a Workspace. Other applications may refer to this as a thread or conversation. Sessions can involve multiple peers with configurable observation settings. A session can optionally join one or more Scopes at creation, or later via the scopes API.

Scopes

A Scope is a named grouping of sessions inside a Workspace. It is a visibility boundary on recall: chat, representation, session context, and workspace search answered through a scope see only what happened in that scope's member sessions. The underlying peers keep their unified representations across everything they have participated in.

Developers manage scopes through the scopes API (honcho.scope(...) / honcho.scopes()) and an optional scopes field on session create — not through observer/observed configuration. Adding a session that already has messages copies its existing explicit conclusions into the scope (no re-derivation); removing one reconciles those copies back out. Query backfill progress with the scope status endpoint.

A single scope name answers from that scope's collection and card. A list of scopes restricts recall to the union of their member sessions. Empty scopes fail closed. scope is mutually exclusive with session / filters on the same read.

Messages

The Message represents an atomic data unit that exists at the session level: communication between peers within a session context. All messages are labelled by their source peer and can be processed asynchronously to update their representations. This flexible design allows for both conversational interactions and broader data ingestion for personality modelling.

</details> <!-- markdownlint-enable MD033 MD001 -->

<!-- markdownlint-disable MD033 -->

<details> <summary>Reasoning pipeline</summary>

The reasoning functionality of Honcho is built on top of the Storage service. As Messages and Sessions are created for Peers, Honcho will asynchronously reason about peer psychology to derive facts about them and store them in reserved internal collections.

A high level summary of the pipeline is as follows:

  1. Messages are created via the API.

  2. Derivation tasks are enqueued for background processing, including:

    • representation: update representations of Peers.

    • summary: create summaries of Sessions.

  3. Session-based queue processing ensures proper ordering.

  4. Results are stored internally and surfaced via the Conclusions API, Representations, Peer Cards, and the Chat Endpoint.

</details> <!-- markdownlint-enable MD033 -->

<!-- markdownlint-disable MD033 MD001 -->

<details> <summary>Retrieving data and insights</summary>

Honcho exposes several different ways to retrieve data from the system to best serve the needs of any given application.

Get Context

In long-running conversations with an LLM, the context window can fill up quickly. To address this, Honcho provides a context endpoint that returns a combination of messages, conclusions, summaries from a session up to a provided token limit.

Use this to keep sessions going indefinitely. If you'd like to see this in action, try out Honcho Chat.

There are several search endpoints that let developers query messages at the Workspace, Session, or Peer level using a hybrid search strategy.

Requests can include advanced filters to further refine the results.

Chat API

The flagship interface for using these insights is the Chat Endpoint (POST /peers/{peer_id}/chat). It takes natural-language requests to get data about a peer and returns reasoning-grounded responses. Examples:

  • Asking Honcho for a generic or specific insight about the peer.

  • Asking Honcho to hydrate a prompt with data about the peer's behaviour.

  • Asking Honcho for a second opinion on how to respond.

  • Getting personalised responses that incorporate long-term facts and context.

Representations

For low-latency use cases, Honcho provides access to a representation endpoint that returns a static document with insights about a peer in the context of a particular session. Use this to quickly add context to a prompt without having to wait for an LLM response.

</details> <!-- markdownlint-enable MD033 MD001 -->

SDKs

SDKs are versioned independently of the server. Current SDK versions track each other; the server badge above reflects the deployed server version.

See the SDK Reference for full API surface, the API Reference for the raw HTTP API, and per-SDK example folders for runnable demos.

Learn More

Contributing

Pull requests are limited to maintainers. If you find a bug or want a change, please open an issue instead. If you think your work is an exception, make the case in Discord, where maintainers are most active.

See CONTRIBUTING.md for the full process, an architecture walkthrough, and a map of where to change what. For vulnerabilities, see SECURITY.md — note that Honcho does not operate a bug bounty.

License

Honcho is licensed under the AGPL-3.0 License. Learn more at the License file.

CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Before opening a PR or filing an issue, read If you're an agent in CONTRIBUTING.md. Pull requests are limited to maintainers (write access); everyone else files an issue. Issues follow Filing an issue.

Honcho Overview

What is Honcho?

Honcho is an infrastructure layer for building AI agents with memory and social cognition. Its primary purposes include:

  • Imbuing agents with a sense of identity

  • Personalizing user experiences through understanding user psychology

  • Providing a Chat Endpoint (the Dialectic agent) that injects personal context just-in-time

  • Supporting development of LLM-powered applications that adapt to end users

  • Enabling multi-peer sessions where multiple participants (users or agents) can interact

Honcho leverages the inherent reasoning capabilities of LLMs to build coherent models of user psychology over time, enabling more personalized and effective AI interactions.

Core Concepts

Peer Paradigm

Honcho uses a peer-based model where both users and agents are represented as "peers". This unified approach enables:

  • Multi-participant sessions with mixed human and AI agents

  • Configurable observation settings (which peers observe which others)

  • Flexible identity management for all participants

Key Primitives
  • Workspace (formerly App): The root organizational unit containing all resources

  • Peer (formerly User): Any participant in the system (human or AI)

  • Session: A conversation context that can involve multiple peers

  • Message: Data units that can represent communication between peers OR arbitrary data ingested by a peer to enhance its global representation

  • Collections & Documents: Internal vector storage for peer representations. Collections are keyed by (observer, observed) peer pairs. Collections/Documents are not directly exposed via API, but the observations stored within them are exposed as Conclusions (see /v3/.../conclusions endpoints).

Architecture Overview

API Structure

All API routes follow the pattern: /v3/{resource}/{id}/{action}. Most "list/search" endpoints are POST so they can accept rich filter bodies.

  • Workspaces: Create, list, update, search

  • Peers: Create, list, update, chat (dialectic), messages, representation

  • Sessions: Create, list, update, delete, clone, manage peers, get context

  • Messages: Create (batch up to 100), upload (file), list, get, update

  • Conclusions: Create, list, query (semantic search), delete — the API-facing name for observations stored in (observer, observed) collections

  • Keys: Create scoped JWTs

  • Tenants: Create (idempotent), get, update (PATCH, derivation_paused only), delete — the above-tenant provisioning surface for control-plane use; authenticated by a service secret, not a JWT (see Tenant isolation)

  • Webhooks: Register endpoint, list, delete, test

Key Features
Chat Endpoint (Dialectic agent) (/peers/{peer_id}/chat)
  • Provides bespoke responses informed by the representation

  • Integrates long-term facts from vector storage

  • Supports streaming responses

  • Configurable LLM providers

Message Processing Pipeline
  1. Messages created via API (batch or single)

  2. Enqueued for background processing:

    • representation: Update peer's context

    • summary: Create session summaries

  3. Session-based queue processing ensures order

  4. Results stored internally in vector DB

Configuration
  • Hierarchical config: config.toml + environment variables

  • Database settings with connection pooling

  • Multiple LLM provider support

  • Background worker (deriver) settings

  • Authentication can be toggled on/off (AUTH_USE_AUTH); under MULTI_TENANT it must be on for API instances — the startup validator refuses the combination

Development Guide

Commands
  • Setup: uv sync

  • Run server: uv run fastapi dev src/main.py

  • Run tests: uv run pytest tests/

  • Run single test: uv run pytest tests/path/to/test_file.py::test_function

  • Reproduce an API bug (5xx, wrong status) as a property test: see the property-repro skill (skills/property-repro/)

  • Linting: uv run ruff check src/

  • Typechecking: uv run basedpyright

  • Format code: uv run ruff format src/

SDK Testing
TypeScript SDK

The TypeScript SDK tests run against a real Honcho server. bun run test (not bare bun test, which has no server to talk to) starts one for them: scripts/run_ts_sdk_tests.py creates a throwaway database on the Postgres named by DB_CONNECTION_URI, migrates it, starts the API and the mock LLM provider (src/mock_provider), runs bun test, and tears it all down. No provider key is needed. They are not part of uv run pytest.

cd sdks/typescript && bun run test             # whole suite
cd sdks/typescript && bun run test peer.test   # bun test args pass through

To type-check the TypeScript SDK (this is fine to run directly):

cd sdks/typescript && bun run tsc --noEmit
Code Style
  • Follow isort conventions with absolute imports preferred

  • Use explicit type hints with SQLAlchemy mapped_column annotations

  • snake_case for variables/functions; PascalCase for classes

  • Line length: 88 chars (Black compatible)

  • Explicit error handling with appropriate exception types

  • Docstrings: Use Google style docstrings

  • Never hold a DB session during external calls (LLM, embedding, HTTP). If a function needs both a DB session and an external call result, compute the external result first and pass it as a parameter. This avoids tying up DB connections during slow network I/O. Use tracked_db for short-lived, DB-only operations; pass a shared session when multiple DB-only calls can reuse one connection.

  • Never write through a read-only session (tracked_db(..., read_only=True), get_read_db, ReadSessionLocal). These run in AUTOCOMMIT mode with no transaction: writes are NOT blocked by the database — they silently commit immediately, and begin_nested() savepoints break. There is no runtime guard; this is enforced by convention only. Use read_only=True strictly for SELECT-only windows; anything that mutates (including get-or-create paths) must use a regular write session.

  • Tenant isolation (MULTI_TENANT, default off). When enabled, every DB session carries a request-scoped app.tenant GUC so row-level-security policies scope reads and writes to a single tenant. tracked_db is then the per-tenant path and is fail-closed — it raises before any query if no tenant is in scope (a passed tenant_id or an ambient tenant_context). The same fail-closed rule holds where a tenant is read implicitly: the tenant_id column default (models._default_tenant_id) raises flag-on with no tenant bound rather than stamp 'default', the message-ingest advisory lock (crud.message._ingest_lock) is keyed on the bound tenant, and the deriver fails a representation work unit whose key carries no tenant prefix instead of reading its batch unscoped. service_db is the explicit RLS-bypass path for the legitimately cross-tenant work (the deriver's queue claim, the reconciler, the dreamer); never do per-tenant writes on it. For an HTTP request, the ambient tenant_context is bound once, in require_auth (src/security.py), from the tenant claim on the caller's JWT, and reset when the request completes — never do a per-tenant write outside a request without threading tenant_id explicitly. A startup validator (src/startup/tenant_isolation_validator.py) refuses to boot on half-states where isolation cannot hold (a transaction-mode pooler, RLS not enforced, no service role) or cannot serve (auth disabled on an API instance: with AUTH_USE_AUTH off every request is a tenant-less admin, no tenant is ever bound, and every tracked_db fails closed — an outage, not a leak; the deriver takes its tenant from the claimed work unit's key, so the deriver entrypoint skips that check). Off (the default, self-host), all of this is inert and honcho runs single-tenant on plain Postgres. TENANT_ID (flag-off only; boot is refused with it set flag-on) names that single tenant, as a name and not isolation: models.instance_tenant_id() is what the flag-off column default stamps and scoped_tenant_id filters on ('default' when unset), telemetry.tenant.current_tenant_id() reports it, and the migrations read it at migrate time — e5fe7f8bcf62 backfills and seeds it, 0c67be41049b writes it into _queue_item_token_count's probe for tenant-less queue rows. It is fixed for the life of a database: the validator refuses to boot when the rows carry another tenant. Enforced by tests/test_single_tenant_mode.py (flag off with every subordinate setting — DB_SERVICE_CONNECTION_URI, DB_POOLER_MODE, TENANT_API_SECRET — set to a value flag-on would act on, nothing changes; add any new tenant-subordinate setting to _SUBORDINATES there) and tests/startup/test_fresh_single_tenant_deploy.py (empty database → alembic upgrade head → all three validators → first write and first claim, under the shipped defaults).

  • Tenant registry (/v3/tenants). A third auth plane sits above the two in the previous bullet: the registry provisions tenants before any JWT for that tenant can exist, so it cannot use require_auth at all — it is guarded by a constant-time-compared service secret (TENANT_API_SECRET), disabled by default and inert unless MULTI_TENANT is also on. That plane authenticates the caller as the control plane, never as a tenant, and the two planes are enforced never to mix on the same route. vector_correlation_id (the tenant's vector-store namespace key) is required on create, min_length=1, max_length=128, RESOURCE_NAME_PATTERN — a tenant registered without one must not be served under MULTI_TENANT (the namespace resolver, src/vector_store/tenant_namespace.py, fails closed rather than substitute a default), so a missing or malformed key is a 422 at the control plane's first allocation rather than a NULL discovered later. A tenant_id equal to a work-unit task type (utils.work_unit.TASK_TYPES) is also a 422: work-unit keys tell a tenant prefix from a task type by that set, so such a tenant could never enqueue work. Create never mutates a tenant (same id + different fields is a 409, which is what makes the control plane's provisioning retries safe); the one mutation door is PATCH /v3/tenants/{id}, whose allowlist is schemas.TenantUpdate (extra="forbid") and has two entries with different semantics: derivation_paused, the control plane's mirrored "do not claim this tenant's billable work" bit, is fully mutable and idempotent, and GET /v3/tenants?derivation_paused=true lists the tenants that carry it; vector_correlation_id is set-once — a NULL row accepts a value, an equal value is a no-op, and a row that already holds a different value is a 409. Set-once is what keeps the resolver's process-lifetime memoization of the key safe without cross-process invalidation: it never caches a missing key (it refuses to serve instead), so the only transition the verb allows is one nothing has cached; the check runs under a row lock so two concurrent PATCHes cannot both see NULL. The deriver honours the bit in SQL, not in process state: crud.deriver.not_paused_clause is a NOT EXISTS against tenants.derivation_paused (served by the partial index ix_tenants_derivation_paused) that the claim, the in-unit fetches and the backlog metrics all apply, so a pause lands on the next claim or batch fetch with no staleness window, and KEDA's eligible count and the claim cannot disagree. It pauses only billable work: task types in crud.deriver.PAUSE_EXEMPT_TASK_TYPES (deletion, webhooks, scope maintenance, the tenant-less reconciler) keep running, and any new task type is paused until it is added there. Excluded units stay in the backlog (skipped, not drained) and are reported on their own gauges, per tenant. Like the previous bullet, all of this is inert with the flag off.

  • Startup validators (src/startup/). Both the API lifespan and the deriver entrypoint run them before serving traffic or claiming work, and each fails closed: validate_embedding_schema (pgvector column dims vs settings), validate_tenant_isolation (above), and validate_queue_item_batches — the deriver claim reads only the trigger-maintained queue_item_batches aggregate, so the process refuses to boot unless that table exists and its three queue triggers are present and enabled; otherwise enqueued work would be invisible to every deriver with no error anywhere.

Multi-row locking and deadlocks

Tables written concurrently by more than one worker — documents (deriver, dreamer, scope backfill/removal, reconciler), queue (every deriver replica), and queue_item_batches (trigger-maintained from every queue write, and claimed FOR UPDATE SKIP LOCKED by every deriver replica) — deadlock when two writers touch an overlapping row set in different orders. Rules:

  • A multi-row SELECT ... FOR UPDATE MUST carry an explicit ORDER BY <pk>. Without it Postgres locks in scan order, which differs per plan, so two writers with overlapping sets can cycle. _apply_document_row_updates in src/crud/document.py is the reference implementation.

  • WHERE id IN (...) does NOT impose an order, so sorting the Python list is a no-op — the list order is discarded and the planner picks Bitmap Heap Scan (ctid order), Index Scan (id order), or Seq Scan per invocation. Deterministic ordering requires either a preceding SELECT ... ORDER BY id FOR UPDATE or WHERE id IN (SELECT id ... ORDER BY id FOR UPDATE).

  • Document.id is a random nanoid (models.py), so id order is uncorrelated with physical order — an unordered predicate UPDATE/DELETE is roughly a coin flip against an id-ordered locker per row pair, not a rare edge case. (QueueItem.id is an integer identity, so there id order is also chronological.)

  • Prefer no separate lock phase. A single UPDATE ... WHERE <predicate> acquires row locks as it writes, so it has no lock phase of its own. Reach for FOR UPDATE only when a value must be read, computed in Python, and written back — that read-modify-write is the only reason _apply_document_row_updates locks (it replaced a server-side func.greatest()), and populate_existing=True is required with it so the identity map doesn't serve a stale pre-lock value. Server-side expressions (func.greatest, the JSONB - operator) avoid the read-back. A single predicate UPDATE/DELETE still locks its rows in scan order, so against another writer that locks an overlapping row set in id order it can still deadlock: when the rows can overlap another multi-row writer's, wrap the predicate in WHERE id IN (SELECT id ... ORDER BY id FOR UPDATE), as the queue writes do (next bullet).

  • Every multi-row write to queue locks in id order or skips locked rows. Build it as WHERE id IN (crud.deriver.queue_ids_locked_in_order(...)), or with FOR UPDATE SKIP LOCKED for garbage collection that can leave a held row for the next pass (cleanup_queue_items). A transaction that also touches the claim table writes queue first, then active_queue_sessions: the batch-completion order, which session and workspace deletion follow through crud.deriver.delete_queue_items_and_claims. tests/deriver/test_queue_write_lock_policy.py lists every update/delete of models.QueueItem in src/ with how it locks; a new one fails that test until it is added.

  • Write documents before collections, and lock collections rows in sorted key order. Every explicit-document insert bumps its collection's counters (crud.collection.record_explicit_documents, which updates in sorted (tenant_id, workspace_name, observer, observed) order), so a collection row is locked until the insert commits. Any transaction that touches several of one observer's collections (process_scope_removal, the scope backfill) must take its document locks first and then its collection locks in that same order, or it can deadlock against a concurrent insert.

  • FOR UPDATE SKIP LOCKED (the reconciler's claim pattern, and the deriver's own work-unit claim over queue_item_batches — claim_rows_query in src/crud/deriver.py) never waits, so it cannot be a deadlock partner for other SKIP LOCKED lockers — but it still locks in output order, its held locks can be the partner a blocking locker deadlocks against (the backlog triggers retry for exactly this), and holding those locks across an external call still stalls other writers. See the "never hold a DB session during external calls" rule above.

Auth scoping
  • Named-scope keys (sc plus w) require explicit allow_scope=True on supported routes. This grants both recall and ingestion within that scope, not peer-member write access. Recall handlers must bind their projection to the token; session routes check active scope membership. Keep the named-scope route allowlist in tests/routes/test_auth_route_policy.py synchronized. Never allow restricted keys to enroll unrelated existing sessions or fall back to global recall.

  • allow_member_read=True (in require_auth(...)) is read-only — NEVER set it on a route that mutates state. It lets a peer-scoped key reach a session route when its peer is an active member of the session, so on a mutating route it would hand any session member write access (message injection, config mutation, deletion). HTTP method is not a reliable read/write signal here (some read routes use POST for a richer body), so this is enforced by an explicit allowlist in tests/routes/test_auth_route_policy.py — adding the flag to a new route fails that test until you consciously add the route to EXPECTED_MEMBER_READ_ROUTES, and you must never add a mutating method there.

  • Under MULTI_TENANT, the tenant-claim check in auth() must run before the admin short-circuit. An admin JWT (ad: true) is admin only within its own tenant; if the tenant gate moved after the admin check, a tenant-less admin token would bypass tenant scoping entirely.

  • The tenant-registry API (/v3/tenants) uses require_tenant_api, never require_auth. It is a separate, above-tenant auth plane authenticated by a service secret; a route must not carry both dependencies. Enforced by test_tenant_api_routes_use_their_own_auth_plane in tests/routes/test_auth_route_policy.py.

  • When a member-read route is keyed by another sub-resource (e.g. peers/{peer_id}/config), the handler must additionally confirm a peer-scoped caller only reads its OWN resource (jwt_params.p == peer_id, else raise AuthenticationException). Membership grants session access, not access to a co-member's data. See get_peer_config in src/routers/sessions.py.

Runtime Architecture

Honcho runs as two cooperating processes that share a Postgres database and Redis cache:

  • API server (uv run fastapi dev src/main.py) — handles HTTP, enqueues background work, returns immediately. Hosts the Dialectic agent inline (synchronous tool loop during chat requests). Every API replica runs DeriverMetricsPoller (src/backlog.py): the deriver/KEDA gauges every 30 s, and the dream-due check plus the MessageEmbedding backlog counts (embeddings_pending, embeddings_pending_due) every DREAM_DUE_POLL_INTERVAL_SECONDS, reusing the last counts in between. Under DERIVER_SCHEDULER=api every replica also enqueues the due dreams it finds; enqueue_dream dedupes on the work-unit key.

  • Deriver worker (uv run python -m src.deriver) — long-running queue consumer (uvloop). Runs the Deriver, Summarizer, and Dreamer off the queue. Can run multiple process replicas (a deployment concern, orthogonal to config); within one process, DERIVER_WORKERS (≤512) sets concurrent work-unit tasks, further capped by DB-pool headroom via DERIVER_WORKERS_PER_POOL_CONNECTION — when the pool is the binding cap, the process logs it at boot and exports deriver_effective_worker_cap. Also hosts an in-process Reconciler scheduler (src/reconciler/) that periodically embeds messages with sync_state='pending' in MessageEmbedding and cleans up stale queue items — embedding generation is decoupled from message creation by design.

Agent Architecture

Honcho uses several specialized LLM agents. They share tool definitions and the LLM client abstraction in src/utils/agent_tools.py + src/llm/.

Terminology: what users see as conclusions (the public API surface and the term we use in documentation) is called observations in code symbols — create_observations, delete_observations, get_observation_context, etc. Doc prose below uses "conclusions"; references to actual code symbols stay as "observations."

1. Deriver (src/deriver/)

Role: Memory formation through content ingestion.

The Deriver processes batches of incoming messages and extracts conclusions about peers. The current architecture is "minimal deriver" — a single LLM call per batch using structured output, not an agentic tool loop. This trades flexibility for cost and predictability.

  • Trigger: Messages enqueued by src/deriver/enqueue.py on message create; consumed by src/deriver/queue_manager.py → consumer.process_item() → deriver.process_representation_tasks_batch().

  • Claim: workers claim whole work units from queue_item_batches — a database-trigger-maintained aggregate (one row per pending unit: tenant, task type, token sum, oldest age) — via FOR UPDATE SKIP LOCKED, round-robin over tenant_id so no tenant starves another within a claim; a claimed unit is marked by an ActiveQueueSession row for the processing duration. Single-tenant deployments (every tenant_id NULL) get plain oldest-first ordering, unchanged.

  • Output: Explicit conclusions (direct facts) and deductive conclusions (inferences) saved to (observer, observed) collections.

  • Entry point: src/deriver/__main__.py → queue_manager.main().

  • Prompts: src/deriver/prompts.py (minimal_deriver_prompt).

  • Custom instructions: per-workspace/peer guidance can be threaded into the prompt via reasoning configuration; DERIVER__MAX_CUSTOM_INSTRUCTIONS_TOKENS caps the addition (default 2000) and DERIVER__MAX_INPUT_TOKENS defaults to 25000 to make room.

2. Dialectic (src/dialectic/)

Role: Analysis and recall for answering queries.

The Dialectic answers questions about peers by strategically gathering context from memory. It is the only tool-using agent on the synchronous request path — it loops over DIALECTIC_TOOLS until it has enough context to answer. (The Dreamer specialists also use tools, but run off the queue.)

  • Trigger: API call to POST /v3/.../peers/{peer_id}/chat.

  • Tools (see DIALECTIC_TOOLS in src/utils/agent_tools.py): search_memory, search_messages, get_observation_context, grep_messages, get_messages_by_date_range, search_messages_temporal, get_reasoning_chain. At the minimal reasoning level, a reduced set (DIALECTIC_TOOLS_MINIMAL) is used: just search_memory + search_messages.

  • Reasoning levels: 5 tiers — minimal, low, medium, high, max — each with its own model config (see DialecticLevelSettings in src/config.py).

  • Output: Natural language response grounded in gathered context. Supports SSE streaming.

  • Entry point: src/dialectic/chat.py → agentic_chat() / agentic_chat_stream() → DialecticAgent (in src/dialectic/core.py).

3. Dreamer (src/dreamer/)

Role: Consolidation and self-improvement of memory.

The Dreamer is an orchestrated multi-specialist system that runs during scheduled "dreams" to consolidate conclusions and build reasoning trees.

  • Trigger: Scheduled via DreamScheduler (src/dreamer/dream_scheduler.py) or explicit dream task on the queue.

  • Strategy: Surprisal-based prioritization (src/dreamer/surprisal.py) selects which conclusions to expand. The orchestrator (orchestrator.run_dream) runs two specialist phases:

    1. DeductionSpecialist (specialists.py) — produces deductive conclusions from explicit conclusions. Tools: get_recent_observations, search_memory, search_messages, create_observations_deductive, delete_observations, update_peer_card.

    2. InductionSpecialist — produces inductive conclusions from explicit + deductive conclusions. Tools: same discovery set + create_observations_inductive, update_peer_card.

  • Reasoning trees (src/dreamer/trees/, migration f1a2b3c4d5e6_add_reasoning_tree_columns): each conclusion links to its premises and downstream conclusions, enabling get_reasoning_chain traversal at recall time.

  • Output: Deductive/inductive conclusions, consolidated redundancies, updated peer cards.

  • Entry point: src/dreamer/orchestrator.py → process_dream() (the package-level export from src/dreamer/__init__.py), which wraps run_dream().

4. Summarizer (src/utils/summarizer.py)

Role: Two-tier session summarization (direct LLM call — no agentic tools).

  • Trigger: Runs as part of the queue pipeline alongside representation tasks.

  • Tiers: short summary every SUMMARY_MESSAGES_PER_SHORT_SUMMARY messages (default 20); long summary every SUMMARY_MESSAGES_PER_LONG_SUMMARY (default 60). Token caps configurable via SUMMARY_MAX_TOKENS_SHORT / SUMMARY_MAX_TOKENS_LONG.

Shared Agent Infrastructure
  • Tool definitions (src/utils/agent_tools.py): unified TOOLS dict; per-agent lists (DIALECTIC_TOOLS, DIALECTIC_TOOLS_MINIMAL, DREAMER_TOOLS, DEDUCTION_SPECIALIST_TOOLS, INDUCTION_SPECIALIST_TOOLS).

  • LLM subsystem (src/llm/): provider-agnostic honcho_llm_call(). Backends in src/llm/backends/ (anthropic.py, gemini.py, openai.py). Includes prompt caching (caching.py), structured output (structured_output.py), tool loop (tool_loop.py), and a model registry. History is typed (messages.py: SystemMessage, UserMessage, AIMessage, ToolMessage); callers pass plain role/content dicts, and each attempt's codec (codecs/, resolved through profiles.py) renders the history for that attempt's provider. Per-retry provider selection is pinned via an AttemptPlan so stream-final retries don't bounce back to primary after the tool loop has settled on fallback.

  • Per-agent model config: each agent has its own MODEL_CONFIG in src/config.py with fallback chains (see ConfiguredModelSettings, FallbackModelSettings).

  • Telemetry: cloudevents in src/telemetry/events/ cover API routes, dialectic, dream, deletion, reconciliation, representation, and per-call LLM accounting (llm.py — LLMCallCompletedEvent fires once per provider hit with full cost-attribution context). High-volume events are sampled deterministically per run_id via TelemetrySettings.HIGH_VOLUME_SAMPLE_RATE.

  • Prometheus metrics (src/telemetry/prometheus/): every metric carries a namespace label and every recorder is fail-soft (a metrics error never propagates into a request or a worker loop). Counter children with a bounded label domain are zero-initialized per process at startup — initialize_bounded_metrics(instance_type=...), called from the src/main.py lifespan (api) and src/deriver/__main__.py (deriver) — so an absent series means a broken scrape rather than "nothing happened". Two consequences worth knowing before touching telemetry:

    • Adding a BaseEvent subclass requires adding its _event_type to ALL_EVENT_TYPES in src/telemetry/events/__init__.py (and to HIGH_VOLUME_EVENT_TYPES if _volume_class == "high_volume"). Enforced by the drift guards in tests/telemetry/test_metric_zero_init.py, which assert set-equality against the discovered subclasses.

    • A service-wide, non-additive gauge must be refreshed by every replica that exports it, on its own timer, and aggregated with max()/avg(), never sum(); a process with no writer must not zero-init it. message_embeddings_pending is the example: it reports a DB-global count, so it is set only by DeriverMetricsPoller in every API process rather than from the work-unit-deduped reconciliation cycle — otherwise, combined with the zero-init, every replica that never won the work unit would export a confident permanent 0. It is set only by API processes, each on its own timer: aggregate with max(). Deriver pods have no writer for it, so they do not zero-init it and export no series.

  • Vector-store namespaces are per tenant (src/vector_store/tenant_namespace.py): a namespace is {prefix}.{doc|msg}.{hash(workspace[, observer, observed])} and the hash carries no tenant, so the prefix is the only thing separating one tenant's vectors from another's — and workspace.name is unique only within a tenant, so two tenants on the SDK-default "default" workspace would otherwise share a namespace. get_vector_namespace is therefore async and resolves the prefix per call: settings.VECTOR_STORE.NAMESPACE when MULTI_TENANT is off (byte-identical to pre-tenancy output, and this beats an explicit prefix=), otherwise the bound tenant's vector_correlation_id, memoized per process. The control plane is expected to set vector_correlation_id for every tenant it registers; nothing in this repo enforces that, so it is a precondition of turning the flag on rather than a guarantee. Two consequences worth knowing before touching the vector store:

    • It fails closed and never falls back to tenant_id. A tenant registered without a vector_correlation_id raises VectorNamespaceUnresolved rather than getting a fresh namespace, because a fresh namespace silently orphans whatever that tenant already had — the symptom would be an empty search, not an error. That exception is deliberately not a VectorStoreError: several callers catch VectorStoreError to mean "the backend is briefly unavailable, retry later", which would absorb a permanent provisioning failure as a transient one. A failed read of the key is still a VectorStoreError, because that one really is retryable.

    • Cross-tenant paths pass the row's prefix explicitly, and contain the failure per row. The reconciler and the soft-delete sweep run across all tenants on service_db with no ambient tenant, so they call prefix_for_tenant(row.tenant_id) and hand the result to get_vector_namespace(..., prefix=...). (Immediate embedding resolves the prefix the same per-row way, but it is not a cross-tenant path — its only entrypoints are the message-creation routes, so it runs on tracked_db bound to the request's tenant.) Each resolves inside a per-row try: one unresolvable tenant must degrade into the existing sync-attempt backoff, never abort a batch its co-tenants are in — an aborted batch rolls back before any attempt counter moves, so the offending row returns to the front of the next batch forever.

  • Tenant identity in telemetry (src/telemetry/tenant.py): under MULTI_TENANT the ambient tenant_context (bound per request in src/security.py, per work unit in src/deriver/queue_manager.py) is read at four chokepoints — the CloudEvents emitter adds a tenantid extension attribute to the envelope (source still names the instance), the six attribution counters (messages_created, dialectic_calls, deriver_queue_items_processed, deriver_tokens_processed, dialectic_tokens_processed, dreamer_tokens_processed) carry a tenant_id label via TenantScopedCounter, the Sentry isolation scope gets a tenant_id tag at both bind sites, and Langfuse's user.id is the tenant. Flag-off every surface is byte-identical to pre-tenancy output: no attribute, tenant_id="" (which Prometheus treats as absent, so zero-init and dashboards are unchanged), no tag, user.id = namespace. A flag-on emit with no tenant bound increments telemetry_events_untenanted{type} (reconciliation events exempt, they are tenant-less by construction) — non-zero means an emit site runs outside its bind scope. A cross-tenant path that makes a billable call binds that call's tenant instead of joining the exempt list: the reconciler groups its re-embeds by tenant and binds each group. Nothing threads a tenant through event classes or emit sites; do not add one.

  • Per-tenant fairness metrics (DERIVER_TENANT_FAIRNESS_METRICS, default off, also needs METRICS_ENABLED): deriver_claims_total{tenant_id} and the deriver_claim_wait_seconds{tenant_id} histogram (claim time − the unit's oldest_created_at) are recorded at the claim, for the units claim_work_units actually took; deriver_inflight_units{tenant_id} is rebuilt on the backlog-metrics poll from live active_queue_sessions (every API replica reports it: max(), never sum()). The claim runs on the service session with no tenant bound, so these take tenant_id from the work-unit key, not from TenantScopedCounter. Flag off: no series and no extra query.

Project Structure
src/
├── main.py              # FastAPI app: middleware, routers, lifespan, exception handlers
├── models.py            # SQLAlchemy ORM models (Workspace/Peer/Session/Message/
│                        #   MessageEmbedding/Collection/Document/QueueItem/
│                        #   QueueItemBatch/...)
├── config.py            # Pydantic-settings configuration (very large; see README)
├── db.py                # Engine + session/context management (request_context var)
├── dependencies.py      # FastAPI DI (tracked_db, etc.)
├── exceptions.py        # Custom exception types (HonchoException + subclasses)
├── security.py          # JWT authentication
├── embedding_client.py  # Embedding provider client (configurable dimensions
│                        #   via EMBEDDING_MODEL_CONFIG__DIMENSIONS_MODE)
├── schemas/             # Pydantic schemas
│   ├── api.py            # Public API request/response schemas
│   ├── configuration.py  # Per-resource configuration schemas
│   └── internal.py       # Internal-only schemas (queue payloads, etc.)
├── crud/                # Per-resource DB operations
│   ├── collection.py, deriver.py, document.py, message.py
│   ├── peer.py, peer_card.py, representation.py  (RepresentationManager)
│   ├── session.py, tenant.py, webhook.py, workspace.py
├── routers/             # FastAPI route handlers (all under /v3)
│   ├── workspaces.py, peers.py (dialectic /chat lives here), sessions.py
│   ├── messages.py, conclusions.py, keys.py, tenants.py, webhooks.py
├── dialectic/           # Dialectic agent — runs inline per chat request
│   ├── chat.py           # agentic_chat() / agentic_chat_stream()
│   ├── core.py           # DialecticAgent (the tool-loop driver)
│   └── prompts.py
├── deriver/             # Background queue consumer (separate process)
│   ├── __main__.py       # `python -m src.deriver` entry point
│   ├── queue_manager.py  # QueueManager + main() loop
│   ├── consumer.py       # process_item dispatcher (representation / deletion / reconciler)
│   ├── deriver.py        # "minimal deriver" — single-LLM-call batch processor
│   ├── enqueue.py        # API → queue producer
│   └── prompts.py
├── dreamer/             # Memory consolidation (runs off the queue)
│   ├── orchestrator.py   # run_dream() / process_dream()
│   ├── specialists.py    # DeductionSpecialist + InductionSpecialist
│   ├── dream_scheduler.py
│   ├── surprisal.py      # Surprisal-based conclusion prioritization
│   └── trees/            # Reasoning-tree primitives
├── reconciler/          # In-process scheduler hosted by the deriver worker
│   ├── scheduler.py      # ReconcilerScheduler (started from queue_manager.py)
│   ├── sync_vectors.py   # Embeds MessageEmbedding rows with sync_state='pending'
│   └── queue_cleanup.py  # Removes stale queue items
├── llm/                 # Provider-agnostic LLM client subsystem
│   ├── api.py, backend.py, executor.py, runtime.py, registry.py
│   ├── caching.py, structured_output.py, tool_loop.py, conversation.py
│   ├── messages.py, profiles.py, request_builder.py, credentials.py, types.py
│   ├── codecs/           # anthropic.py, gemini.py, openai.py (typed history ↔ wire)
│   └── backends/         # anthropic.py, gemini.py, openai.py
├── cache/               # Redis cache abstraction (cashews-backed)
│   └── client.py
├── vector_store/        # Optional external vector stores (pgvector is default,
│   │                    #   implemented via MessageEmbedding/Document in models+crud)
│   ├── lancedb.py
│   ├── tenant_namespace.py  # Per-tenant namespace prefix (MULTI_TENANT)
│   └── turbopuffer.py
├── telemetry/           # Observability
│   ├── emitter.py        # CloudEvents emitter
│   ├── logging.py        # Logging helpers + route-template extraction
│   ├── client_context.py, metrics_collector.py, reasoning_traces.py, sentry.py, tenant.py
│   ├── events/           # Event type definitions
│   └── prometheus/       # Prometheus metric definitions
├── utils/               # Cross-cutting utilities
│   ├── agent_tools.py    # Tool definitions + per-agent tool lists
│   ├── summarizer.py     # Two-tier session summarizer
│   ├── representation.py # Representation formatting (distinct from crud/representation.py)
│   ├── search.py, filter.py, formatting.py
│   ├── tokens.py         # tiktoken-based counting
│   ├── pagination.py     # List pagination: opt-in cursor mode + the cached offset shim
│   ├── work_unit.py, queue_payload.py
│   ├── config_helpers.py, json_parser.py, files.py
│   └── types.py
└── webhooks/            # Webhook delivery
    ├── events.py
    └── webhook_delivery.py
  • Tests in pytest with fixtures in tests/conftest.py; subdirs mirror src/ (tests/deriver/, tests/dialectic/, etc.) plus tests/bench/ (perf benchmarks), tests/integration/, tests/live_llm/ (gated by --live-llm), and tests/unified/ (the unified runner).

  • The suite is hermetic: non-loopback sockets are blocked (pytest-socket) and provider keys are placeholders, except under --live-llm. Fake LLM calls at the import site the code under test uses.

  • A test that reproduces a known, still-open bug is marked pytest.mark.xfail(strict=True, reason="... (issue N)"). Once the bug is fixed the test passes, strict mode turns that into a failure, and the fix removes the marker.

  • Use environment variables via python-dotenv (.env). Config precedence: env > .env > config.toml > defaults.

Database Design
  • All tables use text IDs (nanoid format) as primary keys, except service tables with no FK/RLS surface: queue.id is an integer identity (see the locking section) and queue_item_batches.work_unit_key is the unit's own derived key

  • Composite foreign keys for multi-tenant relationships

  • Feature flags on workspace, peer, and session levels

  • Token counting on messages for usage tracking

  • JSONB metadata fields for extensibility

  • HNSW indexes for vector similarity search

  • Index a large or partitioned table with migrations.utils.create_index_online / drop_index_online, not a hand-rolled CREATE INDEX CONCURRENTLY. They build concurrently (on a partitioned table: ON ONLY the parent, each partition concurrently, then ATTACH), are safe to rerun after a stopped build, and keep src/models.py's Index() as the declaration to match by hand.

  • A Select that feeds a list endpoint MUST have a total ORDER BY ending in a unique column (e.g. created_at, id). paginate_offset_or_cursor (src/utils/pagination.py) seeks by the sort key in both cursor mode and the offset shim; without a unique tail, rows that share a sort key are skipped or repeated across pages.

  • A query on a partitioned table (models.TenantPartitioned) needs a bound tenant_id predicate. RLS compares tenant_id to current_setting('app.tenant'), which Postgres prunes with only at executor startup, so without a bound value the planner locks every partition. Under MULTI_TENANT the do_orm_execute hook models._add_tenant_predicate adds one to ORM statements that name the model in the column list, select_from or a join. Where the hook can't see the model (a Core Table query such as session_peers_table, a model only in a WHERE clause as in exists().where(...) or select(func.count()).where(...), text()), filter on tenant_id == scoped_tenant_id() yourself. Service sessions (Session.info[db.CROSS_TENANT]) are exempt. Add a new hot statement to _CASES in tests/integration/test_tenant_partition_pruning.py, which asserts its lock count does not grow with the partition count.

Key Architectural Decisions
  1. Peer Paradigm: humans and AI agents are unified as "Peers"; many-to-many with Sessions. Internal vector storage (Collections/Documents) is keyed by (observer, observed) peer pairs — the same mechanism powers self-representation (observer == observed) and cross-peer modeling.

  2. Multi-Peer Sessions: Sessions can have multiple participants with different observation settings.

  3. API server / worker split: API enqueues, deriver worker process consumes. Never block HTTP on LLM work. The Reconciler runs as an in-process scheduler inside the deriver, handling async embedding sync and queue cleanup.

  4. "Minimal" deriver: memory formation is a single structured-output LLM call per batch, not an agentic tool loop. Predictable cost, lower latency. The Dialectic is the one true tool-using agent.

  5. Provider-agnostic LLM layer (src/llm/): all model calls go through honcho_llm_call(). Backends (anthropic, gemini, openai) sit behind a registry; per-agent MODEL_CONFIG with fallback chains is resolved at call time.

  6. Dialectic reasoning tiers: 5 levels (minimal → max); each level has its own model config and tool set (minimal uses a reduced toolset).

  7. Hybrid search: Postgres FTS (GIN index on (tenant_id, workspace_name, to_tsvector('english', content)), OR'd with a content ILIKE fallback backed by a pg_trgm GIN index on (tenant_id, workspace_name, content); btree_gin lets both lead with the scalar columns so the bitmap is narrowed to the workspace before the heap is read, and without pg_trgm the trigram index is skipped and the ILIKE scans) + vector similarity (HNSW on MessageEmbedding.embedding). MessageEmbedding is a separate table from Message with its own sync_state so embedding is decoupled from message creation.

  8. Pluggable external vector stores: defaults to pgvector inline; can swap to turbopuffer or lancedb (VECTOR_STORE_* config; src/vector_store/).

  9. Composite-FK multi-tenancy: workspace_name participates in nearly every composite FK. Cross-workspace data leakage is structurally impossible at the schema level.

  10. Scoped Authentication: JWTs can be scoped to tenant, workspace, peer, or session level. Under MULTI_TENANT, every JWT must carry a tenant claim (tn), checked before any admin/workspace/peer/session scope logic — an admin token is admin only within its own tenant. The tenant registry itself (creating/updating/deleting tenants) sits above this scoping and is authenticated separately by a service secret rather than a JWT, since a JWT cannot carry a claim for a tenant that does not exist yet.

  11. Batch Operations: Bulk message creation up to 100 messages per request.

  12. Session History: Two-tier summarization — short every SUMMARY_MESSAGES_PER_SHORT_SUMMARY (default 20), long every SUMMARY_MESSAGES_PER_LONG_SUMMARY (default 60).

Error Handling
  • Custom exceptions defined in src/exceptions.py

  • Use specific exception types (ResourceNotFoundException, ValidationException, etc.)

  • Proper logging with context instead of print statements

  • Global exception handlers defined in main.py

  • See docs/contributing/error-handling.mdx for details

Notes
  • Always use uv run or uv to prefix any commands related to python to ensure you use the virtual environment

512 files · 498 not served here

Advantages

  • Extracts conclusions from conversations rather than just performing chunk matching. evidence: README.md
  • Models relationships and knowledge between multiple peers, users, and agents. evidence: README.md

Limitations

  • Background reasoning is asynchronous, meaning new messages may not be immediately reflected in chat responses. evidence: README.md
  • Requires careful management of database sessions to avoid holding connections during slow network I/O. evidence: CLAUDE.md

Security

Risk level: Medium risk

This brain runs

Git hooks (15)

  • .pre-commit-config.yaml: pre-commit hooks from https://github.com/pre-commit/pre-commit-hooks at v4.5.0 (contributor tooling: runs only after pre-commit install) · uses the network
  • .pre-commit-config.yaml: pre-commit hooks from https://github.com/astral-sh/ruff-pre-commit at v0.15.12 (contributor tooling: runs only after pre-commit install) · uses the network
  • .pre-commit-config.yaml: pre-commit hooks from https://github.com/PyCQA/bandit at 1.7.10 (contributor tooling: runs only after pre-commit install) · uses the network
  • .pre-commit-config.yaml: bash -c 'cd sdks/typescript && bun run lint:fix'
  • .pre-commit-config.yaml: uv run basedpyright
  • .pre-commit-config.yaml: uv run pytest -x tests/ --ignore=tests/alembic/
  • .pre-commit-config.yaml: uv run python scripts/run_alembic_tests.py
  • .pre-commit-config.yaml: uv run python scripts/ensure_alembic_tests.py
  • .pre-commit-config.yaml: uv run python scripts/check_alembic_heads.py
  • .pre-commit-config.yaml: bash -c 'if [ -d "sdks/python/tests" ]; then cd sdks/python && uv run pytest; fi'
  • .pre-commit-config.yaml: bash -c 'cd sdks/typescript && bun run test'
  • .pre-commit-config.yaml: bash -c 'if [ -f "sdks/typescript/package.json" ]; then cd sdks/typescript && bun run build; fi'
  • .pre-commit-config.yaml: bash -c 'if [ -f "sdks/typescript/package.json" ]; then cd sdks/typescript && bun run typecheck; fi'
  • .pre-commit-config.yaml: pre-commit hooks from https://github.com/igorshubovych/markdownlint-cli at v0.37.0 (contributor tooling: runs only after pre-commit install) · uses the network
  • .pre-commit-config.yaml: pre-commit hooks from https://github.com/commitizen-tools/commitizen at v3.13.0 (contributor tooling: runs only after pre-commit install) · uses the network

Agent instructions that run or fetch something (71)

  • CLAUDE.md: Setup: `uv sync`
  • CLAUDE.md: Run server: `uv run fastapi dev src/main.py`
  • CLAUDE.md: Run tests: `uv run pytest tests/`
  • CLAUDE.md: Run single test: `uv run pytest tests/path/to/test_file.py::test_function`
  • CLAUDE.md: Linting: `uv run ruff check src/`
  • CLAUDE.md: Typechecking: `uv run basedpyright`
  • CLAUDE.md: Format code: `uv run ruff format src/`
  • CLAUDE.md: The TypeScript SDK tests run against a real Honcho server.
  • CLAUDE.md: `bun run test` (not bare `bun test`, which has no server to talk to) starts one for them: `scripts/run_ts_sdk_tests.py` creates a throwaway database on the Postgres named by `DB_CONNECTION_URI`, migrates it, starts the API and the mock LLM provider (`src/mock_provider`), runs `bun test` …[+24 chars]
  • CLAUDE.md: They are not part of `uv run pytest`.
  • CLAUDE.md: cd sdks/typescript && bun run test # whole suite
  • CLAUDE.md: cd sdks/typescript && bun run test peer.test # bun test args pass through
  • CLAUDE.md: **To type-check the TypeScript SDK (this is fine to run directly):**
  • CLAUDE.md: cd sdks/typescript && bun run tsc --noEmit
  • CLAUDE.md: These run in AUTOCOMMIT mode with no transaction: writes are NOT blocked by the database — they silently commit immediately, and `begin_nested()` savepoints break.
  • CLAUDE.md: **Startup validators (`src/startup/`).** Both the API lifespan and the deriver entrypoint run them before serving traffic or claiming work, and each fails closed: `validate_embedding_schema` (pgvector column dims vs settings), `validate_tenant_isolation` (above), and `validate_queue_it …[+209 chars]
  • CLAUDE.md: **Under `MULTI_TENANT`, the tenant-claim check in `auth()` must run before the admin short-circuit.** An admin JWT (`ad: true`) is admin only within its own tenant;
  • CLAUDE.md: **API server** (`uv run fastapi dev src/main.py`) — handles HTTP, enqueues background work, returns immediately.
  • CLAUDE.md: **Deriver worker** (`uv run python -m src.deriver`) — long-running queue consumer (uvloop).
  • CLAUDE.md: Can run multiple process replicas (a deployment concern, orthogonal to config);
  • CLAUDE.md: (The Dreamer specialists also use tools, but run off the queue.)
  • CLAUDE.md: **Cross-tenant paths pass the row's prefix explicitly, and contain the failure per row.** The reconciler and the soft-delete sweep run across all tenants on `service_db` with no ambient tenant, so they call `prefix_for_tenant(row.tenant_id)` and hand the result to `get_vector_namespace( …[+18 chars]
  • CLAUDE.md: │ ├── __main__.py # `python -m src.deriver` entry point
  • CLAUDE.md: Always use `uv run` or `uv` to prefix any commands related to python to ensure you use the virtual environment
  • examples/zo/SKILL.md: Get a Honcho API key at [honcho.dev](https://honcho.dev). · uses the network
  • examples/zo/SKILL.md: Install dependencies:
  • integrations/cursor/skills/honcho-grok-bot/SKILL.md: **A routine run** (scheduled or event-triggered work with no user in the loop): `<bot>-routine-<routine-name>-<YYYY-MM-DD>`.
  • integrations/cursor/skills/honcho-grok-bot/SKILL.md: If the metadata is missing, run `honcho-setup` rather than guessing.
  • integrations/cursor/skills/honcho-memory/SKILL.md: If a tool call fails with an authentication error, stop calling tools and run the `honcho-setup` skill instead of retrying.
  • integrations/cursor/skills/honcho-setup/SKILL.md: It is get-or-create, so this is safe on every run.
  • integrations/cursor/skills/honcho-setup/SKILL.md: When asked for Honcho's status, run Step 5 without changing anything, and add how many sessions `search` finds for the current session name.
  • skills/honcho-cli/SKILL.md: run `honcho init` to confirm or set them.
  • skills/honcho-cli/SKILL.md: Run `honcho peer inspect` before `honcho peer chat` to understand context.
  • skills/honcho-cli/SKILL.md: # Always dry-run first: it reads both sides and writes nothing
  • skills/honcho-cli/SKILL.md: honcho workspace replay --from <src> --to <dst> --dry-run --json | jq '.actions, .messages_to_send'
  • skills/honcho-cli/SKILL.md: Each session's `action` in the dry run is `create`, `resume`, `up_to_date` or `conflict`.
  • skills/honcho-integration/SKILL.md: Install the SDK (see [Installation](#installation))
  • skills/honcho-integration/SKILL.md: If the Honcho CLI is available, run `honcho doctor` to confirm connectivity before testing the integration code
  • skills/honcho-integration/SKILL.md: **Get an API key** ask the user to get a Honcho API key from <https://app.honcho.dev> and add it to the environment. · uses the network
  • skills/honcho-integration/SKILL.md: If the user has the Honcho CLI installed (`uv install honcho-cli`), they can validate their setup before writing any integration code:
  • skills/honcho-integration/SKILL.md: uv add honcho-ai
  • skills/honcho-integration/SKILL.md: bun add @honcho-ai/sdk
  • skills/honcho-integration/SKILL.md: [ ] Install SDK with `uv add honcho-ai` (Python) or `bun add @honcho-ai/sdk` (TypeScript)
  • skills/honcho-integration/SKILL.md: [ ] (Optional) Run `honcho doctor` to verify connectivity before testing integration code
  • skills/honcho-memory/SKILL.md: Use it.** In Claude Code, install the [Claude Code plugin](https://honcho.dev/docs/v3/guides/integrations/claude-code.md) (`/plugin marketplace add plastic-labs/claude-honcho`) for persistent memory out of the box;
  • skills/honcho-memory/SKILL.md: You need a Honcho API key — get one free at <https://app.honcho.dev> (starts with `hch-`). · uses the network
  • skills/pre-pr/SKILL.md: git diff main...HEAD --stat
  • skills/pre-pr/SKILL.md: | Surface touched | Required | | --- | --- | | `src/` (non-prompt) | unit tests under the matching `tests/` tree | | deriver / dialectic / dreamer / LLM path | unit + consider live-llm (`tests/live_llm`) | | queue, config hierarchy, multi-turn, SDK contract | unified (`uv run python -m …[+217 chars]
  • skills/pre-pr/SKILL.md: Lint/type before claiming tests are green: `uv run ruff check src/` → `uv run basedpyright` → the pytest command for the layer.
  • skills/property-repro/SKILL.md: HONCHO_FUZZ_EXAMPLES=1000 uv run pytest tests/property/test_api_no_server_errors.py \
  • skills/property-repro/SKILL.md: HONCHO_FUZZ_STATS=/tmp/stats.txt uv run pytest --fuzz tests/property/test_api_no_server_errors.py
  • skills/property-repro/SKILL.md: Hypothesis runs with `database=None`, so a property failure is not replayed on the next run unless you pin it.
  • skills/property-repro/SKILL.md: Background work does not run under test (the deriver, deletion cleanup, the reconciler).
  • skills/property-repro/SKILL.md: re-run with `-n 0` and a fixed `--hypothesis-seed` to replay it.
  • skills/verify/SKILL.md: Docker Compose is the preferred way to run the stack — `docker-compose.yml` at the repo root brings up Postgres (pgvector), Redis, the API server, and the deriver worker together.
  • skills/verify/SKILL.md: If Docker Compose isn't available, the stack can also run directly on the host (see Launch below);
  • skills/verify/SKILL.md: Copy `.env` from the main checkout (that's where the provider keys live), and run `bun install` in `sdks/typescript` if you'll run the full test suite — otherwise the pre-push gate fails on a phantom `Cannot find package 'zod'`.
  • skills/verify/SKILL.md: docker compose ps # look for api / deriver / database / redis
  • skills/verify/SKILL.md: docker compose up -d # start it if not
  • skills/verify/SKILL.md: For verifying a diff, the cheap path is to reuse the stack's Postgres/Redis containers but run the branch's API as a host process on a spare port:
  • skills/verify/SKILL.md: uv run uvicorn src.main:app --port 8901 # branch code, stack's DB/Redis
  • skills/verify/SKILL.md: uv run python -m src.deriver # if the diff touches the worker
  • skills/verify/SKILL.md: Without Docker at all, run the two processes the same way against host Postgres + Redis (API default port 8000 via `uv run fastapi dev src/main.py`).
  • skills/verify/SKILL.md: And for load-time config behavior, `uv run python -c "import src.config;
  • skills/verify/SKILL.md: **Capture the real plan repeatedly.** Save ORM-emitted SQL and bound parameters after tenant hooks, then run natural `EXPLAIN (ANALYZE, BUFFERS)` under the same role/settings for both revisions.
  • skills/verify/SKILL.md: Check bound tenant predicates and partition pruning, including planning/partition lock evidence when relevant, not only which partitions execute.
  • skills/verify/SKILL.md: All run in CI, but they're also runnable locally with whatever API keys and configuration you have — Honcho's config surface is large, so options like per-agent timeouts and provider base URLs can be pointed at your own keys/proxies to exercise a change:
  • skills/verify/SKILL.md: uv run pytest tests/
  • skills/verify/SKILL.md: uv run python -m tests.unified.run
  • skills/verify/SKILL.md: uv run python -m tests.unified.run --test-dir tests/unified/test_cases
  • skills/verify/SKILL.md: uv run pytest tests/live_llm -n 0 --live-llm --no-header -q

Install scripts (3)

  • honcho-cli/src/honcho_cli/commands/install.py: python honcho-cli/src/honcho_cli/commands/install.py
  • honcho-cli/src/honcho_cli/commands/setup.py: python honcho-cli/src/honcho_cli/commands/setup.py
  • honcho-cli/src/honcho_cli/local/setup.py: python honcho-cli/src/honcho_cli/local/setup.py

Hooks (3)

  • integrations/cursor/hooks/hooks.json (sessionStart): bun run ${CURSOR_PLUGIN_ROOT}/dist/hook.js session-start
  • integrations/cursor/hooks/hooks.json (beforeSubmitPrompt): bun run ${CURSOR_PLUGIN_ROOT}/dist/hook.js before-submit-prompt
  • integrations/cursor/hooks/hooks.json (afterAgentResponse): bun run ${CURSOR_PLUGIN_ROOT}/dist/hook.js after-agent-response
  • Medium risk: runs-git-hook-remote-exec (.pre-commit-config.yaml:4)
  • Medium risk: runs-git-hook-remote-exec (.pre-commit-config.yaml:26)
  • Medium risk: runs-git-hook-remote-exec (.pre-commit-config.yaml:38)
  • Medium risk: runs-git-hook-remote-exec (.pre-commit-config.yaml:138)
  • Medium risk: runs-git-hook-remote-exec (.pre-commit-config.yaml:146)
  • Medium risk: runs-instruction-instruction-network (examples/zo/SKILL.md:18)
  • Medium risk: runs-instruction-instruction-network (skills/honcho-integration/SKILL.md:119)
  • Medium risk: runs-instruction-instruction-network (skills/honcho-memory/SKILL.md:61)
  • Low risk: network-instructions (examples/zo/SKILL.md:29)
  • Low risk: scripts-present (honcho-cli/src/honcho_cli/commands/install.py)
  • Low risk: scripts-present (honcho-cli/src/honcho_cli/commands/setup.py)
  • Low risk: scripts-present (honcho-cli/src/honcho_cli/local/setup.py)
  • Low risk: scripts-present (scripts/check_alembic_heads.py)
  • Low risk: scripts-present (scripts/ensure_alembic_tests.py)
  • Low risk: scripts-present (scripts/run_alembic_tests.py)

Attribution and licence

Created by
Plastic Labs
Declared authors
  • Plastic Labs (declared in pyproject.toml)
Publisher
Plastic Labs (Official Plastic Labs project)
Source
plastic-labs/honcho · commit fae2719
Licence
GNU Affero General Public License v3.0 only (files served here)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Plastic Labs.

Install from source

498 of its files are not served here, so there is no ZIP. plastic-labs/honcho at fae2719