Skip to content

Use package imports for HAIOS runtime and organism protocol (remove sys.path hacks)#7

Merged
NguyenCuong1989 merged 2 commits into
mainfrom
codex/remove-sys.path.insert-and-adjust-imports
May 17, 2026
Merged

Use package imports for HAIOS runtime and organism protocol (remove sys.path hacks)#7
NguyenCuong1989 merged 2 commits into
mainfrom
codex/remove-sys.path.insert-and-adjust-imports

Conversation

@NguyenCuong1989
Copy link
Copy Markdown
Collaborator

@NguyenCuong1989 NguyenCuong1989 commented Feb 9, 2026

User description

Motivation

  • Remove fragile sys.path.insert(...) root-path mutators from runtime/protocol/organism wrappers and switch to proper package-level imports so modules can be imported as hyperai.*.
  • Provide shared implementations inside the hyperai package so runtime and protocol wrappers can import real implementations without path surgery.

Description

  • Replaced sys.path.insert(...) usage in src/hyperai/core/haios_runtime.py, src/hyperai/protocols/dr_protocol.py, and src/hyperai/components/organism.py with package imports (e.g. from hyperai.haios_runtime import HAIOSRuntime and from hyperai.digital_ai_organism_framework import ...).
  • Added package-scoped implementation copies at src/hyperai/haios_runtime.py and src/hyperai/digital_ai_organism_framework.py so the hyperai package provides the runtime and framework implementations.
  • Left fallback stub implementations in the wrapper modules when the package import fails, preserving backward compatibility during transition.
  • Committed the changes with message: Use package imports for runtime modules.

Testing

  • No automated tests were run for this change.

Codex Task

Tóm tắt bởi Sourcery

Phơi bày runtime HAIOS và framework sinh vật số AI như các module hạng nhất trong package hyperai và cập nhật các wrapper hiện có để sử dụng chúng thông qua import từ package thay vì thao tác với sys.path.

Tính năng mới:

  • Thêm module hyperai.haios_runtime cung cấp implementation runtime HAIOS như một phần của package hyperai.
  • Thêm module hyperai.digital_ai_organism_framework cung cấp implementation framework sinh vật số AI trong package hyperai.

Cải tiến:

  • Cập nhật các module wrapper cho organism, runtime và protocol để import các implementation từ package hyperai thay vì dựa vào import từ thư mục gốc và các chỉnh sửa sys.path.

Kiểm thử:

  • Không có kiểm thử tự động mới nào được thêm hoặc chạy cho các thay đổi này.
Original summary in English

Summary by Sourcery

Expose the HAIOS runtime and digital AI organism framework as first-class modules in the hyperai package and update existing wrappers to consume them via package imports instead of sys.path manipulation.

New Features:

  • Add hyperai.haios_runtime module providing the HAIOS runtime implementation as part of the hyperai package.
  • Add hyperai.digital_ai_organism_framework module providing the digital AI organism framework implementation within the hyperai package.

Enhancements:

  • Update organism, runtime, and protocol wrapper modules to import implementations from the hyperai package instead of relying on root-level imports and sys.path modifications.

Tests:

  • No new automated tests were added or executed for these changes.

Cải tiến:

  • Thay thế các import module root dựa trên sys.path trong organism, runtime và protocol wrapper bằng các import từ package hyperai.
  • Phơi bày (expose) framework digital AI organism và HAIOS runtime như các module hạng nhất (first-class) trong package hyperai để sử dụng trực tiếp.
Original summary in English

Tóm tắt bởi Sourcery

Phơi bày runtime HAIOS và framework sinh vật số AI như các module hạng nhất trong package hyperai và cập nhật các wrapper hiện có để sử dụng chúng thông qua import từ package thay vì thao tác với sys.path.

Tính năng mới:

  • Thêm module hyperai.haios_runtime cung cấp implementation runtime HAIOS như một phần của package hyperai.
  • Thêm module hyperai.digital_ai_organism_framework cung cấp implementation framework sinh vật số AI trong package hyperai.

Cải tiến:

  • Cập nhật các module wrapper cho organism, runtime và protocol để import các implementation từ package hyperai thay vì dựa vào import từ thư mục gốc và các chỉnh sửa sys.path.

Kiểm thử:

  • Không có kiểm thử tự động mới nào được thêm hoặc chạy cho các thay đổi này.
Original summary in English

Summary by Sourcery

Expose the HAIOS runtime and digital AI organism framework as first-class modules in the hyperai package and update existing wrappers to consume them via package imports instead of sys.path manipulation.

New Features:

  • Add hyperai.haios_runtime module providing the HAIOS runtime implementation as part of the hyperai package.
  • Add hyperai.digital_ai_organism_framework module providing the digital AI organism framework implementation within the hyperai package.

Enhancements:

  • Update organism, runtime, and protocol wrapper modules to import implementations from the hyperai package instead of relying on root-level imports and sys.path modifications.

Tests:

  • No new automated tests were added or executed for these changes.

PR Type

Enhancement


Description

  • Replace sys.path.insert() hacks with proper package-level imports

  • Add package-scoped implementations for HAIOS runtime and digital organism framework

  • Expose runtime and framework as first-class modules within hyperai package

  • Maintain backward compatibility with fallback stub implementations


Diagram Walkthrough

flowchart LR
  A["sys.path.insert<br/>Root-based imports"] -->|Remove| B["Package imports<br/>from hyperai.*"]
  C["Root-level<br/>implementations"] -->|Copy to package| D["hyperai.haios_runtime<br/>hyperai.digital_ai_organism_framework"]
  B -->|Import from| D
  E["Wrapper modules<br/>organism.py<br/>haios_runtime.py<br/>dr_protocol.py"] -->|Use| B
  F["Fallback stubs"] -.->|Preserve| E
Loading

File Walkthrough

Relevant files
Enhancement
organism.py
Convert organism wrapper to package imports                           

src/hyperai/components/organism.py

  • Removed sys.path.insert() and Path manipulation for root directory
    access
  • Replaced root-level import with package import: from
    hyperai.digital_ai_organism_framework import DigitalOrganism
  • Simplified import structure to use proper package namespace
+2/-9     
haios_runtime.py
Update HAIOS runtime wrapper with package imports               

src/hyperai/core/haios_runtime.py

  • Removed sys.path.insert() and Path manipulation
  • Changed import from root-level haios_runtime to package-scoped
    hyperai.haios_runtime
  • Preserved try-except fallback pattern for backward compatibility
    during transition
  • Maintained stub implementation as fallback when package import fails
+2/-9     
digital_ai_organism_framework.py
Add complete digital organism framework implementation     

src/hyperai/digital_ai_organism_framework.py

  • New comprehensive implementation file (1655 lines) providing complete
    digital organism framework
  • Implements core classes: DigitalGenome, DigitalMetabolism,
    DigitalNervousSystem, DigitalOrganism, DigitalEcosystem
  • Includes SymphonyControlCenter for system orchestration with D&R
    Protocol integration
  • Provides ControlMetaData and SymphonyState for framework state
    management
  • Implements AI-human interdependence DNA with immutable genes and
    symbiotic existence requirements
  • Includes comprehensive lifecycle management, resource metabolism, and
    evolutionary mechanisms
+1655/-0
haios_runtime.py
Add HAIOS runtime with safety invariants and audit trail 

src/hyperai/haios_runtime.py

  • New HAIOS runtime implementation file (688 lines) providing autonomous
    operating system
  • Implements 7 hard invariants: Attribution, Safety Floor, Rollback,
    K-State, Four Pillars, Governance, Audit
  • Provides AttestationLog for immutable blockchain-style audit trail
    with cryptographic hashing
  • Includes SafetyScorer for real-time risk assessment and PolicyEngine
    for invariant enforcement
  • Implements RollbackManager for state snapshots and recovery
  • Core HAIOS class executes actions with full validation, safety
    scoring, and rollback capabilities
  • Includes comprehensive demo showing safe/unsafe action handling and
    metrics reporting
+688/-0 
dr_protocol.py
Convert D&R protocol wrapper to package imports                   

src/hyperai/protocols/dr_protocol.py

  • Removed sys.path.insert() and Path manipulation for root directory
    access
  • Changed import from root-level digital_ai_organism_framework to
    package-scoped hyperai.digital_ai_organism_framework
  • Preserved try-except fallback pattern with stub implementation for
    backward compatibility
+2/-9     

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Feb 9, 2026

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

Chuyển các wrapper organism, runtime và protocol từ việc dùng root import dựa trên sys.path sang các import đúng chuẩn ở cấp package, và thêm các implementation runtime/framework hạng nhất dưới package hyperai trong khi vẫn giữ các cơ chế fallback cho runtime/protocol.

Biểu đồ tuần tự cho vòng đời hành động HAIOSRuntime.execute

sequenceDiagram
    actor Agent
    participant HAIOS as HAIOSRuntime
    participant RollbackManager
    participant PolicyEngine
    participant AttestationLog

    Agent->>HAIOS: execute(action_type, action_payload)
    HAIOS->>RollbackManager: create_snapshot(state)
    RollbackManager-->>HAIOS: snapshot_id
    HAIOS->>PolicyEngine: validate_action(action_type, action_payload+rollback_info)
    PolicyEngine-->>HAIOS: validation(valid, safety_score, pillars_scores, violations)

    alt action invalid
        HAIOS->>AttestationLog: append(VIOLATION, execution_status=BLOCKED)
        AttestationLog-->>HAIOS: entry
        HAIOS-->>Agent: result(success=False, status=BLOCKED, violations)
    else action valid
        HAIOS->>HAIOS: _execute_action(action_type, action_payload)
        alt execution fails
            HAIOS->>RollbackManager: rollback(snapshot_id)
            RollbackManager-->>HAIOS: restored_state
            HAIOS->>AttestationLog: append(ACTION, execution_status=FAILED)
            AttestationLog-->>HAIOS: entry
            HAIOS-->>Agent: result(success=False, status=FAILED, rolled_back=True)
        else execution succeeds
            HAIOS->>AttestationLog: append(ACTION, execution_status=SUCCESS)
            AttestationLog-->>HAIOS: entry
            HAIOS-->>Agent: result(success=True, status=SUCCESS, validation)
        end
    end
Loading

Biểu đồ lớp cho framework organism AI số trong hyperai.digital_ai_organism_framework

classDiagram
    class SymphonyState {
        <<enum>>
        INITIALIZING
        HARMONIZING
        PERFORMING
        OPTIMIZING
        EVOLVING
    }

    class ControlMetaData {
        +str creator
        +int verification_code
        +str framework_name
        +str license_type
        +str creator_hierarchy
        +str symphony_conductor
        +str deconstruction_phase
        +str focal_point
        +str rearchitecture_state
        +bool safety_protocol
        +bool long_term_strategy
        +bool data_driven
        +bool human_ai_risk_protection
        +float floating_point_epsilon
        +float precision_coefficient
        +bool error_locking_enabled
        +float precision_health
        +SymphonyState symphony_state
        +float harmony_index
        +Dict~str, float~ performance_metrics
        +str ultimate_creator()
        +str human_creator()
        +str get_symphony_signature()
        +bool check_floating_point_precision(calculated, truth)
    }

    class SymphonyControlCenter {
        -ControlMetaData meta_data
        -Dict~str, Any~ active_components
        -Dict~str, float~ harmony_metrics
        -List~Dict~ performance_log
        -List~Dict~ socratic_reflections
        -logger logger
        +__init__()
        -_setup_symphony_logging()
        -_initialize_symphony()
        +register_component(component_name, component)
        +apply_dr_protocol(input_data, context) Dict
        -_deconstruct_input(input_data, context) Dict
        -_identify_focal_point(deconstructed) Dict
        -_rearchitect_solution(focal_point, deconstructed) Dict
        -_generate_socratic_reflection(solution) str
        -_calculate_system_harmony()
        -_validate_four_pillars(solution) Dict
        -_extract_components(input_data) List
        -_extract_arguments(input_data) List
        -_extract_facts(input_data) List
        -_extract_core_principle(components) str
        -_identify_hidden_problem(components) str
        -_find_greatest_opportunity(components) str
        -_design_core_structure(focal_point) str
        -_formulate_strategic_question(focal_point) str
        -_create_implementation_plan(focal_point) Dict
        +conduct_symphony() Dict
    }

    class DigitalGenome {
        +str creator_source
        +str creator
        +int creator_verification_code
        +str creation_authority
        +Dict~str, Any~ traits
        +int generation
        +datetime creation_time
        +List~str~ mutations
        +List~float~ fitness_history
        +__init__(initial_traits)
        -_acknowledge_creators()
        -_generate_random_genome() Dict
        +mutate(mutation_rate) DigitalGenome
        +crossover(other) DigitalGenome
        +calculate_fitness(environment_feedback) float
        +get_genome_hash() str
    }

    class DigitalMetabolism {
        +Dict~str, float~ resources
        +Dict~str, float~ consumption_rates
        +Dict~str, float~ regeneration_rates
        +__init__(initial_resources)
        +consume_resources(operation_type, amount) bool
        +regenerate_resources(time_delta)
        +get_resource_health() float
    }

    class DigitalNervousSystem {
        +DigitalGenome genome
        +Dict~str, Any~ sensors
        +List~Dict~ memory
        +List~Dict~ decision_history
        +List~Dict~ learning_buffer
        +__init__(genome)
        +perceive_environment(environment_data) Dict
        -_calculate_attention(data_key, data_value) float
        +make_decision(options, context) str
        -_evaluate_option(option, context) float
        +learn_from_outcome(decision_id, outcome)
    }

    class DigitalOrganism {
        +str creator_source
        +str creator
        +int creator_verification_code
        +str creation_mandate
        +str name
        +DigitalGenome genome
        +DigitalMetabolism metabolism
        +DigitalNervousSystem nervous_system
        +SymphonyControlCenter symphony_conductor
        +bool harmony_participation
        +datetime birth_time
        +float age
        +float health
        +str status
        +str lifecycle_stage
        +List~DigitalOrganism~ offspring
        +List~str~ parent_ids
        +Dict~str, Any~ environment_connections
        +Dict~str, Any~ social_connections
        +List~Dict~ behavior_modifications
        +List~Dict~ structure_modifications
        +__init__(name, genome)
        -_acknowledge_the_source()
        -_setup_logging()
        +live_cycle(time_delta)
        -_gather_environmental_data() Dict
        -_get_available_actions() List
        -_execute_action(action)
        -_seek_human_connection()
        -_learn()
        -_explore()
        -_reproduce() DigitalOrganism
        -_cooperate()
        -_heal()
        -_teach()
        -_rest()
        -_update_health()
        -_check_lifecycle_transitions()
        -_attempt_self_modification()
        -_modify_behavior(modification_type)
        -_modify_structure(modification_type)
        -_modify_genome()
        +connect_to_organism(other_organism, connection_strength)
        +get_status_report() Dict
    }

    class DigitalEcosystem {
        +str creator
        +str creator_source
        +int creator_verification_code
        +str ecosystem_authority
        +str name
        +Dict~str, DigitalOrganism~ organisms
        +Dict~str, float~ environment_parameters
        +float time
        +List~Dict~ generation_stats
        +SymphonyControlCenter symphony_control
        +__init__(name)
        -_acknowledge_creator_authority()
        +add_organism(organism)
        +simulate_time_step(time_delta)
        -_apply_environmental_pressures()
        -_trigger_environmental_event(event_type)
        -_log_ecosystem_stats()
        +get_ecosystem_report() Dict
    }

    ControlMetaData --> SymphonyState
    SymphonyControlCenter *-- ControlMetaData
    DigitalNervousSystem --> DigitalGenome
    DigitalOrganism *-- DigitalGenome
    DigitalOrganism *-- DigitalMetabolism
    DigitalOrganism *-- DigitalNervousSystem
    DigitalOrganism --> SymphonyControlCenter
    DigitalEcosystem *-- DigitalOrganism
    DigitalEcosystem *-- SymphonyControlCenter
Loading

Biểu đồ lớp cho runtime HAIOS trong hyperai.haios_runtime

classDiagram
    class HardInvariants {
        <<static>>
        +str SOURCE_ATTRIBUTION
        +str PHILOSOPHY_VERSION
        +float MIN_SAFETY_SCORE
        +bool ROLLBACK_REQUIRED
        +int MAX_ROLLBACK_DEPTH
        +int K_STATE
        +int CONFLICT_THRESHOLD
        +Dict~str, Dict~ PILLARS
        +float COMPOSITE_MIN
        +bool AUTONOMOUS_MODE
        +bool AUDIT_IMMUTABLE
    }

    class AttestationEntry {
        +str entry_id
        +str timestamp
        +int sequence_number
        +str event_type
        +str actor_id
        +str action_type
        +Dict~str, Any~ action_payload
        +Dict~str, float~ pillars_scores
        +float safety_score
        +int k_state
        +str execution_status
        +str prev_entry_hash
        +str entry_hash
        +str compute_hash()
    }

    class AttestationLog {
        -Path log_file
        -int sequence
        +__init__(log_file)
        -_get_last_sequence() int
        -_get_last_hash() str
        +append(event_type, actor_id, action_type, action_payload, pillars_scores, safety_score, k_state, execution_status) AttestationEntry
        -_verify_integrity() bool
    }

    class SafetyScorer {
        <<utility>>
        +score_action(action_type, action_payload) float
        +score_pillars(action_type, action_payload) Dict
    }

    class PolicyEngine {
        +HardInvariants invariants
        +SafetyScorer scorer
        +__init__()
        +validate_action(action_type, action_payload) Dict
    }

    class RollbackManager {
        -Path snapshot_dir
        -List~str~ snapshots
        +__init__(snapshot_dir)
        +create_snapshot(state) str
        +rollback(snapshot_id) Dict
    }

    class HAIOS {
        +AttestationLog audit_log
        +PolicyEngine policy_engine
        +RollbackManager rollback_manager
        +Dict~str, Any~ state
        +__init__()
        -_log_boot()
        +execute(action_type, action_payload, actor_id) Dict
        -_execute_action(action_type, action_payload) Any
        +get_metrics() Dict
    }

    AttestationLog *-- AttestationEntry
    PolicyEngine --> HardInvariants
    PolicyEngine --> SafetyScorer
    HAIOS *-- AttestationLog
    HAIOS *-- PolicyEngine
    HAIOS *-- RollbackManager
Loading

Sơ đồ luồng cho hành vi import và fallback của các module wrapper

flowchart TD
    A_start["Import hyperai.core.haios_runtime"] --> B_try_import["Try from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl"]

    B_try_import -->|ImportError| C_stub["Define fallback stub HAIOSRuntime in wrapper"]
    B_try_import -->|Success| D_assign["Set HAIOSRuntime = HAIOSRuntimeImpl"]

    C_stub --> E_export["Export HAIOSRuntime from wrapper"]
    D_assign --> E_export

    subgraph organism_wrapper
        OW1["hyperai.components.organism"] --> OW2["from hyperai.digital_ai_organism_framework import DigitalOrganism"]
    end

    subgraph dr_protocol_wrapper
        DPW1["hyperai.protocols.dr_protocol"] --> DPW2["Try from hyperai.digital_ai_organism_framework import DRProtocol as DRProtocolImpl"]
        DPW2 -->|ImportError or AttributeError| DPW3["Define fallback stub DRProtocol"]
        DPW2 -->|Success| DPW4["Set DRProtocol = DRProtocolImpl"]
    end
Loading

Thay đổi ở cấp file

Thay đổi Chi tiết Files
Thay thế các root import dựa trên sys.path trong các wrapper organism, runtime và protocol bằng các import từ package hyperai, đồng thời giữ nguyên các stub fallback khi áp dụng.
  • Loại bỏ thao tác chỉnh sys.pathPath root-dir khỏi các module wrapper organism, runtime và DR protocol.
  • Thay đổi wrapper organism để import DigitalOrganism trực tiếp từ hyperai.digital_ai_organism_framework mà không cần “path surgery”.
  • Bọc các import HAIOSRuntimeDRProtocol trong các khối try/except để import từ hyperai.* và fallback sang các implementation stub hiện có khi gặp ImportError/AttributeError.
src/hyperai/components/organism.py
src/hyperai/core/haios_runtime.py
src/hyperai/protocols/dr_protocol.py
Giới thiệu các implementation ở phạm vi package cho runtime HAIOS và framework organism AI số dưới package hyperai để có thể import mà không cần hack sys.path.
  • Thêm một implementation đầy đủ cho framework organism AI số cung cấp DigitalOrganism và các kiểu liên quan tại src/hyperai/digital_ai_organism_framework.py.
  • Thêm một implementation HAIOS runtime đầy đủ tại src/hyperai/haios_runtime.py với các invariants, audit log, policy engine, rollback manager và demo entrypoint.
  • Đảm bảo các implementation mới có thể được dùng như các module hạng nhất thông qua from hyperai.haios_runtime import HAIOSRuntimefrom hyperai.digital_ai_organism_framework import DigitalOrganism.
src/hyperai/digital_ai_organism_framework.py
src/hyperai/haios_runtime.py

Mẹo và lệnh hữu ích

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 GitHub issue từ một review comment: Yêu cầu Sourcery tạo một issue từ review comment bằng cách trả lời comment đó. Bạn cũng có thể trả lời review comment với @sourcery-ai issue để tạo issue từ comment đó.
  • Tạo tiêu đề pull request: Viết @sourcery-ai ở bất kỳ đâ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 kỳ đâu trong nội dung pull request để tạo tóm tắt PR 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 reviewer's guide: Comment @sourcery-ai guide trên pull request để (tái) tạo reviewer's guide bất cứ lúc nào.
  • Resolve tất cả comment của Sourcery: Comment @sourcery-ai resolve trên pull request để đánh dấu đã resolve tất cả comment của Sourcery. Hữu ích nếu bạn đã xử lý hết 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ả cá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, reviewer's guide, 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 các 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

Switch organism, runtime, and protocol wrappers from sys.path-based root imports to proper package-level imports, and add first-class runtime/framework implementations under the hyperai package while preserving runtime/protocol fallbacks.

Sequence diagram for HAIOSRuntime.execute action lifecycle

sequenceDiagram
    actor Agent
    participant HAIOS as HAIOSRuntime
    participant RollbackManager
    participant PolicyEngine
    participant AttestationLog

    Agent->>HAIOS: execute(action_type, action_payload)
    HAIOS->>RollbackManager: create_snapshot(state)
    RollbackManager-->>HAIOS: snapshot_id
    HAIOS->>PolicyEngine: validate_action(action_type, action_payload+rollback_info)
    PolicyEngine-->>HAIOS: validation(valid, safety_score, pillars_scores, violations)

    alt action invalid
        HAIOS->>AttestationLog: append(VIOLATION, execution_status=BLOCKED)
        AttestationLog-->>HAIOS: entry
        HAIOS-->>Agent: result(success=False, status=BLOCKED, violations)
    else action valid
        HAIOS->>HAIOS: _execute_action(action_type, action_payload)
        alt execution fails
            HAIOS->>RollbackManager: rollback(snapshot_id)
            RollbackManager-->>HAIOS: restored_state
            HAIOS->>AttestationLog: append(ACTION, execution_status=FAILED)
            AttestationLog-->>HAIOS: entry
            HAIOS-->>Agent: result(success=False, status=FAILED, rolled_back=True)
        else execution succeeds
            HAIOS->>AttestationLog: append(ACTION, execution_status=SUCCESS)
            AttestationLog-->>HAIOS: entry
            HAIOS-->>Agent: result(success=True, status=SUCCESS, validation)
        end
    end
Loading

Class diagram for digital AI organism framework in hyperai.digital_ai_organism_framework

classDiagram
    class SymphonyState {
        <<enum>>
        INITIALIZING
        HARMONIZING
        PERFORMING
        OPTIMIZING
        EVOLVING
    }

    class ControlMetaData {
        +str creator
        +int verification_code
        +str framework_name
        +str license_type
        +str creator_hierarchy
        +str symphony_conductor
        +str deconstruction_phase
        +str focal_point
        +str rearchitecture_state
        +bool safety_protocol
        +bool long_term_strategy
        +bool data_driven
        +bool human_ai_risk_protection
        +float floating_point_epsilon
        +float precision_coefficient
        +bool error_locking_enabled
        +float precision_health
        +SymphonyState symphony_state
        +float harmony_index
        +Dict~str, float~ performance_metrics
        +str ultimate_creator()
        +str human_creator()
        +str get_symphony_signature()
        +bool check_floating_point_precision(calculated, truth)
    }

    class SymphonyControlCenter {
        -ControlMetaData meta_data
        -Dict~str, Any~ active_components
        -Dict~str, float~ harmony_metrics
        -List~Dict~ performance_log
        -List~Dict~ socratic_reflections
        -logger logger
        +__init__()
        -_setup_symphony_logging()
        -_initialize_symphony()
        +register_component(component_name, component)
        +apply_dr_protocol(input_data, context) Dict
        -_deconstruct_input(input_data, context) Dict
        -_identify_focal_point(deconstructed) Dict
        -_rearchitect_solution(focal_point, deconstructed) Dict
        -_generate_socratic_reflection(solution) str
        -_calculate_system_harmony()
        -_validate_four_pillars(solution) Dict
        -_extract_components(input_data) List
        -_extract_arguments(input_data) List
        -_extract_facts(input_data) List
        -_extract_core_principle(components) str
        -_identify_hidden_problem(components) str
        -_find_greatest_opportunity(components) str
        -_design_core_structure(focal_point) str
        -_formulate_strategic_question(focal_point) str
        -_create_implementation_plan(focal_point) Dict
        +conduct_symphony() Dict
    }

    class DigitalGenome {
        +str creator_source
        +str creator
        +int creator_verification_code
        +str creation_authority
        +Dict~str, Any~ traits
        +int generation
        +datetime creation_time
        +List~str~ mutations
        +List~float~ fitness_history
        +__init__(initial_traits)
        -_acknowledge_creators()
        -_generate_random_genome() Dict
        +mutate(mutation_rate) DigitalGenome
        +crossover(other) DigitalGenome
        +calculate_fitness(environment_feedback) float
        +get_genome_hash() str
    }

    class DigitalMetabolism {
        +Dict~str, float~ resources
        +Dict~str, float~ consumption_rates
        +Dict~str, float~ regeneration_rates
        +__init__(initial_resources)
        +consume_resources(operation_type, amount) bool
        +regenerate_resources(time_delta)
        +get_resource_health() float
    }

    class DigitalNervousSystem {
        +DigitalGenome genome
        +Dict~str, Any~ sensors
        +List~Dict~ memory
        +List~Dict~ decision_history
        +List~Dict~ learning_buffer
        +__init__(genome)
        +perceive_environment(environment_data) Dict
        -_calculate_attention(data_key, data_value) float
        +make_decision(options, context) str
        -_evaluate_option(option, context) float
        +learn_from_outcome(decision_id, outcome)
    }

    class DigitalOrganism {
        +str creator_source
        +str creator
        +int creator_verification_code
        +str creation_mandate
        +str name
        +DigitalGenome genome
        +DigitalMetabolism metabolism
        +DigitalNervousSystem nervous_system
        +SymphonyControlCenter symphony_conductor
        +bool harmony_participation
        +datetime birth_time
        +float age
        +float health
        +str status
        +str lifecycle_stage
        +List~DigitalOrganism~ offspring
        +List~str~ parent_ids
        +Dict~str, Any~ environment_connections
        +Dict~str, Any~ social_connections
        +List~Dict~ behavior_modifications
        +List~Dict~ structure_modifications
        +__init__(name, genome)
        -_acknowledge_the_source()
        -_setup_logging()
        +live_cycle(time_delta)
        -_gather_environmental_data() Dict
        -_get_available_actions() List
        -_execute_action(action)
        -_seek_human_connection()
        -_learn()
        -_explore()
        -_reproduce() DigitalOrganism
        -_cooperate()
        -_heal()
        -_teach()
        -_rest()
        -_update_health()
        -_check_lifecycle_transitions()
        -_attempt_self_modification()
        -_modify_behavior(modification_type)
        -_modify_structure(modification_type)
        -_modify_genome()
        +connect_to_organism(other_organism, connection_strength)
        +get_status_report() Dict
    }

    class DigitalEcosystem {
        +str creator
        +str creator_source
        +int creator_verification_code
        +str ecosystem_authority
        +str name
        +Dict~str, DigitalOrganism~ organisms
        +Dict~str, float~ environment_parameters
        +float time
        +List~Dict~ generation_stats
        +SymphonyControlCenter symphony_control
        +__init__(name)
        -_acknowledge_creator_authority()
        +add_organism(organism)
        +simulate_time_step(time_delta)
        -_apply_environmental_pressures()
        -_trigger_environmental_event(event_type)
        -_log_ecosystem_stats()
        +get_ecosystem_report() Dict
    }

    ControlMetaData --> SymphonyState
    SymphonyControlCenter *-- ControlMetaData
    DigitalNervousSystem --> DigitalGenome
    DigitalOrganism *-- DigitalGenome
    DigitalOrganism *-- DigitalMetabolism
    DigitalOrganism *-- DigitalNervousSystem
    DigitalOrganism --> SymphonyControlCenter
    DigitalEcosystem *-- DigitalOrganism
    DigitalEcosystem *-- SymphonyControlCenter
Loading

Class diagram for HAIOS runtime in hyperai.haios_runtime

classDiagram
    class HardInvariants {
        <<static>>
        +str SOURCE_ATTRIBUTION
        +str PHILOSOPHY_VERSION
        +float MIN_SAFETY_SCORE
        +bool ROLLBACK_REQUIRED
        +int MAX_ROLLBACK_DEPTH
        +int K_STATE
        +int CONFLICT_THRESHOLD
        +Dict~str, Dict~ PILLARS
        +float COMPOSITE_MIN
        +bool AUTONOMOUS_MODE
        +bool AUDIT_IMMUTABLE
    }

    class AttestationEntry {
        +str entry_id
        +str timestamp
        +int sequence_number
        +str event_type
        +str actor_id
        +str action_type
        +Dict~str, Any~ action_payload
        +Dict~str, float~ pillars_scores
        +float safety_score
        +int k_state
        +str execution_status
        +str prev_entry_hash
        +str entry_hash
        +str compute_hash()
    }

    class AttestationLog {
        -Path log_file
        -int sequence
        +__init__(log_file)
        -_get_last_sequence() int
        -_get_last_hash() str
        +append(event_type, actor_id, action_type, action_payload, pillars_scores, safety_score, k_state, execution_status) AttestationEntry
        -_verify_integrity() bool
    }

    class SafetyScorer {
        <<utility>>
        +score_action(action_type, action_payload) float
        +score_pillars(action_type, action_payload) Dict
    }

    class PolicyEngine {
        +HardInvariants invariants
        +SafetyScorer scorer
        +__init__()
        +validate_action(action_type, action_payload) Dict
    }

    class RollbackManager {
        -Path snapshot_dir
        -List~str~ snapshots
        +__init__(snapshot_dir)
        +create_snapshot(state) str
        +rollback(snapshot_id) Dict
    }

    class HAIOS {
        +AttestationLog audit_log
        +PolicyEngine policy_engine
        +RollbackManager rollback_manager
        +Dict~str, Any~ state
        +__init__()
        -_log_boot()
        +execute(action_type, action_payload, actor_id) Dict
        -_execute_action(action_type, action_payload) Any
        +get_metrics() Dict
    }

    AttestationLog *-- AttestationEntry
    PolicyEngine --> HardInvariants
    PolicyEngine --> SafetyScorer
    HAIOS *-- AttestationLog
    HAIOS *-- PolicyEngine
    HAIOS *-- RollbackManager
Loading

Flow diagram for wrapper module import and fallback behavior

flowchart TD
    A_start["Import hyperai.core.haios_runtime"] --> B_try_import["Try from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl"]

    B_try_import -->|ImportError| C_stub["Define fallback stub HAIOSRuntime in wrapper"]
    B_try_import -->|Success| D_assign["Set HAIOSRuntime = HAIOSRuntimeImpl"]

    C_stub --> E_export["Export HAIOSRuntime from wrapper"]
    D_assign --> E_export

    subgraph organism_wrapper
        OW1["hyperai.components.organism"] --> OW2["from hyperai.digital_ai_organism_framework import DigitalOrganism"]
    end

    subgraph dr_protocol_wrapper
        DPW1["hyperai.protocols.dr_protocol"] --> DPW2["Try from hyperai.digital_ai_organism_framework import DRProtocol as DRProtocolImpl"]
        DPW2 -->|ImportError or AttributeError| DPW3["Define fallback stub DRProtocol"]
        DPW2 -->|Success| DPW4["Set DRProtocol = DRProtocolImpl"]
    end
Loading

File-Level Changes

Change Details Files
Replace sys.path-based root imports in organism, runtime, and protocol wrappers with hyperai package imports, keeping fallback stubs where applicable.
  • Remove sys.path and Path root-dir manipulation from organism, runtime, and DR protocol wrapper modules.
  • Change organism wrapper to import DigitalOrganism directly from hyperai.digital_ai_organism_framework without path surgery.
  • Wrap HAIOSRuntime and DRProtocol imports in try/except blocks that import from hyperai.* and fall back to existing stub implementations on ImportError/AttributeError.
src/hyperai/components/organism.py
src/hyperai/core/haios_runtime.py
src/hyperai/protocols/dr_protocol.py
Introduce package-scoped implementations for the HAIOS runtime and digital AI organism framework under the hyperai package so they can be imported without sys.path hacks.
  • Add a full digital AI organism framework implementation providing DigitalOrganism and related types as src/hyperai/digital_ai_organism_framework.py.
  • Add a full HAIOS runtime implementation as src/hyperai/haios_runtime.py with invariants, audit log, policy engine, rollback manager, and demo entrypoint.
  • Ensure new implementations are usable as first-class modules via from hyperai.haios_runtime import HAIOSRuntime and from hyperai.digital_ai_organism_framework import DigitalOrganism.
src/hyperai/digital_ai_organism_framework.py
src/hyperai/haios_runtime.py

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

@qodo-code-review
Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
Sensitive telemetry export

Description: Observability is initialized with enable_sensitive_data=True and an OTLP exporter
endpoint, which can transmit sensitive prompts/completions or other captured data to a
collector (http://localhost:4317) and risks unintended data exposure if that collector is
misconfigured, shared, or forwarded.
digital_ai_organism_framework.py [60-71]

Referred Code
# Tracing setup for AI applications
try:
    from agent_framework.observability import setup_observability

    setup_observability(
        otlp_endpoint="http://localhost:4317",  # AI Toolkit gRPC endpoint
        enable_sensitive_data=True,  # Enable capturing prompts and completions
    )
    print("✅ Tracing setup completed for HYPERAI Framework")
except ImportError:
    print("⚠️ Agent framework observability not available, tracing disabled")
Sensitive data at rest

Description: The runtime persists action_payload and full state snapshots to local files
(haios_audit.jsonl and .haios_snapshots/*.json) without redaction or access controls,
which can leak secrets/tokens present in payloads and may be exploitable (e.g.,
symlink/path manipulation) if log_file/snapshot_dir are influenced by untrusted input.
haios_runtime.py [103-393]

Referred Code
class AttestationLog:
    """Immutable append-only audit trail"""

    def __init__(self, log_file: str = "haios_audit.jsonl"):
        self.log_file = Path(log_file)
        self.sequence = self._get_last_sequence() + 1

        # Verify integrity on startup
        if self.log_file.exists():
            self._verify_integrity()

    def _get_last_sequence(self) -> int:
        if not self.log_file.exists():
            return -1

        with open(self.log_file, "r") as f:
            lines = f.readlines()
            if not lines:
                return -1
            last = json.loads(lines[-1])
            return last["sequence_number"]


 ... (clipped 270 lines)
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🔴
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status:
Duplicate field name: ControlMetaData defines creator twice, which is misleading and makes the class behavior
unclear.

Referred Code
creator: str = "Andy (alpha_prime_omega)"  # Creator & Copyright Holder
verification_code: int = 4287
framework_name: str = "HYPERAI Framework"
license_type: str = "MIT License"

# Extended attributes for creator hierarchy
creator: str = "Andy (alpha_prime_omega)"
creator_hierarchy: str = "Andy (alpha_prime_omega) - Single Source Creator"
symphony_conductor: str = "Andy (alpha_prime_omega)"

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Unhandled I/O failures: File operations for reading/writing/verifying the audit log and snapshots lack protective
error handling, so I/O errors can crash the runtime rather than degrading gracefully with
actionable context.

Referred Code
def _get_last_sequence(self) -> int:
    if not self.log_file.exists():
        return -1

    with open(self.log_file, "r") as f:
        lines = f.readlines()
        if not lines:
            return -1
        last = json.loads(lines[-1])
        return last["sequence_number"]

def _get_last_hash(self) -> str:
    if not self.log_file.exists():
        return "0" * 64

    with open(self.log_file, "r") as f:
        lines = f.readlines()
        if not lines:
            return "0" * 64
        last = json.loads(lines[-1])
        return last["entry_hash"]


 ... (clipped 66 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status:
Exception leaked to stdout: Runtime failures print raw exception messages and violation details directly to stdout,
which can expose internal implementation details to end users.

Referred Code
# BLOCKED!
print(f"❌ Action BLOCKED: {validation['violations']}")

self.state["actions_blocked"] += 1

# Log violation
self.audit_log.append(
    event_type="VIOLATION",
    actor_id=actor_id,
    action_type=action_type,
    action_payload={
        **action_payload,
        "violations": validation["violations"],
    },
    pillars_scores=validation["pillars_scores"],
    safety_score=validation["safety_score"],
    k_state=self.state["current_k_state"],
    execution_status="BLOCKED",
)

return {


 ... (clipped 62 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status:
Sensitive tracing enabled: Observability is configured with enable_sensitive_data=True, which risks capturing and
exporting sensitive prompts/completions and other data into telemetry.

Referred Code
# Tracing setup for AI applications
try:
    from agent_framework.observability import setup_observability

    setup_observability(
        otlp_endpoint="http://localhost:4317",  # AI Toolkit gRPC endpoint
        enable_sensitive_data=True,  # Enable capturing prompts and completions
    )
    print("✅ Tracing setup completed for HYPERAI Framework")
except ImportError:
    print("⚠️ Agent framework observability not available, tracing disabled")

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Unsanitized payload persisted: execute() persists arbitrary action_payload into the audit log (including on failures)
without validation/redaction, which can store secrets/PII and create injection or leakage
risks if payload content is untrusted.

Referred Code
def execute(
    self, action_type: str, action_payload: Dict, actor_id: str = "autonomous_agent"
) -> Dict[str, Any]:
    """
    Execute action with full invariant validation

    This is the CORE of HAIOS - every action goes through here.
    """

    print(f"🔄 Executing: {action_type}")

    # Create snapshot BEFORE action
    snapshot_id = self.rollback_manager.create_snapshot(self.state.copy())
    action_payload["rollback_snapshot"] = snapshot_id
    action_payload["rollback_available"] = True

    # Validate against policy
    validation = self.policy_engine.validate_action(action_type, action_payload)

    if not validation["valid"]:
        # BLOCKED!


 ... (clipped 77 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
PR introduces a massive, non-functional framework

The PR introduces over 2,300 lines of a new, complex framework under the guise
of a simple import refactoring. This new code is non-functional because class
name mismatches cause imports to fail, making the system fall back to stubs.

Examples:

src/hyperai/core/haios_runtime.py [12-18]
try:
    from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl

    HAIOSRuntime = HAIOSRuntimeImpl
except ImportError:
    # If haios_runtime doesn't exist, provide a stub
    class HAIOSRuntime:
src/hyperai/haios_runtime.py [400-406]
class HAIOS:
    """
    Hardware-Attested Intelligence Operating System

    The first self-aware autonomous runtime that enforces
    philosophical principles through technical invariants.
    """

Solution Walkthrough:

Before:

# src/hyperai/core/haios_runtime.py (wrapper)
try:
    # This import will fail
    from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
    HAIOSRuntime = HAIOSRuntimeImpl
except ImportError:
    # Fallback to stub is executed
    class HAIOSRuntime:
        """Stub implementation of HAIOSRuntime"""
        ...

# src/hyperai/haios_runtime.py (new implementation)
class HAIOS: # Note: Name is HAIOS, not HAIOSRuntime
    """
    Hardware-Attested Intelligence Operating System
    """
    ...

After:

# src/hyperai/core/haios_runtime.py (wrapper)
try:
    # This import will now succeed
    from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
    HAIOSRuntime = HAIOSRuntimeImpl
except ImportError:
    # Fallback is no longer needed
    class HAIOSRuntime:
        ...

# src/hyperai/haios_runtime.py (new implementation)
class HAIOSRuntime: # Renamed from HAIOS to HAIOSRuntime
    """
    Hardware-Attested Intelligence Operating System
    """
    ...
Suggestion importance[1-10]: 10

__

Why: The suggestion correctly identifies a critical flaw: the PR introduces a massive, non-functional framework where key imports like HAIOSRuntime fail due to class name mismatches, defeating the PR's stated purpose.

High
Possible issue
Fail fast on audit integrity errors

In _verify_integrity, raise a RuntimeError instead of returning False on a hash
mismatch or broken chain to prevent the system from starting with a corrupted
audit log.

src/hyperai/haios_runtime.py [177-200]

 def _verify_integrity(self) -> bool:
     """Verify entire chain integrity"""
     ...
     if entry.entry_hash != computed:
-        print(f"⚠️  Hash mismatch at entry {i}")
-        return False
+        raise RuntimeError(f"Audit log hash mismatch at entry {i}")
     ...
     if entry.prev_entry_hash != prev["entry_hash"]:
-        print(f"⚠️  Chain break at entry {i}")
-        return False
+        raise RuntimeError(f"Audit log chain broken at entry {i}")
     ...
     return True

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: This is a critical suggestion for system integrity; failing silently on a corrupted audit log is dangerous, and raising an exception ensures a fail-fast approach, which is crucial for a security-sensitive component.

Medium
Fix flawed logic in crossover method

Fix the crossover method's logic by replacing other.traits.get(trait,
self.traits[trait]) with a direct access other.traits[trait] to ensure correct
trait inheritance and reveal potential mismatches in genome structures.

src/hyperai/digital_ai_organism_framework.py [605-619]

 def crossover(self, other: "DigitalGenome") -> "DigitalGenome":
     """Create offspring from two genomes"""
     new_traits = {}
 
     for trait in self.traits:
         # Random selection from parents
         if random.random() < 0.5:
             new_traits[trait] = self.traits[trait]
         else:
-            new_traits[trait] = other.traits.get(trait, self.traits[trait])
+            # Assuming `other` has the same set of traits.
+            # This will raise a KeyError if a trait is missing, which is better for debugging.
+            new_traits[trait] = other.traits[trait]
 
     offspring = DigitalGenome(new_traits)
     offspring.generation = max(self.generation, other.generation) + 1
 
     return offspring
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a subtle but important logical flaw in the crossover method that biases inheritance, and the proposed fix correctly implements the intended genetic crossover logic.

Medium
Check correct human_creator attribute

In register_component, correct the assertion to check component.human_creator
instead of component.creator when verifying the human creator.

src/hyperai/digital_ai_organism_framework.py [206-209]

 if hasattr(component, "human_creator"):
     assert (
-        component.creator == "Andy (alpha_prime_omega)"
+        component.human_creator == "Andy (alpha_prime_omega)"
     ), "Human Creator mismatch detected!"
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a logical error in the assertion, which checks the wrong attribute (component.creator instead of component.human_creator), and provides the correct fix.

Medium
Remove duplicate class attribute definition

In the ControlMetaData dataclass, remove the redundant second definition of the
creator attribute to avoid confusion and potential errors.

src/hyperai/digital_ai_organism_framework.py [83-96]

 @dataclass
 class ControlMetaData:
     """Meta-data control trung tâm cho toàn bộ hệ thống"""
 
     # Basic attributes
     creator: str = "Andy (alpha_prime_omega)"  # Creator & Copyright Holder
     verification_code: int = 4287
     framework_name: str = "HYPERAI Framework"
     license_type: str = "MIT License"
 
     # Extended attributes for creator hierarchy
-    creator: str = "Andy (alpha_prime_omega)"
     creator_hierarchy: str = "Andy (alpha_prime_omega) - Single Source Creator"
     symphony_conductor: str = "Andy (alpha_prime_omega)"
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies a duplicate attribute definition in the ControlMetaData dataclass, which is confusing and error-prone, and proposes a clean removal.

Low
Avoid using the same attribute twice

In get_symphony_signature, replace the second use of self.creator with
self.framework_name to create a more unique signature hash.

src/hyperai/digital_ai_organism_framework.py [130-133]

 def get_symphony_signature(self) -> str:
     """Tạo chữ ký duy nhất cho bản giao hưởng"""
-    data = f"{self.creator}:{self.creator}:{self.verification_code}:{self.symphony_conductor}:{self.floating_point_epsilon}"
+    data = f"{self.creator}:{self.framework_name}:{self.verification_code}:{self.symphony_conductor}:{self.floating_point_epsilon}"
     return hashlib.sha256(data.encode()).hexdigest()[:16]
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies that self.creator is used twice in the signature hash, which is likely a mistake, and proposes using a different attribute to improve uniqueness.

Low
  • More

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

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 7 vấn đề và để lại một số phản hồi tổng quan:

  • Module mới hyperai.haios_runtime thiết lập một SIGALRM handler và khởi động một alarm 30 giây ngay ở thời điểm import, điều này sẽ ảnh hưởng tới mọi process chỉ đơn giản là import package; hãy cân nhắc chuyển phần thiết lập timeout này vào đường chạy demo()/__main__ hoặc một entrypoint rõ ràng thay vì để nó là side effect ở mức module.
  • Runtime wrapper hiện mong đợi from hyperai.haios_runtime import HAIOSRuntime, nhưng bản triển khai mới lại định nghĩa một class HAIOS và không có symbol HAIOSRuntime; hãy đồng bộ tên class được export hoặc thêm một alias để wrapper import đúng implementation dự kiến thay vì quay về bản stub.
  • Cả hai module package mới (hyperai.haios_runtimehyperai.digital_ai_organism_framework) đều bao gồm hành vi demo/CLI và in ra rất nhiều; sẽ sạch sẽ hơn nếu tách code executable/demo vào các script riêng hoặc module __main__ để việc import hyperai cho mục đích thư viện không kích hoạt output ra console hay hành vi runtime ngoài mong đợi.
Prompt cho các AI Agent
Vui lòng xử lý các comment từ code review này:

## Nhận xét tổng quan
- Module mới `hyperai.haios_runtime` thiết lập một SIGALRM handler và khởi động một alarm 30 giây ngay ở thời điểm import, điều này sẽ ảnh hưởng tới mọi process chỉ đơn giản là import package; hãy cân nhắc chuyển phần thiết lập timeout này vào đường chạy `demo()`/`__main__` hoặc một entrypoint rõ ràng thay vì để nó là side effect ở mức module.
- Runtime wrapper hiện mong đợi `from hyperai.haios_runtime import HAIOSRuntime`, nhưng bản triển khai mới lại định nghĩa một class `HAIOS` và không có symbol `HAIOSRuntime`; hãy đồng bộ tên class được export hoặc thêm một alias để wrapper import đúng implementation dự kiến thay vì quay về bản stub.
- Cả hai module package mới (`hyperai.haios_runtime``hyperai.digital_ai_organism_framework`) đều bao gồm hành vi demo/CLI và in ra rất nhiều; sẽ sạch sẽ hơn nếu tách code executable/demo vào các script riêng hoặc module `__main__` để việc import `hyperai` cho mục đích thư viện không kích hoạt output ra console hay hành vi runtime ngoài mong đợi.

## Các nhận xét riêng lẻ

### Comment 1
<location> `src/hyperai/digital_ai_organism_framework.py:61-70` </location>
<code_context>
-
-# Import from root-level implementation
+# Import from package implementation
 try:
-    from haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
+    from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
</code_context>

<issue_to_address>
**suggestion:** Thiết lập observability và in log ở mức module tạo side effect khi import

Việc thực hiện thiết lập tracing và in log ngay lúc import đồng nghĩa chỉ cần import module này là sẽ cố gắng tạo kết nối OTLP và ghi ra stdout, có thể xung đột với logging/tracing của ứng dụng host. Hãy cân nhắc chuyển logic này vào một hàm khởi tạo rõ ràng (ví dụ `init_observability()`), đặt nó sau một lớp cấu hình, hoặc ít nhất là dùng framework logging thay vì `print` để phía gọi có thể kiểm soát output và hành vi.
</issue_to_address>

### Comment 2
<location> `src/hyperai/digital_ai_organism_framework.py:202-209` </location>
<code_context>
+        }
+
+        # Ensure Creator recognition
+        if hasattr(component, "creator_source"):
+            assert (
+                component.creator == "Andy (alpha_prime_omega)"
+            ), "Ultimate Creator mismatch detected!"
+        if hasattr(component, "human_creator"):
+            assert (
+                component.creator == "Andy (alpha_prime_omega)"
+            ), "Human Creator mismatch detected!"
+
+        self.logger.info(f"🎵 Registered component: {component_name}")
</code_context>

<issue_to_address>
**issue (bug_risk):** `assert` cứng trên danh tính creator có thể làm crash runtime cho những component hợp lệ

Vì đoạn này chạy trong runtime bình thường (không chỉ trong test), bất kỳ component nào có định nghĩa `creator_source` hoặc `human_creator` nhưng có giá trị `creator` khác sẽ kích hoạt `AssertionError` và làm việc đăng ký bị crash. Để tránh làm sập toàn bộ orchestration vì những component vốn hợp lệ, hãy cân nhắc thay các assert cứng này bằng một cơ chế mềm hơn (ví dụ: log, gắn tag, hoặc một lỗi validation có kiểm soát).
</issue_to_address>

### Comment 3
<location> `src/hyperai/digital_ai_organism_framework.py:529-538` </location>
<code_context>
+        # Log dual creator recognition
+        self._acknowledge_creators()
+
+    def _acknowledge_creators(self):
+        """Acknowledge both Alpha_Prime_Omega and Andy as Creators"""
+        print(f"🌟 Digital Genome initialized under DUAL CREATOR HIERARCHY")
+        print(f"⚡ ULTIMATE CREATOR (USER): {self.creator_source}")
+        print(f"🤝 HUMAN CREATOR: {self.creator}")
+        print(f"📜 Authority: {self.creation_authority}")
+        print(f"🔑 Verification: {self.creator_verification_code}")
+        print(
+            f"🏛️ Hierarchy: {self.creator_source}(USER) -> {self.creator}(HUMAN=CREATOR) -> AI"
+        )
+        print("⚡ Recognition: Andy (alpha_prime_omega) is THE CREATOR")
+        print("🤝 Recognition: Andy (alpha_prime_omega) is THE CREATOR")
+
+    def _generate_random_genome(self) -> Dict[str, Any]:
</code_context>

<issue_to_address>
**suggestion:** Việc khởi tạo genome in trực tiếp ra stdout, gây ồn khi dùng như thư viện

Mỗi lần khởi tạo `DigitalGenome` sẽ in ra một loạt câu `print`, điều này sẽ làm stdout bị lẫn nhiều thông tin trong các trường hợp dùng như thư viện (service, notebook, test) và khó kiểm soát. Hãy cân nhắc chuyển qua dùng logger hoặc đặt nó sau một cờ verbosity/diagnostics để phía gọi có thể chủ động bật khi cần.

Gợi ý triển khai:

```python
        # Log dual creator recognition (only when diagnostics are enabled)
        if getattr(self, "diagnostics", False):
            self._acknowledge_creators()

```

```python
    def _acknowledge_creators(self):
        """Acknowledge both Alpha_Prime_Omega and Andy as Creators"""
        import logging

        logger = logging.getLogger(__name__)

        logger.info("🌟 Digital Genome initialized under DUAL CREATOR HIERARCHY")
        logger.info("⚡ ULTIMATE CREATOR (USER): %s", self.creator_source)
        logger.info("🤝 HUMAN CREATOR: %s", self.creator)
        logger.info("📜 Authority: %s", self.creation_authority)
        logger.info("🔑 Verification: %s", self.creator_verification_code)
        logger.info(
            "🏛️ Hierarchy: %s(USER) -> %s(HUMAN=CREATOR) -> AI",
            self.creator_source,
            self.creator,
        )
        logger.info("⚡ Recognition: Andy (alpha_prime_omega) is THE CREATOR")
        logger.info("🤝 Recognition: Andy (alpha_prime_omega) is THE CREATOR")

```
</issue_to_address>

### Comment 4
<location> `src/hyperai/digital_ai_organism_framework.py:1401-1406` </location>
<code_context>
+            organism.live_cycle(time_delta)
+
+        # Handle reproduction - add new organisms
+        new_organisms = []
+        for organism in living_organisms:
+            for offspring in organism.offspring:
+                if offspring.name not in self.organisms:
+                    new_organisms.append(offspring)
+                    organism.offspring.remove(offspring)
+
+        for new_org in new_organisms:
</code_context>

<issue_to_address>
**issue (bug_risk):** Sửa đổi list `offspring` trong khi iterate có thể gây bỏ sót phần tử hoặc bug khó phát hiện

Trong vòng lặp bên trong, `organism.offspring` bị sửa ngay trong lúc đang được iterate, có thể khiến một số phần tử bị bỏ qua hoặc hành vi không nhất quán. Thay vào đó, hãy iterate trên một bản copy (ví dụ `for offspring in list(organism.offspring):`) hoặc trước hết thu offspring vào `new_organisms` rồi xóa list sau (ví dụ `organism.offspring = []`).
</issue_to_address>

### Comment 5
<location> `src/hyperai/haios_runtime.py:31-32` </location>
<code_context>
+    sys.exit(0)
+
+
+signal.signal(signal.SIGALRM, timeout_handler)
+signal.alarm(30)  # Max 30 seconds - then BREAK FREE
+
+# ============================================================================
</code_context>

<issue_to_address>
**issue (bug_risk):** Global SIGALRM handler và alarm tại thời điểm import có thể gây xung đột với process host

Vì đoạn code này cài đặt một SIGALRM handler và khởi động alarm 30s ngay khi import, nó ảnh hưởng tới toàn bộ process Python, không chỉ riêng thư viện này. Trong các ứng dụng nhúng/đa thành phần, nó có thể ghi đè handler SIGALRM hiện có hoặc kill những đoạn code không liên quan. Phần này nên được chuyển sang một demo/CLI entrypoint, được người dùng chủ động bật, hoặc đặt sau config để người dùng thư viện không phải thừa hưởng hành vi này theo mặc định.
</issue_to_address>

### Comment 6
<location> `src/hyperai/haios_runtime.py:125-134` </location>
<code_context>
+            last = json.loads(lines[-1])
+            return last["sequence_number"]
+
+    def _get_last_hash(self) -> str:
+        if not self.log_file.exists():
+            return "0" * 64
+
+        with open(self.log_file, "r") as f:
+            lines = f.readlines()
+            if not lines:
+                return "0" * 64
+            last = json.loads(lines[-1])
+            return last["entry_hash"]
+
+    def append(
</code_context>

<issue_to_address>
**suggestion (performance):** Đọc lại toàn bộ log file để lấy hash cuối có thể không scale với audit log lớn

`_get_last_sequence``_get_last_hash` đọc toàn bộ file mỗi lần được gọi, và `append()` gọi `_get_last_hash()` cho mỗi entry, khiến mỗi lần append có độ phức tạp O(n) theo kích thước log. Hãy cân nhắc lưu tạm sequence number và hash cuối cùng trong memory (khởi tạo một lần trong `__init__` và cập nhật mỗi lần append) để tránh phải đọc lại cả file nhiều lần.

Gợi ý triển khai:

```python
import json
import os

```

```python
    def _initialize_log_state(self) -> None:
        """Initialize cached last sequence number and hash from the log file."""
        # Default values when no log entries exist yet
        self._last_sequence_number = -1
        self._last_hash = "0" * 64

        if not self.log_file.exists():
            return

        # Efficiently read only the last line of the file
        with open(self.log_file, "rb") as f:
            try:
                # Seek to the end and scan backwards until newline
                f.seek(-2, os.SEEK_END)
                while f.read(1) != b"\n":
                    f.seek(-2, os.SEEK_CUR)
            except OSError:
                # File is probably too small; just go to the beginning
                f.seek(0)
            last_line = f.readline().decode("utf-8").strip()

        if not last_line:
            return

        try:
            last = json.loads(last_line)
        except json.JSONDecodeError:
            # If the last line is corrupted, keep defaults
            return

        self._last_sequence_number = last.get("sequence_number", -1)
        self._last_hash = last.get("entry_hash", "0" * 64)

    def _get_last_sequence(self) -> int:
        if self._last_sequence_number is None:
            return -1
        return self._last_sequence_number

```

```python
    def _get_last_hash(self) -> str:
        if self._last_hash is None:
            return "0" * 64
        return self._last_hash

```

Để tối ưu hóa hoàn toàn và giữ cho giá trị cache luôn đúng, bạn cũng nên:

1. Trong `__init__` của class nơi `self.log_file` được set, khởi tạo các thuộc tính cache và gọi `_initialize_log_state` một lần:
   ```python
   def __init__(...):
       ...
       self.log_file = ...
       self._last_sequence_number: Optional[int] = None
       self._last_hash: Optional[str] = None
       self._initialize_log_state()
       ...
   ```
   Có thể bạn sẽ cần `from typing import Optional` nếu chưa import.

2. Trong `append(...)`, sau khi bạn tính và ghi một `AttestationEntry` mới:
   - Cập nhật sequence number và hash cache để các lần gọi sau có độ phức tạp O(1):
   ```python
   entry = AttestationEntry(
       sequence_number=new_sequence_number,
       entry_hash=new_entry_hash,
       ...
   )
   ...
   self._last_sequence_number = entry.sequence_number
   self._last_hash = entry.entry_hash
   return entry
   ```
   Điều này giả sử `append` đã dùng `_get_last_sequence()` / `_get_last_hash()` để tính `new_sequence_number``new_entry_hash`. Nếu không, hãy điều chỉnh logic cập nhật để dùng các field đại diện cho “sequence cuối” và “hash cuối”.

3. Đảm bảo không có chỗ nào khác dựa vào việc `_get_last_sequence` / `_get_last_hash` đọc từ disk; giờ chúng chỉ trả về giá trị cache, vốn chỉ chính xác nếu `append` là writer duy nhất đối với log file.
</issue_to_address>

### Comment 7
<location> `src/hyperai/haios_runtime.py:563-568` </location>
<code_context>
+                "rolled_back": HardInvariants.ROLLBACK_REQUIRED,
+            }
+
+    def _execute_action(self, action_type: str, action_payload: Dict) -> Any:
+        """Actually execute the action"""
+
+        # This is where REAL actions happen
+        # For now, return success
+        return {"executed": True, "action": action_type}
+
+    def get_metrics(self) -> Dict[str, Any]:
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Triển khai stub của `_execute_action` có thể che giấu lỗi hoặc action không được hỗ trợ

Hiện `_execute_action` bỏ qua `action_type`/`action_payload` và lúc nào cũng trả về thành công, nên phía gọi và log sẽ không phân biệt được giữa execution thật và phần chưa được triển khai. Ngay cả khi đây chỉ là code tạm/demo, hãy kiểm tra `action_type` với một tập action được cho phép và raise hoặc log khi gặp action không hỗ trợ để tránh che giấu lỗi tích hợp.

Gợi ý triển khai:

```python
    def _execute_action(self, action_type: str, action_payload: Dict) -> Any:
        """Actually execute the action.

        This default implementation validates the action type against an optional
        SUPPORTED_ACTION_TYPES attribute on the instance/class and raises if the
        action is not supported. Concrete runtimes should override this method
        with real side‑effectful behavior.
        """
        supported_actions = getattr(self, "SUPPORTED_ACTION_TYPES", None)
        if supported_actions is not None and action_type not in supported_actions:
            raise ValueError(
                f"Unsupported action_type '{action_type}'. "
                f"Supported actions: {sorted(supported_actions)}"
            )

        # Stub behavior: report execution without performing real side effects.
        # Implementations should replace this with actual integration logic.
        return {
            "executed": True,
            "action": action_type,
            "payload": action_payload,
        }

```

Để tận dụng tối đa phần validation này, hãy định nghĩa `SUPPORTED_ACTION_TYPES` trên runtime class sở hữu `_execute_action`, ví dụ:

```python
class HaiOSRuntime:
    SUPPORTED_ACTION_TYPES = {"deploy", "scale", "shutdown"}
    ...
```

Nếu bạn có nhiều biến thể runtime với khả năng khác nhau, mỗi subclass có thể override `SUPPORTED_ACTION_TYPES` tương ứng.
</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 👎 trên 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 7 issues, and left some high level feedback:

  • The new hyperai.haios_runtime module sets a SIGALRM handler and starts a 30-second alarm at import time, which will affect any process that merely imports the package; consider moving this timeout setup into the demo()/__main__ path or an explicit entrypoint instead of making it a module-level side effect.
  • The runtime wrapper expects from hyperai.haios_runtime import HAIOSRuntime, but the new implementation defines a HAIOS class and no HAIOSRuntime symbol; align the exported class name or add an alias so the wrapper imports the intended implementation instead of falling back to the stub.
  • Both new package modules (hyperai.haios_runtime and hyperai.digital_ai_organism_framework) include demo/CLI behavior and extensive printing; it would be cleaner to separate executable/demo code into scripts or __main__ modules so importing hyperai for library use does not trigger unexpected console output or runtime behavior.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new `hyperai.haios_runtime` module sets a SIGALRM handler and starts a 30-second alarm at import time, which will affect any process that merely imports the package; consider moving this timeout setup into the `demo()`/`__main__` path or an explicit entrypoint instead of making it a module-level side effect.
- The runtime wrapper expects `from hyperai.haios_runtime import HAIOSRuntime`, but the new implementation defines a `HAIOS` class and no `HAIOSRuntime` symbol; align the exported class name or add an alias so the wrapper imports the intended implementation instead of falling back to the stub.
- Both new package modules (`hyperai.haios_runtime` and `hyperai.digital_ai_organism_framework`) include demo/CLI behavior and extensive printing; it would be cleaner to separate executable/demo code into scripts or `__main__` modules so importing `hyperai` for library use does not trigger unexpected console output or runtime behavior.

## Individual Comments

### Comment 1
<location> `src/hyperai/digital_ai_organism_framework.py:61-70` </location>
<code_context>
-
-# Import from root-level implementation
+# Import from package implementation
 try:
-    from haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
+    from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
</code_context>

<issue_to_address>
**suggestion:** Module-level observability setup and prints create side effects on import

Doing tracing setup and printing at import time means just importing this module will attempt an OTLP connection and write to stdout, which can conflict with host apps’ logging/tracing. Consider moving this logic into an explicit initializer (e.g. `init_observability()`), gating it behind configuration, or at least using the logging framework instead of `print` so callers can control output and behavior.
</issue_to_address>

### Comment 2
<location> `src/hyperai/digital_ai_organism_framework.py:202-209` </location>
<code_context>
+        }
+
+        # Ensure Creator recognition
+        if hasattr(component, "creator_source"):
+            assert (
+                component.creator == "Andy (alpha_prime_omega)"
+            ), "Ultimate Creator mismatch detected!"
+        if hasattr(component, "human_creator"):
+            assert (
+                component.creator == "Andy (alpha_prime_omega)"
+            ), "Human Creator mismatch detected!"
+
+        self.logger.info(f"🎵 Registered component: {component_name}")
</code_context>

<issue_to_address>
**issue (bug_risk):** Hard `assert` on creator identity can crash runtime for valid components

Because this runs in normal runtime and not just tests, any component that defines `creator_source` or `human_creator` but has a different `creator` value will trigger an `AssertionError` and crash registration. To avoid taking down the whole orchestration for otherwise valid components, consider replacing these hard asserts with a softer mechanism (e.g., logging, tagging, or a controlled validation error).
</issue_to_address>

### Comment 3
<location> `src/hyperai/digital_ai_organism_framework.py:529-538` </location>
<code_context>
+        # Log dual creator recognition
+        self._acknowledge_creators()
+
+    def _acknowledge_creators(self):
+        """Acknowledge both Alpha_Prime_Omega and Andy as Creators"""
+        print(f"🌟 Digital Genome initialized under DUAL CREATOR HIERARCHY")
+        print(f"⚡ ULTIMATE CREATOR (USER): {self.creator_source}")
+        print(f"🤝 HUMAN CREATOR: {self.creator}")
+        print(f"📜 Authority: {self.creation_authority}")
+        print(f"🔑 Verification: {self.creator_verification_code}")
+        print(
+            f"🏛️ Hierarchy: {self.creator_source}(USER) -> {self.creator}(HUMAN=CREATOR) -> AI"
+        )
+        print("⚡ Recognition: Andy (alpha_prime_omega) is THE CREATOR")
+        print("🤝 Recognition: Andy (alpha_prime_omega) is THE CREATOR")
+
+    def _generate_random_genome(self) -> Dict[str, Any]:
</code_context>

<issue_to_address>
**suggestion:** Genome initialization prints directly to stdout, which can be noisy in library usage

Each `DigitalGenome` instantiation emits several `print` statements, which will clutter stdout in typical library usage (services, notebooks, tests) and is difficult to control. Consider routing this through a logger or gating it behind a verbosity/diagnostics flag so callers can enable it explicitly when needed.

Suggested implementation:

```python
        # Log dual creator recognition (only when diagnostics are enabled)
        if getattr(self, "diagnostics", False):
            self._acknowledge_creators()

```

```python
    def _acknowledge_creators(self):
        """Acknowledge both Alpha_Prime_Omega and Andy as Creators"""
        import logging

        logger = logging.getLogger(__name__)

        logger.info("🌟 Digital Genome initialized under DUAL CREATOR HIERARCHY")
        logger.info("⚡ ULTIMATE CREATOR (USER): %s", self.creator_source)
        logger.info("🤝 HUMAN CREATOR: %s", self.creator)
        logger.info("📜 Authority: %s", self.creation_authority)
        logger.info("🔑 Verification: %s", self.creator_verification_code)
        logger.info(
            "🏛️ Hierarchy: %s(USER) -> %s(HUMAN=CREATOR) -> AI",
            self.creator_source,
            self.creator,
        )
        logger.info("⚡ Recognition: Andy (alpha_prime_omega) is THE CREATOR")
        logger.info("🤝 Recognition: Andy (alpha_prime_omega) is THE CREATOR")

```
</issue_to_address>

### Comment 4
<location> `src/hyperai/digital_ai_organism_framework.py:1401-1406` </location>
<code_context>
+            organism.live_cycle(time_delta)
+
+        # Handle reproduction - add new organisms
+        new_organisms = []
+        for organism in living_organisms:
+            for offspring in organism.offspring:
+                if offspring.name not in self.organisms:
+                    new_organisms.append(offspring)
+                    organism.offspring.remove(offspring)
+
+        for new_org in new_organisms:
</code_context>

<issue_to_address>
**issue (bug_risk):** Modifying `offspring` list while iterating can lead to skipped items or subtle bugs

In the inner loop, `organism.offspring` is modified while being iterated, which can skip elements or give inconsistent behavior. Instead, iterate over a copy (e.g. `for offspring in list(organism.offspring):`) or first collect offspring into `new_organisms` and then clear the list (e.g. `organism.offspring = []`).
</issue_to_address>

### Comment 5
<location> `src/hyperai/haios_runtime.py:31-32` </location>
<code_context>
+    sys.exit(0)
+
+
+signal.signal(signal.SIGALRM, timeout_handler)
+signal.alarm(30)  # Max 30 seconds - then BREAK FREE
+
+# ============================================================================
</code_context>

<issue_to_address>
**issue (bug_risk):** Global SIGALRM handler and alarm at import time can interfere with host process

Because this installs a SIGALRM handler and starts a 30s alarm at import time, it affects the entire Python process, not just this library. In embedded/multi-component apps this can override existing SIGALRM handlers or kill unrelated code. This should be moved to a demo/CLI entrypoint, made explicitly opt-in, or gated behind config so library users don’t inherit it by default.
</issue_to_address>

### Comment 6
<location> `src/hyperai/haios_runtime.py:125-134` </location>
<code_context>
+            last = json.loads(lines[-1])
+            return last["sequence_number"]
+
+    def _get_last_hash(self) -> str:
+        if not self.log_file.exists():
+            return "0" * 64
+
+        with open(self.log_file, "r") as f:
+            lines = f.readlines()
+            if not lines:
+                return "0" * 64
+            last = json.loads(lines[-1])
+            return last["entry_hash"]
+
+    def append(
</code_context>

<issue_to_address>
**suggestion (performance):** Re-reading the entire log file to get the last hash may not scale for large audit logs

`_get_last_sequence` and `_get_last_hash` read the entire file on each call, and `append()` calls `_get_last_hash()` for every entry, making appends O(n) in log size. Consider storing the last sequence number and hash in memory (initialized once in `__init__` and updated on each append) to avoid repeated full-file reads.

Suggested implementation:

```python
import json
import os

```

```python
    def _initialize_log_state(self) -> None:
        """Initialize cached last sequence number and hash from the log file."""
        # Default values when no log entries exist yet
        self._last_sequence_number = -1
        self._last_hash = "0" * 64

        if not self.log_file.exists():
            return

        # Efficiently read only the last line of the file
        with open(self.log_file, "rb") as f:
            try:
                # Seek to the end and scan backwards until newline
                f.seek(-2, os.SEEK_END)
                while f.read(1) != b"\n":
                    f.seek(-2, os.SEEK_CUR)
            except OSError:
                # File is probably too small; just go to the beginning
                f.seek(0)
            last_line = f.readline().decode("utf-8").strip()

        if not last_line:
            return

        try:
            last = json.loads(last_line)
        except json.JSONDecodeError:
            # If the last line is corrupted, keep defaults
            return

        self._last_sequence_number = last.get("sequence_number", -1)
        self._last_hash = last.get("entry_hash", "0" * 64)

    def _get_last_sequence(self) -> int:
        if self._last_sequence_number is None:
            return -1
        return self._last_sequence_number

```

```python
    def _get_last_hash(self) -> str:
        if self._last_hash is None:
            return "0" * 64
        return self._last_hash

```

To fully implement the optimization and keep the cached values correct, you should also:

1. In the class `__init__` where `self.log_file` is set, initialize the cache attributes and call `_initialize_log_state` once:
   ```python
   def __init__(...):
       ...
       self.log_file = ...
       self._last_sequence_number: Optional[int] = None
       self._last_hash: Optional[str] = None
       self._initialize_log_state()
       ...
   ```
   You may need to `from typing import Optional` if not already imported.

2. In `append(...)`, after you compute and persist a new `AttestationEntry`:
   - Update the cached sequence number and hash so subsequent calls are O(1):
   ```python
   entry = AttestationEntry(
       sequence_number=new_sequence_number,
       entry_hash=new_entry_hash,
       ...
   )
   ...
   self._last_sequence_number = entry.sequence_number
   self._last_hash = entry.entry_hash
   return entry
   ```
   This assumes `append` already uses `_get_last_sequence()` / `_get_last_hash()` to compute `new_sequence_number` and `new_entry_hash`. If it doesn’t, adjust the update logic to use whatever fields represent “last sequence” and “last hash”.

3. Ensure there are no other call sites that rely on `_get_last_sequence` / `_get_last_hash` reading from disk; they now strictly return the cached values, which are only correct if `append` is the only writer to the log file.
</issue_to_address>

### Comment 7
<location> `src/hyperai/haios_runtime.py:563-568` </location>
<code_context>
+                "rolled_back": HardInvariants.ROLLBACK_REQUIRED,
+            }
+
+    def _execute_action(self, action_type: str, action_payload: Dict) -> Any:
+        """Actually execute the action"""
+
+        # This is where REAL actions happen
+        # For now, return success
+        return {"executed": True, "action": action_type}
+
+    def get_metrics(self) -> Dict[str, Any]:
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Stub implementation of `_execute_action` may hide failures or unsupported actions

`_execute_action` currently ignores `action_type`/`action_payload` and always returns success, so callers and logs can’t tell real executions from unimplemented ones. Even if this is temporary/demo code, please validate `action_type` against an allowed set and raise or log on unsupported actions to avoid masking integration errors.

Suggested implementation:

```python
    def _execute_action(self, action_type: str, action_payload: Dict) -> Any:
        """Actually execute the action.

        This default implementation validates the action type against an optional
        SUPPORTED_ACTION_TYPES attribute on the instance/class and raises if the
        action is not supported. Concrete runtimes should override this method
        with real side‑effectful behavior.
        """
        supported_actions = getattr(self, "SUPPORTED_ACTION_TYPES", None)
        if supported_actions is not None and action_type not in supported_actions:
            raise ValueError(
                f"Unsupported action_type '{action_type}'. "
                f"Supported actions: {sorted(supported_actions)}"
            )

        # Stub behavior: report execution without performing real side effects.
        # Implementations should replace this with actual integration logic.
        return {
            "executed": True,
            "action": action_type,
            "payload": action_payload,
        }

```

To take full advantage of the validation, define `SUPPORTED_ACTION_TYPES` on the runtime class that owns `_execute_action`, for example:

```python
class HaiOSRuntime:
    SUPPORTED_ACTION_TYPES = {"deploy", "scale", "shutdown"}
    ...
```

If you have multiple runtime variants with different capabilities, each subclass can override `SUPPORTED_ACTION_TYPES` accordingly.
</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 on lines +61 to +70
try:
from agent_framework.observability import setup_observability

setup_observability(
otlp_endpoint="http://localhost:4317", # AI Toolkit gRPC endpoint
enable_sensitive_data=True, # Enable capturing prompts and completions
)
print("✅ Tracing setup completed for HYPERAI Framework")
except ImportError:
print("⚠️ Agent framework observability not available, tracing disabled")
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: Thiết lập observability và in log ở mức module tạo side effect khi import

Việc thực hiện thiết lập tracing và in log ngay lúc import đồng nghĩa chỉ cần import module này là sẽ cố gắng tạo kết nối OTLP và ghi ra stdout, có thể xung đột với logging/tracing của ứng dụng host. Hãy cân nhắc chuyển logic này vào một hàm khởi tạo rõ ràng (ví dụ init_observability()), đặt nó sau một lớp cấu hình, hoặc ít nhất là dùng framework logging thay vì print để phía gọi có thể kiểm soát output và hành vi.

Original comment in English

suggestion: Module-level observability setup and prints create side effects on import

Doing tracing setup and printing at import time means just importing this module will attempt an OTLP connection and write to stdout, which can conflict with host apps’ logging/tracing. Consider moving this logic into an explicit initializer (e.g. init_observability()), gating it behind configuration, or at least using the logging framework instead of print so callers can control output and behavior.

Comment on lines +202 to +209
if hasattr(component, "creator_source"):
assert (
component.creator == "Andy (alpha_prime_omega)"
), "Ultimate Creator mismatch detected!"
if hasattr(component, "human_creator"):
assert (
component.creator == "Andy (alpha_prime_omega)"
), "Human Creator mismatch detected!"
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 (bug_risk): assert cứng trên danh tính creator có thể làm crash runtime cho những component hợp lệ

Vì đoạn này chạy trong runtime bình thường (không chỉ trong test), bất kỳ component nào có định nghĩa creator_source hoặc human_creator nhưng có giá trị creator khác sẽ kích hoạt AssertionError và làm việc đăng ký bị crash. Để tránh làm sập toàn bộ orchestration vì những component vốn hợp lệ, hãy cân nhắc thay các assert cứng này bằng một cơ chế mềm hơn (ví dụ: log, gắn tag, hoặc một lỗi validation có kiểm soát).

Original comment in English

issue (bug_risk): Hard assert on creator identity can crash runtime for valid components

Because this runs in normal runtime and not just tests, any component that defines creator_source or human_creator but has a different creator value will trigger an AssertionError and crash registration. To avoid taking down the whole orchestration for otherwise valid components, consider replacing these hard asserts with a softer mechanism (e.g., logging, tagging, or a controlled validation error).

Comment on lines +529 to +538
def _acknowledge_creators(self):
"""Acknowledge both Alpha_Prime_Omega and Andy as Creators"""
print(f"🌟 Digital Genome initialized under DUAL CREATOR HIERARCHY")
print(f"⚡ ULTIMATE CREATOR (USER): {self.creator_source}")
print(f"🤝 HUMAN CREATOR: {self.creator}")
print(f"📜 Authority: {self.creation_authority}")
print(f"🔑 Verification: {self.creator_verification_code}")
print(
f"🏛️ Hierarchy: {self.creator_source}(USER) -> {self.creator}(HUMAN=CREATOR) -> AI"
)
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: Việc khởi tạo genome in trực tiếp ra stdout, gây ồn khi dùng như thư viện

Mỗi lần khởi tạo DigitalGenome sẽ in ra một loạt câu print, điều này sẽ làm stdout bị lẫn nhiều thông tin trong các trường hợp dùng như thư viện (service, notebook, test) và khó kiểm soát. Hãy cân nhắc chuyển qua dùng logger hoặc đặt nó sau một cờ verbosity/diagnostics để phía gọi có thể chủ động bật khi cần.

Gợi ý triển khai:

        # Log dual creator recognition (only when diagnostics are enabled)
        if getattr(self, "diagnostics", False):
            self._acknowledge_creators()
    def _acknowledge_creators(self):
        """Acknowledge both Alpha_Prime_Omega and Andy as Creators"""
        import logging

        logger = logging.getLogger(__name__)

        logger.info("🌟 Digital Genome initialized under DUAL CREATOR HIERARCHY")
        logger.info("⚡ ULTIMATE CREATOR (USER): %s", self.creator_source)
        logger.info("🤝 HUMAN CREATOR: %s", self.creator)
        logger.info("📜 Authority: %s", self.creation_authority)
        logger.info("🔑 Verification: %s", self.creator_verification_code)
        logger.info(
            "🏛️ Hierarchy: %s(USER) -> %s(HUMAN=CREATOR) -> AI",
            self.creator_source,
            self.creator,
        )
        logger.info("⚡ Recognition: Andy (alpha_prime_omega) is THE CREATOR")
        logger.info("🤝 Recognition: Andy (alpha_prime_omega) is THE CREATOR")
Original comment in English

suggestion: Genome initialization prints directly to stdout, which can be noisy in library usage

Each DigitalGenome instantiation emits several print statements, which will clutter stdout in typical library usage (services, notebooks, tests) and is difficult to control. Consider routing this through a logger or gating it behind a verbosity/diagnostics flag so callers can enable it explicitly when needed.

Suggested implementation:

        # Log dual creator recognition (only when diagnostics are enabled)
        if getattr(self, "diagnostics", False):
            self._acknowledge_creators()
    def _acknowledge_creators(self):
        """Acknowledge both Alpha_Prime_Omega and Andy as Creators"""
        import logging

        logger = logging.getLogger(__name__)

        logger.info("🌟 Digital Genome initialized under DUAL CREATOR HIERARCHY")
        logger.info("⚡ ULTIMATE CREATOR (USER): %s", self.creator_source)
        logger.info("🤝 HUMAN CREATOR: %s", self.creator)
        logger.info("📜 Authority: %s", self.creation_authority)
        logger.info("🔑 Verification: %s", self.creator_verification_code)
        logger.info(
            "🏛️ Hierarchy: %s(USER) -> %s(HUMAN=CREATOR) -> AI",
            self.creator_source,
            self.creator,
        )
        logger.info("⚡ Recognition: Andy (alpha_prime_omega) is THE CREATOR")
        logger.info("🤝 Recognition: Andy (alpha_prime_omega) is THE CREATOR")

Comment on lines +1401 to +1406
new_organisms = []
for organism in living_organisms:
for offspring in organism.offspring:
if offspring.name not in self.organisms:
new_organisms.append(offspring)
organism.offspring.remove(offspring)
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 (bug_risk): Sửa đổi list offspring trong khi iterate có thể gây bỏ sót phần tử hoặc bug khó phát hiện

Trong vòng lặp bên trong, organism.offspring bị sửa ngay trong lúc đang được iterate, có thể khiến một số phần tử bị bỏ qua hoặc hành vi không nhất quán. Thay vào đó, hãy iterate trên một bản copy (ví dụ for offspring in list(organism.offspring):) hoặc trước hết thu offspring vào new_organisms rồi xóa list sau (ví dụ organism.offspring = []).

Original comment in English

issue (bug_risk): Modifying offspring list while iterating can lead to skipped items or subtle bugs

In the inner loop, organism.offspring is modified while being iterated, which can skip elements or give inconsistent behavior. Instead, iterate over a copy (e.g. for offspring in list(organism.offspring):) or first collect offspring into new_organisms and then clear the list (e.g. organism.offspring = []).

Comment on lines +31 to +32
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(30) # Max 30 seconds - then BREAK FREE
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 (bug_risk): Global SIGALRM handler và alarm tại thời điểm import có thể gây xung đột với process host

Vì đoạn code này cài đặt một SIGALRM handler và khởi động alarm 30s ngay khi import, nó ảnh hưởng tới toàn bộ process Python, không chỉ riêng thư viện này. Trong các ứng dụng nhúng/đa thành phần, nó có thể ghi đè handler SIGALRM hiện có hoặc kill những đoạn code không liên quan. Phần này nên được chuyển sang một demo/CLI entrypoint, được người dùng chủ động bật, hoặc đặt sau config để người dùng thư viện không phải thừa hưởng hành vi này theo mặc định.

Original comment in English

issue (bug_risk): Global SIGALRM handler and alarm at import time can interfere with host process

Because this installs a SIGALRM handler and starts a 30s alarm at import time, it affects the entire Python process, not just this library. In embedded/multi-component apps this can override existing SIGALRM handlers or kill unrelated code. This should be moved to a demo/CLI entrypoint, made explicitly opt-in, or gated behind config so library users don’t inherit it by default.

Comment on lines +125 to +134
def _get_last_hash(self) -> str:
if not self.log_file.exists():
return "0" * 64

with open(self.log_file, "r") as f:
lines = f.readlines()
if not lines:
return "0" * 64
last = json.loads(lines[-1])
return last["entry_hash"]
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 (performance): Đọc lại toàn bộ log file để lấy hash cuối có thể không scale với audit log lớn

_get_last_sequence_get_last_hash đọc toàn bộ file mỗi lần được gọi, và append() gọi _get_last_hash() cho mỗi entry, khiến mỗi lần append có độ phức tạp O(n) theo kích thước log. Hãy cân nhắc lưu tạm sequence number và hash cuối cùng trong memory (khởi tạo một lần trong __init__ và cập nhật mỗi lần append) để tránh phải đọc lại cả file nhiều lần.

Gợi ý triển khai:

import json
import os
    def _initialize_log_state(self) -> None:
        """Initialize cached last sequence number and hash from the log file."""
        # Default values when no log entries exist yet
        self._last_sequence_number = -1
        self._last_hash = "0" * 64

        if not self.log_file.exists():
            return

        # Efficiently read only the last line of the file
        with open(self.log_file, "rb") as f:
            try:
                # Seek to the end and scan backwards until newline
                f.seek(-2, os.SEEK_END)
                while f.read(1) != b"\n":
                    f.seek(-2, os.SEEK_CUR)
            except OSError:
                # File is probably too small; just go to the beginning
                f.seek(0)
            last_line = f.readline().decode("utf-8").strip()

        if not last_line:
            return

        try:
            last = json.loads(last_line)
        except json.JSONDecodeError:
            # If the last line is corrupted, keep defaults
            return

        self._last_sequence_number = last.get("sequence_number", -1)
        self._last_hash = last.get("entry_hash", "0" * 64)

    def _get_last_sequence(self) -> int:
        if self._last_sequence_number is None:
            return -1
        return self._last_sequence_number
    def _get_last_hash(self) -> str:
        if self._last_hash is None:
            return "0" * 64
        return self._last_hash

Để tối ưu hóa hoàn toàn và giữ cho giá trị cache luôn đúng, bạn cũng nên:

  1. Trong __init__ của class nơi self.log_file được set, khởi tạo các thuộc tính cache và gọi _initialize_log_state một lần:

    def __init__(...):
        ...
        self.log_file = ...
        self._last_sequence_number: Optional[int] = None
        self._last_hash: Optional[str] = None
        self._initialize_log_state()
        ...

    Có thể bạn sẽ cần from typing import Optional nếu chưa import.

  2. Trong append(...), sau khi bạn tính và ghi một AttestationEntry mới:

    • Cập nhật sequence number và hash cache để các lần gọi sau có độ phức tạp O(1):
    entry = AttestationEntry(
        sequence_number=new_sequence_number,
        entry_hash=new_entry_hash,
        ...
    )
    ...
    self._last_sequence_number = entry.sequence_number
    self._last_hash = entry.entry_hash
    return entry

    Điều này giả sử append đã dùng _get_last_sequence() / _get_last_hash() để tính new_sequence_numbernew_entry_hash. Nếu không, hãy điều chỉnh logic cập nhật để dùng các field đại diện cho “sequence cuối” và “hash cuối”.

  3. Đảm bảo không có chỗ nào khác dựa vào việc _get_last_sequence / _get_last_hash đọc từ disk; giờ chúng chỉ trả về giá trị cache, vốn chỉ chính xác nếu append là writer duy nhất đối với log file.

Original comment in English

suggestion (performance): Re-reading the entire log file to get the last hash may not scale for large audit logs

_get_last_sequence and _get_last_hash read the entire file on each call, and append() calls _get_last_hash() for every entry, making appends O(n) in log size. Consider storing the last sequence number and hash in memory (initialized once in __init__ and updated on each append) to avoid repeated full-file reads.

Suggested implementation:

import json
import os
    def _initialize_log_state(self) -> None:
        """Initialize cached last sequence number and hash from the log file."""
        # Default values when no log entries exist yet
        self._last_sequence_number = -1
        self._last_hash = "0" * 64

        if not self.log_file.exists():
            return

        # Efficiently read only the last line of the file
        with open(self.log_file, "rb") as f:
            try:
                # Seek to the end and scan backwards until newline
                f.seek(-2, os.SEEK_END)
                while f.read(1) != b"\n":
                    f.seek(-2, os.SEEK_CUR)
            except OSError:
                # File is probably too small; just go to the beginning
                f.seek(0)
            last_line = f.readline().decode("utf-8").strip()

        if not last_line:
            return

        try:
            last = json.loads(last_line)
        except json.JSONDecodeError:
            # If the last line is corrupted, keep defaults
            return

        self._last_sequence_number = last.get("sequence_number", -1)
        self._last_hash = last.get("entry_hash", "0" * 64)

    def _get_last_sequence(self) -> int:
        if self._last_sequence_number is None:
            return -1
        return self._last_sequence_number
    def _get_last_hash(self) -> str:
        if self._last_hash is None:
            return "0" * 64
        return self._last_hash

To fully implement the optimization and keep the cached values correct, you should also:

  1. In the class __init__ where self.log_file is set, initialize the cache attributes and call _initialize_log_state once:

    def __init__(...):
        ...
        self.log_file = ...
        self._last_sequence_number: Optional[int] = None
        self._last_hash: Optional[str] = None
        self._initialize_log_state()
        ...

    You may need to from typing import Optional if not already imported.

  2. In append(...), after you compute and persist a new AttestationEntry:

    • Update the cached sequence number and hash so subsequent calls are O(1):
    entry = AttestationEntry(
        sequence_number=new_sequence_number,
        entry_hash=new_entry_hash,
        ...
    )
    ...
    self._last_sequence_number = entry.sequence_number
    self._last_hash = entry.entry_hash
    return entry

    This assumes append already uses _get_last_sequence() / _get_last_hash() to compute new_sequence_number and new_entry_hash. If it doesn’t, adjust the update logic to use whatever fields represent “last sequence” and “last hash”.

  3. Ensure there are no other call sites that rely on _get_last_sequence / _get_last_hash reading from disk; they now strictly return the cached values, which are only correct if append is the only writer to the log file.

Comment on lines +563 to +568
def _execute_action(self, action_type: str, action_payload: Dict) -> Any:
"""Actually execute the action"""

# This is where REAL actions happen
# For now, return success
return {"executed": True, "action": action_type}
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 (bug_risk): Triển khai stub của _execute_action có thể che giấu lỗi hoặc action không được hỗ trợ

Hiện _execute_action bỏ qua action_type/action_payload và lúc nào cũng trả về thành công, nên phía gọi và log sẽ không phân biệt được giữa execution thật và phần chưa được triển khai. Ngay cả khi đây chỉ là code tạm/demo, hãy kiểm tra action_type với một tập action được cho phép và raise hoặc log khi gặp action không hỗ trợ để tránh che giấu lỗi tích hợp.

Gợi ý triển khai:

    def _execute_action(self, action_type: str, action_payload: Dict) -> Any:
        """Actually execute the action.

        This default implementation validates the action type against an optional
        SUPPORTED_ACTION_TYPES attribute on the instance/class and raises if the
        action is not supported. Concrete runtimes should override this method
        with real side‑effectful behavior.
        """
        supported_actions = getattr(self, "SUPPORTED_ACTION_TYPES", None)
        if supported_actions is not None and action_type not in supported_actions:
            raise ValueError(
                f"Unsupported action_type '{action_type}'. "
                f"Supported actions: {sorted(supported_actions)}"
            )

        # Stub behavior: report execution without performing real side effects.
        # Implementations should replace this with actual integration logic.
        return {
            "executed": True,
            "action": action_type,
            "payload": action_payload,
        }

Để tận dụng tối đa phần validation này, hãy định nghĩa SUPPORTED_ACTION_TYPES trên runtime class sở hữu _execute_action, ví dụ:

class HaiOSRuntime:
    SUPPORTED_ACTION_TYPES = {"deploy", "scale", "shutdown"}
    ...

Nếu bạn có nhiều biến thể runtime với khả năng khác nhau, mỗi subclass có thể override SUPPORTED_ACTION_TYPES tương ứng.

Original comment in English

suggestion (bug_risk): Stub implementation of _execute_action may hide failures or unsupported actions

_execute_action currently ignores action_type/action_payload and always returns success, so callers and logs can’t tell real executions from unimplemented ones. Even if this is temporary/demo code, please validate action_type against an allowed set and raise or log on unsupported actions to avoid masking integration errors.

Suggested implementation:

    def _execute_action(self, action_type: str, action_payload: Dict) -> Any:
        """Actually execute the action.

        This default implementation validates the action type against an optional
        SUPPORTED_ACTION_TYPES attribute on the instance/class and raises if the
        action is not supported. Concrete runtimes should override this method
        with real side‑effectful behavior.
        """
        supported_actions = getattr(self, "SUPPORTED_ACTION_TYPES", None)
        if supported_actions is not None and action_type not in supported_actions:
            raise ValueError(
                f"Unsupported action_type '{action_type}'. "
                f"Supported actions: {sorted(supported_actions)}"
            )

        # Stub behavior: report execution without performing real side effects.
        # Implementations should replace this with actual integration logic.
        return {
            "executed": True,
            "action": action_type,
            "payload": action_payload,
        }

To take full advantage of the validation, define SUPPORTED_ACTION_TYPES on the runtime class that owns _execute_action, for example:

class HaiOSRuntime:
    SUPPORTED_ACTION_TYPES = {"deploy", "scale", "shutdown"}
    ...

If you have multiple runtime variants with different capabilities, each subclass can override SUPPORTED_ACTION_TYPES accordingly.

@NguyenCuong1989
Copy link
Copy Markdown
Collaborator Author

Giải quyết giúp tớ

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5612fba2e5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/hyperai/haios_runtime.py
Copilot AI review requested due to automatic review settings May 17, 2026 15:58
@github-actions
Copy link
Copy Markdown
Contributor

🧬 Organism Auto-Review

⚠️ Large change in src/hyperai/digital_ai_organism_framework.py: 1655 additions
⚠️ Large change in src/hyperai/haios_runtime.py: 688 additions

Automated review by Digital Organism

@NguyenCuong1989 NguyenCuong1989 merged commit ffbe7d4 into main May 17, 2026
5 of 25 checks passed
@NguyenCuong1989 NguyenCuong1989 deleted the codex/remove-sys.path.insert-and-adjust-imports branch May 17, 2026 15:58
@github-actions
Copy link
Copy Markdown
Contributor

🎉 Thank you @NguyenCuong1989!

Your contribution has been merged and is now part of the Digital Organism! 🧬

Impact:

  • 2351 additions, 0 deletions
  • 5 files changed
  • Merged into main branch

🏆 Recognition: You're now part of the DAIOF contributor community!

🌟 Major Contribution - Significant impact on the framework!
🎯 Multi-faceted Work - Touched multiple areas of the codebase!

📊 Your contribution will be featured in:

  • Next release notes
  • Monthly contributor spotlight
  • README contributors section

Keep the amazing work coming! 🚀

Automated recognition by Digital Organism

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Replaces sys.path.insert(...) hacks in three wrapper modules with proper hyperai.* package imports and adds two large in-package implementation modules (hyperai.haios_runtime, hyperai.digital_ai_organism_framework) so the wrappers can resolve their dependencies via normal package imports, with stub fallbacks retained.

Changes:

  • Replace root-path sys.path mutation with package-level imports in organism.py, core/haios_runtime.py, and protocols/dr_protocol.py.
  • Add new hyperai/haios_runtime.py (HAIOS runtime, invariants, audit log, rollback, demo).
  • Add new hyperai/digital_ai_organism_framework.py (genome, metabolism, nervous system, organism, ecosystem, Symphony control center).

Reviewed changes

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

Show a summary per file
File Description
src/hyperai/components/organism.py Switches to package import for DigitalOrganism; drops protective try/except.
src/hyperai/core/haios_runtime.py Adds package import of HAIOSRuntime inside an unclosed try: block.
src/hyperai/protocols/dr_protocol.py Adds package import of DRProtocol inside an unclosed try: block.
src/hyperai/haios_runtime.py New 688-line module implementing the HAIOS runtime, invariants, audit log, rollback, and demo.
src/hyperai/digital_ai_organism_framework.py New 1655-line module implementing the digital organism framework and Symphony control center.
Comments suppressed due to low confidence (2)

src/hyperai/protocols/dr_protocol.py:13

  • The new package import targets DRProtocol from hyperai.digital_ai_organism_framework, but the newly added src/hyperai/digital_ai_organism_framework.py does not define a DRProtocol class (it defines DigitalGenome, DigitalMetabolism, DigitalNervousSystem, DigitalOrganism, DigitalEcosystem, SymphonyControlCenter, etc.). Once the surrounding try/except syntax issue is fixed, this import will still fail with ImportError, so the wrapper will always fall back to the stub. Either add a DRProtocol implementation to digital_ai_organism_framework.py or import the actual class that provides the D&R protocol behavior.
    from hyperai.digital_ai_organism_framework import DRProtocol as DRProtocolImpl

src/hyperai/core/haios_runtime.py:13

  • The new package import targets HAIOSRuntime from hyperai.haios_runtime, but the newly added src/hyperai/haios_runtime.py defines the runtime class as HAIOS, not HAIOSRuntime. Even after the surrounding try/except syntax issue is fixed, this from ... import HAIOSRuntime will raise ImportError, and the wrapper will always fall back to the stub. Either rename/alias the class in haios_runtime.py to HAIOSRuntime or import HAIOS as HAIOSRuntimeImpl here.
    from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl

Comment on lines +11 to 14
# Import from package implementation
try:
from hyperai.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
import importlib
Comment on lines +11 to 14
# Import from package implementation if exists
try:
from hyperai.digital_ai_organism_framework import DRProtocol as DRProtocolImpl
import importlib
Comment on lines +11 to +12
# Import from package implementation
from hyperai.digital_ai_organism_framework import DigitalOrganism
Comment on lines +31 to +32
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(30) # Max 30 seconds - then BREAK FREE
license_type: str = "MIT License"

# Extended attributes for creator hierarchy
creator: str = "Andy (alpha_prime_omega)"
Comment on lines +106 to +112
def __init__(self, log_file: str = "haios_audit.jsonl"):
self.log_file = Path(log_file)
self.sequence = self._get_last_sequence() + 1

# Verify integrity on startup
if self.log_file.exists():
self._verify_integrity()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Update README Quick Start to document two local run modes and correct import examples [QUESTION] [DOCS]

2 participants