23-P3D4C0X — Universal PG-to-Outside Signal Architecture Review Prompt (rev2)
23-P3D4C0X — Universal PG-to-Outside Signal Architecture Review Prompt (rev2)
Date: 2026-05-08 Status: PROMPT rev2 — chờ GPT/User final review. CHƯA dispatch. Design note: knowledge/dev/laws/dieu44-trien-khai/design/23-p3d4c0x-universal-event-outbox-notification-architecture.md Report: knowledge/dev/laws/dieu44-trien-khai/reports/23-p3d4c0x-universal-event-outbox-notification-architecture-review-report.md Scope: Architecture design review. NO implementation. NO mutation. Rev1→Rev2: 5-layer pipeline, recipient/routing model, event envelope contract, generalized grouping, notification lifecycle, IU migration, Đ43 deep, law ownership, not-activity-log boundary.
Mục tiêu
Thiết kế cơ chế tổng quát để PG phát tín hiệu/thông báo ra bên ngoài cho mọi domain, mọi loại người/AI/hệ thống nhận. Tận dụng tối đa PG-native: triggers, functions, views, pg_cron, LISTEN/NOTIFY. Không tool/service mới.
IU notification là domain đầu tiên, không phải chủ sở hữu hạ tầng.
Hard Boundaries
- ❌ KHÔNG implement
- ❌ KHÔNG mutate PG/Directus
- ❌ KHÔNG code Nuxt
- ❌ KHÔNG Hermes/Codex
- ❌ KHÔNG external scheduler/tool/service
- ❌ KHÔNG biến thành general activity log — chỉ governance-significant facts
- ✅ KB document create only
- ✅ PG read-only inventory
Ranh giới bắt buộc: KHÔNG phải activity log
Universal event system CHỈ ghi governance-significant facts:
- Entity birth/create ✅
- Draft/version/approval ✅
- Comment/review ✅
- Health check alert ✅
- DOT execution result ✅
KHÔNG ghi:
- Mọi row change ❌
- Telemetry/metrics ❌
- Audit trail (riêng nếu cần) ❌
- Debug logs ❌
Agent phải propose rõ inclusion criteria: event nào đủ "governance-significant" để vào hệ thống.
Step 0: Comprehensive Law Survey (13 luật)
Agent đọc và trích xuất: domain nào cần event, loại gì, actor nào, tần suất ước tính.
| # | Luật | Domain | Tìm gì |
|---|---|---|---|
| 1 | HP | Toàn cục | NT13 PG-first, tuyên ngôn thiết kế |
| 2 | Đ0-G Birth Registry | Entity birth | Birth record, conformance, species |
| 3 | Đ7 Assembly First | Assembly | Constraint cho exposure |
| 4 | Đ22 Self-healing | Health | Issue lifecycle, health alert |
| 5 | Đ28 Display | UI | Display constraint |
| 6 | Đ33 PG/schema | Schema | Schema governance |
| 7 | Đ35 DOT | DOT | Execution event, verify |
| 8 | Đ36 Collection | Collection | Registration event |
| 9 | Đ37 Governance Org | Governance | Agency/owner/approver, checkpoint |
| 10 | Đ38 TAC | Text units | Birth/review/version/indexing |
| 11 | Đ39 Knowledge Graph | KG | Provenance, temporal, constraint |
| 12 | Đ43 System Context | System | Context-pack, DOT registry, health, red zones |
| 13 | Đ44 IU | IU | Current notification runtime (P3D2) |
Output: Domain × Event Type × Actor × Frequency matrix.
Step 1: Existing IU Infrastructure Inventory (read-only)
Xác định: cái gì reusable, cái gì IU-specific, cái gì cần generalize.
Step 2: 5-Layer Pipeline Design
Agent PHẢI tách rõ 5 lớp, mỗi lớp có table/function riêng:
Layer 1: Fact Capture (hot path O(1))
- Trigger/function trên source table
- CHỈ append vào pending/outbox
- KHÔNG computation, KHÔNG JOIN, KHÔNG aggregation
- PG-native: AFTER INSERT trigger
Layer 2: Processing (worker, deferred)
- pg_cron worker mỗi 90-120s
- Debounce, grouping (by stable key, not timing alone)
- Emit durable events
- Advisory lock, exception-safe
- PG-native: pg_cron + functions
Layer 3: Durable Event + Read State
- Universal event table (governance-significant facts)
- Per-actor read state table
- Implicit self-read, explicit read, unread
- PG-native: tables + functions
Layer 4: Notification/Routing
- Who sees what — recipient model
- Domain subscription / role routing
- Per-recipient delivery state
- PG-native: views + functions
Layer 5: Exposure/Delivery
- Directus read projection (views as collections)
- Agent SQL functions (fn_unread, fn_board)
- Nuxt display via Directus (Assembly First)
- Future seams: webhook/email/chat adapters (design only, not implement)
- PG-native: views + Directus auto-discover
Agent phải ghi rõ: computation nào nằm ở lớp nào. KHÔNG trộn lớp.
Step 3: Architecture Questions (12 câu)
Q1. Event Envelope Contract
Propose formal envelope. Candidate fields:
event_id uuid
event_domain text — 'iu', 'birth_registry', 'governance', 'tac', 'kg', 'system', 'dot'
event_type text
event_stream text — 'comment', 'review', 'update', 'alert', 'task', 'health'
event_severity text — 'info', 'warning', 'critical' (optional)
event_subject_type text — entity species / object kind
event_subject_ref uuid — entity reference
event_subject_table text — source PG table
canonical_address text
actor_ref text
source_system text — 'trigger', 'worker', 'function', 'dot'
source_function text
correlation_id text — link related events
causation_id text — what caused this event
source_document_ref text
import_batch_ref text
payload_classification text — 'safe_metadata', 'restricted'
safe_payload jsonb — metadata only
created_at timestamptz
occurred_at timestamptz — when fact happened (may differ from created_at)
CẤM trong payload: body, vector, secret, business content.
Q2. Recipient/Subscriber Model
Actor (who created) ≠ Recipient (who should see).
Recipient types:
- human user (user:huyen)
- AI agent (gpt, opus, agent:codex)
- governance agency (reviewer:gpt)
- role/group
- system service
Questions:
- Per-domain subscription? Per-event-type? Per-entity?
- Creator implicit self-read: universal rule?
- Agency/role routing: PG function or config table?
- Escalation target: design seam?
Q3. Notification Lifecycle States
Agent đánh giá ALL states, phân loại Phase 1 vs Later:
| State | Mô tả | Phase 1? |
|---|---|---|
| pending | In staging, not yet processed | ✅ |
| emitted | Worker created durable event | ✅ |
| read | Recipient marked read | ✅ |
| implicit_self | Creator auto-read | ✅ |
| suppressed | Filtered/muted by subscription | Evaluate |
| acknowledged | Recipient confirmed action taken | Evaluate |
| resolved | Related entity resolved (draft applied, issue closed) | Evaluate |
| failed/retry | Worker error, needs reprocessing | Evaluate |
| dead-letter | Permanently failed | Evaluate |
PG-first: keep Phase 1 simple. Design seams for Later.
Q4. Generalized Grouping/Debounce
Grouping keys beyond IU source_document_ref:
- DOT run id
- Context-pack build id
- Workflow id
- Entity species batch
- Agency checkpoint batch
Worker grouping: universal or per-domain? Configurable per domain?
Q5. PG Signal Channels
How does PG signal outward? Channel classes:
| Channel | Mechanism | Phase 1? |
|---|---|---|
| Directus read projection | PG view as collection | ✅ |
| Agent inbox | SQL function call | ✅ |
| Nuxt display | Via Directus API | ✅ |
| DOT/ops health | View/function | ✅ |
| LISTEN/NOTIFY | PG native, real-time signal | Evaluate |
| Webhook/email | Future adapter, design seam | Later |
Q6. Universal vs Per-Domain Tables
- 1 universal pending table vs N per-domain staging?
- 1 universal event table vs N per-domain?
- 1 universal read state vs N per-domain?
- 1 worker vs N workers?
Evaluate: query performance, permission isolation, schema evolution, maintenance.
Q7. IU Migration Strategy
Existing deployed tables: iu_notification_event, iu_notification_read + 6 functions + 3 triggers.
| Option | Approach | Risk | Effort |
|---|---|---|---|
| A | Rename → universal, migrate data | Data migration, Directus re-register | High |
| B | Keep IU, create universal, migrate triggers | Parallel tables temporarily | Medium |
| C | Keep IU as-is, universal = superset, IU views = wrappers | Compat maintained, gradual | Low-Medium |
| D | IU stays separate with justification | May diverge | Low |
Agent must recommend with justification. Không được phá fn_iu_unread, fn_iu_mark_read, fn_iu_notification_board chưa có compatibility.
Q8. Đ43 Deep Assessment
5 sub-questions:
- context-pack build/verify/health = universal event?
- dot_config dùng chung hay giữ DOT-only?
- Tránh duplicate worker/log/health table với Đ43?
- DOT execution pair event biểu diễn trong universal schema?
- Universal event feed Đ43 context-pack?
Q9. Law Ownership
Universal hạ tầng thuộc luật nào?
| Component | Candidate owner |
|---|---|
| Event schema contract | HP? Điều mới? |
| Notification routing | Đ37? Điều mới? |
| Directus exposure | Đ35? Đ36? |
| Display | Đ28 |
| Worker/pg_cron | Đ33? HP? |
Agent đề xuất. Nếu cần luật mới → note but do not create.
Q10. Directus/Nuxt Exposure Strategy
- Generic board + domain filter?
- Domain-specific Directus collections (views)?
- Assembly First compliance?
- TreeView 2/3 cột?
Q11. Inclusion Criteria
What makes an event "governance-significant" enough to enter the system?
Propose explicit criteria. Examples:
- Creates or modifies a governed entity ✅
- Requires human/AI attention or action ✅
- Changes lifecycle state ✅
- Row-level data change without governance implication ❌
- Performance metric ❌
Q12. PG-First Exploitation Checklist
For each layer, agent must confirm PG-native feature used:
| Layer | PG Feature |
|---|---|
| Fact capture | AFTER INSERT trigger |
| Pending | Table + partial index |
| Worker | pg_cron + advisory lock + function |
| Durable event | Table + CHECK + partial unique |
| Read state | Table + unique constraint |
| Routing | View + function |
| Exposure | View (Directus auto-discover) |
| Signal | LISTEN/NOTIFY (optional) |
| Config | Config table |
Step 4: Output — Architecture Design Note
Path: knowledge/dev/laws/dieu44-trien-khai/design/23-p3d4c0x-universal-event-outbox-notification-architecture.md
A. Law survey results (domain × event matrix)
B. 5-layer pipeline design
C. Event envelope contract
D. Recipient/routing model
E. Notification lifecycle (Phase 1 vs Later)
F. Grouping/debounce generalization
G. PG signal channels
H. Table strategy (universal vs per-domain)
I. IU migration recommendation
J. Đ43 assessment
K. Law ownership proposal
L. Directus/Nuxt strategy
M. Inclusion criteria
N. PG-first exploitation checklist
O. Recommendation — chọn 1:
| Option | Mô tả |
|---|---|
| UNIVERSAL_FIRST | Build universal, migrate IU |
| UNIVERSAL_WITH_IU_COMPAT | Build universal, keep IU as compat wrappers |
| IU_SPECIFIC_JUSTIFIED | Keep IU separate (justify) |
| PHASED_CONVERGENCE | IU → gradually converge |
Verification
phase_status=PASS|FAIL
laws_surveyed=<count>/13
domain_event_matrix=PASS|FAIL
five_layer_design=PASS|FAIL
event_envelope_proposed=PASS|FAIL
recipient_model_proposed=PASS|FAIL
lifecycle_states_evaluated=PASS|FAIL
lifecycle_phase1_defined=PASS|FAIL
grouping_generalized=PASS|FAIL
signal_channels_mapped=PASS|FAIL
table_strategy_proposed=PASS|FAIL
iu_migration_strategy=A|B|C|D
dieu43_deep_assessed=PASS|FAIL
law_ownership_proposed=PASS|FAIL
directus_strategy=PASS|FAIL
inclusion_criteria_defined=PASS|FAIL
pg_first_checklist=PASS|FAIL
not_activity_log_boundary=PASS|FAIL
recommendation=UNIVERSAL_FIRST|UNIVERSAL_WITH_IU_COMPAT|IU_SPECIFIC_JUSTIFIED|PHASED_CONVERGENCE
no_pg_mutation=true
no_directus_mutation=true
no_nuxt_code=true
next_required_pack=<based on recommendation>
Key Principles
- Tổng quát hóa nhu cầu. Hạ tầng event/signal là chung, domain chỉ là filter.
- PG-first, PG-native, PG-driven. Trigger, function, view, pg_cron, LISTEN/NOTIFY. Tối đa PG.
- 5 lớp tách rõ. Fact → Processing → Durable → Routing → Exposure.
- Hot path O(1). Layer 1 chỉ append.
- Không activity log. Chỉ governance-significant facts.
- IU = domain đầu tiên, không phải chủ sở hữu hạ tầng.
- Design seams cho future. Webhook/email/escalation — thiết kế chỗ cắm, không implement.
P3D4C0X rev2 | Universal PG-to-outside signal architecture | 5-layer | 12 questions | CHƯA dispatch | Chờ GPT/User final review