# midden AGENTS.md `README.md` is the design. This file is how to work on the code. - `archive/` stores records in Postgres. `schema.sql` is the whole schema, and `archive.Open` applies it on every start, so each change to it must be safe to run again on a database that has the old one. - `archive.go` opens the archive and appends records. - `unused.go` is `DropUnused`, which `serve` runs after each start. It drops what nothing uses, which `schema.sql` no longer creates: the trigger `records_entry_places`, and then the trigger `records_session_traits` and its function `record_session_traits`, which stored the same rows as `Append`. Dropping a trigger needs an `ACCESS EXCLUSIVE` lock on `records`, so each drop waits for the lock at most `lockTimeout` and tries again. The drop of `record_session_traits` takes the schema's advisory lock first, under the same bound, because a start of an older release replaces the function. Then it drops the indexes `records_search` and `records_session_time`, with `DROP INDEX CONCURRENTLY`, and the functions of `records_search`. Then it sets `records` to be vacuumed after 2% of its rows are new, as the core tables are, in a transaction of its own and only when `pg_class.reloptions` lacks the setting: `ALTER TABLE SET` takes a `SHARE UPDATE EXCLUSIVE` lock, which no `Append` waits for but which waits for autovacuum and for a concurrent index build of `records`, so it waits at most `vacuumLockTimeout`, under the default `deadlock_timeout`, and tries again. Once all that is done it reads only the catalog. - `session_traits`, `entry_traits`, and the SQL function `session_private` in `schema.sql` are the privacy rule that the tools apply. The start that creates `session_traits` backfills it from the records already stored. - `traits.go` is `writeTraits`. In its transaction, `Append` stores in `session_traits` the traits of the records it inserted, in one statement over their ids, from `entry_traits`, and `ON CONFLICT DO NOTHING` keeps one row of each trait. The rows are inserted in sorted order, so that two writers take their locks in one order. `traits_test.go` checks what `Append` stores, case by case and over `testdata/entries.jsonl`, a corpus of the shapes of Claude Code's transcript lines, and the backfill. - `outbox.go` is the outbox of the core layer: in its transaction, `Append` upserts one row of `pending_sessions` for each session it stored transcript rows for, for the live schema and the newest building one in `builds`, sends `NOTIFY midden_core`, and after the commit hands the sessions to its own process's worker on `Wakes`. - `core/` builds the core layer, tables built from `records`, one schema for each builder version, as `plans/1-core-tables-built-from-records.md` designs it. The tools on the core tables read the live schema. - `builder.go` is 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.go` is `Run`: the wakes, `LISTEN`, the sweep every 30 s, and `Drain`, which builds the live schema's pending rows before a rebuild's. `claims.go` claims a pending row and checks its `claim` and `seq`, and `build.go` builds one session in chunks. - `compare.go` is the comparison of `records` with a schema's lines, under a lease on its row of `builds`, and `builds.go` creates a version's build, checks `MIDDEN_DATABASE_LIMIT`, retires an older building version, swaps, and drops a retired schema. - `indexes.go` builds with `CREATE INDEX CONCURRENTLY` the indexes that a version lists in `Indexes`, and `records_core` on `records`, 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 in `builds.go`, which holds and renews the comparison's lease and swaps when they are valid. An index with an `Extension` names 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 plain `CREATE INDEX` blocks the workers' writes, and `IF NOT EXISTS` takes that lock before it finds the index. An index added to an existing schema goes in `Indexes`. - `metrics.go` declares the `midden_core_build_*` series. - `core/v2/` is builder version 2, with schema `core_v2`, the live schema until version 3 swaps. It adds to version 1's tables `tool_calls`, `api_requests`, `session_repos` with each checkout's root, the entry's `session_id`, `at`, and `first_record_id` and each prompt's `source` in `content_blocks`, `sessions.label` and `last_text`, `session_tools.calls`, the rule of repositories in `repoOf` (`traits.go`), and the indexes of search and the tools. `TrigramText` is the expression of the trigram index, which a read must match against. `Size` is its estimate for `MIDDEN_DATABASE_LIMIT`. `parse.go` is its frozen parse of an entry's parts, and `traits.go` its frozen copy of the decode that matches `entry_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.go` checks that each of the builder's reads of a session uses an index that the DDL creates. - `core/v3/` is builder version 3, with schema `core_v3`, which builds beside `core_v2` and swaps live once complete. It starts as a copy of version 2, keeps every table, column, and index that `tools/` reads, and reads a session's repositories from more paths (`inputPaths` in `traits.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 source `subagent`, and lists `content_blocks_searched_at` and `content_blocks_kind_order`. Its `plans_test.go` also checks that the reads those indexes are for use them. The release after a swap removes the retired version's package, as this one removed `core/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 `/mcp` the six tools of plan 2 on the live core schema, with no auth, one file for each tool, its SQL beside its handler, and `NewOnCore` serves them. `core.go` has `onLive`, which reads the live schema from `builds` for 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 CTE `invisible` that starts every query, the sessions that the view does not see: the hidden ones, and in the shared view those that `session_private` marks. `privacy.go` has the `Full` and `Shared` views and `Privacy`, whose repositories `OpenCore` checks in Postgres. `routed.go` is `NewRouted`, 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 returns `ErrOldCore`. `inputs.go` has the inputs that every tool shares and the cap of a result, and `search_query.go` the parse of a query into terms. A query names the schema as `{core}`, and an index's expression, such as `v2.TrigramText`, is copied from `core/v2`, so a read matches it. - `config/` reads the shipper's file of `NAME=value` lines, the private repositories and tools with their defaults, `MIDDEN_DATABASE_LIMIT`, and `MIDDEN_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 Linux `TCP_USER_TIMEOUT`, so that a dead connection fails in about 30 s. A new connection to the database goes through it. `TCP_USER_TIMEOUT` also 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, as `Append` does. `WaitForConnection` waits up to 30 s while the database refuses connections, as it does for a new pod until the NetworkPolicy admits the pod, and `archive.Open` calls 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`, and `core/metrics.go` declare each domain's own series on it. The README's "Metrics" lists them all. - `ko-build.sh` and `.ko.yaml` build the image with ko. The binary is at `/ko-app/midden` and is the image's entrypoint, with no default arguments, so a container passes `serve` as its `args`. - `main.go` is the `midden` command, with `serve`, `mcp`, and `ship`. `serve` runs the intake on `MIDDEN_LISTEN`, each MCP view on its own address when that address is set, the core layer's worker, and `DropUnused`. Both serve the views by `mcpViews` and `tools.NewRouted`. `mcp` runs only the MCP views, on read-only connections, with the hidden sessions of `MIDDEN_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. ```bash 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 `-`. 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.