<!-- SOLIDIVISM · part 26 -->
ive.*


===== FILE: public/solidivism/PHASE1-FINAL-REVIEW.md =====
# PHASE 1 FINAL ENGINEERING REVIEW
## Seven Safeguards — Implementation Specification

**Requested by:** GPT-6 Final Engineering Review
**Date:** October 8, 2026
**Status:** SPECIFICATION ONLY — No live system modification. Awaiting authorization.

---

## ENVIRONMENT CONFIRMATION

Read-only inspection confirms the deployment environment supports the proposed architecture:

- PostgreSQL 18.6 installed and active
- `epistles` database exists
- Node `pg` driver (^8.13.1) already in dependencies
- No new database installation required
- No new Node dependencies required
- No server configuration changes required for Phase 1

Phase 1 requires only: new tables, a restricted database role, and application code. All within existing infrastructure.

---

## SAFEGUARD 1: POSTGRESQL AS AUTHORITATIVE LEDGER

### Architecture

```
┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│  3D World    │────▶│  Epistemology │────▶│  PostgreSQL  │
│  (browser)   │ obs │  (browser)    │ POST│  (authoritative)│
└──────────────┘     └──────────────┘     └──────────────┘
       │                    │                     │
       │                    ▼                     │
       │            ┌──────────────┐              │
       │            │ localStorage │              │
       │            │ (write cache │              │
       │            │  ONLY)       │              │
       │            └──────────────┘              │
       │                    │                     │
       │                    │ sync                │
       └────────────────────┴─────────────────────┘
                     (on reconnect)
```

### Authority Hierarchy

1. **PostgreSQL: AUTHORITATIVE.** The historical record. If PostgreSQL and localStorage disagree, PostgreSQL wins.

2. **localStorage: WRITE CACHE ONLY.** Buffers events when offline or during POST latency. Never treated as the record. Flushed to PostgreSQL on sync. Cleared after confirmed receipt.

3. **JavaScript Maps: RUNTIME INDEX ONLY.** In-memory lookup for current session. Rebuilt from PostgreSQL on load. Discarded on page reload.

### Sync Protocol

```javascript
// Browser → Server
POST /api/solidivism/epistemology/events
Body: { events: [...], idempotencyKeys: [...] }
Response: { accepted: [...eventIds], rejected: [...], serverTime }

// Server → PostgreSQL (single transaction)
// 1. Check idempotency keys (skip duplicates)
// 2. INSERT all new events
// 3. Return accepted IDs

// Browser: on 200, remove accepted events from localStorage cache
// On failure: retain in cache, retry with backoff
```

### Startup Hydration

```javascript
// On Epistemology.init():
// 1. GET /api/solidivism/epistemology/snapshot?since=<lastSync>
// 2. Rebuild in-memory Maps from PostgreSQL data
// 3. Merge any unsynced localStorage events (mark as pending)
// 4. Begin session
```

**Rule:** The browser never trusts its own cache over the server. On conflict, server wins.

---

## SAFEGUARD 2: ENFORCED APPEND-ONLY

### Database Schema

```sql
-- Immutable event ledger
CREATE TABLE solidivism_events (
  -- Immutable identifier (generated server-side, never client-supplied)
  event_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Immutable timestamp (set by database, not application)
  recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),

  -- Client-supplied event time (may differ from recorded_at due to latency)
  event_time TIMESTAMPTZ NOT NULL,

  -- Idempotency (prevents duplicates)
  idempotency_key TEXT NOT NULL UNIQUE,

  -- Event data
  actor_id TEXT NOT NULL,
  action TEXT NOT NULL,
  target_id TEXT,
  inquiry JSONB NOT NULL DEFAULT '{}',
  confidence TEXT NOT NULL CHECK (confidence IN ('high','medium','low','unknown')),
  gaps TEXT[] NOT NULL DEFAULT '{}',

  -- Provenance
  session_id TEXT NOT NULL,
  source TEXT NOT NULL,  -- 'browser' | 'server' | 'backfill'

  -- Correction chain (not modification)
  corrects_event_id UUID REFERENCES solidivism_events(event_id),
  -- If this event corrects a previous one, link here.
  -- The original is NEVER modified. Both exist.

  -- Integrity
  checksum TEXT NOT NULL  -- SHA256 of (event_id + event_time + actor_id + action + target_id + inquiry)
);

-- Prevent UPDATE and DELETE at database level
CREATE RULE solidivism_events_no_update AS ON UPDATE TO solidivism_events DO INSTEAD NOTHING;
CREATE RULE solidivism_events_no_delete AS ON DELETE TO solidivism_events DO INSTEAD NOTHING;

-- Alternatively (PostgreSQL 18): use trigger for clearer error
CREATE OR REPLACE FUNCTION prevent_ledger_mutation()
RETURNS TRIGGER AS $$
BEGIN
  RAISE EXCEPTION 'solidivism_events is append-only. Use corrects_event_id for corrections.';
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER solidivism_events_immutable
  BEFORE UPDATE OR DELETE ON solidivism_events
  FOR EACH ROW EXECUTE FUNCTION prevent_ledger_mutation();
```

### Database Permissions

```sql
-- Applic