guid.foo / midden
An archive of agent session transcripts that serves them back as MCP tools.
Pull this image
docker pull oci.lance.dev/guid.foo/midden:latest
midden
midden archives the transcript of every agent session a person runs:
their own Claude Code sessions on any machine, and the sessions of
simmer. Later it archives
sessions from other harnesses. It keeps everything: prompts, responses, tool calls,
tool results, and subagent turns.
midden is useful without simmer. A person’s sessions can search their
own history. simmer uses midden to explain what its sessions did and to
find what a person keeps coming back to, and simmer’s sessions add to
midden.
midden captures through one OTLP endpoint, and serves the archive back
as MCP tools: a list of sessions, a session’s conversation, and a
search of their text.
The canonical record
The canonical record of a session is the harness’s own transcript,
stored verbatim. For Claude Code, that is the JSONL file under
~/.claude/projects/. Each line is one entry: a full API message with
every content block, or another event of the session. Each entry has a
uuid, a parentUuid, a sessionId, and a timestamp.
midden does not convert entries to its own schema when it writes them.
The JSONL format is internal to Claude Code and changes between
versions, so midden stores each entry as it arrives, and the read path
handles the differences between formats and between harnesses.
One channel: OTLP
Everything reaches midden as OTLP logs over HTTP, at /v1/logs, in
protobuf and in JSON. Two kinds of log record arrive:
- Transcript entries. One log record for each JSONL entry. The
record’s timestamp is the entry’s,event.nameistranscript.entry,
the attributes are the session ID and the entry’suuid, and the
body is the entry, unchanged. - Native events. Claude Code’s own OpenTelemetry events, such as
claude_code.api_request. They add a live view and the cost and
latency of each request. Nothing depends on them.
The shipper
The shipper is a small program that reads a session’s JSONL file and
sends each entry that midden does not have yet.
- A Stop hook runs
midden shipafter each turn, in every
session on every machine. - Backfill runs the same program over every transcript that a machine
still has, such as the retained transcripts on a laptop. - When midden cannot be reached, the shipper keeps its place, and the
next run sends what is left. A machine that is offline loses nothing.
The shipper reads its endpoint, user, and app password from the
environment, or from ~/.config/midden/env, a file of NAME=value
lines.
midden stores each entry of each transcript file once. A retry, a
second backfill, or an overlap between runs stores nothing twice, so
delivery is at least once, with no duplicates.
Native events
Claude Code exports its own events when these are set:
CLAUDE_CODE_ENABLE_TELEMETRY=1
OTEL_LOGS_EXPORTER=otlp
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://midden.example.com/v1/logs
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic%20<base64 of user:app-password>
OTEL_LOG_USER_PROMPTS=1
OTEL_LOG_ASSISTANT_RESPONSES=1
OTEL_LOG_TOOL_DETAILS=1
OTEL_LOG_TOOL_CONTENT=1
OTEL_LOG_TOOL_CONTENT needs tracing, and
OTEL_LOG_ASSISTANT_RESPONSES needs Claude Code 2.1.193 or later. The
OTel specification percent-encodes header values. It is not yet checked
that Claude Code’s exporter decodes %20.
Hosting
midden runs in a Kubernetes cluster, behind an ingress for each path
(midden.example.com here):
/v1/logsis the capture path, behind Authentik.- Pods of the same cluster reach a second address for
/v1/logs
through the Service, with no ingress. See “Auth”. /mcpis the read path. Each of its two addresses has its own
mcp-sidecarand its own OAuth.
Nothing else on midden is routed from outside the cluster.
The image is atcr.io/guid.foo/midden, built with ko. Its entrypoint is
/ko-app/midden and it has no default arguments, so a container runs
the server with args: ["serve"] and leaves command unset.
The intake’s addresses serve GET /healthz, which answers 200 while the
process serves HTTP and does not ask the database. It backs both the
readiness and the liveness probe. Every pod shares one database, so a
probe that checked it would take every pod out of the Service, or
restart every pod, for a fault that no pod can fix.
Every connection to Postgres fails in seconds when the database stops
answering, rather than waiting on TCP’s retransmits: a new connection
within 5 s, unless the URL sets its own connect_timeout, and an open
one within about 30 s. TCP keepalive finds a dead peer while the
connection has sent everything and waits for a reply. On Linux,
TCP_USER_TIMEOUT ends a connection whose data stays unacknowledged
for 30 s, or stays unsent that long because the peer’s receive window
is closed. A healthy Postgres closes its window when it stops reading,
as it does while one statement waits on a lock, so Append sends its
inserts in batches of at most 32 KB on the wire, counting each
insert’s own protocol bytes, which Postgres’s receive window holds,
and a long wait on a lock leaves nothing unsent. An Append over
a dead connection returns an error, which the shipper retries, and the
pool dials again.
Auth
midden’s capture path is behind Authentik’s forward auth, as a
proxy provider, so it is reachable from anywhere. When midden’s host
is outside the cookie domain of the Authentik that protects it, the
proxy provider is forward_single. midden has no auth code of its
own for that path.
- A client sends an Authentik app password as HTTP Basic. Authentik
answers a wrong one with a 302 to its login page, so the shipper
follows no redirect, and it counts a request as sent only when midden’s
own OTLP response comes back. - Authentik passes the user to midden in
X-authentik-username, and
midden records it on each row. - Each machine has its own app password, so one machine can be revoked
alone.
The shipper and the native exporter use the same endpoint and the same
app password.
A pod of midden’s own cluster needs no password. MIDDEN_PODS_LISTEN
is a second address for POST /v1/logs, which only pods reach:
- The pod sends its projected ServiceAccount token for the audience
middenas a bearer token, andmidden shipreads it from
MIDDEN_TOKEN_FILE. - midden sends the token to the API server’s TokenReview, so its own
ServiceAccount is bound tosystem:auth-delegator. A token for
another audience, or one that is bound to no pod, is refused. MIDDEN_POD_USERSmaps a namespace to the user that its pods’ records
are stored under, and a pod of any other namespace is refused. A pod
holds a token for midden only when its spec mounts one, so whoever
writes the pod specs of a listed namespace decides which pods ship.- This address never reads
X-authentik-username, and the address
behind Authentik never reads a token. A NetworkPolicy must keep pods
from the address behind Authentik, where a pod could name any user.
Storage
midden appends to one table in its own Postgres. Each OTLP log record is one row:
- columns for the fields that queries use: the kind of record, the
session ID, the transcript file, the entry’s key, theprompt.idof a
native event, the event name, the timestamp, the Authentik user, and
the harness and host from the resource attributes - the transcript entry, parsed, in a
jsonbcolumn - the full log record, as OTLP JSON, in another
jsonbcolumn
An entry’s key is its uuid, or its byte offset in the file when it
has no uuid. A unique index on the session, the file, and the key
gives each entry of each file one row. A resumed session’s file repeats
earlier entries with the same uuid and different metadata, such as
the Claude Code version, so each file’s copy is its own row. midden
never updates or deletes a row.
Other harnesses
A harness joins midden with a reader for its transcript format in the
shipper. Codex also writes its sessions as JSONL files. Its format is
not checked yet.
The read path
midden serve serves six MCP tools at /mcp, over the streamable
HTTP transport, with the official Go SDK: the tools of
plans/completed/2-mcp-tools-on-the-core-tables.md. They only read,
and they read only the live core schema, never records. Each call
reads the live schema’s name from builds, so the tools follow a swap
with no restart. The swap drops the retired schema at once, so a call that it
fails part way through runs once more on the new schema. Postgres ends
any query of a tool that runs longer than a minute, because it does not
see an MCP client that gives up.
Until a core schema of version 2 or later is live, as on a new
database, the server’s instructions say that the core tables are still
building, and each tool call returns an error that says so. Each
request reads builds again, so a server answers from the first swap
on, with no restart.
list_sessions: which sessions match a time, host, user,
harness, repository, working directory, or tool. Each has its label
(its title, or the first prompt a person wrote, or its first command),
its last text, its times, the host and working directory of its first
entry, its repositories, and its counts.read_session: a session’s main conversation, or one subagent’s,
in order,briefby default, withkindsto keep some kinds of part.describe_session: one session in one call, with its prompts, its
tools, its tokens, the files it wrote or edited, and its subagents,
each list within a budget.search: a plain word matches by full-text search on
content_blocks_search, and a quoted phrase or a term with
punctuation inside, such asarchive/search.go, matches as a
substring through the trigram index onv2.TrigramText, each term on
its own. Matches are grouped by session over the newest 500 matching
parts, or listed one by one withgroupnone.list_prompts: the prompts a person wrote, newest or oldest
first, across sessions, by the builder’ssourceof each prompt, with
their count by session.find_tool_calls: tool calls with the start of their results,
newest or oldest first, by tool, by the end of a path through
tool_calls_path, or by a piece of the input or the result, and with
changedonly the calls that changed a file.
A tool filter that is not a whole tool’s name matches every tool
whose name contains it, in any case, of the tools that the view’s
sessions called, and the result names them. A host filter that matches
no session is refused with the hosts that sessions have.
Each takes the session as session, session_id, SessionID,
sessionID, or id; a host filter matches a host exactly or as the
prefix before a -, and takes a list; and each result is at most
40,000 characters of encoded JSON, with a Next when a page stops
early. A cursor is the records.id of an entry’s first copy, so it
survives a rebuild, except in list_sessions and find_tool_calls,
whose cursors are a session’s last time and ID and a call’s time,
session, and tool_use_id.
The MCP addresses do no auth. The deployment binds each to 127.0.0.1
behind its own mcp-sidecar, and Authentik decides who reaches each
sidecar. The intake’s address answers 404 at /mcp.
midden mcp serves only the MCP tools, on the same addresses and with
the same privacy config as midden serve, so that a person can run
them against the live database from their own machine. It writes
nothing: it does not apply the schema or build the core tables, and
each of its connections sets default_transaction_read_only, so
Postgres refuses a write through it.
After it starts, midden serve drops what an older read path on
records left in the database: the trigger records_entry_places,
its function, and the tables it wrote, entry_places and
unplaced_sessions, with place_session; then the trigger
records_session_traits and its function, which stored the same rows
as Append; then the indexes records_search and
records_session_time, with DROP INDEX CONCURRENTLY, and the
functions of records_search, entry_search and entry_parts.
Dropping a trigger takes an ACCESS EXCLUSIVE lock on records, so
each drop waits at most 2 s for the lock, which holds off the intake
for that long, and tries again every 10 s until it has it. Once they
are gone, each start reads only the catalog.
The core layer
records is append-only and canonical. The core layer is a set of
tables built from records, one row per transcript line, file, logical
entry, and part, so that each read is an index lookup on data that was
parsed once. plans/1-core-tables-built-from-records.md is the design.
The MCP tools read only the live core schema.
- Each builder version builds its own schema, such as
core_v2, and
buildsrecords whether each isbuilding,live, orretired.
Each version is a Go package with its own frozen parser. - In the transaction that stores each record,
Appendupserts the
record’s session intopending_sessions, for the live schema and the
newest building one, so no record is stored without it. After the
commit it wakes its own process’s worker, andNOTIFYwakes the
others'. - Each
midden serveruns a worker, which claims a pending session and
builds it from its lowest new id on, in chunks of at most 1,000
records and about 32 MB, one session at a time. A build of a session
again leaves the same rows. A record over 16 MB, or one that Postgres
refuses, goes tobuild_failures, and the build goes on. - A sweep every 30 s builds what a lost wake left pending. At start and
every hour, one process compares each session’s count of records with
its count of built lines, and writes a pending row for each session
that is missing records, such as the records of older code. - A new version builds beside the live one, and swaps live when it has
taken every record. The old schema is then dropped. When
MIDDEN_DATABASE_LIMITis set, a new version is refused while the
database’s size and the new version’s estimate of its own size, from
the live core schema’s, would pass it. - A build holds at most one chunk of about 32 MB of entries and its
parse, but Go’s collector lets the heap grow to twice what is live
before it runs. On a pod limited to 1 GiB, setGOMEMLIMITto about
800MiB, so that Go collects before the kernel kills the process. MIDDEN_CORE_BUILD_PAUSE, a Go duration such as250ms, is a pause
between the chunks of a schema that is building, to slow a first
build or a rebuild without a release. The live schema’s builds never
pause, because they follow the intake.- The builds read
recordsby the indexrecords_core, whichmidden servebuilds withCREATE INDEX CONCURRENTLYafter it starts. A
worker builds nothing until the index is valid. The indexes of the
reads are built the same way: a building schema’s once it has every
record, in a goroutine of their own that holds and renews the
comparison’s lease, and a schema swaps live only once they are valid.
The trigram index needspg_trgm, which midden creates, and in
whose schema it names the operator class; without the extension, or
when the index’s build fails, the schema swaps without that index. - Version 2,
core_v2, is live. Besidecore_v1, which is retired
and removed, it addedtool_calls(with each call’s path),
api_requests(one row per model request, counted once),
session_repos(the repositories a session works in, with the root
of each checkout, by its working directories and its calls’ paths),
each session’slabelandlast_text, each tool’s count of calls in
a session, each prompt’s source (a person, a slash command, an
interrupt, or the harness), and the indexes that search and the tools
will read. - Version 3,
core_v3, builds besidecore_v2and swaps live when it
is complete. It reads a session’s repositories from more of its
calls’ paths, a Grep’s, a Glob’s, or a notebook’s, relative ones from
the line’s working directory, and paths after a redirection or a
comma in a shell command, so therepofilter finds a session that
worked in a repository by any of them. It gives a subagent’s prompt
the sourcesubagent, and adds two indexes of the reads: one on each searched block’s time, which a search ANDs with the
text index, and one on a session’s blocks by kind, for
read_session’s kinds filter.
Privacy
A session is private when any entry of any of its files works in a
private repository or calls a private tool. The rule is on the whole
session, so a session that calls Gmail an hour after its first prompt
is private from its first entry.
MIDDEN_PRIVATE_REPOSITORIESholds one regular expression for each
private repository, matched against each entry’scwd. The default
is none: no repository is private until it is named here.MIDDEN_PRIVATE_TOOLSholds prefixes of tool names. The default is
Gmail, Google Calendar, and Google Drive, as
claude.ai connectors, such asmcp__claude_ai_Gmail__, and by their
local names, such asmcp__gmail__.
Each list is split by spaces, and an empty one keeps its default.
midden stores each session’s working directories and tool names in
session_traits, in the entry’s own transaction, from Append. The
tools apply the rule to those traits, with the SQL function
session_private, so a change to the config applies at the next start
with nothing to reclassify.
A release before commit 736bffe stores the traits only through the
trigger records_session_traits, which later releases drop. So an
install runs 736bffe or a later release on every process before it
upgrades to a release that drops the trigger, and a rollback must not
go past 736bffe: a process of an earlier release would store no traits,
and its sessions would show in the shared view.
The read path has two views, and the address a request reaches decides
its view:
MIDDEN_MCP_FULL_LISTENserves the full view, with every session,
for the person’s own machines.MIDDEN_MCP_SHARED_LISTENserves the shared view, for simmer’s
service accounts. Private sessions do not exist there: the list skips
them, a read finds no entries, and search finds nothing in them. No
text of a private session reaches a Job’s context.
Both views serve the person and the agents that act for them, which is
one trust boundary, so the shared view hides the sessions that
session_traits marks private and does not follow each path that a
session’s tool calls name: a session that works in a shared repository
and reads one file of a private one stays in the shared view.
midden mcp also reads MIDDEN_HIDDEN_SESSIONS, session IDs split by
spaces or commas, which neither view sees: every tool reads a hidden
session as one that the archive does not have, counts leave it out,
and a cursor into it is bad. A subagent’s entries carry its parent’s
session ID, so hiding a session hides its subagents. An eval hides the session that wrote it, so that
the agents it runs cannot read its answers.
An unset address does not listen, because any default would serve the
archive with no auth.
Metrics
midden serve serves Prometheus’s /metrics, and a /healthz that
answers while the process runs, on MIDDEN_METRICS_LISTEN. No Ingress
routes to it. Each process has its own registry, and the series count
nothing per session, user, or host: a Job’s host is its pod’s name, so
the intake counts by listener, the address a request reached.
authentik is MIDDEN_LISTEN and pods is MIDDEN_PODS_LISTEN.
midden_build_info{version}is always 1. The version is the image’s
tag, ordevfor a build that set none.midden_intake_requests_total{listener, outcome}counts each request
toPOST /v1/logs. The outcome isstored,unauthenticated,
forbidden(a pod of a namespace with no user),review_failed(the
TokenReview could not be asked),undecodable, orstore_failed.midden_records_received_total{listener, kind}counts the records of
each request that decoded, andmidden_records_stored_total{listener, kind}the ones the archive did not have. The kind istranscriptor
event. Received minus stored is the copies that a retry or a
backfill sent again.midden_append_duration_seconds{outcome}times each request’s write
to Postgres, and the outcome isokorerror.midden_record_lag_seconds{listener, kind}observes, for each new
record with a time, how long before midden stored it the harness wrote
it. The shipper runs after each turn, so the lag holds the length of
the turn, and a backfill’s lag is the age of its transcripts. An
entry that never ships has no lag, so a machine that stops shipping
shows only as fewer records.midden_tool_calls_total{tool, view, outcome}counts each MCP tool
call. The tool islist_sessions,read_session,search,
describe_session,list_prompts, orfind_tool_calls, the
view isfullorshared, and the outcome isok,refused(input
that the caller must fix),timeout(Postgres ended the read at its
bound),canceled(the client went away), orerror.midden_tool_call_duration_seconds{tool, view}times each call.midden_core_build_pending_sessions{target}is the number of sessions
with records that the schematarget, such ascore_v2, has not
built yet, andmidden_core_build_failing_sessions{target}the number
of those whose last build failed and that wait for their retry, which
backs off from a minute to an hour.midden_core_build_failed_records{target}is the number of records in
build_failures: over 16 MB, or refused by Postgres.midden_core_build_duration_seconds{target, outcome}times each build
of one session, and the outcome isokorerror. Its buckets reach
about 44 minutes, for a first build of a large session.midden_core_build_lag_seconds{target}observes, for each record
built, how long from midden’s storing it to the commit of its build.
A rebuild’s lag is the age of the records it reads.midden_core_build_refused{version}is 1 while a new builder version
is refused forMIDDEN_DATABASE_LIMIT.midden_core_build_state{target, state}is 1 for the state of each
schema inbuilds,building,live, orretired, and 0 for its
other two, so a rebuild’s swap shows as its schema’slivegoing to 1.midden_core_index_valid{index}is 1 while a listed index of a live
or building schema, such ascore_v2.content_blocks_search, is valid,
and 0 while it is missing or part way built. A building schema’s
indexes are 0 until its bulk load ends and they are built.midden_core_index_builds_total{outcome}counts each concurrent build
of an index of the core layer, and the outcome isokorerror.
The tool series exist only in a process that serves a view. The gauges
of the core layer are set at start and every 30 s, apart from the
builds, so they show a first build while it runs. They have a series
only for a schema that is live or building, except
midden_core_build_state, which has one for every schema in builds. Go’s and
the process’s own series come with every registry.
Not designed yet
- retention