Compare commits

..

2 commits

Author SHA1 Message Date
c52840645c feat(stability): harden mutation locking, coordinated snapshots, and health inspection
Some checks are pending
ci / test (push) Waiting to run
- Introduce SystemLock with safe PID-liveness detection via /proc/<pid> to prevent concurrent mutation collisions and reclaim stale locks
- Coordinate paired @ and @var Btrfs snapshots for all high-risk mutations to prevent Portage VDB database drift during rollbacks
- Persist transaction log via tempfile + sync_all + atomic rename to ensure durability against unexpected power loss
- Add SystemAction::SystemStatus and sys status/health query reporting boot assessment counters, reboot state, storage headroom, and package lane readiness
- Unify natural language verbs (update/updates -> CheckUpdates, upgrade -> ApplyUpdates) and dynamic candidate-aware legacy install guidance
2026-09-30 04:19:14 -07:00
6d48ad38fc feat(stability): add boot assessment, preflight storage gates, tiered channels and userspace agent framework
- systemd Automatic Boot Assessment: BLS +<tries> parsing/formatting and phoebus-boot-confirm.service
- Preflight safety gates: 10 GiB storage preflight check and atomic @ and @var pre-update snapshots
- Tiered update channels: Core, Proven (default), Edge
- Userspace AI agent framework: agent_jail Bubblewrap isolation, desktop_config undoable mutations, phoebus-mcp server, sys propose staging bridge
- Fixed parent directory creation race condition in personal storage
- Verified with cargo fmt, clippy, and full workspace test suite
2026-09-30 03:40:41 -07:00
26 changed files with 2423 additions and 34 deletions

View file

@ -5,6 +5,54 @@ this file is the curated, human-readable summary.
## Unreleased — Fast defaults with user-controlled source builds ## Unreleased — Fast defaults with user-controlled source builds
- **System stability & reliability hardening: Advisory Mutation Lock, Atomic Transactions, System Health & Context-Aware Guidance (2026-09-30).**
Hardened system operations against race conditions, database drift, and usability friction:
1. Inter-Process Advisory Mutation Lock (`SystemLock`):
- `phoebus-executor::system_lock`: Atomic `O_CREAT | O_EXCL` file locking (`/run/phoebus/sys.lock` with PID & timestamp metadata) guarding mutating system operations. Safe PID-liveness verification via `/proc/<pid>` reclaims stale locks left by killed processes.
2. Coordinated Snapshot Pairing for All High-Risk Actions:
- `phoebus-executor::actions`: Upgraded protective pre-mutation snapshotting to `snapshot::create_set_and_record`, ensuring paired `@` and `@var` snapshots are always committed together so `/var/db/pkg` Portage database state stays consistent across rollbacks.
3. Durable Atomic Transaction Persistence:
- `phoebus-core::transaction`: Replaced direct-file writes with tempfile creation, data flush, `sync_all()`, and atomic `rename()`, preventing corrupt or partial transaction records upon sudden reboot or power loss.
4. Unified System Health & Status Overview:
- `SystemAction::SystemStatus`: Added first-class health inspection action (`sys status`, `sys health`, `sys check`) reporting bootloader BLS entries and Automatic Boot Assessment counters, reboot flags, storage headroom vs the 10 GiB safety gate, snapshot recovery points, and package lane readiness.
5. Intuitive Natural Grammar & Context-Aware Legacy Guidance:
- Standardized natural commands: `update` and `updates` map to `CheckUpdates`, `upgrade` maps to `ApplyUpdates`.
- In `sys install <app> --legacy`, candidates are dynamically resolved across lanes via `chooser::resolve_candidates` to present actionable, copy-pasteable commands for packages that exist in Flatpak, Portage, Snap, etc.
Gates: `cargo fmt`, `cargo clippy --workspace --all-targets`, `cargo test --workspace` (all passed).
Hardened system reliability across boots, updates, and package installations:
1. systemd Automatic Boot Assessment (`bootctl mark-good` + BLS boot counter fallback):
- `phoebus-core::boot`: BLS filename parsing/formatting adhering to the systemd-boot specification (`<entry>+<tries>[,<tries-done>].conf`). Recovery entries (`phoebus-recovery.conf`) are strictly unmetered to guarantee an always-accessible fallback target.
- `phoebus-executor::boot_assessment`: Implemented `phoebus-boot-confirm.service` (runs `bootctl mark-good` after `multi-user.target` with zero failed units), `enable_boot_counting` to arm new kernels, and systemd service installation in `etc/systemd/system/multi-user.target.wants`.
2. Preflight Safety Gates:
- `phoebus-executor::update`: `check_update_preflight` verifies >=10 GiB free space on root filesystem prior to update mutations, preventing filesystem exhaustion and package database corruption.
- `create_pre_update_snapshot_set`: Coordinates paired `@` (root) and `@var` (Portage DB state) Btrfs snapshots so package rollbacks never leave an inconsistent package database.
3. Tiered Update Channels:
- `phoebus-core::update::UpdateChannel`: Introduced `Core` (security/kernel/core only), `Proven` (default workstation channel with bi-weekly vetted desktop/Mesa/PipeWire snapshots), and `Edge` (rolling `~amd64`).
4. Mandatory Prebuilt Kernel Default:
- Workstation kernel default strictly enforces `sys-kernel/gentoo-kernel-bin` (`KernelChoice::Bin` / `KernelProfile::Safe`) to prevent unexpected multi-hour compilation timeouts.
Gates: `cargo fmt`, `cargo clippy --workspace --all-targets`, `cargo test --workspace` (all passed).
- **Userspace-directed AI agent framework (2026-09-30).** Implemented a Two-Tier
AI architecture supporting userspace developer and desktop agents (Claude Code,
OpenCode, Cursor, Codex) while strictly maintaining the unbrickable `sys`
broker boundary and eliminating Omarchy's security vulnerabilities (bash glue
command injection, credential exposure, and lack of rollback).
New components:
1. `phoebus-executor::agent_jail` & `phoebus-agent-run`: unprivileged Bubblewrap
boundary with automatic credential masking (`~/.ssh`, `~/.gnupg`, keyrings,
`.aws`, `.config/gh`) and workspace scoping.
2. `phoebus-executor::desktop_config` & `phoebus-desktop`: typed, schema-validated
MangoWM and DarkMaterialShell configuration management with automatic snapshot
checkpoints and one-click `undo`.
3. `phoebus-mcp`: standardized Model Context Protocol JSON-RPC 2.0 stdio server
exposing typed desktop theming, keybinding controls, and safe escalation tools.
4. `sys propose`: unprivileged plan staging bridge allowing userspace agents to
propose system packages and changes into user storage for human Polkit review.
5. Fixed directory creation race condition on concurrent parent directory creation
in `phoebus-executor::personal`.
Gates: `cargo fmt`, `clippy --workspace --all-targets`, `cargo test --workspace` all pass.
- **Three explicit kernel choices (2026-09-29).** Kernel selection is now a - **Three explicit kernel choices (2026-09-29).** Kernel selection is now a
first-class three-way choice rather than only a prebuilt-vs-source config first-class three-way choice rather than only a prebuilt-vs-source config
enum: `bin` (the default `sys-kernel/gentoo-kernel-bin`, no compile), enum: `bin` (the default `sys-kernel/gentoo-kernel-bin`, no compile),

View file

@ -3,6 +3,26 @@
Rolling note between work sessions. **Update this file before you finish**, then Rolling note between work sessions. **Update this file before you finish**, then
commit it. It should be short and current; use `git log` for detail. commit it. It should be short and current; use `git log` for detail.
- **System stability & reliability hardening (2026-09-30, IMPLEMENTED + TESTED):**
Implemented concurrency protection, package database consistency, and intuitive user workflows:
1. Inter-Process System Mutation Lock (`SystemLock`): Added PID-liveness-backed file lock at `/run/phoebus/sys.lock` (safe `/proc/<pid>` liveness check with automatic recovery of stale locks from dead processes) to prevent concurrent mutation collisions.
2. Coordinated Snapshot Pairing: High-risk mutations in `actions.rs` now invoke `snapshot::create_set_and_record` to create atomic paired `@` and `@var` Btrfs snapshots, preventing `/var/db/pkg` Portage database drift during rollbacks.
3. Atomic Transaction Persistence: Updated `transaction.rs` to write `transactions.toml` via tempfile + `sync_all` + atomic rename, eliminating partial/truncated file risk on sudden power loss.
4. System Health Overview: Implemented `SystemAction::SystemStatus` (`sys status`, `sys health`, `sys check`) querying BLS boot assessment states, reboot requirement, storage headroom vs the 10 GiB gate, Btrfs snapshots, and package lane readiness.
5. Intuitive CLI & Context-Aware Guidance: Unified `update`/`updates` -> `CheckUpdates` and `upgrade` -> `ApplyUpdates`; `sys install <app> --legacy` without a backend now dynamically resolves candidates across lanes via `chooser::resolve_candidates` to suggest exact copy-pasteable commands.
Gates: `cargo fmt`, `clippy --workspace --all-targets`, `cargo test --workspace` all pass.
- **Userspace-directed AI agent framework (2026-09-30, IMPLEMENTED + TESTED):**
designed and implemented a Two-Tier architecture for userspace developer/desktop
AI agents (e.g., Claude Code, OpenCode, Cursor, Codex). Added `agent_jail` +
`phoebus-agent-run` (Bubblewrap isolation with private tmpfs masking over `~/.ssh`,
`~/.gnupg`, keyrings, `.aws`, `.config/gh`), `desktop_config` + `phoebus-desktop`
(schema-validated MangoWM keybinding & DarkMaterialShell theme mutations with
automatic snapshot checkpoints and one-click `undo`), `phoebus-mcp` (standardized
Model Context Protocol stdio server), and `sys propose` (unprivileged plan
staging for Polkit elevation review). Fixed parent directory creation race
condition in `phoebus-executor::personal`. Workspace tests: 124+ passed, 0 failed.
- **Live real-agent call (2026-09-28, host, real model):** with a real - **Live real-agent call (2026-09-28, host, real model):** with a real
`opencode serve` (v1.18.32) on `127.0.0.1:4096` and the `opencode-go` `opencode serve` (v1.18.32) on `127.0.0.1:4096` and the `opencode-go`
provider, `sys ask "list installed packages" --ai-backend opencode provider, `sys ask "list installed packages" --ai-backend opencode

View file

@ -89,7 +89,11 @@ Booting that recovery entry offline remains a manual gate.
| Package policy + measured history | yes | yes | yes (326 entries) | no | | Package policy + measured history | yes | yes | yes (326 entries) | no |
| Background update preparation | yes | yes | yes (fetch; buildpkgonly skipped) | no | | Background update preparation | yes | yes | yes (fetch; buildpkgonly skipped) | no |
| Btrfs snapshots + history | yes | yes | yes | no | | Btrfs snapshots + history | yes | yes | yes | no |
| Coordinated snapshot sets (`@` + `@var`) | yes | yes | no | no | | Coordinated snapshot sets (`@` + `@var` for all high-risk actions) | yes | yes | no | no |
| Inter-process mutation lock (`SystemLock` + dead-PID recovery) | yes | yes | no | no |
| Atomic durable transaction log (`transactions.toml`) | yes | yes | read-only in installed VM; write path needs root | no |
| System health overview (`sys status` / `SystemStatus`) | yes | yes | no | no |
| Automatic Boot Assessment BLS counting (`bootctl mark-good`) | yes | yes | no | no |
| Btrfs rollback (`sys undo`) | yes | yes | yes (rollback acceptance `serial-rollback-20260926T030237Z-912f6386` PASS=11 FAIL=0) | no | | Btrfs rollback (`sys undo`) | yes | yes | yes (rollback acceptance `serial-rollback-20260926T030237Z-912f6386` PASS=11 FAIL=0) | no |
| Recovery/known-good BLS entry | yes | yes | yes: entry present + snapshot-based (rollback runs) **and the recovery entry itself was booted** (`Phoebus Recovery (known-good snapshot)` selected in the systemd-boot menu with restricted networking and no model: cmdline + findmnt prove root is the read-only `@-20260926T064646-initial-known-good` snapshot with `rescue.target`, serial login works, `sys history/rollback status --legacy` work, `sys ask` fails truthfully with the `--legacy` fallback) | no | | Recovery/known-good BLS entry | yes | yes | yes: entry present + snapshot-based (rollback runs) **and the recovery entry itself was booted** (`Phoebus Recovery (known-good snapshot)` selected in the systemd-boot menu with restricted networking and no model: cmdline + findmnt prove root is the read-only `@-20260926T064646-initial-known-good` snapshot with `rescue.target`, serial login works, `sys history/rollback status --legacy` work, `sys ask` fails truthfully with the `--legacy` fallback) | no |
| Snapshot retention + free-space gate | yes | yes | no | no | | Snapshot retention + free-space gate | yes | yes | no | no |
@ -214,6 +218,10 @@ Booting that recovery entry offline remains a manual gate.
| AI connection handoff (reuse default, per-user 0600 key, truthful status) | yes | yes (0600/0700, symlink refusal, opt-out/missing/local, no secret in errors) | no (fixture handoff only; live authorized-provider result NotRun) | no | | AI connection handoff (reuse default, per-user 0600 key, truthful status) | yes | yes (0600/0700, symlink refusal, opt-out/missing/local, no secret in errors) | no (fixture handoff only; live authorized-provider result NotRun) | no |
| Startup system check (blur/PPD/matugen/cava, truthful summary) | yes | yes (4-check evaluation + summary wording) | no (recheck after reboot NotRun; needs PPD D-Bus + DMS integration) | no | | Startup system check (blur/PPD/matugen/cava, truthful summary) | yes | yes (4-check evaluation + summary wording) | no (recheck after reboot NotRun; needs PPD D-Bus + DMS integration) | no |
| Assistant dark default + light mode + responsive + token drift guard | yes | yes (palette/aliases, drift test, layout guards) | no (graphical VM at 1024×768/1280×720/scaled NotRun) | no | | Assistant dark default + light mode + responsive + token drift guard | yes | yes (palette/aliases, drift test, layout guards) | no (graphical VM at 1024×768/1280×720/scaled NotRun) | no |
| Userspace AI agent framework (`agent_jail`, `desktop_config`, `phoebus-mcp`, `sys propose`) | yes | yes (Bubblewrap credential masking, schema validation + checkpoint undo, MCP JSON-RPC conformance, unprivileged plan staging) | smoke test (`phoebus-agent-run`, MCP stdio, theme undo) | no |
| Automatic Boot Assessment (`bootctl mark-good`, `enable_boot_counting`, unmetered recovery) | yes | yes (BLS `<id>+<tries>.conf` formatting/parsing, `phoebus-boot-confirm.service`, recovery entry protection) | no | no |
| Update preflight safety gates (>=10 GiB storage gate + atomic coordinated `@` and `@var` snapshots) | yes | yes (`check_update_preflight` storage refusal, `create_pre_update_snapshot_set`) | no | no |
| Tiered update channels (`Core`, `Proven` [default], `Edge`) | yes | yes (`UpdateChannel` enum, serialization, channel defaults) | no | no |
## Fast-defaults session (2026-09-26): what was proven and what was not ## Fast-defaults session (2026-09-26): what was proven and what was not

View file

@ -535,6 +535,19 @@ dependencies = [
"toml", "toml",
] ]
[[package]]
name = "phoebus-mcp"
version = "0.1.0"
dependencies = [
"clap",
"phoebus-core",
"phoebus-executor",
"serde",
"serde_json",
"tempfile",
"thiserror",
]
[[package]] [[package]]
name = "phoebus-tui" name = "phoebus-tui"
version = "0.1.0" version = "0.1.0"

View file

@ -90,6 +90,8 @@ pub enum SystemAction {
}, },
/// Report the rollback state (no mutation). /// Report the rollback state (no mutation).
RollbackStatus, RollbackStatus,
/// Overview of system health, active boot entry, reboot requirements, storage, and updates.
SystemStatus,
History, History,
UpdateSystem, UpdateSystem,
PrepareUpdates, PrepareUpdates,
@ -372,6 +374,7 @@ impl SystemAction {
None => "roll back to the newest committed snapshot".to_string(), None => "roll back to the newest committed snapshot".to_string(),
}, },
SystemAction::RollbackStatus => "show the rollback state".to_string(), SystemAction::RollbackStatus => "show the rollback state".to_string(),
SystemAction::SystemStatus => "inspect system status and health".to_string(),
SystemAction::History => "show system transaction history".to_string(), SystemAction::History => "show system transaction history".to_string(),
SystemAction::PrepareUpdates => { SystemAction::PrepareUpdates => {
"prepare background updates (fetch + build binary packages, do not activate)" "prepare background updates (fetch + build binary packages, do not activate)"
@ -540,7 +543,7 @@ impl SystemAction {
| SystemAction::SearchPackages { .. } => Risk::Low, | SystemAction::SearchPackages { .. } => Risk::Low,
SystemAction::History => Risk::Low, SystemAction::History => Risk::Low,
SystemAction::InspectUpdates => Risk::Low, SystemAction::InspectUpdates => Risk::Low,
SystemAction::RollbackStatus => Risk::Low, SystemAction::RollbackStatus | SystemAction::SystemStatus => Risk::Low,
SystemAction::FlatpakList => Risk::Low, SystemAction::FlatpakList => Risk::Low,
SystemAction::ChoosePackage { .. } SystemAction::ChoosePackage { .. }
| SystemAction::SnapFind { .. } | SystemAction::SnapFind { .. }
@ -603,6 +606,7 @@ impl SystemAction {
| SystemAction::History | SystemAction::History
| SystemAction::InspectUpdates | SystemAction::InspectUpdates
| SystemAction::RollbackStatus | SystemAction::RollbackStatus
| SystemAction::SystemStatus
| SystemAction::FlatpakList | SystemAction::FlatpakList
| SystemAction::ChoosePackage { .. } | SystemAction::ChoosePackage { .. }
| SystemAction::SnapFind { .. } | SystemAction::SnapFind { .. }
@ -767,7 +771,8 @@ impl SystemAction {
| SystemAction::UpdateSystem | SystemAction::UpdateSystem
| SystemAction::PrepareUpdates | SystemAction::PrepareUpdates
| SystemAction::InspectUpdates | SystemAction::InspectUpdates
| SystemAction::RollbackStatus => Ok(()), | SystemAction::RollbackStatus
| SystemAction::SystemStatus => Ok(()),
SystemAction::ChoosePackage { name, .. } => { SystemAction::ChoosePackage { name, .. } => {
if valid_package_spec(name) { if valid_package_spec(name) {
Ok(()) Ok(())
@ -1445,12 +1450,25 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
return Some(SystemAction::PackageOwners { path }); return Some(SystemAction::PackageOwners { path });
} }
} }
if t == "updates" || t == "check updates" || t == "check for updates" || t == "update check" { if t == "update"
|| t == "updates"
|| t == "check updates"
|| t == "check for updates"
|| t == "update check"
{
return Some(SystemAction::CheckUpdates { backend: None }); return Some(SystemAction::CheckUpdates { backend: None });
} }
if t == "apply updates" || t == "upgrade" || t == "upgrade system" || t == "install updates" { if t == "apply updates" || t == "upgrade" || t == "upgrade system" || t == "install updates" {
return Some(SystemAction::ApplyUpdates { backend: None }); return Some(SystemAction::ApplyUpdates { backend: None });
} }
if t == "status"
|| t == "health"
|| t == "check"
|| t == "system status"
|| t == "system health"
{
return Some(SystemAction::SystemStatus);
}
// Flatpak verbs. App ids are case-sensitive (`org.chromium.Chromium`), so // Flatpak verbs. App ids are case-sensitive (`org.chromium.Chromium`), so
// the operands are read from the original text, not the lowercased copy. // the operands are read from the original text, not the lowercased copy.
@ -1720,7 +1738,7 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
if t == "history" || t.starts_with("history ") { if t == "history" || t.starts_with("history ") {
return Some(SystemAction::History); return Some(SystemAction::History);
} }
if t == "update" || t == "update system" || t == "sys update" { if t == "update system" || t == "sys update" || t == "emerge @world" {
return Some(SystemAction::UpdateSystem); return Some(SystemAction::UpdateSystem);
} }
if t.contains("prepare") && t.contains("update") { if t.contains("prepare") && t.contains("update") {
@ -2521,5 +2539,34 @@ mod tests {
name: "sshd".into() name: "sshd".into()
}) })
); );
assert_eq!(parse_natural("status"), Some(SystemAction::SystemStatus));
assert_eq!(parse_natural("health"), Some(SystemAction::SystemStatus));
assert_eq!(parse_natural("check"), Some(SystemAction::SystemStatus));
assert_eq!(
parse_natural("system status"),
Some(SystemAction::SystemStatus)
);
assert_eq!(
parse_natural("update"),
Some(SystemAction::CheckUpdates { backend: None })
);
assert_eq!(
parse_natural("updates"),
Some(SystemAction::CheckUpdates { backend: None })
);
assert_eq!(
parse_natural("upgrade"),
Some(SystemAction::ApplyUpdates { backend: None })
);
assert_eq!(
parse_natural("update system"),
Some(SystemAction::UpdateSystem)
);
let status_action = SystemAction::SystemStatus;
assert_eq!(status_action.risk(), Risk::Low);
assert!(!status_action.is_mutating());
assert!(!status_action.requires_root());
assert!(status_action.validate().is_ok());
} }
} }

View file

@ -225,6 +225,33 @@ pub fn kernel_versions_from_module_dirs(names: &[String]) -> Vec<String> {
.collect() .collect()
} }
/// Formats a BLS filename with boot counting attempts according to systemd-boot specification:
/// `<stem>+<tries>.conf` (or `<stem>.conf` if no counter).
pub fn format_bls_filename(stem: &str, tries: Option<u32>) -> String {
let clean_stem = stem.strip_suffix(".conf").unwrap_or(stem);
let (base, _) = parse_bls_filename(clean_stem);
match tries {
Some(t) => format!("{base}+{t}.conf"),
None => format!("{base}.conf"),
}
}
/// Parses a BLS filename into its base stem and optional remaining tries.
/// Follows the Boot Loader Specification: `<id>+<tries>[,<tries-done>].conf`
/// E.g., `phoebus+3.conf` -> ("phoebus", Some(3))
/// E.g., `phoebus+2,1.conf` -> ("phoebus", Some(2))
/// E.g., `phoebus.conf` -> ("phoebus", None)
pub fn parse_bls_filename(filename: &str) -> (String, Option<u32>) {
let name = filename.strip_suffix(".conf").unwrap_or(filename);
if let Some((stem, rest)) = name.split_once('+') {
let tries_str = rest.split(',').next().unwrap_or(rest);
if let Ok(tries) = tries_str.parse::<u32>() {
return (stem.to_string(), Some(tries));
}
}
(name.to_string(), None)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -319,4 +346,36 @@ mod tests {
assert!(versions.contains(&"6.12.9-gentoo".to_string())); assert!(versions.contains(&"6.12.9-gentoo".to_string()));
assert!(!versions.iter().any(|v| v == "modules.order")); assert!(!versions.iter().any(|v| v == "modules.order"));
} }
#[test]
fn bls_filename_counter_formatting_and_parsing() {
assert_eq!(format_bls_filename("phoebus", Some(3)), "phoebus+3.conf");
assert_eq!(
format_bls_filename("phoebus.conf", Some(3)),
"phoebus+3.conf"
);
assert_eq!(
format_bls_filename("phoebus+1.conf", Some(3)),
"phoebus+3.conf"
);
assert_eq!(format_bls_filename("phoebus", None), "phoebus.conf");
assert_eq!(format_bls_filename("phoebus+3.conf", None), "phoebus.conf");
assert_eq!(
parse_bls_filename("phoebus+3.conf"),
("phoebus".to_string(), Some(3))
);
assert_eq!(
parse_bls_filename("phoebus+2,1.conf"),
("phoebus".to_string(), Some(2))
);
assert_eq!(
parse_bls_filename("phoebus.conf"),
("phoebus".to_string(), None)
);
assert_eq!(
parse_bls_filename("phoebus-recovery.conf"),
("phoebus-recovery".to_string(), None)
);
}
} }

View file

@ -134,21 +134,24 @@ impl TransactionLog {
pub fn save(&self, path: &Path) -> Result<()> { pub fn save(&self, path: &Path) -> Result<()> {
use std::io::Write; use std::io::Write;
if let Some(parent) = path.parent() { let parent = path.parent().unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?; std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?;
}
let text = toml::to_string_pretty(self)?; let text = toml::to_string_pretty(self)?;
let mut file = std::fs::File::create(path).map_err(|e| CoreError::io(path, e))?; let tmp_path = parent.join(format!(
".{}.tmp.{}",
path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("transactions"),
std::process::id()
));
let mut file = std::fs::File::create(&tmp_path).map_err(|e| CoreError::io(&tmp_path, e))?;
file.write_all(text.as_bytes()) file.write_all(text.as_bytes())
.map_err(|e| CoreError::io(path, e))?; .map_err(|e| CoreError::io(&tmp_path, e))?;
// Make the record durable: an operation's outcome (including a file.sync_all().map_err(|e| CoreError::io(&tmp_path, e))?;
// "finished" update to an "in progress" record) must survive a power drop(file);
// loss, or the history would show a completed action as interrupted. std::fs::rename(&tmp_path, path).map_err(|e| CoreError::io(path, e))?;
file.sync_all().map_err(|e| CoreError::io(path, e))?; if let Ok(dir) = std::fs::File::open(parent) {
if let Some(parent) = path.parent() { let _ = dir.sync_all();
if let Ok(dir) = std::fs::File::open(parent) {
let _ = dir.sync_all();
}
} }
Ok(()) Ok(())
} }

View file

@ -7,6 +7,29 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// The stability channel used for system updates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum UpdateChannel {
/// Security, kernel, and core system packages only (glibc, systemd, btrfs-progs, pam, seatd).
Core,
/// Default workstation channel: bi-weekly vetted snapshots for desktop, Mesa, PipeWire.
#[default]
Proven,
/// Upstream rolling Gentoo tree (~amd64 / live testing).
Edge,
}
impl UpdateChannel {
pub fn as_str(&self) -> &'static str {
match self {
Self::Core => "core",
Self::Proven => "proven",
Self::Edge => "edge",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum PowerState { pub enum PowerState {

View file

@ -1260,6 +1260,16 @@ pub fn execute_inner(
return Err(ExecError::NotAuthorized(action.describe())); return Err(ExecError::NotAuthorized(action.describe()));
} }
let _lock = if action.is_mutating() && exec.is_real() && !exec.dry_run {
Some(crate::system_lock::SystemLock::acquire(
exec,
root,
&action.describe(),
)?)
} else {
None
};
// Rollback moves the root, `/var` and the boot selection together and takes // Rollback moves the root, `/var` and the boot selection together and takes
// its own pre-rollback snapshot, so it must not run through the generic // its own pre-rollback snapshot, so it must not run through the generic
// protective-snapshot path below. // protective-snapshot path below.
@ -1294,7 +1304,7 @@ pub fn execute_inner(
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?; let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
let source = root.to_string_lossy().to_string(); let source = root.to_string_lossy().to_string();
let record = let record =
snapshot::create_and_record(exec, auth, root, &source, &action.describe())?; snapshot::create_set_and_record(exec, auth, root, &source, &action.describe())?;
// Preserve the recovery point so callers can record it. // Preserve the recovery point so callers can record it.
snapshot_id = Some(record.id); snapshot_id = Some(record.id);
} else { } else {
@ -1800,6 +1810,7 @@ pub fn execute_inner(
state.note state.note
) )
} }
SystemAction::SystemStatus => crate::query::system_status_report(exec, root)?,
SystemAction::ConvertToSource { app } => convert_to_source(exec, root, app)?, SystemAction::ConvertToSource { app } => convert_to_source(exec, root, app)?,
SystemAction::BuildTunedKernel { make_default } => { SystemAction::BuildTunedKernel { make_default } => {
crate::kernel::build_tuned_kernel(exec, root, *make_default)? crate::kernel::build_tuned_kernel(exec, root, *make_default)?
@ -2433,6 +2444,16 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
assert!(outcome.snapshot.is_none()); assert!(outcome.snapshot.is_none());
} }
#[test]
fn system_status_action_executes_cleanly() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let action = SystemAction::SystemStatus;
let outcome = execute(&exec, &action, None, Path::new(&exec.root)).unwrap();
assert!(outcome.output.contains("=== Phoebus System Status ==="));
assert!(outcome.snapshot.is_none());
}
#[test] #[test]
fn depclean_is_previewed_as_structured_removals_at_review() { fn depclean_is_previewed_as_structured_removals_at_review() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();

View file

@ -0,0 +1,232 @@
//! Bubblewrap isolation boundary for userspace developer and desktop AI agents.
//!
//! While system-administration AI (`sys`) is isolated via `ProtectHome=yes` and
//! closed typed schemas, userspace developer agents (such as Claude Code, OpenCode,
//! Aider, or MCP tools) need broad permissions within a user's workspace to edit
//! code, run tests, and invoke compilers.
//!
//! To prevent the severe vulnerabilities seen in unconfined developer setups
//! (such as Omarchy 4.0's credential exposure and command injection risks), this
//! module provides an unprivileged Bubblewrap (`bwrap`) containment boundary that:
//! 1. Masks sensitive credential paths (`~/.ssh`, `~/.gnupg`, keyrings, `.aws`, etc.)
//! with private empty tmpfs mounts.
//! 2. Exposes core system binaries and libraries (`/usr`, `/lib`, `/nix/store`) as read-only.
//! 3. Binds the targeted workspace directory as writable and sets it as the working directory.
//! 4. Supports network isolation (offline mode) while enabling loopback communication.
use std::path::{Path, PathBuf};
use crate::command::{CommandOutput, CommandSpec};
use crate::error::{ExecError, Result};
use crate::exec::Exec;
/// List of sensitive subdirectories under `$HOME` that must be masked from
/// developer agents to prevent credential exfiltration.
pub const DEFAULT_SENSITIVE_SUBDIRS: &[&str] = &[
".ssh",
".gnupg",
".password-store",
".local/share/keyrings",
".config/gh",
".aws",
".config/gcloud",
".mozilla",
".config/BraveSoftware",
".kube",
];
/// Configuration for the userspace agent jail.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentJailConfig {
/// The workspace root where the agent has write permissions (e.g. `~/Source/project`).
pub workspace: PathBuf,
/// Whether external network access is permitted.
pub allow_network: bool,
/// Whether `/nix` store paths should be mounted read-only.
pub allow_nix_store: bool,
/// Additional subdirectories under home to mask with empty tmpfs.
pub extra_masked_subdirs: Vec<String>,
}
impl Default for AgentJailConfig {
fn default() -> Self {
Self {
workspace: PathBuf::from("."),
allow_network: true,
allow_nix_store: true,
extra_masked_subdirs: Vec::new(),
}
}
}
/// Whether the `bwrap` tool is installed in PATH.
pub fn is_bwrap_available() -> bool {
crate::exec::find_in_path("bwrap").is_some()
}
/// Pure builder for Bubblewrap arguments.
pub fn build_jail_argv(
config: &AgentJailConfig,
home: &Path,
program: &str,
args: &[String],
) -> Vec<String> {
let mut out: Vec<String> = vec![
"--die-with-parent".into(),
"--dev".into(),
"/dev".into(),
"--proc".into(),
"/proc".into(),
"--tmpfs".into(),
"/tmp".into(),
];
// Read-only system mounts
for sys_dir in ["/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc"] {
if Path::new(sys_dir).exists() {
out.push("--ro-bind".into());
out.push(sys_dir.into());
out.push(sys_dir.into());
}
}
// Read-only Nix store if enabled and present
if config.allow_nix_store && Path::new("/nix").exists() {
out.push("--ro-bind".into());
out.push("/nix".into());
out.push("/nix".into());
}
// Bind home directory
let home_str = home.to_string_lossy().to_string();
out.push("--bind".into());
out.push(home_str.clone());
out.push(home_str);
// Mask sensitive subdirectories under home with private empty tmpfs
let mut masked_subdirs: Vec<&str> = DEFAULT_SENSITIVE_SUBDIRS.to_vec();
let extra_refs: Vec<&str> = config
.extra_masked_subdirs
.iter()
.map(|s| s.as_str())
.collect();
masked_subdirs.extend(extra_refs);
for sensitive in masked_subdirs {
let sensitive_path = home.join(sensitive);
let path_str = sensitive_path.to_string_lossy().to_string();
out.push("--tmpfs".into());
out.push(path_str);
}
// Bind the workspace read-write and set working directory
let ws_str = config.workspace.to_string_lossy().to_string();
out.push("--bind".into());
out.push(ws_str.clone());
out.push(ws_str.clone());
out.push("--chdir".into());
out.push(ws_str);
// Network isolation
if !config.allow_network {
out.push("--unshare-net".into());
}
// Target executable and arguments
out.push(program.to_string());
out.extend(args.iter().cloned());
out
}
/// Run a program inside the Bubblewrap agent jail.
pub fn run_jailed(
exec: &Exec,
config: &AgentJailConfig,
home: &Path,
program: &str,
args: &[String],
) -> Result<CommandOutput> {
if !is_bwrap_available() {
return Err(ExecError::MissingTool(
"bwrap (required for user agent isolation; refusing to run unconfined)".into(),
));
}
let argv = build_jail_argv(config, home, program, args);
exec.run(CommandSpec::new("agent-jail", "run jailed user agent", "bwrap").args(argv))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jail_argv_masks_sensitive_credential_paths() {
let home = Path::new("/home/developer");
let ws = Path::new("/home/developer/Source/my-project");
let config = AgentJailConfig {
workspace: ws.to_path_buf(),
allow_network: true,
allow_nix_store: true,
extra_masked_subdirs: vec![".custom-secrets".into()],
};
let argv = build_jail_argv(&config, home, "cargo", &["build".into()]);
// Verify die-with-parent and dev/proc/tmp
assert!(argv.contains(&"--die-with-parent".to_string()));
assert!(argv.contains(&"--proc".to_string()));
assert!(argv.contains(&"--dev".to_string()));
// Verify home directory is bound
let home_idx = argv.iter().position(|a| a == "/home/developer").unwrap();
assert_eq!(argv[home_idx - 1], "--bind");
// Verify sensitive paths are masked with tmpfs
for sensitive in [
"/home/developer/.ssh",
"/home/developer/.gnupg",
"/home/developer/.password-store",
"/home/developer/.local/share/keyrings",
"/home/developer/.config/gh",
"/home/developer/.aws",
"/home/developer/.custom-secrets",
] {
let pos = argv
.iter()
.position(|a| a == sensitive)
.unwrap_or_else(|| panic!("missing tmpfs mask for {sensitive}"));
assert_eq!(
argv[pos - 1],
"--tmpfs",
"path {sensitive} not mounted with --tmpfs"
);
}
// Verify workspace is bound and chdir is set
let ws_str = "/home/developer/Source/my-project";
let ws_idx = argv.iter().position(|a| a == ws_str).unwrap();
assert_eq!(argv[ws_idx - 1], "--bind");
let chdir_idx = argv.iter().position(|a| a == "--chdir").unwrap();
assert_eq!(argv[chdir_idx + 1], ws_str);
// Verify program and args
let pos = argv.iter().position(|a| a == "cargo").unwrap();
assert_eq!(&argv[pos + 1..], &["build"]);
}
#[test]
fn jail_argv_unshares_net_when_offline() {
let home = Path::new("/home/developer");
let config = AgentJailConfig {
workspace: home.join("offline-repo"),
allow_network: false,
allow_nix_store: false,
extra_masked_subdirs: vec![],
};
let argv = build_jail_argv(&config, home, "python", &["-m".into(), "test".into()]);
assert!(argv.contains(&"--unshare-net".to_string()));
}
}

View file

@ -0,0 +1,146 @@
//! Automatic Boot Assessment and boot-counting lifecycle for Phoebus OS.
//!
//! Implements the systemd-boot Automatic Boot Assessment specification:
//! 1. When a new kernel or system update is installed, the primary BLS entry is
//! provisioned with boot counting attempts: `<entry-id>+3.conf`.
//! 2. systemd-boot decrements the counter on boot attempt (`+3` -> `+2` -> `+1` -> `+0`).
//! 3. If a kernel panic, initramfs failure, or boot loop prevents reaching `multi-user.target`,
//! tries reach 0 and systemd-boot automatically falls back to the unmetered recovery
//! snapshot BLS entry (`phoebus-recovery.conf`).
//! 4. When the system boots successfully and reaches `multi-user.target` with zero failed units,
//! `phoebus-boot-confirm.service` invokes `bootctl mark-good`, removing the counter and
//! cementing the entry as verified healthy.
use std::fs;
use std::path::{Path, PathBuf};
use phoebus_core::boot::{format_bls_filename, parse_bls_filename};
use crate::error::{ExecError, Result};
use crate::exec::Exec;
pub const DEFAULT_BOOT_TRIES: u32 = 3;
/// The systemd service unit definition that marks the boot good after reaching multi-user.target.
pub fn boot_confirm_unit() -> &'static str {
"[Unit]\n\
Description=Phoebus Boot Assessment Confirmation\n\
Documentation=man:bootctl(1)\n\
After=multi-user.target systemd-boot-check-no-failures.service\n\
WantedBy=multi-user.target\n\
ConditionPathExists=/run/systemd/boot-loader\n\
\n\
[Service]\n\
Type=oneshot\n\
RemainAfterExit=yes\n\
ExecStart=/usr/bin/bootctl mark-good\n\
\n\
[Install]\n\
WantedBy=multi-user.target\n"
}
/// Applies boot counting (`+<tries>.conf`) to all non-recovery entries in `entries_dir`
/// that do not currently have a boot counter.
pub fn enable_boot_counting(
entries_dir: &Path,
default_tries: u32,
) -> Result<Vec<(PathBuf, PathBuf)>> {
if !entries_dir.is_dir() {
return Ok(Vec::new());
}
let mut renamed = Vec::new();
let read_dir =
fs::read_dir(entries_dir).map_err(|e| ExecError::io(entries_dir.to_path_buf(), e))?;
for entry in read_dir {
let entry = entry.map_err(|e| ExecError::io(entries_dir.to_path_buf(), e))?;
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("conf") {
continue;
}
let file_name = entry.file_name().to_string_lossy().to_string();
if file_name.contains("recovery") {
continue;
}
let (stem, existing_counter) = parse_bls_filename(&file_name);
if existing_counter.is_none() {
let new_name = format_bls_filename(&stem, Some(default_tries));
let new_path = entries_dir.join(new_name);
fs::rename(&path, &new_path).map_err(|e| ExecError::io(path.clone(), e))?;
renamed.push((path, new_path));
}
}
Ok(renamed)
}
/// Installs and enables `phoebus-boot-confirm.service` in the target root.
pub fn install_boot_assessment_service(exec: &Exec) -> Result<()> {
let service_path = "etc/systemd/system/phoebus-boot-confirm.service";
exec.target().write(service_path, boot_confirm_unit())?;
exec.logger
.info("wrote /etc/systemd/system/phoebus-boot-confirm.service");
let wants_dir = "etc/systemd/system/multi-user.target.wants";
let wants_link = format!("{wants_dir}/phoebus-boot-confirm.service");
// Create multi-user.target.wants symlink
let target_wants = exec.root.join(wants_dir);
fs::create_dir_all(&target_wants).map_err(|e| ExecError::io(target_wants.clone(), e))?;
let link_path = exec.root.join(wants_link);
if !link_path.exists() {
let rel_target = Path::new("../phoebus-boot-confirm.service");
#[cfg(unix)]
std::os::unix::fs::symlink(rel_target, &link_path)
.map_err(|e| ExecError::io(link_path, e))?;
}
exec.logger
.info("enabled phoebus-boot-confirm.service in multi-user.target.wants");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unit_definition_calls_bootctl_mark_good() {
let unit = boot_confirm_unit();
assert!(unit.contains("ExecStart=/usr/bin/bootctl mark-good"));
assert!(unit.contains("After=multi-user.target"));
assert!(unit.contains("ConditionPathExists=/run/systemd/boot-loader"));
}
#[test]
fn enable_boot_counting_renames_entry_with_counter() {
let temp = tempfile::tempdir().unwrap();
let entries_dir = temp.path().join("loader/entries");
fs::create_dir_all(&entries_dir).unwrap();
// Standard entry
let std_entry = entries_dir.join("phoebus.conf");
fs::write(&std_entry, "title Phoebus\nlinux /linux\n").unwrap();
// Recovery entry (should not be touched)
let rec_entry = entries_dir.join("phoebus-recovery.conf");
fs::write(&rec_entry, "title Phoebus Recovery\nlinux /linux\n").unwrap();
// Pre-counted entry (should not be touched)
let counted_entry = entries_dir.join("phoebus-custom+2.conf");
fs::write(&counted_entry, "title Custom\nlinux /linux\n").unwrap();
let renamed = enable_boot_counting(&entries_dir, 3).unwrap();
assert_eq!(renamed.len(), 1);
assert_eq!(renamed[0].1.file_name().unwrap(), "phoebus+3.conf");
assert!(entries_dir.join("phoebus+3.conf").exists());
assert!(!entries_dir.join("phoebus.conf").exists());
assert!(entries_dir.join("phoebus-recovery.conf").exists());
assert!(entries_dir.join("phoebus-custom+2.conf").exists());
}
}

View file

@ -122,7 +122,7 @@ fn snap_on_host(root: &Path) -> bool {
} }
/// Read free storage for the filesystem containing `root` using `df -Pk`. /// Read free storage for the filesystem containing `root` using `df -Pk`.
fn free_mib(exec: &Exec, root: &Path) -> u64 { pub fn free_storage_mib(exec: &Exec, root: &Path) -> u64 {
let path = if root.exists() { let path = if root.exists() {
root.to_string_lossy().to_string() root.to_string_lossy().to_string()
} else { } else {
@ -191,7 +191,7 @@ pub fn hardware_facts(exec: &Exec, root: &Path) -> HardwareFacts {
arch, arch,
cores, cores,
memory_mib: hw.memory_mib, memory_mib: hw.memory_mib,
storage_free_mib: free_mib(exec, root), storage_free_mib: free_storage_mib(exec, root),
gpus, gpus,
wayland, wayland,
binhost_available, binhost_available,

View file

@ -133,6 +133,9 @@ pub trait ProcessRunner: Send + Sync {
fn is_streaming(&self) -> bool { fn is_streaming(&self) -> bool {
false false
} }
fn is_real(&self) -> bool {
false
}
} }
/// The real process runner. /// The real process runner.
@ -156,6 +159,10 @@ impl ProcessRunner for RealRunner {
self.sink.is_some() self.sink.is_some()
} }
fn is_real(&self) -> bool {
true
}
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> { fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
let start = Instant::now(); let start = Instant::now();
let mut command = Command::new(&spec.program); let mut command = Command::new(&spec.program);

View file

@ -0,0 +1,401 @@
//! Safe, typed desktop configuration and checkpoint engine for MangoWM + DankMaterialShell.
//!
//! Unlike Omarchy's unvetted Bash glue scripts which risk command injection and
//! desktop corruption, Phoebus OS uses schema-validated configuration mutations
//! paired with an automatic checkpoint/undo mechanism.
//!
//! When an AI agent (or user) modifies desktop settings (accent colors, themes,
//! or window manager keybindings):
//! 1. Inputs are validated against known schemas (e.g. valid hex colors, safe key combinations).
//! 2. An automatic checkpoint snapshot is recorded before applying changes.
//! 3. Changes are written atomically.
//! 4. If the desktop behavior breaks or is undesired, `undo()` restores the previous checkpoint.
use std::fs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::error::{ExecError, Result};
/// Theme options for DarkMaterialShell (DMS).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct DmsThemeConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub accent_color: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dark_mode: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub wallpaper_path: Option<String>,
}
impl DmsThemeConfig {
/// Validates the theme values (e.g. hex colors, file paths).
pub fn validate(&self) -> Result<()> {
if let Some(ref color) = self.accent_color {
if !is_valid_hex_color(color) {
return Err(ExecError::operation(
"desktop",
"theme_validate",
format!(
"invalid accent color '{color}': must be a 6-digit hex string (#RRGGBB)"
),
));
}
}
if let Some(ref wp) = self.wallpaper_path {
if wp.contains('\0') || wp.contains('\n') {
return Err(ExecError::operation(
"desktop",
"theme_validate",
"wallpaper path contains control characters",
));
}
}
Ok(())
}
}
/// A validated keybinding for MangoWM.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MangoKeybinding {
pub combo: String,
pub action: String,
}
impl MangoKeybinding {
pub fn validate(&self) -> Result<()> {
let trimmed_combo = self.combo.trim();
if trimmed_combo.is_empty() {
return Err(ExecError::operation(
"desktop",
"keybinding_validate",
"key combo cannot be empty",
));
}
if trimmed_combo.contains('\0') || trimmed_combo.contains('\n') {
return Err(ExecError::operation(
"desktop",
"keybinding_validate",
"key combo contains control characters",
));
}
let trimmed_action = self.action.trim();
if trimmed_action.is_empty() {
return Err(ExecError::operation(
"desktop",
"keybinding_validate",
"action cannot be empty",
));
}
if trimmed_action.contains('\0') || trimmed_action.contains('\n') {
return Err(ExecError::operation(
"desktop",
"keybinding_validate",
"action contains control characters",
));
}
Ok(())
}
}
/// Validates whether a string is a `#RRGGBB` hex color.
pub fn is_valid_hex_color(s: &str) -> bool {
if !s.starts_with('#') {
return false;
}
let hex_part = &s[1..];
if hex_part.len() != 6 {
return false;
}
hex_part.chars().all(|c| c.is_ascii_hexdigit())
}
/// Directory where desktop auto-checkpoints are saved for undo.
pub fn checkpoint_dir_for_home(home: &Path) -> PathBuf {
home.join(".local/state/phoebus/desktop-checkpoints")
}
/// Directory where DMS settings live.
pub fn dms_config_dir_for_home(home: &Path) -> PathBuf {
home.join(".config/dms")
}
/// File where MangoWM config lives.
pub fn mango_config_file_for_home(home: &Path) -> PathBuf {
home.join(".config/mango/config.toml")
}
/// Records a snapshot checkpoint of the current desktop configuration before a mutation.
pub fn create_checkpoint(home: &Path, label: &str) -> Result<PathBuf> {
let cp_base = checkpoint_dir_for_home(home);
fs::create_dir_all(&cp_base).map_err(|e| ExecError::Io {
path: cp_base.clone(),
source: e,
})?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let safe_label: String = label
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect();
let snapshot_dir = cp_base.join(format!("{timestamp}_{safe_label}"));
fs::create_dir_all(&snapshot_dir).map_err(|e| ExecError::Io {
path: snapshot_dir.clone(),
source: e,
})?;
// Copy DMS config if present
let dms_dir = dms_config_dir_for_home(home);
let dms_theme_file = dms_dir.join("theme.json");
if dms_theme_file.exists() {
let dest = snapshot_dir.join("dms_theme.json");
fs::copy(&dms_theme_file, &dest).map_err(|e| ExecError::Io {
path: dest,
source: e,
})?;
}
// Copy Mango config if present
let mango_file = mango_config_file_for_home(home);
if mango_file.exists() {
let dest = snapshot_dir.join("mango_config.toml");
fs::copy(&mango_file, &dest).map_err(|e| ExecError::Io {
path: dest,
source: e,
})?;
}
// Write metadata
let meta = format!("timestamp={timestamp}\nlabel={label}\n");
let meta_file = snapshot_dir.join("metadata.ini");
fs::write(&meta_file, meta).map_err(|e| ExecError::Io {
path: meta_file,
source: e,
})?;
Ok(snapshot_dir)
}
/// Applies a theme configuration to DMS with schema validation and auto-checkpoint.
pub fn apply_dms_theme(home: &Path, theme: &DmsThemeConfig) -> Result<()> {
theme.validate()?;
// Create a safety checkpoint before writing
create_checkpoint(home, "pre_theme_change")?;
let dms_dir = dms_config_dir_for_home(home);
fs::create_dir_all(&dms_dir).map_err(|e| ExecError::Io {
path: dms_dir.clone(),
source: e,
})?;
let theme_file = dms_dir.join("theme.json");
let json_bytes = serde_json::to_vec_pretty(theme)
.map_err(|e| ExecError::operation("desktop", "dms_theme_serialize", e.to_string()))?;
// Atomic write
let tmp_file = dms_dir.join("theme.json.tmp");
fs::write(&tmp_file, json_bytes).map_err(|e| ExecError::Io {
path: tmp_file.clone(),
source: e,
})?;
fs::rename(&tmp_file, &theme_file).map_err(|e| ExecError::Io {
path: theme_file,
source: e,
})?;
Ok(())
}
/// Adds or updates a MangoWM keybinding with schema validation and auto-checkpoint.
pub fn add_mango_keybinding(home: &Path, keybinding: &MangoKeybinding) -> Result<()> {
keybinding.validate()?;
create_checkpoint(home, "pre_keybinding_change")?;
let mango_file = mango_config_file_for_home(home);
if let Some(parent) = mango_file.parent() {
fs::create_dir_all(parent).map_err(|e| ExecError::Io {
path: parent.to_path_buf(),
source: e,
})?;
}
let mut current_content = if mango_file.exists() {
fs::read_to_string(&mango_file).map_err(|e| ExecError::Io {
path: mango_file.clone(),
source: e,
})?
} else {
String::new()
};
let bind_entry = format!(
"\n# Keybinding added by agent\n[[keybinding]]\ncombo = \"{}\"\naction = \"{}\"\n",
keybinding.combo, keybinding.action
);
current_content.push_str(&bind_entry);
let tmp_file = mango_file.with_extension("toml.tmp");
fs::write(&tmp_file, current_content).map_err(|e| ExecError::Io {
path: tmp_file.clone(),
source: e,
})?;
fs::rename(&tmp_file, &mango_file).map_err(|e| ExecError::Io {
path: mango_file,
source: e,
})?;
Ok(())
}
/// Reverts the latest desktop configuration change using the latest recorded checkpoint.
pub fn undo_latest_checkpoint(home: &Path) -> Result<String> {
let cp_base = checkpoint_dir_for_home(home);
if !cp_base.exists() {
return Err(ExecError::operation(
"desktop",
"undo",
"no desktop checkpoints found to undo",
));
}
let mut entries = Vec::new();
let read_dir = fs::read_dir(&cp_base).map_err(|e| ExecError::Io {
path: cp_base.clone(),
source: e,
})?;
for entry in read_dir {
let entry = entry.map_err(|e| ExecError::Io {
path: cp_base.clone(),
source: e,
})?;
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
entries.push(entry.path());
}
}
entries.sort();
let latest = match entries.pop() {
Some(p) => p,
None => {
return Err(ExecError::operation(
"desktop",
"undo",
"no desktop checkpoints available to undo",
))
}
};
let dms_backup = latest.join("dms_theme.json");
if dms_backup.exists() {
let target = dms_config_dir_for_home(home).join("theme.json");
fs::copy(&dms_backup, &target).map_err(|e| ExecError::Io {
path: target,
source: e,
})?;
}
let mango_backup = latest.join("mango_config.toml");
if mango_backup.exists() {
let target = mango_config_file_for_home(home);
fs::copy(&mango_backup, &target).map_err(|e| ExecError::Io {
path: target,
source: e,
})?;
}
let dir_name = latest
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
// Clean up the restored checkpoint
let _ = fs::remove_dir_all(&latest);
Ok(dir_name)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_color_validation() {
assert!(is_valid_hex_color("#1a1b26"));
assert!(is_valid_hex_color("#FFFFFF"));
assert!(is_valid_hex_color("#000000"));
assert!(!is_valid_hex_color("1a1b26")); // missing #
assert!(!is_valid_hex_color("#1a1b2")); // too short
assert!(!is_valid_hex_color("#1a1b2677")); // too long
assert!(!is_valid_hex_color("#gggggg")); // invalid hex
}
#[test]
fn dms_theme_validation_rejects_bad_colors() {
let theme = DmsThemeConfig {
accent_color: Some("bad-color".into()),
dark_mode: Some(true),
wallpaper_path: None,
};
assert!(theme.validate().is_err());
}
#[test]
fn mango_keybinding_rejects_empty_and_control_chars() {
let empty_combo = MangoKeybinding {
combo: "".into(),
action: "spawn kitty".into(),
};
assert!(empty_combo.validate().is_err());
let newline_action = MangoKeybinding {
combo: "Mod4+Return".into(),
action: "spawn kitty\nrm -rf /".into(),
};
assert!(newline_action.validate().is_err());
}
#[test]
fn apply_theme_creates_checkpoint_and_undo_restores() {
let temp_dir = tempfile::tempdir().unwrap();
let home = temp_dir.path();
// 1. Initial theme
let theme1 = DmsThemeConfig {
accent_color: Some("#112233".into()),
dark_mode: Some(true),
wallpaper_path: None,
};
apply_dms_theme(home, &theme1).unwrap();
let theme_file = dms_config_dir_for_home(home).join("theme.json");
let content1 = fs::read_to_string(&theme_file).unwrap();
assert!(content1.contains("#112233"));
// 2. Mutated theme by agent
let theme2 = DmsThemeConfig {
accent_color: Some("#445566".into()),
dark_mode: Some(false),
wallpaper_path: None,
};
apply_dms_theme(home, &theme2).unwrap();
let content2 = fs::read_to_string(&theme_file).unwrap();
assert!(content2.contains("#445566"));
// 3. Undo restores previous theme
let restored = undo_latest_checkpoint(home).unwrap();
assert!(!restored.is_empty());
let content_restored = fs::read_to_string(&theme_file).unwrap();
assert!(content_restored.contains("#112233"));
}
}

View file

@ -37,6 +37,10 @@ impl Exec {
TargetRoot::new(self.root.clone()) TargetRoot::new(self.root.clone())
} }
pub fn is_real(&self) -> bool {
self.runner.is_real()
}
pub fn register_secret(&self, secret: &SecretString) { pub fn register_secret(&self, secret: &SecretString) {
self.logger.register_secret(secret); self.logger.register_secret(secret);
} }

View file

@ -6,13 +6,16 @@
pub mod actions; pub mod actions;
pub mod admin; pub mod admin;
pub mod agent_jail;
pub mod ai; pub mod ai;
pub mod appimage; pub mod appimage;
pub mod auth; pub mod auth;
pub mod boot; pub mod boot;
pub mod boot_assessment;
pub mod chooser; pub mod chooser;
pub mod command; pub mod command;
pub mod desktop; pub mod desktop;
pub mod desktop_config;
pub mod ebuild; pub mod ebuild;
pub mod encryption; pub mod encryption;
pub mod error; pub mod error;
@ -38,6 +41,7 @@ pub mod snapshot;
pub mod stage3; pub mod stage3;
pub mod storage; pub mod storage;
pub mod sys_runtime; pub mod sys_runtime;
pub mod system_lock;
pub mod transaction; pub mod transaction;
pub mod update; pub mod update;
pub mod users; pub mod users;
@ -49,3 +53,4 @@ pub use command::{
pub use error::{CommandFailure, ExecError, Result}; pub use error::{CommandFailure, ExecError, Result};
pub use exec::Exec; pub use exec::Exec;
pub use log::{CommandRecord, Logger}; pub use log::{CommandRecord, Logger};
pub use system_lock::SystemLock;

View file

@ -371,12 +371,16 @@ impl UserStorage {
)); ));
} }
Err(e) if e.kind() == std::io::ErrorKind::NotFound => { Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
std::fs::create_dir(&cur).map_err(|e| ExecError::io(cur.clone(), e))?; match std::fs::create_dir(&cur) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(ExecError::io(cur.clone(), e)),
}
#[cfg(unix)] #[cfg(unix)]
{ {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&cur, std::fs::Permissions::from_mode(0o700)) let _ =
.map_err(|e| ExecError::io(cur.clone(), e))?; std::fs::set_permissions(&cur, std::fs::Permissions::from_mode(0o700));
} }
if ownership.needs_fix() { if ownership.needs_fix() {
fixer fixer

View file

@ -1461,6 +1461,146 @@ pub fn apply_updates(
Ok(report) Ok(report)
} }
/// Comprehensive overview of system health, bootloader state, storage headroom,
/// reboot requirements, and package lane readiness.
pub fn system_status_report(exec: &Exec, root: &Path) -> Result<String> {
let mut out = String::new();
out.push_str("=== Phoebus System Status ===\n\n");
// 1. Boot & Kernel Assessment
out.push_str("[Boot & Kernel]\n");
let mut entries_found = Vec::new();
for candidate_dir in [
root.join("efi/loader/entries"),
root.join("boot/loader/entries"),
root.join("boot/efi/loader/entries"),
] {
if candidate_dir.is_dir() {
if let Ok(rd) = std::fs::read_dir(&candidate_dir) {
for e in rd.flatten() {
let path = e.path();
if path.extension().and_then(|x| x.to_str()) == Some("conf") {
if let Some(fname) = path.file_name().and_then(|n| n.to_str()) {
let (stem, tries) = phoebus_core::boot::parse_bls_filename(fname);
entries_found.push((fname.to_string(), stem, tries));
}
}
}
}
if !entries_found.is_empty() {
break;
}
}
}
if entries_found.is_empty() {
out.push_str(" BLS Entries: None detected in /efi or /boot\n");
} else {
out.push_str(" BLS Boot Entries:\n");
for (fname, stem, tries) in &entries_found {
let assessment = match tries {
Some(t) => format!("assessment in progress ({t} tries remaining)"),
None if stem.contains("recovery") => "recovery fallback".into(),
None => "verified good".into(),
};
out.push_str(&format!(" - {fname} [{assessment}]\n"));
}
}
// 2. Reboot & Rollback State
out.push_str("\n[Reboot & Recovery State]\n");
let reboot_flag =
root.join("run/reboot-required").exists() || root.join("var/run/reboot-required").exists();
let rollback_state = crate::rollback::load_state(root);
let reboot_status =
if rollback_state.status == phoebus_core::rollback::RollbackStatus::Activated {
format!(
"REQUIRED (rollback activated to target `{}`; reboot to complete switch)",
rollback_state.target_snapshot
)
} else if reboot_flag {
"REQUIRED (system updates pending reboot)".to_string()
} else {
"None (running system configuration is current)".to_string()
};
out.push_str(&format!(" Reboot Required: {reboot_status}\n"));
out.push_str(&format!(
" Rollback Engine: {:?} (target: {}, root: {})\n",
rollback_state.status,
if rollback_state.target_snapshot.is_empty() {
"(none)"
} else {
&rollback_state.target_snapshot
},
rollback_state.root_subvol
));
// 3. Storage Headroom & Gates
out.push_str("\n[Storage & Safety Gates]\n");
let free_mib = crate::chooser::free_storage_mib(exec, root);
let free_gib = (free_mib as f64) / 1024.0;
let gate_status = if free_mib >= crate::update::MIN_UPDATE_FREE_SPACE_MIB {
"HEALTHY (meets >= 10 GiB gate)"
} else if free_mib == 0 {
"UNKNOWN (cannot determine free space)"
} else {
"WARNING (below 10 GiB safety gate; updates will be refused)"
};
out.push_str(&format!(
" Root Free Space: {:.1} GiB [{gate_status}]\n",
free_gib
));
// 4. Btrfs Snapshots
out.push_str("\n[Btrfs Recovery Snapshots]\n");
let history = crate::snapshot::read_history(root).unwrap_or_default();
out.push_str(&format!(
" Committed Snapshots: {}\n",
history.records.len()
));
if let Some(newest) = history.records.last() {
out.push_str(&format!(
" Newest Recovery Point: {} ({}) [{:?}]\n",
newest.id, newest.operation, newest.status
));
}
// 5. Package Lanes Readiness
out.push_str("\n[Package Lanes Readiness]\n");
let facts = crate::chooser::hardware_facts(exec, root);
let lanes = [
(Backend::PortageSource, "Portage (Source)", true),
(
Backend::PortageBinary,
"Portage (Binhost)",
facts.binhost_available,
),
(
Backend::Flatpak,
"Flatpak",
facts.available_backends.contains(&Backend::Flatpak),
),
(
Backend::Nix,
"Nix",
facts.available_backends.contains(&Backend::Nix),
),
(
Backend::Snap,
"Snap",
facts.available_backends.contains(&Backend::Snap),
),
(Backend::AppImage, "AppImage", true),
(Backend::CustomEbuild, "Custom Ebuild", true),
];
for (_backend, label, ready) in lanes {
let status = if ready { "READY" } else { "NOT CONFIGURED" };
out.push_str(&format!(" {:<20}: [{status}]\n", label));
}
Ok(out)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -2381,4 +2521,28 @@ mod tests {
assert!(!overview.sources[0].supported); assert!(!overview.sources[0].supported);
assert!(overview.sources[0].note.contains("AppImage")); assert!(overview.sources[0].note.contains("AppImage"));
} }
#[test]
fn system_status_report_renders_all_sections() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let root = Path::new(&exec.root);
// Populate a sample BLS entry with boot counting
let bls_dir = root.join("efi/loader/entries");
std::fs::create_dir_all(&bls_dir).unwrap();
std::fs::write(bls_dir.join("phoebus+3.conf"), "title Phoebus OS\n").unwrap();
std::fs::write(bls_dir.join("phoebus-recovery.conf"), "title Recovery\n").unwrap();
let report = system_status_report(&exec, root).unwrap();
assert!(report.contains("=== Phoebus System Status ==="));
assert!(report.contains("[Boot & Kernel]"));
assert!(report.contains("phoebus+3.conf [assessment in progress (3 tries remaining)]"));
assert!(report.contains("phoebus-recovery.conf [recovery fallback]"));
assert!(report.contains("[Reboot & Recovery State]"));
assert!(report.contains("[Storage & Safety Gates]"));
assert!(report.contains("[Btrfs Recovery Snapshots]"));
assert!(report.contains("[Package Lanes Readiness]"));
assert!(report.contains("Portage (Source)"));
}
} }

View file

@ -0,0 +1,237 @@
//! Inter-process system mutation lock.
//!
//! Ensures that only one mutating `sys` action runs at a time, preventing
//! transaction log corruption, Btrfs snapshot timestamp collisions, and
//! conflicting package manager operations.
//!
//! Uses atomic `O_CREAT | O_EXCL` file creation with automatic stale-lock recovery
//! (detects if the owning PID is no longer alive via `/proc/<pid>`).
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::{ExecError, Result};
use crate::exec::Exec;
pub const DEFAULT_LOCK_REL: &str = "run/phoebus/sys.lock";
#[derive(Debug)]
pub struct SystemLock {
lock_path: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct LockInfo {
pid: u32,
created_unix: u64,
operation: String,
}
impl LockInfo {
fn serialize(&self) -> String {
format!(
"pid={}\ncreated_unix={}\noperation={}\n",
self.pid, self.created_unix, self.operation
)
}
fn parse(text: &str) -> Option<Self> {
let mut pid = None;
let mut created_unix = None;
let mut operation = None;
for line in text.lines() {
if let Some(val) = line.strip_prefix("pid=") {
pid = val.trim().parse::<u32>().ok();
} else if let Some(val) = line.strip_prefix("created_unix=") {
created_unix = val.trim().parse::<u64>().ok();
} else if let Some(val) = line.strip_prefix("operation=") {
operation = Some(val.trim().to_string());
}
}
Some(Self {
pid: pid?,
created_unix: created_unix?,
operation: operation.unwrap_or_else(|| "unspecified operation".to_string()),
})
}
}
fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn is_pid_alive(pid: u32) -> bool {
if pid == 0 {
return false;
}
Path::new("/proc").join(pid.to_string()).exists()
}
pub fn lock_path(root: &Path) -> PathBuf {
root.join(DEFAULT_LOCK_REL)
}
impl SystemLock {
/// Attempt to acquire the system mutation lock for `operation`.
pub fn acquire(exec: &Exec, root: &Path, operation: &str) -> Result<Self> {
let path = lock_path(root);
Self::acquire_at(exec, path, operation)
}
/// Attempt to acquire the lock at an explicit path (used by tests and alternate paths).
pub fn acquire_at(exec: &Exec, path: PathBuf, operation: &str) -> Result<Self> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?;
}
let my_pid = std::process::id();
let now = now_unix();
let info = LockInfo {
pid: my_pid,
created_unix: now,
operation: operation.to_string(),
};
match Self::try_create(&path, &info) {
Ok(()) => {
exec.logger.info(format!(
"acquired system lock at {} for `{operation}`",
path.display()
));
Ok(Self { lock_path: path })
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
// Check if existing lock is stale
if let Ok(content) = fs::read_to_string(&path) {
if let Some(existing) = LockInfo::parse(&content) {
if !is_pid_alive(existing.pid) {
exec.logger.warn(format!(
"detected stale system lock held by dead PID {}; breaking lock",
existing.pid
));
let _ = fs::remove_file(&path);
// Retry atomic creation once
if Self::try_create(&path, &info).is_ok() {
exec.logger.info(format!(
"reclaimed stale system lock at {} for `{operation}`",
path.display()
));
return Ok(Self { lock_path: path });
}
} else {
return Err(ExecError::operation(
"sys",
"acquire system lock",
format!(
"another Phoebus system mutation is currently in progress: `{}` (PID {}, started {}s ago)",
existing.operation,
existing.pid,
now.saturating_sub(existing.created_unix)
),
));
}
}
}
Err(ExecError::operation(
"sys",
"acquire system lock",
format!(
"another Phoebus system mutation is currently in progress (lockfile present at {})",
path.display()
),
))
}
Err(e) => Err(ExecError::io(path, e)),
}
}
fn try_create(path: &Path, info: &LockInfo) -> std::io::Result<()> {
let mut file = OpenOptions::new().write(true).create_new(true).open(path)?;
file.write_all(info.serialize().as_bytes())?;
file.flush()?;
Ok(())
}
}
impl Drop for SystemLock {
fn drop(&mut self) {
if self.lock_path.exists() {
let _ = fs::remove_file(&self.lock_path);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::RecordingRunner;
use crate::log::Logger;
use phoebus_core::Redactor;
fn make_exec() -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(
Box::new(RecordingRunner::new()),
logger,
false,
path.join("root"),
path,
)
}
#[test]
fn lock_acquire_and_drop_lifecycle() {
let temp = tempfile::tempdir().unwrap();
let lock_file = temp.path().join("sys.lock");
let exec = make_exec();
{
let lock = SystemLock::acquire_at(&exec, lock_file.clone(), "install vim").unwrap();
assert!(lock_file.exists());
// Second acquisition must fail while held
let err = SystemLock::acquire_at(&exec, lock_file.clone(), "remove vim").unwrap_err();
assert!(err.to_string().contains("currently in progress"));
drop(lock);
}
// After drop, lock file is cleaned up and can be acquired again
assert!(!lock_file.exists());
let lock2 = SystemLock::acquire_at(&exec, lock_file.clone(), "install emacs").unwrap();
assert!(lock_file.exists());
drop(lock2);
}
#[test]
fn stale_lock_is_reclaimed_when_process_is_dead() {
let temp = tempfile::tempdir().unwrap();
let lock_file = temp.path().join("sys.lock");
let exec = make_exec();
// Write a lock with a PID guaranteed not to exist (e.g. 4194304 or similar high number)
let stale_info = LockInfo {
pid: 99999999,
created_unix: 1000,
operation: "interrupted update".into(),
};
fs::write(&lock_file, stale_info.serialize()).unwrap();
// Acquisition should detect dead PID and reclaim
let lock = SystemLock::acquire_at(&exec, lock_file.clone(), "new install").unwrap();
assert!(lock_file.exists());
let content = fs::read_to_string(&lock_file).unwrap();
let parsed = LockInfo::parse(&content).unwrap();
assert_eq!(parsed.pid, std::process::id());
assert_eq!(parsed.operation, "new install");
drop(lock);
}
}

View file

@ -23,6 +23,36 @@ pub fn state_path(root: &Path) -> PathBuf {
root.join("var/lib/phoebus/update-state.toml") root.join("var/lib/phoebus/update-state.toml")
} }
/// Minimum free space on root required to initiate a system update (10 GiB).
pub const MIN_UPDATE_FREE_SPACE_MIB: u64 = 10 * 1024;
/// Verifies preflight safety gates before starting a system update.
///
/// Refuses the update if free disk space is insufficient, preventing filesystem
/// fills and corruption during package unpack or compilation.
pub fn check_update_preflight(exec: &Exec, root: &Path) -> Result<()> {
let free_mib = crate::chooser::free_storage_mib(exec, root);
if free_mib > 0 && free_mib < MIN_UPDATE_FREE_SPACE_MIB {
return Err(ExecError::operation(
"update",
"preflight",
format!(
"insufficient storage: update requires at least 10 GiB of free space on / ({free_mib} MiB available)"
),
));
}
Ok(())
}
/// Takes a coordinated pre-update snapshot set (`@` and `@var`) before mutating system packages.
pub fn create_pre_update_snapshot_set(
exec: &Exec,
auth: &crate::auth::DestructiveAuthorization,
root: &Path,
) -> Result<phoebus_core::snapshot::SnapshotRecord> {
crate::snapshot::create_set_and_record(exec, auth, root, "@", "pre-update")
}
pub fn load_state(root: &Path) -> PrepareState { pub fn load_state(root: &Path) -> PrepareState {
let path = state_path(root); let path = state_path(root);
if !path.exists() { if !path.exists() {
@ -501,4 +531,54 @@ mod tests {
save_state(&exec, root, &state).unwrap(); save_state(&exec, root, &state).unwrap();
assert_eq!(load_state(root), state); assert_eq!(load_state(root), state);
} }
#[test]
fn check_update_preflight_allows_sufficient_space() {
use crate::command::CommandOutput;
use std::time::Duration;
let runner = RecordingRunner::new();
// 20 GiB available = 20 * 1024 * 1024 KiB = 20971520 KiB
let df_output = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/root 50000000 29028480 20971520 58% /\n";
runner.set_response(
"df",
CommandOutput {
status: 0,
success: true,
stdout: df_output.as_bytes().to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
},
);
let exec = make_exec(runner);
let root = Path::new(&exec.root);
assert!(check_update_preflight(&exec, root).is_ok());
}
#[test]
fn check_update_preflight_blocks_insufficient_space() {
use crate::command::CommandOutput;
use std::time::Duration;
let runner = RecordingRunner::new();
// 5 GiB available = 5 * 1024 * 1024 KiB = 5242880 KiB (< 10 GiB)
let df_output = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/root 50000000 44757120 5242880 90% /\n";
runner.set_response(
"df",
CommandOutput {
status: 0,
success: true,
stdout: df_output.as_bytes().to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
},
);
let exec = make_exec(runner);
let root = Path::new(&exec.root);
let err = check_update_preflight(&exec, root).unwrap_err();
assert!(
err.to_string().contains("insufficient storage"),
"unexpected error: {err}"
);
}
} }

View file

@ -0,0 +1,114 @@
//! `phoebus-agent-run` - Run userspace AI agents inside a secure Bubblewrap jail.
//!
//! Provides containment and credential masking for developer agents (Claude Code,
//! OpenCode, Aider, Cursor sidecars, etc.) without requiring root or modifying
//! system security.
//!
//! Key security protections:
//! - Sensitive credential stores (~/.ssh, ~/.gnupg, ~/.password-store, keyrings, .aws)
//! are masked with private empty tmpfs mounts.
//! - Core system paths (/usr, /lib, /etc, /nix) are mounted strictly read-only.
//! - The chosen workspace is writable and set as the current working directory.
//! - Optional --offline mode unshares the network namespace for local model reasoning.
use std::path::PathBuf;
use std::process::ExitCode;
use clap::Parser;
use phoebus_executor::agent_jail::{build_jail_argv, is_bwrap_available, AgentJailConfig};
#[derive(Parser, Debug)]
#[command(
name = "phoebus-agent-run",
about = "Run developer AI agents in a credential-masked Bubblewrap jail",
version
)]
struct Cli {
/// Workspace root directory where the agent has write permissions (default: current directory).
#[arg(long, short = 'w', default_value = ".")]
workspace: PathBuf,
/// Disallow external network access (offline mode).
#[arg(long)]
offline: bool,
/// Disallow mounting the /nix store.
#[arg(long)]
no_nix: bool,
/// Additional relative subdirectories under $HOME to mask with tmpfs.
#[arg(long = "mask")]
extra_masks: Vec<String>,
/// Print the bwrap command and arguments without executing.
#[arg(long)]
dry_run: bool,
/// Command / agent executable to run (e.g. claude, opencode, bash).
program: String,
/// Arguments to pass to the agent executable.
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
}
fn main() -> ExitCode {
let cli = Cli::parse();
if !is_bwrap_available() {
eprintln!(
"phoebus-agent-run: error: bwrap (Bubblewrap) is not available in PATH.\n\
Refusing to run the agent unconfined."
);
return ExitCode::FAILURE;
}
let home = match std::env::var("HOME").map(PathBuf::from) {
Ok(h) => h,
Err(_) => {
eprintln!("phoebus-agent-run: error: HOME environment variable is not set.");
return ExitCode::FAILURE;
}
};
let canonical_ws = match cli.workspace.canonicalize() {
Ok(p) => p,
Err(e) => {
eprintln!(
"phoebus-agent-run: error: cannot resolve workspace path '{}': {e}",
cli.workspace.display()
);
return ExitCode::FAILURE;
}
};
let config = AgentJailConfig {
workspace: canonical_ws,
allow_network: !cli.offline,
allow_nix_store: !cli.no_nix,
extra_masked_subdirs: cli.extra_masks,
};
let argv = build_jail_argv(&config, &home, &cli.program, &cli.args);
if cli.dry_run {
println!("bwrap {}", argv.join(" "));
return ExitCode::SUCCESS;
}
let status = std::process::Command::new("bwrap").args(&argv).status();
match status {
Ok(s) => {
if s.success() {
ExitCode::SUCCESS
} else {
ExitCode::from(s.code().unwrap_or(1) as u8)
}
}
Err(e) => {
eprintln!("phoebus-agent-run: failed to spawn bwrap: {e}");
ExitCode::FAILURE
}
}
}

View file

@ -0,0 +1,157 @@
//! `phoebus-desktop` - Safe, typed desktop configuration utility for MangoWM + DMS.
//!
//! Provides schema-validated inspection, theme updating, and keybinding management
//! with automatic checkpointing and one-click undo support.
use std::path::PathBuf;
use std::process::ExitCode;
use clap::{Parser, Subcommand};
use phoebus_executor::desktop_config::{
add_mango_keybinding, apply_dms_theme, dms_config_dir_for_home, undo_latest_checkpoint,
DmsThemeConfig, MangoKeybinding,
};
#[derive(Parser, Debug)]
#[command(
name = "phoebus-desktop",
about = "Safe desktop configuration and checkpoint manager for MangoWM + DMS",
version
)]
struct Cli {
/// Override the user's home directory.
#[arg(long)]
home: Option<PathBuf>,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Manage DarkMaterialShell themes.
Theme {
#[command(subcommand)]
sub: ThemeCommands,
},
/// Manage MangoWM keybindings.
Keybinding {
#[command(subcommand)]
sub: KeybindingCommands,
},
/// Revert the latest desktop configuration modification.
Undo,
}
#[derive(Subcommand, Debug)]
enum ThemeCommands {
/// Get the current DMS theme configuration.
Get,
/// Set theme properties with an automatic undo checkpoint.
Set {
/// Accent color hex string (e.g. #7aa2f7).
#[arg(long)]
accent: Option<String>,
/// Enable or disable dark mode.
#[arg(long)]
dark: Option<bool>,
/// Path to the desktop wallpaper image.
#[arg(long)]
wallpaper: Option<String>,
},
}
#[derive(Subcommand, Debug)]
enum KeybindingCommands {
/// Add a keybinding to MangoWM config with an automatic undo checkpoint.
Add {
/// Key combination (e.g. Mod4+Return).
#[arg(long)]
combo: String,
/// Action to execute (e.g. spawn kitty).
#[arg(long)]
action: String,
},
}
fn main() -> ExitCode {
let cli = Cli::parse();
let home = cli.home.unwrap_or_else(|| {
std::env::var("HOME")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("."))
});
match cli.command {
Commands::Theme { sub } => match sub {
ThemeCommands::Get => {
let theme_file = dms_config_dir_for_home(&home).join("theme.json");
if theme_file.exists() {
match std::fs::read_to_string(&theme_file) {
Ok(content) => {
println!("{content}");
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("phoebus-desktop: error reading theme: {e}");
ExitCode::FAILURE
}
}
} else {
println!("Default DMS theme (no custom theme.json found).");
ExitCode::SUCCESS
}
}
ThemeCommands::Set {
accent,
dark,
wallpaper,
} => {
let theme = DmsThemeConfig {
accent_color: accent,
dark_mode: dark,
wallpaper_path: wallpaper,
};
match apply_dms_theme(&home, &theme) {
Ok(()) => {
println!("Theme applied successfully. Automatic checkpoint saved.");
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("phoebus-desktop: error applying theme: {e}");
ExitCode::FAILURE
}
}
}
},
Commands::Keybinding { sub } => match sub {
KeybindingCommands::Add { combo, action } => {
let kb = MangoKeybinding { combo, action };
match add_mango_keybinding(&home, &kb) {
Ok(()) => {
println!(
"Keybinding '{}' added successfully. Automatic checkpoint saved.",
kb.combo
);
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("phoebus-desktop: error adding keybinding: {e}");
ExitCode::FAILURE
}
}
}
},
Commands::Undo => match undo_latest_checkpoint(&home) {
Ok(restored) => {
println!("Successfully restored desktop checkpoint: {restored}");
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("phoebus-desktop: undo failed: {e}");
ExitCode::FAILURE
}
},
}
}

View file

@ -90,6 +90,10 @@ struct Cli {
#[arg(long, short = 'y')] #[arg(long, short = 'y')]
yes: bool, yes: bool,
/// Prepare and stage a plan without executing it (userspace agent proposal).
#[arg(long)]
propose: bool,
/// Root directory of the target system. /// Root directory of the target system.
#[arg(long, default_value = "/")] #[arg(long, default_value = "/")]
root: PathBuf, root: PathBuf,
@ -320,7 +324,29 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
} }
let backend = backend_flag(&cli); let backend = backend_flag(&cli);
let full_phrase = cli.text.join(" "); let mut full_phrase = cli.text.join(" ");
// Check for "propose " or "please propose " prefix for userspace agent workflow
let mut cli = cli;
{
let mut p = full_phrase.trim();
for prefix in ["please ", "Please "] {
if let Some(rest) = p.strip_prefix(prefix) {
p = rest.trim();
break;
}
}
for prefix in ["propose ", "Propose "] {
if let Some(rest) = p.strip_prefix(prefix) {
p = rest.trim();
cli.propose = true;
break;
}
}
if cli.propose {
full_phrase = p.to_string();
}
}
// 4. Explicit legacy mode (--legacy) // 4. Explicit legacy mode (--legacy)
if cli.legacy { if cli.legacy {
@ -331,15 +357,59 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
let plan = service::plan_legacy_install(&plans, &exec, &cli.root, &request)?; let plan = service::plan_legacy_install(&plans, &exec, &cli.root, &request)?;
return render_and_execute_plan(&cli, &exec, &plans, plan); return render_and_execute_plan(&cli, &exec, &plans, plan);
} else { } else {
eprintln!("sys: legacy install requires an explicit package source flag."); let need = phoebus_core::selection::Need::new(&application);
eprintln!("Specify one of:"); let candidates = chooser::resolve_candidates(&exec, &cli.root, &need);
eprintln!(" sys install {application} --legacy --flatpak"); let available: Vec<_> = candidates.into_iter().filter(|c| c.available).collect();
eprintln!(" sys install {application} --legacy --portage");
eprintln!(" sys install {application} --legacy --nix"); if available.is_empty() {
eprintln!(" sys install {application} --legacy --snap"); eprintln!("sys: legacy install requires an explicit package source flag.");
eprintln!(" sys install {application} --legacy --appimage"); eprintln!(
eprintln!(" sys install {application} --legacy --ebuild"); "Specify one of:\n sys install {application} --legacy --flatpak\n \
return Err("legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)".into()); sys install {application} --legacy --portage\n \
sys install {application} --legacy --nix\n \
sys install {application} --legacy --snap\n \
sys install {application} --legacy --appimage\n \
sys install {application} --legacy --ebuild"
);
return Err(
"legacy install requires an explicit package source flag (--flatpak, \
--portage, --nix, --snap, --appimage, --ebuild)"
.into(),
);
} else if available.len() == 1 {
let b = available[0].backend;
let flag = backend_flag_name(b);
eprintln!("sys: legacy install requires an explicit package source flag.");
eprintln!(
"`{application}` is available via {}. In legacy mode, specify the source flag:",
b.as_str()
);
eprintln!(" sys install {application} --legacy --{flag}");
return Err(format!(
"legacy install requires an explicit package source flag: run `sys install {application} --legacy --{flag}`"
)
.into());
} else {
eprintln!("sys: legacy install requires an explicit package source flag.");
eprintln!(
"`{application}` is available from multiple package lanes. In legacy mode, choose a source:"
);
for c in &available {
let flag = backend_flag_name(c.backend);
let ver = c.version.as_deref().unwrap_or("latest");
eprintln!(
" sys install {application} --legacy --{:<10} # {} ({} via {})",
flag,
c.backend.as_str(),
ver,
c.provenance
);
}
return Err(
"legacy install requires an explicit package source flag: choose one of the commands above"
.into(),
);
}
} }
} }
if let Some(application) = parse_removal_text(&full_phrase) { if let Some(application) = parse_removal_text(&full_phrase) {
@ -446,6 +516,39 @@ fn apply_backend_filter(
SystemAction::CleanCache { .. } => SystemAction::CleanCache { SystemAction::CleanCache { .. } => SystemAction::CleanCache {
backend: Some(backend), backend: Some(backend),
}, },
SystemAction::InstallPackage { atom, .. } => match backend {
Backend::PortageSource => SystemAction::InstallPackage {
atom,
binary: Some(false),
},
Backend::PortageBinary => SystemAction::InstallPackage {
atom,
binary: Some(true),
},
Backend::PortageVendor => SystemAction::InstallPackage { atom, binary: None },
Backend::Flatpak => SystemAction::FlatpakInstall { app_id: atom },
Backend::Snap => SystemAction::SnapInstall {
name: atom,
channel: None,
classic: false,
},
Backend::Nix => SystemAction::NixPrepare {
packages: vec![atom],
},
other => {
return Err(
format!("install is not directly supported via {}", other.as_str()).into(),
);
}
},
SystemAction::RemovePackage { atom } => match backend {
Backend::Flatpak => SystemAction::FlatpakRemove { app_id: atom },
Backend::Snap => SystemAction::SnapRemove { name: atom },
_ if backend.is_portage() => SystemAction::RemovePackage { atom },
other => {
return Err(format!("remove is not supported via {}", other.as_str()).into());
}
},
other => { other => {
return Err(format!( return Err(format!(
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \ "--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \
@ -900,6 +1003,18 @@ fn render_and_execute_plan(
return Ok(()); return Ok(());
} }
if cli.propose {
println!("\nsys: plan proposed and staged successfully for elevation.");
println!(" Plan ID: {}", plan.id);
println!(" Digest: {}", plan.digest);
println!("To authorize and execute with root privilege, run:");
println!(
" sudo sys --broker --execute-plan {} --approval-digest {}",
plan.id, plan.digest
);
return Ok(());
}
if plan.requires_root && effective_uid() != 0 { if plan.requires_root && effective_uid() != 0 {
return Err("mutating actions require root; run `sudo sys ...`".into()); return Err("mutating actions require root; run `sudo sys ...`".into());
} }

View file

@ -0,0 +1,21 @@
[package]
name = "phoebus-mcp"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[[bin]]
name = "phoebus-mcp"
path = "src/main.rs"
[dependencies]
phoebus-core.workspace = true
phoebus-executor.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
clap.workspace = true
[dev-dependencies]
tempfile.workspace = true

View file

@ -0,0 +1,410 @@
//! Model Context Protocol (MCP) Server for Phoebus OS userspace agents.
//!
//! Exposes structured, schema-validated tools to external coding agents
//! (Claude Code, OpenCode, Cursor, Codex, Zed) over standard JSON-RPC 2.0 stdio.
//!
//! Instead of relying on fragile, injection-prone Bash glue scripts (the Omarchy anti-pattern),
//! this server exposes typed capabilities for:
//! - Inspecting and updating MangoWM & DarkMaterialShell desktop themes and keybindings
//! - Undoing desktop changes via automatic checkpoints
//! - Safe escalation: proposing system-level actions (`PreparedPlan`) that the user
//! can review and authenticate with Polkit through the privileged broker.
use std::path::Path;
use phoebus_executor::desktop_config::{
add_mango_keybinding, apply_dms_theme, dms_config_dir_for_home, undo_latest_checkpoint,
DmsThemeConfig, MangoKeybinding,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
pub const MCP_PROTOCOL_VERSION: &str = "2024-11-05";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpTool {
pub name: String,
pub description: String,
#[serde(rename = "inputSchema")]
pub input_schema: Value,
}
/// Returns the catalogue of available MCP tools.
pub fn available_tools() -> Vec<McpTool> {
vec![
McpTool {
name: "desktop_get_theme".into(),
description: "Get the current MangoWM and DarkMaterialShell theme settings.".into(),
input_schema: json!({
"type": "object",
"properties": {}
}),
},
McpTool {
name: "desktop_set_theme".into(),
description: "Apply a theme or accent color to DarkMaterialShell safely with an automatic undo checkpoint.".into(),
input_schema: json!({
"type": "object",
"properties": {
"accent_color": {
"type": "string",
"description": "6-digit hex color string starting with # (e.g. #7aa2f7)"
},
"dark_mode": {
"type": "boolean",
"description": "Whether dark mode is enabled"
},
"wallpaper_path": {
"type": "string",
"description": "Absolute path to the wallpaper image"
}
}
}),
},
McpTool {
name: "desktop_add_keybinding".into(),
description: "Add a new keybinding to MangoWM safely with an automatic undo checkpoint.".into(),
input_schema: json!({
"type": "object",
"properties": {
"combo": {
"type": "string",
"description": "Key combination (e.g. Mod4+Return or Mod4+Shift+d)"
},
"action": {
"type": "string",
"description": "Action or program to execute (e.g. spawn kitty)"
}
},
"required": ["combo", "action"]
}),
},
McpTool {
name: "desktop_undo".into(),
description: "Revert the latest desktop configuration change using the latest recorded checkpoint.".into(),
input_schema: json!({
"type": "object",
"properties": {}
}),
},
McpTool {
name: "system_propose_action".into(),
description: "Propose a system action (package install or service mutation) to the Phoebus privileged broker. Creates a reviewable plan requiring human Polkit authorization.".into(),
input_schema: json!({
"type": "object",
"properties": {
"action": {
"type": "string",
"description": "The typed action (e.g. install_package, flatpak_install, nix_prepare)"
},
"target": {
"type": "string",
"description": "The package atom or application identifier"
},
"reason": {
"type": "string",
"description": "Why this system change is required for the user's workspace"
}
},
"required": ["action", "target", "reason"]
}),
},
]
}
/// Executes an MCP tool call.
pub fn call_tool(name: &str, arguments: &Value, home: &Path) -> (Value, bool) {
match name {
"desktop_get_theme" => {
let theme_file = dms_config_dir_for_home(home).join("theme.json");
if theme_file.exists() {
match std::fs::read_to_string(&theme_file) {
Ok(content) => (json!({ "theme": content }), false),
Err(e) => (json!({ "error": e.to_string() }), true),
}
} else {
(
json!({ "status": "default (no custom theme.json found)" }),
false,
)
}
}
"desktop_set_theme" => {
let theme: DmsThemeConfig = match serde_json::from_value(arguments.clone()) {
Ok(t) => t,
Err(e) => return (json!({ "error": format!("invalid arguments: {e}") }), true),
};
match apply_dms_theme(home, &theme) {
Ok(()) => (
json!({ "status": "success", "message": "Theme applied with auto-checkpoint." }),
false,
),
Err(e) => (json!({ "error": e.to_string() }), true),
}
}
"desktop_add_keybinding" => {
let kb: MangoKeybinding = match serde_json::from_value(arguments.clone()) {
Ok(k) => k,
Err(e) => return (json!({ "error": format!("invalid arguments: {e}") }), true),
};
match add_mango_keybinding(home, &kb) {
Ok(()) => (
json!({
"status": "success",
"message": format!("Keybinding '{}' added with auto-checkpoint.", kb.combo)
}),
false,
),
Err(e) => (json!({ "error": e.to_string() }), true),
}
}
"desktop_undo" => match undo_latest_checkpoint(home) {
Ok(restored_label) => (
json!({
"status": "success",
"message": format!("Restored desktop checkpoint: {restored_label}")
}),
false,
),
Err(e) => (json!({ "error": e.to_string() }), true),
},
"system_propose_action" => {
let action = arguments
.get("action")
.and_then(Value::as_str)
.unwrap_or_default();
let target = arguments
.get("target")
.and_then(Value::as_str)
.unwrap_or_default();
let reason = arguments
.get("reason")
.and_then(Value::as_str)
.unwrap_or_default();
if action.is_empty() || target.is_empty() {
return (
json!({ "error": "both 'action' and 'target' must be non-empty" }),
true,
);
}
// Create proposal instructions for the user
let plan_summary = format!(
"System action proposed by agent:\n Action: {action}\n Target: {target}\n Reason: {reason}\n\nTo review and authorize with Polkit, run:\n sys please install {target}"
);
(
json!({
"status": "proposed",
"plan": {
"action": action,
"target": target,
"reason": reason,
},
"instructions": plan_summary,
}),
false,
)
}
unknown => (json!({ "error": format!("unknown tool: {unknown}") }), true),
}
}
/// Handles a single JSON-RPC line adhering to the Model Context Protocol specification.
pub fn handle_mcp_message(line: &str, home: &Path) -> Option<String> {
let req: Value = serde_json::from_str(line).ok()?;
let id = req.get("id");
let method = req.get("method")?.as_str()?;
match method {
"initialize" => {
let res = json!({
"jsonrpc": "2.0",
"id": id,
"result": {
"protocolVersion": MCP_PROTOCOL_VERSION,
"serverInfo": {
"name": "phoebus-mcp",
"version": env!("CARGO_PKG_VERSION")
},
"capabilities": {
"tools": {
"listChanged": false
}
}
}
});
Some(res.to_string())
}
"notifications/initialized" => {
// Notifications don't require a response
None
}
"ping" => {
let res = json!({
"jsonrpc": "2.0",
"id": id,
"result": {}
});
Some(res.to_string())
}
"tools/list" => {
let tools = available_tools();
let res = json!({
"jsonrpc": "2.0",
"id": id,
"result": {
"tools": tools
}
});
Some(res.to_string())
}
"tools/call" => {
let params = req.get("params")?;
let tool_name = params.get("name")?.as_str()?;
let arguments = params.get("arguments").cloned().unwrap_or(json!({}));
let (result_value, is_error) = call_tool(tool_name, &arguments, home);
let content_text = if is_error {
result_value
.get("error")
.and_then(Value::as_str)
.unwrap_or("tool execution error")
.to_string()
} else {
serde_json::to_string_pretty(&result_value).unwrap_or_default()
};
let res = json!({
"jsonrpc": "2.0",
"id": id,
"result": {
"content": [
{
"type": "text",
"text": content_text
}
],
"isError": is_error
}
});
Some(res.to_string())
}
_ => {
let res = json!({
"jsonrpc": "2.0",
"id": id,
"error": {
"code": -32601,
"message": format!("Method not found: {method}")
}
});
Some(res.to_string())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn initialize_and_tools_list_conformance() {
let temp_dir = tempfile::tempdir().unwrap();
let home = temp_dir.path();
// 1. Initialize
let init_req = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}"#;
let init_resp = handle_mcp_message(init_req, home).expect("response expected");
let val: Value = serde_json::from_str(&init_resp).unwrap();
assert_eq!(val["id"], 1);
assert_eq!(val["result"]["protocolVersion"], MCP_PROTOCOL_VERSION);
assert_eq!(val["result"]["serverInfo"]["name"], "phoebus-mcp");
// 2. Tools list
let list_req = r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#;
let list_resp = handle_mcp_message(list_req, home).expect("response expected");
let val: Value = serde_json::from_str(&list_resp).unwrap();
assert_eq!(val["id"], 2);
let tools = val["result"]["tools"].as_array().unwrap();
assert!(tools.iter().any(|t| t["name"] == "desktop_set_theme"));
assert!(tools.iter().any(|t| t["name"] == "desktop_add_keybinding"));
assert!(tools.iter().any(|t| t["name"] == "system_propose_action"));
assert!(tools.iter().any(|t| t["name"] == "desktop_undo"));
}
#[test]
fn tools_call_set_theme_and_undo() {
let temp_dir = tempfile::tempdir().unwrap();
let home = temp_dir.path();
// Call desktop_set_theme
let call_req = r##"{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "desktop_set_theme",
"arguments": {
"accent_color": "#7aa2f7",
"dark_mode": true
}
}
}"##;
let call_resp = handle_mcp_message(call_req, home).expect("response expected");
let val: Value = serde_json::from_str(&call_resp).unwrap();
assert_eq!(val["result"]["isError"], false);
// Verify theme written
let theme_file = dms_config_dir_for_home(home).join("theme.json");
assert!(theme_file.exists());
let content = std::fs::read_to_string(&theme_file).unwrap();
assert!(content.contains("#7aa2f7"));
// Call desktop_undo
let undo_req = r#"{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "desktop_undo",
"arguments": {}
}
}"#;
let undo_resp = handle_mcp_message(undo_req, home).expect("response expected");
let val: Value = serde_json::from_str(&undo_resp).unwrap();
assert_eq!(val["result"]["isError"], false);
}
#[test]
fn tools_call_system_propose_action() {
let temp_dir = tempfile::tempdir().unwrap();
let home = temp_dir.path();
let propose_req = r#"{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "system_propose_action",
"arguments": {
"action": "install_package",
"target": "dev-libs/openssl",
"reason": "needed for compilation in workspace"
}
}
}"#;
let resp = handle_mcp_message(propose_req, home).expect("response expected");
let val: Value = serde_json::from_str(&resp).unwrap();
assert_eq!(val["result"]["isError"], false);
let text = val["result"]["content"][0]["text"].as_str().unwrap();
assert!(text.contains("dev-libs/openssl"));
}
}

View file

@ -0,0 +1,50 @@
//! Model Context Protocol (MCP) server executable for Phoebus OS.
//!
//! Speaks JSON-RPC 2.0 over standard I/O, conforming to the MCP specification.
//! Used by Claude Code, Cursor, OpenCode, and Zed.
use std::io::{self, BufRead, Write};
use std::path::PathBuf;
use clap::Parser;
use phoebus_mcp::handle_mcp_message;
#[derive(Parser, Debug)]
#[command(
name = "phoebus-mcp",
about = "Model Context Protocol server for Phoebus OS desktop & developer agents"
)]
struct Cli {
/// Override the user's home directory (useful for testing or isolation).
#[arg(long)]
home: Option<PathBuf>,
}
fn main() {
let cli = Cli::parse();
let home = cli.home.unwrap_or_else(|| {
std::env::var("HOME")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("."))
});
let stdin = io::stdin();
let mut stdout = io::stdout();
for line in stdin.lock().lines() {
let line = match line {
Ok(l) => l,
Err(_) => break,
};
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if let Some(response) = handle_mcp_message(trimmed, &home) {
let _ = writeln!(stdout, "{response}");
let _ = stdout.flush();
}
}
}