Skip to content

Enforce preflight gate, add runtime bootstrap, DB integrity check, health daemon, and test matrix#86

Open
NguyenCuong1989 wants to merge 1 commit intomainfrom
codex/refactor-daily_dnr_run.py-for-double-run-guard-s5hmca
Open

Enforce preflight gate, add runtime bootstrap, DB integrity check, health daemon, and test matrix#86
NguyenCuong1989 wants to merge 1 commit intomainfrom
codex/refactor-daily_dnr_run.py-for-double-run-guard-s5hmca

Conversation

@NguyenCuong1989
Copy link
Copy Markdown
Owner

@NguyenCuong1989 NguyenCuong1989 commented Feb 11, 2026

Motivation

  • Ensure every runtime entrypoint respects the deterministic preflight gate to avoid respawn storms and ambiguous failures by stopping on hard FAIL (2).
  • Provide a deterministic production bootstrap flow that prepares directories, initializes the DB with WAL, runs rotation and DNR, and boots jobs in explicit order.
  • Add a DB integrity gate and a watchdog to detect and record recurring hard failures so operators can react to systemic degradation.
  • Provide an automated integration test matrix and unit tests to assert the strict 0/1/2 exit semantics across failure scenarios.

Description

  • Enforced preflight in entrypoints by running ./tools/runtime/preflight.sh --summary and immediately exiting on rc==2 in tools/runtime/launchd_safe_wrapper.sh and tools/runtime/daily_dnr_run.py (the latter can be skipped with SKIP_PREFLIGHT=1).
  • Added tools/runtime/bootstrap_runtime.sh which runs the preflight gate (respects POLICY_ALLOW_WARN), ensures ~/.hyperai/{logs,state,db}, initializes the SQLite DB with PRAGMA journal_mode=WAL and baseline tables, runs log rotation and the daily DNR, and sequentially bootstraps launchd jobs with a final post-bootstrap preflight and deterministic exit code.
  • Extended tools/runtime/preflight.sh with a check_db_integrity function that runs sqlite3 "$DB_PATH" "PRAGMA integrity_check;" and maps results to 0/1/2 per policy, keeping the prior disk, entrypoint, job, and log gates and the --summary mode.
  • Added integration/test tooling: tools/runtime/test_runtime_matrix.sh (simulates missing entrypoints, low disk, log pressure, corrupt DB, DB lock overlap, and launchd absence) and tests/runtime/test_runtime_tools.py unit tests for preflight, DNR idempotence, and the health daemon.
  • Implemented tools/runtime/runtime_health_daemon.py to run preflight on an interval, log JSON event lines, track consecutive FAIL counts, and write an system_unhealthy.marker when threshold is reached; added PROMPTS.md and updated docs/operations/runtime_stability_blueprint.md to document the flow and contracts.

Testing

  • Static/syntax checks: ran bash -n on modified shell scripts and python3 -m py_compile on Python scripts and they succeeded.
  • Unit test suite: ran python3 -m unittest tests.runtime.test_runtime_tools which executed 3 tests and returned OK.
  • Integration matrix: executed ./tools/runtime/test_runtime_matrix.sh and it completed with no failures (all scenarios asserted expected exit semantics).
  • Bootstrap smoke: exercised POLICY_ALLOW_WARN=1 bootstrap in a temporary environment to validate directory creation, DB initialization, DNR invocation, rotation, and observed the expected WARN-path with exit 1 under the constrained CI environment.

Codex Task

Summary by Sourcery

Giới thiệu một luồng kiểm tra trước (preflight), khởi động (bootstrap) và giám sát sức khỏe runtime mang tính tất định cho HyperAI runtime cục bộ, được hỗ trợ bởi kiểm tra tính toàn vẹn SQLite, xoay vòng log (log rotation) và ma trận kiểm thử để áp đặt chặt chẽ ngữ nghĩa mã thoát 0/1/2.

Tính năng mới:

  • Thêm script DNR chạy hàng ngày, quản lý một chu kỳ bảo trì mỗi ngày một lần có khóa, sử dụng SQLite với khởi tạo WAL và mã thoát tất định.
  • Thêm một daemon sức khỏe runtime định kỳ chạy preflight, ghi log các sự kiện sức khỏe dạng JSON, và ghi một marker không khỏe (unhealthy) khi số lần lỗi liên tiếp vượt quá ngưỡng.
  • Thêm một script bootstrap runtime để chuẩn bị thư mục, khởi tạo cơ sở dữ liệu, chạy bảo trì hàng ngày và xoay vòng log, và tuần tự bootstrap các job launchd với bước kiểm tra sức khỏe sau bootstrap.
  • Giới thiệu một script xoay vòng log thực thi xoay vòng dựa trên kích thước và đảm bảo an toàn theo tuổi log, với các bản lưu trữ nén và chính sách lưu giữ.
  • Thêm một script ma trận kiểm thử runtime để mô phỏng các kịch bản lỗi và khẳng định ngữ nghĩa mã thoát mong đợi trên các hành vi preflight và DNR.
  • Thêm một wrapper an toàn với launchd cho các entrypoint Python, có ghi log preflight và thực thi, tuân thủ các lỗi preflight nghiêm trọng.

Cải tiến:

  • Thêm một script preflight toàn diện để kiểm tra dung lượng đĩa, các entrypoint bắt buộc, các job launchd, tính toàn vẹn cơ sở dữ liệu và áp lực log, rồi tổng hợp chúng thành một cổng đánh giá sức khỏe có chấm điểm với ngữ nghĩa 0/1/2 nghiêm ngặt.

Tài liệu:

  • Tài liệu hóa bản thiết kế ổn định runtime mang tính tất định, bao gồm thứ tự các cổng, bảng hành vi job, các lệnh vận hành và cách sử dụng ma trận runtime.
  • Thêm một hướng dẫn prompt cho công việc runtime theo hướng agent, chuẩn hóa ngữ nghĩa mã thoát, các script bắt buộc, lệnh xác thực và quy tắc viết mã.

Kiểm thử:

  • Thêm unit test cho hành vi lỗi preflight, tính idempotent của DNR hàng ngày, và xu hướng cùng đầu ra marker của daemon sức khỏe runtime.
Original summary in English

Summary by Sourcery

Introduce a deterministic runtime preflight, bootstrap, and health monitoring flow for the local HyperAI runtime, backed by SQLite integrity checks, log rotation, and a test matrix to enforce strict 0/1/2 exit semantics.

New Features:

  • Add a daily DNR runner script that manages a locked, once-per-day SQLite-backed maintenance cycle with WAL initialization and deterministic exit codes.
  • Add a runtime health daemon that periodically runs preflight, logs JSON health events, and writes an unhealthy marker when consecutive failures exceed a threshold.
  • Add a runtime bootstrap script that prepares directories, initializes the database, runs daily maintenance and log rotation, and sequentially bootstraps launchd jobs with post-bootstrap health gating.
  • Introduce a log rotation script that enforces size-based rotation and age-aware safety with compressed archives and retention policies.
  • Add a runtime test matrix script to simulate failure scenarios and assert expected exit semantics across preflight and DNR behaviors.
  • Add a launchd-safe wrapper for Python entrypoints that logs preflight and execution, respecting hard preflight failures.

Enhancements:

  • Add a comprehensive preflight script that checks disk capacity, required entrypoints, launchd jobs, database integrity, and log pressure, aggregating them into a scored health gate with strict 0/1/2 semantics.

Documentation:

  • Document the deterministic runtime stability blueprint, including gate ordering, job behavior table, operational commands, and runtime matrix usage.
  • Add a prompt guide for agent-oriented runtime work that codifies exit semantics, required scripts, validation commands, and coding rules.

Tests:

  • Add unit tests for preflight failure behavior, daily DNR idempotence, and the runtime health daemon trend and marker outputs.

@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Feb 11, 2026

Hướng Dẫn Cho Người Review (Reviewer's Guide)

Triển khai một framework ổn định runtime có tính quyết định bằng cách giới thiệu một “preflight health gate”, một script bootstrap chuẩn bị các thư mục runtime và DB SQLite (WAL), một trình chạy DNR hằng ngày, một health daemon định kỳ với các marker “unhealthy”, xoay vòng log (log rotation), cùng ma trận test runtime tự động và unit test để thực thi nghiêm ngặt semantics mã thoát 0/1/2.

ER diagram cho các bảng SQLite runtime được DNR và bootstrap sử dụng

erDiagram
  runtime_bootstrap {
    INTEGER id PK
    TEXT boot_at
  }

  dnr_runs {
    INTEGER id PK
    TEXT run_at
  }

  %% No explicit foreign keys; tables are independent
  runtime_bootstrap ||--o{ dnr_runs : records_separate_events
Loading

Class diagram cho locking và DB helpers trong daily_dnr_run.py

classDiagram

  class CycleLock {
    -Path path
    -int fd
    +CycleLock(path)
    +__enter__() CycleLock
    +__exit__(exc_type, exc, tb) void
  }

  class DailyDnrModule {
    +parse_args() argparse_Namespace
    +configure_logging(log_dir) void
    +marker_for_today(marker_dir) Path
    +mark_cycle_complete(marker) void
    +wal_marker_for_db(db_path, state_dir) Path
    +ensure_wal_initialized(db_path, state_dir) void
    +connect_db(db_path, state_dir) sqlite3_Connection
    +run_cycle(db_path, marker_dir, lock_file, state_dir) int
    +run_preflight_gate() int
    +main() int
  }

  DailyDnrModule "1" o-- "1" CycleLock : uses_for_exclusive_cycle
  DailyDnrModule "1" o-- "1" sqlite3_Connection : manages_db_connection
Loading

Thay Đổi Ở Cấp Độ File

Thay đổi Chi tiết File
Thêm trình chạy DNR hằng ngày có tính quyết định với khởi tạo DB hỗ trợ WAL và preflight gating.
  • Giới thiệu context manager CycleLock sử dụng lockfile trong state dir để đảm bảo semantics “single-run”.
  • Implement hàm run_cycle hằng ngày, idempotent, ghi vào bảng dnr_runs, dùng file marker theo từng ngày và bỏ qua một cách “graceful” nếu DB không tồn tại.
  • Thêm helper khởi tạo WAL thiết lập PRAGMA journal_mode=WAL và synchronous=NORMAL, đồng thời dùng file marker để tránh khởi tạo lại.
  • Chạy preflight gate trước cycle (có thể bỏ qua qua biến môi trường SKIP_PREFLIGHT), chuyển tiếp (forward) output của preflight và coi FAIL cứng (2) là dừng nghiêm trọng.
  • Ánh xạ tranh chấp lock và lỗi sqlite sang mã thoát WARN/FAIL đồng thời đảm bảo semantics mã thoát 0/1/2 có tính quyết định.
tools/runtime/daily_dnr_run.py
Giới thiệu script preflight hợp nhất, đảm bảo các gate về đĩa, entrypoint, job, tính toàn vẹn DB và áp lực log với semantics 0/1/2 nghiêm ngặt.
  • Thêm các ngưỡng và đường dẫn cấu hình được (MIN_FREE_GB, DISK_PATH, DB_PATH, LOG_DIR, JOB_PATTERN) cùng danh sách REQUIRED_SCRIPTS để xác thực entrypoint.
  • Implement các hàm check_disk, check_entrypoints, check_jobs, check_db_integrity và check_logs, xuất các dòng trạng thái có nhãn và trả về 0/1/2 tùy mức độ nghiêm trọng.
  • Thêm gate kiểm tra toàn vẹn DB dùng sqlite3 PRAGMA integrity_check, ánh xạ kết quả không-ok sang FAIL (2) và DB/sqlite3 thiếu sang WARN (1).
  • Tổng hợp kết quả các gate vào HEALTH_SCORE, theo dõi mọi hard_fail và chuyển score/hard-fail thành mã thoát cuối cùng 0/1/2 với tùy chọn output --summary.
  • Đảm bảo trường hợp thiếu launchctl và áp lực log chỉ phát ra WARN, giữ hành vi không mang tính “critical” nhưng vẫn hiển thị vấn đề.
tools/runtime/preflight.sh
Thêm script bootstrap runtime sắp xếp tuần tự preflight, tạo thư mục, khởi tạo DB, gọi DNR, xoay vòng log và bootstrap job launchd với mã thoát có tính quyết định.
  • Chạy preflight.sh --summary trước tiên và áp dụng POLICY_ALLOW_WARN để quyết định WARN (1) có chặn bootstrap hay không.
  • Đảm bảo tồn tại các thư mục state, log và DB, đồng thời khởi tạo DB SQLite với WAL và các bảng baseline khi còn thiếu, với fallback WARN nếu sqlite3 không khả dụng.
  • Gọi các script daily_dnr_run.py và rotate_hyperai_logs.sh theo kiểu “best-effort”, bỏ qua lỗi của chúng để không chặn quá trình bootstrap.
  • Bootstrap danh sách cố định các job launchd thông qua launchctl bootout/bootstrap/kickstart, log các file plist bị thiếu và cho phép môi trường không có launchctl.
  • Chạy gate preflight cuối cùng sau bootstrap và dịch kết quả của nó thành mã thoát và thông điệp bootstrap rõ ràng (OK, WARN, FAIL).
tools/runtime/bootstrap_runtime.sh
Thêm health daemon chạy preflight gate theo chu kỳ, log sự kiện JSON, và ghi marker “unhealthy” khi số lần lỗi vượt quá ngưỡng.
  • Expose các tham số CLI cho khoảng thời gian lặp (interval), ngưỡng số lần lỗi, state dir, logfile và số vòng lặp tối đa để hỗ trợ cả chế độ daemon và test.
  • Mỗi cycle chạy preflight.sh --summary, phản chiếu stdout/stderr và chuẩn hóa mã thoát thành các trạng thái có tên (OK/WARN/FAIL).
  • Theo dõi các trạng thái FAIL liên tiếp, ghi thêm (append) các dòng JSON có cấu trúc vào logfile và duy trì một snapshot runtime_health_trend.json phản ánh sự kiện mới nhất.
  • Tạo hoặc xóa file system_unhealthy.marker dựa trên việc số lỗi liên tiếp có đạt ngưỡng được cấu hình hay không.
  • Cho phép chạy hữu hạn thông qua --max-cycles để hỗ trợ unit test có tính quyết định đối với hành vi của daemon.
tools/runtime/runtime_health_daemon.py
Thêm unit test để xác thực hành vi lỗi preflight, tính idempotent của DNR và việc tạo marker “unhealthy” của health daemon.
  • Thêm preflight test buộc DISK_PATH không hợp lệ và assert mã thoát 2 từ preflight.sh --summary.
  • Test daily_dnr_run.py bằng cách chạy nó hai lần trong môi trường tạm với SKIP_PREFLIGHT=1 và assert thành công idempotent (rc=0 cả hai lần).
  • Test runtime_health_daemon.py với DISK_PATH gây lỗi, interval ngắn, threshold thấp và max-cycles=1, assert nó thoát với 0 và ghi cả file trend lẫn file marker unhealthy.
tests/runtime/test_runtime_tools.py
Giới thiệu script xoay vòng log với ngưỡng kích thước/tuổi file và chính sách lưu giữ (retention policy) cho log chuẩn và log lỗi.
  • Phát hiện các file log trong LOG_DIR, bỏ qua xoay vòng với các file được chỉnh sửa trong vòng MIN_AGE_SECONDS, và chỉ xoay vòng những file vượt các ngưỡng kích thước theo từng lớp.
  • Implement các helper kích thước file và mtime có tính “portable”, hỗ trợ cả biến thể stat BSD và GNU.
  • Khi xoay vòng, di chuyển file sang tên có timestamp, truncate file gốc, gzip bản copy đã xoay vòng và in các thông điệp ROTATED.
  • Dọn dẹp các archive .error.log..gz và .log..gz cũ dựa trên cài đặt riêng RETENTION_DAYS_ERROR và RETENTION_DAYS_STANDARD.
tools/runtime/rotate_hyperai_logs.sh
Tài liệu hóa bản thiết kế (blueprint) ổn định runtime và các hợp đồng prompt theo hướng agent cho vận hành và test có tính quyết định.
  • Thêm blueprint ổn định runtime mô tả thứ tự các gate, semantics mã thoát, bảng trạng thái runtime, kỳ vọng về tính toàn vẹn DB và các ví dụ gọi daily DNR, bootstrap và test matrix.
  • Thêm PROMPTS.md với hợp đồng cốt lõi cho semantics mã thoát 0/1/2, snippet preflight guard cho shell entrypoint, danh sách script runtime bắt buộc, lệnh xác thực và các quy tắc coding cho tính quyết định và khả năng chẩn đoán.
docs/operations/runtime_stability_blueprint.md
PROMPTS.md
Thêm ma trận test runtime để kiểm tra các chế độ lỗi và xác minh mã thoát kỳ vọng cho script preflight và daily DNR.
  • Tạo một harness chạy preflight.sh và daily_dnr_run.py dưới nhiều điều kiện mô phỏng khác nhau và so sánh mã thoát của chúng với giá trị kỳ vọng.
  • Mô phỏng thiếu entrypoint bằng cách tạm thời di chuyển bootstrap_runtime.sh ra khỏi vị trí, và xác nhận preflight lỗi (rc=2).
  • Mô phỏng dung lượng đĩa thấp bằng DISK_PATH không hợp lệ, áp lực log bằng log file lớn và hỏng DB bằng file không phải SQLite, assert các kết quả WARN/FAIL phù hợp.
  • Mô phỏng chồng lặp lock DNR bằng cách tạo trước lockfile và kỳ vọng WARN (1), đồng thời mô phỏng môi trường không có launchctl nhưng input “healthy” dẫn tới WARN do thiếu job.
  • Tóm tắt kết quả chạy bằng MATRIX_RESULT, fail script với rc=2 nếu bất kỳ kịch bản nào không đáp ứng semantics mã thoát mong đợi.
tools/runtime/test_runtime_matrix.sh
Thêm wrapper an toàn với launchd, chạy preflight trước khi thực thi Python entrypoint và chuẩn hóa hành vi launchd để tránh “respawn storm”.
  • Tham số hóa đường dẫn script được bọc, log và binary python thông qua biến môi trường với giá trị mặc định hợp lý.
  • Chạy preflight.sh --summary và log output của nó; coi FAIL cứng (2) là chí tử và exit 2, nhưng cho phép WARN/OK tiếp tục.
  • Bảo vệ trường hợp thiếu SCRIPT_PATH bằng cách log lỗi, ngủ ngắn và exit 0 để tránh khuếch đại respawn của launchd.
  • Thực thi script Python mục tiêu, log stdout/stderr sang các log run/error riêng, và khi lỗi thì log error, ngủ ngắn nhưng vẫn exit 0.
  • Đảm bảo wrapper luôn exit 0 cho các lỗi không thuộc preflight để giữ các job launchd KeepAlive tránh lặp respawn, trong khi vẫn bảo tồn khả năng chẩn đoán.
tools/runtime/launchd_safe_wrapper.sh

Tips và lệnh hữu ích

Tương tác với Sourcery

  • Kích hoạ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 issue từ một review comment bằng cách reply vào comment đó. Bạn cũng có thể trả lời một review comment với @sourcery-ai issue để tạo issue từ comment đó.
  • Sinh tiêu đề pull request: Viết @sourcery-ai ở bất kỳ đâu trong tiêu đề pull request để sinh 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) sinh tiêu đề bất cứ lúc nào.
  • Sinh tóm tắt pull request: Viết @sourcery-ai summary ở bất kỳ đâu trong phần body của pull request để sinh 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) sinh tóm tắt bất cứ lúc nào.
  • Sinh hướng dẫn cho người review: Comment @sourcery-ai guide trên pull request để (tái) sinh hướng dẫn cho người review (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 để resolve tất cả comment của Sourcery. Hữu ích khi bạn đã xử lý xong mọi comment và không muốn thấy chúng nữa.
  • Dismiss tất cả review của Sourcery: Comment @sourcery-ai dismiss trên pull request để dismiss tất cả review hiện tại của Sourcery. Đặc biệt hữu ích nếu bạn muốn bắt đầu lại với mộ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 sinh, hướng dẫn cho người review, và các tính năng khác.
  • Thay đổi ngôn ngữ review.
  • Thêm, xóa hoặc chỉnh sửa các hướng dẫn review tùy biến.
  • Đ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

Implements a deterministic runtime stability framework by introducing a preflight health gate, a bootstrap script that prepares runtime directories and SQLite (WAL) DB, a daily DNR runner, a periodic health daemon with unhealthy markers, log rotation, and an automated runtime test matrix plus unit tests to enforce strict 0/1/2 exit semantics.

ER diagram for runtime SQLite tables used by DNR and bootstrap

erDiagram
  runtime_bootstrap {
    INTEGER id PK
    TEXT boot_at
  }

  dnr_runs {
    INTEGER id PK
    TEXT run_at
  }

  %% No explicit foreign keys; tables are independent
  runtime_bootstrap ||--o{ dnr_runs : records_separate_events
Loading

Class diagram for daily_dnr_run.py locking and DB helpers

classDiagram

  class CycleLock {
    -Path path
    -int fd
    +CycleLock(path)
    +__enter__() CycleLock
    +__exit__(exc_type, exc, tb) void
  }

  class DailyDnrModule {
    +parse_args() argparse_Namespace
    +configure_logging(log_dir) void
    +marker_for_today(marker_dir) Path
    +mark_cycle_complete(marker) void
    +wal_marker_for_db(db_path, state_dir) Path
    +ensure_wal_initialized(db_path, state_dir) void
    +connect_db(db_path, state_dir) sqlite3_Connection
    +run_cycle(db_path, marker_dir, lock_file, state_dir) int
    +run_preflight_gate() int
    +main() int
  }

  DailyDnrModule "1" o-- "1" CycleLock : uses_for_exclusive_cycle
  DailyDnrModule "1" o-- "1" sqlite3_Connection : manages_db_connection
Loading

File-Level Changes

Change Details Files
Add deterministic daily DNR runner with WAL-aware DB initialization and preflight gating.
  • Introduce a CycleLock context manager using lockfiles in the state dir to enforce single-run semantics.
  • Implement daily idempotent run_cycle that writes to a dnr_runs table, uses a per-day marker file, and gracefully skips if DB is missing.
  • Add WAL initialization helper that sets PRAGMA journal_mode=WAL and synchronous=NORMAL and uses a marker file to avoid re-initialization.
  • Run a preflight gate before the cycle (skippable via SKIP_PREFLIGHT), forwarding preflight output and treating hard FAIL (2) as a critical stop.
  • Map lock contention and sqlite errors to WARN/FAIL exit codes while ensuring deterministic 0/1/2 semantics.
tools/runtime/daily_dnr_run.py
Introduce a consolidated preflight script that enforces disk, entrypoint, job, DB integrity, and log-pressure gates with strict 0/1/2 semantics.
  • Add configurable thresholds and paths (MIN_FREE_GB, DISK_PATH, DB_PATH, LOG_DIR, JOB_PATTERN) and a REQUIRED_SCRIPTS list for entrypoint validation.
  • Implement check_disk, check_entrypoints, check_jobs, check_db_integrity, and check_logs functions that emit labeled status lines and return 0/1/2 based on severity.
  • Add a DB integrity gate using sqlite3 PRAGMA integrity_check, mapping non-ok results to FAIL (2) and missing DB/sqlite3 to WARN (1).
  • Aggregate gate results into a HEALTH_SCORE, track any hard_fail, and convert score/hard-fail into final exit codes 0/1/2 with optional --summary output.
  • Ensure launchctl absence and log pressure only emit WARN, preserving non-critical behavior while still surfacing issues.
tools/runtime/preflight.sh
Add a runtime bootstrap script that sequences preflight, directory creation, DB initialization, DNR invocation, log rotation, and launchd job bootstrapping with deterministic exit codes.
  • Run preflight.sh --summary up front and enforce POLICY_ALLOW_WARN to decide whether WARN (1) should block bootstrap.
  • Ensure state, log, and DB directories exist and initialize the SQLite DB with WAL and baseline tables when missing, with a fallback WARN if sqlite3 is unavailable.
  • Invoke the daily_dnr_run.py and rotate_hyperai_logs.sh scripts in a best-effort manner, ignoring their failures for bootstrap continuity.
  • Bootstrap a fixed list of launchd jobs via launchctl bootout/bootstrap/kickstart, logging missing plist files and allowing environments without launchctl.
  • Run a final preflight gate post-bootstrap and translate its result into explicit bootstrap exit codes and messages (OK, WARN, FAIL).
tools/runtime/bootstrap_runtime.sh
Add a health daemon that periodically runs the preflight gate, logs JSON events, and writes an unhealthy marker once failures exceed a threshold.
  • Expose CLI arguments for interval, failure threshold, state dir, log file, and max cycles to support both daemon and test modes.
  • Run preflight.sh --summary each cycle, mirror its stdout/stderr, and normalize exit codes into named states (OK/WARN/FAIL).
  • Track consecutive FAIL states, append structured JSON lines to a log file, and maintain a single runtime_health_trend.json snapshot with the latest event.
  • Create or remove a system_unhealthy.marker based on whether consecutive failures meet the configured threshold.
  • Allow finite run via --max-cycles to enable deterministic unit testing of the daemon behavior.
tools/runtime/runtime_health_daemon.py
Add unit tests to validate preflight failure behavior, DNR idempotence, and health daemon unhealthy marker creation.
  • Add a preflight test that forces an invalid DISK_PATH and asserts exit code 2 from preflight.sh --summary.
  • Test daily_dnr_run.py by running it twice in a temp environment with SKIP_PREFLIGHT=1 and asserting idempotent success (rc=0 both runs).
  • Test runtime_health_daemon.py with a failing DISK_PATH, short interval, low threshold, and max-cycles=1, asserting it exits 0 and writes trend and unhealthy marker files.
tests/runtime/test_runtime_tools.py
Introduce a log rotation script with size/age thresholds and retention policy for standard and error logs.
  • Detect log files under LOG_DIR, skip rotation for files modified within MIN_AGE_SECONDS, and rotate only those exceeding per-class size thresholds.
  • Implement portable file size and mtime helpers supporting both BSD and GNU stat variants.
  • On rotation, move the file to a timestamped name, truncate the original, gzip the rotated copy, and print ROTATED messages.
  • Clean up historical .error.log..gz and .log..gz archives based on separate RETENTION_DAYS_ERROR and RETENTION_DAYS_STANDARD settings.,
tools/runtime/rotate_hyperai_logs.sh
Document the runtime stability blueprint and agent-oriented runtime prompt contracts for deterministic operation and testing.
  • Add a runtime stability blueprint that describes gate ordering, exit semantics, runtime state table, DB integrity expectations, and invocation examples for daily DNR, bootstrap, and test matrix.
  • Add PROMPTS.md with a core contract for 0/1/2 exit semantics, preflight guard snippet for shell entrypoints, required runtime scripts list, validation commands, and coding rules for determinism and diagnostics.
docs/operations/runtime_stability_blueprint.md
PROMPTS.md
Add a runtime test matrix to exercise failure modes and verify expected exit codes for the preflight and daily DNR scripts.
  • Create a harness that runs preflight.sh and daily_dnr_run.py under multiple simulated conditions and compares their exit codes to expected values.
  • Simulate missing entrypoints by temporarily moving bootstrap_runtime.sh out of place, and validate preflight failure (rc=2).
  • Simulate low disk via invalid DISK_PATH, log pressure via large log files, and DB corruption via a non-SQLite file, asserting appropriate WARN/FAIL outcomes.
  • Simulate DNR lock overlap by pre-creating a lockfile and expecting WARN (1), and a no-launchctl environment with healthy inputs leading to WARN due to missing jobs.
  • Summarize the run with a MATRIX_RESULT, failing the script with rc=2 if any scenario did not meet the expected exit semantics.
tools/runtime/test_runtime_matrix.sh
Add a launchd-safe wrapper that runs preflight before executing a Python entrypoint and normalizes launchd behavior to avoid respawn storms.
  • Parameterize the wrapped script path, logs, and python binary via environment variables with sensible defaults.
  • Run preflight.sh --summary and log its output; treat a hard FAIL (2) as fatal and exit 2, but allow WARN/OK to continue.
  • Guard against missing SCRIPT_PATH by logging an error, sleeping briefly, and exiting 0 to avoid launchd respawn amplification.
  • Execute the target Python script, logging stdout/stderr to dedicated run/error logs, and on failure log an error, sleep briefly, and still exit 0.
  • Ensure the wrapper always exits 0 for non-preflight failures to keep launchd KeepAlive jobs from entering respawn storms while preserving diagnostics.
tools/runtime/launchd_safe_wrapper.sh

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
Entrypoint path injection

Description: The wrapper executes an entrypoint from SCRIPT_PATH (argument or ORIG) and appends output
to logs, so if an untrusted actor can influence the job arguments/environment they can
redirect execution to an arbitrary local script (same-user code execution) or redirect log
paths to unintended locations.
launchd_safe_wrapper.sh [4-36]

Referred Code
SCRIPT_PATH="${1:-${ORIG:-$HOME/workbench/daily_dnr_run.py}}"
if [[ $# -gt 0 ]]; then
  shift
fi

ERR_LOG="${ERR_LOG:-$HOME/.hyperai/logs/os_master_error.log}"
RUN_LOG="${RUN_LOG:-$HOME/.hyperai/logs/os_master.log}"
PYTHON_BIN="${PYTHON_BIN:-python3}"

mkdir -p "$(dirname "$ERR_LOG")"

ts() {
  date '+%Y-%m-%dT%H:%M:%S%z'
}

./tools/runtime/preflight.sh --summary >> "$RUN_LOG" 2>> "$ERR_LOG" || rc=$?
rc="${rc:-0}"
if [[ "$rc" -eq 2 ]]; then
  echo "$(ts) [FATAL] Preflight FAIL" >> "$ERR_LOG"
  exit 2
fi


 ... (clipped 12 lines)
Symlink/TOCTOU on lock

Description: CycleLock creates and later unlinks --lock-file without symlink-safe checks, so if an
attacker with write access to the lock directory can swap the lock path for a symlink
between creation and cleanup, it could lead to unintended file deletion or interference
with other files.
daily_dnr_run.py [26-45]

Referred Code
class CycleLock:
    def __init__(self, path: Path) -> None:
        self.path = path
        self.fd: int | None = None

    def __enter__(self) -> "CycleLock":
        self.path.parent.mkdir(parents=True, exist_ok=True)
        try:
            self.fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
            os.write(self.fd, str(os.getpid()).encode())
        except FileExistsError as exc:
            raise RuntimeError(f"Lock already held: {self.path}") from exc
        return self

    def __exit__(self, exc_type, exc, tb) -> None:
        if self.fd is not None:
            os.close(self.fd)
        if self.path.exists():
            self.path.unlink()
Unsafe env-controlled delete

Description: The cleanup routine deletes files via find "$LOG_DIR" ... -delete, so if LOG_DIR is
attacker-controlled (e.g., via environment in a privileged context) it could be abused to
delete matching .log..gz files outside the intended runtime log directory.
rotate_hyperai_logs.sh [55-59]

Referred Code
cleanup_old_archives() {
  local pattern="$1"
  local days="$2"
  find "$LOG_DIR" -type f -name "$pattern" -mtime "+$days" -print -delete
}
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: Passed

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

🔴
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing user context: Critical actions (periodic preflight execution and writing health markers) are logged
without including a user identifier, preventing reliable attribution in an audit trail.

Referred Code
event = {
    "timestamp": now,
    "exit_code": rc,
    "state": state,
    "consecutive_failures": consecutive_failures,
}

state_changed = previous_state != state
if state_changed:
    event["event"] = "state_changed"
append_log(log_file, event)

trend_file.parent.mkdir(parents=True, exist_ok=True)
trend_file.write_text(json.dumps(event, ensure_ascii=False, indent=2), encoding="utf-8")

if consecutive_failures >= args.threshold:
    unhealthy_marker.write_text(now, encoding="utf-8")
elif unhealthy_marker.exists():

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:
Errors silently ignored: The bootstrap flow explicitly suppresses failures for critical steps (DNR run, log
rotation, and launchctl operations) via || true, which can mask broken states and hinder
actionable diagnosis.

Referred Code
if command -v python3 >/dev/null 2>&1; then
  python3 tools/runtime/daily_dnr_run.py \
    --db-path "$DB_PATH" \
    --marker-dir "$STATE_DIR/dnr" \
    --lock-file "$STATE_DIR/dnr.lock" \
    --log-dir "$LOG_DIR" || true
fi

./tools/runtime/rotate_hyperai_logs.sh || true

if command -v launchctl >/dev/null 2>&1; then
  for job in "${JOB_ORDER[@]}"; do
    plist="$PLIST_DIR/$job.plist"
    if [[ -f "$plist" ]]; then
      launchctl bootout "gui/$UID" "$plist" >/dev/null 2>&1 || true
      launchctl bootstrap "gui/$UID" "$plist" >/dev/null 2>&1 || true
      launchctl kickstart -k "gui/$UID/$job" >/dev/null 2>&1 || true
      echo "[INFO] launchctl loaded $job"
    else

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:
Unstructured log lines: New runtime logs are emitted as unstructured plain-text lines (timestamps + messages)
rather than structured JSON, reducing auditability and making automated monitoring/parsing
more error-prone.

Referred Code
./tools/runtime/preflight.sh --summary >> "$RUN_LOG" 2>> "$ERR_LOG" || rc=$?
rc="${rc:-0}"
if [[ "$rc" -eq 2 ]]; then
  echo "$(ts) [FATAL] Preflight FAIL" >> "$ERR_LOG"
  exit 2
fi

if [[ ! -f "$SCRIPT_PATH" ]]; then
  echo "$(ts) Missing entrypoint: $SCRIPT_PATH" >> "$ERR_LOG"
  sleep 2
  exit 0
fi

if ! "$PYTHON_BIN" "$SCRIPT_PATH" "$@" >> "$RUN_LOG" 2>> "$ERR_LOG"; then
  echo "$(ts) Execution fail for $SCRIPT_PATH" >> "$ERR_LOG"
  sleep 2
  exit 0

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:
Raw stderr to stdout: The daemon prints preflight stdout/stderr directly to the console, which may expose
internal paths or system details depending on preflight output and where this daemon is
run.

Referred Code
def run_preflight() -> int:
    result = subprocess.run(["./tools/runtime/preflight.sh", "--summary"], capture_output=True, text=True)
    if result.stdout:
        print(result.stdout.strip())
    if result.stderr:
        print(result.stderr.strip())
    return int(result.returncode)

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:
Unvalidated external inputs: Environment-controlled inputs (e.g., JOB_PATTERN, DISK_PATH, DB_PATH, LOG_DIR) are used
directly in filesystem operations and grep -E without validation/sanitization, which may
be unsafe depending on the threat model and execution context.

Referred Code
MIN_FREE_GB="${MIN_FREE_GB:-15}"
DISK_PATH="${DISK_PATH:-/Users/andy}"
DB_PATH="${DB_PATH:-$HOME/.hyperai/db/memory.sqlite}"
LOG_DIR="${LOG_DIR:-$HOME/.hyperai/logs}"
JOB_PATTERN="${JOB_PATTERN:-hyperai|daily-dnr-runner}"
SUMMARY_ONLY=0

REQUIRED_SCRIPTS=(
  "tools/runtime/preflight.sh"
  "tools/runtime/daily_dnr_run.py"
  "tools/runtime/launchd_safe_wrapper.sh"
  "tools/runtime/rotate_hyperai_logs.sh"
  "tools/runtime/bootstrap_runtime.sh"
)

if [[ "${1:-}" == "--summary" ]]; then
  SUMMARY_ONLY=1
fi

status_line() {
  local label="$1"


 ... (clipped 63 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

qodo-code-review bot commented Feb 11, 2026

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle preflight execution errors correctly

In run_preflight_gate, handle FileNotFoundError and other critical exceptions by
returning an exit code of 2 (FAIL) instead of 1 (WARN) to prevent the process
from continuing in an unsafe state.

tools/runtime/daily_dnr_run.py [131-148]

 def run_preflight_gate() -> int:
     if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
         return 0
 
     try:
         result = subprocess.run(
             ["./tools/runtime/preflight.sh", "--summary"],
             capture_output=True,
             text=True,
             check=False,
         )
         if result.stdout:
             print(result.stdout.strip())
         if result.stderr:
             print(result.stderr.strip())
         return int(result.returncode)
+    except FileNotFoundError:
+        logging.error("Preflight script not found. This is a critical failure.")
+        return 2
     except Exception:
-        return 1
+        logging.exception("Failed to execute preflight script.")
+        return 2
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that masking critical errors like a missing preflight.sh script as a non-critical warning is a significant risk that could lead to unsafe operations.

Medium
General
Clear stale lockfiles

In the CycleLock class, add logic to check if a lock file is stale (i.e., the
process that created it is no longer running) and remove it to prevent
deadlocks.

tools/runtime/daily_dnr_run.py [36-37]

-except FileExistsError as exc:
-        raise RuntimeError(f"Lock already held: {self.path}") from exc
+except FileExistsError:
+        existing = Path(self.path)
+        try:
+            pid = int(existing.read_text())
+            os.kill(pid, 0)
+            # Lock held by a live process
+        except Exception:
+            existing.unlink()
+            return self.__enter__()
+        raise RuntimeError(f"Lock already held: {self.path}")
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: This suggestion addresses a critical potential issue where a stale lock file from a crashed process could cause a permanent deadlock. Adding logic to check for and clear stale locks significantly improves the script's resilience.

Medium
Improve database integrity check error handling

In check_db_integrity, capture stderr from the sqlite3 command and check its
exit code to provide more specific error messages if the command fails, rather
than redirecting stderr to /dev/null.

tools/runtime/preflight.sh [89-110]

 check_db_integrity() {
   if [[ ! -f "$DB_PATH" ]]; then
     status_line "DB" "WARN" "missing database: $DB_PATH"
     return 1
   fi
 
   if ! command -v sqlite3 >/dev/null 2>&1; then
     status_line "DB" "WARN" "sqlite3 command unavailable"
     return 1
   fi
 
   local result
-  result="$(sqlite3 "$DB_PATH" 'PRAGMA integrity_check;' 2>/dev/null | tr -d '\r')"
+  result="$(sqlite3 "$DB_PATH" 'PRAGMA integrity_check;' 2>&1 | tr -d '\r')"
+  local rc=$?
+
+  if [[ $rc -ne 0 ]]; then
+    status_line "DB" "FAIL" "sqlite3 command failed: $result"
+    return 2
+  fi
 
   if [[ "$result" == "ok" ]]; then
     status_line "DB" "OK" "integrity_check=ok"
     return 0
   fi
 
   status_line "DB" "FAIL" "integrity_check=$result"
   return 2
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that suppressing stderr from sqlite3 hides valuable diagnostic information, leading to unhelpful error messages. Capturing stderr and checking the exit code makes error handling more robust and improves debuggability.

Medium
Fix default script resolution

In launchd_safe_wrapper.sh, change the default SCRIPT_PATH to be relative to the
script's own directory instead of using a hardcoded absolute path and an
undefined ORIG variable.

tools/runtime/launchd_safe_wrapper.sh [4]

-SCRIPT_PATH="${1:-${ORIG:-$HOME/workbench/daily_dnr_run.py}}"
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+SCRIPT_PATH="${1:-$SCRIPT_DIR/daily_dnr_run.py}"
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the default path for SCRIPT_PATH is fragile and relies on an undefined variable and a hardcoded path. Using a path relative to the script's own location makes the wrapper more robust and portable.

Medium
Possible issue
Use absolute script path

In run_preflight, use an absolute path to call preflight.sh to ensure it runs
correctly regardless of the current working directory, especially when executed
by services like launchd.

tools/runtime/runtime_health_daemon.py [36-42]

 def run_preflight() -> int:
-    result = subprocess.run(["./tools/runtime/preflight.sh", "--summary"], capture_output=True, text=True)
+    preflight = (Path(__file__).resolve().parent / "preflight.sh")
+    result = subprocess.run([str(preflight), "--summary"], capture_output=True, text=True)
     if result.stdout:
         print(result.stdout.strip())
     if result.stderr:
         print(result.stderr.strip())
     return int(result.returncode)
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a critical robustness issue where the script's execution is dependent on the current working directory, which is unreliable for daemons, and provides a correct fix.

Medium
Avoid failing on low score

Modify the preflight.sh script to only exit with a FAIL status on an explicit
hard gate failure, treating low scores from multiple warnings as a WARN instead.

tools/runtime/preflight.sh [155-167]

 printf 'HEALTH_SCORE: %s/%s\n' "$score" "$total"
 
-if (( hard_fail == 1 || score <= 2 )); then
+if (( hard_fail == 1 )); then
   status_line "SYSTEM_STATE" "FAIL" "hard gate failed"
   (( SUMMARY_ONLY == 1 )) && printf 'SUMMARY: FAIL score=%s/%s\n' "$score" "$total"
   exit 2
 fi
 
-if (( score <= 4 )); then
+if (( score < total )); then
   status_line "SYSTEM_STATE" "WARN" "non-critical warnings present"
   (( SUMMARY_ONLY == 1 )) && printf 'SUMMARY: WARN score=%s/%s\n' "$score" "$total"
   exit 1
 fi
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that multiple warnings can be incorrectly escalated to a hard failure, which contradicts the documented exit semantics, and the proposed change fixes this logic.

Medium
Hash marker filenames safely

In wal_marker_for_db, use a hash of the database path for the marker filename to
prevent issues with long or invalid characters, ensuring idempotency.

tools/runtime/daily_dnr_run.py [78-80]

 def wal_marker_for_db(db_path: Path, state_dir: Path) -> Path:
-    db_key = db_path.resolve().as_posix().replace("/", "_")
-    return state_dir / f"wal_initialized{db_key}.done"
+    import hashlib
 
+    db_key = hashlib.sha256(db_path.resolve().as_posix().encode("utf-8")).hexdigest()[:16]
+    return state_dir / f"wal_initialized_{db_key}.done"
+
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a potential issue with creating filenames from long paths, which could lead to filesystem errors and break idempotency, and proposes a robust hashing-based solution.

Medium
  • 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 - tôi đã tìm thấy 6 vấn đề và để lại một số phản hồi tổng quan:

  • Trong preflight.sh giá trị mặc định của DISK_PATH đang được hardcode thành /Users/andy, khiến bước kiểm tra dung lượng đĩa không dùng lại được trên các máy khác; hãy cân nhắc đặt mặc định là $HOME hoặc một đường dẫn tổng quát hơn để lần kiểm tra này hoạt động đúng trên nhiều môi trường người dùng khác nhau.
  • Trong launchd_safe_wrapper.sh giá trị fallback của SCRIPT_PATH đang mặc định là $HOME/workbench/daily_dnr_run.py, có vẻ phụ thuộc vào repo/người dùng cụ thể; có thể sẽ ổn định hơn nếu mặc định trỏ tới file được track tools/runtime/daily_dnr_run.py hoặc yêu cầu truyền đường dẫn rõ ràng.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Trong `preflight.sh` giá trị mặc định của `DISK_PATH` đang được hardcode thành `/Users/andy`, khiến bước kiểm tra dung lượng đĩa không dùng lại được trên các máy khác; hãy cân nhắc đặt mặc định là `$HOME` hoặc một đường dẫn tổng quát hơn để lần kiểm tra này hoạt động đúng trên nhiều môi trường người dùng khác nhau.
- Trong `launchd_safe_wrapper.sh` giá trị fallback của `SCRIPT_PATH` đang mặc định là `$HOME/workbench/daily_dnr_run.py`, có vẻ phụ thuộc vào repo/người dùng cụ thể; có thể sẽ ổn định hơn nếu mặc định trỏ tới file được track `tools/runtime/daily_dnr_run.py` hoặc yêu cầu truyền đường dẫn rõ ràng.

## Individual Comments

### Comment 1
<location> `tools/runtime/daily_dnr_run.py:131-148` </location>
<code_context>
+
+
+
+def run_preflight_gate() -> int:
+    if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
+        return 0
+
+    try:
+        result = subprocess.run(
+            ["./tools/runtime/preflight.sh", "--summary"],
+            capture_output=True,
+            text=True,
+            check=False,
+        )
+        if result.stdout:
+            print(result.stdout.strip())
+        if result.stderr:
+            print(result.stderr.strip())
+        return int(result.returncode)
+    except Exception:
+        return 1
+
</code_context>

<issue_to_address>
**suggestion:** Hãy cân nhắc log khi chính việc gọi preflight bị lỗi thay vì âm thầm trả về 1.

Hiện tại mọi ngoại lệ từ `subprocess.run` (thiếu script, quyền truy cập, v.v.) đều được ánh xạ thành mã thoát `1` mà không có ngữ cảnh, khiến lỗi hạ tầng không phân biệt được với một WARN thực sự. Vui lòng log ngoại lệ hoặc một thông báo lỗi ngắn trước khi trả về để bên gọi có thể phân biệt lỗi preflight với lỗi runtime/môi trường khi diễn giải mã thoát.

```suggestion
def run_preflight_gate() -> int:
    if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
        return 0

    try:
        result = subprocess.run(
            ["./tools/runtime/preflight.sh", "--summary"],
            capture_output=True,
            text=True,
            check=False,
        )
        if result.stdout:
            print(result.stdout.strip())
        if result.stderr:
            print(result.stderr.strip())
        return int(result.returncode)
    except Exception:
        logging.exception("Preflight gate invocation failed (unable to run preflight.sh)")
        return 1
```
</issue_to_address>

### Comment 2
<location> `tools/runtime/runtime_health_daemon.py:36-37` </location>
<code_context>
+        handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
+
+
+def run_preflight() -> int:
+    result = subprocess.run(["./tools/runtime/preflight.sh", "--summary"], capture_output=True, text=True)
+    if result.stdout:
+        print(result.stdout.strip())
</code_context>

<issue_to_address>
**issue (bug_risk):** Việc dùng đường dẫn tương đối cho `preflight.sh` khiến daemon phụ thuộc vào thư mục làm việc hiện tại.

`subprocess.run([
</issue_to_address>

### Comment 3
<location> `tools/runtime/preflight.sh:5` </location>
<code_context>
+set -euo pipefail
+
+MIN_FREE_GB="${MIN_FREE_GB:-15}"
+DISK_PATH="${DISK_PATH:-/Users/andy}"
+DB_PATH="${DB_PATH:-$HOME/.hyperai/db/memory.sqlite}"
+LOG_DIR="${LOG_DIR:-$HOME/.hyperai/logs}"
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Giá trị mặc định của `DISK_PATH` gắn với người dùng cụ thể và có thể không chạy được trên các máy khác.

Hãy cân nhắc đặt mặc định thành một đường dẫn tổng quát hơn (ví dụ `${DISK_PATH:-$HOME}` hoặc tương tự) để preflight có thể dùng lại được, đồng thời vẫn cho phép override qua biến môi trường.

```suggestion
DISK_PATH="${DISK_PATH:-$HOME}"
```
</issue_to_address>

### Comment 4
<location> `tools/runtime/launchd_safe_wrapper.sh:4` </location>
<code_context>
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_PATH="${1:-${ORIG:-$HOME/workbench/daily_dnr_run.py}}"
+if [[ $# -gt 0 ]]; then
+  shift
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Giá trị mặc định của `SCRIPT_PATH` trỏ tới một đường dẫn gần như chỉ tồn tại cục bộ, có thể không ổn định.

Vì `$HOME/workbench/daily_dnr_run.py` phụ thuộc vào môi trường, nên khi `ORIG` không được set và không truyền tham số vị trí nào, script này rất có thể sẽ lỗi trong hầu hết môi trường. Hãy cân nhắc đặt mặc định thành một đường dẫn bên trong repo (ví dụ `./tools/runtime/daily_dnr_run.py` được resolve tương đối so với wrapper) để script có một giá trị mặc định có thể dùng lại và có thể dự đoán được.

```suggestion
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
SCRIPT_PATH="${1:-${ORIG:-"$SCRIPT_DIR/daily_dnr_run.py"}}"
```
</issue_to_address>

### Comment 5
<location> `tests/runtime/test_runtime_tools.py:22-31` </location>
<code_context>
+    def test_daily_dnr_idempotent_same_day(self):
</code_context>

<issue_to_address>
**suggestion (testing):** Thêm các bài test DNR cho trường hợp thiếu DB, tranh chấp lock, và các nhánh lỗi SQLite

Để kiểm thử đầy đủ hợp đồng mã thoát của `daily_dnr_run.py`, vui lòng thêm các bài test:
- Bao phủ trường hợp thiếu đường dẫn DB và assert WARN (thoát 1) cùng log cảnh báo.
- Mô phỏng tranh chấp lock (giữ trước file lock) và assert nhánh `RuntimeError` cũng cho kết quả WARN (thoát 1).
- Gây ra `sqlite3.Error` (ví dụ file DB hỏng hoặc lỗi quyền) và assert FAIL (thoát 2).
Điều này đảm bảo tất cả các nhánh được mô tả trong `main()` đều được kiểm chứng bằng test.

Gợi ý triển khai:

```python
DAEMON = ROOT / "tools/runtime/runtime_health_daemon.py"
DAILY_DNR = ROOT / "tools/runtime/daily_dnr_run.py"

```

```python
    def test_preflight_fail_on_invalid_disk_path(self):
        env = os.environ.copy()
        env["DISK_PATH"] = "/path/does/not/exist"
        result = subprocess.run([str(PREFLIGHT), "--summary"], cwd=ROOT, env=env, capture_output=True, text=True)
        self.assertEqual(result.returncode, 2)

    def test_daily_dnr_idempotent_same_day(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "memory.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"
            db.parent.mkdir(parents=True, exist_ok=True)
            sqlite3.connect(db).close()

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            # First run should succeed and create the marker/lock state
            result1 = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result1.returncode, 0)

            # Second run on the same day should be idempotent and still succeed
            result2 = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result2.returncode, 0)

    def test_daily_dnr_warns_on_missing_db(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "missing.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            result = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )

            # WARN: Missing DB should exit 1 and emit a warning on stderr
            self.assertEqual(result.returncode, 1)
            self.assertTrue(result.stderr, "Expected warning output when DB path is missing")

    def test_daily_dnr_warns_on_lock_contention(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "memory.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"
            db.parent.mkdir(parents=True, exist_ok=True)
            sqlite3.connect(db).close()

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            # Pre-hold the lock file to simulate another process owning it
            lock_file.parent.mkdir(parents=True, exist_ok=True)
            with open(lock_file, "w") as fh:
                try:
                    import fcntl

                    fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
                except (ImportError, OSError):
                    # If flock is not available or locking fails for platform reasons,
                    # still keep the file present to exercise the lock contention path
                    pass

                result = subprocess.run(
                    [sys.executable, str(DAILY_DNR)],
                    cwd=ROOT,
                    env=env,
                    capture_output=True,
                    text=True,
                )

            # WARN: lock contention is treated as RuntimeError -> exit 1
            self.assertEqual(result.returncode, 1)
            self.assertTrue(result.stderr, "Expected warning output when lock contention occurs")

    def test_daily_dnr_fails_on_sqlite_error(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            # Point DB at a directory to provoke a sqlite3.Error when connecting
            db = td_path / "not_a_file.sqlite"
            db.mkdir(parents=True, exist_ok=True)

            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            result = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )

            # FAIL: sqlite3.Error paths should exit 2 and log an error
            self.assertEqual(result.returncode, 2)
            self.assertTrue(result.stderr, "Expected error output when sqlite3.Error is raised")

```

1. Đảm bảo `DAILY_DNR` là hằng đường dẫn đúng cho `daily_dnr_run.py`; nếu file này đã có một hằng khác (ví dụ `DAILY_DNR_RUN`), hãy tái sử dụng thay vì tạo hằng mới.
2. Đồng bộ tên các biến môi trường (`DAILY_DNR_DB_PATH`, `DAILY_DNR_LOG_DIR`, `DAILY_DNR_MARKER_DIR`, `DAILY_DNR_LOCK_FILE`) với những gì `daily_dnr_run.main()` thực sự đọc; cập nhật các key trong cả bốn bài test cho phù hợp.
3. Nếu `daily_dnr_run.py` được gọi trực tiếp như một script thực thi (shebang + `chmod +x`), và các test khác gọi nó mà không qua `sys.executable`, hãy cập nhật các lệnh `subprocess.run` cho phù hợp với convention hiện tại.
4. Nếu thông báo cảnh báo/lỗi đã biết và ổn định, hãy tăng độ chặt cho các assert trên `stderr` bằng cách kiểm tra các substring cụ thể (ví dụ "WARN" hoặc thông điệp log cụ thể) thay vì chỉ kiểm tra là có output.
</issue_to_address>

### Comment 6
<location> `tests/runtime/test_runtime_tools.py:53-62` </location>
<code_context>
+    def test_health_daemon_writes_trend(self):
</code_context>

<issue_to_address>
**suggestion (testing):** Mở rộng các test cho health daemon để kiểm tra nội dung sự kiện, ngưỡng và hành vi phục hồi

Bài test hiện tại chỉ assert rằng một chu kỳ FAIL đơn lẻ tạo ra `runtime_health_trend.json` và marker unhealthy. Để kiểm thử hành vi của daemon tốt hơn, hãy cân nhắc:
- Assert rằng entry JSON trong trend chứa các trường mong đợi (`exit_code`, `state`, `consecutive_failures`, và tùy chọn `event == 'state_changed'`).
- Thêm một bài test đa chu kỳ với `max-cycles > 1` để xác minh `threshold` được tôn trọng (ví dụ threshold=2 chỉ đánh dấu unhealthy sau 2 FAIL liên tiếp).
- Thêm một bài test phục hồi, trong đó một chu kỳ FAIL được theo sau bởi một chu kỳ không FAIL, assert rằng `consecutive_failures` được reset và bất kỳ `system_unhealthy.marker` hiện có nào được xóa.
Điều này sẽ giúp kiểm chứng đầy đủ ngữ nghĩa watchdog chạy lâu dài.

Gợi ý triển khai:

```python
import os
import json
import subprocess
import tempfile
from pathlib import Path

```

```python
    def test_health_daemon_writes_trend(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            # Force the daemon into a failing state so we exercise the
            # unhealthy path and trend writing.
            env = os.environ.copy()
            env["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "1",
                "--threshold",
                "1",
            ]

            result = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            # Validate that at least one event was written and that it contains
            # the core fields we expect for watchdog semantics.
            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            self.assertGreaterEqual(len(events), 1)
            last = events[-1]

            self.assertIn("exit_code", last)
            self.assertIn("state", last)
            self.assertIn("consecutive_failures", last)
            if "event" in last:
                self.assertEqual(last["event"], "state_changed")

            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

    def test_health_daemon_honors_failure_threshold(self):
        """Verify that threshold > 1 only marks unhealthy after enough consecutive failures."""
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            env = os.environ.copy()
            env["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "3",
                "--threshold",
                "2",
            ]

            result = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            # We expect multiple cycles to have been recorded.
            self.assertGreaterEqual(len(events), 2)

            # Find the last event for the failing probe and assert that the
            # consecutive failure count reached at least the threshold.
            last = events[-1]
            self.assertIn("consecutive_failures", last)
            self.assertGreaterEqual(last["consecutive_failures"], 2)

            # Once threshold is reached, the system must be marked unhealthy.
            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

    def test_health_daemon_recovers_and_resets_failures(self):
        """Verify that a recovery cycle resets consecutive_failures and clears the unhealthy marker."""
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            # First run: force failures so we cross the threshold.
            env_fail = os.environ.copy()
            env_fail["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "3",
                "--threshold",
                "2",
            ]

            result_fail = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env_fail,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result_fail.returncode, 0, msg=result_fail.stderr)

            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

            # Second run: allow the daemon to succeed so it can recover.
            env_ok = os.environ.copy()
            # Do not override DISK_PATH (or set it to a valid path) so the probe passes.

            result_ok = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env_ok,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result_ok.returncode, 0, msg=result_ok.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            self.assertGreaterEqual(len(events), 1)
            last = events[-1]

            # Recovery should reset the failure counter.
            self.assertIn("consecutive_failures", last)
            self.assertEqual(last["consecutive_failures"], 0)

            # Recovery should also clear any unhealthy marker.
            self.assertFalse(marker_path.exists())

```

Các lệnh và tên trường JSON trong các bài test này giả định daemon hỗ trợ các tùy chọn CLI và schema sự kiện sau:

- Cờ CLI: `--state-dir`, `--log-file`, `--max-cycles`, `--threshold`.
- Các trường sự kiện JSON: ít nhất `exit_code`, `state`, `consecutive_failures`, và tùy chọn `event == "state_changed"` khi chuyển trạng thái.
- Một file marker tên `system_unhealthy.marker` được tạo/xóa dưới `state_dir`.

Nếu CLI hoặc schema thực tế khác, bạn nên:
1. Điều chỉnh mảng `cmd` (các cờ/giá trị) cho khớp với các tham số thật.
2. Cập nhật các key JSON được assert (`exit_code`, `state`, `consecutive_failures`, `event`) thành các tên trường thật sự mà daemon sử dụng.
3. Cập nhật tên file marker (`system_unhealthy.marker`) và kỳ vọng về vòng đời của nó (khi nào được tạo/xóa) để khớp với triển khai thực tế.
4. Nếu hành vi phục hồi dùng cơ chế khác với việc reset `consecutive_failures` về `0`, hãy điều chỉnh các assert cuối cùng cho phù hợp.
</issue_to_address>

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

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

  • In preflight.sh the default DISK_PATH is hardcoded to /Users/andy, which makes the disk gate non-portable; consider defaulting to $HOME or a more generic path so the check behaves correctly across different user environments.
  • In launchd_safe_wrapper.sh the fallback SCRIPT_PATH defaults to $HOME/workbench/daily_dnr_run.py, which looks repo/user-specific; it may be more robust to default to the tracked tools/runtime/daily_dnr_run.py or require the path be passed explicitly.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `preflight.sh` the default `DISK_PATH` is hardcoded to `/Users/andy`, which makes the disk gate non-portable; consider defaulting to `$HOME` or a more generic path so the check behaves correctly across different user environments.
- In `launchd_safe_wrapper.sh` the fallback `SCRIPT_PATH` defaults to `$HOME/workbench/daily_dnr_run.py`, which looks repo/user-specific; it may be more robust to default to the tracked `tools/runtime/daily_dnr_run.py` or require the path be passed explicitly.

## Individual Comments

### Comment 1
<location> `tools/runtime/daily_dnr_run.py:131-148` </location>
<code_context>
+
+
+
+def run_preflight_gate() -> int:
+    if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
+        return 0
+
+    try:
+        result = subprocess.run(
+            ["./tools/runtime/preflight.sh", "--summary"],
+            capture_output=True,
+            text=True,
+            check=False,
+        )
+        if result.stdout:
+            print(result.stdout.strip())
+        if result.stderr:
+            print(result.stderr.strip())
+        return int(result.returncode)
+    except Exception:
+        return 1
+
</code_context>

<issue_to_address>
**suggestion:** Consider logging when preflight invocation itself fails instead of silently returning 1.

Right now any exception from `subprocess.run` (missing script, permissions, etc.) is mapped to exit code `1` with no context, making infra failures indistinguishable from a real WARN. Please log the exception or a short error message before returning so callers can differentiate preflight failures from runtime/environment issues when interpreting the exit code.

```suggestion
def run_preflight_gate() -> int:
    if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
        return 0

    try:
        result = subprocess.run(
            ["./tools/runtime/preflight.sh", "--summary"],
            capture_output=True,
            text=True,
            check=False,
        )
        if result.stdout:
            print(result.stdout.strip())
        if result.stderr:
            print(result.stderr.strip())
        return int(result.returncode)
    except Exception:
        logging.exception("Preflight gate invocation failed (unable to run preflight.sh)")
        return 1
```
</issue_to_address>

### Comment 2
<location> `tools/runtime/runtime_health_daemon.py:36-37` </location>
<code_context>
+        handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
+
+
+def run_preflight() -> int:
+    result = subprocess.run(["./tools/runtime/preflight.sh", "--summary"], capture_output=True, text=True)
+    if result.stdout:
+        print(result.stdout.strip())
</code_context>

<issue_to_address>
**issue (bug_risk):** Using a relative path for `preflight.sh` makes the daemon sensitive to the working directory.

`subprocess.run([
</issue_to_address>

### Comment 3
<location> `tools/runtime/preflight.sh:5` </location>
<code_context>
+set -euo pipefail
+
+MIN_FREE_GB="${MIN_FREE_GB:-15}"
+DISK_PATH="${DISK_PATH:-/Users/andy}"
+DB_PATH="${DB_PATH:-$HOME/.hyperai/db/memory.sqlite}"
+LOG_DIR="${LOG_DIR:-$HOME/.hyperai/logs}"
</code_context>

<issue_to_address>
**suggestion (bug_risk):** The default `DISK_PATH` is user-specific and may not work on other machines.

Consider defaulting to a more generic path (e.g., `${DISK_PATH:-$HOME}` or similar) so the preflight remains portable while still allowing environment overrides.

```suggestion
DISK_PATH="${DISK_PATH:-$HOME}"
```
</issue_to_address>

### Comment 4
<location> `tools/runtime/launchd_safe_wrapper.sh:4` </location>
<code_context>
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_PATH="${1:-${ORIG:-$HOME/workbench/daily_dnr_run.py}}"
+if [[ $# -gt 0 ]]; then
+  shift
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Default `SCRIPT_PATH` points to a likely local-only path, which may be brittle.

Because `$HOME/workbench/daily_dnr_run.py` is environment-specific, when `ORIG` is unset and no positional argument is provided this will likely break in most environments. Consider defaulting to a path within the repo (e.g., `./tools/runtime/daily_dnr_run.py` resolved relative to the wrapper) so the script has a portable, predictable default.

```suggestion
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
SCRIPT_PATH="${1:-${ORIG:-"$SCRIPT_DIR/daily_dnr_run.py"}}"
```
</issue_to_address>

### Comment 5
<location> `tests/runtime/test_runtime_tools.py:22-31` </location>
<code_context>
+    def test_daily_dnr_idempotent_same_day(self):
</code_context>

<issue_to_address>
**suggestion (testing):** Add DNR tests for missing DB, lock contention, and SQLite error paths

To fully exercise `daily_dnr_run.py`’s exit contract, please add tests that:
- Cover a missing DB path and assert WARN (exit 1) plus the warning log.
- Simulate lock contention (pre-hold the lock file) and assert the `RuntimeError` path also yields WARN (exit 1).
- Trigger a `sqlite3.Error` (e.g., bad DB file or permissions) and assert FAIL (exit 2).
This will ensure all documented branches in `main()` are verified by tests.

Suggested implementation:

```python
DAEMON = ROOT / "tools/runtime/runtime_health_daemon.py"
DAILY_DNR = ROOT / "tools/runtime/daily_dnr_run.py"

```

```python
    def test_preflight_fail_on_invalid_disk_path(self):
        env = os.environ.copy()
        env["DISK_PATH"] = "/path/does/not/exist"
        result = subprocess.run([str(PREFLIGHT), "--summary"], cwd=ROOT, env=env, capture_output=True, text=True)
        self.assertEqual(result.returncode, 2)

    def test_daily_dnr_idempotent_same_day(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "memory.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"
            db.parent.mkdir(parents=True, exist_ok=True)
            sqlite3.connect(db).close()

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            # First run should succeed and create the marker/lock state
            result1 = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result1.returncode, 0)

            # Second run on the same day should be idempotent and still succeed
            result2 = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result2.returncode, 0)

    def test_daily_dnr_warns_on_missing_db(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "missing.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            result = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )

            # WARN: Missing DB should exit 1 and emit a warning on stderr
            self.assertEqual(result.returncode, 1)
            self.assertTrue(result.stderr, "Expected warning output when DB path is missing")

    def test_daily_dnr_warns_on_lock_contention(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "memory.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"
            db.parent.mkdir(parents=True, exist_ok=True)
            sqlite3.connect(db).close()

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            # Pre-hold the lock file to simulate another process owning it
            lock_file.parent.mkdir(parents=True, exist_ok=True)
            with open(lock_file, "w") as fh:
                try:
                    import fcntl

                    fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
                except (ImportError, OSError):
                    # If flock is not available or locking fails for platform reasons,
                    # still keep the file present to exercise the lock contention path
                    pass

                result = subprocess.run(
                    [sys.executable, str(DAILY_DNR)],
                    cwd=ROOT,
                    env=env,
                    capture_output=True,
                    text=True,
                )

            # WARN: lock contention is treated as RuntimeError -> exit 1
            self.assertEqual(result.returncode, 1)
            self.assertTrue(result.stderr, "Expected warning output when lock contention occurs")

    def test_daily_dnr_fails_on_sqlite_error(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            # Point DB at a directory to provoke a sqlite3.Error when connecting
            db = td_path / "not_a_file.sqlite"
            db.mkdir(parents=True, exist_ok=True)

            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            result = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )

            # FAIL: sqlite3.Error paths should exit 2 and log an error
            self.assertEqual(result.returncode, 2)
            self.assertTrue(result.stderr, "Expected error output when sqlite3.Error is raised")

```

1. Ensure `DAILY_DNR` is the correct path constant for `daily_dnr_run.py`; if a different constant already exists in this file (e.g., `DAILY_DNR_RUN`), reuse it instead of introducing a new one.
2. Align the environment variable names (`DAILY_DNR_DB_PATH`, `DAILY_DNR_LOG_DIR`, `DAILY_DNR_MARKER_DIR`, `DAILY_DNR_LOCK_FILE`) with what `daily_dnr_run.main()` actually reads; adjust the keys in all four tests accordingly.
3. If `daily_dnr_run.py` is invoked directly as an executable script (shebang + `chmod +x`), and other tests call it without `sys.executable`, update the `subprocess.run` invocations to match the existing convention.
4. If the warning/error messages are known and stable, strengthen the `stderr` assertions to check for specific substrings (e.g., "WARN" or the concrete log message) rather than only non-empty output.
</issue_to_address>

### Comment 6
<location> `tests/runtime/test_runtime_tools.py:53-62` </location>
<code_context>
+    def test_health_daemon_writes_trend(self):
</code_context>

<issue_to_address>
**suggestion (testing):** Extend health daemon tests to validate event contents, thresholds, and recovery behavior

The current test only asserts that a single FAIL cycle produces `runtime_health_trend.json` and the unhealthy marker. To better exercise the daemon’s behavior, consider:
- Asserting that the JSON trend entry includes the expected fields (`exit_code`, `state`, `consecutive_failures`, and optionally `event == 'state_changed'`).
- Adding a multi-cycle test with `max-cycles > 1` to verify that `threshold` is honored (e.g., threshold=2 only marks unhealthy after 2 consecutive FAILs).
- Adding a recovery test where a FAIL is followed by a non-FAIL cycle, asserting that `consecutive_failures` resets and any existing `system_unhealthy.marker` is removed.
This would more fully validate the long-running watchdog semantics.

Suggested implementation:

```python
import os
import json
import subprocess
import tempfile
from pathlib import Path

```

```python
    def test_health_daemon_writes_trend(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            # Force the daemon into a failing state so we exercise the
            # unhealthy path and trend writing.
            env = os.environ.copy()
            env["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "1",
                "--threshold",
                "1",
            ]

            result = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            # Validate that at least one event was written and that it contains
            # the core fields we expect for watchdog semantics.
            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            self.assertGreaterEqual(len(events), 1)
            last = events[-1]

            self.assertIn("exit_code", last)
            self.assertIn("state", last)
            self.assertIn("consecutive_failures", last)
            if "event" in last:
                self.assertEqual(last["event"], "state_changed")

            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

    def test_health_daemon_honors_failure_threshold(self):
        """Verify that threshold > 1 only marks unhealthy after enough consecutive failures."""
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            env = os.environ.copy()
            env["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "3",
                "--threshold",
                "2",
            ]

            result = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            # We expect multiple cycles to have been recorded.
            self.assertGreaterEqual(len(events), 2)

            # Find the last event for the failing probe and assert that the
            # consecutive failure count reached at least the threshold.
            last = events[-1]
            self.assertIn("consecutive_failures", last)
            self.assertGreaterEqual(last["consecutive_failures"], 2)

            # Once threshold is reached, the system must be marked unhealthy.
            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

    def test_health_daemon_recovers_and_resets_failures(self):
        """Verify that a recovery cycle resets consecutive_failures and clears the unhealthy marker."""
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            # First run: force failures so we cross the threshold.
            env_fail = os.environ.copy()
            env_fail["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "3",
                "--threshold",
                "2",
            ]

            result_fail = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env_fail,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result_fail.returncode, 0, msg=result_fail.stderr)

            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

            # Second run: allow the daemon to succeed so it can recover.
            env_ok = os.environ.copy()
            # Do not override DISK_PATH (or set it to a valid path) so the probe passes.

            result_ok = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env_ok,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result_ok.returncode, 0, msg=result_ok.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            self.assertGreaterEqual(len(events), 1)
            last = events[-1]

            # Recovery should reset the failure counter.
            self.assertIn("consecutive_failures", last)
            self.assertEqual(last["consecutive_failures"], 0)

            # Recovery should also clear any unhealthy marker.
            self.assertFalse(marker_path.exists())

```

The commands and JSON field names in these tests assume the daemon supports the following CLI options and event schema:

- CLI flags: `--state-dir`, `--log-file`, `--max-cycles`, `--threshold`.
- JSON event fields: at least `exit_code`, `state`, `consecutive_failures`, and optionally `event == "state_changed"` on state transitions.
- A marker file named `system_unhealthy.marker` created/removed under `state_dir`.

If the actual CLI or schema differ, you should:
1. Adjust the `cmd` array flags/values to match the real arguments.
2. Update the asserted JSON keys (`exit_code`, `state`, `consecutive_failures`, `event`) to the actual field names used by your daemon.
3. Update the marker filename (`system_unhealthy.marker`) and its lifecycle expectations (when it is created/removed) to match the real implementation.
4. If the recovery behavior uses a different mechanism than resetting `consecutive_failures` to `0`, adapt the final assertions 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 +131 to +148
def run_preflight_gate() -> int:
if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
return 0

try:
result = subprocess.run(
["./tools/runtime/preflight.sh", "--summary"],
capture_output=True,
text=True,
check=False,
)
if result.stdout:
print(result.stdout.strip())
if result.stderr:
print(result.stderr.strip())
return int(result.returncode)
except Exception:
return 1
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: Hãy cân nhắc log khi chính việc gọi preflight bị lỗi thay vì âm thầm trả về 1.

Hiện tại mọi ngoại lệ từ subprocess.run (thiếu script, quyền truy cập, v.v.) đều được ánh xạ thành mã thoát 1 mà không có ngữ cảnh, khiến lỗi hạ tầng không phân biệt được với một WARN thực sự. Vui lòng log ngoại lệ hoặc một thông báo lỗi ngắn trước khi trả về để bên gọi có thể phân biệt lỗi preflight với lỗi runtime/môi trường khi diễn giải mã thoát.

Suggested change
def run_preflight_gate() -> int:
if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
return 0
try:
result = subprocess.run(
["./tools/runtime/preflight.sh", "--summary"],
capture_output=True,
text=True,
check=False,
)
if result.stdout:
print(result.stdout.strip())
if result.stderr:
print(result.stderr.strip())
return int(result.returncode)
except Exception:
return 1
def run_preflight_gate() -> int:
if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
return 0
try:
result = subprocess.run(
["./tools/runtime/preflight.sh", "--summary"],
capture_output=True,
text=True,
check=False,
)
if result.stdout:
print(result.stdout.strip())
if result.stderr:
print(result.stderr.strip())
return int(result.returncode)
except Exception:
logging.exception("Preflight gate invocation failed (unable to run preflight.sh)")
return 1
Original comment in English

suggestion: Consider logging when preflight invocation itself fails instead of silently returning 1.

Right now any exception from subprocess.run (missing script, permissions, etc.) is mapped to exit code 1 with no context, making infra failures indistinguishable from a real WARN. Please log the exception or a short error message before returning so callers can differentiate preflight failures from runtime/environment issues when interpreting the exit code.

Suggested change
def run_preflight_gate() -> int:
if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
return 0
try:
result = subprocess.run(
["./tools/runtime/preflight.sh", "--summary"],
capture_output=True,
text=True,
check=False,
)
if result.stdout:
print(result.stdout.strip())
if result.stderr:
print(result.stderr.strip())
return int(result.returncode)
except Exception:
return 1
def run_preflight_gate() -> int:
if os.environ.get("SKIP_PREFLIGHT", "0") == "1":
return 0
try:
result = subprocess.run(
["./tools/runtime/preflight.sh", "--summary"],
capture_output=True,
text=True,
check=False,
)
if result.stdout:
print(result.stdout.strip())
if result.stderr:
print(result.stderr.strip())
return int(result.returncode)
except Exception:
logging.exception("Preflight gate invocation failed (unable to run preflight.sh)")
return 1

Comment on lines +36 to +37
def run_preflight() -> int:
result = subprocess.run(["./tools/runtime/preflight.sh", "--summary"], capture_output=True, text=True)
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): Việc dùng đường dẫn tương đối cho preflight.sh khiến daemon phụ thuộc vào thư mục làm việc hiện tại.

`subprocess.run([

Original comment in English

issue (bug_risk): Using a relative path for preflight.sh makes the daemon sensitive to the working directory.

`subprocess.run([

set -euo pipefail

MIN_FREE_GB="${MIN_FREE_GB:-15}"
DISK_PATH="${DISK_PATH:-/Users/andy}"
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): Giá trị mặc định của DISK_PATH gắn với người dùng cụ thể và có thể không chạy được trên các máy khác.

Hãy cân nhắc đặt mặc định thành một đường dẫn tổng quát hơn (ví dụ ${DISK_PATH:-$HOME} hoặc tương tự) để preflight có thể dùng lại được, đồng thời vẫn cho phép override qua biến môi trường.

Suggested change
DISK_PATH="${DISK_PATH:-/Users/andy}"
DISK_PATH="${DISK_PATH:-$HOME}"
Original comment in English

suggestion (bug_risk): The default DISK_PATH is user-specific and may not work on other machines.

Consider defaulting to a more generic path (e.g., ${DISK_PATH:-$HOME} or similar) so the preflight remains portable while still allowing environment overrides.

Suggested change
DISK_PATH="${DISK_PATH:-/Users/andy}"
DISK_PATH="${DISK_PATH:-$HOME}"

#!/usr/bin/env bash
set -euo pipefail

SCRIPT_PATH="${1:-${ORIG:-$HOME/workbench/daily_dnr_run.py}}"
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (bug_risk): Giá trị mặc định của SCRIPT_PATH trỏ tới một đường dẫn gần như chỉ tồn tại cục bộ, có thể không ổn định.

$HOME/workbench/daily_dnr_run.py phụ thuộc vào môi trường, nên khi ORIG không được set và không truyền tham số vị trí nào, script này rất có thể sẽ lỗi trong hầu hết môi trường. Hãy cân nhắc đặt mặc định thành một đường dẫn bên trong repo (ví dụ ./tools/runtime/daily_dnr_run.py được resolve tương đối so với wrapper) để script có một giá trị mặc định có thể dùng lại và có thể dự đoán được.

Suggested change
SCRIPT_PATH="${1:-${ORIG:-$HOME/workbench/daily_dnr_run.py}}"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
SCRIPT_PATH="${1:-${ORIG:-"$SCRIPT_DIR/daily_dnr_run.py"}}"
Original comment in English

suggestion (bug_risk): Default SCRIPT_PATH points to a likely local-only path, which may be brittle.

Because $HOME/workbench/daily_dnr_run.py is environment-specific, when ORIG is unset and no positional argument is provided this will likely break in most environments. Consider defaulting to a path within the repo (e.g., ./tools/runtime/daily_dnr_run.py resolved relative to the wrapper) so the script has a portable, predictable default.

Suggested change
SCRIPT_PATH="${1:-${ORIG:-$HOME/workbench/daily_dnr_run.py}}"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
SCRIPT_PATH="${1:-${ORIG:-"$SCRIPT_DIR/daily_dnr_run.py"}}"

Comment on lines +22 to +31
def test_daily_dnr_idempotent_same_day(self):
with tempfile.TemporaryDirectory() as td:
td_path = Path(td)
db = td_path / "memory.sqlite"
log_dir = td_path / "logs"
marker_dir = td_path / "state/dnr"
lock_file = td_path / "state/dnr.lock"
db.parent.mkdir(parents=True, exist_ok=True)
sqlite3.connect(db).close()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (testing): Thêm các bài test DNR cho trường hợp thiếu DB, tranh chấp lock, và các nhánh lỗi SQLite

Để kiểm thử đầy đủ hợp đồng mã thoát của daily_dnr_run.py, vui lòng thêm các bài test:

  • Bao phủ trường hợp thiếu đường dẫn DB và assert WARN (thoát 1) cùng log cảnh báo.
  • Mô phỏng tranh chấp lock (giữ trước file lock) và assert nhánh RuntimeError cũng cho kết quả WARN (thoát 1).
  • Gây ra sqlite3.Error (ví dụ file DB hỏng hoặc lỗi quyền) và assert FAIL (thoát 2).
    Điều này đảm bảo tất cả các nhánh được mô tả trong main() đều được kiểm chứng bằng test.

Gợi ý triển khai:

DAEMON = ROOT / "tools/runtime/runtime_health_daemon.py"
DAILY_DNR = ROOT / "tools/runtime/daily_dnr_run.py"
    def test_preflight_fail_on_invalid_disk_path(self):
        env = os.environ.copy()
        env["DISK_PATH"] = "/path/does/not/exist"
        result = subprocess.run([str(PREFLIGHT), "--summary"], cwd=ROOT, env=env, capture_output=True, text=True)
        self.assertEqual(result.returncode, 2)

    def test_daily_dnr_idempotent_same_day(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "memory.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"
            db.parent.mkdir(parents=True, exist_ok=True)
            sqlite3.connect(db).close()

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            # First run should succeed and create the marker/lock state
            result1 = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result1.returncode, 0)

            # Second run on the same day should be idempotent and still succeed
            result2 = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result2.returncode, 0)

    def test_daily_dnr_warns_on_missing_db(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "missing.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            result = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )

            # WARN: Missing DB should exit 1 and emit a warning on stderr
            self.assertEqual(result.returncode, 1)
            self.assertTrue(result.stderr, "Expected warning output when DB path is missing")

    def test_daily_dnr_warns_on_lock_contention(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "memory.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"
            db.parent.mkdir(parents=True, exist_ok=True)
            sqlite3.connect(db).close()

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            # Pre-hold the lock file to simulate another process owning it
            lock_file.parent.mkdir(parents=True, exist_ok=True)
            with open(lock_file, "w") as fh:
                try:
                    import fcntl

                    fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
                except (ImportError, OSError):
                    # If flock is not available or locking fails for platform reasons,
                    # still keep the file present to exercise the lock contention path
                    pass

                result = subprocess.run(
                    [sys.executable, str(DAILY_DNR)],
                    cwd=ROOT,
                    env=env,
                    capture_output=True,
                    text=True,
                )

            # WARN: lock contention is treated as RuntimeError -> exit 1
            self.assertEqual(result.returncode, 1)
            self.assertTrue(result.stderr, "Expected warning output when lock contention occurs")

    def test_daily_dnr_fails_on_sqlite_error(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            # Point DB at a directory to provoke a sqlite3.Error when connecting
            db = td_path / "not_a_file.sqlite"
            db.mkdir(parents=True, exist_ok=True)

            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            result = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )

            # FAIL: sqlite3.Error paths should exit 2 and log an error
            self.assertEqual(result.returncode, 2)
            self.assertTrue(result.stderr, "Expected error output when sqlite3.Error is raised")
  1. Đảm bảo DAILY_DNR là hằng đường dẫn đúng cho daily_dnr_run.py; nếu file này đã có một hằng khác (ví dụ DAILY_DNR_RUN), hãy tái sử dụng thay vì tạo hằng mới.
  2. Đồng bộ tên các biến môi trường (DAILY_DNR_DB_PATH, DAILY_DNR_LOG_DIR, DAILY_DNR_MARKER_DIR, DAILY_DNR_LOCK_FILE) với những gì daily_dnr_run.main() thực sự đọc; cập nhật các key trong cả bốn bài test cho phù hợp.
  3. Nếu daily_dnr_run.py được gọi trực tiếp như một script thực thi (shebang + chmod +x), và các test khác gọi nó mà không qua sys.executable, hãy cập nhật các lệnh subprocess.run cho phù hợp với convention hiện tại.
  4. Nếu thông báo cảnh báo/lỗi đã biết và ổn định, hãy tăng độ chặt cho các assert trên stderr bằng cách kiểm tra các substring cụ thể (ví dụ "WARN" hoặc thông điệp log cụ thể) thay vì chỉ kiểm tra là có output.
Original comment in English

suggestion (testing): Add DNR tests for missing DB, lock contention, and SQLite error paths

To fully exercise daily_dnr_run.py’s exit contract, please add tests that:

  • Cover a missing DB path and assert WARN (exit 1) plus the warning log.
  • Simulate lock contention (pre-hold the lock file) and assert the RuntimeError path also yields WARN (exit 1).
  • Trigger a sqlite3.Error (e.g., bad DB file or permissions) and assert FAIL (exit 2).
    This will ensure all documented branches in main() are verified by tests.

Suggested implementation:

DAEMON = ROOT / "tools/runtime/runtime_health_daemon.py"
DAILY_DNR = ROOT / "tools/runtime/daily_dnr_run.py"
    def test_preflight_fail_on_invalid_disk_path(self):
        env = os.environ.copy()
        env["DISK_PATH"] = "/path/does/not/exist"
        result = subprocess.run([str(PREFLIGHT), "--summary"], cwd=ROOT, env=env, capture_output=True, text=True)
        self.assertEqual(result.returncode, 2)

    def test_daily_dnr_idempotent_same_day(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "memory.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"
            db.parent.mkdir(parents=True, exist_ok=True)
            sqlite3.connect(db).close()

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            # First run should succeed and create the marker/lock state
            result1 = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result1.returncode, 0)

            # Second run on the same day should be idempotent and still succeed
            result2 = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result2.returncode, 0)

    def test_daily_dnr_warns_on_missing_db(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "missing.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            result = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )

            # WARN: Missing DB should exit 1 and emit a warning on stderr
            self.assertEqual(result.returncode, 1)
            self.assertTrue(result.stderr, "Expected warning output when DB path is missing")

    def test_daily_dnr_warns_on_lock_contention(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            db = td_path / "memory.sqlite"
            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"
            db.parent.mkdir(parents=True, exist_ok=True)
            sqlite3.connect(db).close()

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            # Pre-hold the lock file to simulate another process owning it
            lock_file.parent.mkdir(parents=True, exist_ok=True)
            with open(lock_file, "w") as fh:
                try:
                    import fcntl

                    fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
                except (ImportError, OSError):
                    # If flock is not available or locking fails for platform reasons,
                    # still keep the file present to exercise the lock contention path
                    pass

                result = subprocess.run(
                    [sys.executable, str(DAILY_DNR)],
                    cwd=ROOT,
                    env=env,
                    capture_output=True,
                    text=True,
                )

            # WARN: lock contention is treated as RuntimeError -> exit 1
            self.assertEqual(result.returncode, 1)
            self.assertTrue(result.stderr, "Expected warning output when lock contention occurs")

    def test_daily_dnr_fails_on_sqlite_error(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            # Point DB at a directory to provoke a sqlite3.Error when connecting
            db = td_path / "not_a_file.sqlite"
            db.mkdir(parents=True, exist_ok=True)

            log_dir = td_path / "logs"
            marker_dir = td_path / "state/dnr"
            lock_file = td_path / "state/dnr.lock"

            env = os.environ.copy()
            env["DAILY_DNR_DB_PATH"] = str(db)
            env["DAILY_DNR_LOG_DIR"] = str(log_dir)
            env["DAILY_DNR_MARKER_DIR"] = str(marker_dir)
            env["DAILY_DNR_LOCK_FILE"] = str(lock_file)

            result = subprocess.run(
                [sys.executable, str(DAILY_DNR)],
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )

            # FAIL: sqlite3.Error paths should exit 2 and log an error
            self.assertEqual(result.returncode, 2)
            self.assertTrue(result.stderr, "Expected error output when sqlite3.Error is raised")
  1. Ensure DAILY_DNR is the correct path constant for daily_dnr_run.py; if a different constant already exists in this file (e.g., DAILY_DNR_RUN), reuse it instead of introducing a new one.
  2. Align the environment variable names (DAILY_DNR_DB_PATH, DAILY_DNR_LOG_DIR, DAILY_DNR_MARKER_DIR, DAILY_DNR_LOCK_FILE) with what daily_dnr_run.main() actually reads; adjust the keys in all four tests accordingly.
  3. If daily_dnr_run.py is invoked directly as an executable script (shebang + chmod +x), and other tests call it without sys.executable, update the subprocess.run invocations to match the existing convention.
  4. If the warning/error messages are known and stable, strengthen the stderr assertions to check for specific substrings (e.g., "WARN" or the concrete log message) rather than only non-empty output.

Comment on lines +53 to +62
def test_health_daemon_writes_trend(self):
with tempfile.TemporaryDirectory() as td:
td_path = Path(td)
state_dir = td_path / "state"
log_file = td_path / "logs/daemon.log"
env = os.environ.copy()
env["DISK_PATH"] = "/path/does/not/exist"

cmd = [
"python3",
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (testing): Mở rộng các test cho health daemon để kiểm tra nội dung sự kiện, ngưỡng và hành vi phục hồi

Bài test hiện tại chỉ assert rằng một chu kỳ FAIL đơn lẻ tạo ra runtime_health_trend.json và marker unhealthy. Để kiểm thử hành vi của daemon tốt hơn, hãy cân nhắc:

  • Assert rằng entry JSON trong trend chứa các trường mong đợi (exit_code, state, consecutive_failures, và tùy chọn event == 'state_changed').
  • Thêm một bài test đa chu kỳ với max-cycles > 1 để xác minh threshold được tôn trọng (ví dụ threshold=2 chỉ đánh dấu unhealthy sau 2 FAIL liên tiếp).
  • Thêm một bài test phục hồi, trong đó một chu kỳ FAIL được theo sau bởi một chu kỳ không FAIL, assert rằng consecutive_failures được reset và bất kỳ system_unhealthy.marker hiện có nào được xóa.
    Điều này sẽ giúp kiểm chứng đầy đủ ngữ nghĩa watchdog chạy lâu dài.

Gợi ý triển khai:

import os
import json
import subprocess
import tempfile
from pathlib import Path
    def test_health_daemon_writes_trend(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            # Force the daemon into a failing state so we exercise the
            # unhealthy path and trend writing.
            env = os.environ.copy()
            env["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "1",
                "--threshold",
                "1",
            ]

            result = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            # Validate that at least one event was written and that it contains
            # the core fields we expect for watchdog semantics.
            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            self.assertGreaterEqual(len(events), 1)
            last = events[-1]

            self.assertIn("exit_code", last)
            self.assertIn("state", last)
            self.assertIn("consecutive_failures", last)
            if "event" in last:
                self.assertEqual(last["event"], "state_changed")

            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

    def test_health_daemon_honors_failure_threshold(self):
        """Verify that threshold > 1 only marks unhealthy after enough consecutive failures."""
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            env = os.environ.copy()
            env["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "3",
                "--threshold",
                "2",
            ]

            result = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            # We expect multiple cycles to have been recorded.
            self.assertGreaterEqual(len(events), 2)

            # Find the last event for the failing probe and assert that the
            # consecutive failure count reached at least the threshold.
            last = events[-1]
            self.assertIn("consecutive_failures", last)
            self.assertGreaterEqual(last["consecutive_failures"], 2)

            # Once threshold is reached, the system must be marked unhealthy.
            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

    def test_health_daemon_recovers_and_resets_failures(self):
        """Verify that a recovery cycle resets consecutive_failures and clears the unhealthy marker."""
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            # First run: force failures so we cross the threshold.
            env_fail = os.environ.copy()
            env_fail["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "3",
                "--threshold",
                "2",
            ]

            result_fail = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env_fail,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result_fail.returncode, 0, msg=result_fail.stderr)

            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

            # Second run: allow the daemon to succeed so it can recover.
            env_ok = os.environ.copy()
            # Do not override DISK_PATH (or set it to a valid path) so the probe passes.

            result_ok = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env_ok,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result_ok.returncode, 0, msg=result_ok.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            self.assertGreaterEqual(len(events), 1)
            last = events[-1]

            # Recovery should reset the failure counter.
            self.assertIn("consecutive_failures", last)
            self.assertEqual(last["consecutive_failures"], 0)

            # Recovery should also clear any unhealthy marker.
            self.assertFalse(marker_path.exists())

Các lệnh và tên trường JSON trong các bài test này giả định daemon hỗ trợ các tùy chọn CLI và schema sự kiện sau:

  • Cờ CLI: --state-dir, --log-file, --max-cycles, --threshold.
  • Các trường sự kiện JSON: ít nhất exit_code, state, consecutive_failures, và tùy chọn event == "state_changed" khi chuyển trạng thái.
  • Một file marker tên system_unhealthy.marker được tạo/xóa dưới state_dir.

Nếu CLI hoặc schema thực tế khác, bạn nên:

  1. Điều chỉnh mảng cmd (các cờ/giá trị) cho khớp với các tham số thật.
  2. Cập nhật các key JSON được assert (exit_code, state, consecutive_failures, event) thành các tên trường thật sự mà daemon sử dụng.
  3. Cập nhật tên file marker (system_unhealthy.marker) và kỳ vọng về vòng đời của nó (khi nào được tạo/xóa) để khớp với triển khai thực tế.
  4. Nếu hành vi phục hồi dùng cơ chế khác với việc reset consecutive_failures về 0, hãy điều chỉnh các assert cuối cùng cho phù hợp.
Original comment in English

suggestion (testing): Extend health daemon tests to validate event contents, thresholds, and recovery behavior

The current test only asserts that a single FAIL cycle produces runtime_health_trend.json and the unhealthy marker. To better exercise the daemon’s behavior, consider:

  • Asserting that the JSON trend entry includes the expected fields (exit_code, state, consecutive_failures, and optionally event == 'state_changed').
  • Adding a multi-cycle test with max-cycles > 1 to verify that threshold is honored (e.g., threshold=2 only marks unhealthy after 2 consecutive FAILs).
  • Adding a recovery test where a FAIL is followed by a non-FAIL cycle, asserting that consecutive_failures resets and any existing system_unhealthy.marker is removed.
    This would more fully validate the long-running watchdog semantics.

Suggested implementation:

import os
import json
import subprocess
import tempfile
from pathlib import Path
    def test_health_daemon_writes_trend(self):
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            # Force the daemon into a failing state so we exercise the
            # unhealthy path and trend writing.
            env = os.environ.copy()
            env["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "1",
                "--threshold",
                "1",
            ]

            result = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            # Validate that at least one event was written and that it contains
            # the core fields we expect for watchdog semantics.
            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            self.assertGreaterEqual(len(events), 1)
            last = events[-1]

            self.assertIn("exit_code", last)
            self.assertIn("state", last)
            self.assertIn("consecutive_failures", last)
            if "event" in last:
                self.assertEqual(last["event"], "state_changed")

            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

    def test_health_daemon_honors_failure_threshold(self):
        """Verify that threshold > 1 only marks unhealthy after enough consecutive failures."""
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            env = os.environ.copy()
            env["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "3",
                "--threshold",
                "2",
            ]

            result = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            # We expect multiple cycles to have been recorded.
            self.assertGreaterEqual(len(events), 2)

            # Find the last event for the failing probe and assert that the
            # consecutive failure count reached at least the threshold.
            last = events[-1]
            self.assertIn("consecutive_failures", last)
            self.assertGreaterEqual(last["consecutive_failures"], 2)

            # Once threshold is reached, the system must be marked unhealthy.
            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

    def test_health_daemon_recovers_and_resets_failures(self):
        """Verify that a recovery cycle resets consecutive_failures and clears the unhealthy marker."""
        with tempfile.TemporaryDirectory() as td:
            td_path = Path(td)
            state_dir = td_path / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            log_dir = td_path / "logs"
            log_dir.mkdir(parents=True, exist_ok=True)
            log_file = log_dir / "daemon.log"

            # First run: force failures so we cross the threshold.
            env_fail = os.environ.copy()
            env_fail["DISK_PATH"] = "/path/does/not/exist"

            cmd = [
                "python3",
                str(DAEMON),
                "--state-dir",
                str(state_dir),
                "--log-file",
                str(log_file),
                "--max-cycles",
                "3",
                "--threshold",
                "2",
            ]

            result_fail = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env_fail,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result_fail.returncode, 0, msg=result_fail.stderr)

            marker_path = state_dir / "system_unhealthy.marker"
            self.assertTrue(marker_path.exists())

            # Second run: allow the daemon to succeed so it can recover.
            env_ok = os.environ.copy()
            # Do not override DISK_PATH (or set it to a valid path) so the probe passes.

            result_ok = subprocess.run(
                cmd,
                cwd=ROOT,
                env=env_ok,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result_ok.returncode, 0, msg=result_ok.stderr)

            trend_path = state_dir / "runtime_health_trend.json"
            self.assertTrue(trend_path.exists())

            with trend_path.open() as f:
                events = [json.loads(line) for line in f if line.strip()]

            self.assertGreaterEqual(len(events), 1)
            last = events[-1]

            # Recovery should reset the failure counter.
            self.assertIn("consecutive_failures", last)
            self.assertEqual(last["consecutive_failures"], 0)

            # Recovery should also clear any unhealthy marker.
            self.assertFalse(marker_path.exists())

The commands and JSON field names in these tests assume the daemon supports the following CLI options and event schema:

  • CLI flags: --state-dir, --log-file, --max-cycles, --threshold.
  • JSON event fields: at least exit_code, state, consecutive_failures, and optionally event == "state_changed" on state transitions.
  • A marker file named system_unhealthy.marker created/removed under state_dir.

If the actual CLI or schema differ, you should:

  1. Adjust the cmd array flags/values to match the real arguments.
  2. Update the asserted JSON keys (exit_code, state, consecutive_failures, event) to the actual field names used by your daemon.
  3. Update the marker filename (system_unhealthy.marker) and its lifecycle expectations (when it is created/removed) to match the real implementation.
  4. If the recovery behavior uses a different mechanism than resetting consecutive_failures to 0, adapt the final assertions accordingly.

@NguyenCuong1989 NguyenCuong1989 self-assigned this Feb 13, 2026
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.

1 participant