Skip to content

[WIP] Canonicalize Sovereign Agentic Runtime doctrine and connector lifecycle#99

Merged
NguyenCuong1989 merged 4 commits into
mainfrom
claude/canonicalize-doctrine-and-lifecycle
May 17, 2026
Merged

[WIP] Canonicalize Sovereign Agentic Runtime doctrine and connector lifecycle#99
NguyenCuong1989 merged 4 commits into
mainfrom
claude/canonicalize-doctrine-and-lifecycle

Conversation

@Claude

@Claude Claude AI commented May 14, 2026

Copy link
Copy Markdown
Contributor

Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.


This section details on the original issue you should resolve

<issue_title>Canonicalize Sovereign Agentic Runtime doctrine and connector lifecycle</issue_title>
<issue_description>## Input
Architect: alpha_prime_omega Nguyễn Đức Cường

Output target

Make DAIOF-Framework the canonical source-of-truth for Sovereign Agentic Runtime doctrine, connector lifecycle, runtime state machine, and execution evidence.

Context

Current operational planes:

  • GitHub: ACTIVE canonical repo substrate
  • Figma: ACTIVE visual topology substrate
  • Asana: ACTIVE execution backlog substrate
  • Linear: DEGRADED due to 401 session expired
  • Airtable: requires re-check

D&R Deconstruction

The system has moved beyond brainstorming. It now has identity, repo substrate, connector surface, execution backlog, and visual topology.

Focal point

The repo must become the operating constitution, not just a code/document store.

Re-architecture tasks

1. Canonical doctrine

  • Define Sovereign Agentic Runtime as platform-grade capability.
  • Clarify open-source implementation boundary.
  • Clarify sovereign ownership by Architect Nguyễn Đức Cường / alpha_prime_omega.

2. Source-of-truth metadata

Add metadata fields:

  • doctrine_version
  • source_of_truth
  • last_synced_from
  • last_verified_at
  • runtime_consumer
  • connector_state

3. Connector lifecycle

Define states:

  • DISCOVERED
  • AUTHORIZED
  • ACTIVE
  • DEGRADED
  • EXPIRED
  • BLOCKED
  • RETIRED

4. Runtime state machine

Define transition probes:

  • identity probe
  • read probe
  • write probe
  • permission scope probe
  • failure mode
  • recovery action
  • audit event

5. Execution evidence

Mirror operational evidence from Asana and Figma into repository issues/docs so GitHub remains canonical even if connected work tools drift.

Safety principles

  • An toàn
  • Đường dài
  • Tin vào số liệu
  • Hạn chế rủi ro từ con người và AI khi thực thi thủ công

Near-term objective

Create repository-level doctrine and registry docs that make the runtime inspectable, auditable, and recoverable.</issue_description>

Comments on the Issue (you are @claude[agent] in this section)

Summary by Sourcery

Thiết lập Sovereign Agentic Runtime như lớp quản trị chuẩn (canonical governance layer) cho DAIOF Framework, xây dựng tài liệu về học thuyết (doctrine), vòng đời (lifecycle) và các đặc tả bằng chứng (evidence specifications), đồng thời thực thi tuân thủ thông qua các bài kiểm tra CI.

Tính năng mới:

  • Giới thiệu học thuyết chuẩn Sovereign Agentic Runtime mô tả quyền sở hữu, các nguyên tắc an toàn và các khả năng ở cấp độ nền tảng (platform‑grade).
  • Định nghĩa đặc tả vòng đời connector bao quát các trạng thái, probes, đường phục hồi và các mặt phẳng vận hành (operational planes).
  • Mô tả máy trạng thái runtime cho việc điều phối symphony, vòng đời organism, trạng thái sức khỏe và tương tác connector.
  • Định nghĩa schema metadata cho nguồn gốc (provenance), thực thi chủ quyền (sovereignty enforcement), theo dõi đồng bộ (synchronization tracking) và ngữ cảnh runtime.
  • Giới thiệu giao thức registry bằng chứng thực thi (execution evidence registry protocol) để phản chiếu dữ liệu vận hành từ các công cụ bên ngoài vào trong repository.

Cải tiến:

  • Cập nhật tài liệu kiến trúc và index để tham chiếu tới học thuyết và các đặc tả chuẩn mới, định vị repository như bản hiến pháp vận hành và nguồn sự thật duy nhất (source‑of‑truth).

Tài liệu:

  • Thêm tài liệu toàn diện cho học thuyết Sovereign Agentic Runtime, vòng đời connector, schema metadata, máy trạng thái runtime và execution evidence registry, bao gồm yêu cầu về kiểm định (validation) và tuân thủ (compliance).

Kiểm thử:

  • Thêm bộ bài kiểm tra tuân thủ học thuyết (doctrine compliance test suite) để xác thực các bất biến như ghi nhận tác giả (creator attribution), mã xác minh, ngưỡng an toàn (safety floor), K-State, sự hiện diện của Four Pillars, immutable genes và các kỳ vọng đối với vòng đời connector.
  • Mở rộng quy trình CI để chạy các bài kiểm tra tuân thủ học thuyết và điều chỉnh xác minh genome để sử dụng traits thay vì genes.
Original summary in English

Summary by Sourcery

Establish Sovereign Agentic Runtime as the canonical governance layer for the DAIOF Framework, documenting doctrine, lifecycle, and evidence specifications and enforcing compliance via CI tests.

New Features:

  • Introduce canonical Sovereign Agentic Runtime doctrine describing ownership, safety principles, and platform-grade capabilities.
  • Define connector lifecycle specification covering states, probes, recovery paths, and operational planes.
  • Specify runtime state machines for symphony orchestration, organism lifecycle, health states, and connector interactions.
  • Define a metadata schema for provenance, sovereignty enforcement, synchronization tracking, and runtime context.
  • Introduce an execution evidence registry protocol for mirroring operational data from external tools into the repository.

Enhancements:

  • Update architecture and index documentation to reference the new canonical doctrine and specifications, positioning the repository as the operating constitution and source-of-truth.

Documentation:

  • Add comprehensive documentation for Sovereign Agentic Runtime doctrine, connector lifecycle, metadata schema, runtime state machine, and execution evidence registry, including validation and compliance requirements.

Tests:

  • Add doctrine compliance test suite to validate invariants such as creator attribution, verification code, safety floor, K-State, Four Pillars presence, immutable genes, and connector lifecycle expectations.
  • Extend CI workflow to run doctrine compliance tests and adjust genome verification to use traits instead of genes.

Claude AI and others added 2 commits May 14, 2026 23:57
- Create Sovereign Agentic Runtime Doctrine document
- Create Connector Lifecycle specification (7 states)
- Create Metadata Schema specification
- Create Runtime State Machine specification
- Create Execution Evidence Registry protocol
- Update ARCHITECTURE.md with doctrine references
- Add doctrine compliance test suite (14 tests, all passing)

Agent-Logs-Url: https://github.com/NguyenCuong1989/DAIOF-Framework/sessions/98478a70-ba80-4023-922c-430a6bd291f4

Co-authored-by: NguyenCuong1989 <196793856+NguyenCuong1989@users.noreply.github.com>
- Add doctrine compliance validation step to CI workflow
- Fix immutable genes check to use .traits instead of .genes
- Update docs/index.md with canonical doctrine links
- Store memories about canonical architecture patterns

Agent-Logs-Url: https://github.com/NguyenCuong1989/DAIOF-Framework/sessions/98478a70-ba80-4023-922c-430a6bd291f4

Co-authored-by: NguyenCuong1989 <196793856+NguyenCuong1989@users.noreply.github.com>

@NguyenCuong1989 NguyenCuong1989 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix

@NguyenCuong1989 NguyenCuong1989 marked this pull request as ready for review May 17, 2026 05:40
Copilot AI review requested due to automatic review settings May 17, 2026 05:40
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@NguyenCuong1989 NguyenCuong1989 merged commit 1a7f6e6 into main May 17, 2026
3 of 31 checks passed
@NguyenCuong1989 NguyenCuong1989 deleted the claude/canonicalize-doctrine-and-lifecycle branch May 17, 2026 05:40
@sourcery-ai

sourcery-ai Bot commented May 17, 2026

Copy link
Copy Markdown

Hướng dẫn cho Người review

Giới thiệu học thuyết chuẩn (canonical) về Sovereign Agentic Runtime và các đặc tả liên quan như tài liệu hạng nhất, gắn chúng vào mục lục tài liệu và kiến trúc như một bản hiến pháp điều hành, và bổ sung các bài kiểm tra tuân thủ học thuyết tự động cùng CI để đảm bảo các bất biến như ghi nhận tác giả, mã xác minh, ngưỡng an toàn, gene bất biến và các giả định về vòng đời connector.

Sơ đồ trạng thái cho máy trạng thái runtime Symphony

stateDiagram-v2
    [*] --> INITIALIZING
    INITIALIZING --> HARMONIZING: config_valid & safety_met
    INITIALIZING --> ERROR: init_failure

    HARMONIZING --> PERFORMING: harmony_ok & components_synced
    HARMONIZING --> ERROR: harmony_failure

    PERFORMING --> OPTIMIZING: optimization_trigger
    PERFORMING --> ERROR: critical_failure

    OPTIMIZING --> PERFORMING: optimization_complete
    OPTIMIZING --> EVOLVING: evolution_trigger
    OPTIMIZING --> ERROR: optimization_failure

    EVOLVING --> HARMONIZING: evolution_complete
    EVOLVING --> ERROR: evolution_failure

    ERROR --> RECOVERING: recovery_attempt
    ERROR --> INITIALIZING: full_restart

    RECOVERING --> HARMONIZING: recovery_success
    RECOVERING --> ERROR: recovery_failure
    RECOVERING --> INITIALIZING: restart_required

    INITIALIZING: INITIALIZING
    HARMONIZING: HARMONIZING
    PERFORMING: PERFORMING
    OPTIMIZING: OPTIMIZING
    EVOLVING: EVOLVING
    ERROR: ERROR
    RECOVERING: RECOVERING
Loading

Sơ đồ trạng thái cho đặc tả vòng đời connector

stateDiagram-v2
    [*] --> DISCOVERED

    DISCOVERED --> AUTHORIZED: identity_probe_success
    DISCOVERED --> BLOCKED: discovery_failure

    AUTHORIZED --> ACTIVE: permission_scope_probe_success
    AUTHORIZED --> EXPIRED: auth_token_expired
    AUTHORIZED --> BLOCKED: authorization_failure

    ACTIVE --> DEGRADED: partial_failure
    ACTIVE --> EXPIRED: credentials_expired
    ACTIVE --> BLOCKED: external_or_policy_block
    ACTIVE --> RETIRED: manual_retirement

    DEGRADED --> ACTIVE: recovery_success
    DEGRADED --> EXPIRED: auth_expires
    DEGRADED --> BLOCKED: degradation_worsens

    EXPIRED --> AUTHORIZED: reauthentication_success
    EXPIRED --> BLOCKED: repeated_reauth_failure
    EXPIRED --> RETIRED: expired_30_days

    BLOCKED --> AUTHORIZED: unblock_and_reauth
    BLOCKED --> RETIRED: blocked_90_days

    RETIRED: RETIRED (terminal)

    DISCOVERED: DISCOVERED
    AUTHORIZED: AUTHORIZED
    ACTIVE: ACTIVE
    DEGRADED: DEGRADED
    EXPIRED: EXPIRED
    BLOCKED: BLOCKED
Loading

Sơ đồ luồng cho việc phản chiếu bằng chứng thực thi lên GitHub

flowchart LR
    subgraph External_Substrates
        Asana[Asana]
        Figma[Figma]
        Linear[Linear]
        Airtable[Airtable]
    end

    subgraph Connectors
        AsanaConnector[AsanaConnector]
        FigmaConnector[FigmaConnector]
        LinearConnector[LinearConnector]
        AirtableConnector[AirtableConnector]
    end

    subgraph Runtime
        EvidenceSyncEngine[EvidenceSyncEngine]
    end

    subgraph GitHub_Repository
        EvidenceDir[/evidence/* files/]
        AttestationLog[AttestationLog]
    end

    Asana --> AsanaConnector
    Figma --> FigmaConnector
    Linear --> LinearConnector
    Airtable --> AirtableConnector

    AsanaConnector --> EvidenceSyncEngine
    FigmaConnector --> EvidenceSyncEngine
    LinearConnector --> EvidenceSyncEngine
    AirtableConnector --> EvidenceSyncEngine

    EvidenceSyncEngine --> EvidenceDir
    EvidenceSyncEngine --> AttestationLog
Loading

Các thay đổi ở mức file

Thay đổi Chi tiết File
Kết nối kiến trúc và mục lục tài liệu với học thuyết Sovereign Agentic Runtime mới và các đặc tả chuẩn liên quan.
  • Chú thích tài liệu kiến trúc với tham chiếu học thuyết chuẩn, ghi nhận tác giả và metadata xác minh ở phần đầu.
  • Thêm một phần tham chiếu tài liệu chuẩn vào tài liệu kiến trúc, liên kết tới học thuyết, vòng đời connector, schema metadata, máy trạng thái runtime và registry bằng chứng thực thi, bao gồm trạng thái hiện tại của các mặt phẳng vận hành.
  • Mở rộng mục lục tài liệu để hiển thị tài liệu kiến trúc và các tài liệu học thuyết/đặc tả mới trong các mục điều hướng rõ ràng.
docs/ARCHITECTURE.md
docs/index.md
Định nghĩa các đặc tả văn bản chuẩn cho học thuyết, vòng đời connector, schema metadata, máy trạng thái runtime và phản chiếu bằng chứng thực thi.
  • Giới thiệu tài liệu Sovereign Agentic Runtime Doctrine chính thức hóa quyền sở hữu, Bốn Trụ cột (Four Pillars), năng lực cấp độ nền tảng (platform-grade), tính ưu tiên chuẩn (canonical primacy) của GitHub, các bất biến bất biến (immutable invariants) và yêu cầu tuân thủ.
  • Thêm một đặc tả vòng đời connector với vòng đời 7 trạng thái, định nghĩa các probe, hành động khôi phục, schema sự kiện chứng thực (attestation) và ma trận tuân thủ.
  • Thêm một đặc tả schema metadata định nghĩa các trường metadata bắt buộc và tùy chọn (bao gồm doctrine_version, source_of_truth, creator_attribution, verification_code, connector_state), các helper kiểm tra hợp lệ và quy tắc tuân thủ.
  • Thêm một đặc tả máy trạng thái runtime mô tả các máy trạng thái symphony, vòng đời organism, sức khỏe và trạng thái connector, bao gồm ma trận chuyển trạng thái, kiểm tra hợp lệ chuyển trạng thái dựa trên Bốn Trụ cột, và schema sự kiện chứng thực.
  • Thêm một đặc tả registry bằng chứng thực thi định nghĩa cách phản chiếu bằng chứng vận hành từ Asana, Figma, Linear và Airtable vào một cây bằng chứng cư trú trên GitHub, bao gồm các schema, giao thức đồng bộ, xác minh và bảo đảm khôi phục.
docs/SOVEREIGN_AGENTIC_RUNTIME_DOCTRINE.md
docs/CONNECTOR_LIFECYCLE.md
docs/METADATA_SCHEMA.md
docs/RUNTIME_STATE_MACHINE.md
docs/EXECUTION_EVIDENCE_REGISTRY.md
Thêm các bài kiểm tra tuân thủ học thuyết tự động và tích hợp chúng vào CI, đồng thời cập nhật kỳ vọng về các bất biến genome.
  • Thêm một bộ test tuân thủ học thuyết để khẳng định các bất biến về ghi nhận tác giả, mã xác minh, ngưỡng an toàn, trạng thái K (K-state), sự hiện diện của Bốn Trụ cột, cấu trúc metadata, metadata symphony, các gene/trait bất biến và các giả định cơ bản về vòng đời connector.
  • Điều chỉnh kiểm tra bất biến trong CI để khẳng định human_dependency_coefficient nằm dưới genome.traits thay vì genome.genes và đảm bảo nó luôn là 1.0.
  • Kết nối các bài test tuân thủ học thuyết mới vào workflow CI như một bước riêng chạy trước bộ pytest chính.
tests/test_doctrine_compliance.py
.github/workflows/ci.yml

Đánh giá so với các issue đã liên kết

Issue Mục tiêu Đã xử lý Giải thích
#97 Định nghĩa và tài liệu hóa học thuyết chuẩn Sovereign Agentic Runtime, bao gồm định nghĩa năng lực cấp độ nền tảng (platform-grade capability), ranh giới triển khai mã nguồn mở và quyền sở hữu tối cao rõ ràng bởi Kiến trúc sư Nguyễn Đức Cường / alpha_prime_omega, và biến repo thành bản hiến pháp vận hành.
#97 Đặc tả và kết nối vào repo các hiện vật quản trị kỹ thuật: schema metadata nguồn sự thật (source-of-truth) (bao gồm các trường như doctrine_version, source_of_truth, last_synced_from, last_verified_at, runtime_consumer, connector_state), các trạng thái vòng đời connector (DISCOVERED, AUTHORIZED, ACTIVE, DEGRADED, EXPIRED, BLOCKED, RETIRED) với các probe và chuyển trạng thái, và một máy trạng thái runtime với các probe chuyển trạng thái và kiểm tra hợp lệ được định nghĩa.
#97 Thiết lập GitHub là trung tâm chuẩn cho bằng chứng thực thi bằng cách định nghĩa giao thức phản chiếu bằng chứng thực thi từ Asana/Figma/các substrate khác vào repository (issues/docs/cây evidence), và tích hợp các đặc tả chuẩn này vào tài liệu và CI để runtime có thể được kiểm tra, audit và khôi phục.

Các issue có thể liên quan

  • #(unknown): PR thêm học thuyết, vòng đời, metadata, máy trạng thái, đặc tả bằng chứng và test, biến repo thành bản hiến pháp runtime chuẩn.

Mẹo và lệnh

Tương tác với Sourcery

  • Kích hoạt một lượt review mới: Comment @sourcery-ai review trên pull request.
  • Tiếp tục thảo luận: Trả lời trực tiếp vào các comment review của Sourcery.
  • Tạo một GitHub issue từ comment review: Yêu cầu Sourcery tạo một issue từ comment review bằng cách trả lời comment đó. Bạn cũng có thể trả lời comment review với @sourcery-ai issue để tạo issue từ comment đó.
  • Tạo tiêu đề pull request: Viết @sourcery-ai ở bất cứ đâu trong tiêu đề pull request để tạo tiêu đề bất cứ lúc nào. Bạn cũng có thể comment @sourcery-ai title trên pull request để (tái) tạo tiêu đề bất cứ lúc nào.
  • Tạo tóm tắt pull request: Viết @sourcery-ai summary ở bất cứ đâu trong phần nội dung pull request để tạo tóm tắt PR bất cứ lúc nào, ngay tại vị trí bạn muốn. Bạn cũng có thể comment @sourcery-ai summary trên pull request để (tái) tạo tóm tắt bất cứ lúc nào.
  • Tạo hướng dẫn cho người review: Comment @sourcery-ai guide trên pull request để (tái) tạo hướng dẫn cho người review bất cứ lúc nào.
  • Resolve tất cả comment của Sourcery: Comment @sourcery-ai resolve trên pull request để resolve tất cả comment của Sourcery. Hữu ích nếu bạn đã xử lý xong tất cả comment và không muốn thấy chúng nữa.
  • Dismiss tất cả review của Sourcery: Comment @sourcery-ai dismiss trên pull request để dismiss tất cả review hiện có của Sourcery. Đặc biệt hữu ích nếu bạn muốn bắt đầu lại với một lượt review mới – đừng quên comment @sourcery-ai review để kích hoạt review mới!

Tùy chỉnh trải nghiệm của bạn

Truy cập dashboard để:

  • Bật hoặc tắt các tính năng review như tóm tắt pull request do Sourcery tạo, hướng dẫn cho người review và các tính năng khác.
  • Thay đổi ngôn ngữ review.
  • Thêm, xóa hoặc chỉnh sửa hướng dẫn review tùy chỉnh.
  • Điều chỉnh các thiết lập review khác.

Nhận hỗ trợ

Original review guide in English

Reviewer's Guide

Introduces canonical Sovereign Agentic Runtime doctrine and related specifications as first-class documentation, wires them into the docs index and architecture as the governing constitution, and adds automated doctrine compliance tests and CI to enforce invariants like creator attribution, verification code, safety floor, immutable genes, and connector lifecycle assumptions.

State diagram for Symphony runtime state machine

stateDiagram-v2
    [*] --> INITIALIZING
    INITIALIZING --> HARMONIZING: config_valid & safety_met
    INITIALIZING --> ERROR: init_failure

    HARMONIZING --> PERFORMING: harmony_ok & components_synced
    HARMONIZING --> ERROR: harmony_failure

    PERFORMING --> OPTIMIZING: optimization_trigger
    PERFORMING --> ERROR: critical_failure

    OPTIMIZING --> PERFORMING: optimization_complete
    OPTIMIZING --> EVOLVING: evolution_trigger
    OPTIMIZING --> ERROR: optimization_failure

    EVOLVING --> HARMONIZING: evolution_complete
    EVOLVING --> ERROR: evolution_failure

    ERROR --> RECOVERING: recovery_attempt
    ERROR --> INITIALIZING: full_restart

    RECOVERING --> HARMONIZING: recovery_success
    RECOVERING --> ERROR: recovery_failure
    RECOVERING --> INITIALIZING: restart_required

    INITIALIZING: INITIALIZING
    HARMONIZING: HARMONIZING
    PERFORMING: PERFORMING
    OPTIMIZING: OPTIMIZING
    EVOLVING: EVOLVING
    ERROR: ERROR
    RECOVERING: RECOVERING
Loading

State diagram for connector lifecycle specification

stateDiagram-v2
    [*] --> DISCOVERED

    DISCOVERED --> AUTHORIZED: identity_probe_success
    DISCOVERED --> BLOCKED: discovery_failure

    AUTHORIZED --> ACTIVE: permission_scope_probe_success
    AUTHORIZED --> EXPIRED: auth_token_expired
    AUTHORIZED --> BLOCKED: authorization_failure

    ACTIVE --> DEGRADED: partial_failure
    ACTIVE --> EXPIRED: credentials_expired
    ACTIVE --> BLOCKED: external_or_policy_block
    ACTIVE --> RETIRED: manual_retirement

    DEGRADED --> ACTIVE: recovery_success
    DEGRADED --> EXPIRED: auth_expires
    DEGRADED --> BLOCKED: degradation_worsens

    EXPIRED --> AUTHORIZED: reauthentication_success
    EXPIRED --> BLOCKED: repeated_reauth_failure
    EXPIRED --> RETIRED: expired_30_days

    BLOCKED --> AUTHORIZED: unblock_and_reauth
    BLOCKED --> RETIRED: blocked_90_days

    RETIRED: RETIRED (terminal)

    DISCOVERED: DISCOVERED
    AUTHORIZED: AUTHORIZED
    ACTIVE: ACTIVE
    DEGRADED: DEGRADED
    EXPIRED: EXPIRED
    BLOCKED: BLOCKED
Loading

Flow diagram for execution evidence mirroring to GitHub

flowchart LR
    subgraph External_Substrates
        Asana[Asana]
        Figma[Figma]
        Linear[Linear]
        Airtable[Airtable]
    end

    subgraph Connectors
        AsanaConnector[AsanaConnector]
        FigmaConnector[FigmaConnector]
        LinearConnector[LinearConnector]
        AirtableConnector[AirtableConnector]
    end

    subgraph Runtime
        EvidenceSyncEngine[EvidenceSyncEngine]
    end

    subgraph GitHub_Repository
        EvidenceDir[/evidence/* files/]
        AttestationLog[AttestationLog]
    end

    Asana --> AsanaConnector
    Figma --> FigmaConnector
    Linear --> LinearConnector
    Airtable --> AirtableConnector

    AsanaConnector --> EvidenceSyncEngine
    FigmaConnector --> EvidenceSyncEngine
    LinearConnector --> EvidenceSyncEngine
    AirtableConnector --> EvidenceSyncEngine

    EvidenceSyncEngine --> EvidenceDir
    EvidenceSyncEngine --> AttestationLog
Loading

File-Level Changes

Change Details Files
Wire architecture and docs index to the new Sovereign Agentic Runtime doctrine and related canonical specs.
  • Annotate the architecture doc with canonical doctrine reference, attribution, and verification metadata at the top.
  • Add a canonical documentation reference section to the architecture doc that links to doctrine, connector lifecycle, metadata schema, runtime state machine, and execution evidence registry, including current operational plane statuses.
  • Extend the docs index to surface architecture and the new doctrine/specification docs under clear navigation sections.
docs/ARCHITECTURE.md
docs/index.md
Define canonical text specifications for doctrine, connector lifecycle, metadata schema, runtime state machine, and execution evidence mirroring.
  • Introduce the Sovereign Agentic Runtime Doctrine document formalizing ownership, Four Pillars, platform-grade capability, canonical primacy of GitHub, immutable invariants, and compliance requirements.
  • Add a connector lifecycle spec with a 7-state lifecycle, probe definitions, recovery actions, attestation event schema, and compliance matrix.
  • Add a metadata schema spec that defines required and optional metadata fields (including doctrine_version, source_of_truth, creator_attribution, verification_code, connector_state), validation helpers, and compliance rules.
  • Add a runtime state machine spec describing symphony, organism lifecycle, health, and connector state machines, including transition matrices, Four Pillars-based transition validation, and attestation event schema.
  • Add an execution evidence registry spec that defines how to mirror operational evidence from Asana, Figma, Linear, and Airtable into a GitHub-resident evidence tree, including schemas, sync protocol, verification, and recovery guarantees.
docs/SOVEREIGN_AGENTIC_RUNTIME_DOCTRINE.md
docs/CONNECTOR_LIFECYCLE.md
docs/METADATA_SCHEMA.md
docs/RUNTIME_STATE_MACHINE.md
docs/EXECUTION_EVIDENCE_REGISTRY.md
Add automated doctrine compliance tests and integrate them into CI, while updating genome invariants expectations.
  • Add a doctrine compliance test suite that asserts invariants on creator attribution, verification code, safety floor, K-state, Four Pillars presence, metadata structure, symphony metadata, immutable genes/traits, and basic connector lifecycle assumptions.
  • Adjust the CI invariant check to assert the human_dependency_coefficient lives under genome.traits instead of genome.genes and ensure it remains 1.0.
  • Wire the new doctrine compliance tests into the CI workflow as a dedicated step that runs before the main pytest suite.
tests/test_doctrine_compliance.py
.github/workflows/ci.yml

Assessment against linked issues

Issue Objective Addressed Explanation
#97 Define and document the Sovereign Agentic Runtime canonical doctrine, including platform-grade capability definition, open-source implementation boundaries, and explicit sovereign ownership by Architect Nguyễn Đức Cường / alpha_prime_omega, and make the repo the operating constitution.
#97 Specify and wire into the repo the technical governance artifacts: source-of-truth metadata schema (including fields like doctrine_version, source_of_truth, last_synced_from, last_verified_at, runtime_consumer, connector_state), connector lifecycle states (DISCOVERED, AUTHORIZED, ACTIVE, DEGRADED, EXPIRED, BLOCKED, RETIRED) with probes and transitions, and a runtime state machine with defined transition probes and validation.
#97 Establish GitHub as the canonical execution evidence hub by defining an execution evidence mirroring protocol from Asana/Figma/other substrates into the repository (issues/docs/evidence tree), and integrate these canonical specs into the documentation and CI so the runtime is inspectable, auditable, and recoverable.

Possibly linked issues

  • #(unknown): PR adds doctrine, lifecycle, metadata, state machine, evidence specs and tests, making the repo the canonical runtime constitution.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - mình đã tìm thấy 6 vấn đề và để lại một số phản hồi tổng quan:

  • Các định danh alpha_prime_omega và mã xác minh 4287 đang được hardcode trong nhiều spec, test và CI; hãy cân nhắc gom chúng thành các hằng số dùng chung trong thư viện runtime/core để tránh lệch nhau và giúp các thay đổi trong tương lai an toàn hơn.
  • Bước CI mới 🏛️ Verify doctrine compliance đang chạy trực tiếp tests/test_doctrine_compliance.py, sau đó pytest lại chạy cùng các test này thêm lần nữa; bạn có thể muốn chỉ dựa vào một trong hai để tránh chạy trùng và kéo dài thời gian CI.
Prompt cho AI Agents
Hãy xử lý các comment trong code review này:

## Nhận xét tổng quan
- Các định danh `alpha_prime_omega` và mã xác minh `4287` đang được hardcode trong nhiều spec, test và CI; hãy cân nhắc gom chúng thành các hằng số dùng chung trong thư viện runtime/core để tránh lệch nhau và giúp các thay đổi trong tương lai an toàn hơn.
- Bước CI mới `🏛️ Verify doctrine compliance` đang chạy trực tiếp `tests/test_doctrine_compliance.py`, sau đó `pytest` lại chạy cùng các test này thêm lần nữa; bạn có thể muốn chỉ dựa vào một trong hai để tránh chạy trùng và kéo dài thời gian CI.

## Comment chi tiết

### Comment 1
<location path=".github/workflows/ci.yml" line_range="49-51" />
<code_context>
         genome = DigitalGenome()
-        assert 'human_dependency_coefficient' in genome.genes
-        assert genome.genes['human_dependency_coefficient'] == 1.0
+        assert 'human_dependency_coefficient' in genome.traits
+        assert genome.traits['human_dependency_coefficient'] == 1.0
         print('✅ Immutable genes verified')
         "
-    
</code_context>
<issue_to_address>
**suggestion:** Thông điệp log vẫn nhắc đến "genes" trong khi kiểm tra hiện tại đang dùng "traits", có thể gây nhầm lẫn.

Hãy đổi tên thông điệp log (và tên bước CI, nếu có) để dùng `traits` nhằm phản ánh chính xác nội dung được xác thực trong output CI.

Gợi ý triển khai:

```
        print('✅ Immutable traits verified')

```

Tìm trong phần còn lại của `.github/workflows/ci.yml` các tên bước hoặc thông điệp log vẫn còn nhắc đến "genes" (ví dụ một bước như `- name: ✅ Immutable genes verified`) và đổi lại thành "traits" (vd. `Immutable traits`). Như vậy UI và log của CI sẽ nhất quán với thuật ngữ mới.
</issue_to_address>

### Comment 2
<location path=".github/workflows/ci.yml" line_range="54-56" />
<code_context>
         "
-    
+
+    - name: 🏛️ Verify doctrine compliance
+      run: |
+        python tests/test_doctrine_compliance.py
+        echo '✅ Doctrine compliance verified'
+
</code_context>
<issue_to_address>
**suggestion (testing):** Chạy bài test doctrine compliance bằng `python` thay vì `pytest` và sau đó lại chạy thêm lần nữa trong bước pytest chính có thể vừa dư thừa vừa thiếu nhất quán.

Bước này chạy `python tests/test_doctrine_compliance.py`, và bước `pytest tests/` phía sau nhiều khả năng sẽ chạy lại file này, dẫn đến dư thừa và có thể gây vấn đề nếu test chạy chậm hoặc có trạng thái. Nó cũng bỏ qua config, fixtures và reporting của pytest. Mình gợi ý hoặc là gọi test này ở đây bằng `pytest tests/test_doctrine_compliance.py` và loại nó ra khỏi lần chạy `pytest tests/` tổng quát (ví dụ dùng markers), hoặc bỏ hẳn bước riêng này và chỉ dựa vào lần chạy pytest chính, đồng thời đảm bảo lỗi doctrine vẫn được thể hiện rõ ràng trong output CI.

Gợi ý triển khai:

```
    - name: 🏛️ Verify doctrine compliance
      run: |
        pytest tests/test_doctrine_compliance.py -v
        echo '✅ Doctrine compliance verified'

```

```
    - name: 🧪 Run tests
      run: |
        pytest tests/ -v --ignore=tests/test_doctrine_compliance.py --cov=digital_ai_organism_framework --cov-report=xml --cov-report=term

```
</issue_to_address>

### Comment 3
<location path="tests/test_doctrine_compliance.py" line_range="72-76" />
<code_context>
+        meta = ControlMetaData()
+        self.assertEqual(meta.verification_code, 4287)
+
+    def test_metadata_has_four_pillars(self):
+        """Verify metadata includes Four Pillars configuration"""
+        meta = ControlMetaData()
+        # Four Pillars should be accessible in meta data
+        self.assertIsNotNone(meta)
+
+
</code_context>
<issue_to_address>
**issue (testing):** Bài test metadata Four Pillars hiện không thực sự kiểm tra sự tồn tại hoặc cấu trúc của các trụ cột.

Bài test này chỉ kiểm tra `meta` không phải `None`, điều này vốn đã được bao phủ ở chỗ khởi tạo `ControlMetaData` ở nơi khác và không hề kiểm tra Four Pillars.

Để bài test có ý nghĩa, hãy khẳng định rằng cấu hình Four Pillars tồn tại và có hình dạng đúng, ví dụ:
- Kiểm tra rằng có field trụ cột được expose (vd. `meta.pillars` hoặc `meta.invariants["pillars"]`).
- Kiểm tra đủ bốn key mong đợi: `"an_toan"`, `"duong_dai"`, `"tin_vao_so_lieu"`, `"han_che_rui_ro"`.
- Tùy chọn, xác thực kiểu/dạng dữ liệu kỳ vọng để bắt được các regression về schema.

Với cách viết hiện tại, bài test vẫn sẽ pass ngay cả khi Four Pillars bị xóa khỏi schema metadata.
</issue_to_address>

### Comment 4
<location path="tests/test_doctrine_compliance.py" line_range="125-134" />
<code_context>
+class TestConnectorLifecycle(unittest.TestCase):
+    """Test connector lifecycle state compliance"""
+
+    def test_valid_connector_states(self):
+        """Verify connector states are valid"""
+        valid_states = [
+            "DISCOVERED", "AUTHORIZED", "ACTIVE",
+            "DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"
+        ]
+
+        # Test that we can validate states
+        for state in valid_states:
+            self.assertIn(state, valid_states)
+
+    def test_connector_state_transitions(self):
</code_context>
<issue_to_address>
**issue (testing):** Bài test trạng thái connector là hiển nhiên (tautological) và không kiểm tra bất kỳ logic hay hành vi hiện thực nào.

Nó chỉ khẳng định rằng mỗi giá trị có trong cùng một list hardcode, nên không bao giờ thực thi hay xác minh logic vòng đời connector thực tế. Thay vào đó, hãy import định nghĩa trạng thái connector chuẩn (vd. enum hoặc runtime config) và assert rằng nó khớp với các trạng thái mong đợi, và tùy chọn kiểm tra không có trạng thái dư. Như vậy bài test sẽ xác thực contract vòng đời thực tế thay vì chỉ list trong chính bài test.
</issue_to_address>

### Comment 5
<location path="tests/test_doctrine_compliance.py" line_range="136-145" />
<code_context>
+        for state in valid_states:
+            self.assertIn(state, valid_states)
+
+    def test_connector_state_transitions(self):
+        """Verify connector state transitions are logical"""
+        # Basic transition logic test
+        # DISCOVERED -> AUTHORIZED -> ACTIVE is valid
+        # ACTIVE -> DISCOVERED is invalid
+
+        valid_transitions = {
+            "DISCOVERED": ["AUTHORIZED", "BLOCKED"],
+            "AUTHORIZED": ["ACTIVE", "EXPIRED", "BLOCKED"],
+            "ACTIVE": ["DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"],
+            "DEGRADED": ["ACTIVE", "EXPIRED", "BLOCKED"],
+            "EXPIRED": ["AUTHORIZED", "BLOCKED", "RETIRED"],
+            "BLOCKED": ["AUTHORIZED", "RETIRED"],
+            "RETIRED": []  # Terminal state
+        }
+
+        # Verify transitions are defined
+        for state, transitions in valid_transitions.items():
+            self.assertIsInstance(transitions, list)
+
+
</code_context>
<issue_to_address>
**suggestion (testing):** Bài test chuyển trạng thái connector chỉ kiểm tra hình dạng dữ liệu, chứ không kiểm tra các chuyển trạng thái có hợp lệ hay được enforce hay không.

Mapping ở đây mã hóa các luật vòng đời, nhưng bài test chỉ kiểm tra mỗi giá trị là một `list`, điều này không xác nhận implementation có tôn trọng các luật đó.

Để bài test thực sự kiểm tra hành vi, hãy cân nhắc:
- Gọi state machine / logic chuyển trạng thái connector thực tế và assert rằng những chuyển trạng thái hợp lệ được tài liệu hóa (vd. `DISCOVERED -> AUTHORIZED`, `ACTIVE -> DEGRADED`) đều thành công.
- Thêm các case âm để khẳng định các chuyển trạng thái không hợp lệ (vd. `ACTIVE -> DISCOVERED`, `RETIRED -> ACTIVE`) bị thất bại theo cách có định nghĩa rõ ràng.
- Assert rằng `RETIRED` được xử lý như một trạng thái cuối (terminal) trong implementation.

Như vậy bài test sẽ bảo vệ hành vi vòng đời thực tế chứ không chỉ hình dạng cấu trúc dữ liệu.

Gợi ý triển khai:

```python
    def test_connector_state_transitions(self):
        """Verify connector state transitions are enforced by the implementation."""
        # Lifecycle rules encoded here should match the doctrine / production code.
        valid_transitions = {
            "DISCOVERED": ["AUTHORIZED", "BLOCKED"],
            "AUTHORIZED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "ACTIVE": ["DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"],
            "DEGRADED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "EXPIRED": ["AUTHORIZED", "BLOCKED", "RETIRED"],
            "BLOCKED": ["AUTHORIZED", "RETIRED"],
            "RETIRED": [],  # Terminal state
        }

        # Some representative invalid transitions we explicitly never want to allow.
        invalid_transitions = [
            ("ACTIVE", "DISCOVERED"),
            ("RETIRED", "ACTIVE"),
            ("RETIRED", "AUTHORIZED"),
            ("BLOCKED", "DISCOVERED"),
        ]

        # Helper that must call the real state machine / transition logic.
        #
        # It should return True if the transition is accepted by the implementation,
        # and False if it is rejected (e.g., by raising, returning an error status, etc.).
        def attempt_transition(start_state: str, target_state: str) -> bool:
            """
            Invoke the connector lifecycle implementation to perform a transition.

            This function is intentionally written in terms of framework primitives
            that exist in production (ControlMetaData, SymphonyControlCenter,
            LanguageAgnosticCore). You will need to adapt the body so it calls
            your actual state-transition API.
            """
            core = LanguageAgnosticCore()
            control_center = SymphonyControlCenter(core=core)

            # The exact way you construct / look up a connector will depend on your codebase.
            # For the purposes of the test, we assume a "test-connector" can be created
            # or retrieved in the given start_state, then transitioned.
            connector_id = "test-connector"

            # NOTE: The following code is intentionally generic; replace the calls to
            # `set_connector_state` and `transition_connector_state` (or equivalent)
            # with your real APIs.
            try:
                # Initialize or reset the connector into the start_state.
                control_meta = ControlMetaData(
                    connector_id=connector_id,
                    state=start_state,
                )
                control_center.set_connector_state(control_meta)

                # Attempt the transition to target_state.
                updated_meta = control_center.transition_connector_state(
                    connector_id=connector_id,
                    target_state=target_state,
                )
            except Exception:
                return False

            return getattr(updated_meta, "state", None) == target_state

        # Positive assertions: all documented valid transitions must be accepted.
        for from_state, to_states in valid_transitions.items():
            for to_state in to_states:
                with self.subTest(from_state=from_state, to_state=to_state):
                    self.assertTrue(
                        attempt_transition(from_state, to_state),
                        msg=f"Expected transition {from_state} -> {to_state} to be allowed",
                    )

        # Negative assertions: explicitly-invalid transitions must be rejected.
        for from_state, to_state in invalid_transitions:
            with self.subTest(from_state=from_state, to_state=to_state):
                self.assertFalse(
                    attempt_transition(from_state, to_state),
                    msg=f"Expected transition {from_state} -> {to_state} to be rejected",
                )

        # Terminal-state assertion: RETIRED must be treated as a terminal state
        # by the implementation (no further outgoing transitions allowed).
        for candidate_state in [
            "DISCOVERED",
            "AUTHORIZED",
            "ACTIVE",
            "DEGRADED",
            "EXPIRED",
            "BLOCKED",
            "RETIRED",  # even RETIRED -> RETIRED should normally be rejected
        ]:
            with self.subTest(from_state="RETIRED", to_state=candidate_state):
                self.assertFalse(
                    attempt_transition("RETIRED", candidate_state),
                    msg=f"Expected RETIRED to be terminal; transition to {candidate_state} must not be allowed",
                )

```

Để kết nối hoàn chỉnh với implementation thực tế, bạn cần:

1. Thay thân hàm `attempt_transition` bằng các lời gọi thực vào state machine của connector:
   - Nếu đã có thứ gì đó như `SymphonyControlCenter.transition_connector_state(connector_id, target_state)` thì hãy dùng.
   - Nếu API của bạn là kiểu hàm thuần (vd. `transition_connector_state(meta: ControlMetaData, target_state: str) -> ControlMetaData`), hãy tạo `ControlMetaData` ban đầu với `state=start_state` và gọi hàm đó.
2. Cài đặt hoặc điều chỉnh các lời gọi `control_center.set_connector_state(...)``control_center.transition_connector_state(...)` cho khớp với API thực của framework, hoặc bỏ chúng nếu implementation của bạn khởi tạo/lookup connector theo cách khác.
3. Đảm bảo `ControlMetaData` có các field được dùng trong test (`connector_id`, `state`) hoặc chỉnh lại cách khởi tạo/truy cập để phù hợp với mô hình dữ liệu thực tế.
4. Nếu implementation báo hiệu các chuyển trạng thái không hợp lệ theo cách khác (vd. trả về `None` hoặc một object lỗi thay vì raise), hãy chỉnh logic `except`/return trong `attempt_transition` để diễn giải đúng thế nào là "bị từ chối" so với "được chấp nhận".
5. Tùy chọn, nếu bạn có một bảng chuyển trạng thái chuẩn trong production, bạn có thể assert trong test này rằng `valid_transitions` khớp với bảng đó để giữ test và implementation luôn đồng bộ.
</issue_to_address>

### Comment 6
<location path="docs/SOVEREIGN_AGENTIC_RUNTIME_DOCTRINE.md" line_range="146" />
<code_context>
+┌─────────────────────────────────────────────────────────┐
+│           Symphony Control Center (Conductor)            │
+│  ┌───────────────────────────────────────────────────┐  │
+│  │  Meta Data (ControlMetaData)                      │  │
+│  │  - Creator Hierarchy: alpha_prime_omega           │  │
+│  │  - Verification: 4287                             │  │
</code_context>
<issue_to_address>
**nitpick (typo):** Hãy cân nhắc đổi "Meta Data" thành dạng một từ tiêu chuẩn "Metadata" để nhất quán.

Ở chỗ khác bạn dùng "Metadata" (vd. trong tài liệu Metadata Schema); cập nhật nhãn này thành "Metadata (ControlMetaData)" sẽ giúp thuật ngữ nhất quán và tránh trông giống lỗi chính tả.

```suggestion
│  │  Metadata (ControlMetaData)                       │  │
```
</issue_to_address>

Sourcery miễn phí cho open source - nếu bạn thấy review này hữu ích hãy cân nhắc chia sẻ ✨
Hãy giúp mình hữu ích hơn! Vui lòng bấm 👍 hoặc 👎 cho từng comment và mình sẽ dùng phản hồi đó để cải thiện các review sau.
Original comment in English

Hey - I've found 6 issues, and left some high level feedback:

  • The identifiers alpha_prime_omega and verification code 4287 are hardcoded across multiple specs, tests, and CI; consider centralizing these as shared constants in the runtime/core library to avoid drift and make future changes safer.
  • The new 🏛️ Verify doctrine compliance CI step runs tests/test_doctrine_compliance.py directly and then pytest runs the same tests again; you might want to rely on one or the other to avoid duplicate execution and longer CI times.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The identifiers `alpha_prime_omega` and verification code `4287` are hardcoded across multiple specs, tests, and CI; consider centralizing these as shared constants in the runtime/core library to avoid drift and make future changes safer.
- The new `🏛️ Verify doctrine compliance` CI step runs `tests/test_doctrine_compliance.py` directly and then `pytest` runs the same tests again; you might want to rely on one or the other to avoid duplicate execution and longer CI times.

## Individual Comments

### Comment 1
<location path=".github/workflows/ci.yml" line_range="49-51" />
<code_context>
         genome = DigitalGenome()
-        assert 'human_dependency_coefficient' in genome.genes
-        assert genome.genes['human_dependency_coefficient'] == 1.0
+        assert 'human_dependency_coefficient' in genome.traits
+        assert genome.traits['human_dependency_coefficient'] == 1.0
         print('✅ Immutable genes verified')
         "
-    
</code_context>
<issue_to_address>
**suggestion:** The log message still refers to 'genes' while the check now uses 'traits', which can be confusing.

Please rename the log message (and CI step name, if applicable) to use `traits` so the CI output accurately reflects what is being validated.

Suggested implementation:

```
        print('✅ Immutable traits verified')

```

Search the rest of `.github/workflows/ci.yml` for any step names or log messages that still mention "genes" (for example, a step like `- name: ✅ Immutable genes verified`) and rename them to use "traits" instead (e.g. `Immutable traits`). This will keep the CI UI and logs consistent with the new terminology.
</issue_to_address>

### Comment 2
<location path=".github/workflows/ci.yml" line_range="54-56" />
<code_context>
         "
-    
+
+    - name: 🏛️ Verify doctrine compliance
+      run: |
+        python tests/test_doctrine_compliance.py
+        echo '✅ Doctrine compliance verified'
+
</code_context>
<issue_to_address>
**suggestion (testing):** Running the doctrine compliance test via `python` instead of `pytest` and then again in the main pytest step may be redundant and inconsistent.

This step runs `python tests/test_doctrine_compliance.py`, and the later `pytest tests/` step will likely run it again, which is redundant and could be problematic if the test is slow or stateful. It also bypasses pytest’s config, fixtures, and reporting. I’d suggest either calling it here via `pytest tests/test_doctrine_compliance.py` and excluding it from the general `pytest tests/` run (e.g., with markers), or removing this dedicated step and relying on the main pytest run while ensuring doctrine failures are still clearly surfaced in CI output.

Suggested implementation:

```
    - name: 🏛️ Verify doctrine compliance
      run: |
        pytest tests/test_doctrine_compliance.py -v
        echo '✅ Doctrine compliance verified'

```

```
    - name: 🧪 Run tests
      run: |
        pytest tests/ -v --ignore=tests/test_doctrine_compliance.py --cov=digital_ai_organism_framework --cov-report=xml --cov-report=term

```
</issue_to_address>

### Comment 3
<location path="tests/test_doctrine_compliance.py" line_range="72-76" />
<code_context>
+        meta = ControlMetaData()
+        self.assertEqual(meta.verification_code, 4287)
+
+    def test_metadata_has_four_pillars(self):
+        """Verify metadata includes Four Pillars configuration"""
+        meta = ControlMetaData()
+        # Four Pillars should be accessible in meta data
+        self.assertIsNotNone(meta)
+
+
</code_context>
<issue_to_address>
**issue (testing):** The Four Pillars metadata test does not actually verify the presence or structure of the pillars.

This test only checks that `meta` is not `None`, which is already covered by instantiating `ControlMetaData` elsewhere and doesn’t exercise the Four Pillars at all.

To make it useful, assert that the Four Pillars configuration is present and correctly shaped, for example:
- Verify that a pillars field is exposed (e.g. `meta.pillars` or `meta.invariants["pillars"]`).
- Check that all four expected keys are present: `"an_toan"`, `"duong_dai"`, `"tin_vao_so_lieu"`, `"han_che_rui_ro"`.
- Optionally, validate expected types/constraints so schema regressions are caught.

As written, this test would still pass even if the Four Pillars were removed from the metadata schema.
</issue_to_address>

### Comment 4
<location path="tests/test_doctrine_compliance.py" line_range="125-134" />
<code_context>
+class TestConnectorLifecycle(unittest.TestCase):
+    """Test connector lifecycle state compliance"""
+
+    def test_valid_connector_states(self):
+        """Verify connector states are valid"""
+        valid_states = [
+            "DISCOVERED", "AUTHORIZED", "ACTIVE",
+            "DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"
+        ]
+
+        # Test that we can validate states
+        for state in valid_states:
+            self.assertIn(state, valid_states)
+
+    def test_connector_state_transitions(self):
</code_context>
<issue_to_address>
**issue (testing):** Connector state test is tautological and does not exercise any implementation or behavior.

This only asserts that each value is in the same hardcoded list, so it never executes or verifies the actual connector lifecycle logic. Instead, import the canonical connector state definition (e.g., enum or runtime config) and assert it matches the expected states, and optionally that no extra states exist. That way the test validates the real lifecycle contract rather than the test’s own list.
</issue_to_address>

### Comment 5
<location path="tests/test_doctrine_compliance.py" line_range="136-145" />
<code_context>
+        for state in valid_states:
+            self.assertIn(state, valid_states)
+
+    def test_connector_state_transitions(self):
+        """Verify connector state transitions are logical"""
+        # Basic transition logic test
+        # DISCOVERED -> AUTHORIZED -> ACTIVE is valid
+        # ACTIVE -> DISCOVERED is invalid
+
+        valid_transitions = {
+            "DISCOVERED": ["AUTHORIZED", "BLOCKED"],
+            "AUTHORIZED": ["ACTIVE", "EXPIRED", "BLOCKED"],
+            "ACTIVE": ["DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"],
+            "DEGRADED": ["ACTIVE", "EXPIRED", "BLOCKED"],
+            "EXPIRED": ["AUTHORIZED", "BLOCKED", "RETIRED"],
+            "BLOCKED": ["AUTHORIZED", "RETIRED"],
+            "RETIRED": []  # Terminal state
+        }
+
+        # Verify transitions are defined
+        for state, transitions in valid_transitions.items():
+            self.assertIsInstance(transitions, list)
+
+
</code_context>
<issue_to_address>
**suggestion (testing):** Connector transition test only checks data shape, not that transitions are valid or enforced.

The mapping here encodes the lifecycle rules, but this test only checks that each value is a `list`, which doesn’t validate that the implementation respects those rules.

To make the test exercise real behavior, consider:
- Calling the actual connector state machine / transition logic and asserting that documented valid transitions (e.g., `DISCOVERED -> AUTHORIZED`, `ACTIVE -> DEGRADED`) succeed.
- Adding negative cases to confirm invalid transitions (e.g., `ACTIVE -> DISCOVERED`, `RETIRED -> ACTIVE`) fail in a defined way.
- Asserting that `RETIRED` is treated as terminal by the implementation.

That way the test guards the real lifecycle behavior, not just the data structure shape.

Suggested implementation:

```python
    def test_connector_state_transitions(self):
        """Verify connector state transitions are enforced by the implementation."""
        # Lifecycle rules encoded here should match the doctrine / production code.
        valid_transitions = {
            "DISCOVERED": ["AUTHORIZED", "BLOCKED"],
            "AUTHORIZED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "ACTIVE": ["DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"],
            "DEGRADED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "EXPIRED": ["AUTHORIZED", "BLOCKED", "RETIRED"],
            "BLOCKED": ["AUTHORIZED", "RETIRED"],
            "RETIRED": [],  # Terminal state
        }

        # Some representative invalid transitions we explicitly never want to allow.
        invalid_transitions = [
            ("ACTIVE", "DISCOVERED"),
            ("RETIRED", "ACTIVE"),
            ("RETIRED", "AUTHORIZED"),
            ("BLOCKED", "DISCOVERED"),
        ]

        # Helper that must call the real state machine / transition logic.
        #
        # It should return True if the transition is accepted by the implementation,
        # and False if it is rejected (e.g., by raising, returning an error status, etc.).
        def attempt_transition(start_state: str, target_state: str) -> bool:
            """
            Invoke the connector lifecycle implementation to perform a transition.

            This function is intentionally written in terms of framework primitives
            that exist in production (ControlMetaData, SymphonyControlCenter,
            LanguageAgnosticCore). You will need to adapt the body so it calls
            your actual state-transition API.
            """
            core = LanguageAgnosticCore()
            control_center = SymphonyControlCenter(core=core)

            # The exact way you construct / look up a connector will depend on your codebase.
            # For the purposes of the test, we assume a "test-connector" can be created
            # or retrieved in the given start_state, then transitioned.
            connector_id = "test-connector"

            # NOTE: The following code is intentionally generic; replace the calls to
            # `set_connector_state` and `transition_connector_state` (or equivalent)
            # with your real APIs.
            try:
                # Initialize or reset the connector into the start_state.
                control_meta = ControlMetaData(
                    connector_id=connector_id,
                    state=start_state,
                )
                control_center.set_connector_state(control_meta)

                # Attempt the transition to target_state.
                updated_meta = control_center.transition_connector_state(
                    connector_id=connector_id,
                    target_state=target_state,
                )
            except Exception:
                return False

            return getattr(updated_meta, "state", None) == target_state

        # Positive assertions: all documented valid transitions must be accepted.
        for from_state, to_states in valid_transitions.items():
            for to_state in to_states:
                with self.subTest(from_state=from_state, to_state=to_state):
                    self.assertTrue(
                        attempt_transition(from_state, to_state),
                        msg=f"Expected transition {from_state} -> {to_state} to be allowed",
                    )

        # Negative assertions: explicitly-invalid transitions must be rejected.
        for from_state, to_state in invalid_transitions:
            with self.subTest(from_state=from_state, to_state=to_state):
                self.assertFalse(
                    attempt_transition(from_state, to_state),
                    msg=f"Expected transition {from_state} -> {to_state} to be rejected",
                )

        # Terminal-state assertion: RETIRED must be treated as a terminal state
        # by the implementation (no further outgoing transitions allowed).
        for candidate_state in [
            "DISCOVERED",
            "AUTHORIZED",
            "ACTIVE",
            "DEGRADED",
            "EXPIRED",
            "BLOCKED",
            "RETIRED",  # even RETIRED -> RETIRED should normally be rejected
        ]:
            with self.subTest(from_state="RETIRED", to_state=candidate_state):
                self.assertFalse(
                    attempt_transition("RETIRED", candidate_state),
                    msg=f"Expected RETIRED to be terminal; transition to {candidate_state} must not be allowed",
                )

```

To fully wire this up against your real implementation, you will need to:

1. Replace the body of `attempt_transition` with actual calls into your connector state machine:
   - If you already have something like `SymphonyControlCenter.transition_connector_state(connector_id, target_state)` or similar, use that.
   - If your API is pure-functional (e.g., `transition_connector_state(meta: ControlMetaData, target_state: str) -> ControlMetaData`), construct the initial `ControlMetaData` with `state=start_state` and call that function instead.
2. Implement or adjust the calls to `control_center.set_connector_state(...)` and `control_center.transition_connector_state(...)` to match your framework’s real APIs, or remove them if your implementation initializes/looks up connectors differently.
3. Ensure `ControlMetaData` has the fields used in the test (`connector_id`, `state`) or adapt the constructor access to match your actual data model.
4. If the implementation signals invalid transitions differently (e.g., returning `None` or an error object instead of raising), adjust the `except`/return logic in `attempt_transition` to correctly interpret “rejected” vs. “accepted” transitions.
5. Optionally, if you have a canonical transition table in production, you can assert in this test that `valid_transitions` matches that table to keep the test and implementation in sync.
</issue_to_address>

### Comment 6
<location path="docs/SOVEREIGN_AGENTIC_RUNTIME_DOCTRINE.md" line_range="146" />
<code_context>
+┌─────────────────────────────────────────────────────────┐
+│           Symphony Control Center (Conductor)            │
+│  ┌───────────────────────────────────────────────────┐  │
+│  │  Meta Data (ControlMetaData)                      │  │
+│  │  - Creator Hierarchy: alpha_prime_omega           │  │
+│  │  - Verification: 4287                             │  │
</code_context>
<issue_to_address>
**nitpick (typo):** Consider changing “Meta Data” to the standard single word “Metadata” for consistency.

Elsewhere you use “Metadata” (e.g., in the Metadata Schema docs); updating this label to “Metadata (ControlMetaData)” will keep terminology consistent and prevent it looking like a typo.

```suggestion
│  │  Metadata (ControlMetaData)                       │  │
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread .github/workflows/ci.yml
Comment on lines +49 to 51
assert 'human_dependency_coefficient' in genome.traits
assert genome.traits['human_dependency_coefficient'] == 1.0
print('✅ Immutable genes verified')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Thông điệp log vẫn nhắc đến 'genes' trong khi phần kiểm tra bây giờ dùng 'traits', có thể gây nhầm lẫn.

Hãy đổi tên thông điệp log (và tên bước CI, nếu có) để dùng traits nhằm phản ánh chính xác nội dung được xác thực trong output CI.

Gợi ý triển khai:

        print('✅ Immutable traits verified')

Tìm trong phần còn lại của .github/workflows/ci.yml các tên bước hoặc thông điệp log vẫn còn nhắc đến "genes" (ví dụ một bước như - name: ✅ Immutable genes verified) và đổi lại thành "traits" (vd. Immutable traits). Như vậy UI và log của CI sẽ nhất quán với thuật ngữ mới.

Original comment in English

suggestion: The log message still refers to 'genes' while the check now uses 'traits', which can be confusing.

Please rename the log message (and CI step name, if applicable) to use traits so the CI output accurately reflects what is being validated.

Suggested implementation:

        print('✅ Immutable traits verified')

Search the rest of .github/workflows/ci.yml for any step names or log messages that still mention "genes" (for example, a step like - name: ✅ Immutable genes verified) and rename them to use "traits" instead (e.g. Immutable traits). This will keep the CI UI and logs consistent with the new terminology.

Comment thread .github/workflows/ci.yml
Comment on lines +54 to +56
- name: 🏛️ Verify doctrine compliance
run: |
python tests/test_doctrine_compliance.py

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Chạy bài test doctrine compliance bằng python thay vì pytest và sau đó lại chạy thêm lần nữa trong bước pytest chính có thể vừa dư thừa vừa thiếu nhất quán.

Bước này chạy python tests/test_doctrine_compliance.py, và bước pytest tests/ phía sau nhiều khả năng sẽ chạy lại file này, dẫn đến dư thừa và có thể gây vấn đề nếu test chạy chậm hoặc có trạng thái. Nó cũng bỏ qua config, fixtures và reporting của pytest. Mình gợi ý hoặc là gọi test này ở đây bằng pytest tests/test_doctrine_compliance.py và loại nó ra khỏi lần chạy pytest tests/ tổng quát (ví dụ dùng markers), hoặc bỏ hẳn bước riêng này và chỉ dựa vào lần chạy pytest chính, đồng thời đảm bảo lỗi doctrine vẫn được thể hiện rõ ràng trong output CI.

Gợi ý triển khai:

    - name: 🏛️ Verify doctrine compliance
      run: |
        pytest tests/test_doctrine_compliance.py -v
        echo '✅ Doctrine compliance verified'

    - name: 🧪 Run tests
      run: |
        pytest tests/ -v --ignore=tests/test_doctrine_compliance.py --cov=digital_ai_organism_framework --cov-report=xml --cov-report=term

Original comment in English

suggestion (testing): Running the doctrine compliance test via python instead of pytest and then again in the main pytest step may be redundant and inconsistent.

This step runs python tests/test_doctrine_compliance.py, and the later pytest tests/ step will likely run it again, which is redundant and could be problematic if the test is slow or stateful. It also bypasses pytest’s config, fixtures, and reporting. I’d suggest either calling it here via pytest tests/test_doctrine_compliance.py and excluding it from the general pytest tests/ run (e.g., with markers), or removing this dedicated step and relying on the main pytest run while ensuring doctrine failures are still clearly surfaced in CI output.

Suggested implementation:

    - name: 🏛️ Verify doctrine compliance
      run: |
        pytest tests/test_doctrine_compliance.py -v
        echo '✅ Doctrine compliance verified'

    - name: 🧪 Run tests
      run: |
        pytest tests/ -v --ignore=tests/test_doctrine_compliance.py --cov=digital_ai_organism_framework --cov-report=xml --cov-report=term

Comment on lines +72 to +76
def test_metadata_has_four_pillars(self):
"""Verify metadata includes Four Pillars configuration"""
meta = ControlMetaData()
# Four Pillars should be accessible in meta data
self.assertIsNotNone(meta)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (testing): Bài test metadata Four Pillars hiện không thực sự kiểm tra sự tồn tại hoặc cấu trúc của các trụ cột.

Bài test này chỉ kiểm tra meta không phải None, điều này vốn đã được bao phủ ở chỗ khởi tạo ControlMetaData ở nơi khác và không hề kiểm tra Four Pillars.

Để bài test có ý nghĩa, hãy khẳng định rằng cấu hình Four Pillars tồn tại và có hình dạng đúng, ví dụ:

  • Kiểm tra rằng có field trụ cột được expose (vd. meta.pillars hoặc meta.invariants["pillars"]).
  • Kiểm tra đủ bốn key mong đợi: "an_toan", "duong_dai", "tin_vao_so_lieu", "han_che_rui_ro".
  • Tùy chọn, xác thực kiểu/dạng dữ liệu kỳ vọng để bắt được các regression về schema.

Với cách viết hiện tại, bài test vẫn sẽ pass ngay cả khi Four Pillars bị xóa khỏi schema metadata.

Original comment in English

issue (testing): The Four Pillars metadata test does not actually verify the presence or structure of the pillars.

This test only checks that meta is not None, which is already covered by instantiating ControlMetaData elsewhere and doesn’t exercise the Four Pillars at all.

To make it useful, assert that the Four Pillars configuration is present and correctly shaped, for example:

  • Verify that a pillars field is exposed (e.g. meta.pillars or meta.invariants["pillars"]).
  • Check that all four expected keys are present: "an_toan", "duong_dai", "tin_vao_so_lieu", "han_che_rui_ro".
  • Optionally, validate expected types/constraints so schema regressions are caught.

As written, this test would still pass even if the Four Pillars were removed from the metadata schema.

Comment on lines +125 to +134
def test_valid_connector_states(self):
"""Verify connector states are valid"""
valid_states = [
"DISCOVERED", "AUTHORIZED", "ACTIVE",
"DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"
]

# Test that we can validate states
for state in valid_states:
self.assertIn(state, valid_states)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (testing): Bài test trạng thái connector là hiển nhiên (tautological) và không kiểm tra bất kỳ logic hay hành vi hiện thực nào.

Nó chỉ khẳng định rằng mỗi giá trị có trong cùng một list hardcode, nên không bao giờ thực thi hay xác minh logic vòng đời connector thực tế. Thay vào đó, hãy import định nghĩa trạng thái connector chuẩn (vd. enum hoặc runtime config) và assert rằng nó khớp với các trạng thái mong đợi, và tùy chọn kiểm tra không có trạng thái dư. Như vậy bài test sẽ xác thực contract vòng đời thực tế thay vì chỉ list trong chính bài test.

Original comment in English

issue (testing): Connector state test is tautological and does not exercise any implementation or behavior.

This only asserts that each value is in the same hardcoded list, so it never executes or verifies the actual connector lifecycle logic. Instead, import the canonical connector state definition (e.g., enum or runtime config) and assert it matches the expected states, and optionally that no extra states exist. That way the test validates the real lifecycle contract rather than the test’s own list.

Comment on lines +136 to +145
def test_connector_state_transitions(self):
"""Verify connector state transitions are logical"""
# Basic transition logic test
# DISCOVERED -> AUTHORIZED -> ACTIVE is valid
# ACTIVE -> DISCOVERED is invalid

valid_transitions = {
"DISCOVERED": ["AUTHORIZED", "BLOCKED"],
"AUTHORIZED": ["ACTIVE", "EXPIRED", "BLOCKED"],
"ACTIVE": ["DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Bài test chuyển trạng thái connector chỉ kiểm tra hình dạng dữ liệu, chứ không kiểm tra các chuyển trạng thái có hợp lệ hay được enforce hay không.

Mapping ở đây mã hóa các luật vòng đời, nhưng bài test chỉ kiểm tra mỗi giá trị là một list, điều này không xác nhận implementation có tôn trọng các luật đó.

Để bài test thực sự kiểm tra hành vi, hãy cân nhắc:

  • Gọi state machine / logic chuyển trạng thái connector thực tế và assert rằng những chuyển trạng thái hợp lệ được tài liệu hóa (vd. DISCOVERED -> AUTHORIZED, ACTIVE -> DEGRADED) đều thành công.
  • Thêm các case âm để khẳng định các chuyển trạng thái không hợp lệ (vd. ACTIVE -> DISCOVERED, RETIRED -> ACTIVE) bị thất bại theo cách có định nghĩa rõ ràng.
  • Assert rằng RETIRED được xử lý như một trạng thái cuối (terminal) trong implementation.

Như vậy bài test sẽ bảo vệ hành vi vòng đời thực tế chứ không chỉ hình dạng cấu trúc dữ liệu.

Gợi ý triển khai:

    def test_connector_state_transitions(self):
        """Verify connector state transitions are enforced by the implementation."""
        # Lifecycle rules encoded here should match the doctrine / production code.
        valid_transitions = {
            "DISCOVERED": ["AUTHORIZED", "BLOCKED"],
            "AUTHORIZED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "ACTIVE": ["DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"],
            "DEGRADED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "EXPIRED": ["AUTHORIZED", "BLOCKED", "RETIRED"],
            "BLOCKED": ["AUTHORIZED", "RETIRED"],
            "RETIRED": [],  # Terminal state
        }

        # Some representative invalid transitions we explicitly never want to allow.
        invalid_transitions = [
            ("ACTIVE", "DISCOVERED"),
            ("RETIRED", "ACTIVE"),
            ("RETIRED", "AUTHORIZED"),
            ("BLOCKED", "DISCOVERED"),
        ]

        # Helper that must call the real state machine / transition logic.
        #
        # It should return True if the transition is accepted by the implementation,
        # and False if it is rejected (e.g., by raising, returning an error status, etc.).
        def attempt_transition(start_state: str, target_state: str) -> bool:
            """
            Invoke the connector lifecycle implementation to perform a transition.

            This function is intentionally written in terms of framework primitives
            that exist in production (ControlMetaData, SymphonyControlCenter,
            LanguageAgnosticCore). You will need to adapt the body so it calls
            your actual state-transition API.
            """
            core = LanguageAgnosticCore()
            control_center = SymphonyControlCenter(core=core)

            # The exact way you construct / look up a connector will depend on your codebase.
            # For the purposes of the test, we assume a "test-connector" can be created
            # or retrieved in the given start_state, then transitioned.
            connector_id = "test-connector"

            # NOTE: The following code is intentionally generic; replace the calls to
            # `set_connector_state` and `transition_connector_state` (or equivalent)
            # with your real APIs.
            try:
                # Initialize or reset the connector into the start_state.
                control_meta = ControlMetaData(
                    connector_id=connector_id,
                    state=start_state,
                )
                control_center.set_connector_state(control_meta)

                # Attempt the transition to target_state.
                updated_meta = control_center.transition_connector_state(
                    connector_id=connector_id,
                    target_state=target_state,
                )
            except Exception:
                return False

            return getattr(updated_meta, "state", None) == target_state

        # Positive assertions: all documented valid transitions must be accepted.
        for from_state, to_states in valid_transitions.items():
            for to_state in to_states:
                with self.subTest(from_state=from_state, to_state=to_state):
                    self.assertTrue(
                        attempt_transition(from_state, to_state),
                        msg=f"Expected transition {from_state} -> {to_state} to be allowed",
                    )

        # Negative assertions: explicitly-invalid transitions must be rejected.
        for from_state, to_state in invalid_transitions:
            with self.subTest(from_state=from_state, to_state=to_state):
                self.assertFalse(
                    attempt_transition(from_state, to_state),
                    msg=f"Expected transition {from_state} -> {to_state} to be rejected",
                )

        # Terminal-state assertion: RETIRED must be treated as a terminal state
        # by the implementation (no further outgoing transitions allowed).
        for candidate_state in [
            "DISCOVERED",
            "AUTHORIZED",
            "ACTIVE",
            "DEGRADED",
            "EXPIRED",
            "BLOCKED",
            "RETIRED",  # even RETIRED -> RETIRED should normally be rejected
        ]:
            with self.subTest(from_state="RETIRED", to_state=candidate_state):
                self.assertFalse(
                    attempt_transition("RETIRED", candidate_state),
                    msg=f"Expected RETIRED to be terminal; transition to {candidate_state} must not be allowed",
                )

Để kết nối hoàn chỉnh với implementation thực tế, bạn cần:

  1. Thay thân hàm attempt_transition bằng các lời gọi thực vào state machine của connector:
    • Nếu đã có thứ gì đó như SymphonyControlCenter.transition_connector_state(connector_id, target_state) thì hãy dùng.
    • Nếu API của bạn là kiểu hàm thuần (vd. transition_connector_state(meta: ControlMetaData, target_state: str) -> ControlMetaData), hãy tạo ControlMetaData ban đầu với state=start_state và gọi hàm đó.
  2. Cài đặt hoặc điều chỉnh các lời gọi control_center.set_connector_state(...)control_center.transition_connector_state(...) cho khớp với API thực của framework, hoặc bỏ chúng nếu implementation của bạn khởi tạo/lookup connector theo cách khác.
  3. Đảm bảo ControlMetaData có các field được dùng trong test (connector_id, state) hoặc chỉnh lại cách khởi tạo/truy cập để phù hợp với mô hình dữ liệu thực tế.
  4. Nếu implementation báo hiệu các chuyển trạng thái không hợp lệ theo cách khác (vd. trả về None hoặc một object lỗi thay vì raise), hãy chỉnh logic except/return trong attempt_transition để diễn giải đúng thế nào là "bị từ chối" so với "được chấp nhận".
  5. Tùy chọn, nếu bạn có một bảng chuyển trạng thái chuẩn trong production, bạn có thể assert trong test này rằng valid_transitions khớp với bảng đó để giữ test và implementation luôn đồng bộ.
Original comment in English

suggestion (testing): Connector transition test only checks data shape, not that transitions are valid or enforced.

The mapping here encodes the lifecycle rules, but this test only checks that each value is a list, which doesn’t validate that the implementation respects those rules.

To make the test exercise real behavior, consider:

  • Calling the actual connector state machine / transition logic and asserting that documented valid transitions (e.g., DISCOVERED -> AUTHORIZED, ACTIVE -> DEGRADED) succeed.
  • Adding negative cases to confirm invalid transitions (e.g., ACTIVE -> DISCOVERED, RETIRED -> ACTIVE) fail in a defined way.
  • Asserting that RETIRED is treated as terminal by the implementation.

That way the test guards the real lifecycle behavior, not just the data structure shape.

Suggested implementation:

    def test_connector_state_transitions(self):
        """Verify connector state transitions are enforced by the implementation."""
        # Lifecycle rules encoded here should match the doctrine / production code.
        valid_transitions = {
            "DISCOVERED": ["AUTHORIZED", "BLOCKED"],
            "AUTHORIZED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "ACTIVE": ["DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"],
            "DEGRADED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "EXPIRED": ["AUTHORIZED", "BLOCKED", "RETIRED"],
            "BLOCKED": ["AUTHORIZED", "RETIRED"],
            "RETIRED": [],  # Terminal state
        }

        # Some representative invalid transitions we explicitly never want to allow.
        invalid_transitions = [
            ("ACTIVE", "DISCOVERED"),
            ("RETIRED", "ACTIVE"),
            ("RETIRED", "AUTHORIZED"),
            ("BLOCKED", "DISCOVERED"),
        ]

        # Helper that must call the real state machine / transition logic.
        #
        # It should return True if the transition is accepted by the implementation,
        # and False if it is rejected (e.g., by raising, returning an error status, etc.).
        def attempt_transition(start_state: str, target_state: str) -> bool:
            """
            Invoke the connector lifecycle implementation to perform a transition.

            This function is intentionally written in terms of framework primitives
            that exist in production (ControlMetaData, SymphonyControlCenter,
            LanguageAgnosticCore). You will need to adapt the body so it calls
            your actual state-transition API.
            """
            core = LanguageAgnosticCore()
            control_center = SymphonyControlCenter(core=core)

            # The exact way you construct / look up a connector will depend on your codebase.
            # For the purposes of the test, we assume a "test-connector" can be created
            # or retrieved in the given start_state, then transitioned.
            connector_id = "test-connector"

            # NOTE: The following code is intentionally generic; replace the calls to
            # `set_connector_state` and `transition_connector_state` (or equivalent)
            # with your real APIs.
            try:
                # Initialize or reset the connector into the start_state.
                control_meta = ControlMetaData(
                    connector_id=connector_id,
                    state=start_state,
                )
                control_center.set_connector_state(control_meta)

                # Attempt the transition to target_state.
                updated_meta = control_center.transition_connector_state(
                    connector_id=connector_id,
                    target_state=target_state,
                )
            except Exception:
                return False

            return getattr(updated_meta, "state", None) == target_state

        # Positive assertions: all documented valid transitions must be accepted.
        for from_state, to_states in valid_transitions.items():
            for to_state in to_states:
                with self.subTest(from_state=from_state, to_state=to_state):
                    self.assertTrue(
                        attempt_transition(from_state, to_state),
                        msg=f"Expected transition {from_state} -> {to_state} to be allowed",
                    )

        # Negative assertions: explicitly-invalid transitions must be rejected.
        for from_state, to_state in invalid_transitions:
            with self.subTest(from_state=from_state, to_state=to_state):
                self.assertFalse(
                    attempt_transition(from_state, to_state),
                    msg=f"Expected transition {from_state} -> {to_state} to be rejected",
                )

        # Terminal-state assertion: RETIRED must be treated as a terminal state
        # by the implementation (no further outgoing transitions allowed).
        for candidate_state in [
            "DISCOVERED",
            "AUTHORIZED",
            "ACTIVE",
            "DEGRADED",
            "EXPIRED",
            "BLOCKED",
            "RETIRED",  # even RETIRED -> RETIRED should normally be rejected
        ]:
            with self.subTest(from_state="RETIRED", to_state=candidate_state):
                self.assertFalse(
                    attempt_transition("RETIRED", candidate_state),
                    msg=f"Expected RETIRED to be terminal; transition to {candidate_state} must not be allowed",
                )

To fully wire this up against your real implementation, you will need to:

  1. Replace the body of attempt_transition with actual calls into your connector state machine:
    • If you already have something like SymphonyControlCenter.transition_connector_state(connector_id, target_state) or similar, use that.
    • If your API is pure-functional (e.g., transition_connector_state(meta: ControlMetaData, target_state: str) -> ControlMetaData), construct the initial ControlMetaData with state=start_state and call that function instead.
  2. Implement or adjust the calls to control_center.set_connector_state(...) and control_center.transition_connector_state(...) to match your framework’s real APIs, or remove them if your implementation initializes/looks up connectors differently.
  3. Ensure ControlMetaData has the fields used in the test (connector_id, state) or adapt the constructor access to match your actual data model.
  4. If the implementation signals invalid transitions differently (e.g., returning None or an error object instead of raising), adjust the except/return logic in attempt_transition to correctly interpret “rejected” vs. “accepted” transitions.
  5. Optionally, if you have a canonical transition table in production, you can assert in this test that valid_transitions matches that table to keep the test and implementation in sync.

┌─────────────────────────────────────────────────────────┐
│ Symphony Control Center (Conductor) │
│ ┌───────────────────────────────────────────────────┐ │
│ │ Meta Data (ControlMetaData) │ │

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick (typo): Hãy cân nhắc đổi "Meta Data" thành dạng một từ tiêu chuẩn "Metadata" để nhất quán.

Ở chỗ khác bạn dùng "Metadata" (vd. trong tài liệu Metadata Schema); cập nhật nhãn này thành "Metadata (ControlMetaData)" sẽ giúp thuật ngữ nhất quán và tránh trông giống lỗi chính tả.

Suggested change
│ │ Meta Data (ControlMetaData) │ │
│ │ Metadata (ControlMetaData) │ │
Original comment in English

nitpick (typo): Consider changing “Meta Data” to the standard single word “Metadata” for consistency.

Elsewhere you use “Metadata” (e.g., in the Metadata Schema docs); updating this label to “Metadata (ControlMetaData)” will keep terminology consistent and prevent it looking like a typo.

Suggested change
│ │ Meta Data (ControlMetaData) │ │
│ │ Metadata (ControlMetaData) │ │

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This WIP PR establishes DAIOF-Framework as the canonical source-of-truth for the Sovereign Agentic Runtime by adding five new doctrine documents, wiring them into the docs index and ARCHITECTURE.md, and introducing an initial doctrine-compliance test suite plus a CI step that runs it. It also fixes a stale genome.genes reference in the existing CI script to use genome.traits.

Changes:

  • Adds five canonical docs: SOVEREIGN_AGENTIC_RUNTIME_DOCTRINE, CONNECTOR_LIFECYCLE (7 states + 4 probes), METADATA_SCHEMA, RUNTIME_STATE_MACHINE, EXECUTION_EVIDENCE_REGISTRY; updates docs/index.md and docs/ARCHITECTURE.md to cross-link them.
  • Adds tests/test_doctrine_compliance.py covering creator attribution, verification code 4287, safety floor, K-state, Four Pillars, Symphony init, and immutable genes.
  • Updates .github/workflows/ci.yml: corrects genome.genesgenome.traits in the inline immutable-genes check and adds a "Verify doctrine compliance" step invoking the new test script.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
docs/SOVEREIGN_AGENTIC_RUNTIME_DOCTRINE.md New constitutional doctrine doc (sovereignty, Four Pillars, Symphony architecture, immutable truths).
docs/CONNECTOR_LIFECYCLE.md Defines 7-state connector lifecycle, 4 probe specs, recovery matrix, attestation events.
docs/METADATA_SCHEMA.md Canonical metadata fields and validation functions for source-of-truth tracking.
docs/RUNTIME_STATE_MACHINE.md Symphony, organism-lifecycle, health, and connector state machines + Four Pillars transition validator.
docs/EXECUTION_EVIDENCE_REGISTRY.md Protocol for mirroring Asana/Figma/Linear/Airtable evidence into the repo.
docs/ARCHITECTURE.md Adds doctrine reference header and a Canonical Documentation Reference section.
docs/index.md Adds Core/Canonical doc subsections linking the new specs.
tests/test_doctrine_compliance.py New unittest module asserting doctrine invariants; some tests are tautological.
.github/workflows/ci.yml Fixes genestraits reference and adds doctrine-compliance step.
Comments suppressed due to low confidence (3)

tests/test_doctrine_compliance.py:134

  • This test is tautological: it iterates over valid_states and asserts each item is in valid_states, which is guaranteed to pass. It does not actually validate any production code. To be meaningful, it should compare against a list of states defined in the implementation (e.g. a connector state enum imported from the framework module).
    def test_valid_connector_states(self):
        """Verify connector states are valid"""
        valid_states = [
            "DISCOVERED", "AUTHORIZED", "ACTIVE",
            "DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"
        ]

        # Test that we can validate states
        for state in valid_states:
            self.assertIn(state, valid_states)

tests/test_doctrine_compliance.py:154

  • This test only asserts that each value in the locally-defined dict is a list — it does not exercise any code under test or assert the actual transition rules described in CONNECTOR_LIFECYCLE.md. The assertion will always pass for any dict whose values are lists. Consider importing the transition logic from production code and asserting that, e.g., ACTIVE → DISCOVERED is rejected and the documented valid transitions are accepted.
    def test_connector_state_transitions(self):
        """Verify connector state transitions are logical"""
        # Basic transition logic test
        # DISCOVERED -> AUTHORIZED -> ACTIVE is valid
        # ACTIVE -> DISCOVERED is invalid

        valid_transitions = {
            "DISCOVERED": ["AUTHORIZED", "BLOCKED"],
            "AUTHORIZED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "ACTIVE": ["DEGRADED", "EXPIRED", "BLOCKED", "RETIRED"],
            "DEGRADED": ["ACTIVE", "EXPIRED", "BLOCKED"],
            "EXPIRED": ["AUTHORIZED", "BLOCKED", "RETIRED"],
            "BLOCKED": ["AUTHORIZED", "RETIRED"],
            "RETIRED": []  # Terminal state
        }

        # Verify transitions are defined
        for state, transitions in valid_transitions.items():
            self.assertIsInstance(transitions, list)

tests/test_doctrine_compliance.py:177

  • run_tests() returns an exit code but the script is invoked from the new CI step via python tests/test_doctrine_compliance.py without set -e semantics on the python exit; CI will fail on non-zero exit, which is correct. However, the subsequent echo '✅ Doctrine compliance verified' runs unconditionally only if the python step succeeded — that part is fine. More importantly, calling exit(run_tests()) inside __main__ shadows the builtin via the imported unittest namespace pattern; this works but sys.exit(run_tests()) would be clearer and avoids relying on the REPL-oriented exit callable in production scripts.
if __name__ == '__main__':
    exit(run_tests())

Comment on lines +75 to +76
# Four Pillars should be accessible in meta data
self.assertIsNotNone(meta)
Comment thread .github/workflows/ci.yml
Comment on lines +56 to 61
python tests/test_doctrine_compliance.py
echo '✅ Doctrine compliance verified'

- name: 🧪 Run tests
run: |
pytest tests/ -v --cov=digital_ai_organism_framework --cov-report=xml --cov-report=term
| **GitHub** | ✅ ACTIVE | Code repository, canonical source-of-truth | **YES** |
| **Figma** | ✅ ACTIVE | Visual topology substrate | No |
| **Asana** | ✅ ACTIVE | Execution backlog substrate | No |
| **Linear** | ⚠️ DEGRADED | Project management (401 session expired) | No |
Comment thread docs/ARCHITECTURE.md
- ✅ **GitHub**: ACTIVE - Canonical source-of-truth
- ✅ **Figma**: ACTIVE - Visual topology substrate
- ✅ **Asana**: ACTIVE - Execution backlog substrate
- ⚠️ **Linear**: DEGRADED - 401 session expired, requires re-authentication
- [ ] Enforce immutability (no direct state mutation)
- [ ] Maintain K-State = 1 throughout

**Validation**: Run `pytest tests/test_state_machine.py` to verify compliance.
'source_of_truth': 'github:NguyenCuong1989/DAIOF-Framework',
'creator_attribution': 'alpha_prime_omega',
'verification_code': 4287,
'synced_at': datetime.utcnow().isoformat() + 'Z',
Comment thread docs/METADATA_SCHEMA.md
Comment on lines +251 to +287
### 7. last_synced_from

**Type**: String (URI) or null
**Required**: No (null if never synced)
**Immutable**: No (updates on sync)
**Format**: `scheme:location?timestamp=ISO8601` or `null`

**Description**: Last external substrate sync source and timestamp.

**Purpose:**
- Track external substrate sync state
- Detect drift from external tools
- Enable sync conflict resolution

**Validation:**
```python
def validate_last_synced_from(synced: str | None) -> bool:
if synced is None:
return True # Never synced is valid

# Format: "asana:123456789?timestamp=2026-05-14T23:47:24.959Z"
if '?' not in synced:
return False

source, query = synced.split('?', 1)
if not query.startswith('timestamp='):
return False

timestamp = query.split('=', 1)[1]
return validate_created_at(timestamp)
```

**Examples:**
- `null` - Never synced from external substrate
- `"asana:1234567890?timestamp=2026-05-14T10:00:00.000Z"` - Synced from Asana
- `"figma:file-abc123?timestamp=2026-05-14T09:00:00.000Z"` - Synced from Figma

Comment thread docs/METADATA_SCHEMA.md
Comment on lines +305 to +319
```python
def validate_runtime_consumer(consumer: str) -> bool:
valid_consumers = [
'SymphonyControlCenter',
'DigitalOrganism',
'DigitalEcosystem',
'DigitalGenome',
'DigitalMetabolism',
'DigitalNervousSystem',
'DRProtocol',
'AttestationLog',
'AuxiliaryPilot'
]
return consumer in valid_consumers or consumer.startswith('Custom')
```
### States

```
INITIALIZING → HARMONIZING → PERFORMING ⇄ OPTIMIZING → EVOLVING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Canonicalize Sovereign Agentic Runtime doctrine and connector lifecycle

3 participants