Skip to content

Add system monitoring and persistent alert management to daemon#685

Draft
Copilot wants to merge 11 commits intomainfrom
copilot/add-system-monitoring-alert-management
Draft

Add system monitoring and persistent alert management to daemon#685
Copilot wants to merge 11 commits intomainfrom
copilot/add-system-monitoring-alert-management

Conversation

Copy link

Copilot AI commented Jan 26, 2026

The daemon lacked ability to monitor system health and manage alerts persistently. This adds monitoring for memory, disk space, and failed systemd services with SQLite-backed alert storage.

Implementation

New cx-daemon binary

  • Monitors memory (/proc/meminfo), disk (statvfs), and systemd services
  • Generates alerts when configurable thresholds exceeded
  • Periodic checks in background thread (default 5min, configurable)
  • Unix socket IPC at $XDG_RUNTIME_DIR/cx/daemon.sock or ~/.cx/daemon.sock

Alert database (alerts.rs)

  • SQLite storage at ~/.cx/alerts.db
  • Alert states: activeacknowledgeddismissed
  • Severity levels: info, warning, error, critical
  • Filtering by status/severity with prepared statements

IPC handlers (ipc.rs)

  • JSON protocol over Unix socket
  • Endpoints: Health, Status, Alerts, AcknowledgeAlert, DismissAlert, AcknowledgeAllAlerts

CLI commands

cx daemon status [-v]              # daemon info, optional health details
cx daemon health                   # memory/disk/services metrics
cx daemon alerts                   # list all alerts
cx daemon alerts --status active   # filter by status
cx daemon alerts --acknowledge-all # bulk acknowledge
cx daemon alerts --dismiss <uuid>  # dismiss specific alert

Shared path module (paths.rs)

  • Consistent socket/database path resolution between daemon and CLI
  • Prevents path mismatch issues

Example

$ cx daemon health
System Health
  Memory Usage: 12.5%
  Disk Usage: 81.9%
  Uptime: 165 seconds
  Failed Services: none

$ cx daemon alerts
Alerts (2)

ID: d8520c2e-146d-4d94-8831-2296f1f9753d
  Severity: warning
  Source: disk_monitor
  Title: Low Disk Space
  Description: Disk usage is at 81.9% (warning threshold: 50.0%)
  Status: active

Security

  • Database/socket in user-scoped directories with appropriate permissions
  • Parameterized SQL queries prevent injection
  • Integer overflow protection in disk calculations (u64 arithmetic)
Original prompt

This section details on the original issue you should resolve

<issue_title>[CORE] System Monitoring and Persistent Alert Management for Daemon</issue_title>
<issue_description>## Problem

Related to #427. Part 2/3 of the Features.

The cortexd daemon currently provides only basic IPC handlers (ping, version, config, shutdown) and lacks the ability to monitor system health or manage persistent alerts.

Without system monitoring capabilities, the daemon cannot:

  • Detect and report system health issues (high memory usage, disk space, failed services, etc.)
  • Track alerts persistently across daemon restarts
  • Provide proactive notifications about system problems
  • Enable users to acknowledge or dismiss alerts through the IPC interface

This limits the daemon's utility as a system management tool and prevents integration with monitoring workflows.

Proposed solution

Adds system monitoring and persistent alert management on top of the daemon.

System Monitoring

  • Implement a system monitoring service that tracks:
    • Memory usage and thresholds
    • Disk space utilization
    • Failed systemd services
    • System resource metrics
  • Run monitoring checks at configurable intervals
  • Generate alerts when thresholds are exceeded or issues are detected

Persistent Alert Management

  • Implement alert storage using SQLite database (similar to history.db pattern)
  • Store alerts in ~/.cortex/alerts.db or /var/lib/cortex/alerts.db
  • Implement IPC handlers for:
    • alerts - Retrieve all active alerts or alerts by filter
    • alerts.acknowledge - Mark an alert as acknowledged
    • alerts.dismiss - Permanently dismiss an alert
  • Persist alert state (active, acknowledged, dismissed) across daemon restarts
  • Support alert metadata (severity, timestamp, source, description)

Integration Points

  • Add monitoring service as a daemon service (following Service interface pattern)
  • Extend IPC handlers to support alert methods
  • Add configuration options for monitoring intervals and thresholds
  • Integrate with existing notification system (if applicable)

Example Usage

# Uses status IPC handler - Show daemon status
cortex daemon status

# Verbose status with health info - Detailed system health
cortex daemon status -v

# Uses health IPC handler - Check system health
cortex daemon health

# Uses alerts IPC handlers - List all alerts
cortex daemon alerts

# Filter by severity
cortex daemon alerts --severity <level>

# Uses alerts.acknowledge handler - Acknowledge all alerts
cortex daemon alerts --acknowledge-all

# Uses alerts.dismiss handler - Dismiss specific alert
cortex daemon alerts --dismiss <uuid>

</issue_description>

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a background daemon system for real-time system monitoring and persistent alert management
    • Added CLI commands to check daemon status, view health metrics, and manage alerts (acknowledge/dismiss)
    • System automatically monitors memory usage, disk space, and service health with configurable thresholds
  • Chores

    • Updated build configurations and added audio library dependencies

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI and others added 4 commits January 26, 2026 22:41
Co-authored-by: mikejmorgan-ai <73376634+mikejmorgan-ai@users.noreply.github.com>
Co-authored-by: mikejmorgan-ai <73376634+mikejmorgan-ai@users.noreply.github.com>
Co-authored-by: mikejmorgan-ai <73376634+mikejmorgan-ai@users.noreply.github.com>
…l issues

Co-authored-by: mikejmorgan-ai <73376634+mikejmorgan-ai@users.noreply.github.com>
Copilot AI changed the title [WIP] Add system monitoring and persistent alert management for daemon Add system monitoring and persistent alert management to daemon Jan 26, 2026
Copilot AI requested a review from mikejmorgan-ai January 26, 2026 22:57
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 27, 2026

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • ✅ Full review completed - (🔄 Check again to review again)

Comment @coderabbitai help to get the list of available commands and usage tips.

Mike Morgan and others added 4 commits January 27, 2026 14:10
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- wezterm → cx-terminal
- wezterm-gui → cx-terminal-gui

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add alsa-lib-devel for Fedora/CentOS
- Add libasound2-dev for Debian/Ubuntu

Required for cx-daemon monitoring features.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Required for cx-daemon monitoring features.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@sonarqubecloud
Copy link

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 12

🤖 Fix all issues with AI agents
In @.github/workflows/gen_macos.yml:
- Around line 62-73: The macOS workflow currently uploads the wrong artifact
name and misses required Rust CI checks; update the upload artifact path in
.github/workflows/gen_macos.yml from WezTerm-*.zip to CXTerminal-*.zip to match
the artifact produced by ci/deploy.sh (which creates CXTerminal-macos-*.zip),
and insert explicit pre-test steps for Cargo Check and Rustfmt check (add steps
running cargo check and cargo fmt --check) before the existing Test Suite step
so the workflow includes Cargo Check, Rustfmt, Tests, and Docs as required.

In `@cx-daemon/src/alerts.rs`:
- Around line 1-4: The file alerts.rs is missing the required BSL 1.1 license
header; add the standard Boost Software License 1.1 header comment at the top of
alerts.rs (above the existing module doc comments like the //! Alert database
lines) so the license block appears as the first lines of the file and covers
the whole source file per project guidelines.

In `@cx-daemon/src/ipc.rs`:
- Around line 1-2: The file ipc.rs (module doc comment "//! IPC request handlers
for the daemon") is missing the BSL 1.1 license header; add the standard BSL 1.1
license header block at the top of ipc.rs before any module comments or code so
the file includes the required license text per project guidelines.

In `@cx-daemon/src/lib.rs`:
- Around line 1-3: Update the crate-level doc comments (the top //! comments in
lib.rs) to explain WHY this crate exists (its intent and purpose for the CX
Terminal) rather than WHAT it is; replace or rewrite the current lines to a
purpose-driven sentence that starts with the CX addition marker (use a leading
comment like "// CX Terminal:" immediately before or as part of the crate docs)
and ensure the text follows the project's "why" style (zero documentation
philosophy). Target the crate-level doc comments in lib.rs and keep the original
information concise while emphasizing intent and CX Terminal ownership.
- Around line 1-3: This new Rust file is missing the required BSL 1.1 license
header; add the standard Boost Software License 1.1 header comment block at the
top of cx-daemon/src/lib.rs including the copyright notice "AI Venture Holdings
LLC" and the SPDX or license text per project guidelines so the file begins with
the full BSL 1.1 header before the module doc comments (i.e., above the existing
//! CX Daemon shared library lines).

In `@cx-daemon/src/main.rs`:
- Around line 1-7: Add the required BSL 1.1 license header as a top-of-file
comment block to this new Rust source (before the existing crate-level doc
comments) so the file includes the standard Boost Software License 1.1 text;
insert the full BSL 1.1 header (including copyright/years/holder as appropriate)
at the very top of main.rs so the existing module docs remain unchanged below
it.

In `@cx-daemon/src/monitoring.rs`:
- Around line 68-131: check_and_alert currently creates alerts on every run even
when identical active alerts exist, causing duplicates; fix by querying existing
active alerts before calling create_alert: add a helper like
has_active_alert(&self, source: &str) that locks alert_db and lists alerts
filtered by AlertStatus::Active (use the same DB access pattern as
create_alert), then in check_and_alert (for each alerting branch:
memory_monitor, disk_monitor, service_monitor) call has_active_alert and skip
create_alert if an active alert from the same source already exists; ensure you
reference create_alert, check_and_alert, alert_db/list and AlertStatus::Active
when implementing the check.
- Around line 1-4: Add the BSL 1.1 license header to the top of the new module
file above the existing module docs; specifically insert the standard BSL 1.1
block header at the very beginning of cx-daemon/src/monitoring.rs (i.e., before
the leading "//! System monitoring service" comments) so the file includes the
required license text for new files while preserving the existing module-level
documentation.

In `@cx-daemon/src/paths.rs`:
- Line 1: Add the BSL 1.1 license header to the top of the new file (paths.rs)
including the copyright notice for AI Venture Holdings LLC; update the
module-level comment (the existing //! Shared utilities for CX daemon) so the
license header appears above it and ensure the full BSL 1.1 block is present and
formatted as a Rust comment (//! or /* ... */) per project convention.

In `@wezterm/src/cli/daemon.rs`:
- Line 1: Add the BSL 1.1 license header at the top of the file (above the
existing module doc comment "//! CLI commands for interacting with the CX
daemon"), using the project's standard Boost Software License 1.1 block and
filling in the correct year and copyright owner; ensure the header is formatted
as a comment and placed before any code or module-level doc comments.
- Line 7: The use of std::os::unix::net::UnixStream causes Windows build
failures; update DaemonCommand::run (and any functions referencing UnixStream)
to use conditional compilation: add a #[cfg(not(unix))] branch that returns a
clear error (e.g., bail or Err) stating daemon commands are only supported on
Unix, and wrap the existing Unix-specific logic behind #[cfg(unix)] so
UnixStream is only referenced on Unix targets.

In `@wezterm/src/main.rs`:
- Around line 180-185: Replace the current doc comment for the Daemon enum
variant with a brief WHY-focused comment prefixed by the CX marker: add a Rust
line comment starting with "// CX Terminal:" that explains the intent/purpose of
the Daemon subcommand (e.g., why we expose it: to monitor and manage daemon
health/status/alerts for CX Terminal integration), and update the associated
#[command(..., about = "...")] text if needed to match that intent; locate the
Daemon enum variant (Daemon(cli::daemon::DaemonCommand)) and change the
triple-slash WHAT comment to the CX WHY comment accordingly.
🧹 Nitpick comments (8)
cx-daemon/src/main.rs (2)

207-214: Shutdown via process::exit(0) leaves socket file orphaned.

The daemon exits immediately without removing the socket file. While the code handles this on startup (line 146-148), a cleaner approach would be to signal the main loop to exit gracefully.

Consider using a shutdown flag or channel to break the accept loop and perform cleanup, rather than calling process::exit(0) directly from the client handler thread.


176-177: Unreachable code: monitoring_thread.join() will never execute.

The for stream in listener.incoming() loop runs indefinitely (or until process exit), so this join call is unreachable. If this is intentional (daemon runs forever), consider removing the dead code or adding a comment explaining the intent.

wezterm/src/cli/daemon.rs (1)

53-95: Consider reusing IPC types from cx-daemon crate.

The Request and Response enums here duplicate the DaemonRequest and DaemonResponse types defined in cx-daemon/src/ipc.rs. While the slight differences in field naming/structure may be intentional (CLI vs daemon perspective), this creates a maintenance burden where protocol changes require updates in two places.

Consider either:

  1. Reusing the types from cx_daemon::ipc directly, or
  2. Creating a shared protocol crate if the types must differ
cx-daemon/src/alerts.rs (3)

32-40: Consider implementing std::str::FromStr trait.

The custom from_str method works but implementing the standard FromStr trait would allow using .parse() and integrate better with the Rust ecosystem.


174-188: Silent fallback on invalid data could mask database corruption.

When parsing severity, status, or timestamps from the database fails, the code silently falls back to defaults (AlertSeverity::Info, AlertStatus::Active, Utc::now()). This could hide data integrity issues.

Consider logging a warning when fallback occurs:

severity: AlertSeverity::from_str(&row.get::<_, String>(1)?)
    .unwrap_or_else(|| {
        log::warn!("Invalid severity in DB, defaulting to Info");
        AlertSeverity::Info
    }),

301-335: Test cleanup could be more robust.

The test removes the temp file at the end, but if the test panics earlier, the file remains. Consider using a test helper or Drop guard for cleanup.

cx-daemon/src/monitoring.rs (1)

140-146: Mutex::lock().unwrap() can panic on poisoned lock.

If another thread panics while holding the lock, subsequent unwrap() calls will panic. Consider using lock().unwrap_or_else(|e| e.into_inner()) or proper error handling to maintain daemon stability.

cx-daemon/src/ipc.rs (1)

153-170: Consistent mutex handling pattern recommended.

Multiple methods use .lock().unwrap() which can panic on poisoned locks. Consider extracting a helper method or using a consistent error-handling pattern across all handlers.

fn with_db<F, T>(&self, f: F) -> Result<T, String>
where
    F: FnOnce(&AlertDatabase) -> Result<T>,
{
    let db = self.alert_db.lock()
        .map_err(|_| "Database lock poisoned".to_string())?;
    f(&db).map_err(|e| e.to_string())
}

Comment on lines 62 to +73
- name: "Build cx-terminal (Release mode Intel)"
shell: bash
run: "cargo build --target x86_64-apple-darwin -p wezterm --release"
run: "cargo build --target x86_64-apple-darwin -p cx-terminal --release"
- name: "Build cx-terminal (Release mode ARM)"
shell: bash
run: "cargo build --target aarch64-apple-darwin -p wezterm --release"
run: "cargo build --target aarch64-apple-darwin -p cx-terminal --release"
- name: "Build cx-terminal-gui (Release mode Intel)"
shell: bash
run: "cargo build --target x86_64-apple-darwin -p wezterm-gui --release"
run: "cargo build --target x86_64-apple-darwin -p cx-terminal-gui --release"
- name: "Build cx-terminal-gui (Release mode ARM)"
shell: bash
run: "cargo build --target aarch64-apple-darwin -p wezterm-gui --release"
run: "cargo build --target aarch64-apple-darwin -p cx-terminal-gui --release"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# Check if macOS bundle structure exists
test -f "assets/macos/CX Terminal.app/Contents/Info.plist" && echo "✓ Info.plist exists" || echo "✗ Info.plist missing"

# Examine ci/deploy.sh for binary references and artifact naming
echo "=== ci/deploy.sh references ===" && cat -n ci/deploy.sh | head -100

Repository: cxlinux-ai/cx-core

Length of output: 148


🏁 Script executed:

# Search for any references to cx-terminal or wezterm in deploy scripts
echo "=== Binary references in deploy-related files ===" && \
rg -n "(cx-terminal|cx_terminal|wezterm|WezTerm)" --type bash --type sh . 2>/dev/null | head -30

Repository: cxlinux-ai/cx-core

Length of output: 111


🏁 Script executed:

# Direct file existence check
ls -la "assets/macos/CX Terminal.app/Contents/Info.plist" 2>&1 || echo "File not found"

Repository: cxlinux-ai/cx-core

Length of output: 159


🏁 Script executed:

# Locate ci/deploy.sh
find . -name "deploy.sh" -o -name "*deploy*" -type f | grep -v node_modules | head -20

Repository: cxlinux-ai/cx-core

Length of output: 76


🏁 Script executed:

# Check gen_macos.yml for CI checks (Cargo Check, Rustfmt, Test Suite, Documentation Tests)
grep -n "cargo check\|rustfmt\|test\|cargo test\|doc-tests" .github/workflows/gen_macos.yml || echo "No CI checks found"

Repository: cxlinux-ai/cx-core

Length of output: 266


🏁 Script executed:

# Read the gen_macos.yml workflow file
cat -n .github/workflows/gen_macos.yml

Repository: cxlinux-ai/cx-core

Length of output: 4180


🏁 Script executed:

# Read the deploy script to see how it consumes binaries
cat -n ci/deploy.sh

Repository: cxlinux-ai/cx-core

Length of output: 20928


Fix artifact upload path and add required CI checks to macOS workflow.

The ci/deploy.sh script produces CXTerminal-macos-*.zip, not WezTerm-*.zip. Line 101 of the workflow uploads with path WezTerm-*.zip, which won't match the actual artifact produced by deploy.sh on line 96, causing upload failures.

Additionally, the workflow is missing required CI checks. Per coding guidelines for .github/workflows/**/*.{yml,yaml}, all Rust PRs must include: Cargo Check, Rustfmt, Test Suite (present), and Documentation Tests. Add explicit cargo check and cargo fmt --check steps before the test suite.

Artifact path mismatch

Line 96 runs ci/deploy.sh, which creates CXTerminal-macos-$TAG_NAME.zip (per lines 25–31 in ci/deploy.sh).
Line 101 attempts to upload WezTerm-*.zip, which doesn't exist.
Update line 101 to: path: "CXTerminal-*.zip"

🤖 Prompt for AI Agents
In @.github/workflows/gen_macos.yml around lines 62 - 73, The macOS workflow
currently uploads the wrong artifact name and misses required Rust CI checks;
update the upload artifact path in .github/workflows/gen_macos.yml from
WezTerm-*.zip to CXTerminal-*.zip to match the artifact produced by ci/deploy.sh
(which creates CXTerminal-macos-*.zip), and insert explicit pre-test steps for
Cargo Check and Rustfmt check (add steps running cargo check and cargo fmt
--check) before the existing Test Suite step so the workflow includes Cargo
Check, Rustfmt, Tests, and Docs as required.

Comment on lines +1 to +4
//! Alert database for persistent alert storage
//!
//! Stores alerts in SQLite database at ~/.cx/alerts.db

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Missing BSL 1.1 license header.

New files require the BSL 1.1 license header. As per coding guidelines.

🤖 Prompt for AI Agents
In `@cx-daemon/src/alerts.rs` around lines 1 - 4, The file alerts.rs is missing
the required BSL 1.1 license header; add the standard Boost Software License 1.1
header comment at the top of alerts.rs (above the existing module doc comments
like the //! Alert database lines) so the license block appears as the first
lines of the file and covers the whole source file per project guidelines.

Comment on lines +1 to +2
//! IPC request handlers for the daemon

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Missing BSL 1.1 license header.

New files require the BSL 1.1 license header. As per coding guidelines.

🤖 Prompt for AI Agents
In `@cx-daemon/src/ipc.rs` around lines 1 - 2, The file ipc.rs (module doc comment
"//! IPC request handlers for the daemon") is missing the BSL 1.1 license
header; add the standard BSL 1.1 license header block at the top of ipc.rs
before any module comments or code so the file includes the required license
text per project guidelines.

Comment on lines +1 to +3
//! CX Daemon shared library
//!
//! Provides shared utilities for the daemon and CLI
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Rephrase crate docs to state intent and include the CX Terminal prefix.
The current doc comments describe what the module is, but the guideline asks for why plus the CX Terminal prefix.

✍️ Suggested rewrite
-//! CX Daemon shared library
-//!
-//! Provides shared utilities for the daemon and CLI
+//! CX Terminal: Keep daemon/CLI path resolution consistent to avoid diverging socket and DB locations.
As per coding guidelines: Write comments explaining WHY, never WHAT or HOW, following zero documentation philosophy. Rust: Mark CX additions with '// CX Terminal:' comment prefix.
🤖 Prompt for AI Agents
In `@cx-daemon/src/lib.rs` around lines 1 - 3, Update the crate-level doc comments
(the top //! comments in lib.rs) to explain WHY this crate exists (its intent
and purpose for the CX Terminal) rather than WHAT it is; replace or rewrite the
current lines to a purpose-driven sentence that starts with the CX addition
marker (use a leading comment like "// CX Terminal:" immediately before or as
part of the crate docs) and ensure the text follows the project's "why" style
(zero documentation philosophy). Target the crate-level doc comments in lib.rs
and keep the original information concise while emphasizing intent and CX
Terminal ownership.

⚠️ Potential issue | 🟠 Major

Add BSL 1.1 license header to this new Rust file.
This file is new and currently lacks the required license header.

📝 Suggested header
+// Copyright (c) 2026 AI Venture Holdings LLC
+// SPDX-License-Identifier: BSL-1.1
+
 //! CX Daemon shared library
 //!
 //! Provides shared utilities for the daemon and CLI
As per coding guidelines: Include BSL 1.1 license header on all new files with copyright to AI Venture Holdings LLC.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
//! CX Daemon shared library
//!
//! Provides shared utilities for the daemon and CLI
// Copyright (c) 2026 AI Venture Holdings LLC
// SPDX-License-Identifier: BSL-1.1
//! CX Daemon shared library
//!
//! Provides shared utilities for the daemon and CLI
🤖 Prompt for AI Agents
In `@cx-daemon/src/lib.rs` around lines 1 - 3, This new Rust file is missing the
required BSL 1.1 license header; add the standard Boost Software License 1.1
header comment block at the top of cx-daemon/src/lib.rs including the copyright
notice "AI Venture Holdings LLC" and the SPDX or license text per project
guidelines so the file begins with the full BSL 1.1 header before the module doc
comments (i.e., above the existing //! CX Daemon shared library lines).

Comment on lines +1 to +7
//! CX Daemon - System monitoring and alert management daemon for CX Linux
//!
//! The daemon provides:
//! - System health monitoring (memory, disk, services)
//! - Persistent alert management with SQLite storage
//! - IPC interface via Unix socket for terminal integration

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Missing BSL 1.1 license header.

New files require the BSL 1.1 license header. As per coding guidelines.

📜 Suggested license header
+// Copyright (c) 2026 AI Venture Holdings LLC
+//
+// This file is part of CX Linux and is licensed under the Business Source License 1.1.
+// See the LICENSE file in the project root for license information.
+
 //! CX Daemon - System monitoring and alert management daemon for CX Linux
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
//! CX Daemon - System monitoring and alert management daemon for CX Linux
//!
//! The daemon provides:
//! - System health monitoring (memory, disk, services)
//! - Persistent alert management with SQLite storage
//! - IPC interface via Unix socket for terminal integration
// Copyright (c) 2026 AI Venture Holdings LLC
//
// This file is part of CX Linux and is licensed under the Business Source License 1.1.
// See the LICENSE file in the project root for license information.
//! CX Daemon - System monitoring and alert management daemon for CX Linux
//!
//! The daemon provides:
//! - System health monitoring (memory, disk, services)
//! - Persistent alert management with SQLite storage
//! - IPC interface via Unix socket for terminal integration
🤖 Prompt for AI Agents
In `@cx-daemon/src/main.rs` around lines 1 - 7, Add the required BSL 1.1 license
header as a top-of-file comment block to this new Rust source (before the
existing crate-level doc comments) so the file includes the standard Boost
Software License 1.1 text; insert the full BSL 1.1 header (including
copyright/years/holder as appropriate) at the very top of main.rs so the
existing module docs remain unchanged below it.

Comment on lines +68 to +131
pub fn check_and_alert(&self) -> Result<()> {
let health = self.get_health()?;

// Check memory usage
if health.memory_usage_percent >= self.config.memory_critical_threshold {
self.create_alert(
AlertSeverity::Critical,
"memory_monitor",
"Critical Memory Usage",
&format!(
"Memory usage is at {:.1}% (critical threshold: {:.1}%)",
health.memory_usage_percent, self.config.memory_critical_threshold
),
)?;
} else if health.memory_usage_percent >= self.config.memory_warning_threshold {
self.create_alert(
AlertSeverity::Warning,
"memory_monitor",
"High Memory Usage",
&format!(
"Memory usage is at {:.1}% (warning threshold: {:.1}%)",
health.memory_usage_percent, self.config.memory_warning_threshold
),
)?;
}

// Check disk usage
if health.disk_usage_percent >= self.config.disk_critical_threshold {
self.create_alert(
AlertSeverity::Critical,
"disk_monitor",
"Critical Disk Space",
&format!(
"Disk usage is at {:.1}% (critical threshold: {:.1}%)",
health.disk_usage_percent, self.config.disk_critical_threshold
),
)?;
} else if health.disk_usage_percent >= self.config.disk_warning_threshold {
self.create_alert(
AlertSeverity::Warning,
"disk_monitor",
"Low Disk Space",
&format!(
"Disk usage is at {:.1}% (warning threshold: {:.1}%)",
health.disk_usage_percent, self.config.disk_warning_threshold
),
)?;
}

// Check for failed services
if !health.failed_services.is_empty() {
self.create_alert(
AlertSeverity::Error,
"service_monitor",
"Failed Services Detected",
&format!(
"The following services have failed: {}",
health.failed_services.join(", ")
),
)?;
}

Ok(())
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Potential alert flooding: duplicate alerts created on each check interval.

The check_and_alert method creates a new alert every time a threshold is exceeded, even if an identical active alert already exists. With a 5-minute default interval, this could rapidly fill the database with duplicate alerts during sustained high-resource conditions.

Consider checking for existing active alerts from the same source before creating new ones:

// Before creating a new alert, check if a similar active alert exists
fn has_active_alert(&self, source: &str) -> Result<bool> {
    let db = self.alert_db.lock().unwrap();
    let alerts = db.list(Some(AlertStatus::Active), None)?;
    Ok(alerts.iter().any(|a| a.source == source))
}
🤖 Prompt for AI Agents
In `@cx-daemon/src/monitoring.rs` around lines 68 - 131, check_and_alert currently
creates alerts on every run even when identical active alerts exist, causing
duplicates; fix by querying existing active alerts before calling create_alert:
add a helper like has_active_alert(&self, source: &str) that locks alert_db and
lists alerts filtered by AlertStatus::Active (use the same DB access pattern as
create_alert), then in check_and_alert (for each alerting branch:
memory_monitor, disk_monitor, service_monitor) call has_active_alert and skip
create_alert if an active alert from the same source already exists; ensure you
reference create_alert, check_and_alert, alert_db/list and AlertStatus::Active
when implementing the check.

@@ -0,0 +1,32 @@
//! Shared utilities for CX daemon
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Missing BSL 1.1 license header.

New files require the BSL 1.1 license header with copyright to AI Venture Holdings LLC. As per coding guidelines: "Include BSL 1.1 license header on all new files with copyright to AI Venture Holdings LLC".

📜 Suggested license header
+// Copyright (c) 2026 AI Venture Holdings LLC
+//
+// This file is part of CX Linux and is licensed under the Business Source License 1.1.
+// See the LICENSE file in the project root for license information.
+
 //! Shared utilities for CX daemon
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
//! Shared utilities for CX daemon
// Copyright (c) 2026 AI Venture Holdings LLC
//
// This file is part of CX Linux and is licensed under the Business Source License 1.1.
// See the LICENSE file in the project root for license information.
//! Shared utilities for CX daemon
🤖 Prompt for AI Agents
In `@cx-daemon/src/paths.rs` at line 1, Add the BSL 1.1 license header to the top
of the new file (paths.rs) including the copyright notice for AI Venture
Holdings LLC; update the module-level comment (the existing //! Shared utilities
for CX daemon) so the license header appears above it and ensure the full BSL
1.1 block is present and formatted as a Rust comment (//! or /* ... */) per
project convention.

@@ -0,0 +1,335 @@
//! CLI commands for interacting with the CX daemon
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Missing BSL 1.1 license header.

New files require the BSL 1.1 license header. As per coding guidelines.

🤖 Prompt for AI Agents
In `@wezterm/src/cli/daemon.rs` at line 1, Add the BSL 1.1 license header at the
top of the file (above the existing module doc comment "//! CLI commands for
interacting with the CX daemon"), using the project's standard Boost Software
License 1.1 block and filling in the correct year and copyright owner; ensure
the header is formatted as a comment and placed before any code or module-level
doc comments.

use clap::Parser;
use serde::{Deserialize, Serialize};
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Build failure on Windows: std::os::unix is not available.

The pipeline failure indicates this code doesn't compile on Windows because std::os::unix::net::UnixStream is Unix-only. Consider adding platform-specific compilation or a graceful error message.

🔧 Proposed fix with conditional compilation
 //! CLI commands for interacting with the CX daemon
 
 use anyhow::{Context, Result};
 use clap::Parser;
 use serde::{Deserialize, Serialize};
-use std::io::{BufRead, BufReader, Write};
-use std::os::unix::net::UnixStream;
 use std::path::PathBuf;
+
+#[cfg(unix)]
+use std::io::{BufRead, BufReader, Write};
+#[cfg(unix)]
+use std::os::unix::net::UnixStream;

Then guard the implementation:

impl DaemonCommand {
    pub fn run(&self) -> Result<()> {
        #[cfg(not(unix))]
        {
            anyhow::bail!("Daemon commands are only supported on Unix systems");
        }
        
        #[cfg(unix)]
        {
            // existing implementation
        }
    }
}
🧰 Tools
🪛 GitHub Actions: windows

[error] 7-7: could not find unix in os. use std::os::unix::net::UnixStream;

🤖 Prompt for AI Agents
In `@wezterm/src/cli/daemon.rs` at line 7, The use of
std::os::unix::net::UnixStream causes Windows build failures; update
DaemonCommand::run (and any functions referencing UnixStream) to use conditional
compilation: add a #[cfg(not(unix))] branch that returns a clear error (e.g.,
bail or Err) stating daemon commands are only supported on Unix, and wrap the
existing Unix-specific logic behind #[cfg(unix)] so UnixStream is only
referenced on Unix targets.

Comment on lines +180 to +185
/// Manage the CX daemon
#[command(
name = "daemon",
about = "Manage the CX daemon (status, health, alerts)"
)]
Daemon(cli::daemon::DaemonCommand),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Adjust daemon subcommand doc comment to reflect intent and use CX prefix.
Line 180’s doc comment is a what description; the guideline prefers why and the CX Terminal prefix.

✍️ Suggested rewrite
-    /// Manage the CX daemon
+    /// CX Terminal: Surface daemon health/alerts for troubleshooting from the CLI.
As per coding guidelines: Write comments explaining WHY, never WHAT or HOW, following zero documentation philosophy. Rust: Mark CX additions with '// CX Terminal:' comment prefix.
🤖 Prompt for AI Agents
In `@wezterm/src/main.rs` around lines 180 - 185, Replace the current doc comment
for the Daemon enum variant with a brief WHY-focused comment prefixed by the CX
marker: add a Rust line comment starting with "// CX Terminal:" that explains
the intent/purpose of the Daemon subcommand (e.g., why we expose it: to monitor
and manage daemon health/status/alerts for CX Terminal integration), and update
the associated #[command(..., about = "...")] text if needed to match that
intent; locate the Daemon enum variant (Daemon(cli::daemon::DaemonCommand)) and
change the triple-slash WHAT comment to the CX WHY comment accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[CORE] System Monitoring and Persistent Alert Management for Daemon

3 participants