diff --git a/pm-stack/SHARED-SCHEMA-MAP.md b/pm-stack/SHARED-SCHEMA-MAP.md index a1771bf377..c7f751f901 100644 --- a/pm-stack/SHARED-SCHEMA-MAP.md +++ b/pm-stack/SHARED-SCHEMA-MAP.md @@ -40,6 +40,16 @@ service's current source of truth and native restore path. | Supabase `alerts.incidents`, `alerts.incident_events`, `alerts.push_subscriptions`, `alerts.notification_sends` ([store and writes](aggregator/src/alerts.ts#L275-L310), [incident mutations](aggregator/src/alerts.ts#L340-L363), [send ledger](aggregator/src/alerts.ts#L448-L460); [schema/location](aggregator/README.md#L299-L310)) | aggregator alerts service | No; acknowledgement state, subscriptions, and delivery history are writable durable records | `agg_` alerts; `incident_events` maps to `shared_events` | | Drill state under `~/.local/state/pm-drills/` ([default state path](aggregator/scripts/kill-collector-drill.sh#L41-L49)) | laptop-only aggregator drill script | Yes; run results/locks/incident flags are operational drill artifacts | `agg_` operational, or omit from shared tables as ephemeral | +#### First action/event column contract (#6103) + +The first Move 1 store group is now specified by the versioned +[action/event schema contract](shared-schema/README.md): `public.agg_actions` +owns the aggregator's `actions.json` records, and `public.shared_events` +holds their cross-service outcomes. The paired up/down migration and +disposable PostgreSQL test are under `shared-schema/`. This is DDL and a +contract only; `actions.json` / `events.json` remain authoritative, with no +rows copied and no live reader or writer changed. + Read-only producer inputs (quota register/view, OpenChamber state, Cloudflare and Supabase exports, DNS/orchestration/charge/launch records) are not aggregator-owned stores: their producer remains owner and their target is diff --git a/pm-stack/SHARED-SCHEMA-MIGRATION-PLAN.md b/pm-stack/SHARED-SCHEMA-MIGRATION-PLAN.md index f81da88124..02777bba96 100644 --- a/pm-stack/SHARED-SCHEMA-MIGRATION-PLAN.md +++ b/pm-stack/SHARED-SCHEMA-MIGRATION-PLAN.md @@ -24,20 +24,18 @@ namespaced-table decision or the #3142 storage choice. ## Preconditions (not moves — must land before Move 1) -- **P0 — `pmp_links` backup legs.** The only non-rebuildable - cross-service store has no evidenced backup leg: the dashboard archive - manifest stages aggregator files and does not include `projector.db` - or a `pmp_links` export (map's "Registry backup legs" section, - verified at this branch's base). Adding a `pmp_links` export to all - three archive legs (local, R2, Drive) is a prerequisite for any - migration touching the link registry. Named follow-up: backup-leg - slice (does the export + verifies all three legs). -- **P1 — Target schema vetted.** Supabase `muse-dev2` table groups - (`agg_*`, `shared_items`, `shared_links`, `shared_comments`, - `shared_events`) created with the column contracts from the map; - projector `pmp_*` group created alongside (new libSQL home or the - existing file — location is a P1 decision, recorded in the move-2 - slice). +- **P0 — `pmp_links` backup legs (complete, PR #5315).** The dashboard + archive now stages and verifies the `pmp_links`-only SQL export on the + local, R2, and Drive legs; see the map's "Registry backup legs" section. + This remains a hard prerequisite for any move touching the link + registry, but it is no longer outstanding work. +- **P1 — Target schema vetted (partial, this slice).** The first action + group now has a column contract and reversible, locally tested DDL for + `public.agg_actions` and action outcomes in `public.shared_events` + ([contract](shared-schema/README.md)). This specifies the target but + does not apply it to `muse-dev2`. P1 remains open for the other + `agg_*` / `shared_*` groups and the projector `pmp_*` location decision + (recorded in the move-2 slice). ## Moves (ordered) @@ -49,8 +47,9 @@ feed/quota/heartbeat caches refreshable) and every other service reads aggregator output. Per store, in this order inside the move: 1. Append-only / audit stores (`actions.json` → `agg_` actions + - `shared_events` outcomes; `usage-snapshot-outbox.jsonl` drained then - moved to `shared_events`/`agg_` ingestion). + `shared_events` outcomes; the #6103 contract is the first schema-only + prerequisite, not a data move or writer cutover. `usage-snapshot-outbox.jsonl` + is drained then moved to `shared_events`/`agg_` ingestion). 2. User-authored durable stores (`comments.json` → `shared_comments`; `roadmap-annotations.json` → `agg_`; `views.json` → `agg_`; `alerts.*` incl. `incident_events` → `agg_` + `shared_events`). @@ -63,6 +62,15 @@ Rollback per store: writer points back at the file; files are retained until the move's stability window closes. Reversibility is per store, so Move 1 itself ships as a sequence of small PRs. +For the actions slice, `actions.json` and `events.json` remain the read +fallback and source of truth until a separate Move 1 execution slice +verifies DB reads. If the DB path is unavailable or parity fails, keep +serving the files and route writers back there. Before a later down +migration, export/replay any canonical DB rows needed by the file store; +the #6103 down migration refuses to drop non-empty tables. This slice +does not itself copy rows, switch readers/writers, or check #1744 +acceptance criterion 3. + ### Move 2 — Projector DB → shared groups, `pmp_links` as canonical `shared_links` source Second because the projector is disposable _except_ `pmp_links`, and diff --git a/pm-stack/shared-schema/README.md b/pm-stack/shared-schema/README.md new file mode 100644 index 0000000000..0f6c4c5aec --- /dev/null +++ b/pm-stack/shared-schema/README.md @@ -0,0 +1,124 @@ +# Shared schema v1: aggregator actions and outcomes + +Status: schema contract and local migration only. This migration has **not** +been applied to Supabase `muse-dev2`; no rows have been copied, and the +aggregator's JSON files remain authoritative. + +The target uses the `public` schema and the table-group names from +[#1744](https://github.com/developing-today/code/issues/1744): +`public.agg_actions` is owned by the PM aggregator, and +`public.shared_events` is the cross-service event record. The database is a +new backing-store target under #3142, not a change in ownership. The +aggregator remains the source of truth for actions and their outcomes. + +## `public.agg_actions` + +One row per action record from the version-1 `actions.json` envelope. IDs are +text because action IDs are application-generated strings, not UUIDs. + +| Column | Type / nullability | JSON action field | Contract | +|---|---|---|---| +| `id` | `text` primary key | `id` | Stable action identity; never reused or deleted. | +| `client_token` | `text`, nullable | `clientToken` | Per-form idempotency token. A partial unique index covers non-null values; null remains valid for legacy pre-token records. | +| `kind`, `verb` | `text`, not null | `kind`, `verb` | Kinds are `triage`, `status-request`, `session`, `preference`; the check constraint permits only the current `VERBS_BY_KIND` pairs in `../aggregator/src/actions.ts`. | +| `object_ref` | `text`, not null | `objectRef` | Non-empty object identity. | +| `target_ref`, `session_id`, `session_source` | `text`, nullable | `targetRef`, `sessionId`, `sessionSource` | Optional routing/target references. | +| `payload` | `jsonb`, not null | `payload` | Must be a JSON object; verb-specific validation stays at the application boundary. | +| `author` | `jsonb`, not null | `author` | Must contain a supported `kind`, non-empty `id`, and non-empty `label`. This is self-asserted authorship, **not authenticated identity**. | +| `created_at` | `timestamptz`, not null | `createdAt` | Creation time; no `updated_at` field exists in the source contract. | +| `state` | `text`, not null, default `new` | `state` | Check-constrained to `new`, `applied`, `rejected`, `superseded`. A result timestamp is recorded in `applied_at` for applied and consumer-rejected transitions; a check constraint enforces this (`applied` requires `applied_at`, `new` forbids it, `rejected` requires it unless the row is a rejected duplicate — `ActionsStore.add()` creates duplicate attempts directly in state `rejected` with `duplicateOf`/`resultNote` and no consumer timestamp, and those records must import losslessly). | +| `applied_at`, `applied_by_run`, `result_note` | `timestamptz`, `text`, `text`, nullable | `appliedAt`, `appliedByRun`, `resultNote` | First consumer result time, run ID, and optional explanation. | +| `supersedes_action_id`, `duplicate_of_action_id` | `text`, nullable | `supersedes`, `duplicateOf` | Optional self-references with restrictive foreign keys. History is superseded/rejected, never deleted. | + +The primary key, allowed kind/verb/state checks, JSON object checks, and +partial unique `client_token` index are database constraints. The consume-once +rule remains a transactional writer contract: a future result writer must +update only `WHERE state = 'new'` and append its outcome in the same database +transaction. The schema migration does not change that writer. + +## `public.shared_events` + +This table preserves the aggregator's v2 audit-event fields and adds a +structured action link for DB-authored action outcomes. `id` remains the +event's independent stable text ID; it is not the action ID. + +| Column | Type / nullability | Event field | Contract | +|---|---|---|---| +| `id` | `text` primary key | `id` | Stable event identity. | +| `event_at`, `ingested_at` | `timestamptz`, not null | `at`, `ingestedAt` | When the event happened and when the store accepted it; they are distinct. `ingested_at` defaults to database time. | +| `event_at_raw`, `ingested_at_raw` | `text`, nullable | `at`, `ingestedAt` (verbatim) | The exact timestamp strings the event hash was computed over (`canonicalFields` in `../aggregator/src/events.ts` hashes the literal strings). `timestamptz` normalizes spellings (`2026-11-05T03:00:00+03:00` and `2026-11-05T00:00:00Z` are the same instant but different hash inputs), so importers MUST store the original strings here and DB-authored writers MUST store the exact strings they feed the hash; without them, exported rows cannot be hash-verified against the JSON rollback path. | +| `actor`, `kind`, `ref`, `summary` | `text`, not null | same | Current stream fields. Action results use `action-applied` / `action-rejected`, run actor, the action's `objectRef`, and the current summary format. | +| `attribution`, `source` | `jsonb`, not null | same | Attribution must have a supported confidence and boolean `asserted`; source must identify its writer. Defaults preserve current unknown/unasserted attribution and `pm-stack/aggregator` source. | +| `attribution_raw`, `source_raw` | `text`, nullable | same (verbatim) | The exact JSON serializations the event hash was computed over: `canonicalFields` includes `attribution` and `source` via `JSON.stringify` of the original objects, and `jsonb` does not preserve object-key ordering, so a round-trip through `jsonb` alone cannot reproduce every accepted original event's hash. Importers MUST store the original serializations here; DB-authored writers MUST store the exact strings they feed the hash. | +| `corrects_event_id` | `text`, nullable | `corrects` | Soft reference, intentionally not a foreign key: event retention can prune the corrected record. | +| `migrated_from_version` | `smallint`, nullable | `migratedFromVersion` | If set, must be `1`. | +| `prev_hash`, `hash` | `text`, not null | same | Lowercase 64-character SHA-256 chain values. The migration validates shape; serialization and chain ordering remain a single-writer responsibility. | +| `action_id` | `text`, nullable FK to `agg_actions.id` | new DB linkage | Set for DB-authored action-result events; null is allowed for existing JSON event rows, which have no structured action ID. | +| `idempotency_key` | `text`, nullable | new DB linkage | For a DB-authored action outcome, use `action-result:`. Unique when present. Existing unlinked JSON events may leave it null. | + +An action outcome must either be unlinked (both fields null, for existing JSON +events) or have both fields set with the matching stable key. Other event kinds +may use an idempotency key without an action link. A partial unique index on +`action_id` allows at most one linked outcome per action; the key index makes +retries idempotent. The two linkage columns are nullable for compatibility +with current JSON outcomes: the +`/api/actions/result` writer currently emits a random event ID and summary but +does not pass an action ID to `recordStreamEvent`. A later DB writer must +populate both fields. This schema-only slice does not alter that behavior or +backfill the unlinked event file. Because the old outcome records cannot be +reliably joined back to actions from their summary text, a future data-move +slice must choose whether to retain those records in `events.json` or import +them as explicitly unlinked history; it must not guess the linkage. + +The action author and event actor are provenance claims, not authentication. +Current events default to `{confidence: "unknown", asserted: false}` and +`{identity: "pm-stack/aggregator"}`. Do not upgrade these to authenticated +provenance without the separate #941 trust-hardening work. + +RLS is enabled on both tables. The migration grants the Supabase +`service_role` the minimum table privileges needed by the current contracts: +actions can be read/inserted/updated but not deleted; events can be +read/inserted and pruned under the existing event-retention policy, but not +updated. No client-facing RLS policy or production database write is part of +this change. + +## Migration, fallback, and rollback + +There is no shared Postgres migration runner yet. +`migrations/20261105_0001_action_event_store.up.sql` creates only these two +tables, constraints, indexes, and grants. Its paired `.down.sql` refuses to +drop either table while it contains rows, then drops `shared_events` before +`agg_actions`. The refusal is deliberate protection against an accidental +data-loss rollback. + +For a future store move, retain `actions.json` and `events.json` as the +authoritative write and read path while DB writes are only a mirror. Enable DB +reads only after parity checks pass; on a DB outage or read-parity failure, +fall back to those files. A later writer cutover must preserve a replayable +JSON copy. If rollback happens after any DB-only writes, stop DB writes, export +and replay missing rows to JSON in action/event order, verify IDs, client +tokens, outcomes, and event hashes, then route reads and writes back to the +files. Empty the target tables only after that verification; the down +migration refuses to drop non-empty tables. No reader, writer, migration +runner, or live row is changed by this slice. + +This supplies the first column contract and reversible DDL artifact for P1 / +Move 1 (`actions.json` → `agg_actions` + action outcomes in `shared_events`). +It does **not** apply the DDL to `muse-dev2`, migrate or cut over the action +store, finish the remaining `agg_*` / `shared_*` contracts, decide the +projector's P1 location, or complete P1 / Move 1. #1744 acceptance criterion +3 remains unchecked. + +## Disposable test + +Run from the repository root: + +```sh +bash pm-stack/shared-schema/test-migration.sh +``` + +The script starts its own temporary PostgreSQL 16 container, applies the up +migration, proves key/foreign-key/check/idempotency behavior (including +legacy-null compatibility), proves the down migration refuses non-empty +tables, clears only its disposable fixtures, applies down, and verifies the +tables are gone. It does not connect to Supabase or the PM Compose database. diff --git a/pm-stack/shared-schema/migrations/20261105_0001_action_event_store.down.sql b/pm-stack/shared-schema/migrations/20261105_0001_action_event_store.down.sql new file mode 100644 index 0000000000..3220192b80 --- /dev/null +++ b/pm-stack/shared-schema/migrations/20261105_0001_action_event_store.down.sql @@ -0,0 +1,14 @@ +-- #6103 rollback guard: never discard rows during a schema rollback. +DO $$ +BEGIN + IF (to_regclass('public.shared_events') IS NOT NULL + AND EXISTS (SELECT 1 FROM public.shared_events LIMIT 1)) + OR (to_regclass('public.agg_actions') IS NOT NULL + AND EXISTS (SELECT 1 FROM public.agg_actions LIMIT 1)) THEN + RAISE EXCEPTION 'refusing to drop non-empty action/event tables; export/replay rows first'; + END IF; +END +$$; + +DROP TABLE IF EXISTS public.shared_events; +DROP TABLE IF EXISTS public.agg_actions; diff --git a/pm-stack/shared-schema/migrations/20261105_0001_action_event_store.up.sql b/pm-stack/shared-schema/migrations/20261105_0001_action_event_store.up.sql new file mode 100644 index 0000000000..8ec2b43839 --- /dev/null +++ b/pm-stack/shared-schema/migrations/20261105_0001_action_event_store.up.sql @@ -0,0 +1,140 @@ +-- #6103: first schema contract for PM aggregator actions and their outcomes. +-- Target: Supabase muse-dev2, public schema. This DDL is not applied here. + +CREATE TABLE public.agg_actions ( + id text PRIMARY KEY CHECK (btrim(id) <> ''), + client_token text CHECK (client_token IS NULL OR btrim(client_token) <> ''), + kind text NOT NULL CHECK (kind IN ('triage', 'status-request', 'session', 'preference')), + verb text NOT NULL, + object_ref text NOT NULL CHECK (btrim(object_ref) <> ''), + target_ref text, + session_id text, + session_source text, + payload jsonb NOT NULL CHECK (jsonb_typeof(payload) = 'object'), + author jsonb NOT NULL CHECK ( + jsonb_typeof(author) = 'object' + AND coalesce(author->>'kind' IN ('drew', 'muse', 'agent'), false) + AND nullif(btrim(author->>'id'), '') IS NOT NULL + AND nullif(btrim(author->>'label'), '') IS NOT NULL + ), + created_at timestamptz NOT NULL, + state text NOT NULL DEFAULT 'new' + CHECK (state IN ('new', 'applied', 'rejected', 'superseded')), + applied_at timestamptz, + applied_by_run text, + result_note text, + supersedes_action_id text REFERENCES public.agg_actions(id) ON DELETE RESTRICT, + duplicate_of_action_id text REFERENCES public.agg_actions(id) ON DELETE RESTRICT, + CONSTRAINT agg_actions_verb_for_kind_check CHECK ( + (kind = 'triage' AND verb IN ( + 'acknowledge', 'snooze', 'escalate', 'de-escalate', 'answer', 'delegate', + 'dismiss', 'approve-proposal', 'reject-proposal', 'mark-done', 'restore' + )) + OR (kind = 'status-request' AND verb = 'request-status') + OR (kind = 'session' AND verb IN ('poke', 'answer', 'stop')) + OR (kind = 'preference' AND verb IN ( + 'set-delegation-default', 'set-needs-order', 'save-view', 'rename-view', + 'delete-view', 'set-default-view' + )) + ), + CONSTRAINT agg_actions_result_timestamp_check CHECK ( + (state = 'applied' AND applied_at IS NOT NULL) + OR (state = 'rejected' + AND (applied_at IS NOT NULL OR duplicate_of_action_id IS NOT NULL)) + OR (state = 'new' AND applied_at IS NULL) + OR state = 'superseded' + ), + CONSTRAINT agg_actions_not_self_superseded_check CHECK ( + supersedes_action_id IS NULL OR supersedes_action_id <> id + ), + CONSTRAINT agg_actions_not_self_duplicate_check CHECK ( + duplicate_of_action_id IS NULL OR duplicate_of_action_id <> id + ) +); + +CREATE UNIQUE INDEX agg_actions_client_token_uq + ON public.agg_actions (client_token) + WHERE client_token IS NOT NULL; + +CREATE INDEX agg_actions_state_created_at_idx + ON public.agg_actions (state, created_at DESC); + +CREATE INDEX agg_actions_object_created_at_idx + ON public.agg_actions (object_ref, created_at DESC); + +CREATE TABLE public.shared_events ( + id text PRIMARY KEY CHECK (btrim(id) <> ''), + event_at timestamptz NOT NULL, + ingested_at timestamptz NOT NULL DEFAULT now(), + event_at_raw text CHECK (event_at_raw IS NULL OR btrim(event_at_raw) <> ''), + ingested_at_raw text CHECK (ingested_at_raw IS NULL OR btrim(ingested_at_raw) <> ''), + actor text NOT NULL CHECK (btrim(actor) <> ''), + kind text NOT NULL CHECK (btrim(kind) <> ''), + ref text NOT NULL CHECK (btrim(ref) <> ''), + summary text NOT NULL, + attribution jsonb NOT NULL DEFAULT '{"confidence":"unknown","asserted":false}'::jsonb + CHECK ( + jsonb_typeof(attribution) = 'object' + AND coalesce(attribution->>'confidence' IN ('authenticated', 'pre-sso', 'unknown'), false) + AND coalesce(jsonb_typeof(attribution->'asserted') = 'boolean', false) + AND (attribution->>'confidence' <> 'authenticated' OR attribution->'asserted' = 'true'::jsonb) + ), + source jsonb NOT NULL DEFAULT '{"identity":"pm-stack/aggregator"}'::jsonb + CHECK ( + jsonb_typeof(source) = 'object' + AND nullif(btrim(source->>'identity'), '') IS NOT NULL + ), + attribution_raw text CHECK ( + attribution_raw IS NULL + OR jsonb_typeof(attribution_raw::jsonb) = 'object' + ), + source_raw text CHECK ( + source_raw IS NULL + OR jsonb_typeof(source_raw::jsonb) = 'object' + ), + corrects_event_id text, + migrated_from_version smallint CHECK (migrated_from_version IS NULL OR migrated_from_version = 1), + prev_hash text NOT NULL CHECK (prev_hash ~ '^[0-9a-f]{64}$'), + hash text NOT NULL CHECK (hash ~ '^[0-9a-f]{64}$'), + action_id text REFERENCES public.agg_actions(id) ON DELETE RESTRICT, + idempotency_key text CHECK (idempotency_key IS NULL OR btrim(idempotency_key) <> ''), + CONSTRAINT shared_events_action_link_check CHECK ( + ( + kind IN ('action-applied', 'action-rejected') + AND action_id IS NULL + AND idempotency_key IS NULL + ) + OR ( + kind IN ('action-applied', 'action-rejected') + AND action_id IS NOT NULL + AND idempotency_key IS NOT NULL + AND idempotency_key = 'action-result:' || action_id + ) + OR (kind NOT IN ('action-applied', 'action-rejected') AND action_id IS NULL) + ) +); + +CREATE UNIQUE INDEX shared_events_idempotency_key_uq + ON public.shared_events (idempotency_key) + WHERE idempotency_key IS NOT NULL; + +CREATE UNIQUE INDEX shared_events_action_outcome_uq + ON public.shared_events (action_id) + WHERE action_id IS NOT NULL; + +CREATE INDEX shared_events_event_at_idx + ON public.shared_events (event_at DESC); + +CREATE INDEX shared_events_kind_ref_event_at_idx + ON public.shared_events (kind, ref, event_at DESC); + +ALTER TABLE public.agg_actions ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.shared_events ENABLE ROW LEVEL SECURITY; + +GRANT SELECT, INSERT, UPDATE ON public.agg_actions TO service_role; +GRANT SELECT, INSERT, DELETE ON public.shared_events TO service_role; + +COMMENT ON TABLE public.agg_actions IS + 'Aggregator-owned action records; JSON remains authoritative until a separate Move 1 cutover.'; +COMMENT ON TABLE public.shared_events IS + 'Shared audit events; action-result rows link to agg_actions when written by the DB-backed store.'; diff --git a/pm-stack/shared-schema/test-migration.sh b/pm-stack/shared-schema/test-migration.sh new file mode 100755 index 0000000000..d1a39f9bb1 --- /dev/null +++ b/pm-stack/shared-schema/test-migration.sh @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +set -euo pipefail + +schema_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +migrations="$schema_dir/migrations" +up="$migrations/20261105_0001_action_event_store.up.sql" +down="$migrations/20261105_0001_action_event_store.down.sql" +container="pm-action-schema-test-$$" + +if ! command -v docker >/dev/null 2>&1; then + echo "docker is required for the disposable PostgreSQL migration test" >&2 + exit 1 +fi +if docker container inspect "$container" >/dev/null 2>&1; then + echo "refusing to reuse existing container: $container" >&2 + exit 1 +fi + +cleanup() { + docker rm -f "$container" >/dev/null 2>&1 || true +} +trap cleanup EXIT + +docker run --detach --rm \ + --name "$container" \ + --env POSTGRES_HOST_AUTH_METHOD=trust \ + --env POSTGRES_DB=pm_actions_test \ + postgres:16-alpine >/dev/null + +ready=false +for _ in $(seq 1 60); do + if docker exec "$container" psql -X -qAt -U postgres -d pm_actions_test -c 'SELECT 1' >/dev/null 2>&1; then + ready=true + break + fi + sleep 1 +done +if [[ "$ready" != true ]]; then + echo "disposable PostgreSQL did not become ready" >&2 + exit 1 +fi + +psql_test() { + docker exec -i "$container" psql -X -v ON_ERROR_STOP=1 -U postgres -d pm_actions_test "$@" +} + +# Supabase's service_role carries BYPASSRLS; model that so the test proves +# the role can actually operate under the RLS model, not just hold grants. +psql_test -c 'CREATE ROLE service_role BYPASSRLS LOGIN;' +psql_test < "$up" + +# A pre-token action is valid, as are modern actions and the source's JSON +# object payload/author contracts. +psql_test -c "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at) + VALUES ('da-legacy', 'triage', 'acknowledge', 'orch:legacy', '{}', + '{\"kind\":\"drew\",\"id\":\"drew\",\"label\":\"Drew\"}', now());" +psql_test -c "INSERT INTO public.agg_actions + (id, client_token, kind, verb, object_ref, payload, author, created_at) + VALUES ('da-current', 'ct-current-12345678', 'triage', 'acknowledge', + 'orch:item-1', '{}', + '{\"kind\":\"agent\",\"id\":\"session-1\",\"label\":\"agent\"}', now());" +psql_test -c "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at) + VALUES ('da-legacy-2', 'triage', 'acknowledge', 'orch:legacy-2', '{}', + '{\"kind\":\"drew\",\"id\":\"drew\",\"label\":\"Drew\"}', now());" + +privileges="$(psql_test -Atc "SELECT concat( + (SELECT relrowsecurity::text FROM pg_class WHERE oid = 'public.agg_actions'::regclass), ':', + (SELECT relrowsecurity::text FROM pg_class WHERE oid = 'public.shared_events'::regclass), ':', + has_table_privilege('service_role', 'public.agg_actions', 'UPDATE')::text, ':', + has_table_privilege('service_role', 'public.agg_actions', 'DELETE')::text, ':', + has_table_privilege('service_role', 'public.shared_events', 'DELETE')::text)")" +if [[ "$privileges" != "true:true:true:false:true" ]]; then + echo "unexpected RLS/service_role privileges: $privileges" >&2 + exit 1 +fi +echo "ok - RLS and service_role privileges" + +# The service_role must actually be able to operate under RLS (Supabase's +# service_role carries BYPASSRLS); a role that only holds grants but is +# blocked by RLS would pass the privilege probe above while being +# unusable in production. +svc_hash="$(printf '%064d' 7)" +docker exec -i "$container" psql -X -v ON_ERROR_STOP=1 -U service_role -d pm_actions_test -c "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash) + VALUES ('event-service-role', now(), 'run-svc', 'comment', 'orch:item-1', + 'service_role write probe', '$svc_hash', '$svc_hash');" +svc_seen="$(docker exec -i "$container" psql -X -qAt -v ON_ERROR_STOP=1 -U service_role -d pm_actions_test -c "SELECT count(*) FROM public.shared_events WHERE id = 'event-service-role'")" +if [[ "$svc_seen" != "1" ]]; then + echo "service_role could not read back its own event row under RLS" >&2 + exit 1 +fi +docker exec -i "$container" psql -X -v ON_ERROR_STOP=1 -U service_role -d pm_actions_test -c "DELETE FROM public.shared_events WHERE id = 'event-service-role';" +echo "ok - service_role can write and read under RLS" + +expect_rejected() { + local label="$1" + local sql="$2" + if psql_test -c "$sql" >/dev/null 2>&1; then + echo "expected database constraint rejection: $label" >&2 + exit 1 + fi + echo "ok - rejected $label" +} + +expect_rejected "duplicate client token" "INSERT INTO public.agg_actions + (id, client_token, kind, verb, object_ref, payload, author, created_at) + VALUES ('da-duplicate-token', 'ct-current-12345678', 'triage', 'acknowledge', + 'orch:item-2', '{}', + '{\"kind\":\"drew\",\"id\":\"drew\",\"label\":\"Drew\"}', now())" +expect_rejected "invalid action state" "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at, state) + VALUES ('da-invalid-state', 'triage', 'acknowledge', 'orch:item-3', '{}', + '{\"kind\":\"drew\",\"id\":\"drew\",\"label\":\"Drew\"}', now(), 'pending')" +expect_rejected "invalid kind/verb pair" "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at) + VALUES ('da-invalid-verb', 'status-request', 'acknowledge', 'orch:item-4', '{}', + '{\"kind\":\"drew\",\"id\":\"drew\",\"label\":\"Drew\"}', now())" +expect_rejected "non-object action payload" "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at) + VALUES ('da-invalid-payload', 'triage', 'acknowledge', 'orch:item-5', '[]', + '{\"kind\":\"drew\",\"id\":\"drew\",\"label\":\"Drew\"}', now())" +expect_rejected "incomplete action author" "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at) + VALUES ('da-invalid-author', 'triage', 'acknowledge', 'orch:item-6', '{}', + '{\"kind\":\"drew\",\"id\":\"drew\"}', now())" + +zero_hash="$(printf '%064d' 0)" +one_hash="$(printf '%064d' 1)" +psql_test -c "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash, action_id, idempotency_key) + VALUES ('event-current', now(), 'run-1', 'action-applied', 'orch:item-1', + 'triage/acknowledge applied by run-1', '$zero_hash', '$one_hash', + 'da-current', 'action-result:da-current');" + +# Existing JSON action-result events do not carry an action ID. Both new DB +# linkage fields may stay null when such legacy events are replayed. +psql_test -c "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash) + VALUES ('event-legacy', now(), 'run-old', 'action-rejected', 'orch:legacy', + 'triage/acknowledge rejected by run-old', '$zero_hash', '$one_hash');" + +expect_rejected "orphan action link" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash, action_id, idempotency_key) + VALUES ('event-orphan', now(), 'run-2', 'action-applied', 'orch:item-1', 'outcome', + '$zero_hash', '$one_hash', 'missing-action', 'action-result:missing-action')" +expect_rejected "action link without idempotency key" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash, action_id) + VALUES ('event-no-key', now(), 'run-2', 'action-applied', 'orch:item-1', 'outcome', + '$zero_hash', '$one_hash', 'da-current')" +expect_rejected "action link with mismatched idempotency key" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash, action_id, idempotency_key) + VALUES ('event-wrong-key', now(), 'run-2', 'action-applied', 'orch:item-1', 'outcome', + '$zero_hash', '$one_hash', 'da-current', 'action-result:another-action')" +expect_rejected "duplicate outcome idempotency key" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash, action_id, idempotency_key) + VALUES ('event-retry', now(), 'run-1', 'action-applied', 'orch:item-1', 'retry', + '$zero_hash', '$one_hash', 'da-current', 'action-result:da-current')" +expect_rejected "action link on non-outcome event" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash, action_id, idempotency_key) + VALUES ('event-wrong-kind', now(), 'run-1', 'comment', 'orch:item-1', 'wrong kind', + '$zero_hash', '$one_hash', 'da-current', 'action-result:da-current')" +expect_rejected "malformed hash" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash) + VALUES ('event-bad-hash', now(), 'run-old', 'comment', 'orch:item-1', 'bad hash', + 'not-a-hash', '$one_hash')" +expect_rejected "authenticated but unasserted attribution" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, attribution, prev_hash, hash) + VALUES ('event-bad-attribution', now(), 'run-old', 'comment', 'orch:item-1', 'bad attribution', + '{\"confidence\":\"authenticated\",\"asserted\":false}', '$zero_hash', '$one_hash')" +expect_rejected "attribution missing the asserted flag" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, attribution, prev_hash, hash) + VALUES ('event-missing-asserted', now(), 'run-old', 'comment', 'orch:item-1', 'missing asserted', + '{\"confidence\":\"authenticated\"}', '$zero_hash', '$one_hash')" +expect_rejected "applied action without a result timestamp" "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at, state) + VALUES ('da-applied-no-ts', 'triage', 'acknowledge', 'orch:item-7', '{}', + '{\"kind\":\"drew\",\"id\":\"drew\",\"label\":\"Drew\"}', now(), 'applied')" +expect_rejected "rejected non-duplicate action without a result timestamp" "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at, state) + VALUES ('da-rejected-no-ts', 'triage', 'acknowledge', 'orch:item-8', '{}', + '{\"kind\":\"drew\",\"id\":\"drew\",\"label\":\"Drew\"}', now(), 'rejected')" +# ActionsStore.add() creates duplicate attempts directly in state rejected +# with duplicateOf and a result note but no consumer timestamp; those rows +# are valid audit history and must import losslessly. +psql_test -c "INSERT INTO public.agg_actions + (id, kind, verb, object_ref, payload, author, created_at, state, duplicate_of_action_id, result_note) + VALUES ('da-duplicate-rejected', 'triage', 'acknowledge', 'orch:item-1', '{}', + '{\"kind\":\"agent\",\"id\":\"session-2\",\"label\":\"agent\"}', now(), 'rejected', + 'da-current', 'Duplicate answer; existing action da-current is new.');" +echo "ok - rejected duplicate without a consumer timestamp is accepted" +expect_rejected "empty idempotency key" "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, prev_hash, hash, idempotency_key) + VALUES ('event-empty-key', now(), 'run-old', 'comment', 'orch:item-1', 'empty key', + '$zero_hash', '$one_hash', '')" + +# The raw timestamp strings are the hash inputs: an offset-spelled original +# must round-trip verbatim even though timestamptz normalizes the instant. +psql_test -c "INSERT INTO public.shared_events + (id, event_at, ingested_at, event_at_raw, ingested_at_raw, actor, kind, ref, summary, prev_hash, hash) + VALUES ('event-raw-ts', '2026-11-05T03:00:00+03:00', '2026-11-05T03:00:01+03:00', + '2026-11-05T03:00:00+03:00', '2026-11-05T03:00:01+03:00', + 'run-old', 'comment', 'orch:item-1', 'raw timestamp preservation', + '$zero_hash', '$one_hash');" +raw_seen="$(psql_test -Atc "SELECT event_at_raw || '|' || ingested_at_raw || '|' || (event_at AT TIME ZONE 'UTC')::text FROM public.shared_events WHERE id = 'event-raw-ts'")" +if [[ "$raw_seen" != "2026-11-05T03:00:00+03:00|2026-11-05T03:00:01+03:00|2026-11-05 00:00:00" ]]; then + echo "raw timestamp strings did not round-trip: $raw_seen" >&2 + exit 1 +fi +echo "ok - raw timestamp strings preserved alongside normalized timestamptz" + +# The raw JSON serializations are hash inputs too: canonicalFields hashes +# JSON.stringify of the original attribution/source objects, and jsonb +# reorders object keys (shortest first), so only the verbatim text +# reproduces the original hash input. +psql_test -c "INSERT INTO public.shared_events + (id, event_at, actor, kind, ref, summary, attribution, attribution_raw, source, source_raw, prev_hash, hash) + VALUES ('event-raw-json', now(), 'run-old', 'comment', 'orch:item-1', 'raw json preservation', + '{\"confidence\":\"unknown\",\"asserted\":false}', + '{\"confidence\":\"unknown\",\"asserted\":false}', + '{\"identity\":\"pm-stack/aggregator\",\"channel\":\"test\"}', + '{\"identity\":\"pm-stack/aggregator\",\"channel\":\"test\"}', + '$zero_hash', '$one_hash');" +raw_json_seen="$(psql_test -Atc "SELECT attribution_raw || '|' || source_raw FROM public.shared_events WHERE id = 'event-raw-json'")" +if [[ "$raw_json_seen" != "{\"confidence\":\"unknown\",\"asserted\":false}|{\"identity\":\"pm-stack/aggregator\",\"channel\":\"test\"}" ]]; then + echo "raw JSON serializations did not round-trip: $raw_json_seen" >&2 + exit 1 +fi +echo "ok - raw JSON serializations preserved alongside jsonb" + +if psql_test < "$down" >/dev/null 2>&1; then + echo "down migration should refuse populated tables" >&2 + exit 1 +fi +echo "ok - down migration protects non-empty tables" + +psql_test -c 'DELETE FROM public.shared_events; DELETE FROM public.agg_actions;' +psql_test < "$down" +remaining="$(psql_test -Atc "SELECT (to_regclass('public.agg_actions') IS NULL AND to_regclass('public.shared_events') IS NULL)::text")" +if [[ "$remaining" != true ]]; then + echo "down migration left schema objects behind" >&2 + exit 1 +fi + +echo "ok - migration constraints and rollback verified on disposable PostgreSQL 16"