KB-2963 rev 2

Kiến trúc v3.0 — Bản cuối sau AI Council 3 Vòng

29 min read Revision 2
architecturev3consolidatedfinallifecycle-lawmatrix-lawliveness-lawuniversal-rulesschema

Kiến trúc v3.0 — Bản chính thức sau AI Council 3 Vòng

Phiên: S136 | Ngày: 2026-03-19 Tác giả: Claude Desktop (tổng hợp) + Anh Huyên (chỉ đạo) + GPT + Gemini (đóng góp 3 vòng) Trạng thái: BẢN CUỐI — đủ đồng thuận, sẵn sàng Phase 1 Đọc trước: search_knowledge("council synthesis v3 round1"), search_knowledge("entity lifecycle") Lịch sử: v1 (draft) → v2 (sau vòng 2) → v3 (sau vòng 3, tích hợp 8 changes)


MỤC LỤC

  • I. BỐI CẢNH + CHẨN ĐOÁN
  • II. 10 UNIVERSAL RULES
  • III. ĐIỀU 27 — LIFECYCLE LAW
  • IV. ĐIỀU 28 — MATRIX LAW
  • V. ĐIỀU 29 — LIVENESS LAW
  • VI. SCHEMA MỚI (DDL CHÍNH THỨC)
  • VII. DECISION TREE PHÂN LOẠI OBJECT
  • VIII. KẾ HOẠCH TRIỂN KHAI
  • IX. NGUYÊN TẮC AN TOÀN: SOURCE-OF-TRUTH vs MIRROR
  • PHỤ LỤC A: TỔNG KẾT ĐÓNG GÓP AI COUNCIL
  • PHỤ LỤC B: CHANGELOG VÒNG 3

I. BỐI CẢNH + CHẨN ĐOÁN GỐC

Lỗ hổng đã phát hiện (S136)

Hệ thống hiện tại tư duy hướng đối tượng (mỗi collection có luật riêng) thay vì hướng nguyên tắc phổ quát (mọi entity tuân theo cùng bộ luật). Hệ quả:

  1. Chỉ quản lý 27 registered types — mỗi type mới cần code mới
  2. Không có lifecycle chung — entity sinh ra nhưng không có quy trình thống nhất cho deprecate/retire/merge/split
  3. Quan hệ xuyên lớp bị ẩn — FK chỉ trong cùng collection, không có cơ chế discovery toàn hệ thống
  4. Luật tồn tại trong tài liệu, không tự chạy — vi phạm không được auto-detect
  5. Đối tượng phái sinh không được quản trị — views, computed fields, derived data nằm ngoài registry

Giải pháp: 3 Luật mới + 10 Universal Rules

Chuyển từ "mỗi collection một bộ luật" → "MỌI entity tuân theo CÙNG bộ nguyên tắc." Ba luật mới lấp đúng 3 lỗ hổng: vòng đời (Lifecycle), quan hệ (Matrix), sức khoẻ tự động (Liveness).


II. 10 UNIVERSAL RULES

Nguyên tắc: Mọi entity trong hệ thống — bất kể lớp nào, collection nào — PHẢI thoả mãn cả 10 rules. Rule nào không đo hết bằng SQL thì PHẢI có DOT/UX contract bù.

# Rule Mô tả Đo bằng
1 Identity Mọi entity PHẢI có code PREFIX-NNN duy nhất SQL: v_rule_identity_violations
2 Registry Mọi entity PHẢI xuất hiện trong registry tương ứng SQL: check_registry_coverage() (đã có)
3 Classification Mọi entity PHẢI được gán ít nhất 1 label thuộc ít nhất 1 facet SQL: v_rule_classification_violations
4 Connectivity Mọi entity PHẢI có ít nhất 1 quan hệ (không orphan graph) SQL: v_rule_connectivity_violations (severity=warning)
5 Countability Mọi entity PHẢI được đếm chính xác — complete + orphan = actual SQL: verify_counts() (đã có, Điều 26)
6 Birth Control Mọi entity PHẢI sinh qua Birth Pipeline — có _dot_origin + date_created + code SQL: v_rule_birth_violations
7 Visibility Mọi entity PHẢI hiển thị đúng trên UI tương ứng DOT contract: DOT scan Điều 23 question A
8 Liveness Mọi entity PHẢI ở trạng thái xác định và được kiểm tra định kỳ SQL: v_rule_liveness_violations
9 Uniqueness Không entity nào trùng code, không cặp entity nào trùng name trong cùng collection SQL: v_rule_uniqueness_violations
10 Traceability Mọi entity, quan hệ, và dữ liệu phái sinh PHẢI truy vết được nguồn gốc SQL: v_rule_traceability_violations

Cách vận hành

  • Tự động: Rules 1-6, 8-10 → PG views + triggers + universal_rule_violations table
  • Bán tự động: Rule 7 (Visibility) → DOT scan tools, kết quả ghi vào universal_rule_violations
  • Tần suất: Health Check chạy fn_run_all_rules() mỗi lần CI/CD
  • Phân vai Điều 29 vs Điều 23: Điều 29 = engine + court record (đo, lưu, phán). Điều 23/DOT = sensor (thu thập dữ liệu cho Rule 7)

III. ĐIỀU 27 — LUẬT VÒNG ĐỜI (LIFECYCLE LAW)

"Mọi thực thể được quản trị PHẢI có vòng đời rõ ràng — từ lúc sinh đến lúc nghỉ hưu — và MỌI chuyển trạng thái PHẢI được kiểm soát, ghi nhận, và kiểm chứng."

§1. Phạm vi

Áp dụng cho MỌI entity trong 18+ managed collections, bất kể lớp (atom → building).

  • draft = managed entity đang trong giai đoạn chưa active — KHÔNG phải "nửa entity". Vẫn phải có identity tối thiểu + registry + metadata.

§2. Trạng thái hợp lệ (Lifecycle States) — SỬA VÒNG 3

Hai trục phân tách (theo đề xuất GPT, Claude chấp thuận):

  • lifecycle_status: draft | active | deprecated | retired — trạng thái vòng đời chính
  • terminal_reason: none | merged | split_replaced | archived — lý do kết thúc (chỉ áp dụng khi status = retired)

Lý do tách: merged không cùng bản chất với deprecated; nó là kết quả nghiệp vụ đặc biệt. archived (Gemini đề xuất) = entity quá cũ không dùng nhưng cần giữ cho audit, khác với retired bình thường.

State diagram:

  • draft → active (activate)
  • active → deprecated (deprecate)
  • deprecated → retired (retire, terminal_reason = none)
  • deprecated → active (reactivate)
  • retired → active (reactivate, chỉ khi terminal_reason = none)
  • active → retired (merge, terminal_reason = merged)
  • active → retired (split, terminal_reason = split_replaced)
  • retired → retired (archive, terminal_reason = archived)

§3. Chuyển trạng thái (Transitions)

Transition From → To Pre-check Post-check Ai thực hiện
activate draft → active Has code + _dot_origin + ≥1 label Appears in registry count Birth Pipeline (PG function)
deprecate active → deprecated Reason ghi vào lifecycle_log UI hiển thị badge "deprecated" DOT tool → PG function chuẩn
retire deprecated → retired Retire Gate: 0 active dependencies Removed from active counts, kept in history DOT tool → Retire Gate → PG function
reactivate deprecated/retired → active terminal_reason = none + approval Re-appears in active counts DOT tool → PG function
merge active → retired(merged) Target entity specified, all edges migrated Old = retired+merged, new inherits all edges DOT tool → PG function
split active → retired(split_replaced) Child entities created, edges distributed Old = retired+split_replaced, children = active DOT tool → PG function
archive retired → retired(archived) Reason ghi vào lifecycle_log Moved to archive zone DOT tool → PG function

§4. Pre-Birth Check (bắt buộc — trước Birth Pipeline) — MỞ RỘNG VÒNG 3

Trước khi Birth Pipeline tạo entity, PHẢI validate theo thứ tự (rẻ/cứng trước, sâu sau):

  1. Collection/type hợp lệ (thuộc managed collections)
  2. Caller + permission hợp lệ (DOT tool hoặc PG function, có quyền tạo đúng collection/type)
  3. Metadata tối thiểu: _dot_origin, status = 'draft', composition_level hợp lệ
  4. Duplicate check: code format đúng PREFIX-NNN + name không trùng entity active + business essence không trùng
  5. Registry readiness: Collection có wiring đầy đủ trong registry system chưa

Fail bất kỳ check → REJECT, ghi vào system_issues với issue_type = 'birth_rejection'.

Lưu ý Assembly First (GPT vòng 3): Pre-Birth Check nên là PG function chuẩn fn_pre_birth_check(...). Trigger chỉ là lớp chặn cuối, không phải business entrypoint chính.

§5. Retire Gate (bắt buộc — trước khi retire) — CẢI THIỆN VÒNG 3

Dual-source check (theo GPT vòng 3: mirror có thể trễ, phải đọc source-of-truth):

CREATE OR REPLACE FUNCTION fn_retire_gate_check(p_table TEXT, p_entity_id INT)
RETURNS TABLE(blocker_source TEXT, blocker_table TEXT, blocker_id INT, blocker_code TEXT) AS $$
BEGIN
  -- Lớp 1: HARD blockers từ native FK/M2M (source-of-truth)
  -- (generated dynamically per collection từ information_schema)
  
  -- Lớp 2: SOFT blockers từ universal_edges (bổ sung visibility)
  RETURN QUERY
  SELECT 'edge_mirror'::TEXT, ue.source_collection, ue.source_id, ue.source_code
  FROM universal_edges ue
  WHERE ue.target_collection = p_table
    AND ue.target_id = p_entity_id
    AND ue.status = 'active';
END;
$$ LANGUAGE plpgsql;

Nếu có hard blocker → CHẶN TUYỆT ĐỐI. Soft blocker → CẢNH BÁO + cần review.

§6. Lifecycle Log — MỞ RỘNG VÒNG 3

CREATE TABLE lifecycle_log (
  id SERIAL PRIMARY KEY,
  entity_collection VARCHAR(100) NOT NULL,
  entity_id INT NOT NULL,
  entity_code VARCHAR(50),
  from_status VARCHAR(20) NOT NULL,
  to_status VARCHAR(20) NOT NULL,
  terminal_reason VARCHAR(30) DEFAULT 'none',
  transition_type VARCHAR(30),                    -- 'activate','deprecate','retire','merge','split','archive','reactivate'
  reason TEXT,
  performed_by VARCHAR(100) NOT NULL,             -- 'DOT:tool_name' hoặc 'PG:function_name'
  performed_at TIMESTAMPTZ DEFAULT NOW(),
  related_entity_collection VARCHAR(100),         -- cho merge/split: entity liên quan
  related_entity_id INT,
  related_entity_code VARCHAR(50),
  approval_ref TEXT,                              -- cho reactivate: reference approval
  metadata JSONB DEFAULT '{}'
);

§7. Quan hệ với các Điều khác

  • Điều 0 (Entity definition): draft = managed-but-not-active, vẫn phải có identity tối thiểu
  • Điều 0-B (Composition Levels): Lifecycle áp dụng đồng nhất cho cả 6 lớp
  • Điều 24 (Label Law): Entity retired → labels giữ nguyên (lịch sử), không gán label mới
  • Điều 26 (Counting Law): Chỉ đếm entity active + deprecated vào managed count. draftretired đếm riêng.
  • Điều 23 (DOT Scanning): Mỗi transition phải có DOT check tương ứng

IV. ĐIỀU 28 — LUẬT MA TRẬN (MATRIX LAW)

"Mọi quan hệ trong hệ thống PHẢI được ghi nhận, phân loại, và truy vấn được — cả trong cùng lớp lẫn xuyên lớp — thông qua một cơ chế thống nhất."

§1. Nguyên tắc kép (Dual Mechanism)

Phạm vi Cơ chế Mục đích Ví dụ
Cùng lớp (atom↔atom) Native FK / M2M trong Directus Integrity cứng (PG constraint) ingredient.category_id → categories.id
Xuyên lớp (atom→molecule→...→building) universal_edges table Discovery + visibility toàn hệ thống atom ATM-001 → molecule MOL-005 → product PRD-002
Derived objects derived_objects_registry Quản trị đối tượng phái sinh view v_product_summary derived from PRD + ATM

§2. Nguyên tắc: FK cho Integrity, universal_edges cho Visibility

  • FK native = ràng buộc cứng, PG enforce, không thể vi phạm. Dùng cho quan hệ CẤU TRÚC (belongs_to, contains).
  • universal_edges = read-model + discovery backbone. Dùng cho: quan hệ xuyên lớp, quan hệ ngữ nghĩa (similar_to, used_by), và mirror toàn bộ FK native.
  • KHÔNG BAO GIỜ dùng universal_edges để thay thế FK. FK là source of truth, universal_edges là mirror.
  • KHÔNG BAO GIỜ mirror được quyền sửa ngược source native (xem §IX).

§3. 6 Loại quan hệ (mapping UI Registries Layer 5)

# Tên Tiếng Việt edge_type Mô tả
1 belongs_to Thuộc ai BELONGS_TO Entity thuộc entity cha (1:N)
2 contains Chứa gì CONTAINS Entity chứa entity con (1:N ngược)
3 uses Dùng ai USES Entity sử dụng entity khác (M2M)
4 used_by Ai dùng tôi USED_BY Ngược của uses (auto-generated)
5 group_with Cùng nhóm GROUP_WITH Entities cùng nhóm/category (M2M symmetric)
6 similar_to Tương tự SIMILAR_TO Entities tương tự nhau (M2M symmetric, có thể AI-inferred)

Điều NHẤT QUÁN: 6 heading này PHẢI luôn hiển thị đầy đủ, đúng thứ tự, tại mọi entity Layer 5. Empty = để trống. Không ẩn, không gộp.

§4. Sync Protocol (FK → universal_edges)

FK native thay đổi → PG TRIGGER → UPSERT universal_edges với source_info = 'FK_SYNC:{collection}.{fk_column}' + is_auto_managed = TRUE

Quy tắc:

  • Sync là one-way: FK → edges. KHÔNG BAO GIỜ ngược lại.
  • Trigger CHỈ tác động edges có is_auto_managed = TRUE. Edges semantic (is_auto_managed = FALSE) không bị ghi đè.
  • Mỗi native FK/M2M relation sinh 2 edges hướng (source→target + target→source) để UI Layer 5 hiển thị đầy đủ cả 6 headings mà không cần tự suy diễn.
  • Symmetric edges (GROUP_WITH, SIMILAR_TO): lưu 2 rows nhưng quản bằng symmetry_group_id.

Assembly First (GPT vòng 3): Generate sync triggers từ catalog/meta, không hand-code từng trigger.

§5. Derived Objects Registry — MỞ RỘNG VÒNG 3

CREATE TABLE derived_objects_registry (
  id SERIAL PRIMARY KEY,
  code VARCHAR(50) UNIQUE NOT NULL,               -- 'DRV-001'
  name VARCHAR(200) NOT NULL,
  object_type VARCHAR(50) NOT NULL,
  definition_source TEXT NOT NULL,
  depends_on_collections TEXT[] NOT NULL,
  depends_on_edges TEXT[],
  refresh_strategy VARCHAR(50),
  -- Freshness Contract (GPT vòng 3 — gap quan trọng)
  freshness_sla_seconds INT,                      -- SLA: max stale time
  refresh_mode VARCHAR(20),                       -- 'realtime_trigger', 'scheduled', 'on_demand'
  stale_after TIMESTAMPTZ,                        -- khi nào expired
  last_computed_at TIMESTAMPTZ,                   -- lần cuối refresh
  recompute_status VARCHAR(20) DEFAULT 'ok',      -- 'ok', 'stale', 'error'
  stale_reason TEXT,
  -- Standard fields
  status VARCHAR(20) DEFAULT 'active',
  _dot_origin VARCHAR(100),
  date_created TIMESTAMPTZ DEFAULT NOW(),
  date_updated TIMESTAMPTZ DEFAULT NOW(),
  -- Constraints
  CONSTRAINT chk_object_type CHECK (object_type IN (
    'view', 'materialized_view', 'function', 'generated_column',
    'computed_field', 'summary_table', 'matrix', 'inference_snapshot'
  ))
);

§6. Quan hệ với các Điều khác

  • Điều 0-B: 6 lớp composition = 6 lớp trong universal_edges (source_composition_level/target_composition_level)
  • Điều NHẤT QUÁN: 6 headings quan hệ = 6 edge_types trong Matrix
  • Điều 27 (Lifecycle): Edge có lifecycle theo entity; edge status follows entity status
  • Điều 23 (DOT): DOT scan question B kiểm tra edge data correctness

V. ĐIỀU 29 — LUẬT SỐNG (LIVENESS LAW)

"Mọi luật trong Hiến pháp PHẢI tự chạy, tự phát hiện vi phạm, và tự cảnh báo — không dựa vào con người kiểm tra thủ công. Luật không tự chạy = KHÔNG PHẢI LUẬT."

§1. Nguyên tắc

Liveness Law là "luật của các luật" — nó đảm bảo mọi Điều khác trong Hiến pháp đều sống (tự vận hành) chứ không chỉ tồn tại (nằm trong tài liệu).

§2. Universal Rules Engine — NÂNG CẤP VÒNG 3

Engine hoàn chỉnh (không chỉ iterator function):

fn_run_all_rules(triggered_by)
  → Tạo run record trong universal_rule_runs
    → Chạy từng rule theo execution_order
      → Mỗi rule trả standardized output: (collection, entity_id, code, detail, severity)
        → UPSERT violations (dedupe bằng violation_hash)
          → Close violations đã hết (auto-resolve)
            → Ghi run_results
              → Health Check đọc latest run → pass/fail

§3. Schema: Universal Rules Registry

CREATE TABLE universal_rule_registry (
  id SERIAL PRIMARY KEY,
  rule_number INT UNIQUE NOT NULL,
  rule_name VARCHAR(100) NOT NULL,
  description TEXT,
  measurement_type VARCHAR(50) NOT NULL,          -- 'sql_view', 'sql_function', 'dot_contract'
  measurement_source TEXT NOT NULL,               -- view/function name
  severity VARCHAR(20) DEFAULT 'error',           -- 'error' (block), 'warning' (log), 'info' (trend)
  execution_order INT DEFAULT 100,                -- thứ tự chạy (Identity trước, Traceability sau)
  is_active BOOLEAN DEFAULT TRUE,
  is_blocking BOOLEAN DEFAULT TRUE,               -- block deploy nếu violations > 0?
  date_created TIMESTAMPTZ DEFAULT NOW()
);

§4. Schema: Universal Rule Violations — NÂNG CẤP VÒNG 3

CREATE TABLE universal_rule_violations (
  id SERIAL PRIMARY KEY,
  rule_number INT NOT NULL REFERENCES universal_rule_registry(rule_number),
  entity_collection VARCHAR(100) NOT NULL,
  entity_id INT,
  entity_code VARCHAR(50),
  violation_detail TEXT NOT NULL,
  severity VARCHAR(20) NOT NULL,
  violation_hash TEXT NOT NULL,                    -- dedupe key: md5(rule+collection+entity_id+detail)
  evidence JSONB DEFAULT '{}',                    -- raw data cho troubleshooting
  detected_at TIMESTAMPTZ DEFAULT NOW(),
  resolved_at TIMESTAMPTZ,
  resolved_by VARCHAR(100),
  status VARCHAR(20) DEFAULT 'open'               -- 'open', 'resolved', 'acknowledged', 'false_positive'
);

CREATE UNIQUE INDEX uq_open_violation_hash ON universal_rule_violations(violation_hash) WHERE status = 'open';
CREATE INDEX idx_violations_open ON universal_rule_violations(status) WHERE status = 'open';
CREATE INDEX idx_violations_entity ON universal_rule_violations(entity_code);

§5. Schema: Run History — MỚI VÒNG 3

CREATE TABLE universal_rule_runs (
  id SERIAL PRIMARY KEY,
  started_at TIMESTAMPTZ DEFAULT NOW(),
  ended_at TIMESTAMPTZ,
  triggered_by VARCHAR(100),                      -- 'GH_ACTIONS:health_check', 'MANUAL:admin', 'DOT:scan'
  status VARCHAR(20) DEFAULT 'running',           -- 'running', 'completed', 'error'
  total_violations INT DEFAULT 0,
  delta_vs_previous INT DEFAULT 0                 -- +/- so với run trước
);

CREATE TABLE universal_rule_run_results (
  run_id INT NOT NULL REFERENCES universal_rule_runs(id),
  rule_number INT NOT NULL REFERENCES universal_rule_registry(rule_number),
  violations_found INT NOT NULL,
  severity VARCHAR(20),
  PRIMARY KEY (run_id, rule_number)
);

§6. Cơ chế vận hành

Tầng 1 — Phát hiện (Detection):

  • fn_run_all_rules(triggered_by) tạo run → chạy rules theo execution_order → UPSERT violations (dedupe by hash) → auto-close resolved → ghi run_results
  • DOT scan ghi kết quả Rule 7 vào violations table

Tầng 2 — Cảnh báo (Alert):

  • open violations with is_blocking rule → pipeline FAIL
  • Warning rules → log + dashboard, không block
  • Delta vs previous run → trend monitoring

Tầng 3 — Giải quyết (Resolution):

  • Mỗi violation phải có resolved_by + resolved_at khi đóng
  • false_positive phải có reason trong evidence
  • Run history = timeline sức khoẻ hệ thống

§7. Liveness Self-Check

CREATE VIEW v_liveness_self_check AS
SELECT r.rule_number, r.rule_name, r.measurement_source,
  CASE 
    WHEN r.measurement_type = 'sql_view' 
      THEN EXISTS(SELECT 1 FROM information_schema.views WHERE table_name = r.measurement_source)
    WHEN r.measurement_type = 'sql_function'
      THEN EXISTS(SELECT 1 FROM information_schema.routines WHERE routine_name = r.measurement_source)
    ELSE TRUE
  END AS measurement_exists
FROM universal_rule_registry r
WHERE is_active = TRUE;

§8. Quan hệ với các Điều khác

  • Mọi Điều (0-28): Liveness Law kiểm tra tất cả đều "sống"
  • Điều 26 (Counting): verify_counts() = measurement cho Rule 5
  • Điều 24 (Label): Classification check = measurement cho Rule 3
  • Điều 23 (DOT): DOT = sensor (thu thập data Rule 7). Liveness = engine + court record (đo, lưu, phán)

VI. SCHEMA MỚI — DDL CHÍNH THỨC

6.1 universal_edges (core table) — SỬA VÒNG 3

CREATE TABLE universal_edges (
  id SERIAL PRIMARY KEY,
  -- Source
  source_collection VARCHAR(100) NOT NULL,
  source_id INT NOT NULL,
  source_code VARCHAR(50),
  source_composition_level VARCHAR(20) NOT NULL,  -- 'atom','molecule','compound','material','product','building' (SỬA: không dùng INT)
  -- Target
  target_collection VARCHAR(100) NOT NULL,
  target_id INT NOT NULL,
  target_code VARCHAR(50),
  target_composition_level VARCHAR(20) NOT NULL,
  -- Relationship
  edge_type VARCHAR(50) NOT NULL,
  edge_subtype VARCHAR(100),
  weight NUMERIC(5,2) DEFAULT 1.0,
  -- Management
  source_info VARCHAR(200) NOT NULL,              -- 'FK_SYNC:products.category_id' hoặc 'DOT:relate_tool' hoặc 'AI:similarity'
  is_auto_managed BOOLEAN DEFAULT FALSE,          -- TRUE = FK mirror, FALSE = semantic/manual
  symmetry_group_id UUID,                         -- cho GROUP_WITH, SIMILAR_TO pairs
  -- Metadata
  metadata JSONB DEFAULT '{}',
  valid_from TIMESTAMPTZ DEFAULT NOW(),
  valid_to TIMESTAMPTZ,                           -- NULL = currently valid
  -- Standard
  status VARCHAR(20) DEFAULT 'active',
  _dot_origin VARCHAR(100),
  date_created TIMESTAMPTZ DEFAULT NOW(),
  date_updated TIMESTAMPTZ DEFAULT NOW(),
  -- Constraints
  UNIQUE(source_collection, source_id, target_collection, target_id, edge_type),
  CONSTRAINT chk_edge_type CHECK (edge_type IN ('BELONGS_TO','CONTAINS','USES','USED_BY','GROUP_WITH','SIMILAR_TO')),
  CONSTRAINT chk_edge_status CHECK (status IN ('active','deprecated','retired')),
  CONSTRAINT chk_weight_positive CHECK (weight > 0),
  CONSTRAINT chk_no_self_edge CHECK (NOT (source_collection = target_collection AND source_id = target_id AND edge_type IN ('BELONGS_TO','CONTAINS','USES','USED_BY'))),
  CONSTRAINT chk_composition_level CHECK (source_composition_level IN ('atom','molecule','compound','material','product','building')),
  CONSTRAINT chk_target_composition_level CHECK (target_composition_level IN ('atom','molecule','compound','material','product','building'))
);

-- Indexes
CREATE INDEX idx_edges_source ON universal_edges(source_collection, source_id);
CREATE INDEX idx_edges_target ON universal_edges(target_collection, target_id);
CREATE INDEX idx_edges_source_active ON universal_edges(source_collection, source_id, edge_type) WHERE status = 'active';
CREATE INDEX idx_edges_target_active ON universal_edges(target_collection, target_id, edge_type) WHERE status = 'active';
CREATE INDEX idx_edges_type ON universal_edges(edge_type);
CREATE INDEX idx_edges_cross_level ON universal_edges(source_composition_level, target_composition_level);
CREATE INDEX idx_edges_source_code ON universal_edges(source_code);
CREATE INDEX idx_edges_target_code ON universal_edges(target_code);
CREATE INDEX idx_edges_symmetry ON universal_edges(symmetry_group_id) WHERE symmetry_group_id IS NOT NULL;

6.2 lifecycle_log (xem Điều 27 §6)

6.3 derived_objects_registry (xem Điều 28 §5)

6.4 universal_rule_registry (xem Điều 29 §3)

6.5 universal_rule_violations (xem Điều 29 §4)

6.6 universal_rule_runs + universal_rule_run_results (xem Điều 29 §5)

6.7 birth_rejection_log → GỘP VÀO system_issues (SỬA VÒNG 3)

Không tạo bảng riêng. Ghi birth rejections vào bảng system_issues hiện có (Điều 22) với:

  • issue_type = 'birth_rejection'
  • issue_data JSONB chứa: attempted_collection, attempted_code, attempted_name, rejection_reason, rejected_at_step, attempted_payload, caller_origin

Assembly First (Gemini vòng 3): Dùng table có sẵn, giảm số table mới từ 6 → 5.

Tổng kết: 7 objects mới (5 tables + 2 tables phụ)

Object Loại Mô tả
universal_edges TABLE Core — quan hệ toàn hệ thống
lifecycle_log TABLE Lịch sử chuyển trạng thái
derived_objects_registry TABLE Registry đối tượng phái sinh + freshness
universal_rule_registry TABLE Đăng ký 10+ rules
universal_rule_violations TABLE Vi phạm (dedupe by hash)
universal_rule_runs TABLE Lịch sử chạy rules engine
universal_rule_run_results TABLE Kết quả chi tiết per rule per run

VII. DECISION TREE — PHÂN LOẠI OBJECT — MỞ RỘNG VÒNG 3

Có object mới cần quản lý?
│
├─ Nó có identity quản trị độc lập không?
│  │
│  ├─ CÓ — Identity do ai quản lý?
│  │  │
│  │  ├─ PREFIX-NNN (Birth Pipeline) → MANAGED ENTITY (Stream 1)
│  │  │  ├─ Thuộc lớp nào? (Điều 0-B: atom → building)
│  │  │  ├─ Pre-Birth Check → assign code
│  │  │  └─ Registry (Rule 2) + Label (Rule 3)
│  │  │
│  │  └─ PG/Directus native natural key → NATIVE-MANAGED RESOURCE
│  │     └─ Ví dụ: field, trigger, permission, flow (có identity nhưng PG/Directus quản lý)
│  │
│  └─ KHÔNG — Nó phụ thuộc vào object khác?
│     │
│     ├─ Nó là liên kết cấu trúc/semantic giữa entities?
│     │  ├─ Cùng lớp + structural → NATIVE BOND (FK/M2M) + mirror to edges
│     │  ├─ Xuyên lớp → EDGE RECORD (universal_edges only)
│     │  └─ Semantic → EDGE RECORD (universal_edges, is_auto_managed=false)
│     │
│     ├─ Nó là object phái sinh từ object khác?
│     │  └─ CÓ → DERIVED OBJECT → derived_objects_registry (DRV-NNN)
│     │     └─ Types: view, materialized_view, function, computed_field, summary_table, matrix
│     │
│     └─ Nó là log/metric/action?
│        └─ CÓ → Stream 2 (logs) hoặc Stream 3 (actions) — KHÔNG vào registry
│
└─ Object hiện hữu đổi composition_level?
   └─ CÓ → WCR/governance + reclassify pipeline (không tự ý đổi)

VIII. KẾ HOẠCH TRIỂN KHAI

Phase 1: Schema + Core Views (ưu tiên cao nhất)

  1. Tạo 7 tables/objects mới (universal_edges, lifecycle_log, derived_objects_registry, universal_rule_registry, universal_rule_violations, universal_rule_runs, universal_rule_run_results)
  2. Tạo PG views cho 10 Universal Rules
  3. Tạo fn_run_all_rules() nâng cấp + v_liveness_self_check
  4. Tạo fn_pre_birth_check() + fn_retire_gate_check() (dual-source)

Phase 2: Sync + Triggers

  1. Generate FK→edge sync triggers từ catalog (không hand-code)
  2. Tạo Birth Pipeline integration (fn_pre_birth_check là entrypoint)
  3. Tạo lifecycle transition PG functions chuẩn (DOT tools gọi functions, không tự viết logic)

Phase 3: Integration

  1. Tích hợp fn_run_all_rules() vào Health Check GH Actions
  2. Cập nhật Registries UI Layer 5 đọc từ Directus-registered views trên universal_edges (không custom Nuxt query)
  3. DOT tools gọi PG functions chuẩn cho lifecycle transitions

Phase 4: Migration + Reconciliation

  1. Backfill universal_edges từ existing FK relationships
  2. Backfill lifecycle_log cho existing entities (status = 'active', performed_by = 'MIGRATION:v3.0')
  3. Tạo reconciliation jobs: native FK vs edges, rule registry vs actual views, derived freshness
  4. Audit + verify counts

IX. NGUYÊN TẮC AN TOÀN: SOURCE-OF-TRUTH vs MIRROR — MỚI VÒNG 3

Rủi ro lớn nhất (GPT vòng 3): Mirror layer (universal_edges + violations + derived registry) trở thành "hệ thống thứ hai" lệch khỏi source-of-truth → "governance theatre."

5 Nguyên tắc cứng:

  1. Source-of-truth cho mọi entity: Native table + FK/M2M. KHÔNG PHẢI universal_edges.
  2. Mirror chỉ dùng cho: Discovery, UI Layer 5, cross-layer visibility, trend/reporting.
  3. Critical gates (Retire Gate, Pre-Birth, Deploy block): PHẢI đọc source-of-truth TRƯỚC, mirror chỉ bổ sung.
  4. Mirror KHÔNG BAO GIỜ sửa ngược source native.
  5. Reconciliation bắt buộc: Chạy định kỳ so khớp native vs mirror. Mismatch > 0 = system_issue.

PHỤ LỤC A: TỔNG KẾT ĐÓNG GÓP AI COUNCIL (3 VÒNG)

Đóng góp Nguồn Vòng Trạng thái
Chẩn đoán gốc: object-centric → principle-centric Claude 1 ✅ Tích hợp
10 Universal Rules Claude (9) + GPT (Rule 10) 1-2 ✅ Tích hợp
SQL cho 10 rules Gemini 2 ✅ Tích hợp
Pre-Birth Check (mở rộng 9 validations) GPT 2-3 ✅ Tích hợp
Universal Matrix Table → universal_edges Gemini 2 ✅ Tích hợp
Birth Signal / Metadata Hub Gemini 2 ✅ Tích hợp
FK integrity + edges visibility (hoà giải) Claude 2 ✅ Tích hợp
Universal Rules Engine (nâng cấp) GPT 2-3 ✅ Tích hợp
Derived Objects + Freshness Contract GPT 2-3 ✅ Tích hợp
State Machine + merged/terminal_reason tách GPT + Gemini 2-3 ✅ Tích hợp
Liveness self-check Claude 2 ✅ Tích hợp
composition_level thay layer (thuật ngữ) GPT 3 ✅ Tích hợp
birth_rejection → system_issues (Assembly First) Gemini 3 ✅ Tích hợp
Retire Gate dual-source GPT 3 ✅ Tích hợp
Violation dedupe (hash) + run history GPT 3 ✅ Tích hợp
Symmetric edge management GPT 3 ✅ Tích hợp
Source-of-truth vs Mirror principles GPT + Claude 3 ✅ Tích hợp (§IX)
Decision tree mở rộng (native-managed, bond, reclassify) GPT 3 ✅ Tích hợp

PHỤ LỤC B: CHANGELOG VÒNG 3

# Change Nguồn Lý do
1 Tách lifecycle: status + terminal_reason GPT merged khác bản chất với deprecated
2 Đổi source_layer → source_composition_level VARCHAR GPT Đúng thuật ngữ Điều 0-B, tránh nhầm layer/tầng
3 Gộp birth_rejection_log → system_issues Gemini Assembly First: dùng table có sẵn
4 Thêm freshness contract cho derived_objects GPT Gap quan trọng: registry mà không có SLA = danh bạ chết
5 Thêm violation_hash + evidence cho dedupe GPT + Gemini Tránh trùng violation mỗi lần chạy
6 Thêm 2 bảng run history (runs + results) GPT Engine cần snapshot/trend, không chỉ current state
7 Retire Gate dual-source (native FK + edges) GPT Mirror có thể trễ, critical gate phải đọc truth
8 Schema constraints (CHECK, partial indexes) GPT + Gemini Production-ready cần constraints chặt