midden AGENTS.md #
README.md is the design. This file is how to work on the code.
archive/stores records in Postgres.schema.sqlis the whole schema, andarchive.Openapplies it on every start, so each change to it must be safe to run again on a database that has the old one.archive.goopens the archive and appends records.unused.goisDropUnused, whichserveruns after each start. It drops what nothing uses, whichschema.sqlno longer creates: the triggerrecords_entry_places, and then the triggerrecords_session_traitsand its functionrecord_session_traits, which stored the same rows asAppend. Dropping a trigger needs anACCESS EXCLUSIVElock onrecords, so each drop waits for the lock at mostlockTimeoutand tries again. The drop ofrecord_session_traitstakes the schema's advisory lock first, under the same bound, because a start of an older release replaces the function. Then it drops the indexesrecords_searchandrecords_session_time, withDROP INDEX CONCURRENTLY, and the functions ofrecords_search. Then it setsrecordsto be vacuumed after 2% of its rows are new, as the core tables are, in a transaction of its own and only whenpg_class.reloptionslacks the setting:ALTER TABLE SETtakes aSHARE UPDATE EXCLUSIVElock, which noAppendwaits for but which waits for autovacuum and for a concurrent index build ofrecords, so it waits at mostvacuumLockTimeout, under the defaultdeadlock_timeout, and tries again. Once all that is done it reads only the catalog.session_traits,entry_traits, and the SQL functionsession_privateinschema.sqlare the privacy rule that the tools apply. The start that createssession_traitsbackfills it from the records already stored.traits.goiswriteTraits. In its transaction,Appendstores insession_traitsthe traits of the records it inserted, in one statement over their ids, fromentry_traits, andON CONFLICT DO NOTHINGkeeps one row of each trait. The rows are inserted in sorted order, so that two writers take their locks in one order.traits_test.gochecks whatAppendstores, case by case and overtestdata/entries.jsonl, a corpus of the shapes of Claude Code's transcript lines, and the backfill.outbox.gois the outbox of the core layer: in its transaction,Appendupserts one row ofpending_sessionsfor each session it stored transcript rows for, for the live schema and the newest building one inbuilds, sendsNOTIFY midden_core, and after the commit hands the sessions to its own process's worker onWakes.
core/builds the core layer, tables built fromrecords, one schema for each builder version, asplans/1-core-tables-built-from-records.mddesigns it. The tools on the core tables read the live schema.builder.gois the contract of a builder version: its DDL, its parse of a chunk of a session's records, and its finish of a session.worker.goisRun: the wakes,LISTEN, the sweep every 30 s, andDrain, which builds the live schema's pending rows before a rebuild's.claims.goclaims a pending row and checks itsclaimandseq, andbuild.gobuilds one session in chunks.compare.gois the comparison ofrecordswith a schema's lines, under a lease on its row ofbuilds, andbuilds.gocreates a version's build, checksMIDDEN_DATABASE_LIMIT, retires an older building version, swaps, and drops a retired schema.indexes.gobuilds withCREATE INDEX CONCURRENTLYthe indexes that a version lists inIndexes, andrecords_coreonrecords, under a try-lock, and drops an index that a valid one replaces. It builds the live schema's at start and in each sweep, and a building schema's once the schema has every record, in a goroutine that the swap starts inbuilds.go, which holds and renews the comparison's lease and swaps when they are valid. An index with anExtensionnames the extension's schema as%[1]s, and is skipped when core cannot create the extension or build the index, and the swap does not wait for it. A version's DDL creates indexes only in a new schema, on empty tables: a plainCREATE INDEXblocks the workers' writes, andIF NOT EXISTStakes that lock before it finds the index. An index added to an existing schema goes inIndexes.metrics.godeclares themidden_core_build_*series.
core/v2/is builder version 2, with schemacore_v2, the live schema until version 3 swaps. It adds to version 1's tablestool_calls,api_requests,session_reposwith each checkout's root, the entry'ssession_id,at, andfirst_record_idand each prompt'ssourceincontent_blocks,sessions.labelandlast_text,session_tools.calls, the rule of repositories inrepoOf(traits.go), and the indexes of search and the tools.TrigramTextis the expression of the trigram index, which a read must match against.Sizeis its estimate forMIDDEN_DATABASE_LIMIT.parse.gois its frozen parse of an entry's parts, andtraits.goits frozen copy of the decode that matchesentry_traits. A change to either, or to what a table holds, is a new version in a package of its own, and a full rebuild.plans_test.gochecks that each of the builder's reads of a session uses an index that the DDL creates.core/v3/is builder version 3, with schemacore_v3, which builds besidecore_v2and swaps live once complete. It starts as a copy of version 2, keeps every table, column, and index thattools/reads, and reads a session's repositories from more paths (inputPathsintraits.go: Grep, Glob, LS, and notebook paths, and relative paths joined to the line's working directory, and paths after a redirection or a comma in a command), gives a sidechain's prompt the sourcesubagent, and listscontent_blocks_searched_atandcontent_blocks_kind_order. Itsplans_test.goalso checks that the reads those indexes are for use them. The release after a swap removes the retired version's package, as this one removedcore/v1/.intake/is the HTTP handler: OTLP logs in, archive records out. It has one handler for requests that Authentik checked, and one for pods that send a ServiceAccount token.cluster/asks the API server's TokenReview who a pod's token belongs to.tools/serves at/mcpthe six tools of plan 2 on the live core schema, with no auth, one file for each tool, its SQL beside its handler, andNewOnCoreserves them.core.gohasonLive, which reads the live schema frombuildsfor each call, reads once the sessions that the call's view does not see (see), and runs a call once more when the swap drops its schema part way through, and the CTEinvisiblethat starts every query, the sessions that the view does not see: the hidden ones, and in the shared view those thatsession_privatemarks.privacy.gohas theFullandSharedviews andPrivacy, whose repositoriesOpenCorechecks in Postgres.routed.goisNewRouted, which chooses at each request between the tools' server and one whose instructions say that the core tables are still building, by whether a schema of version 2 or later is live; until one is, each call returnsErrOldCore.inputs.gohas the inputs that every tool shares and the cap of a result, andsearch_query.gothe parse of a query into terms. A query names the schema as{core}, and an index's expression, such asv2.TrigramText, is copied fromcore/v2, so a read matches it.config/reads the shipper's file ofNAME=valuelines, the private repositories and tools with their defaults,MIDDEN_DATABASE_LIMIT, andMIDDEN_CORE_BUILD_PAUSE.ship/reads Claude Code's transcripts and sends them to midden.postgres/opens midden's pools of connections to its database. The archive's two pools, the core layer's pool, with its LISTEN and index connections, and the tools' pool are all dialed here, with a connect timeout, TCP keepalive, and on LinuxTCP_USER_TIMEOUT, so that a dead connection fails in about 30 s. A new connection to the database goes through it.TCP_USER_TIMEOUTalso ends a healthy connection whose data stays unsent for 30 s because Postgres is not reading, so a writer that sends much at once sends it in batches that Postgres's receive window holds on the wire, asAppenddoes.WaitForConnectionwaits up to 30 s while the database refuses connections, as it does for a new pod until the NetworkPolicy admits the pod, andarchive.Opencalls it before it applies the schema.metrics/holds the registry, the build and process series, and the handler of/metrics.intake/metrics.go,tools/metrics.go, andcore/metrics.godeclare each domain's own series on it. The README's "Metrics" lists them all.ko-build.shand.ko.yamlbuild the image with ko. The binary is at/ko-app/middenand is the image's entrypoint, with no default arguments, so a container passesserveas itsargs.main.gois themiddencommand, withserve,mcp, andship.serveruns the intake onMIDDEN_LISTEN, each MCP view on its own address when that address is set, the core layer's worker, andDropUnused. Both serve the views bymcpViewsandtools.NewRouted.mcpruns only the MCP views, on read-only connections, with the hidden sessions ofMIDDEN_HIDDEN_SESSIONS.
Tests run against a real Postgres. internal/testdb starts one for
each package with embedded-postgres, which downloads the Postgres
binaries once into ~/.embedded-postgres-go. Each test gets its own
database. A test of a series reads it from the registry with
internal/promtest. The shipper's tests run the real intake handler behind a
stand-in for Authentik. The tools' tests drive both MCP addresses with
the SDK's client. The core layer's tests build a session in each way its
records can arrive, and compare every row of core_v2 with a build of
the same records from nothing.
make test # gofmt, go mod tidy -diff, go vet, staticcheck, go test -race
prek run --all-files
go test -race needs cgo and a C compiler. Without one, run
go test ./....
CI is .tangled/workflows/ci.yml. It runs the checks of make test
without -race, because its pod has no C compiler, runs the tests as
an unprivileged user because Postgres refuses root, and on a push to
main, in the weekly run, and in a manual run on main builds the image with ./ko-build.sh and pushes it to
atcr.io/guid.foo/midden, tagged latest and
<UTC yyyymmddHHMMSS>-<short sha>. A pull request builds the image
and pushes nothing.
A transcript entry is never dropped. midden keeps one row for each entry of each transcript file, keyed by the session, the file, and the entry's uuid, or its byte offset when it has no uuid. A resumed session's file repeats earlier entries with the same uuid, and each copy is kept.
Plans #
A plan's location shows its status. A file at the top of plans/ is
not built yet, and a file in plans/completed/ is built, so the commit
that builds a plan also moves it to completed/ and adds the date to
its header. Write the plan before the code, except for a small fix that
a test reproduces and that changes no design. plans/README.md
describes the layout.