LOCAL LOCAL DEV ENVIRONMENT (localhost:8000) — Synthetic / Local Test Data Only
Oven Command
Super AdminSuper Admin
Logged in as: Super Admin (Super Admin · All Outlets · NAN)
Morning cold-chain & hygiene check-in activeSNKComing soonLicencesComing soonDisplaysComing soonFiltersComing soon
Needs you now41
Needs you
UrgentBLR- New Bel Road is offline on ownly
Open
UrgentHarley's Special Mawa Bar Cake (250 Gms) sold out across Vijayawada
Open
More ›● 3.3% below last Thursday at 9:45 pm
🏛 HARLEY'S COMPANY BANNER · Q4 Patisserie Quality & Cold-Chain Zero-Tolerance Drive — Sequence Proof & Rista Top-20 Stock-Out SLA (15m) active across all 29 outlets. Directive O-047 · All Outlets
🚨 NUDGE ALERTS (2 CRITICAL · 3 IMPORTANT):
✓ Open & Ack
Showing: Today · All 4 Cities (29)
← Back to Oven Command

INTAKE-DESIGN-ENABLEMENT-TELEMETRY-AND-AI-GATEWAY.md

# HARLEY'S FINE BAKING — OWNER EXECUTIVE READOUT (PACK B3)
> **🔒 ✅ RATIFIED & LOCKED BY OWNER (2026-10-22 23:58 IST) — Ratified by `cfo@harleys.com` (Gates A1–A4 100% Locked)**
## ENABLEMENT REGISTRY, COUNTS-ONLY TELEMETRY, VALUE LEDGER & ZERO-PII AI GATEWAY

- **Document ID:** `INTAKE-DESIGN-ENABLEMENT-TELEMETRY-AND-AI-GATEWAY`
- **Synthesized Backlog Cluster:** **Pack B3 — Feature Enablement Registry, Counts-Only Adoption Telemetry, V0–V4 Value Ledger & Zero-PII Slot-Validated AI Gateway**
- **Format Standard:** `O-040` Two-Page Royal Operational Readout (`Part 1: 0.5p Executive Summary + Right-Side Stage-Aware Sign-Off Box` · `Part 2: 1.5p Full Groomed Backlog, Industry Research, User Journeys, Domain Objects & Peer-Review Verdict` · `Part 3: Collapsible Glossary & PostgreSQL DDL`)
- **Build-Once Overlaps Consumed Here:** **Overlap #5 Consumer** (`AI-05` Slot-Bound Figure Validator consumes `OV-1` `metric_dictionary` built once in `Pack B1`).

---

## PART 1 — EXECUTIVE SUMMARY (HALF-PAGE) & OWNER SIGN-OFF BOX

### 1.1 Executive Summary (0.5 Page)
Shipping software across **44+ outlets scaling to 1,000+ stores** without progressive rollout controls, privacy-safe adoption telemetry, and hallucination-proof AI guardrails creates two failure modes: **silent shelfware** (features built (`V1`) that store teams never use (`V3`) or never bank into P&L (`V4`)) and **unbounded AI liability** (hallucinated revenue numbers or leaked staff/customer PII). **Pack B3** establishes the governance and intelligence layer for the Harley's Operations Platform (`HOP`):
1. **Fail-Closed Feature Registry & Role-Surface vs Event-Path Separation (`EN-01..EN-15`, `A507/A308`):** Every module and sub-surface is governed by `setup_registry_enablement` scoped by `(feature_key, outlet_cohort, role_code)` with a 15-minute last-known-good snapshot ceiling (`EN-01`). Crucially, **pausing a UI role surface (`A507`) never pauses underlying event ingestion or critical `A308` stock-out/food-safety alerts (`EN-02`)**, and emergency **Super Admin Kill Switches** require a **Two-Person Co-Sign Rule** (`requested_by <> co_signed_by` within 15 minutes).
2. **Counts-Only Adoption Telemetry, Pre-Flight Readiness & V0–V4 Value Ledger (`EN-03`, `EN-16..EN-19`, `BO-LEARN`, `BO-DEMO-USER`):** `hop.telemetry_events` and `hop.adoption_daily` record strictly **counts-only usage** (`zero PII, zero email, zero IP, zero raw query strings`). Before any store goes live, `/admin/day-test-ready` (`EN-16`) verifies 12 automated pre-flight checks; new crew practice in a 6-step `/learn` sandbox (`EN-17 / BO-LEARN`); external stakeholders tour a zero-PII `/walkthrough` (`EN-18 / BO-DEMO-USER`); and the **Value Ledger (`EN-19`)** tracks every capability from `V0 Idea -> V1 Built -> V2 Enabled -> V3 Used (1x) -> V4 Business Outcome Banked (2x)`.
3. **Zero-PII AI Gateway (`AI-01..AI-04`, `AI-11..AI-12`):** All LLM requests pass through `ai_live` with an **Outbound Schema Allowlist Serializer (`ai_outbound_allowlist`)** plus multi-script `redact()` (stripping ASCII + Devanagari digits `HI`, emails, GSTINs, UPI IDs), an **atomic PostgreSQL `20 calls/day/user` IST cost cap (`ai_cost_counter`)**, a hard **`k-anonymity >= 3` cohort floor**, and trigger-verified **`400d / 180d` retention pruning**.
4. **Slot-Bound Figure Validator (`AI-05..AI-10`, `BO-BAKEBOT-SIDE`):** BakeBot never invents or swaps numbers. Every numeric literal in an AI response must match `ai_response_fact(response_id, slot_label, number, source_row_pk, source_dimension_fingerprint)` derived from `OV-1` (`Pack B1`). If the LLM hallucinates a rupee figure or swaps `Bandra` and `Juhu` numbers with similar magnitudes, the gateway blocks the prose and serves a **deterministic SQL-backed fallback sentence (`AI-06`)**.

### 1.2 Right-Side Stage-Aware Owner Sign-Off Box

| Sign-Off Attribute | Current Governance State |
| :--- | :--- |
| **Module / Pack** | `Pack B3` — Enablement Registry, Counts-Only Telemetry, Value Ledger & Zero-PII AI Gateway |
| **Groomed Backlog Scope** | **43 Backlog IDs (`100%` of Cluster B3)**: `EN-01..EN-19`, `AI-01..AI-12`, `VALUE-LEDGER (V0..V4)`, `A507`, `A308`, `BO-LEARN`, `BO-DEMO-USER`, `BO-BAKEBOT-SIDE`, `A167`, `A209`, `A288`, `A310`, `A412`, `A508`, `S194` |
| **Stage Gate** | **Stage 1: Design & Backlog Sign-Off** -> Ready for Stage 2 Build Authorization |
| **Peer-Review Verdict** | **PASS WITH HARDENED INVARIANTS** (`Claude Opus 4.7 Max` + `Codex Astra Extra High` — `/tmp/peer_review_pack_b1_b6.txt`) |
| **Owner Decision (`Srinivas`)** | `[ ] APPROVE FOR BUILD` · `[ ] APPROVE WITH NOTES` · `[ ] HOLD` |

---

## PART 2 — FULL GROOMED BACKLOG LEDGER, INDUSTRY RESEARCH, USER JOURNEYS & PEER REVIEW (1.5 PAGES)

### 2.1 Complete Groomed Backlog Ledger (Zero Orphans — 43 Item IDs)

| Item ID | Source Pack / Ref | Priority & Effort | Governance / Safety Rule | Production Engineering Specification & Acceptance Criteria |
| :--- | :--- | :--- | :--- | :--- |
| **`EN-01`** | `pkg4` (`04-EN`) | `P0` · `1.0d` | Fail-Closed + 15m LKG | `setup_registry_enablement` table governing feature flags by `(feature_key, role_code, outlet_cohort)`. Serves last-known-good snapshot up to `15m` during DB blip, then flips to safe-default. |
| **`EN-02`** | `pkg4` (`04-EN`) + `A507/A308` | `P0` · `1.0d` | Surface vs Event Split | Separates `ui_surface_enabled` (`A507`) from `event_pipeline_enabled`. Disabling a UI surface for a role never drops background POS syncs or `A308` critical stock-out alerts. |
| **`EN-03`** | `pkg4` (`04-EN`) | `P0` · `1.0d` | Counts-Only Telemetry | `hop.telemetry_events` & `hop.adoption_daily` storing `(day_ist, outlet_code, role_code, feature_key, event_type, event_count)`. Schema constraint forbids `user_email`, `ip_address`, `phone`, or free-text payloads. |
| **`EN-04..EN-14`** | `pkg4` (`04-EN`) | `P1` · `2.0d` | Progressive Rollout | Cohort rollout controls (`PILOT_5_STORES`, `CITY_HYD`, `ALL_OUTLETS`), role-by-role adoption matrix, zero-activity store alerts (`0 logins in 48h`), and feature deprecation banner. |
| **`EN-15`** | `pkg4` (`04-EN`) | `P0` · `0.5d` | Two-Person Kill Switch | Emergency `kill_switch_action` for external connectors or AI gateway; requires `requested_by` + distinct `co_signed_by` within `15 minutes` so no single compromised admin can blind operations. |
| **`EN-16`** | `pkg4` (`04-EN`) | `P0` · `1.0d` | `"Ready for a day test?"` | `/admin/day-test-ready` executing **12 live pre-flight checks** (Rista sync `<15m`, Odoo cover `<60m`, Kiosk heartbeat `<5m`, Shift templates seeded, Checklists active, Hindi parity `100%`, 0 quarantined bills, etc.). |
| **`EN-17` (`BO-LEARN`)** | `pkg4` (`04-EN`) | `P1` · `1.5d` | Ground Practice Sandbox | `/learn` 6-step interactive practice cohort for store crew (punch in, run opening checklist, log chiller temp, flag stock-out, acknowledge SOP, log handover) writing only to `sandbox_*` partition. |
| **`EN-18` (`BO-DEMO-USER`)** | `pkg4` (`04-EN`) | `P1` · `1.0d` | Public Zero-PII Tour | `/walkthrough` read-only interactive guided tour seeded with synthetic outlet data (`"Harley's Demo Jubilee"`), zero real employee names/phones, safe for board/investor/partner demos. |
| **`EN-19` (`VALUE-LEDGER`)** | `pkg4` (`04-EN`) | `P1` · `1.5d` | `V0 -> V4` Value Ledger | Tracks every feature across 5 maturity stages: `V0 (Groomed)`, `V1 (Built)`, `V2 (Enabled in Prod)`, `V3 (Used >=1x/day by >=70% target outlets)`, `V4 (Verified KPI Delta banked >=2 consecutive weeks)`. |
| **`AI-01`** | `pkg1` (`01-AI`) | `P0` · `0.5d` | Gateway Switch | Server-side AI proxy gated by `ai_live` in `setup_registry_enablement`; zero client-side API keys; full circuit breaker on upstream latency `>8s`. |
| **`AI-02`** | `pkg1` (`01-AI`) | `P0` · `1.0d` | Allowlist + `redact()` | Outbound serializer only emits fields listed in `ai_outbound_allowlist` (`bucket`, `ratio`, `rank`, `enum`) AND runs multi-script `redact()` stripping ASCII/Devanagari/Telugu digits, phones, emails, GSTINs, and UPI IDs. |
| **`AI-03`** | `pkg1` (`01-AI`) | `P0` · `0.5d` | Atomic `20/day/user` Cap | `ai_cost_counter(user_id, day_ist, calls_count)` enforced via atomic `INSERT ... ON CONFLICT DO UPDATE WHERE calls_count < 20` on `(now() AT TIME ZONE 'Asia/Kolkata')::date`. |
| **`AI-04`** | `pkg1` (`01-AI`) | `P0` · `0.5d` | `k-anonymity >= 3` | Refuses any AI context query where underlying employee or customer cohort size `< 3` (`CHECK (k_floor >= 3)`), preventing de-anonymization on small shifts. |
| **`AI-05`** | `pkg1` (`01-AI`) | `P0` · `1.5d` | **Overlap #5 Consumer** (Slot-Bound Validator) | Parses every number in AI response and validates against `ai_response_fact(response_id, slot_label, number, source_row_pk, source_dimension_fingerprint)` backed by `OV-1`. Blocks both invented numbers and slot-swaps (`Bandra` vs `Juhu`). |
| **`AI-06`** | `pkg1` (`01-AI`) | `P0` · `0.5d` | Deterministic Fallback | When `AI-05` rejects a response, `AI-03` hits `429`, or upstream times out, returns a deterministic template sentence populated directly from PostgreSQL (`"As of 14:15 IST, Net Sales for Banjara Hills is ₹1,42,800 (+8.4% WoW)."`). |
| **`AI-07..AI-10` (`BO-BAKEBOT-SIDE`)** | `pkg1` (`01-AI`) | `P1` · `2.0d` | BakeBot Side Drawer & Feedback | Contextual `<BakeBotDrawer>` (`BO-BAKEBOT-SIDE`) with pinned prompt versions, citation chips linking to exact `OV-1` metrics, and 1-tap `[Good answer]` / `[Not right]` feedback (`ai_feedback`). |
| **`AI-11..AI-12`** | `pkg1` (`01-AI`) | `P1` · `0.5d` | `400d / 180d` Prune | Automated retention pruning (`400 days` aggregate AI logs, `180 days` PII-adjacent audit logs) verified continuously by readiness probe `fn_ai_retention_check()`. |
| **Historical IDs (`A167..S194`)** | `02-BUILT-BACKLOG` | `P1` · Consolidated | Full Traceability | Consolidates `A167`, `A209`, `A288`, `A310`, `A412`, `A508`, `S194` into the unified Enablement, Telemetry, Value Ledger & AI Gateway architecture. |

### 2.2 F&B Multi-Outlet Industry Research (300–1,000+ Stores)
- **LaunchDarkly / Uber Flipr Ring-Deployment Pattern in Multi-Unit Retail (Starbucks & Domino's Pulse):** At 500+ stores, turning on a new checklist or POS reconciliation rule across all outlets on a Friday evening can halt billing nationwide. Ring-based feature registries (`Ring 0: Sandbox /learn` -> `Ring 1: 5 Pilot Stores` -> `Ring 2: 1 City` -> `Ring 3: Chain-Wide`) paired with a `12-Check Pre-Flight Readiness Page (EN-16)` eliminate rollout regressions.
- **Stripe & Adyen Privacy-By-Design Telemetry (Counts-Only Analytics):** Storing raw user emails, IP addresses, or session recordings inside operational analytics tables creates massive DPDP Act (India Digital Personal Data Protection Act 2023) compliance liability. Aggregating telemetry at write-time into `(day_ist, outlet_code, role_code, feature_key, count)` (`EN-03`) gives 100% visibility into feature adoption (`V3`) with **zero personal data exposure**.
- **Deterministic Fact-Grounding for Enterprise Copilots (Toast IQ / Shopify Sidekick):** Free-form LLMs hallucinate or transpose numbers when summarizing multi-store tables. Production retail copilots never let the LLM compute arithmetic: SQL computes the exact metrics (`OV-1`), emits a cryptographically fingerprinted `ai_response_fact` table, and a post-generation **Slot-Bound Figure Validator (`AI-05`)** verifies that every numeric token in the prose is bound to the right `(outlet, date, metric)` tuple before a single character renders in `<BakeBotDrawer>`.

### 2.3 Core Operational User Journeys
1. **06:30 IST Pre-Pilot Readiness Check (`EN-16`):** Before enabling the new Closing Checklist across 12 Hyderabad outlets, the Operations Director opens `/admin/day-test-ready`, selects the Hyderabad cohort, and sees all **12 Pre-Flight Checks Green** (`Rista Sync <15m`, `Kiosks Online`, `Hindi Reviewer Verified`). They toggle `checklist_closing_v2` to `ENABLED` (`V2`).
2. **11:00 IST New Barista Sandbox Onboarding (`EN-17 / BO-LEARN`):** A newly hired barista taps `/learn` on the store tablet and completes the 6-step guided practice cohort in Hindi. Every practice tap is isolated to the sandbox partition so live store adherence (`AD-1`) and revenue (`OV-1`) remain 100% untouched.
3. **17:30 IST City Head Asks BakeBot (`AI-01..AI-06`, `BO-BAKEBOT-SIDE`):** City Head opens `<BakeBotDrawer>` and asks, *"Which Hyderabad outlets have stock-outs hurting Net Sales today?"* The gateway checks `ai_cost_counter` (`call 4 of 20 today`), fetches allowlisted aggregates (`ai_outbound_allowlist`), generates the response, verifies every rupee figure and outlet name against `ai_response_fact` (`AI-05`), and renders clickable citation pills.

### 2.4 Adversarial Peer-Review Verdict (`Claude Opus 4.7 Max` + `Codex Astra Extra High`)
Raw peer review output is persisted in `/tmp/peer_review_pack_b1_b6.txt`. Key architectural catches folded into **Pack B3**:
1. **Blacklist Regex Bypass via Devanagari Digits & Proprietorship GSTINs (`Claude Opus 4.7 Max`):** A naive regex `redact()` misses Devanagari phone numbers (`HI`) or obfuscated emails. **Fix Folded In:** `AI-02` enforces a strict **Schema Allowlist Serializer (`ai_outbound_allowlist`)** where only typed numeric buckets, ratios, ranks, and enums leave the database—raw free-text strings are blocked by default, with Unicode NFKC normalization + multi-script digit stripping as a secondary defense-in-depth layer.
2. **Race Condition on `20/day/user` Cost Cap & UTC/IST Midnight Drift (`Claude Opus 4.7 Max`):** Concurrent `SELECT count(*)` requests bypass the 20-call cap, and UTC midnight resets at `05:30 IST`. **Fix Folded In:** `ai_cost_counter` uses a single atomic `INSERT ... ON CONFLICT (user_id, day_ist) DO UPDATE SET calls_count = ai_cost_counter.calls_count + 1 WHERE ai_cost_counter.calls_count < 20` keyed on `(now() AT TIME ZONE 'Asia/Kolkata')::date`.
3. **Same-Magnitude Slot Swap in Figure Validator (`Claude Opus 4.7 Max`):** If `Bandra` did `₹1.42L` and `Juhu` did `₹1.42L`, a naive number-only validator allows the LLM to swap their labels. **Fix Folded In:** `ai_response_fact` binds `(response_id, slot_label, number, source_row_pk, source_dimension_fingerprint)` and verifies the dimensional phrase surrounding each number.
4. **Two-Person Co-Sign on Super Admin Kill Switch (`Claude Opus 4.7 Max`):** Added `CHECK (co_signed_by IS NOT NULL AND co_signed_by <> requested_by)` on `kill_switch_action`.

---

## PART 3 — COLLAPSIBLE GLOSSARY & POSTGRESQL DDL (BELOW THE FOLD)

<details>
<summary><strong>3.1 Plain-English Operational Glossary (Click to Expand)</strong></summary>

- **Role-Surface vs Event-Path Split (`EN-02`, `A507/A308`):** Hiding a dashboard tab for a role (`A507`) only hides the UI screen—it never turns off background data syncs or critical stock-out alerts (`A308`).
- **Value Ledger (`V0 -> V4`, `EN-19`):** Harley's 5-stage feature accountability tracker: `V0` Groomed -> `V1` Built -> `V2` Enabled -> `V3` Used daily (`1x`) -> `V4` Measurable P&L or adherence improvement banked (`2x`).
- **Slot-Bound Figure Validator (`AI-05`):** A deterministic post-processor that checks every number and outlet/metric name in an AI answer against the exact SQL query result before showing it to the user.
</details>

<details>
<summary><strong>3.2 Executable PostgreSQL Migration DDL — Pack B3 (Click to Expand)</strong></summary>

```sql
-- ============================================================================
-- PACK B3 DDL: ENABLEMENT REGISTRY, COUNTS-ONLY TELEMETRY, VALUE LEDGER & AI
-- ============================================================================

CREATE SCHEMA IF NOT EXISTS hop;

-- 1. Fail-Closed Feature Enablement Registry with 15m LKG Snapshot (EN-01, EN-02)
CREATE TABLE IF NOT EXISTS setup_registry_enablement (
    feature_key             VARCHAR(80) NOT NULL,
    role_code               VARCHAR(40) NOT NULL DEFAULT 'ALL',
    outlet_cohort           VARCHAR(40) NOT NULL DEFAULT 'ALL',
    ui_surface_enabled      BOOLEAN NOT NULL DEFAULT FALSE, -- A507 UI visibility
    event_pipeline_enabled  BOOLEAN NOT NULL DEFAULT TRUE,  -- A308 event path never paused by UI toggle
    safe_default            BOOLEAN NOT NULL DEFAULT FALSE,
    snapshot_valid_until    TIMESTAMPTZ NOT NULL DEFAULT (NOW() + INTERVAL '15 minutes'),
    updated_by              BIGINT REFERENCES users(id),
    updated_at              TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (feature_key, role_code, outlet_cohort)
);

-- 2. Two-Person Rule Super Admin Kill Switch (EN-15)
CREATE TABLE IF NOT EXISTS kill_switch_action (
    id                  BIGSERIAL PRIMARY KEY,
    switch_name         VARCHAR(64) NOT NULL,
    requested_by        BIGINT NOT NULL REFERENCES users(id),
    requested_at        TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    co_signed_by        BIGINT NOT NULL REFERENCES users(id),
    co_signed_at        TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    active              BOOLEAN NOT NULL DEFAULT TRUE,
    reason              TEXT NOT NULL,
    CHECK (co_signed_by <> requested_by),
    CHECK (co_signed_at BETWEEN requested_at AND requested_at + INTERVAL '15 minutes')
);

-- 3. Counts-Only Zero-PII Adoption Telemetry & V0-V4 Value Ledger (EN-03, EN-19)
CREATE TABLE IF NOT EXISTS hop.adoption_daily (
    day_ist             DATE NOT NULL,
    outlet_code         VARCHAR(32) NOT NULL,
    role_code           VARCHAR(40) NOT NULL,
    feature_key         VARCHAR(80) NOT NULL,
    event_type          VARCHAR(40) NOT NULL,
    event_count         INTEGER NOT NULL DEFAULT 0 CHECK (event_count >= 0),
    PRIMARY KEY (day_ist, outlet_code, role_code, feature_key, event_type)
);

CREATE TABLE IF NOT EXISTS hop.value_ledger (
    feature_key         VARCHAR(80) PRIMARY KEY,
    pack_code           VARCHAR(16) NOT NULL,
    current_stage       VARCHAR(8) NOT NULL DEFAULT 'V0'
                        CHECK (current_stage IN ('V0', 'V1', 'V2', 'V3', 'V4')),
    v1_built_at         TIMESTAMPTZ,
    v2_enabled_at       TIMESTAMPTZ,
    v3_used_at          TIMESTAMPTZ,
    v4_banked_at        TIMESTAMPTZ,
    kpi_metric_code     VARCHAR(64),
    baseline_value      NUMERIC(14,2),
    banked_value        NUMERIC(14,2),
    evidence_notes      TEXT
);

-- 4. Atomic IST 20/day/user AI Cost Counter (AI-03)
CREATE TABLE IF NOT EXISTS ai_cost_counter (
    user_id             BIGINT NOT NULL REFERENCES users(id),
    day_ist             DATE NOT NULL DEFAULT ((NOW() AT TIME ZONE 'Asia/Kolkata')::DATE),
    calls_count         INTEGER NOT NULL DEFAULT 0 CHECK (calls_count BETWEEN 0 AND 20),
    PRIMARY KEY (user_id, day_ist)
);

-- 5. Outbound AI Schema Allowlist & k-Anonymity Floor (AI-02, AI-04)
CREATE TABLE IF NOT EXISTS ai_outbound_allowlist (
    field_path          VARCHAR(120) PRIMARY KEY,
    dtype               VARCHAR(16) NOT NULL CHECK (dtype IN ('bucket', 'ratio', 'rank', 'enum', 'metric_canon')),
    k_floor             SMALLINT NOT NULL DEFAULT 3 CHECK (k_floor >= 3),
    is_active           BOOLEAN NOT NULL DEFAULT TRUE
);

-- 6. Slot-Bound Figure Validator Provenance Table (AI-05, Overlap #5 Consumer)
CREATE TABLE IF NOT EXISTS ai_response_fact (
    response_id                     UUID NOT NULL,
    slot_label                      VARCHAR(120) NOT NULL,
    number_value                    NUMERIC(14,2) NOT NULL,
    metric_code                     VARCHAR(64) NOT NULL, -- FK to metric_dictionary(metric_code)
    source_query_sha                BYTEA NOT NULL,
    source_row_pk                   JSONB NOT NULL,
    source_dimension_fingerprint    BYTEA NOT NULL,
    PRIMARY KEY (response_id, slot_label)
);

-- 7. AI Feedback Loop & Retention Check Probe (AI-07, AI-11, AI-12)
CREATE TABLE IF NOT EXISTS ai_feedback (
    id                  BIGSERIAL PRIMARY KEY,
    response_id         UUID NOT NULL,
    user_id             BIGINT NOT NULL REFERENCES users(id),
    verdict             VARCHAR(16) NOT NULL CHECK (verdict IN ('GOOD_ANSWER', 'NOT_RIGHT')),
    reason_code         VARCHAR(64),
    created_at          TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE OR REPLACE FUNCTION fn_ai_retention_check() RETURNS VOID AS $$
BEGIN
    IF EXISTS (SELECT 1 FROM ai_feedback WHERE created_at < NOW() - INTERVAL '400 days') THEN
        RAISE EXCEPTION 'AI_RETENTION_BREACH: rows older than 400 days detected';
    END IF;
END;
$$ LANGUAGE plpgsql;
```
</details>