Điều 43 — Luật Bản đồ Hệ thống v1.2 FINAL rev 6 BAN HÀNH
ĐIỀU 43 — LUẬT BẢN ĐỒ HỆ THỐNG
(System Context Law) — v1.2 FINAL BAN HÀNH
Version: v1.2 FINAL (rev 6 — thêm cột
target_db§5.7 cho multi-DB dispatch theo Assembly First NT8, 2026-04-17 Fix 12 Desktop) Ngày BAN HÀNH: 2026-04-17 (S178 Fix 11) Tác giả amend: Claude Desktop. Amend thuần kỹ thuật tuân HP v4.6.1 NT2/NT4/NT11. Triết lý v1.1 giữ 100%. Council: R1 Gemini 9.5 MINOR + GPT 6.9 CHANGES → apply 7 patches P1-P7. R2 Gemini 10 FINAL + GPT 8.8 MINOR → apply 2 patches P8+P9 security+contract inline. Post-enact rà 13 NT Desktop phát hiện 2 lỗ hổng tầng SQL DDL mà Council bỏ sót (P10 GRANT + P11 Trigger) → patch inline rev 2 KHÔNG qua Council (clarification, không đổi semantic). 0 blocker. BAN HÀNH. Backup v1.1:dieu43-system-context-law-v1-1-backup.md.
§0. BỐI CẢNH AMEND v1.1 → v1.2
Fix 11 rà soát phát hiện 16 điểm vi phạm HP (NT2+NT4+NT11) do v1.1 có nhiều hardcode — mở rộng hệ thống = sửa code = vi phạm tự động 100%.
11 patches total áp dụng:
- P1-P7 từ R1: schema/config hóa (section_count, check_type, section_definitions data binding, output root, grace period, cron wording, CẤM fallback)
- P8+P9 từ R2: security guards SQL executor + render_config fail-fast
- P10+P11 từ Desktop rà post-enact (rev 2): GRANT role cross-DB + DEFAULT PRIVILEGES (thay GRANT từng table) + Trigger function body đọc dot_config runtime (thay bind pattern vào WHEN)
Triết lý v1.1 giữ 100%: 3 lớp Meta-Incomex, 8 bước build, 2 checksum, 2-phase publish, DOT cặp, AP-24.
§1. MỤC TIÊU (giữ v1.1)
5 mục tiêu MT1-MT5: tổng cảnh 30s + sống theo hệ thống + 3 lớp + không lạc lối + xem bằng mắt thường.
§2. PHẠM VI (giữ v1.1)
§3. NGUYÊN TẮC NỀN TẢNG
Đ43 kế thừa 13 NT HP v4.6.1. v1.2 không amend HP.
| NT | Tên | v1.2 chứng minh |
|---|---|---|
| NT1 | SSOT | Reference tables + dot_config = SSOT |
| NT2 | Tự động 100% | ★ Core amend — đọc config + generic executor |
| NT3 | DOT 100% | 2 DOT cặp giữ |
| NT4 | Thay đổi = config | ★ Core amend — UPDATE SQL thay redeploy |
| NT5 | Tự phát hiện | + retry policy queue |
| NT7 | Dual-trigger | Giữ |
| NT8 | Assembly First | Giữ |
| NT9 | Không chắc = sai | Giữ |
| NT10 | PG trước text | ★ Section + health + executor sống PG |
| NT11 | Khai tối thiểu | ★ pg_database catalog thay hardcode 3 |
| NT12 | DOT cặp | Giữ |
| NT13 | PG Native | Giữ |
§3.1 — Clause Vận hành AI (giữ v1.1)
Mọi AI/agent phiên mới BẮT BUỘC đọc PROJECT_MAP.md trước hành động. 3 mức enforce A/B/C.
§4. BẢN ĐỒ 3 LỚP META-INCOMEX (giữ v1.1)
§5. SCHEMA PG
§5.1 — context_trigger_sources (giữ v1.1 — 6 rows enum)
§5.2 — context_pack_requests — ★ retry support
CREATE TABLE context_pack_requests (
id BIGSERIAL PRIMARY KEY,
requested_at TIMESTAMPTZ NOT NULL DEFAULT now(),
trigger_source TEXT NOT NULL REFERENCES context_trigger_sources(code),
dedupe_bucket TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL CHECK (status IN ('pending','running','done','skipped','failed')) DEFAULT 'pending',
detail JSONB NOT NULL DEFAULT '{}',
coalesced_events_count INT DEFAULT 0,
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
manifest_id BIGINT,
retry_count INT NOT NULL DEFAULT 0,
next_retry_at TIMESTAMPTZ,
last_error TEXT
);
CREATE UNIQUE INDEX uq_context_pack_requests_open
ON context_pack_requests(trigger_source, dedupe_bucket)
WHERE status IN ('pending','running');
§5.3 — context_pack_manifest — ★ P1: section_count > 0
CREATE TABLE context_pack_manifest (
id BIGSERIAL PRIMARY KEY,
generated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
published_at TIMESTAMPTZ,
git_commit TEXT NOT NULL,
trigger_source TEXT NOT NULL REFERENCES context_trigger_sources(code),
law_count INT NOT NULL,
dot_count INT NOT NULL,
entity_count BIGINT NOT NULL,
species_count INT NOT NULL,
db_count INT NOT NULL,
total_size_bytes BIGINT NOT NULL,
section_count INT NOT NULL CHECK (section_count > 0),
logical_checksum_sha256 TEXT NOT NULL,
file_checksum_sha256 TEXT NOT NULL,
publish_status TEXT NOT NULL CHECK (publish_status IN ('staging','live','failed')) DEFAULT 'staging',
kb_mirror_status TEXT NOT NULL CHECK (kb_mirror_status IN ('pending','live','failed')) DEFAULT 'pending',
publish_step TEXT,
health_status TEXT NOT NULL CHECK (health_status IN ('healthy','warn','stale','fail')),
generation_duration_ms INT,
_dot_origin TEXT NOT NULL DEFAULT 'unknown'
);
CREATE INDEX idx_cpm_generated_at ON context_pack_manifest(generated_at DESC);
CREATE INDEX idx_cpm_logical_checksum ON context_pack_manifest(logical_checksum_sha256);
CREATE INDEX idx_cpm_publish_status ON context_pack_manifest(publish_status);
DOT build fill section_count = (SELECT COUNT(*) FROM context_pack_section_definitions WHERE is_active=true) tại build time.
§5.4 — context_pack_sections — ★ FK thay CHECK enum
CREATE TABLE context_pack_sections (
id BIGSERIAL PRIMARY KEY,
manifest_id BIGINT NOT NULL REFERENCES context_pack_manifest(id) ON DELETE CASCADE,
section_code TEXT NOT NULL REFERENCES context_pack_section_definitions(code),
file_path TEXT NOT NULL,
kb_document_path TEXT,
size_bytes INT NOT NULL CHECK (size_bytes >= 0),
line_count INT NOT NULL CHECK (line_count >= 0),
logical_checksum_sha256 TEXT NOT NULL,
file_checksum_sha256 TEXT NOT NULL,
UNIQUE(manifest_id, section_code)
);
§5.5 — View v_context_pack_latest (giữ v1.1 + section_code)
§5.6 — Seed dot_operations (giữ v1.1 — 2 ops CONTEXT_PACK_BUILD/VERIFY)
§5.7 — context_pack_section_definitions — ★ P3 data binding + P8 path whitelist
CREATE TABLE context_pack_section_definitions (
code TEXT PRIMARY KEY,
name TEXT NOT NULL,
order_index INT NOT NULL UNIQUE,
output_filename TEXT NOT NULL UNIQUE,
format TEXT NOT NULL CHECK (format IN ('markdown','json','mermaid')),
min_size_bytes INT NOT NULL CHECK (min_size_bytes >= 0),
target_size_bytes INT NOT NULL CHECK (target_size_bytes >= min_size_bytes),
max_size_bytes INT CHECK (max_size_bytes IS NULL OR max_size_bytes >= target_size_bytes),
template_kb_path TEXT,
query_kb_path TEXT,
data_source TEXT NOT NULL CHECK (data_source IN ('pg_query','filesystem_scan','static','kb_query','custom')),
target_db TEXT CHECK (target_db IN ('directus','incomex_metadata','workflow')),
render_config JSONB NOT NULL DEFAULT '{}',
is_active BOOLEAN NOT NULL DEFAULT true,
_dot_origin TEXT NOT NULL DEFAULT 'dieu43_v1_2_seed',
-- ★ P8 R2: CHECK path whitelist cho query_kb_path + template_kb_path
CONSTRAINT chk_query_kb_path_whitelist CHECK (
query_kb_path IS NULL OR query_kb_path LIKE 'knowledge__current-state__queries__%'
),
CONSTRAINT chk_template_kb_path_whitelist CHECK (
template_kb_path IS NULL OR template_kb_path LIKE 'knowledge__current-state__templates__%'
),
-- ★ rev 6: target_db NOT NULL khi data_source cần query DB; NULL khi static
CONSTRAINT chk_target_db_consistency CHECK (
(data_source IN ('pg_query','kb_query') AND target_db IS NOT NULL)
OR (data_source IN ('static','filesystem_scan','custom') AND target_db IS NULL)
)
);
-- Seed 8 section mặc định (rev 6: thêm target_db theo Assembly First NT8)
INSERT INTO context_pack_section_definitions(code, name, order_index, output_filename, format, min_size_bytes, target_size_bytes, max_size_bytes, data_source, target_db, render_config) VALUES
('project_map', 'Project Map', 1, 'PROJECT_MAP.md', 'markdown', 3000, 15000, 20000, 'pg_query', 'directus', '{"placeholder_style":"mustache"}'),
('laws_index', 'Laws Index', 2, 'LAWS_INDEX.md', 'markdown', 1000, 8000, 15000, 'kb_query', 'incomex_metadata', '{"source_patterns_key":"context_pack_watched_key_patterns"}'),
('dot_registry', 'DOT Registry', 3, 'DOT_REGISTRY.md', 'markdown', 2000, 20000, 30000, 'pg_query', 'directus', '{}'),
('entities_overview', 'Entities Overview', 4, 'ENTITIES_OVERVIEW.md', 'markdown', 500, 5000, 10000, 'pg_query', 'directus', '{"group_by":"species"}'),
('db_map', 'Database Map', 5, 'DB_MAP.md', 'markdown', 1000, 10000, 15000, 'pg_query', 'directus', '{"whitelist_key":"context_pack_scan_db_whitelist"}'),
('red_zones', 'Red Zones', 6, 'RED_ZONES.md', 'markdown', 500, 3000, 8000, 'static', NULL, '{}'),
('architecture_mmd', 'Architecture Diagram',7, 'ARCHITECTURE.mmd', 'mermaid', 500, 8000, 15000, 'pg_query', 'directus', '{"diagram_type":"flowchart"}'),
('project_map_json', 'Project Map JSON', 8, 'project-map.json', 'json', 200, 2000, 5000, 'pg_query', 'directus', '{}')
ON CONFLICT (code) DO NOTHING;
★ P9: render_config contract — key whitelist:
Keys cho phép trong render_config (v1.2 seed spec — mở rộng qua phụ lục):
placeholder_style:'mustache'(mặc định) |'jinja'date_format: ISO format string (mặc định'YYYY-MM-DD')group_by: field name cho pg_query data sourcewhitelist_key: reference tớidot_configkeysource_patterns_key: reference tớidot_configkeydiagram_type:'flowchart'|'sequence'|'class'(cho mermaid)filters: JSON object with WHERE-clause builders
Key lạ → renderer FAIL-FAST + log WARN, KHÔNG silent ignore. Phụ lục Đ43 §15.2 Render Config Spec sẽ tài liệu hóa đầy đủ keys + giá trị hợp lệ.
Thêm section thứ 9 (ví dụ MCP_SERVERS.md):
INSERT INTO context_pack_section_definitions VALUES
('mcp_servers', 'MCP Servers', 9, 'MCP_SERVERS.md', 'markdown', 500, 3000, 5000,
'knowledge__current-state__templates__mcp-servers.mustache', -- template (path whitelist, __ separator)
'knowledge__current-state__queries__mcp-servers-list.sql', -- query (path whitelist, __ separator)
'kb_query', '{"placeholder_style":"mustache"}',
true, 'manual_insert');
→ INSERT row + upload SQL + template vào path whitelist. KHÔNG sửa code.
§5.8 — context_pack_health_checks — ★ P2 generic executor + P8 SQL security
CREATE TABLE context_pack_health_checks (
code TEXT PRIMARY KEY,
name TEXT NOT NULL,
executor_type TEXT NOT NULL CHECK (executor_type IN ('builtin','sql','function')),
executor_ref TEXT NOT NULL,
threshold_config JSONB NOT NULL DEFAULT '{}',
severity_on_fail TEXT NOT NULL CHECK (severity_on_fail IN ('warn','critical')),
is_active BOOLEAN NOT NULL DEFAULT true,
order_index INT NOT NULL UNIQUE,
_dot_origin TEXT NOT NULL DEFAULT 'dieu43_v1_2_seed',
-- ★ P8 R2: SQL executor path phải whitelist
CONSTRAINT chk_sql_executor_path CHECK (
executor_type != 'sql' OR executor_ref LIKE 'knowledge__current-state__queries__%'
)
);
-- Seed 9 H1-H9 mặc định (tất cả builtin)
INSERT INTO context_pack_health_checks(code, name, executor_type, executor_ref, threshold_config, severity_on_fail, order_index) VALUES
('H1','Manifest LIVE age', 'builtin','check_manifest_age', '{"critical_hours":6,"warn_hours":3}', 'critical', 1),
('H2','Section file exists', 'builtin','check_section_exists', '{}', 'critical', 2),
('H3','Section file_checksum match', 'builtin','check_checksum_match', '{}', 'critical', 3),
('H4','KB mirror diff', 'builtin','check_kb_mirror_diff', '{"warn_pct":1,"critical_pct":5}', 'warn', 4),
('H5','PROJECT_MAP size', 'builtin','check_section_size', '{"section":"project_map","warn_kb":15,"critical_kb":20}', 'warn', 5),
('H6','Required headers', 'builtin','check_section_headers', '{}', 'critical', 6),
('H7','Mermaid parse OK', 'builtin','check_mermaid_parse', '{"section":"architecture_mmd"}', 'critical', 7),
('H8','JSON schema valid', 'builtin','check_json_valid', '{"section":"project_map_json"}', 'critical', 8),
('H9','Publish state consistency', 'builtin','check_publish_state', '{"staging_timeout_min":15}', 'critical', 9),
('H11','Description Coverage', 'sql','knowledge__current-state__queries__health-h11-description-coverage.sql', '{"warn_threshold":0}', 'warn', 11)
ON CONFLICT (code) DO NOTHING;
★ P8 R2 — SQL executor SECURITY GUARDS (BẮT BUỘC khi executor_type='sql'):
Verify script khi load SQL từ executor_ref hoặc load query từ query_kb_path (ở §5.7) PHẢI tuân 5 guard:
- Path whitelist — CHECK constraint PG + verify script double-check: path CHỈ trong
knowledge__current-state__queries__%. Path khác → REJECT + log ERROR. - Statement token blocker — reject SQL chứa các token nguy hiểm (case-insensitive):
INSERT,UPDATE,DELETE,ALTER,DROP,TRUNCATE,GRANT,REVOKE,COPY,DO,CALL,CREATE,VACUUM,ANALYZE,GRANT,SET SESSION,SET ROLE. Reject SQL multiple statement (;trong body sau parse). - Read-only DB role — executor runtime dùng PG role
context_pack_readonly. ★ P10 rev 2 (NT2+NT4): Cấp quyền quaGRANT SELECT ON ALL TABLES IN SCHEMA public TO context_pack_readonly+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO context_pack_readonly— áp dụng cho MỌI DB Đ43 cần đọc (directus+incomex_metadata+workflowsau này). CẤMGRANT SELECTtừng table riêng lẻ (mai thêm table nguồn mới = ALTER GRANT tay = vi phạm NT2+NT4). KHÔNG dùngdirectushayworkflow_adminđể chạy executor SQL. - Read-only transaction — wrap executor trong
BEGIN READ ONLY; ... COMMIT;. Force fail nếu query cố ghi. - Timeout cứng —
SET LOCAL statement_timeout = '30s'trước mỗi query. Vượt → abort + log.
5 guard áp dụng cho CẢ data_source='kb_query' (§5.7) và executor_type='sql' (§5.8). Vi phạm bất kỳ guard nào → verify script abort + fn_log_issue CRITICAL.
Thêm H10 với executor_type='sql':
-- Upload SQL query vào path whitelist (kb_documents.key dùng '__' separator — rev 3)
-- knowledge__current-state__queries__health-h10-dot-active.sql:
-- SELECT count(*) as actual_count FROM dot_tools WHERE status='active';
INSERT INTO context_pack_health_checks VALUES
('H10','DOT active count > threshold',
'sql', 'knowledge__current-state__queries__health-h10-dot-active.sql',
'{"threshold":300,"comparator":"gt","result_field":"actual_count"}',
'warn', 10, true, 'manual_insert');
→ INSERT row + upload SQL path whitelist. KHÔNG sửa verify.sh.
§5.9 — dot_config keys Đ43 (★ P4+P6)
INSERT INTO dot_config(key, value, description) VALUES
('context_pack_scan_paths',
'["/opt/incomex/dot/bin","/opt/incomex/web/app","/opt/incomex/deploy","/opt/incomex/scripts"]',
'JSONB array: folders scan'),
('context_pack_scan_db_whitelist',
'[]',
'JSONB array: DB names. Rỗng → pg_database catalog (NT11)'),
('context_pack_watched_key_patterns',
'["knowledge__dev__laws__%","knowledge__dev__ssot__%","knowledge__dev__architecture__%"]',
'JSONB array: KB key patterns trigger rebuild. kb_documents.key dùng __ separator do Agent Data _fs_key() encoding legacy Firestore (trước S109, xem s170-deep-investigation). Nếu S170 PA5 approved migrate về / → amend rev 4 đảo ngược + ALTER 3 CHECK §5.7+§5.8 (TD-S178-19).'),
('context_pack_retry_policy',
'{"max_retries":3,"backoff_seconds":[60,300,1800]}',
'JSON: retry cho build failed'),
('context_pack_mode',
'warn',
'warn|block — grace enforcement §10'),
('context_pack_output_root',
'/opt/incomex/context-pack',
'Thư mục gốc output. Mặc định path cũ. UPDATE để chuyển vị trí.'),
('context_pack_grace_period_days',
'7',
'Grace period Đ43 §10.')
ON CONFLICT (key) DO NOTHING;
§6. 8 BƯỚC QUY TRÌNH — AMEND CORE
Bước 1 PRECHECK, Bước 2 TRY-LOCK — giữ v1.1.
Bước 3 QUERY PG: đọc context_pack_scan_db_whitelist, rỗng → pg_database catalog. CẤM hardcode số DB.
Bước 4 SCAN FS: đọc context_pack_scan_paths, loop array. Folder không tồn tại → WARN + skip. CẤM hardcode folder.
Bước 5 GENERATE + 2 checksum:
- Query
context_pack_section_definitions WHERE is_active=true ORDER BY order_index - Với mỗi section:
- Load template từ
template_kb_path(path whitelist).template_kb_pathNULL → FAIL-FAST + log ERROR. CẤM fallback built-in renderer trong code. - Load data theo
data_source; nếukb_query→ load SQL từquery_kb_path(path whitelist) + áp 5 guard §5.8.query_kb_pathNULL khidata_source IN ('kb_query','pg_query')→ FAIL-FAST. - ★ rev 6 (NT8 Assembly First + NT11): Dispatch query theo
section_definitions.target_db— connect đúng PG DB (directus/incomex_metadata/workflow) qua rolecontext_pack_readonly(cross-DB DEFAULT PRIVILEGES §11 Bước 6.4). CẤM hardcode target DB trong code. CẤM magic comment trong SQL body để định DB (vi phạm NT1 SSOT metadata). - Apply
render_configtheo contract §5.7 key whitelist; key lạ → FAIL-FAST - Render vào
$OUTPUT_ROOT/$build_id/$output_filename - Volatile header BẮT BUỘC đầu mỗi file, format theo
formatcủa section:- markdown / mermaid: exact delimiters mở/đóng, 4 dòng key
<key>: <value>ở giữa.<!-- VOLATILE HEADER -->generated_at: 2026-04-17T10:30:00Zbuild_id: 20260417-103000-abc123git_commit: d1b2a3c4trigger_source: on_demand<!-- /VOLATILE HEADER --> - json: key
_volatile_headerở đầu object, value là object 4 field:{ "_volatile_header": { "generated_at": "2026-04-17T10:30:00Z", "build_id": "20260417-103000-abc123", "git_commit": "d1b2a3c4", "trigger_source": "on_demand" }, ...} - Strip rule cho logical_checksum:
- markdown / mermaid:
sed '/<!-- VOLATILE HEADER -->/,/<!-- \/VOLATILE HEADER -->/d'block-delete (inclusive 2 delimiter lines + 4 key lines giữa). - json:
jq -S 'del(._volatile_header)'— canonicalize bằng-Ssort keys trước khi hash để tránh key order non-determinism.
- markdown / mermaid:
logical_checksum_sha256= sha256 body sau strip.file_checksum_sha256= sha256 file nguyên bao gồm volatile header.- Common runtime fields bắt buộc 4:
generated_at(ISO 8601 UTC),build_id,git_commit(5-tier fallback, có thể ='unknown'),trigger_source(6 enum §5.1). Sectionstaticvẫn PHẢI có volatile header (renderer inject).
- markdown / mermaid: exact delimiters mở/đóng, 4 dòng key
- Load template từ
- 2 checksum: giữ v1.1.
- CẤM hardcode section list, output path.
Bước 6 VALIDATE: min/max size từ context_pack_section_definitions. CẤM hardcode trong code.
Bước 7 2-PHASE PUBLISH: giữ v1.1 + dùng $OUTPUT_ROOT.
Bước 8 RELEASE:
- Fail: đọc
context_pack_retry_policy.retry_count < max_retries→ UPDATE retry pending. retry_count >= max_retries→ status='failed' +fn_log_issueCRITICAL + APR.
§6.X CẤM HARDCODE (wording đanh thép):
- CẤM hardcode: section list, folder list, DB list, law pattern, min_size/max_size, health threshold, output root, health check handler logic khi sql/function.
- CẤM fallback hardcode giá trị mặc định khi JSONB thiếu key.
- CẤM switch-case hardcode tên check trong verify script.
- CẤM executor_type='sql' không tuân 5 guard §5.8.
- ★ rev 4 (NT2+NT4): CẤM case-dispatch per-section code (ví dụ
build_section_project_map(),build_section_dot_registry(), switch-case theocode...). Mọi section PHẢI render qua generic dispatcher đọcsection_definitions.template_kb_path+data_source+render_config, pattern giống §5.8 health_checks generic executor. Thêm section mới = INSERT row + upload template KB, 0 sửa code. - ★ rev 6 (NT1+NT8+NT11): CẤM hardcode target DB trong code renderer. Mọi query DB name PHẢI đọc từ
context_pack_section_definitions.target_db(§5.7 schema) + CHECK constraintchk_target_db_consistencyenforce. Thêm DB nguồn mới (ví dụworkflowkhi active) = INSERT row vớitarget_db='workflow'+ GRANT DEFAULT PRIVILEGEScontext_pack_readonlycho DB đó (§11 Bước 6.4). CẤM magic comment trong SQL body (ví dụ-- DB: incomex_metadata) để define target — metadata phải ở schema PG, không lẫn với data. - ★ P10 rev 2 (NT2+NT4): CẤM
GRANT SELECTtừng table riêng lẻ chocontext_pack_readonly. PHẢI dùngGRANT SELECT ON ALL TABLES IN SCHEMA public+ALTER DEFAULT PRIVILEGES, áp cross-DB. Thêm table nguồn mới = table tự có quyền đọc, không sửa code, không ALTER tay. - ★ P11 rev 2 (NT2+NT4): CẤM bind pattern cố định vào
WHENclause của trigger on-law-enact. PHẢI implement trigger function body PL/pgSQL SELECTdot_config.context_pack_watched_key_patternstại runtime — UPDATE JSONB pattern phải có hiệu lực ngay ở event tiếp theo, KHÔNG cần DROP+CREATE trigger. - Mọi giá trị phải từ PG reference tables hoặc
dot_confighoặc path whitelist KB.
§7. OUTPUT FILES
Số + tên + size: tuân context_pack_section_definitions. Bảng §5.7 seed 8 section — không phải ràng buộc cứng. Template mặc định sống KB path whitelist.
§8. DOT GOVERNANCE
§8.1 — dot-context-pack-build
| Field | Value |
|---|---|
code |
DOT-CONTEXT-PACK-BUILD |
tier |
B |
domain |
context.pack |
operation |
CONTEXT_PACK_BUILD |
trigger_type |
cron |
paired_dot |
DOT-CONTEXT-PACK-VERIFY |
coverage_status |
complete |
cron_schedule |
0 */3 * * * — seed mặc định. Đổi qua UPDATE dot_tools SET cron_schedule=.... Không bất biến trong luật. |
file_path |
/opt/incomex/dot/bin/dot-context-pack-build.sh |
_dot_origin |
dieu43_enacted |
extra_metadata |
{"secondary_triggers":["on_demand","on_deploy","on_law_enact","on_dot_register"]} |
§8.2 — dot-context-pack-verify
| Field | Value |
|---|---|
code |
DOT-CONTEXT-PACK-VERIFY |
tier |
A |
cron_schedule |
30 */3 * * * — seed mặc định — đổi qua UPDATE |
paired_dot |
DOT-CONTEXT-PACK-BUILD |
operation |
CONTEXT_PACK_VERIFY |
_dot_origin |
dieu43_enacted |
§9. HEALTH CHECKS — Generic Executor + CẤM fallback
Tuân context_pack_health_checks table (§5.8 seed 9 H1-H9 builtin).
Verify script logic:
FOR check IN (SELECT * FROM context_pack_health_checks WHERE is_active=true ORDER BY order_index):
IF check.executor_type = 'builtin':
invoke handler ${check.executor_ref} with check.threshold_config JSONB
ELIF check.executor_type = 'sql':
verify path whitelist (§5.8 P8 guard 1) — REJECT nếu fail
load SQL from KB at check.executor_ref
verify no dangerous tokens (§5.8 P8 guard 2) — REJECT nếu fail
exec with context_pack_readonly role + READ ONLY TX + statement_timeout=30s (guard 3+4+5)
compare result with check.threshold_config
ELIF check.executor_type = 'function':
call PG function check.executor_ref(check.threshold_config)
IF FAIL:
fn_log_issue(severity=check.severity_on_fail, category=check.executor_ref, ...)
★ CẤM TUYỆT ĐỐI (P5 R1 + P8 R2):
- CẤM hardcode threshold value trong verify script (ví dụ
if age > 6h then critical). PHẢI đọcthreshold_configJSONB. - CẤM switch-case hardcode tên check. PHẢI lookup
executor_type+executor_ref. - CẤM fallback giá trị mặc định khi JSONB thiếu key. PHẢI fail-fast + log nếu config incomplete.
- CẤM executor_type='sql' load từ path ngoài
knowledge/current-state/queries/%. - CẤM SQL statement có token DML/DDL/privilege.
- CẤM executor SQL chạy với role
directus/workflow_admin. PHẢI dùngcontext_pack_readonly.
Thêm H10+ tương lai: INSERT row với executor_type 'builtin' (reuse handler), 'sql' (upload SQL KB), hoặc 'function' (CREATE FUNCTION). KHÔNG sửa verify.sh.
§9.1 — Description Coverage (Nguyên tắc Xưng Danh)
Mọi đối tượng được quản lý trong hệ thống registry phải có trường description không rỗng. Thiếu description = thiếu sót từ khai sinh, phải bổ sung.
Nguyên tắc scale tự động: H11 scan tất cả bảng trong schema public có cột description (query information_schema.columns). Mỗi row có description IS NULL OR description = '' → ghi system_issues severity=WARNING, issue_class='missing_description'. PROJECT_MAP hiển thị tổng count thiếu mô tả. Thêm bảng mới có cột description → tự vào scope, zero config.
Áp dụng: DOT, domain, collection, module, và mọi entity type tương lai. Backfill 1 lần cho entity hiện có, dùng mãi mãi. Tạo mới thiếu description = vi phạm.
§10. GRACE PERIOD + ENFORCE — config hóa
Grace: dot_config.context_pack_grace_period_days (seed 7 ngày §5.9). Đổi = UPDATE SQL.
Sau grace expire AND 0 drift 3 ngày + 0 missing + mirror LIVE + H1-H9 PASS → UPDATE dot_config SET value='block' WHERE key='context_pack_mode'.
Block: thiếu > 6h → block worker. AI không declare → AP-24 CRITICAL.
§11. BOOTSTRAP (BLOCK 1) — 17 BƯỚC
- Create
context_trigger_sources+ seed 6 rows - Create
context_pack_requests+ retry cols + unique index - Create
context_pack_manifest(section_count > 0) - Create
context_pack_sections(FK section_code) - Create view
v_context_pack_latest - Seed
dot_operations2 rows (CONTEXT_PACK_*) 6.1. Createcontext_pack_section_definitions+ path whitelist CHECK + target_db column + chk_target_db_consistency CHECK (rev 6) + seed 8 rows 6.2. Createcontext_pack_health_checks+ SQL path whitelist CHECK + seed 9 rows builtin 6.3. Seed 7dot_configkeys 6.4. ★ P8 R2 + P10 rev 2: Create PG rolecontext_pack_readonly(CLUSTER-level, 1 lần). Với MỖI DB Đ43 cần đọc (directus,incomex_metadata, sau nàyworkflow):
CẤM GRANT từng table riêng lẻ. Table sinh sau cũng tự có quyền đọc — mở rộng section query = INSERT row mới, không ALTER GRANT, không sửa code.GRANT USAGE ON SCHEMA public TO context_pack_readonly;GRANT SELECT ON ALL TABLES IN SCHEMA public TO context_pack_readonly;ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO context_pack_readonly; - Tạo folders
/opt/incomex/context-pack{,.tmp,-staging}/+$OUTPUT_ROOT(Phase 2 đã DONE 2026-04-17 Fix 11) - Tạo KB folders
context-pack/+context-pack-staging/(Phase 3 DONE) - Deploy 2 DOT scripts (
build.sh+verify.sh) - Register 2 DOT qua
dot-dot-register(11 fields Đ35 v5.1) - Install cron (seed 0 */3 + 30 */3)
- Install PG triggers on-law-enact + on-dot-register. ★ P11 rev 2: Trigger on-law-enact implement dưới dạng function PL/pgSQL body SELECT patterns từ
dot_config.context_pack_watched_key_patternstại RUNTIME mỗi lần fire — KHÔNG bind pattern vàoWHEN (NEW.key LIKE '...')clause cố định. UPDATE JSONBdot_configphải có hiệu lực ngay ở event tiếp theo, KHÔNG cần DROP+CREATE trigger. Ví dụ body:CREATE FUNCTION fn_context_pack_on_law_enact() RETURNS TRIGGER AS $$DECLARE p TEXT;BEGIN FOR p IN SELECT jsonb_array_elements_text(value::jsonb) FROM dot_config WHERE key='context_pack_watched_key_patterns' LOOP IF NEW.key LIKE p THEN PERFORM pg_notify('context_pack_event', 'law_enact'); RETURN NEW; END IF; END LOOP; RETURN NEW;END; $$ LANGUAGE plpgsql; - Chạy build lần đầu
trigger_source='system_init'→ verify 8 section → promote live UPDATE dot_config SET value=NOW() AT TIME ZONE 'UTC' WHERE key='law_v43_enacted_at'
§12. SUCCESS METRICS (giữ v1.1)
§13. GOVERNANCE + AP-24 (giữ v1.1)
§14. RETROFIT CLAUSE (giữ v1.1)
§15. PHỤ LỤC
File riêng dieu43-phu-luc-ban-do-he-thong.md living doc.
- §15.1 — Snapshot hệ thống mỗi tháng
- §15.2 — ★ Render Config Spec (P9 R2 — contract đầy đủ render_config keys + giá trị hợp lệ)
- §15.3 — Output templates chi tiết
- §15.4 — Pipeline Mermaid/Structurizr
- §15.5 — Deployment log
- §15.6 — Drift postmortems
- §15.7 — AI compliance metrics A/B/C
- §15.8 — Coalesced events + skipped_unchanged stats
§16. LIÊN KẾT LUẬT KHÁC
| Luật | Quan hệ |
|---|---|
| HP v4.6.3 NT1-NT13 | Tuân đầy đủ — §3 bảng chứng minh. Extension vận hành ops_code_inventory được theo dõi ở living-doc/context-pack theo enact S178 Fix 15. |
| Đ0-G Birth | Đếm entities từ birth_registry |
| Đ22 Self-healing | H1-H10+ fail → fn_log_issue → APR. Retry policy queue |
| Đ26 Pivot | KHÔNG dùng pivot_count() |
| Đ33 v2.0 §14 + §15 | Access control + CI/Deploy hooks |
| Đ35 v5.1 | 2 DOT tuân §4.1 11 fields + §5.1 CẤM POST partial |
| Đ36 Collection Protocol | ENTITIES_OVERVIEW join collection_registry |
| Đ38 Văn bản Quy phạm | v1.2 amend theo format luật |
| Đ41 Deploy | on-deploy chỉ sau Bước 6.5 is_known_good=true |
| KB Protection | Trigger on-law-enact dùng context_pack_watched_key_patterns |
| Anti-patterns | AP-24 |
§17. CHANGELOG
| Version | Ngày | Thay đổi |
|---|---|---|
| v1.0 DRAFT | 2026-04-16 sáng | Soạn lần đầu |
| v1.0 DRAFT patch | 2026-04-16 trưa | §3 thêm NT12+NT13 |
| v1.1 DRAFT | 2026-04-16 chiều | 14 patches Council R1 |
| v1.1 FINAL | 2026-04-16 chiều | BAN HÀNH. 4 patches R2 inline. Backup |
| v1.2 DRAFT rev 1 | 2026-04-17 Fix 11 | 5 khoản amend thuần kỹ thuật |
| v1.2 DRAFT rev 2 | 2026-04-17 Fix 11 post R1 | 7 patches P1-P7 |
| v1.2 FINAL | 2026-04-17 Fix 11 BAN HÀNH | Council 2 vòng DONE. R1 Gemini 9.5 MINOR + GPT 6.9 CHANGES → 7 patches. R2 Gemini 10 FINAL + GPT 8.8 MINOR → 2 patches inline: P8 SQL executor security (5 guards: path whitelist + token blocker + readonly role + READ ONLY TX + timeout 30s) + CHECK constraint path whitelist cho query_kb_path/template_kb_path/executor_ref. P9 render_config fail-fast contract + key whitelist trong §15.2. 0 blocker còn lại. Triết lý v1.1 giữ 100%. 16 vi phạm HP đã đóng. 5/5 test NT2+NT4+NT11 PASS. |
| v1.2 FINAL rev 2 | 2026-04-17 Fix 11 post-enact | Desktop rà 13 NT post-enact phát hiện 2 vi phạm NT2+NT4 ở tầng SQL DDL mà Council R1+R2 bỏ sót: (a) §5.8 guard 3 + §11 Bước 6.4: GRANT SELECT từng table riêng → phải GRANT ON ALL TABLES + ALTER DEFAULT PRIVILEGES áp cross-DB (directus + incomex_metadata + workflow). (b) §11 Bước 12: trigger bind pattern vào WHEN tĩnh → phải function body PL/pgSQL SELECT runtime từ dot_config. Thêm P10+P11 vào §6.X CẤM HARDCODE. Patch inline clarification, KHÔNG cần Council lại vì không đổi semantic. Bài học: rà NT phải soi 3 tầng (code bash/python / SQL DDL / SQL data seed) — tầng DDL dễ lọt nhất. |
| v1.2 FINAL rev 3 | 2026-04-17 Fix 12 Desktop | Amend separator / → __ khớp PG reality. kb_documents.key dùng __ do Agent Data _fs_key() encoding legacy Firestore (trước S109 — xem s170-deep-investigation, s170-finalize-pa5-report READY-FOR-APPROVAL). Phạm vi 6 patch: §5.7 CHECK chk_query_kb_path_whitelist + chk_template_kb_path_whitelist + ví dụ section 9 (2 path). §5.8 CHECK chk_sql_executor_path + guard 1 wording + ví dụ H10 (1 path). §5.9 seed context_pack_watched_key_patterns (3 patterns). Desktop tự amend không Council vì: (a) clarification wording khớp hạ tầng, không đổi semantic/triết lý; (b) rà rủi ro = 0 (8 row section_definitions seed đều NULL query/template path; 9 H seed đều builtin CHECK không trigger; agent Phase 1.5 đã tự seed __ §5.9 bonus). Nguyên tắc áp dụng: "Nếu luật chưa đúng thì sửa luật cho sát thực tế" (Huyên Fix 12). TD-S178-18 RESOLVED. TD-S178-19 MỚI: khi S170 PA5 approved + migrate kb_documents.key __→/ → amend rev 4 đảo ngược + ALTER 3 CHECK + UPDATE 3 patterns §5.9. Phase 1.6 migration 05-*.sql sẽ ALTER 3 CHECK constraint PG khớp rev 3. |
| v1.2 FINAL rev 4 | 2026-04-17 Fix 12 Desktop | Đóng kẽ hở NT2+NT4 built-in renderer fallback. Phase 4a P3 Pre-D phát hiện §5.7+§6 Bước 5 wording ambiguous: cho phép hiểu "template_kb_path NULL → fallback built-in renderer trong code" = vi phạm NT2/NT4 (thêm section = sửa code). Patch §6 Bước 5 + §6.X CẤM rev 4: template NULL → FAIL-FAST, CẤM case-dispatch per-section, mọi render qua generic dispatcher giống §5.8 pattern. Desktop tự amend không Council — clarification đóng kẽ hở, không đổi semantic/triết lý (nguyên tắc sinh ra §5.8 generic executor đã được Council duyệt ở rev 2). Bài học: luật không rõ "NULL xử lý thế nào" = kẽ hở cho agent tự đẻ fallback = vi phạm HP. Rà luật phải săn cả những chỗ không nói gì chứ không chỉ những chỗ viết sai. |
| v1.2 FINAL rev 5 | 2026-04-17 Fix 12 Desktop | Định nghĩa volatile header wording exact + strip rule. Pre-D' phát hiện §6 Bước 5 + §7 không có wording cho volatile header format (rev 1-4 implicit "VOLATILE HEADER" nhưng không exact delimiter/key/strip rule). Agent Phase 4a P3 không thể tính logical_checksum deterministic mà không có spec. Patch §6 Bước 5: markdown/mermaid dùng <!-- VOLATILE HEADER --> ... <!-- /VOLATILE HEADER --> block 4 keys + sed strip rule. JSON dùng _volatile_header object key + jq -S 'del(._volatile_header)' strip + canonicalize -S sort keys chống non-deterministic key order. 4 common runtime fields bắt buộc: generated_at ISO UTC, build_id, git_commit 5-tier, trigger_source §5.1 enum. Section static vẫn phải có volatile header. Desktop tự amend không Council — bổ sung spec thiếu, không đổi semantic. Bài học rà luật: "chỗ không nói gì" cần soi trước khi ban hành, không sau. |
| v1.2 FINAL rev 6 | 2026-04-17 Fix 12 Desktop | Multi-DB dispatch theo Assembly First NT8 + NT1 SSOT metadata. Pre-D' Task 2 phát hiện: laws_index section cần query incomex_metadata DB, 6 section khác query directus DB. Rev 5 không có field metadata định target DB → renderer phải đoán (hardcode code→DB map) hoặc magic comment trong SQL body (-- DB: xxx) — cả 2 đều vi phạm NT1/NT2/NT8. Phạm vi 5 patch: (1) §5.7 schema thêm cột target_db TEXT CHECK IN ('directus','incomex_metadata','workflow'). (2) §5.7 thêm CHECK constraint chk_target_db_consistency — NOT NULL khi data_source IN ('pg_query','kb_query'), NULL khi static/filesystem_scan/custom. (3) §5.7 seed 8 row bổ sung target_db (laws_index=incomex_metadata, 6 pg_query=directus, red_zones=NULL static). (4) §6 Bước 5 wording dispatch theo target_db runtime, CẤM hardcode DB trong code. (5) §6.X CẤM magic SQL comment define DB. Desktop tự amend không Council — thêm metadata column theo pattern §5.8 đã Council duyệt (precedent). Migration PG: file mới 08-dieu43-v1-2-rev6-target-db.sql ALTER + UPDATE 8 row. Căn cứ HP: NT1 SSOT (metadata ở schema không lẫn data), NT8 Assembly First (DB name từ PG metadata), NT11 khai tối thiểu (thêm DB mới = INSERT row, không sửa code). Bài học: khi renderer đọc query mà không biết target DB → metadata thiếu. Rà luật phải hỏi "renderer có đủ context runtime chưa" mỗi field. |
Đ43 v1.2 FINAL BAN HÀNH (rev 6 — multi-DB dispatch column target_db) | 2026-04-17 S178 Fix 12 Desktop | Council 2 vòng + Desktop post-enact NT audit + rev 3/4/5/6 clarification | 11 + 10 patches | 0 blocker Triển khai: BLOCK 1 Bootstrap 17 bước §11 — Phase 1+2+3+Q2+1.5+1.6+Pre-D' Task 1+Task 2 DONE → tiếp migration file 08 (ALTER target_db + UPDATE 8 row) + install chevron → Stage D' generic renderer.