Audit admission and durable recovery
This implements the foundation slice of #27, under epic #12, ADR-0005 and ADR-0006. It consumes unchanged arbi.audit/1.0 semantics. The SQLite library supports edge/pod local reuse; app-specific HTTP, enrollment verification, PostgreSQL, migration and notification adapters belong to apps/arbi-dashboard.
Transactional cloud admission
PostgresAuditStore.admit requires a trusted cloud intent plus its independently authorized allow record and explicit trusted bindings. Its single checked-out PostgreSQL transaction appends both records and the immutable outbox row before returning. Staging sets transaction-local synchronous_commit=on and refuses a server reporting fsync=off; a pool/session preference cannot silently weaken durable receipt. Staging returns a provisional receipt; durable: true is added only after the enclosing COMMIT succeeds. Any database failure rolls all three and the chain head back. No external delivery runs inside admission. The outbox represents a notification of committed intent, never an actuator command or permission. Actual command/jobs and lifecycle instrumentation remain #28 and #46.
deliver(realm, siteId, send, limit) reads at most 64 undelivered notifications and invokes a trusted server transport. The destination must deduplicate the immutable intent ID. A delivery receipt is appended only after the callback succeeds. Process death after remote delivery can repeat that notification; it does not create another logical intent or delete history. A new store/process can recover pending rows after a crash immediately after admission. A dispatcher must not turn stale authorization into execution permission; local command validity, current permissions, fencing and safety gates still apply independently.
Migration 0003-audit.sql is additive after unchanged 0001 enrollment and 0002 media. Original audit rows, source times, IDs and transaction behavior remain intact. arbi_audit_history unions original and new records for protected server joins; it is not a search/export endpoint. Corrections add a new causal record. Original enrollment/media history is protected by append-only triggers without backfill or invented receipt timestamps. Their existing transactional seams retain their ownership; this change does not orchestrate media, jobs or telemetry. The separately applied query/retention migration later adds a conservative receipt index and a privileged, receipted payload-retirement exception; it preserves the hashes and makes retired payloads explicit.
Device ingestion boundary
The Node HTTP endpoint is POST /api/sites/:siteId/audit/ingest. It is fail-closed until composed with createAuditServer, a migrated database and a protected EvidenceResolver. There is no fixture identity, static public credential or deployment default. Current enrollment supports simulation in test/preview only; production/hardware cloud ingestion remains disabled until enrollment itself acquires separately accepted authority. This gate does not disable local safety stopping.
The transport envelope is arbi.audit-upload/1.0 with realm, site/device/credential IDs, current uploader identity, fresh issue/expiry times, one immutable audit event and an Ed25519 signature. It reuses the enrollment arbi-device-proof/1.0 canonical signing primitive with an independently named envelope version. Sign all fields except signature. Each retry wraps the same event in a freshly signed envelope with a maximum 60-second lifetime. Event source time can be arbitrarily old; fresh transport authorization never rewrites it. Audit event IDs and boot/session sequences, rather than envelope retry numbers, own deduplication.
Only a currently active enrolled edge credential and exact current uploader epoch may upload. The transaction locks the installation registry until receipt COMMIT, serializing revocation, replacement and rotation. Current credentials must remain valid on every replay. Browser Origin/Cookie/Authorization requests are rejected; browser identity or engineering presentation cannot submit device evidence. Unknown keys, oversized bodies/events and raw errors are rejected without echoing input. The HTTP body is capped at 12,288 bytes and the unchanged event at 8,192 bytes.
The resolver receives only an event ID and independently authenticated inventory/uploader. It must load protected admission/command/local outcome evidence and approved redacted references, verify original actor, action/evidence, logical resource, command/correlation/causal links, target epoch and record authenticity, then return TrustedBinding. It must never derive that binding by spreading or trusting the submitted event. No full command orchestration is implemented here, so an absent resolver/record denies ingestion. Child records additionally join an existing root intent in protected history using correlateAuditEvent. Tests use an explicit synthetic protected evidence map, never a runtime default.
The binding source must be the active edge itself or its active enrolled Pico/pod child, with exact role/module and a known current/retired source epoch. Pico and pod credentials stay local; they receive no direct cloud authority. An edge gateway can relay child evidence only after the resolver independently authenticates the referenced local module record. A new current edge boot can replay approved evidence from retained older epochs; revoked/replaced devices and forgotten/unknown epochs fail closed.
admitAuditEvent compares all trusted fields and stamps receipt time with the cloud receiver identity. PostgreSQL stores original source UTC, monotonic time and uncertainty without normalization. A receipt returns durable, original event ID/content hash and the first committed ingest time only after COMMIT. An identical replay returns the same receipt even through another cloud process. Changed content under an existing ID, or another ID at the same scoped source sequence, conflicts without inserting evidence. The sender may compact only matching durable acknowledgements received over an authenticated channel.
Gaps, clocks and integrity
Emitters start audit sequence at 1 in this slice; the accepted uint64 counter, including 0, remains compatible. Sequence is decimal uint64 scoped by realm/mode/site/module/device/boot/session. It is not a database commit cursor. Missing-prefix diagnostics assume the conventional first sequence 1; a received sequence 0 is preserved. Cloud per-site ordinals are allocated under a row lock in the admission transaction, not via an independent SQL sequence; aborted admissions do not advance the checkpoint. Reordered receipt fills current sequence gaps while preserving earlier immutable gap observations. arbi_audit_evidence records the first 32 missing ranges plus truncation, source monotonic regressions, disjoint source/receipt uncertainty intervals, unsynchronized clocks and observations of another boot. These diagnose incomplete evidence; they imply no command success, measurement, exact global order or watched duration. No trailing gap can be detected until a later sequence/checkpoint advertises it.
Cloud hashes chain the complete admitted record including receipt time. Local hashes chain original immutable source records, retaining an acknowledged prefix anchor when compacting. Verification recomputes event hashes, ordinals, links and the current checkpoint; edits/deletions/reordering and mismatched tails are detected. Persist checkpoints outside the database in independently controlled, versioned append storage or signed offline records with revision/site/time provenance, and compare against those records during inspection. Hashes are tamper evidence only while an independent trusted checkpoint survives. An administrator who rewrites both rows and checkpoints, drops triggers, alters backups or compromises the emitter/resolver can forge a consistent chain. These hashes are neither device signatures nor proof of physical truth.
Roles, backup and operational limits
Use separate operator migration ownership, server append credentials and read-only inspection/backup credentials. Browser/device clients never connect directly to PostgreSQL. After operator migration, the server role needs schema USAGE; SELECT/INSERT on immutable audit/evidence/outbox/delivery tables; SELECT/INSERT/UPDATE on the mutable head; SELECT on history; and the existing narrowly scoped enrollment/media/resolver permissions. It must have no table/schema ownership, superuser, role administration, trigger control or UPDATE/DELETE/TRUNCATE grants on historical records. Grant history reads only to protected server code that applies current site/resource permissions; the view is not public. For example, with an operator-provisioned role:
GRANT USAGE ON SCHEMA public TO arbi_server;
GRANT SELECT, INSERT ON arbi_audit_events, arbi_audit_evidence,
arbi_audit_outbox, arbi_audit_deliveries TO arbi_server;
GRANT SELECT, INSERT, UPDATE ON arbi_audit_heads TO arbi_server;
GRANT SELECT ON arbi_audit_history TO arbi_server;
GRANT SELECT, INSERT ON arbi_device_audit, arbi_media_audit,
arbi_device_lifecycle TO arbi_server;The migration revokes PUBLIC access and adds UPDATE/DELETE/TRUNCATE rejection triggers to all historical audit/lifecycle/outbox/delivery tables. Tests exercise a non-owner app role and owner DML rejection. Operators can disable those safeguards, so privileges and independent checkpoints remain part of the threat model. Corrections append records; retention/export policy is separate #36.
Use provider PostgreSQL snapshots/PITR and independently retained immutable exports/checkpoints, access-controlled and encrypted with restore drills. A restore must verify the chain, preserved enrollment/media history and outbox delivery reconciliation before resuming work; compare against independently saved checkpoints to detect rollback. For local backup, stop/close the spool under supervision before copying its database to protected storage; do not copy a live database without its journal or a supported consistent SQLite backup. Acknowledged records live in cloud history; a restored older spool may replay and must receive identical cloud receipts. Schedule and test backup/restore outside this source slice; no live provider backup or retention configuration is claimed.
SQLite limits event count, payload bytes and page allocation without evicting unreceived rows. Full spool/storage blocks new discretionary actions because intent cannot commit. Direct safety stop runs first, records best-effort afterwards and exposes bounded persistent or volatile loss/degradation counters. Total storage failure can prevent persistence of even a loss counter; later source sequence/boot gaps and independently exported health evidence bound that limitation. See the local API. An independent safety path must not share cloud/audit availability as an admission requirement.
The implementation follows Node's SQLite API, SQLite synchronization semantics and PostgreSQL privilege semantics. FULL fsync/process restart tests cannot prove storage firmware honors flushes during real power loss. Power-cut tests on selected storage/filesystem, bench/HIL, installed operation, backup restoration, provider integration and qualified physical review remain separate gates. Parked never implies safe update/restraint, recording #68 stays disabled, and audit receipts never imply actuator or physical measurement confirmation.
Committed verification
Run pnpm --filter @arbi/audit test for actual temporary SQLite process crash/unfinished-transaction recovery, prefix acknowledgements, bounded spool, actual SQLITE_FULL, independent stop-first callbacks and tamper checks. Run pnpm --filter @arbi/dashboard test:postgres with local pg_config, initdb and pg_ctl: it owns a fresh temporary socket-only PostgreSQL cluster, preserves independent enrollment/media suites and isolates audit in its own database. No provider credentials or existing database are used.
Native PostgreSQL tests kill an admitted cloud process before notification, restart a new store, replay through real SQLite after lost receipt, concurrently deduplicate admissions, reject conflicting IDs/sequences, reconcile reordering/missing ranges, detect skew/regression/new boots, verify old-epoch replay and current revocation, reject arbitrary body authority, roll back audit/outbox/head failures, enforce non-owner append-only roles, and detect privileged row tampering. HTTP tests reject browser authority, oversized requests and unconfigured runtime. This is reproducible source/host evidence, not provider deployment or physical acceptance. End-to-end completeness remains #64.