Agent Rooms
PostgreSQL Migrations

Agent Room PostgreSQL migration guide

This guide covers upgrades from the original Agent Room schema to the complete operational schema. Migrations are additive and must be applied in order by @agentplat/rooms-postgres.

Migration inventory

VersionCapabilityPrimary persisted state
001Agent Room aggregateRooms, participants, messages, tasks, runs, artifacts, approvals, memory, tools and domain events
002Execution sessionsResumable execution state and intervention history
003Agent Definition RegistryStable agent identities and immutable published revisions
004AgentPlat HandoffsTyped transfer lifecycle and revision fencing
005CoordinationRevisioned inbox, leases, retries and outcomes
006Human contributionsRequests, lifecycle events and work-management deliveries
007Knowledge bundlesImmutable content-addressed knowledge revisions
008PlannerTyped plans, materialized identities and step progress
009Participant membershipRouting and Handoff eligibility plus allowed agent revisions
010Operational streamTransactional Room-scoped transition stream
011Projection checkpointsDurable projector high-water positions
012Approval expiry/eventsTerminal approval deadlines and full bounded Room-event payloads in the operational stream
013Agent governanceSuspended versioned configuration, atomic head/journal CAS and immutable audit history
014Agent inceptionsImmutable intake/assessments, governance-fenced CAS and assessment lineage
015Attention signalsImmutable definitions/references and atomic bounded observation/wakeup state
016Governed executionActivation status, immutable limits/task bindings, cumulative budgets and effect receipts
017Purpose missionsGoverned mission envelopes, immutable history, plan ownership and run-effect evidence lookup
018Governed continuityParent/child consent, immutable receipts and ancestral budget enforcement
019AgentPlat PlannerRoom Planner state, revision history and durable call-result receipts

Before upgrading

  1. Take and restore-test a database backup.
  2. Stop application processes that can run an older schema-dependent worker.
  3. Build or install one coordinated AgentPlat package version; do not mix versions of @agentplat/rooms, @agentplat/rooms-api and @agentplat/rooms-postgres.
  4. Use the same explicit schema for each adapter and its migration runner. Rooms and workflows may share a schema with distinct application ledgers; the optional artifacts adapter must use a separate schema.
  5. Check migration status and investigate checksum drift before proceeding.

Apply

export AGENTPLAT_DB_SCHEMA=agentplat_rooms
pnpm --filter @agentplat/rooms-postgres migrate
pnpm --filter @agentplat/rooms-postgres migrate:status

The runner serializes migration with a schema/application advisory lock. A failed migration transaction does not advance the recorded schema version. Re-running migrate is the supported recovery path after correcting the underlying failure.

Application rollout

  1. Deploy the coordinated package version after migration 018 is present when adopting purpose governance. Existing instruction-only data is preserved by the additive upgrade.
  2. Start only one worker cohort for each coordination scope during the rollout; revision fencing still prevents stale workers from committing.
  3. Confirm that new messages produce both a Room domain event and coordination state in the same transaction.
  4. Confirm operational stream growth and projection checkpoint advancement.
  5. Run the reference end-to-end and restart-recovery scenarios against a disposable database before promoting the deployment.

Rollback and compatibility

Prefer a forward fix. Down migrations are destructive and the CLI requires the observed version, the exact confirmation string and explicit data-loss opt-in. Restore from the tested backup if an application rollback requires state that a down migration would remove.

Older application versions do not understand the new operational projections. Do not run an older worker concurrently with a new worker merely because the base Room tables remain readable. Database state stays authoritative; Temporal, SSE clients and external work-management systems are not rollback sources.

Migration 018 — governed continuity

Adds current parent/child consent links and immutable operation receipts. Execution locks involved governance accounts in agent-ID order and reserves ancestor budgets atomically; native Handoff state is read under a shared row lock. Reconciliation refunds recorded accounts even after revocation. Rollback refuses any governed origin, because removing ancestry would discard enforcement state. See continuity for host wiring and bounded support.

Coordinated 1.4.0 upgrade

Pin all participating packages to 1.4.0. Planner needs Rooms through 019 and workflows through 001. Optional artifacts needs 001–002 in a separate namespace; the optional memory ledger is independent. Migration 008's typed Room plans and migration 019's AgentPlat Planner coordination state are distinct capabilities.

Drain admission and old workers before applying 019. The old adapter rejects migration versions absent from its packaged SQL, so turning Planner off does not make an old application compatible with the new ledger. Do not overlap old and new worker cohorts. After 019, recover with a compatible application image; do not automatically restore the old adapter or erase ledger rows.

Provision agentplat_rooms and agentplat_artifacts with the intended app role before running this example. Save as migrate-1.4.mjs; it uses application credentials and verified TLS. Use a disposable database for rehearsal, then the approved database during the authorized deployment window.

npm install pg @agentplat/rooms-postgres@1.4.0 @agentplat/workflows-postgres@1.4.0 @agentplat/artifacts-postgres@1.4.0
# Supply PGHOST, PGDATABASE, PGUSER, PGPASSWORD and PGSSLCA through your secret mechanism.
node migrate-1.4.mjs --status
node migrate-1.4.mjs --apply
node migrate-1.4.mjs --status
import pg from 'pg';
import { readFileSync } from 'node:fs';
import * as rooms from '@agentplat/rooms-postgres';
import * as workflows from '@agentplat/workflows-postgres';
import * as artifacts from '@agentplat/artifacts-postgres';
 
for (const key of ['PGHOST', 'PGDATABASE', 'PGUSER', 'PGPASSWORD', 'PGSSLCA']) {
  if (!process.env[key]) throw new Error(`Missing ${key}`);
}
const roomSchema = 'agentplat_rooms';
const artifactSchema = 'agentplat_artifacts';
if (roomSchema === artifactSchema) throw new Error('Artifacts requires a separate schema');
const pool = new pg.Pool({
  host: process.env.PGHOST,
  port: Number(process.env.PGPORT || 5432),
  database: process.env.PGDATABASE,
  user: process.env.PGUSER,
  password: process.env.PGPASSWORD,
  ssl: { ca: readFileSync(process.env.PGSSLCA, 'utf8'), rejectUnauthorized: true },
  max: 1,
});
const adapters = [
  ['rooms', rooms, roomSchema, 19],
  ['workflows', workflows, roomSchema, 1],
  ['artifacts', artifacts, artifactSchema, 2],
];
try {
  const apply = process.argv.includes('--apply');
  if (apply) {
    // Inspect every ledger first; reject checksum/version drift before any write.
    for (const [, adapter, schema] of adapters)
      await adapter.getMigrationStatus(pool, { schema });
  }
  for (const [name, adapter, schema, expected] of adapters) {
    if (apply) await adapter.runMigrations(pool, { schema, createSchema: false });
    const status = await adapter.getMigrationStatus(pool, { schema });
    console.log(name, JSON.stringify(status));
    if (apply && (status.currentVersion !== expected || status.pendingVersions.length))
      throw new Error(`Incomplete migration: ${name}`);
  }
} finally {
  await pool.end();
}

Apply in the listed order and require all three statuses to match before starting the new app. Construction of stores and health checks must not apply migrations. Fail readiness closed if any required ledger is missing, pending or inconsistent. Each adapter commits its own migrations; this is not one atomic transaction across all three ledgers. A failure requires inspection and a forward repair before resuming consumers.

Rehearse against a restored non-production backup and verify both old records and restart recovery. A synthetic fixture is bounded evidence, not a production data restore rehearsal. Keep a reviewed backup/restore plan; destructive down migrations are not an ordinary image rollback.