chat / state-pg
AGENTS.md2.4k starsChanged 59 days agoMITView on GitHub
Guidance for coding agents working inside the PostgreSQL state adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls. @chat-adapter/state-pg persists Chat SDK state in PostgreSQL using the pg client. Pick this adapter when: - Postgres is already your primary datastore and you don't want to add Redis to the stack. - You need rich query access (analytics, audit, joins) over subscriptions / cache…
Trending
Quiet since March.thin dataabout the whole repository
Who's talking about vercel/chat
- @camilleroux.com“Un SDK TypeScript unifié pour créer des chatbots qui fonctionnent sur Slack, Teams, Google Chat, Discord, …”Bluesky · Mar 3, 2026 · 3 likes
- @technews4869.bsky.social“github.com/vercel/chat GitHub - vercel/chat: A unified TypeScript SDK for building chat bots across Slack, …”Bluesky · Mar 7, 2026 · 1 likes
- @yug1224.com“チャットアプリ開発に使える統一SDKを提供するツールらしい 様々なプラットフォーム対応で便利そうだな yug1224 starred vercel/chat https://github.com/vercel/chat”Bluesky · Mar 7, 2026 · 1 likes
- @news.humancoders.com“Vercel lance Chat SDK : un SDK TypeScript unifié pour créer des bots multi-plateformes”Bluesky · Mar 5, 2026 · 1 likes
- @github-trending-js.bsky.social“🔥 Hot Repo! 🔥 (100+ new stars) 📦 vercel / chat ⭐ 871 (+121) 🗒 TypeScript A unified TypeScript SDK for …”Bluesky · Feb 27, 2026 · 1 likes
The biggest 5 of 5 mentions linking to the repository that our crawl found. Each line is their own headline.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository44 other files it gives its agents.
- AGENTS.mdAGENTS.md
- apps/docs/AGENTS.mdAGENTS.md
- chat-sdkAGENTS.md
- packages/adapter-discord/AGENTS.mdAGENTS.md
- packages/adapter-gchat/AGENTS.mdAGENTS.md
- packages/adapter-github/AGENTS.mdAGENTS.md
- packages/adapter-instagram/AGENTS.mdAGENTS.md
- packages/adapter-linear/AGENTS.mdAGENTS.md
- packages/adapter-messenger/AGENTS.mdAGENTS.md
- packages/adapter-notion/AGENTS.mdAGENTS.md
- packages/adapter-slack/AGENTS.mdAGENTS.md
- packages/adapter-teams/AGENTS.mdAGENTS.md
- packages/adapter-telegram/AGENTS.mdAGENTS.md
- packages/adapter-web/AGENTS.mdAGENTS.md
- packages/adapter-whatsapp/AGENTS.mdAGENTS.md
- packages/chat/src/adapters/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/_template/AGENTS.mdAGENTS.md
- packages/state-ioredis/AGENTS.mdAGENTS.md
- packages/state-memory/AGENTS.mdAGENTS.md
- packages/state-redis/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- packages/adapter-discord/CLAUDE.mdCLAUDE.md
- packages/adapter-gchat/CLAUDE.mdCLAUDE.md
- packages/adapter-github/CLAUDE.mdCLAUDE.md
- packages/adapter-linear/CLAUDE.mdCLAUDE.md
- packages/adapter-messenger/CLAUDE.mdCLAUDE.md
- packages/adapter-slack/CLAUDE.mdCLAUDE.md
- packages/adapter-teams/CLAUDE.mdCLAUDE.md
- packages/adapter-telegram/CLAUDE.mdCLAUDE.md
- packages/adapter-web/CLAUDE.mdCLAUDE.md
- packages/adapter-whatsapp/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/_template/CLAUDE.mdCLAUDE.md
- packages/state-ioredis/CLAUDE.mdCLAUDE.md
- packages/state-memory/CLAUDE.mdCLAUDE.md
- packages/state-pg/CLAUDE.mdCLAUDE.md
- packages/state-redis/CLAUDE.mdCLAUDE.md
- add-adapterSkill
- technical-writerSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
The file
We split this AGENTS.md into the rules it gives an agent
6 rules. About 0 are common, 3 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 76
Never fall back to an application's POSTGRES_URL for these tests.
- Very specific: line 123
UPDATE only on locks, cache, and lists, and nextval on the list and queue sequences via USAGE or UPDATE, skipped for identity columns.
- Distinctive: line 223
Use named exports throughout.
- Distinctive: line 224
Keep SQL close to the operation using the existing parameterized-query style.
- Distinctive: line 230
Use parameterized queries everywhere — never string-concatenate user input into SQL.
- Very specific: line 239
Update postgresSchemaStatements and the matching SQL blocks in README.md and apps/docs/content/adapters/official/postgres.mdx (the unit …
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md — @chat-adapter/state-pg
Guidance for coding agents working inside the PostgreSQL state adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls.
Overview
@chat-adapter/state-pg persists Chat SDK state in PostgreSQL using
the pg client. Pick this adapter when:
- Postgres is already your primary datastore and you don't want to add Redis to the stack.
- You need rich query access (analytics, audit, joins) over subscriptions / cache / lists.
- You're deploying to platforms with managed Postgres (Vercel Postgres, Supabase, Neon, RDS, Cloud SQL) and prefer not to add a separate cache.
Trade-offs vs Redis: lock acquisition is slower (single-row
upsert with timestamp comparison instead of SET NX PX) and TTL
cleanup must run as a periodic job rather than via Redis's built-in
expiration.
Directory layout
packages/state-pg/
├── src/
│ ├── index.ts # PostgresStateAdapter + createPostgresState
│ ├── index.test.ts # mocked StateAdapter tests
│ └── postgres.integration.test.ts # real database regression tests
├── package.json
├── tsconfig.json
├── tsup.config.ts
├── vitest.config.ts
└── README.mdBuild, test, typecheck
pnpm build
pnpm dev
pnpm test
pnpm test:watch
pnpm typecheck
pnpm clean
# from repo root
pnpm --filter @chat-adapter/state-pg build
pnpm --filter @chat-adapter/state-pg testThe unit tests use a vi.fn()-backed Postgres stub. They also read the
migration SQL block from README.md and the adapter docs and compare it,
whitespace-normalized, to postgresSchemaStatements, so documentation
drift fails pnpm test without a database.
Real database tests live in src/postgres.integration.test.ts and run
only when POSTGRES_TEST_URL is exported. Use a disposable database and
an admin role with CREATEROLE and CREATE on the database; superuser
is not required because the tests grant the admin membership in the
runtime role they create. The tests create UUID-named schemas and
restricted roles, execute postgresSchemaStatements, and remove only
those resources afterward. POSTGRES_TEST_URL is declared in
turbo.json globalEnv, so both invocations below see it.
POSTGRES_TEST_URL=postgres://localhost/chat_test pnpm --filter @chat-adapter/state-pg test
POSTGRES_TEST_URL=postgres://localhost/chat_test pnpm testNever fall back to an application's POSTGRES_URL for these tests.
Public surface
Main exports from src/index.ts:
createPostgresState(config?)— primary factory. Auto-detectsPOSTGRES_URL(a.k.a.DATABASE_URL).PostgresStateAdapterclass — implements the Chat SDKStateAdapterinterface. Public methods cover subscriptions, locks, cache, lists, queues, plusdisconnect().PostgresStateAdapterOptions— URL or external-client options union.postgresSchemaStatements— the complete DDL, in execution order, for migration tooling and for the docs parity test.
Configuration
import pg from "pg";
import { createPostgresState } from "@chat-adapter/state-pg";
createPostgresState({
client: existingPgPool, // or provide url, not both
keyPrefix: "chat-sdk",
logger: customLogger,
autoCreateSchema: false, // default true; false for migrations
});Either url, client, or one of the auto-detected env vars must be
present at runtime. The adapter creates a pg.Pool with sensible
defaults when only url is provided.
Schema
By default, connect() creates five tables and four expiry indexes by
running postgresSchemaStatements in order. That array is the single
source of the DDL; ensureSchema() iterates it, the unit tests assert it,
and the SQL blocks in README.md and
the adapter docs must match it statement for statement (a unit test
enforces this). List and queue seq columns use bigserial sequences.
With autoCreateSchema: false, connect() issues no DDL. After SELECT 1
it runs one read-only probe and rejects with a descriptive error when a
table or grant is missing, so misconfiguration fails at startup rather than
inside the first message. The probe checks only what each operation needs
(tablePrivileges in index.ts): SELECT/INSERT/DELETE on every table,
UPDATE only on locks, cache, and lists, and nextval on the list and queue
sequences via USAGE or UPDATE, skipped for identity columns. Keep that map
in step with the SQL when adding operations. The integration suite runs
under exactly these least-privilege grants. Applications must migrate
first and grant the runtime role at least these privileges plus schema
USAGE. Future schema updates are also the application's responsibility.
There is no schemaName option. Queries use unqualified table names and
resolve against PostgreSQL search_path. The docs recommend
ALTER ROLE ... SET search_path for the runtime role because it survives
transaction-mode poolers, with per-connection options as the
direct-connection alternative.
Locking semantics
acquireLock(threadId, ttlMs):
- Generates a unique token (UUID v4).
- Issues
INSERT ... ON CONFLICT (key_prefix, thread_id) DO UPDATE SET token = EXCLUDED.token, expires_at = EXCLUDED.expires_at WHERE chat_state_locks.expires_at <= now(). - Returns
{ threadId, token, expiresAt }when the row was inserted or updated,nullotherwise.
releaseLock(lock):
DELETE FROM chat_state_locks WHERE key_prefix = $1 AND thread_id = $2 AND token = $3.- Resolves without a return value.
forceReleaseLock(threadId) is unconditional DELETE.
PostgreSQL row locking on the (key_prefix, thread_id) primary key
gives serialised acquisitions; the expires_at <= now() clause lets
expired locks be replaced atomically.
Capabilities
- Persistence — yes.
- Multi-instance — yes.
- Subscriptions — yes.
- Distributed locking — yes, atomic via
ON CONFLICTupsert. - Key-value cache — yes, with TTL.
- Lists — yes, with per-entry TTL.
- Queues — yes, with per-entry TTL.
- Automatic reconnect — yes (delegated to
pg.Pool). - Cluster — n/a; use a multi-replica Postgres or a connection pooler (PgBouncer).
- Sentinel — n/a.
- Key prefix namespacing — yes.
Expired row cleanup
Postgres does not expire rows automatically. The adapter performs opportunistic cleanup:
- Expired locks are overwritten on the next
acquireLockcall. - Expired cache entries are deleted on the next
getcall for the same key. - Expired queue entries are purged on enqueue/dequeue.
- Expired list entries are filtered out of reads but are not deleted.
For high-throughput deployments, run a periodic job:
DELETE FROM chat_state_locks WHERE expires_at <= now();
DELETE FROM chat_state_cache WHERE expires_at <= now();
DELETE FROM chat_state_lists WHERE expires_at <= now();
DELETE FROM chat_state_queues WHERE expires_at <= now();A scheduled worker once per minute is plenty.
Connection management
The adapter uses one Postgres pool per PostgresStateAdapter
instance. If you bring your own client (pg.Pool or compatible),
the adapter still checks connectivity on connect() and does not call
end() on disconnect(). Concurrent connect calls share initialization;
failed initialization can be retried.
Queries are issued via pool.query. There are no implicit transactions.
Individual lock/cache upserts and queue dequeue use atomic SQL statements.
Error handling
Connection errors are logged and rethrown. Query errors propagate from
pg without custom error mapping or automatic adapter-level retries.
Testing approach
- Unit tests in
index.test.tsuse a mocked pool to verify SQL and lifecycle. - Real database tests execute
postgresSchemaStatementswith an owner role, then exercise state operations under a role without DDL privileges, and assert thatconnect()rejects when tables or grants are missing. - Cache regressions cover expiry without a prior read, the exact
now()boundary, and claims from independent connections.
Coding conventions
- Use named exports throughout. No default exports.
- Keep SQL close to the operation using the existing parameterized-query style.
- TTLs are stored as
timestamptzcolumns — never asintervalvalues — so reads can compare againstnow()without per-row math. - Top-level regex literals only.
- Use parameterized queries everywhere — never string-concatenate user input into SQL.
Releases
Behavioural changes need a changeset (pnpm changeset, choose
@chat-adapter/state-pg plus chat if a public StateAdapter type
changed). Schema-changing PRs must additionally:
- Update
postgresSchemaStatementsand the matching SQL blocks inREADME.mdandapps/docs/content/adapters/official/postgres.mdx(the unit test fails otherwise). - Publish the incremental statements (
ALTER TABLE ... ADD COLUMN,CREATE INDEX IF NOT EXISTS, ...) in the changeset.CREATE TABLE IF NOT EXISTSnever alters an existing table, so both auto-created and migration-owned deployments need them, andautoCreateSchema: falsedeployments run no DDL onconnect()at all.
Where to look next
- User-facing docs:
apps/docs/content/adapters/official/postgres.mdx - README:
packages/state-pg/README.md - Core StateAdapter contract:
packages/chat/src/types.ts - Sibling state adapters:
packages/state-memorypackages/state-redispackages/state-ioredis
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

