DevelopStorage
@holtkeeper/store-postgres
PostgreSQL implementation of the Store contract from @holtkeeper/store, built on Bun’s built-in client (import { SQL } from 'bun'): tagged-template queries with bound parameters, no ORM, no extra dependencies. It passes describeStoreContract unchanged, so it behaves like memoryStore and sqliteStore, including the optional parts: config documents, kv, the audit log and external accounts.
Use it when several server processes share one database, or when you already run Postgres with backups and monitoring. For a single process, @holtkeeper/store-sqlite is simpler.
import { defineConfig } from '@holtkeeper/core'import { env } from '@holtkeeper/forge'import { postgresStore } from '@holtkeeper/store-postgres'
export default defineConfig({ // ... server: { store: postgresStore({ url: env('DATABASE_URL') }), },})postgresStore(options) returns a PostgresStore (a Store plus ready()):
| Option | Default | Meaning |
|---|---|---|
url |
required | postgres://user:password@host:5432/db, or env('NAME') / { env: 'NAME' } to read it from the environment on first use |
schema |
holtkeeper |
Schema holding every table. Lowercase letters, digits and _; created on first use if missing |
max |
10 |
Pool size: the most connections this process opens |
ssl |
from the URL | true, an SSL mode ('require', 'verify-full', …) or Bun’s TLS options ({ ca: Bun.file('ca.pem') }). ?sslmode= in the URL works too |
Creating the store does nothing: the URL is read, the pool opens and migrations run on the first call. Call await store.ready() at startup to fail fast on a wrong URL or missing rights. A failed start is retried by the next call. close() waits for running queries and closes the pool.
Every query names its tables with the schema ("holtkeeper"."jobs"), so the store does not depend on search_path and works behind PgBouncer. With PgBouncer in transaction mode, use version 1.21 or later with max_prepared_statements set; Bun uses named prepared statements.
Local Postgres
Section titled “Local Postgres”services: postgres: image: postgres:17-alpine environment: POSTGRES_USER: holtkeeper POSTGRES_PASSWORD: holtkeeper POSTGRES_DB: holtkeeper ports: ['5432:5432'] volumes: ['pgdata:/var/lib/postgresql/data'] healthcheck: test: ['CMD', 'pg_isready', '-U', 'holtkeeper'] interval: 5svolumes: pgdata:docker compose up -d postgresexport DATABASE_URL=postgres://holtkeeper:holtkeeper@localhost:5432/holtkeeperexamples/dev/holtkeeper.config.ts has the matching postgresStore line as a commented alternative to SQLite.
Rights
Section titled “Rights”The role needs CREATE on the database to create the schema on first start, or the schema can be created beforehand (CREATE SCHEMA holtkeeper AUTHORIZATION holtkeeper), after which owning that schema is enough. Accent-insensitive search needs the unaccent extension: the first migration installs it when it can (it is a trusted extension, so a role with CREATE on the database may) and otherwise falls back to search without accent folding.
The database inspector (store.database, see @holtkeeper/store) works with these rights alone, with two exceptions. Statement statistics need pg_stat_statements loaded through shared_preload_libraries and CREATE EXTENSION pg_stat_statements in the database (on CloudNativePG, setting any pg_stat_statements.* parameter does both). Statements and session details of other users, and replication lag, need the pg_read_all_stats role; without it they read as <insufficient privilege> or are left out. Resetting statement statistics needs EXECUTE on pg_stat_statements_reset, which only superusers have by default.
Migrations
Section titled “Migrations”src/migrations.ts holds an ordered, append-only list of { version, sql } steps. On start, migrate runs in one transaction:
pg_advisory_xact_lockon a key derived from the schema name, so processes that start together wait for each other and only the first one migrates;- creates the schema if it does not exist, and
schema_migrations (version, applied_at)inside it; - applies every step whose version is not recorded yet, in version order (also lower versions merged after higher ones), with
search_pathset to the schema for that transaction only.
A failing step rolls back the whole run, so the schema is never half-migrated. To change the schema, append a step with the next version; never edit a released one. migrate(sql, schema, steps?) and migrations are exported for tooling.
Migration 21 cleans up after retired features (no schema change): it deletes analysis records and jobs of the retired analyzers (changelog, quality, release-risk, fleet, delivery, port, warmup), settings rows under the retired keys (llm.model, llm.models, review.instructions, agent.instructions, analyzers.<retired kind>), the digest and Slack policy entries in kv (digests, digest:*, chat:slack:policy; the stored Slack tokens in chat:slack:connection stay), and removes those analyzers from schedule and trigger documents. A document left with no analyzer (or a command trigger for one) is deleted with its history; any other changed document gets a new version by system, its previous version archived in config_history. The server still ignores such leftovers (retired setting keys, unknown analyzers in schedules, triggers and commands, records of unknown kinds) on stores that never ran it.
Migration 22 adds the jsonb column analyses.metrics. Existing records keep it NULL (no backfill): servers compute metrics of the newest records from their data when they read them, until the next run stores them.
Migration 31 deletes the settings rows of the retired slack.reviews key (no schema change); other settings stay.
Schema
Section titled “Schema”Columns that are filtered or sorted are real columns; nested data is jsonb. Timestamps are timestamptz and come back as Date#toISOString() strings (2026-10-29T12:00:00.000Z), whatever offset they were written with. Passkey and link token times are text and come back exactly as written. Every table has an identity seq (or a natural key) that keeps insertion order for ties.
| Table | Notes |
|---|---|
analyses |
data and metrics (migration 22) in jsonb; indexes on time and repository |
credentials, settings |
scope, rotation, options, value in jsonb |
users, passkeys, identities, link_tokens |
children reference users (id) ON DELETE CASCADE; email_lower for case-insensitive lookup |
jobs |
partial index of due jobs; partial unique index jobs_one_running_per_analyzer on (repo_forge, repo_path, analyzer) WHERE status = 'running'; jobs_active_repo for claim checks |
ai_usage |
teams in jsonb with a GIN index (ai_usage_teams; groups / ai_usage_groups before migration 29); tokens and durations bigint, cost double precision |
config_documents, config_history, kv |
documents keyed by (type, id); kv.expires_at is a timestamptz; leases and compare-and-set are single statements on kv |
external_accounts |
unique (provider, external_id); not tied to users by a foreign key (principals of other providers link too) |
audit_events, audit_state |
each event whole in jsonb plus filter columns; one audit_state row holds the chain head and how far retention swept |
libraries, library_versions, library_chunks, library_chunk_versions, library_issues |
migration 10; records and issues whole in data (jsonb), chunk versions in their own table (cascading on chunk delete), generated tsvector columns search with GIN indexes |
learning_claims, review_reactions |
migration 15; reaction counts whole in data (jsonb); claim is an INSERT ... ON CONFLICT DO NOTHING |
credentials.capabilities, ai_usage.transcript_ref |
migration 16; probe results in jsonb, the run’s transcript artifact id; index ai_usage_job on job_id |
chat_threads, chat_messages, chat_thread_reads |
migration 17; threads and messages whole in data (jsonb); chat_messages.seq is an identity column and the polling cursor (a new message locks its thread row first, so one thread’s messages commit in seq order); read markers keyed by (thread_id, user_id) |
agent_task_groups, agent_tasks |
migration 20; groups and tasks whole in data (jsonb), agent_tasks with group_id, repo, status and updated_at columns for lookups |
ai_usage.interactive, ai_usage.subject, jobs_analysis |
migration 23; who started a run (boolean, false for older rows) and what it worked on; indexes ai_usage_actor_at on (actor, at) and jobs_analysis on analysis_id |
chat_threads.context_repos, chat_messages.refs, chat_thread_mutes |
migration 25; context repositories and message refs as jsonb arrays kept out of data ([] for older rows), mutes keyed by (user_id, thread_id) |
users.last_seen_at, credentials.last_used_at |
migration 26; timestamptz, NULL until the first touchUser / touch; upserts keep the later of the stored and the written value (GREATEST) |
slack_messages |
migration 27; one row per Slack message and merge request, the link whole in data (jsonb); indexes on (repo, merge_request) and created_at |
slack_replies |
migration 28; one row per status reply, keyed (channel, ts) of the message it answers, the reply whole in data (jsonb); index on created_at |
rules, rule_history, learnings |
migration 33; replaces knowledge, knowledge_history, guides, guide_history, guide_generated, families, embeddings and the old learnings (nothing carried over). Rules in columns (scope, files, agents as jsonb) with a generated tsvector search and a GIN index, history cascading on delete; learnings whole in data (jsonb) with key, text, status, origin and text timestamps as columns and a generated search |
ai_usage.teams |
migration 29; renames ai_usage.groups to teams (and its index to ai_usage_teams). No values are converted; stored group keys become team keys through the separate one-off conversion |
Behavior worth knowing
Section titled “Behavior worth knowing”- Job claims.
claimruns in one transaction: it picks the first due job that may start under theClaimRules(apriorityjob first, with a second lookup for the rest, so both walk the due index in order) and locks it withFOR UPDATE SKIP LOCKED, so concurrent workers never wait on or share a row. Then it takes a transaction-level advisory lock on the job’s repository and marks the job running only if it still may start. Workers starting jobs of one repository serialize on that lock and each sees what the previous one committed, so a reader never starts next to an exclusive job even when two workers pick jobs of one repository at the same moment; the loser rolls back and picks again. The unique indexjobs_one_running_per_analyzerbacks the one-job-per-analyzer rule. Migration 9 replaced the olderjobs_one_running_per_repoindex; running rows of an existing database always satisfy the new one.heartbeat,fail,cancelandrecoverStaleare single conditionalUPDATEs that also end the last entry of theattempts_historyjsonb array in place. Migration 13 dropped the oldlogcolumn, addedattempts_historyanderror_signatureand indexes failed jobs byfinished_atforfailures. - Rule and learning search.
rules.search=setweight(title, 'A') || setweight(description, 'B') || setweight(body, 'C')andlearnings.search=setweight(text, 'A'), overto_tsvector('simple', knowledge_fold(...)), whereknowledge_foldisunaccentwhen available. The input is split into words like the memory store does, each word becomes a quoted prefix operand ('migr':*) and words are OR-ed (prefixTsQuery), so operators, quotes and punctuation are always plain text. Results are ordered byts_rankwith weights A 1.0, B 0.6, C 0.2 (the 5 : 3 : 1 of the SQLite store), then by recency;scoreis that rank. Ruleputserializes writers of one rule with an advisory lock, so versions never collide andexpectedVersionis checked against what is really stored. - Library search.
library_chunks.search=setweight(heading_text, 'A') || setweight(text, 'C'),library_issues.search=setweight(title, 'A') || setweight(digest_text, 'B') || setweight(body_text, 'C'), overto_tsvector('simple', library_search_text(...)), which replaces ASCII punctuation with spaces (sofs.readFileindexesfsandreadfileinstead of one host-like token) and appliesknowledge_fold.libraryTsQuerybuilds the query from words ('use':*) and quoted phrases (('cannot' <-> 'read')), OR-ed; results are ordered byts_rankwith the same weights.listVersionsand chunkversionsare sorted in JavaScript bycompareLibraryVersions; chunk lists use theCcollation for path order.libraryStatsis one query with correlatedcount(*)subqueries per library. - AI usage aggregates. One static
GROUP BYquery: every dimension is computed only when requested (to_char(at AT TIME ZONE 'UTC', ...)fordayandmonth,date_trunc('week', ...)for the Monday of the ISO week), the others collapse to''.teamexpandsteamswith a lateral join. Scope filters resolve to the covered (repository, teams) pairs first, like SQLite. - Query plans. Connections set
plan_cache_mode = force_custom_plan. Bun prepares every statement, and the optional filters ($1 IS NULL OR kind = $2) would otherwise get a generic plan after five runs that filters every row instead of using an index (10 ms instead of 0.2 ms for an analysis list of 3000 records). - Newest analyses.
analyses.latestpicks oneseqper repository and kind withDISTINCT ONoveranalyses_repo_kind, then reads only those rows, so the largedataof older records is never fetched. - Database inspector. Sizes come from
pg_relation_size,pg_indexes_sizeandpg_total_relation_size(TOAST is the rest), counters frompg_stat_all_tables,pg_stat_all_indexesandpg_stat_database; row counts arereltuplesestimates, or live tuples before the first analyze. Connections count every client backend of the server, sincemax_connectionsis server-wide. Statements are those of the current database from the schemapg_stat_statementsis installed in. Replicas are listed only on a primary. - Audit summary.
summaryruns one grouped query per dimension; days areto_char(at AT TIME ZONE 'UTC', 'YYYY-MM-DD'), actor names come from the newest matching event’sjsonb. - Audit log.
appendlocks theaudit_staterow, so appends from every process form one chain.sweepdeletes the oldest events up to the first one at or after the cutoff and records how far it went, soverifyChainstill knows where the kept chain starts after everything was swept.
Differences from SQLite
Section titled “Differences from SQLite”- Several processes can share the database; SQLite serializes writers on one file.
jsonbdoes not keep object key order or duplicate keys, and cannot hold\u0000in strings. Values compare equal after a round trip, but key order may differ.- Timestamps are real instants: written
+02:00offsets come back as UTC...Z, and invalid timestamps are rejected instead of stored as text. - Search uses the
simpletext search configuration, not FTS5unicode61. Ranks are not the same numbers as SQLite’s-bm25, but order results the same way (title over tags over body). Withoutunaccent,cafedoes not findcafé. - Lists ordered by text (config documents) use the
Ccollation, matching the memory store’s code-unit order regardless of the database locale.
Backups
Section titled “Backups”- Logical:
pg_dump --schema=holtkeeper --format=custom "$DATABASE_URL" > holtkeeper.dump, restore withpg_restore --dbname "$DATABASE_URL" holtkeeper.dump. A dump is a consistent snapshot of a running database. - Physical / point in time: use your platform’s base backups and WAL archiving (managed Postgres,
pgBackRest,barman). - Credential secrets and webhook secrets are sealed by the
Vault; back up the vault key separately from the database.
src/database.test.ts checks the database inspector against the same database. src/postgres.test.ts runs describeStoreContract('postgres', ...) plus Postgres-specific tests (concurrent starts, migration rollback, same-repository claim races with exclusive jobs, the running-job index migration, timestamp normalization, accent folding) when HOLTKEEPER_PG_URL is set. Each store under test gets its own schema holtkeeper_test_<run>_<n>, dropped afterwards. Without the variable those tests are skipped; src/rows.test.ts, src/queries.test.ts and src/libraries.test.ts (row mapping, filter parameters, search terms, migration ordering) always run.
docker run --rm -d --name holtkeeper-pg -e POSTGRES_PASSWORD=pw -p 55432:5432 postgres:17-alpineHOLTKEEPER_PG_URL=postgres://postgres:pw@localhost:55432/postgres bun test packages/store-postgresdocker stop holtkeeper-pg