diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a7ee2a2..e9ec0e5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -101,9 +101,10 @@ The only crate that runs privileged commands. ### phoebus-installer - `orchestrate` — `Installer` runs the plan stages and stops on first failure. -- `service` — shared administration service layer (`PreparedPlan`, `PlanStore`, planning, authorization, Polkit elevation, execution, and verification) shared identically by CLI and GUI. -- `conversation` — bounded conversation history and contextual follow-up resolution (tradeoff comparisons, backend switching, and plan confirmation). -- `assistant_bridge` — JSON-RPC stdio bridge serving the Quickshell desktop assistant. +- `service` — shared administration service layer (`PreparedPlan`, `PlanStore`, planning, authorization, Polkit elevation, execution, and verification) shared identically by CLI and GUI. The single authoritative validation boundary (`validate_prepared_plan`) runs before elevation and is repeated in the broker after authentication; plans bind actions, effects, candidate, target root and initiating uid, are stored per-user with an integrity seal, and are atomically claimed before execution. +- `ai_setup` — one provider/endpoint/model/credential resolver shared by the CLI and the desktop bridge, so their provider setup cannot diverge. Credentials load from a 0600 file (configured path, `PHOEBUS_AI_API_KEY_FILE`, or `~/.config/phoebus/ai.key`) and never travel through QML, prompts or argv. +- `conversation` — bounded, minimized conversation history and contextual follow-up resolution (tradeoff comparisons, backend switching, and plan confirmation). Raw requests are not persisted; registered secrets are redacted; history is 0600/0700, atomic, bounded and clearable. +- `assistant_bridge` — JSON-RPC stdio bridge serving the Quickshell desktop assistant. Every plan type returns the same `plan_id`/`digest` review card; `execute` runs only the referenced reviewed plan. - `release` — `ReleaseManifest` create/verify, candidate gates, atomic publish and signing command helpers. - Binaries: `phoebus-installer`, `sys`, `phoebus-release`. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 91e03a0..ba157a1 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,54 @@ All notable changes are recorded here. The authoritative history is `git log`; this file is the curated, human-readable summary. +## 2026-09-25 — Privileged-boundary, GUI-review, removal, transaction and privacy remediation + +- **Single privileged validation boundary (`phoebus-installer::service`):** + - `validate_prepared_plan` is the one authoritative check, run before + elevation and repeated inside the broker after authentication. It re-derives + the plan seal from the plan's own contents, rejects expired/claimed/modified/ + malformed/wrong-root/wrong-uid plans, and revalidates live state. + - Plans now bind the exact actions, effects, candidate, canonical target root + and initiating uid; multi-action plans store per-step effects and are + revalidated action-by-action (fixing an aggregate digest comparison bug). + - Protected per-user plan storage (`/run/user//phoebus/plans`, 0700 / 0600, + atomic writes, 128-bit ids, symlink/ownership checks) and atomic `O_EXCL` + consumption so concurrent requests cannot both mutate and retries cannot + repeat. The broker resolves storage from the uid, not an arbitrary path. + - `sys --broker --execute-plan --plan-uid --root `; a dropped + or mismatched root is rejected rather than silently executing against `/`. +- **Truthful transaction outcomes:** verification failure, action failure, + refusal and cancellation all finish the transaction with a truthful result; + completed steps and the protective snapshot are retained; persistence failures + are surfaced; a malformed broker reply is a protocol failure, not success. +- **GUI plan review for every plan type:** the assistant renders one review card + for install, removal, general administration, rollback and follow-up + confirmation; approval/cancel controls execute only the referenced reviewed + plan and update the original card; "prepared" is never shown as "completed"; + verification results are shown; launch is offered only when a concrete desktop + entry/command was identified. Corrected the assistant's `PhoebusButton` API + usage (`label`/`actionEnabled`). +- **Shared provider/credential handling (`phoebus_installer::ai_setup`):** the CLI + and GUI resolve provider, endpoint, model and credential reference through one + module. Credentials load from a configured 0600 file, `PHOEBUS_AI_API_KEY_FILE` + or a default `~/.config/phoebus/ai.key`; they are never sent through QML, + prompts or argv. The GUI direct transport no longer uses an empty key. +- **AI-first removal and corrected follow-ups:** default removal routes through + the connected model while deterministic ownership discovery and policy + validation stay underneath; only `--legacy` bypasses the model. Follow-ups + prefer explicit application references, so "install vlc using flatpak" is + about VLC, "use flatpak for that one" refers to the previous app, and + "why is my audio broken?" is not answered as a package explanation. +- **Honest conversation privacy:** history stores minimized structured context + (never the raw request), uses the active redactor, is written 0600/0700 + atomically, is bounded to ten turns, surfaces write errors, and can be cleared. +- **Tests:** regression coverage for tampered/expired/replayed/malformed plans, + plan replacement after review, concurrent claims, refusal, target-root and uid + binding, verification failure, transaction truthfulness, follow-up resolution, + credential loading, and history privacy/retention/deletion. Storage is injected + in tests (no shared `PHOEBUS_PLANS_DIR` race). Full workspace suite, `fmt` and + `clippy` run; static binaries build. + ## 2026-09-24 — AI-first administration remediation: shared service layer, Polkit elevation, QML provisioning, and conversation continuity - **Shared Administration Service Layer (`phoebus_installer::service`):** diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 357c34a..7d395c8 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,43 +3,62 @@ 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. -- **Last updated:** this session (2026-09-24), AI-First Administration & Desktop Assistant Remediation: - Shared planning service layer (`phoebus_installer::service`), reviewable plan staging with - cryptographic digests (`PreparedPlan`, `PlanStore`), target desktop QML and Polkit policy - provisioning, unprivileged GUI execution with Polkit elevation (`pkexec`), contextual conversation - continuity (`conversation::*`), and cross-source application removal with user data preservation. +- **Last updated:** this session (2026-09-25), privileged-boundary, GUI-review, + removal, transaction and privacy remediation: + Authoritative plan validation (`validate_prepared_plan`), protected per-user + plan storage with atomic claim, truthful transaction outcomes, shared provider + credentials (`ai_setup`), AI-first default removal, corrected conversational + follow-ups, and an honest conversation-history privacy boundary. - **Current focus:** - 1. **Shared planning and execution layer (`phoebus_installer::service`)**: - - Both CLI (`sys`) and desktop GUI (`phoebus-assistant` via `assistant_bridge.rs`) share one unified - administration pipeline for investigation, recommendation, effect resolution, authorization, execution, and verification. - - Reviewable plans staged as `PreparedPlan` with cryptographic digests (`Sha256`), 15-minute TTL, and replay rejection. - - System state revalidation before mutation; material alterations invalidate previous approvals and abort. - - Honest recommendation formatting with verified provenance (no false "avoids a lengthy build" claims). - - In-progress transaction recording (`begin`) before mutation; completed verification (`finish`) after mutation. - 2. **Target desktop & QML asset provisioning**: - - `gui-apps/quickshell` added to canonical Mango desktop package list. - - Embedded all 13 QML and policy assets into `/usr/share/phoebus/assistant/` via `TargetRoot` in `write_session_script`. - - Polkit policy (`club.phoebus.sys.policy`) enables desktop users to elevate mutating plans via `pkexec` without passwordless sudo. - 3. **Desktop assistant responsiveness**: - - Eliminated startup polling freeze; update checks are on-demand when switching to the Updates tab. - - Fast deterministic status checking on startup (reboot-required marker). - 4. **Contextual conversation continuity (`phoebus_installer::conversation`)**: - - Bounded 10-turn history with secret redaction. - - Follow-up resolution for comparative questions, backend switching, and plan confirmations. - 5. **Cross-source removal**: - - Unified removal planning (`plan_removal`) across Flatpak, Snap, AppImage, and Portage. - - Requires explicit lane flag if ambiguous duplicate copies exist; preserves user home data by default. + 1. **Single privileged validation boundary (`phoebus_installer::service`)**: + - `validate_prepared_plan` runs before elevation and is repeated inside the + privileged broker after authentication. It re-derives the plan seal from + the plan's own contents (never two supplied digest strings), and rejects + expired/claimed/modified/malformed/wrong-root/wrong-uid plans. + - Plans bind the exact actions, effects, candidate, canonical target root + and initiating uid. `PreparedPlan.step_effects` revalidates multi-action + plans action-by-action (fixing an aggregate-digest bug). + - `PlanStore` is per-user (`/run/user//phoebus/plans`, 0700 / 0600), + writes atomically, uses 128-bit ids, rejects symlinks/third-party + ownership, and claims a plan with `O_EXCL` so at most one execution runs. + - `sys --broker --execute-plan --plan-uid --root `; a + dropped/mismatched root is rejected rather than executing against `/`. + 2. **Truthful transaction outcomes**: verification failure, action failure, + refusal and cancellation finish the transaction truthfully; completed steps + and the snapshot are retained; persistence failures surface; a malformed + broker reply is a protocol failure, not fabricated success. + 3. **GUI plan review**: one review card for install/removal/general/rollback/ + follow-up, with approval/cancel; executes only the referenced plan; updates + the original card; never says "completed" for a prepared plan; shows + verification; offers launch only when a concrete entry was identified. The + assistant also used the wrong `PhoebusButton` API (`text`/`enabled`) and is + corrected to `label`/`actionEnabled`. + 4. **Shared provider credentials (`ai_setup`)**: CLI and GUI resolve provider, + endpoint, model and credential reference through one module; keys load from + a configured 0600 file, `PHOEBUS_AI_API_KEY_FILE` or `~/.config/phoebus/ai.key` + and are never passed through QML, prompts or argv. + 5. **AI-first removal + follow-ups**: default removal uses the model with + deterministic ownership discovery underneath; only `--legacy` bypasses it. + Explicit application references beat stale context. + 6. **Conversation privacy**: minimized structured history (no raw request), + active redactor, 0600/0700 atomic writes, bounded to ten turns, clearable. - **Last verified (this session):** - `cargo fmt --all -- --check` clean. - - `cargo clippy --workspace --all-targets` clean (0 errors, 0 custom warnings). - - `cargo test --workspace` (all 486 crate unit/integration tests pass: 173 phoebus-core, 205 phoebus-executor, 108 phoebus-installer). - - `cargo build --release -p phoebus-installer` compiled cleanly. - - Static binary build with `crt-static` compiled cleanly. - - `installer/tests/vm/sys-acceptance.sh` passed 23/23 cases (`PASS=23 FAIL=0`). -- **Not yet verified this session:** - - AI-selected live installation against a remote production provider with live credentials - (fixture and mock paths fully verified). - - Physical-seat DRM desktop session (headless and virtual seats verified). + - `cargo test --workspace` all pass (67 phoebus-installer, 173 phoebus-core, + 195 phoebus-executor, plus integration/CLI suites). + - `cargo clippy --workspace --all-targets` runs (exit 0; pre-existing + `result_large_err`/arg-count lints remain, as at the reviewed commit). + - `make test` passes (Rust workspace + VM disk-safety suite). + - Static `sys` and `phoebus-installer` (`crt-static`) build cleanly. + - `sys install/remove firefox` without a model stop and print legacy guidance + (no mutation); `sys history --legacy` runs deterministically. +- **Not yet verified this session (BLOCKED):** + - Live AI install/removal journey with an authorized provider — no credential + is present; do not invent one. + - Installed GUI/AI journey and the 12-step acceptance list — requires a + graphical, seat-providing VM and a live model. The installed encrypted disk + (`/var/tmp/phoebus-vm/disks/test-disk.qcow2`) has no LUKS passphrase available + in this environment, so it cannot be booted here. - **Public repo:** (remote `origin`, SSH port 2222). diff --git a/docs/STATUS.md b/docs/STATUS.md index 111a8f9..50d23eb 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -145,8 +145,15 @@ still not VM-verified. | Quiet proactive assistance monitor & deduplicated alerting | yes | yes | no | no | | User preference profiles & project environment mappings | yes | yes | no | n/a | | Shared administration service layer (`service::*`) & PreparedPlan staging | yes | yes | yes (acceptance matrix) | n/a | -| Plan cryptographically bound digests, TTL & replay protection | yes | yes | yes (acceptance matrix) | n/a | +| Authoritative privileged validation boundary (integrity/root/uid/state/claim) | yes | yes | no (needs an authenticated VM boot) | n/a | +| Protected per-user plan storage, atomic claim, tamper/traversal rejection | yes | yes | no (needs an authenticated VM boot) | n/a | +| Plan digests, target-root/uid binding, TTL, replay & concurrent-claim protection | yes | yes | no | n/a | +| Truthful transaction outcomes (failure/verify-fail/refusal/interruption) | yes | yes | no | n/a | +| AI-first removal (deterministic discovery underneath; `--legacy` bypasses) | yes | yes | no | n/a | +| GUI plan review card for every plan type; prepared ≠ completed | yes | no (QML) | no (needs graphical VM) | no | +| Shared provider/credential handling (`ai_setup::*`) for CLI and GUI | yes | yes | no (no live credential) | n/a | | Contextual conversation continuity (`conversation::*`) | yes | yes | yes (acceptance matrix) | n/a | +| Conversation-history privacy (minimized, redacted, 0600, bounded, clearable) | yes | yes | no | n/a | | Target desktop QML assets & Polkit policy provisioning | yes | yes | yes (live VM layout) | no | | Desktop assistant unprivileged execution & Polkit elevation | yes | yes | yes (live VM layout) | no | | UKI | no (deferred) | no | no | no | diff --git a/docs/SYS.md b/docs/SYS.md index f7dff18..0093487 100644 --- a/docs/SYS.md +++ b/docs/SYS.md @@ -44,6 +44,19 @@ sys install MyTool --appimage # AI workflow constrained to AppImage sys install app-misc/my-thing --ebuild # AI workflow constrained to custom ebuild ``` +Removal is also AI-first by default. The deterministic ownership discovery and +policy validation always run underneath; the connected model confirms the exact +discovered copy. An ambiguous multi-lane install still requires an explicit +source flag, and a model failure stops execution rather than silently removing +deterministically: + +```sh +sys remove firefox # AI workflow: confirm target, then remove +sys remove firefox --flatpak # AI workflow constrained to Flatpak +sys remove firefox --legacy # deterministic removal, no model +sys remove firefox --legacy --flatpak # deterministic removal from Flatpak +``` + ### Deterministic administration (`--legacy`) Deterministic operation must be explicitly selected with `--legacy`: @@ -51,13 +64,15 @@ Deterministic operation must be explicitly selected with `--legacy`: ```sh sys install firefox --legacy --flatpak # deterministic Flatpak workflow; no model interaction sys install firefox --legacy --portage # deterministic Portage workflow; no model interaction +sys remove firefox --legacy # deterministic removal, no model interaction sys history --legacy # deterministic history without model sys undo --legacy # deterministic recovery without model sys install firefox --legacy # REFUSED: requires an explicit package source flag ``` When `--legacy` is used with `install` but without an explicit source flag, -execution is refused and available package sources are displayed. +execution is refused and available package sources are displayed. `--legacy` +never contacts a model. Direct JSON and action-file invocations (`--action` and `--action-file`) are audited entry points: they fail closed unless invoked with `--legacy` (for @@ -236,10 +251,16 @@ a stdio JSON-RPC server speaking newline-delimited JSON messages: - `handshake`: validates client identity and checks active AI model connectivity. - `ask`: submits a conversational request (`install firefox`, `why is audio broken?`) - into the shared AI workflow, returning assistant proposals and bounded evidence. -- `execute`: executes a reviewed, approved plan by plan ID and plan digest. + into the shared AI workflow, returning a reviewed plan card for install, + removal, general administration, or a follow-up confirmation. Every plan type + carries the same `plan_id`/`digest` review and approval state; information and + clarification replies carry no execution control. Removal is AI-first by + default. +- `execute`: executes exactly the referenced reviewed plan by plan ID and plan + digest. The privileged broker repeats the full validation. - `legacy_install`: performs deterministic installation with an explicit backend. - `legacy_execute`: executes typed actions deterministically. +- `clear_conversation`: deletes the persisted, minimized follow-up context. - `updates`: queries the unified multi-source update system across Portage, Flatpak, Snap, AppImage, and Nix. - `proactive_alerts`, `proactive_snooze`, `proactive_dismiss`: interacts with the @@ -251,6 +272,51 @@ a stdio JSON-RPC server speaking newline-delimited JSON messages: Zero business logic lives in the GUI: equivalent CLI and GUI requests produce identical validated plans given the same facts and preferences. +## Privileged execution boundary + +A mutating plan is stored as a `PreparedPlan` in protected, per-user storage +(`/run/user//phoebus/plans`, mode 0700; a 0600 plan file; atomic write; a +128-bit unpredictable identifier). The plan is sealed with an integrity digest +over the reviewed fields, the target root and the initiating uid. + +`execute_plan` validates the plan before elevation and again — authoritatively — +inside the privileged broker (`sys --broker --execute-plan --plan-uid +--root `). The broker: + +- re-derives the integrity seal from the plan's own contents (it never trusts + two supplied digest strings); +- rejects expired, already-claimed, modified, malformed, wrong-root or + wrong-uid plans; +- revalidates the current package/removal state after authentication; +- atomically claims the plan (`O_EXCL`) so two concurrent requests cannot both + mutate the system, and a retry never repeats a consumed plan; +- treats the plan file and its contents as untrusted input, resolving storage + from the uid rather than an arbitrary path. + +Authentication happens outside model context through Polkit (`pkexec`), never +passwordless sudo. Cancelling or refusing authentication performs no mutation +and leaves the plan unconsumed until it expires. + +## Transaction truthfulness + +Every mutation is recorded as an in-progress transaction **before** it runs. On +action failure, verification failure, refusal or cancellation the same record is +finished with a truthful result (`failed: …` / `verify failed: …`); completed +steps and their protective snapshot are retained. A record that never reaches a +terminal result is an interrupted operation, and its consumed plan cannot be +replayed. A malformed broker reply is a protocol failure, never fabricated +success. History persistence failures are surfaced, not swallowed. + +## Conversation privacy + +Follow-up context is minimized before persistence: the raw request is never +stored, only structured context (kind, application, candidate, rationale), and +registered secrets are scrubbed with the active redactor. The history file is +0600 inside a 0700 directory, written atomically, bounded to ten turns, and can +be cleared (`clear_conversation`) so it no longer informs later follow-ups. +Redaction removes known secrets; it does not claim to detect arbitrary sensitive +text, which is why raw requests are not persisted. + ## Acceptance matrix The matrix below is the repeatable acceptance suite. `installer/tests/vm/sys-acceptance.sh` diff --git a/installer-rs/crates/phoebus-core/src/config.rs b/installer-rs/crates/phoebus-core/src/config.rs index 6e4ff21..a0b9a00 100644 --- a/installer-rs/crates/phoebus-core/src/config.rs +++ b/installer-rs/crates/phoebus-core/src/config.rs @@ -407,6 +407,11 @@ pub struct AiConfig { pub opencode_model: String, /// OpenCode model variant (e.g. `default`, `low`, `high`, `max`). pub opencode_variant: String, + /// Path to a mode-0600 file holding the direct provider API key. The key + /// itself is never stored in the configuration. + pub direct_credential_file: String, + /// Path to a mode-0600 file holding the OpenCode server credential. + pub opencode_credential_file: String, } impl AiConfig { diff --git a/installer-rs/crates/phoebus-installer/src/ai_setup.rs b/installer-rs/crates/phoebus-installer/src/ai_setup.rs new file mode 100644 index 0000000..2d8fd4c --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/ai_setup.rs @@ -0,0 +1,263 @@ +//! Shared provider configuration and credential handling for `sys` and the +//! desktop assistant. +//! +//! Both surfaces use this module to resolve which model backend to use, where +//! the endpoint/model live, and how to load the credential reference safely, +//! so the two cannot drift apart again. Credentials are only ever read from a +//! mode-0600 file (or an environment-provided path) and are registered with the +//! executor's redactor before any transport use. A key never travels through +//! QML, a model prompt, a command line or conversation history. + +use std::path::{Path, PathBuf}; + +use phoebus_ai::provider::{ModelTransport, ProviderKind}; +use phoebus_core::{AiBackend, AiConfig, SecretString}; +use phoebus_executor::ai::CurlTransport; +use phoebus_executor::error::{ExecError, Result}; +use phoebus_executor::exec::Exec; +use phoebus_executor::opencode_client::ExecOpenCodeTransport; + +/// Caller-supplied overrides (CLI flags or GUI settings). `None` means "fall +/// back to the environment or the installed configuration". +#[derive(Debug, Clone, Default)] +pub struct AiOverrides { + pub backend: Option, + pub provider: Option, + pub model: Option, + pub endpoint: Option, + pub api_key_file: Option, + pub opencode_server: Option, + pub opencode_provider: Option, + pub opencode_model: Option, + pub opencode_password_file: Option, + pub no_sandbox: bool, + /// When true, environment variables are consulted between the explicit + /// override and the installed configuration. + pub use_environment: bool, +} + +/// Fully resolved provider settings. No secret value is held here, only the +/// path to the mode-0600 credential file. +#[derive(Debug, Clone)] +pub struct ResolvedAi { + pub backend: AiBackend, + pub provider: ProviderKind, + pub endpoint: String, + pub model: String, + pub opencode_server: String, + pub opencode_provider: String, + pub opencode_model: String, + pub api_key_file: Option, + pub opencode_password_file: Option, + pub no_sandbox: bool, +} + +fn env_var(use_env: bool, name: &str) -> Option { + if !use_env { + return None; + } + std::env::var(name).ok().filter(|s| !s.trim().is_empty()) +} + +/// A well-known per-user credential location used when nothing is configured. +/// Only returned when the file already exists, so the absence of a key is not +/// turned into an error for providers (like a local model) that need none. +fn default_credential_file() -> Option { + let base = std::env::var("XDG_CONFIG_HOME") + .ok() + .filter(|s| !s.trim().is_empty()) + .map(PathBuf::from) + .or_else(|| { + std::env::var("HOME") + .ok() + .map(|h| PathBuf::from(h).join(".config")) + })?; + let path = base.join("phoebus").join("ai.key"); + if path.is_file() { + Some(path) + } else { + None + } +} + +/// Resolve the provider configuration from explicit overrides, the +/// environment (when enabled) and the installed `assistant.conf`. +pub fn resolve(_root: &Path, ov: &AiOverrides, conf: Option<&AiConfig>) -> ResolvedAi { + let backend = ov + .backend + .clone() + .or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_BACKEND")) + .or_else(|| conf.map(|c| c.backend.as_str().to_string())) + .and_then(|s| AiBackend::parse(&s)) + .unwrap_or(AiBackend::Direct); + + let provider = ov + .provider + .clone() + .or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_PROVIDER")) + .or_else(|| conf.map(|c| c.provider.clone())) + .and_then(|s| ProviderKind::parse(&s)) + .unwrap_or(ProviderKind::None); + + let opencode_server = ov + .opencode_server + .clone() + .or_else(|| env_var(ov.use_environment, "PHOEBUS_OPENCODE_SERVER")) + .or_else(|| conf.map(|c| c.opencode_server.clone())) + .unwrap_or_default(); + let opencode_provider = ov + .opencode_provider + .clone() + .or_else(|| env_var(ov.use_environment, "PHOEBUS_OPENCODE_PROVIDER")) + .or_else(|| conf.map(|c| c.opencode_provider.clone())) + .unwrap_or_default(); + let opencode_model = ov + .opencode_model + .clone() + .or_else(|| env_var(ov.use_environment, "PHOEBUS_OPENCODE_MODEL")) + .or_else(|| conf.map(|c| c.opencode_model.clone())) + .unwrap_or_default(); + + let endpoint = ov + .endpoint + .clone() + .or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_ENDPOINT")) + .or_else(|| { + conf.map(|c| c.endpoint.clone()) + .filter(|s| !s.trim().is_empty()) + }) + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| { + if backend == AiBackend::OpenCode { + opencode_server.clone() + } else { + provider.endpoint().to_string() + } + }); + let model = ov + .model + .clone() + .or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_MODEL")) + .or_else(|| conf.map(|c| c.model.clone())) + .unwrap_or_default(); + + let api_key_file = ov + .api_key_file + .clone() + .or_else(|| env_var(ov.use_environment, "PHOEBUS_AI_API_KEY_FILE").map(PathBuf::from)) + .or_else(|| { + conf.map(|c| c.direct_credential_file.clone()) + .filter(|s| !s.trim().is_empty()) + .map(PathBuf::from) + }) + // Default authorized-provider location: a per-user 0600 file. Used + // only when it already exists, so a local model needs no key. + .or_else(default_credential_file); + let opencode_password_file = ov + .opencode_password_file + .clone() + .or_else(|| { + env_var(ov.use_environment, "PHOEBUS_OPENCODE_PASSWORD_FILE").map(PathBuf::from) + }) + .or_else(|| { + conf.map(|c| c.opencode_credential_file.clone()) + .filter(|s| !s.trim().is_empty()) + .map(PathBuf::from) + }); + + ResolvedAi { + backend, + provider, + endpoint, + model, + opencode_server, + opencode_provider, + opencode_model, + api_key_file, + opencode_password_file, + no_sandbox: ov.no_sandbox, + } +} + +impl ResolvedAi { + /// Whether the resolved backend is usable at all. + pub fn is_configured(&self) -> bool { + match self.backend { + AiBackend::OpenCode => { + !self.opencode_server.trim().is_empty() + && !self.opencode_provider.trim().is_empty() + && !self.opencode_model.trim().is_empty() + } + AiBackend::Direct => self.provider != ProviderKind::None, + } + } + + /// Load the direct-provider key, explaining clearly when it is missing or + /// inaccessible. The value is registered with the redactor by the transport. + pub fn load_direct_key(&self, exec: &Exec) -> Result> { + match &self.api_key_file { + Some(path) => { + let key = phoebus_executor::ai::load_api_key(path).map_err(|e| { + ExecError::operation( + "ai", + "load provider credential", + format!( + "could not load the provider API key from {}: {e}", + path.display() + ), + ) + })?; + exec.register_secret(&key); + Ok(Some(key)) + } + None => Ok(None), + } + } + + pub fn load_opencode_password(&self) -> Result> { + match &self.opencode_password_file { + Some(path) => Ok(Some(phoebus_executor::ai::load_api_key(path)?)), + None => Ok(None), + } + } + + /// Build a transport for this configuration. The direct provider gets the + /// OS-level sandbox unless explicitly disabled; the OpenCode agent server + /// is a different trust boundary and keeps its own transport. + pub fn transport<'e>(&self, exec: &'e Exec) -> Result> { + match self.backend { + AiBackend::OpenCode => { + let password = self.load_opencode_password()?; + Ok(Box::new( + ExecOpenCodeTransport::new( + exec, + self.opencode_server.clone(), + self.opencode_provider.clone(), + self.opencode_model.clone(), + ) + .with_auth(password), + )) + } + AiBackend::Direct => { + let key = self.load_direct_key(exec)?; + if self.provider.requires_key() && key.is_none() { + return Err(ExecError::operation( + "ai", + "load provider credential", + format!( + "provider `{}` requires an API key file (api_key_file in \ + assistant.conf, PHOEBUS_AI_API_KEY_FILE, or --ai-api-key-file)", + self.provider.as_str() + ), + )); + } + let direct = CurlTransport::new(exec, key); + if self.no_sandbox { + Ok(Box::new(direct)) + } else { + Ok(Box::new(direct.sandboxed())) + } + } + } + } +} diff --git a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs index 1184ced..9f05473 100644 --- a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs +++ b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs @@ -8,22 +8,21 @@ use std::io::{BufRead, Write}; use std::path::Path; use phoebus_ai::install::{Evidence, InstallSession}; -use phoebus_ai::provider::{ProviderKind, SystemFacts}; +use phoebus_ai::provider::SystemFacts; use phoebus_core::action::{parse_natural, SystemAction}; use phoebus_core::selection::Backend; use phoebus_core::{AiBackend, InstallConfig, Preferences}; -use phoebus_executor::ai::CurlTransport; use phoebus_executor::chooser; use phoebus_executor::install::{AiInstall, InstallRequest}; -use phoebus_executor::opencode_client::ExecOpenCodeTransport; use phoebus_executor::proactive; use phoebus_executor::probe; use phoebus_executor::transaction; use phoebus_executor::update::check_unified_updates; use phoebus_executor::{actions, Exec}; +use crate::ai_setup; use crate::conversation::{self, ConversationTurn, FollowupResolution}; -use crate::service::{self, PreparedPlan}; +use crate::service::{self, PlanStore, PreparedPlan}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -100,6 +99,14 @@ fn now_unix() -> u64 { .unwrap_or(0) } +/// Persist a minimized turn with the registered-secret redactor, surfacing a +/// storage failure rather than silently dropping the context. +fn record_turn(exec: &Exec, path: &Path, turn: ConversationTurn) { + if let Err(e) = conversation::save_turn(path, exec.redactor(), turn) { + eprintln!("assistant-bridge: could not persist conversation context: {e}"); + } +} + fn load_installed_ai_config(root: &Path) -> Option { let conf_path = root.join("etc/phoebus/assistant.conf"); let text = std::fs::read_to_string(&conf_path).ok()?; @@ -162,7 +169,77 @@ impl InstallSession for BridgeSession<'_> { } } -pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeResponse { +/// Resolve the connected provider and credentials through the shared setup +/// module, then run `f` with the result. Never exposes the credential to QML. +fn with_bridge_ai( + exec: &Exec, + root: &Path, + f: impl FnOnce(&AiInstall, &SystemFacts) -> T, +) -> std::result::Result { + let conf = load_installed_ai_config(root); + let resolved = ai_setup::resolve(root, &ai_setup::AiOverrides::default(), conf.as_ref()); + if !resolved.is_configured() { + return Err( + "No AI model is connected. Connect a provider or use Legacy Admin for \ + deterministic administration." + .into(), + ); + } + let transport = resolved.transport(exec).map_err(|e| e.to_string())?; + let facts = gather_facts(exec, root); + let ai = AiInstall { + provider: resolved.provider, + endpoint: if resolved.backend == AiBackend::OpenCode { + resolved.opencode_server.clone() + } else { + resolved.endpoint.clone() + }, + model: if resolved.backend == AiBackend::OpenCode { + resolved.opencode_model.clone() + } else { + resolved.model.clone() + }, + transport: transport.as_ref(), + limits: phoebus_ai::install::Limits::default(), + }; + Ok(f(&ai, &facts)) +} + +/// The shared, complete review card for any prepared plan. QML renders this +/// directly; administrative decisions stay in the service. +fn plan_response(id: u64, kind: &str, plan: &PreparedPlan) -> BridgeResponse { + BridgeResponse::ok( + id, + json!({ + "kind": kind, + "state": "prepared", + "prepared": true, + "plan_id": plan.id, + "summary": plan.summary, + "recommendation": plan.recommendation, + "application": plan.application, + "backend": plan.candidate.as_ref().map(|c| c.backend.as_str()), + "source": plan.source, + "chosen": plan.candidate, + "alternatives": plan.alternatives, + "rationale": plan.rationale, + "action": plan.actions.first(), + "actions": plan.actions, + "digest": plan.digest, + "effects": plan.effects.effects, + "warnings": plan.warnings, + "requires_root": plan.requires_root, + "verification": plan.verification, + }), + ) +} + +pub fn handle_request( + exec: &Exec, + root: &Path, + plans: &PlanStore, + req: BridgeRequest, +) -> BridgeResponse { let id = req.id; match req.op.as_str() { "handshake" => { @@ -233,11 +310,15 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes Ok(log) => BridgeResponse::ok(id, json!(log.records)), Err(e) => BridgeResponse::err(id, e.to_string()), }, + "clear_conversation" => match conversation::clear_history(&conversation::history_path()) { + Ok(()) => BridgeResponse::ok(id, json!({ "cleared": true })), + Err(e) => BridgeResponse::err(id, e.to_string()), + }, "undo" => { let action = SystemAction::Undo { snapshot: req.snapshot, }; - execute_action_helper(exec, root, id, action, req.yes.unwrap_or(false)) + execute_action_helper(exec, root, plans, id, action, req.yes.unwrap_or(false)) } "legacy_install" => { let app = match req.application { @@ -255,22 +336,8 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes }; let mut install_req = InstallRequest::new(&app); install_req.backend = Some(backend_enum); - match service::plan_legacy_install(exec, root, &install_req) { - Ok(plan) => BridgeResponse::ok( - id, - json!({ - "kind": "install", - "plan_id": plan.id, - "application": plan.application, - "backend": plan.candidate.as_ref().map(|c| c.backend.as_str()), - "source": plan.source, - "recommendation": plan.recommendation, - "action": plan.actions.first(), - "digest": plan.digest, - "effects": plan.effects.effects, - "requires_root": plan.requires_root, - }), - ), + match service::plan_legacy_install(plans, exec, root, &install_req) { + Ok(plan) => plan_response(id, "install", &plan), Err(e) => BridgeResponse::err(id, e.to_string()), } } @@ -290,7 +357,7 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes } else { return BridgeResponse::err(id, "missing action or phrase parameter"); }; - execute_action_helper(exec, root, id, action, req.yes.unwrap_or(false)) + execute_action_helper(exec, root, plans, id, action, req.yes.unwrap_or(false)) } "ask" => { let query = req.request.unwrap_or_default(); @@ -300,8 +367,26 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes let conv_path = conversation::history_path(); let history = conversation::load_history(&conv_path); + let constrained_backend = req.backend.as_deref().and_then(Backend::parse); - // 1. Contextual follow-up check + // 0. An explicit application reference always wins over inferred + // conversational context ("install vlc using flatpak"). + if let Some((app, source)) = conversation::parse_explicit_install(&query) { + return plan_and_respond_install( + plans, + exec, + root, + id, + &app, + source.or(constrained_backend), + &query, + &conv_path, + ); + } + + // 1. Contextual follow-up check. Conversational context only ever + // produces further investigation or a reference to a reviewed + // plan; it never executes anything directly. if let Some(followup) = conversation::resolve_followup(&query, &history) { match followup { FollowupResolution::Comparison { @@ -313,6 +398,7 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes id, json!({ "kind": "info", + "state": "info", "application": application, "summary": explanation.clone(), "recommendation": explanation, @@ -324,6 +410,7 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes target_backend, } => { return plan_and_respond_install( + plans, exec, root, id, @@ -334,29 +421,26 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes ); } FollowupResolution::ConfirmPlan { plan_id, digest } => { - if let Ok(plan) = service::PlanStore::load(&plan_id) { - return BridgeResponse::ok( - id, - json!({ - "kind": "confirm", - "plan_id": plan.id, - "digest": digest, - "summary": plan.summary, - "recommendation": plan.recommendation, - "action": plan.actions.first(), - "effects": plan.effects.effects, - "requires_root": plan.requires_root, - }), - ); + match plans.load(&plan_id) { + Ok(plan) if plan.digest == digest => { + return plan_response(id, "confirm", &plan); + } + _ => { + return BridgeResponse::err( + id, + "that plan is no longer available or has changed; \ + ask again for a fresh recommendation", + ); + } } } } } // 2. Install request - let constrained_backend = req.backend.as_deref().and_then(Backend::parse); if let Some(app) = parse_install_phrase(&query) { return plan_and_respond_install( + plans, exec, root, id, @@ -367,122 +451,34 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes ); } - // 3. Removal request + // 3. Removal request (AI-first by default; legacy selection is an + // explicit GUI/CLI choice). if let Some(app) = parse_removal_phrase(&query) { - match service::plan_removal(exec, root, &app, constrained_backend) { - Ok(plan) => { - conversation::save_turn( - &conv_path, - ConversationTurn { - timestamp_unix: now_unix(), - query: query.clone(), - response_kind: "removal".into(), - application: Some(app), - chosen_candidate: None, - alternatives: Vec::new(), - plan_id: Some(plan.id.clone()), - plan_digest: Some(plan.digest.clone()), - rationale: plan.rationale.clone(), - }, - ); - return BridgeResponse::ok( - id, - json!({ - "kind": "removal", - "plan_id": plan.id, - "application": plan.application, - "source": plan.source, - "recommendation": plan.recommendation, - "action": plan.actions.first(), - "digest": plan.digest, - "effects": plan.effects.effects, - "requires_root": plan.requires_root, - }), - ); - } - Err(e) => return BridgeResponse::err(id, e.to_string()), - } + return plan_and_respond_removal( + plans, + exec, + root, + id, + &app, + constrained_backend, + &query, + &conv_path, + ); } - // 4. General natural language request via connected model - let facts = gather_facts(exec, root); - let conf = load_installed_ai_config(root); - let ai_backend = conf - .as_ref() - .map(|c| c.backend) - .unwrap_or(AiBackend::Direct); - - let (provider, endpoint, model); - let transport: Box; - - match ai_backend { - AiBackend::OpenCode => { - let server = conf - .as_ref() - .map(|c| c.opencode_server.clone()) - .unwrap_or_default(); - let op_provider = conf - .as_ref() - .map(|c| c.opencode_provider.clone()) - .unwrap_or_default(); - let op_model = conf - .as_ref() - .map(|c| c.opencode_model.clone()) - .unwrap_or_default(); - if server.is_empty() || op_model.is_empty() { - return BridgeResponse::err( - id, - "OpenCode is not configured. Configure model or use legacy mode.", - ); - } - provider = ProviderKind::Local; - endpoint = server.clone(); - model = op_model.clone(); - transport = Box::new(ExecOpenCodeTransport::new( + // 4. General natural language request via the connected model. + let response = with_bridge_ai(exec, root, |ai, facts| { + service::plan_general(plans, exec, root, &query, facts, ai) + }); + match response { + Ok(Ok(plan)) => { + record_turn( exec, - server, - op_provider, - op_model, - )); - } - AiBackend::Direct => { - let p = conf - .as_ref() - .and_then(|c| ProviderKind::parse(&c.provider)) - .unwrap_or(ProviderKind::None); - if p == ProviderKind::None { - return BridgeResponse::err( - id, - "No AI model is connected. Use legacy mode for deterministic administration.", - ); - } - endpoint = conf - .as_ref() - .map(|c| c.endpoint.clone()) - .filter(|s| !s.trim().is_empty()) - .unwrap_or_else(|| p.endpoint().to_string()); - model = conf.as_ref().map(|c| c.model.clone()).unwrap_or_default(); - provider = p; - let direct = CurlTransport::new(exec, None); - transport = Box::new(direct.sandboxed()); - } - } - - let ai = AiInstall { - provider, - endpoint, - model, - transport: transport.as_ref(), - limits: phoebus_ai::install::Limits::default(), - }; - - match service::plan_general(exec, root, &query, &facts, &ai) { - Ok(plan) => { - conversation::save_turn( &conv_path, ConversationTurn { timestamp_unix: now_unix(), - query, + // Structured plan summary, not the raw request. + query: plan.summary.clone(), response_kind: "plan".into(), application: None, chosen_candidate: None, @@ -492,20 +488,10 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes rationale: plan.rationale.clone(), }, ); - BridgeResponse::ok( - id, - json!({ - "kind": "plan", - "plan_id": plan.id, - "summary": plan.summary, - "actions": plan.actions, - "digest": plan.digest, - "effects": plan.effects.effects, - "requires_root": plan.requires_root, - }), - ) + plan_response(id, "plan", &plan) } - Err(e) => BridgeResponse::err(id, e.to_string()), + Ok(Err(e)) => BridgeResponse::err(id, e.to_string()), + Err(e) => BridgeResponse::err(id, e), } } "execute" => { @@ -518,14 +504,23 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes None => return BridgeResponse::err(id, "missing digest parameter"), }; - match service::execute_plan(exec, root, plan_id, digest, req.yes.unwrap_or(false)) { + match service::execute_plan( + exec, + root, + plans, + plan_id, + digest, + req.yes.unwrap_or(false), + ) { Ok(outcome) => BridgeResponse::ok( id, json!({ "completed": outcome.completed, + "state": "completed", "snapshot": outcome.snapshot, "result": outcome.result, "verification": outcome.verification, + "launch": outcome.launch, }), ), Err(e) => BridgeResponse::err(id, e.to_string()), @@ -535,7 +530,9 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes } } +#[allow(clippy::too_many_arguments)] fn plan_and_respond_install( + plans: &PlanStore, exec: &Exec, root: &Path, id: u64, @@ -546,82 +543,16 @@ fn plan_and_respond_install( ) -> BridgeResponse { let mut install_req = InstallRequest::new(app); install_req.backend = constrained_backend; - - let facts = gather_facts(exec, root); - let conf = load_installed_ai_config(root); - let ai_backend = conf - .as_ref() - .map(|c| c.backend) - .unwrap_or(AiBackend::Direct); - - let (provider, endpoint, model); - let transport: Box; - - match ai_backend { - AiBackend::OpenCode => { - let server = conf - .as_ref() - .map(|c| c.opencode_server.clone()) - .unwrap_or_default(); - let op_provider = conf - .as_ref() - .map(|c| c.opencode_provider.clone()) - .unwrap_or_default(); - let op_model = conf - .as_ref() - .map(|c| c.opencode_model.clone()) - .unwrap_or_default(); - if server.is_empty() || op_model.is_empty() { - return BridgeResponse::err( - id, - "OpenCode is not configured. Configure model or use legacy mode.", - ); - } - provider = ProviderKind::Local; - endpoint = server.clone(); - model = op_model.clone(); - transport = Box::new(ExecOpenCodeTransport::new( - exec, - server, - op_provider, - op_model, - )); - } - AiBackend::Direct => { - let p = conf - .as_ref() - .and_then(|c| ProviderKind::parse(&c.provider)) - .unwrap_or(ProviderKind::None); - if p == ProviderKind::None { - return BridgeResponse::err( - id, - "No AI model is connected. Use legacy mode for deterministic administration (sys install --legacy --).", - ); - } - endpoint = conf - .as_ref() - .map(|c| c.endpoint.clone()) - .filter(|s| !s.trim().is_empty()) - .unwrap_or_else(|| p.endpoint().to_string()); - model = conf.as_ref().map(|c| c.model.clone()).unwrap_or_default(); - provider = p; - let direct = CurlTransport::new(exec, None); - transport = Box::new(direct.sandboxed()); - } - } - - let ai = AiInstall { - provider, - endpoint, - model, - transport: transport.as_ref(), - limits: phoebus_ai::install::Limits::default(), - }; let session = BridgeSession { exec, root }; - match service::plan_install(exec, root, &install_req, &session, Some(&ai), &facts) { - Ok(plan) => { - conversation::save_turn( + let result = with_bridge_ai(exec, root, |ai, facts| { + service::plan_install(plans, exec, root, &install_req, &session, Some(ai), facts) + }); + + match result { + Ok(Ok(plan)) => { + record_turn( + exec, conv_path, ConversationTurn { timestamp_unix: now_unix(), @@ -635,33 +566,56 @@ fn plan_and_respond_install( rationale: plan.rationale.clone(), }, ); - - BridgeResponse::ok( - id, - json!({ - "kind": "install", - "plan_id": plan.id, - "application": plan.application, - "backend": plan.candidate.as_ref().map(|c| c.backend.as_str()), - "source": plan.source, - "recommendation": plan.recommendation, - "chosen": plan.candidate, - "alternatives": plan.alternatives, - "rationale": plan.rationale, - "action": plan.actions.first(), - "digest": plan.digest, - "effects": plan.effects.effects, - "requires_root": plan.requires_root, - }), - ) + plan_response(id, "install", &plan) } - Err(e) => BridgeResponse::err(id, e.to_string()), + Ok(Err(e)) => BridgeResponse::err(id, e.to_string()), + Err(e) => BridgeResponse::err(id, e), + } +} + +#[allow(clippy::too_many_arguments)] +fn plan_and_respond_removal( + plans: &PlanStore, + exec: &Exec, + root: &Path, + id: u64, + app: &str, + constrained_backend: Option, + query: &str, + conv_path: &Path, +) -> BridgeResponse { + let result = with_bridge_ai(exec, root, |ai, facts| { + service::plan_removal_with_ai(plans, exec, root, app, constrained_backend, ai, facts) + }); + + match result { + Ok(Ok(plan)) => { + record_turn( + exec, + conv_path, + ConversationTurn { + timestamp_unix: now_unix(), + query: query.to_string(), + response_kind: "removal".into(), + application: Some(app.to_string()), + chosen_candidate: None, + alternatives: Vec::new(), + plan_id: Some(plan.id.clone()), + plan_digest: Some(plan.digest.clone()), + rationale: plan.rationale.clone(), + }, + ); + plan_response(id, "removal", &plan) + } + Ok(Err(e)) => BridgeResponse::err(id, e.to_string()), + Err(e) => BridgeResponse::err(id, e), } } fn execute_action_helper( exec: &Exec, root: &Path, + plans: &PlanStore, id: u64, action: SystemAction, assume_yes: bool, @@ -674,8 +628,8 @@ fn execute_action_helper( let now = now_unix(); let actions_vec = vec![action.clone()]; let digest = service::compute_plan_digest(&actions_vec, None, &effects); - let plan = PreparedPlan { - id: format!("plan-act-{now}"), + let mut plan = PreparedPlan { + id: service::fresh_plan_id("act"), created_unix: now, expires_unix: now + service::DEFAULT_PLAN_TTL_SECONDS, kind: service::PlanKind::General, @@ -687,23 +641,29 @@ fn execute_action_helper( rationale: Vec::new(), warnings: Vec::new(), actions: actions_vec, - effects, + effects: effects.clone(), + step_effects: vec![effects], digest: digest.clone(), verification: "action completed".into(), requires_root: action.is_mutating(), source: "legacy".into(), executed: false, + target_root: service::canonical_root(root), + initiator_uid: service::effective_uid(), + integrity: String::new(), }; - if let Err(e) = service::PlanStore::save(&plan) { + if let Err(e) = plans.save(&mut plan) { return BridgeResponse::err(id, format!("could not stage plan: {e}")); } - match service::execute_plan(exec, root, &plan.id, &digest, assume_yes) { + match service::execute_plan(exec, root, plans, &plan.id, &digest, assume_yes) { Ok(outcome) => BridgeResponse::ok( id, json!({ "output": outcome.result, "snapshot": outcome.snapshot, + "verification": outcome.verification, + "state": "completed", }), ), Err(e) => BridgeResponse::err(id, e.to_string()), @@ -755,6 +715,7 @@ pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box std::result::Result<(), Box, - /// Execute a prepared plan file directly (internal broker invocation). - #[arg(long, value_name = "PATH")] - execute_plan: Option, + /// Execute a prepared plan by identifier (internal broker invocation). + #[arg(long, value_name = "PLAN_ID")] + execute_plan: Option, + + /// The uid that reviewed and approved the plan (internal broker only). + #[arg(long, value_name = "UID")] + plan_uid: Option, /// Auto-approve (unattended); still requires root. #[arg(long, short = 'y')] @@ -191,6 +194,14 @@ fn effective_uid() -> u32 { .unwrap_or(1) } +/// Persist a minimized conversation turn with the process redactor, surfacing a +/// storage failure instead of silently losing it. +fn record_turn(exec: &Exec, path: &Path, turn: ConversationTurn) { + if let Err(e) = conversation::save_turn(path, exec.redactor(), turn) { + eprintln!("sys: warning: could not persist conversation context: {e}"); + } +} + fn main() -> ExitCode { match run() { Ok(()) => ExitCode::SUCCESS, @@ -217,6 +228,7 @@ fn run() -> std::result::Result<(), Box> { cli.root.clone(), state_dir, ); + let plans = service::PlanStore::for_current_user(); // 1. Assistant Bridge if cli.assistant_bridge { @@ -224,15 +236,27 @@ fn run() -> std::result::Result<(), Box> { } // 2. Broker execute plan - if let Some(plan_path) = &cli.execute_plan { + if let Some(plan_id) = &cli.execute_plan { if !cli.broker { return Err("--execute-plan requires --broker for privileged invocation".into()); } if effective_uid() != 0 { return Err("privileged plan execution requires root".into()); } - let plan = service::PlanStore::load(&plan_path.to_string_lossy())?; - let outcome = service::execute_plan_direct(&exec, &cli.root, plan, true)?; + let initiator_uid = cli + .plan_uid + .ok_or("--execute-plan requires --plan-uid (the reviewing user)")?; + // The broker resolves storage from the initiating uid, never from an + // arbitrary path, and repeats the full validation itself. + let plans = service::PlanStore::for_uid(initiator_uid); + let outcome = service::execute_plan_privileged( + &exec, + &cli.root, + &plans, + plan_id, + initiator_uid, + true, + )?; println!("{}", serde_json::to_string(&outcome)?); return Ok(()); } @@ -266,8 +290,8 @@ fn run() -> std::result::Result<(), Box> { if let Some(b) = backend { let mut request = InstallRequest::new(&application); request.backend = Some(b); - let plan = service::plan_legacy_install(&exec, &cli.root, &request)?; - return render_and_execute_plan(&cli, &exec, plan); + let plan = service::plan_legacy_install(&plans, &exec, &cli.root, &request)?; + return render_and_execute_plan(&cli, &exec, &plans, plan); } else { eprintln!("sys: legacy install requires an explicit package source flag."); eprintln!("Specify one of:"); @@ -281,8 +305,8 @@ fn run() -> std::result::Result<(), Box> { } } if let Some(application) = parse_removal_text(&full_phrase) { - let plan = service::plan_removal(&exec, &cli.root, &application, backend)?; - return render_and_execute_plan(&cli, &exec, plan); + let plan = service::plan_removal(&plans, &exec, &cli.root, &application, backend)?; + return render_and_execute_plan(&cli, &exec, &plans, plan); } if backend.is_some() { return Err( @@ -331,17 +355,17 @@ fn run() -> std::result::Result<(), Box> { if instruction.trim().is_empty() { return Err("usage: sys ask ".into()); } - return run_ask(&cli, &exec, &instruction, backend); + return run_ask(&cli, &exec, &plans, &instruction, backend); } // Natural `sys install ` / `sys please install ` if let Some(application) = parse_install_text(&full_phrase) { - return run_install(&cli, &exec, &application, backend); + return run_install(&cli, &exec, &plans, &application, backend); } // Natural `sys remove ` / `sys please remove ` if let Some(application) = parse_removal_text(&full_phrase) { - return run_remove(&cli, &exec, &application, backend); + return run_remove(&cli, &exec, &plans, &application, backend); } if backend.is_some() { @@ -353,7 +377,7 @@ fn run() -> std::result::Result<(), Box> { } // Other natural language instructions enter the AI workflow by default - run_ask(&cli, &exec, &full_phrase, None) + run_ask(&cli, &exec, &plans, &full_phrase, None) } fn execute_action( @@ -551,123 +575,55 @@ fn print_install_offer(cli: &Cli, exec: &Exec, application: &str) { fn run_install( cli: &Cli, exec: &Exec, + plans: &service::PlanStore, application: &str, backend: Option, ) -> std::result::Result<(), Box> { let mut request = InstallRequest::new(application); request.backend = backend; - let conf = load_installed_ai_config(&cli.root); - let ai_backend = resolve_backend(cli, conf.as_ref()); + let resolved = resolve_ai(cli); let facts = gather_facts(exec); - let (provider, endpoint, model); - let transport: Box; - - match ai_backend { - AiBackend::OpenCode => { - let server = cli - .opencode_server - .clone() - .or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok()) - .or_else(|| conf.as_ref().map(|c| c.opencode_server.clone())) - .unwrap_or_default(); - let opencode_provider = cli - .opencode_provider - .clone() - .or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok()) - .or_else(|| conf.as_ref().map(|c| c.opencode_provider.clone())) - .unwrap_or_default(); - let opencode_model = cli - .opencode_model - .clone() - .or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok()) - .or_else(|| conf.as_ref().map(|c| c.opencode_model.clone())) - .unwrap_or_default(); - if server.trim().is_empty() - || opencode_provider.trim().is_empty() - || opencode_model.trim().is_empty() - { - if let Some(b) = backend { - eprintln!("sys: OpenCode is not configured for this request."); - eprintln!("Run deterministically without a model using legacy mode:"); - eprintln!( - " sys install {application} --legacy --{}", - backend_flag_name(b) - ); - } else { - print_install_offer(cli, exec, application); - } - return Err( - "OpenCode needs --opencode-server, --opencode-provider and --opencode-model" - .into(), - ); - } - let password = match &cli.opencode_password_file { - Some(path) => Some(phoebus_executor::ai::load_api_key(path)?), - None => None, - }; - provider = ProviderKind::Local; - endpoint = server; - model = opencode_model; - transport = Box::new( - ExecOpenCodeTransport::new( - exec, - endpoint.clone(), - opencode_provider, - model.clone(), - ) - .with_auth(password), + if !resolved.is_configured() { + if let Some(b) = backend { + eprintln!("sys: no AI model is configured for this request."); + eprintln!("Run deterministically without a model using legacy mode:"); + eprintln!( + " sys install {application} --legacy --{}", + backend_flag_name(b) ); + } else { + print_install_offer(cli, exec, application); } - AiBackend::Direct => { - provider = resolve_provider(cli, conf.as_ref()); - if provider == ProviderKind::None { - if let Some(b) = backend { - eprintln!("sys: no AI provider is configured for this request."); - eprintln!("Run deterministically without a model using legacy mode:"); - eprintln!( - " sys install {application} --legacy --{}", - backend_flag_name(b) - ); - } else { - print_install_offer(cli, exec, application); - } - return Err("no AI provider configured".into()); - } - let key = match api_key_file(cli) { - Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?), - None => None, - }; - if provider.requires_key() && key.is_none() { - if let Some(b) = backend { - eprintln!( - "sys: provider `{}` requires --ai-api-key-file (mode 0600)", - provider.as_str() - ); - eprintln!("Run deterministically without a model using legacy mode:"); - eprintln!( - " sys install {application} --legacy --{}", - backend_flag_name(b) - ); - } else { - print_install_offer(cli, exec, application); - } - return Err(format!( - "provider `{}` requires --ai-api-key-file (mode 0600)", - provider.as_str() - ) - .into()); - } - endpoint = resolve_endpoint(cli, provider, conf.as_ref()); - model = resolve_model(cli, conf.as_ref()); - let direct = phoebus_executor::ai::CurlTransport::new(exec, key); - transport = if cli.no_sandbox { - Box::new(direct) - } else { - Box::new(direct.sandboxed()) - }; - } + return Err("no AI provider configured".into()); } + let transport = match resolved.transport(exec) { + Ok(t) => t, + Err(e) => { + if let Some(b) = backend { + eprintln!("sys: {e}"); + eprintln!("Run deterministically without a model using legacy mode:"); + eprintln!( + " sys install {application} --legacy --{}", + backend_flag_name(b) + ); + } else { + print_install_offer(cli, exec, application); + } + return Err(e.to_string().into()); + } + }; + let provider = resolved.provider; + let endpoint = if resolved.backend == AiBackend::OpenCode { + resolved.opencode_server.clone() + } else { + resolved.endpoint.clone() + }; + let model = if resolved.backend == AiBackend::OpenCode { + resolved.opencode_model.clone() + } else { + resolved.model.clone() + }; if let Some(b) = backend { eprintln!( @@ -695,7 +651,15 @@ fn run_install( root: &cli.root, ask: asker.as_deref(), }; - let plan = match service::plan_install(exec, &cli.root, &request, &session, Some(&ai), &facts) { + let plan = match service::plan_install( + plans, + exec, + &cli.root, + &request, + &session, + Some(&ai), + &facts, + ) { Ok(plan) => plan, Err(e) => { // The model failed: offer the actionable legacy alternative and stop; @@ -715,7 +679,8 @@ fn run_install( }; let conv_path = conversation::history_path(); - conversation::save_turn( + record_turn( + exec, &conv_path, ConversationTurn { timestamp_unix: now_unix(), @@ -730,18 +695,38 @@ fn run_install( }, ); - render_and_execute_plan(cli, exec, plan) + render_and_execute_plan(cli, exec, plans, plan) } +/// `sys remove `: the shared AI-first removal workflow. Default +/// removal goes through the connected model; only `--legacy` bypasses it. The +/// deterministic ownership discovery and policy validation run underneath in +/// both modes. fn run_remove( cli: &Cli, exec: &Exec, + plans: &service::PlanStore, application: &str, backend: Option, ) -> std::result::Result<(), Box> { - let plan = service::plan_removal(exec, &cli.root, application, backend)?; + let plan = match run_remove_plan(cli, exec, plans, application, backend) { + Ok(plan) => plan, + Err(e) => { + // The model failed: offer the actionable legacy alternative and + // stop; do not silently remove deterministically. + eprintln!("sys: the AI-assisted removal did not produce a plan ({e})."); + eprintln!("Run deterministically without a model using legacy mode:"); + let lane = backend + .map(|b| format!(" --{}", backend_flag_name(b))) + .unwrap_or_default(); + eprintln!(" sys remove {application} --legacy{lane}"); + return Err(format!("the AI-assisted removal did not produce a plan: {e}").into()); + } + }; + let conv_path = conversation::history_path(); - conversation::save_turn( + record_turn( + exec, &conv_path, ConversationTurn { timestamp_unix: now_unix(), @@ -755,12 +740,58 @@ fn run_remove( rationale: plan.rationale.clone(), }, ); - render_and_execute_plan(cli, exec, plan) + render_and_execute_plan(cli, exec, plans, plan) +} + +/// Build a removal plan through the connected model (default) or the +/// deterministic selector (legacy). The model only chooses/confirms among +/// copies the deterministic discovery already found. +fn run_remove_plan( + cli: &Cli, + exec: &Exec, + plans: &service::PlanStore, + application: &str, + backend: Option, +) -> std::result::Result> { + if cli.legacy { + return Ok(service::plan_removal( + plans, + exec, + &cli.root, + application, + backend, + )?); + } + + let resolved = resolve_ai(cli); + if !resolved.is_configured() { + return Err("no AI provider configured".into()); + } + let transport = resolved.transport(exec).map_err(|e| e.to_string())?; + let ai = AiInstall { + provider: resolved.provider, + endpoint: if resolved.backend == AiBackend::OpenCode { + resolved.opencode_server.clone() + } else { + resolved.endpoint.clone() + }, + model: if resolved.backend == AiBackend::OpenCode { + resolved.opencode_model.clone() + } else { + resolved.model.clone() + }, + transport: transport.as_ref(), + limits: phoebus_ai::install::Limits::default(), + }; + let facts = gather_facts(exec); + service::plan_removal_with_ai(plans, exec, &cli.root, application, backend, &ai, &facts) + .map_err(Into::into) } fn render_and_execute_plan( cli: &Cli, exec: &Exec, + plans: &service::PlanStore, plan: PreparedPlan, ) -> std::result::Result<(), Box> { println!("{}", plan.render()); @@ -781,7 +812,7 @@ fn render_and_execute_plan( authorize(&confirmation, &plan.summary, "execute")?; } - let outcome = service::execute_plan(exec, &cli.root, &plan.id, &plan.digest, true)?; + let outcome = service::execute_plan(exec, &cli.root, plans, &plan.id, &plan.digest, true)?; if let Some(snapshot) = outcome.snapshot { println!("protective snapshot: {snapshot}"); } @@ -832,61 +863,24 @@ fn load_installed_ai_config(root: &Path) -> Option { toml::from_str(&text).ok() } -fn resolve_backend(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> AiBackend { - let raw = cli - .ai_backend - .clone() - .or_else(|| std::env::var("PHOEBUS_AI_BACKEND").ok()) - .or_else(|| conf.map(|c| c.backend.as_str().to_string())) - .unwrap_or_default(); - AiBackend::parse(&raw).unwrap_or(AiBackend::Direct) -} - -fn resolve_provider(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> ProviderKind { - let raw = cli - .ai_provider - .clone() - .or_else(|| std::env::var("PHOEBUS_AI_PROVIDER").ok()) - .or_else(|| conf.map(|c| c.provider.clone())) - .unwrap_or_default(); - ProviderKind::parse(&raw).unwrap_or(ProviderKind::None) -} - -fn resolve_endpoint( - cli: &Cli, - provider: ProviderKind, - conf: Option<&phoebus_core::AiConfig>, -) -> String { - cli.ai_endpoint - .clone() - .or_else(|| std::env::var("PHOEBUS_AI_ENDPOINT").ok()) - .or_else(|| { - conf.and_then(|c| { - if c.endpoint.is_empty() { - None - } else { - Some(c.endpoint.clone()) - } - }) - }) - .filter(|s| !s.trim().is_empty()) - .unwrap_or_else(|| provider.endpoint().to_string()) -} - -fn resolve_model(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> String { - cli.ai_model - .clone() - .or_else(|| std::env::var("PHOEBUS_AI_MODEL").ok()) - .or_else(|| conf.map(|c| c.model.clone())) - .unwrap_or_default() -} - -fn api_key_file(cli: &Cli) -> Option { - cli.ai_api_key_file.clone().or_else(|| { - std::env::var("PHOEBUS_AI_API_KEY_FILE") - .ok() - .map(PathBuf::from) - }) +/// Resolve provider configuration and credential references through the shared +/// setup module, so the CLI and the GUI cannot diverge. +fn resolve_ai(cli: &Cli) -> phoebus_installer::ai_setup::ResolvedAi { + let conf = load_installed_ai_config(&cli.root); + let overrides = phoebus_installer::ai_setup::AiOverrides { + backend: cli.ai_backend.clone(), + provider: cli.ai_provider.clone(), + model: cli.ai_model.clone(), + endpoint: cli.ai_endpoint.clone(), + api_key_file: cli.ai_api_key_file.clone(), + opencode_server: cli.opencode_server.clone(), + opencode_provider: cli.opencode_provider.clone(), + opencode_model: cli.opencode_model.clone(), + opencode_password_file: cli.opencode_password_file.clone(), + no_sandbox: cli.no_sandbox, + use_environment: true, + }; + phoebus_installer::ai_setup::resolve(&cli.root, &overrides, conf.as_ref()) } fn deterministic_fallback(instruction: &str) { @@ -911,14 +905,18 @@ fn deterministic_fallback(instruction: &str) { fn run_ask( cli: &Cli, exec: &Exec, + plans: &service::PlanStore, instruction: &str, backend: Option, ) -> std::result::Result<(), Box> { - if let Some(application) = parse_install_text(instruction) { - return run_install(cli, exec, &application, backend); + // An explicit application reference takes precedence over any inferred + // conversational reference: "install vlc using flatpak" concerns VLC even + // right after a conversation about Firefox. + if let Some((application, source)) = conversation::parse_explicit_install(instruction) { + return run_install(cli, exec, plans, &application, source.or(backend)); } if let Some(application) = parse_removal_text(instruction) { - return run_remove(cli, exec, &application, backend); + return run_remove(cli, exec, plans, &application, backend); } let conv_path = conversation::history_path(); @@ -933,100 +931,45 @@ fn run_ask( application, target_backend, } => { - return run_install(cli, exec, &application, Some(target_backend)); + return run_install(cli, exec, plans, &application, Some(target_backend)); } FollowupResolution::ConfirmPlan { plan_id, digest } => { - let plan = service::PlanStore::load(&plan_id)?; + // Conversational confirmation never bypasses normal plan + // validation or authentication: it references a reviewed plan + // and goes through the same execution boundary. + let plan = plans.load(&plan_id)?; if plan.digest != digest { return Err("plan digest mismatch".into()); } - return render_and_execute_plan(cli, exec, plan); + return render_and_execute_plan(cli, exec, plans, plan); } } } + let resolved = resolve_ai(cli); + if !resolved.is_configured() { + deterministic_fallback(instruction); + return Err("no AI provider configured".into()); + } + let transport = match resolved.transport(exec) { + Ok(t) => t, + Err(e) => { + deterministic_fallback(instruction); + return Err(e.to_string().into()); + } + }; let facts = gather_facts(exec); - let conf = load_installed_ai_config(&cli.root); - let ai_backend = resolve_backend(cli, conf.as_ref()); - let (provider, endpoint, model); - let transport: Box; - - match ai_backend { - AiBackend::OpenCode => { - let server = cli - .opencode_server - .clone() - .or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok()) - .or_else(|| conf.as_ref().map(|c| c.opencode_server.clone())) - .unwrap_or_default(); - let opencode_provider = cli - .opencode_provider - .clone() - .or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok()) - .or_else(|| conf.as_ref().map(|c| c.opencode_provider.clone())) - .unwrap_or_default(); - let opencode_model = cli - .opencode_model - .clone() - .or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok()) - .or_else(|| conf.as_ref().map(|c| c.opencode_model.clone())) - .unwrap_or_default(); - if server.trim().is_empty() - || opencode_provider.trim().is_empty() - || opencode_model.trim().is_empty() - { - deterministic_fallback(instruction); - return Err( - "OpenCode requires --opencode-server, --opencode-provider and --opencode-model" - .into(), - ); - } - let password = match &cli.opencode_password_file { - Some(path) => Some(phoebus_executor::ai::load_api_key(path)?), - None => None, - }; - provider = ProviderKind::Local; - endpoint = server; - model = opencode_model; - transport = Box::new( - ExecOpenCodeTransport::new( - exec, - endpoint.clone(), - opencode_provider, - model.clone(), - ) - .with_auth(password), - ); - } - AiBackend::Direct => { - let resolved = resolve_provider(cli, conf.as_ref()); - if resolved == ProviderKind::None { - deterministic_fallback(instruction); - return Err("no AI provider configured".into()); - } - let key = match api_key_file(cli) { - Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?), - None => None, - }; - if resolved.requires_key() && key.is_none() { - deterministic_fallback(instruction); - return Err(format!( - "provider `{}` requires --ai-api-key-file (mode 0600)", - resolved.as_str() - ) - .into()); - } - provider = resolved; - endpoint = resolve_endpoint(cli, resolved, conf.as_ref()); - model = resolve_model(cli, conf.as_ref()); - let direct = phoebus_executor::ai::CurlTransport::new(exec, key); - transport = if cli.no_sandbox { - Box::new(direct) - } else { - Box::new(direct.sandboxed()) - }; - } - } + let provider = resolved.provider; + let endpoint = if resolved.backend == AiBackend::OpenCode { + resolved.opencode_server.clone() + } else { + resolved.endpoint.clone() + }; + let model = if resolved.backend == AiBackend::OpenCode { + resolved.opencode_model.clone() + } else { + resolved.model.clone() + }; let ai = AiInstall { provider, @@ -1036,7 +979,7 @@ fn run_ask( limits: phoebus_ai::install::Limits::default(), }; - let plan = match service::plan_general(exec, &cli.root, instruction, &facts, &ai) { + let plan = match service::plan_general(plans, exec, &cli.root, instruction, &facts, &ai) { Ok(plan) => plan, Err(e) => { eprintln!("The model is unavailable or returned an unusable plan: {e}"); @@ -1045,11 +988,14 @@ fn run_ask( } }; - conversation::save_turn( + record_turn( + exec, &conv_path, ConversationTurn { timestamp_unix: now_unix(), - query: instruction.to_string(), + // Persist the plan's own summary, not the raw request: structured + // context is sufficient for follow-ups and minimizes exposure. + query: plan.summary.clone(), response_kind: "plan".into(), application: None, chosen_candidate: None, @@ -1060,7 +1006,7 @@ fn run_ask( }, ); - render_and_execute_plan(cli, exec, plan) + render_and_execute_plan(cli, exec, plans, plan) } #[allow(dead_code)] diff --git a/installer-rs/crates/phoebus-installer/src/conversation.rs b/installer-rs/crates/phoebus-installer/src/conversation.rs index b9ceae0..b3f408e 100644 --- a/installer-rs/crates/phoebus-installer/src/conversation.rs +++ b/installer-rs/crates/phoebus-installer/src/conversation.rs @@ -4,9 +4,17 @@ //! "why did you choose that over nix?", "install the flatpak one", or "proceed with that" //! without restarting candidate investigation from scratch. //! -//! All stored history is bounded (max 10 turns) and sensitive credentials are -//! redacted before persistence. +//! All stored history is bounded (max 10 turns) and minimized before +//! persistence. Only structured context (the application, chosen candidate, +//! rationale and a short summary) is kept, never the unrestricted raw request. +//! Registered secrets are scrubbed with the caller's redactor; that is an +//! honest boundary — it removes known secrets, it does not detect arbitrary +//! sensitive text, which is why raw requests are not stored. +//! +//! History is kept in a 0600 file inside a 0700 directory, written atomically, +//! and can be cleared without leaving the follow-up context behind. +use std::io::Write; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -16,10 +24,14 @@ use serde::{Deserialize, Serialize}; const MAX_TURNS: usize = 10; const FOLLOWUP_WINDOW_SECONDS: u64 = 1800; // 30 minutes +/// Upper bound on a persisted free-text summary or rationale line. +const MAX_TEXT_CHARS: usize = 240; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConversationTurn { pub timestamp_unix: u64, + /// A minimized, structured summary of the request (e.g. "install firefox"), + /// never the unrestricted raw natural-language request. pub query: String, pub response_kind: String, // "install", "removal", "plan", "info" #[serde(default, skip_serializing_if = "Option::is_none")] @@ -91,31 +103,170 @@ pub fn load_history(path: &Path) -> ConversationHistory { serde_json::from_str(&data).unwrap_or_default() } -pub fn save_turn(path: &Path, turn: ConversationTurn) { +/// Bound a piece of free text: collapse whitespace, drop control characters +/// and cap the length. Combined with the registered-secret redactor, this keeps +/// persisted history minimal and stable. +fn minimize(redactor: &Redactor, text: &str) -> String { + let redacted = redactor.redact(text); + let cleaned: String = redacted + .chars() + .filter(|c| !c.is_control() || *c == ' ') + .collect(); + let collapsed = cleaned.split_whitespace().collect::>().join(" "); + if collapsed.chars().count() > MAX_TEXT_CHARS { + collapsed.chars().take(MAX_TEXT_CHARS).collect::() + "…" + } else { + collapsed + } +} + +/// Append a turn. The caller supplies the process redactor (which holds any +/// registered secret), so a known secret can never be persisted. Returns an +/// error on a write failure instead of silently discarding history. +pub fn save_turn( + path: &Path, + redactor: &Redactor, + mut turn: ConversationTurn, +) -> std::io::Result<()> { let mut history = load_history(path); - // Redact sensitive patterns in query and rationale - let redactor = Redactor::new(); - let mut sanitized_turn = turn; - sanitized_turn.query = redactor.redact(&sanitized_turn.query); - sanitized_turn.rationale = sanitized_turn + turn.query = minimize(redactor, &turn.query); + turn.rationale = turn .rationale .into_iter() - .map(|r| redactor.redact(&r)) + .map(|r| minimize(redactor, &r)) .collect(); + if let Some(app) = &turn.application { + turn.application = Some(minimize(redactor, app)); + } - history.turns.push(sanitized_turn); + history.turns.push(turn); if history.turns.len() > MAX_TURNS { history.turns.drain(0..history.turns.len() - MAX_TURNS); } if let Some(parent) = path.parent() { - let _ = std::fs::create_dir_all(parent); + std::fs::create_dir_all(parent)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)); + } } - if let Ok(serialized) = serde_json::to_string_pretty(&history) { - let _ = std::fs::write(path, serialized); + let serialized = serde_json::to_string_pretty(&history) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; + atomic_write_private(path, serialized.as_bytes()) +} + +/// Delete the persisted history so it can no longer inform a later follow-up. +pub fn clear_history(path: &Path) -> std::io::Result<()> { + match std::fs::remove_file(path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e), } } +fn atomic_write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let tmp = path.with_extension("tmp"); + { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut file = opts.open(&tmp)?; + file.write_all(bytes)?; + file.flush()?; + file.sync_all()?; + } + std::fs::rename(&tmp, path)?; + Ok(()) +} + +fn backend_from_word(word: &str) -> Option { + match word { + "flatpak" => Some(Backend::Flatpak), + "portage" => Some(Backend::PortageSource), + "source" => Some(Backend::PortageSource), + "binary" => Some(Backend::PortageBinary), + "nix" => Some(Backend::Nix), + "nixpkgs" => Some(Backend::Nix), + "snap" => Some(Backend::Snap), + "appimage" => Some(Backend::AppImage), + "ebuild" => Some(Backend::CustomEbuild), + _ => None, + } +} + +/// Tokens that are never an application name: articles, pronouns, verbs and +/// software-lane names. +const NON_APP_TOKENS: &[&str] = &[ + "the", + "a", + "an", + "that", + "this", + "it", + "one", + "those", + "these", + "using", + "via", + "with", + "from", + "through", + "instead", + "please", + "install", + "add", + "remove", + "uninstall", + "delete", + "for", + "and", + "to", + "switch", + "try", + "flatpak", + "portage", + "source", + "binary", + "nix", + "nixpkgs", + "snap", + "appimage", + "ebuild", +]; + +/// Parse an explicit `install ` or `install using/via/with ` +/// request. Returns `None` for a vague reference such as "install the flatpak +/// one", which is a conversational follow-up rather than a new application. +pub fn parse_explicit_install(query: &str) -> Option<(String, Option)> { + let lower = query.trim().to_ascii_lowercase(); + let lower = lower.strip_prefix("please ").unwrap_or(&lower).trim(); + let rest = lower + .strip_prefix("install ") + .or_else(|| lower.strip_prefix("add "))?; + let tokens: Vec<&str> = rest.split_whitespace().collect(); + let app = tokens + .first() + .copied() + .filter(|t| !NON_APP_TOKENS.contains(t) && !t.starts_with('-'))?; + let mut backend = None; + for token in &tokens[1..] { + if let Some(b) = backend_from_word(token) { + backend = Some(b); + } else if !NON_APP_TOKENS.contains(token) { + // A trailing word that is not a source or a filler makes this an + // ambiguous instruction; let the model investigate it instead. + return None; + } + } + Some((app.to_string(), backend)) +} + /// Analyze incoming query against the most recent conversation turn. pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option { let last = history.turns.last()?; @@ -148,7 +299,6 @@ pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option Option Option Option")); + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "history must be private"); + + // Clearing removes the context used for later follow-ups. + clear_history(&path).unwrap(); + assert!(!path.exists()); + assert!(load_history(&path).turns.is_empty()); + } + + #[test] + fn history_is_bounded() { + let temp = tempdir().unwrap(); + let path = temp.path().join("conversation.json"); + for i in 0..(MAX_TURNS + 5) { + save_turn( + &path, + &Redactor::new(), + ConversationTurn { + timestamp_unix: now_unix(), + query: format!("install app{i}"), + response_kind: "install".into(), + application: Some(format!("app{i}")), + chosen_candidate: None, + alternatives: vec![], + plan_id: None, + plan_digest: None, + rationale: vec![], + }, + ) + .unwrap(); + } + assert_eq!(load_history(&path).turns.len(), MAX_TURNS); + } + + #[test] + fn long_text_is_bounded_not_stored_raw() { + let temp = tempdir().unwrap(); + let path = temp.path().join("conversation.json"); + let long = "x".repeat(2000); + save_turn( + &path, + &Redactor::new(), + ConversationTurn { + timestamp_unix: now_unix(), + query: long.clone(), + response_kind: "plan".into(), + application: None, + chosen_candidate: None, + alternatives: vec![], + plan_id: None, + plan_digest: None, + rationale: vec![], + }, + ) + .unwrap(); + let history = load_history(&path); + assert!(history.turns[0].query.chars().count() <= MAX_TEXT_CHARS + 1); + assert!(!history.turns[0].query.contains(&long)); + } } diff --git a/installer-rs/crates/phoebus-installer/src/lib.rs b/installer-rs/crates/phoebus-installer/src/lib.rs index d553f84..9050454 100644 --- a/installer-rs/crates/phoebus-installer/src/lib.rs +++ b/installer-rs/crates/phoebus-installer/src/lib.rs @@ -1,6 +1,7 @@ //! Phoebus installer orchestration and CLI support. pub mod ai_guide; +pub mod ai_setup; pub mod assistant_bridge; pub mod conversation; pub mod gui_bridge; diff --git a/installer-rs/crates/phoebus-installer/src/service.rs b/installer-rs/crates/phoebus-installer/src/service.rs index 6a48e2e..bb84235 100644 --- a/installer-rs/crates/phoebus-installer/src/service.rs +++ b/installer-rs/crates/phoebus-installer/src/service.rs @@ -10,6 +10,7 @@ //! - Two-phase transaction logging (`begin` before mutation, `finish` with verification) //! - Unprivileged-to-privileged desktop Polkit elevation (`pkexec`) +use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -33,7 +34,11 @@ use sha2::{Digest, Sha256}; pub const DEFAULT_PLAN_TTL_SECONDS: u64 = 900; // 15 minutes +/// How many plan identifiers may be generated before the process-wide counter +/// wraps. Identifiers also include 128 bits of randomness from `/dev/urandom`. static PLAN_COUNTER: AtomicU64 = AtomicU64::new(1); +/// A plan id is exactly this token: no separators, no traversal. +const PLAN_ID_HEX_LEN: usize = 32; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -65,11 +70,47 @@ pub struct PreparedPlan { pub warnings: Vec, pub actions: Vec, pub effects: ResolvedPlan, + /// Per-step resolved effects, so a multi-action plan can be revalidated + /// action by action instead of comparing one action against the aggregate. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub step_effects: Vec, pub digest: String, pub verification: String, pub requires_root: bool, pub source: String, pub executed: bool, + /// Canonical root the plan was reviewed against. Elevated execution refuses + /// to run against any other root (never silently falls back to `/`). + #[serde(default)] + pub target_root: String, + /// The unprivileged user that reviewed and approved the plan. A privileged + /// broker refuses to run a plan prepared for another user. + #[serde(default)] + pub initiator_uid: u32, + /// Self-consistency seal over the reviewed fields (including target root, + /// initiator and digest). Rejected if it does not match on reload. + #[serde(default)] + pub integrity: String, +} + +/// A handle to a prepared plan that the broker has atomically claimed for +/// execution. Holding it proves the plan was consumed exactly once. +#[derive(Debug)] +pub struct PlanClaim { + marker: PathBuf, +} + +impl PlanClaim { + pub fn marker_path(&self) -> &Path { + &self.marker + } +} + +impl Drop for PlanClaim { + fn drop(&mut self) { + // The claim marker is intentionally left in place: it is the durable + // record that the plan was consumed, so a retry cannot repeat it. + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -80,6 +121,10 @@ pub struct PlanExecutionOutcome { pub verification: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub output: Vec, + /// A concrete command that launches the installed application, when a + /// desktop entry could be identified. Never guessed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub launch: Option>, } impl PreparedPlan { @@ -216,6 +261,132 @@ pub fn effective_uid() -> u32 { .unwrap_or(1) } +/// Canonicalise a target root so two spellings of the same path compare equal. +/// When the path cannot be canonicalised (e.g. a not-yet-created target), fall +/// back to the lexical path rather than silently selecting `/`. +pub fn canonical_root(root: &Path) -> String { + match std::fs::canonicalize(root) { + Ok(p) => p.to_string_lossy().to_string(), + Err(_) => { + let p = if root.as_os_str().is_empty() { + Path::new("/") + } else { + root + }; + p.to_string_lossy().to_string() + } + } +} + +/// 128 bits of unpredictable data for a plan identifier/marker name. +fn random_token() -> String { + let mut bytes = [0u8; 16]; + let filled = std::fs::File::open("/dev/urandom") + .and_then(|mut f| { + use std::io::Read; + f.read_exact(&mut bytes) + }) + .is_ok(); + if !filled { + // Fallback that is still unique within a boot: time + pid + counter. + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let mut hasher = Sha256::new(); + hasher.update(nanos.to_le_bytes()); + hasher.update(std::process::id().to_le_bytes()); + hasher.update(PLAN_COUNTER.fetch_add(1, Ordering::SeqCst).to_le_bytes()); + let digest = format!("{:x}", hasher.finalize()); + return digest[..PLAN_ID_HEX_LEN].to_string(); + } + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// A fresh, unpredictable plan identifier: `plan--<32 hex>`. +pub(crate) fn fresh_plan_id(prefix: &str) -> String { + let counter = PLAN_COUNTER.fetch_add(1, Ordering::SeqCst); + let mut hasher = Sha256::new(); + hasher.update(random_token().as_bytes()); + hasher.update(counter.to_le_bytes()); + let digest = format!("{:x}", hasher.finalize()); + format!("plan-{prefix}-{}", &digest[..PLAN_ID_HEX_LEN]) +} + +fn is_safe_plan_id(plan_id: &str) -> bool { + !plan_id.is_empty() + && plan_id.len() <= 128 + && plan_id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// Recompute the self-consistency seal over every reviewed field. The stored +/// `integrity` value is deliberately excluded. A reload whose recomputation +/// differs was modified after it was approved. +fn plan_integrity(plan: &PreparedPlan) -> String { + let mut hasher = Sha256::new(); + hasher.update(plan.id.as_bytes()); + hasher.update(b"\0"); + hasher.update(format!("{:?}", plan.kind).as_bytes()); + hasher.update(b"\0"); + hasher.update(plan.created_unix.to_le_bytes()); + hasher.update(plan.expires_unix.to_le_bytes()); + hasher.update(plan.digest.as_bytes()); + hasher.update(b"\0"); + hasher.update(plan.effects.digest.as_bytes()); + hasher.update(b"\0"); + if let Some(c) = &plan.candidate { + hasher.update(c.backend.as_str().as_bytes()); + hasher.update(b"\0"); + hasher.update(c.id.as_bytes()); + hasher.update(b"\0"); + hasher.update(c.version.as_deref().unwrap_or("").as_bytes()); + hasher.update(b"\0"); + } + for act in &plan.actions { + hasher.update(serde_json::to_string(act).unwrap_or_default().as_bytes()); + hasher.update(b"\0"); + } + for step in &plan.step_effects { + hasher.update(step.digest.as_bytes()); + hasher.update(b"\0"); + } + hasher.update(plan.target_root.as_bytes()); + hasher.update(b"\0"); + hasher.update(plan.source.as_bytes()); + hasher.update(b"\0"); + hasher.update(plan.initiator_uid.to_le_bytes()); + hasher.update(b"\0"); + hasher.update([plan.requires_root as u8]); + hasher.update([plan.executed as u8]); + // Everything the human reviewed is sealed, so a modified summary or + // verification statement cannot pass as the approved plan. + for field in [ + &plan.summary, + &plan.recommendation, + plan.application.as_deref().unwrap_or(""), + &plan.verification, + ] { + hasher.update(field.as_bytes()); + hasher.update(b"\0"); + } + for line in plan.rationale.iter().chain(plan.warnings.iter()) { + hasher.update(line.as_bytes()); + hasher.update(b"\0"); + } + for alt in &plan.alternatives { + hasher.update(serde_json::to_string(alt).unwrap_or_default().as_bytes()); + hasher.update(b"\0"); + } + format!("{:x}", hasher.finalize()) +} + +/// Compute and store the plan seal. Must be called before persistence. +pub fn seal_plan(plan: &mut PreparedPlan) { + plan.integrity = plan_integrity(plan); +} + /// Compute a cryptographic digest binding the exact actions, candidate, and effects. pub fn compute_plan_digest( actions: &[SystemAction], @@ -294,61 +465,219 @@ pub fn format_recommendation(candidate: &Candidate, application: &str) -> String // PlanStore // ----------------------------------------------------------------------------- -pub struct PlanStore; +/// Protected, per-user plan storage. +/// +/// A plan is written with a 0600 mode inside a 0700 directory owned by the +/// reviewing user (or the broker for root). Reloading rejects a symlink, a +/// file owned by someone other than the initiator/root, or a group/world +/// writable file. Consumption uses an `O_EXCL` marker so two concurrent +/// executions cannot both run the same plan. +#[derive(Debug, Clone)] +pub struct PlanStore { + dir: PathBuf, + /// The uid a plan is expected to belong to. The privileged broker sets this + /// to the initiating user so it can read that user's plan while still + /// rejecting a file owned by anyone else. + expected_uid: Option, +} impl PlanStore { - pub fn plan_dir() -> PathBuf { + /// Storage for a specific uid. Used by the privileged broker, which + /// recomputes the directory from the uid the caller passed rather than + /// trusting an arbitrary path. + pub fn for_uid(uid: u32) -> Self { if let Ok(dir) = std::env::var("PHOEBUS_PLANS_DIR") { - return PathBuf::from(dir); + return Self { + dir: PathBuf::from(dir), + expected_uid: Some(uid), + }; } - let run_dir = PathBuf::from("/run/phoebus/plans"); - if std::fs::create_dir_all(&run_dir).is_ok() { - return run_dir; - } - let temp = std::env::temp_dir().join("phoebus-plans"); - let _ = std::fs::create_dir_all(&temp); - temp - } - - pub fn plan_path(plan_id: &str) -> PathBuf { - if plan_id.contains('/') || plan_id.contains('\\') { - PathBuf::from(plan_id) + let candidates: Vec = if uid == 0 { + vec![PathBuf::from("/run/phoebus/plans")] } else { - Self::plan_dir().join(format!("{plan_id}.json")) + // Prefer the canonical per-user runtime path so the privileged + // broker (which derives the same path from the uid) finds it. + let mut v = vec![PathBuf::from(format!("/run/user/{uid}/phoebus/plans"))]; + if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") { + v.push(PathBuf::from(xdg).join("phoebus/plans")); + } + v + }; + for dir in candidates { + if std::fs::create_dir_all(&dir).is_ok() { + return Self { + dir, + expected_uid: Some(uid), + }; + } + } + let temp = std::env::temp_dir().join(format!("phoebus-plans-{uid}")); + let _ = std::fs::create_dir_all(&temp); + Self { + dir: temp, + expected_uid: Some(uid), } } - pub fn save(plan: &PreparedPlan) -> Result { - let path = Self::plan_path(&plan.id); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?; + pub fn for_current_user() -> Self { + Self::for_uid(effective_uid()) + } + + /// Explicit directory, for tests and callers that manage their own store. + pub fn with_dir(dir: impl Into) -> Self { + Self { + dir: dir.into(), + expected_uid: None, } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn ensure_dir(&self) -> Result<()> { + std::fs::create_dir_all(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700)); + } + Ok(()) + } + + fn path(&self, plan_id: &str, suffix: &str) -> Result { + if !is_safe_plan_id(plan_id) { + return Err(ExecError::operation( + "service", + "plan path", + format!("unsafe plan identifier `{plan_id}`"), + )); + } + Ok(self.dir.join(format!("{plan_id}{suffix}"))) + } + + /// Write a plan atomically (temp file -> fsync -> rename) with mode 0600. + pub fn save(&self, plan: &mut PreparedPlan) -> Result { + seal_plan(plan); + let path = self.path(&plan.id, ".json")?; + self.ensure_dir()?; let text = serde_json::to_string_pretty(plan) .map_err(|e| ExecError::operation("service", "serialize plan", e.to_string()))?; - std::fs::write(&path, text).map_err(|e| ExecError::io(path.clone(), e))?; + + let tmp = self.dir.join(format!(".{}.tmp", random_token())); + { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut file = opts.open(&tmp).map_err(|e| ExecError::io(tmp.clone(), e))?; + file.write_all(text.as_bytes()) + .and_then(|_| file.flush()) + .and_then(|_| file.sync_all()) + .map_err(|e| ExecError::io(tmp.clone(), e))?; + } + std::fs::rename(&tmp, &path).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + ExecError::io(path.clone(), e) + })?; + if let Ok(dir) = std::fs::File::open(&self.dir) { + let _ = dir.sync_all(); + } Ok(path) } - pub fn load(plan_id: &str) -> Result { - let path = Self::plan_path(plan_id); - if !path.is_file() { + /// Load a plan, rejecting malformed identifiers, symlinks and unsafe + /// ownership/permissions. The caller still has to validate the contents. + pub fn load(&self, plan_id: &str) -> Result { + let path = self.path(plan_id, ".json")?; + let meta = std::fs::symlink_metadata(&path).map_err(|_| { + ExecError::operation( + "service", + "load plan", + format!("plan `{plan_id}` not found, consumed or expired"), + ) + })?; + if meta.file_type().is_symlink() { return Err(ExecError::operation( "service", "load plan", - format!("plan `{plan_id}` not found or expired"), + "plan path is a symlink; refusing to follow it", )); } + if !meta.is_file() { + return Err(ExecError::operation( + "service", + "load plan", + "plan path is not a regular file", + )); + } + #[cfg(unix)] + { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + if meta.permissions().mode() & 0o022 != 0 { + return Err(ExecError::operation( + "service", + "load plan", + "plan file is group/world writable; refusing to trust it", + )); + } + let owner = meta.uid(); + let expected = self.expected_uid.unwrap_or_else(effective_uid); + // The broker runs as root but is reading the initiating user's plan, + // so the expected owner is the initiator, not root. A plan owned by + // a third party is rejected. + if owner != expected && owner != 0 { + return Err(ExecError::operation( + "service", + "load plan", + format!("plan file is owned by uid {owner}, not the expected uid {expected}"), + )); + } + } let text = std::fs::read_to_string(&path).map_err(|e| ExecError::io(path.clone(), e))?; let plan: PreparedPlan = serde_json::from_str(&text) .map_err(|e| ExecError::operation("service", "deserialize plan", e.to_string()))?; + if plan.id != plan_id { + return Err(ExecError::operation( + "service", + "load plan", + "plan identifier does not match its storage name", + )); + } Ok(plan) } - pub fn mark_executed(plan_id: &str) -> Result<()> { - let mut plan = Self::load(plan_id)?; - plan.executed = true; - Self::save(&plan)?; - Ok(()) + /// Atomically claim a plan for execution. Returns a guard that keeps the + /// marker on disk; a second claim (or a retry after a crash) fails. + pub fn claim(&self, plan_id: &str) -> Result { + let marker = self.path(plan_id, ".claim")?; + self.ensure_dir()?; + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + opts.open(&marker).map_err(|e| { + ExecError::operation( + "service", + "claim plan", + format!("plan `{plan_id}` is already consumed or being executed ({e})"), + ) + })?; + Ok(PlanClaim { marker }) + } + + /// True when a plan has already been claimed (consumed) for execution. + pub fn is_claimed(&self, plan_id: &str) -> bool { + match self.path(plan_id, ".claim") { + Ok(p) => p.exists(), + Err(_) => true, + } } } @@ -358,6 +687,7 @@ impl PlanStore { /// Plan an installation using AI investigation and policy checks. pub fn plan_install( + plans: &PlanStore, exec: &Exec, root: &Path, request: &InstallRequest, @@ -377,11 +707,12 @@ pub fn plan_install( }; let resolved = install::resolve_with_ai(exec, root, request, session, ai, facts)?; - build_install_plan(resolved, PlanKind::Install) + build_install_plan(plans, root, resolved, PlanKind::Install) } /// Plan an installation deterministically without contacting a model. pub fn plan_legacy_install( + plans: &PlanStore, exec: &Exec, root: &Path, request: &InstallRequest, @@ -394,13 +725,17 @@ pub fn plan_legacy_install( )); } let resolved = install::resolve_explicit(exec, root, request)?; - build_install_plan(resolved, PlanKind::LegacyInstall) + build_install_plan(plans, root, resolved, PlanKind::LegacyInstall) } -fn build_install_plan(resolved: install::ResolvedInstall, kind: PlanKind) -> Result { +fn build_install_plan( + plans: &PlanStore, + root: &Path, + resolved: install::ResolvedInstall, + kind: PlanKind, +) -> Result { let now = now_unix(); - let counter = PLAN_COUNTER.fetch_add(1, Ordering::SeqCst); - let plan_id = format!("plan-inst-{now}-{counter}"); + let plan_id = fresh_plan_id("inst"); let rec = format_recommendation(&resolved.candidate, &resolved.request.application); let source_display = match resolved.candidate.backend { @@ -418,8 +753,9 @@ fn build_install_plan(resolved: install::ResolvedInstall, kind: PlanKind) -> Res let digest = resolved.approval_digest(); let actions = vec![resolved.action.clone()]; let requires_root = resolved.action.is_mutating(); + let step_effects = vec![resolved.effects.clone()]; - let plan = PreparedPlan { + let mut plan = PreparedPlan { id: plan_id, created_unix: now, expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, @@ -437,24 +773,30 @@ fn build_install_plan(resolved: install::ResolvedInstall, kind: PlanKind) -> Res warnings: resolved.warnings.clone(), actions, effects: resolved.effects.clone(), + step_effects, digest, verification: resolved.verification.clone(), requires_root, source: source_display, executed: false, + target_root: canonical_root(root), + initiator_uid: effective_uid(), + integrity: String::new(), }; - PlanStore::save(&plan)?; + plans.save(&mut plan)?; Ok(plan) } -/// Plan an application removal across supported sources preserving user data by default. -pub fn plan_removal( +/// Deterministically choose which installed copy a removal targets. Shared by +/// the legacy and AI-first paths so ownership discovery and the ambiguity +/// policy cannot diverge. Ambiguity always requires an explicit lane flag. +pub fn select_removal_copy( exec: &Exec, root: &Path, application: &str, backend_filter: Option, -) -> Result { +) -> Result { let inspection = chooser::installed_copies(exec, root, application); if inspection.copies.is_empty() { return Err(ExecError::operation( @@ -464,8 +806,8 @@ pub fn plan_removal( )); } - let target_copy = if let Some(b) = backend_filter { - inspection + if let Some(b) = backend_filter { + return inspection .copies .into_iter() .find(|c| c.backend == b.as_str()) @@ -478,8 +820,9 @@ pub fn plan_removal( b.as_str() ), ) - })? - } else if inspection.copies.len() > 1 { + }); + } + if inspection.copies.len() > 1 { let details = inspection .copies .iter() @@ -493,10 +836,136 @@ pub fn plan_removal( "`{application}` is installed in multiple lanes: {details}. Specify which one to remove explicitly (e.g. sys remove {application} --flatpak or --portage)." ), )); - } else { - inspection.copies.into_iter().next().unwrap() - }; + } + Ok(inspection.copies.into_iter().next().unwrap()) +} +/// Plan an application removal across supported sources preserving user data by +/// default, without contacting a model (legacy mode only). +pub fn plan_removal( + plans: &PlanStore, + exec: &Exec, + root: &Path, + application: &str, + backend_filter: Option, +) -> Result { + let target_copy = select_removal_copy(exec, root, application, backend_filter)?; + build_removal_plan( + plans, + exec, + root, + application, + &target_copy, + Vec::new(), + Vec::new(), + ) +} + +/// Plan an application removal through the connected model (the default). The +/// deterministic discovery and ambiguity policy run first; the model must then +/// confirm exactly the discovered target. A model failure, or a proposal that +/// does not match the deterministic target, stops the workflow. +pub fn plan_removal_with_ai( + plans: &PlanStore, + exec: &Exec, + root: &Path, + application: &str, + backend_filter: Option, + ai: &AiInstall, + facts: &SystemFacts, +) -> Result { + let target_copy = select_removal_copy(exec, root, application, backend_filter)?; + let discovered = chooser::installed_copies(exec, root, application); + let list = discovered + .copies + .iter() + .map(|c| format!("{} ({})", c.id, c.backend)) + .collect::>() + .join(", "); + + let instruction = format!( + "The user asked to remove `{application}`. Read-only discovery found these installed \ + copies: [{list}]. The policy-selected target is `{}` in the {} lane. Confirm a removal \ + plan for exactly that copy by proposing the matching remove action; if the request is \ + ambiguous, propose no action and explain what clarification is needed.", + target_copy.id, target_copy.backend + ); + let assistant_plan: AssistantPlan = complete_plan( + ai.provider, + &ai.endpoint, + &ai.model, + facts, + &instruction, + ai.transport, + ) + .map_err(|e| ExecError::operation("service", "plan_removal_with_ai", e.to_string()))?; + + if assistant_plan.actions.len() != 1 + || !removal_action_matches(&assistant_plan.actions[0], &target_copy) + { + return Err(ExecError::operation( + "service", + "plan_removal_with_ai", + format!( + "the model did not confirm the discovered removal target `{}` ({}); no removal \ + plan was produced", + target_copy.id, target_copy.backend + ), + )); + } + + let mut rationale: Vec = assistant_plan + .rationale + .into_iter() + .map(|r| format!("AI: {}", r.reason)) + .collect(); + if rationale.is_empty() { + rationale.push(format!( + "AI confirmed removal of the discovered {} copy", + target_copy.backend + )); + } + + build_removal_plan( + plans, + exec, + root, + application, + &target_copy, + rationale, + Vec::new(), + ) +} + +/// Whether a proposed action is the correct removal of the discovered copy. +fn removal_action_matches(action: &SystemAction, copy: &chooser::InstalledCopy) -> bool { + match (action, copy.backend.as_str()) { + (SystemAction::FlatpakRemove { app_id }, "flatpak") => app_id == ©.id, + (SystemAction::SnapRemove { name }, "snap") => name == ©.id, + (SystemAction::AppImageRemove { name, .. }, "appimage") => name == ©.id, + (SystemAction::RemovePackage { atom }, _) + if copy.backend != "flatpak" + && copy.backend != "snap" + && copy.backend != "appimage" => + { + atom == ©.id + } + _ => false, + } +} + +/// Build a removal plan for a specific, already-discovered installed copy. +/// Used by both the deterministic (legacy) path and the AI-first path, so the +/// ownership discovery and policy validation are identical. +pub fn build_removal_plan( + plans: &PlanStore, + exec: &Exec, + root: &Path, + application: &str, + target_copy: &chooser::InstalledCopy, + rationale: Vec, + warnings: Vec, +) -> Result { let action = match target_copy.backend.as_str() { "flatpak" => SystemAction::FlatpakRemove { app_id: target_copy.id.clone(), @@ -516,12 +985,21 @@ pub fn plan_removal( let effects = actions::resolve_effects(exec, &action, root)?; let now = now_unix(); - let counter = PLAN_COUNTER.fetch_add(1, Ordering::SeqCst); - let plan_id = format!("plan-rem-{now}-{counter}"); + let plan_id = fresh_plan_id("rem"); let actions_vec = vec![action.clone()]; let digest = compute_plan_digest(&actions_vec, None, &effects); - let plan = PreparedPlan { + let mut rationale = rationale; + rationale.insert( + 0, + format!( + "installed package {} detected in {} lane", + target_copy.id, target_copy.backend + ), + ); + rationale.push("preserves user configuration and data in home directory by default".into()); + + let mut plan = PreparedPlan { id: plan_id, created_unix: now, expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, @@ -534,29 +1012,31 @@ pub fn plan_removal( application: Some(application.to_string()), candidate: None, alternatives: Vec::new(), - rationale: vec![ - format!("installed package {} detected in {} lane", target_copy.id, target_copy.backend), - "preserves user configuration and data in home directory by default".into(), - ], - warnings: Vec::new(), + rationale, + warnings, actions: actions_vec, - effects, + effects: effects.clone(), + step_effects: vec![effects], digest, verification: format!( "verify that `{}` ({}) is completely removed from the system", target_copy.id, target_copy.backend ), requires_root: action.is_mutating(), - source: target_copy.backend, + source: target_copy.backend.clone(), executed: false, + target_root: canonical_root(root), + initiator_uid: effective_uid(), + integrity: String::new(), }; - PlanStore::save(&plan)?; + plans.save(&mut plan)?; Ok(plan) } /// Plan general system administration tasks via connected model. pub fn plan_general( + plans: &PlanStore, exec: &Exec, root: &Path, query: &str, @@ -578,6 +1058,7 @@ pub fn plan_general( ..Default::default() }; let mut any_mutating = false; + let mut step_effects = Vec::new(); for act in &assistant_plan.actions { let eff = actions::resolve_effects(exec, act, root).map_err(|e| { @@ -588,16 +1069,18 @@ pub fn plan_general( ) })?; if eff.established { - combined_effects.effects.extend(eff.effects); - combined_effects.consequences.extend(eff.consequences); + combined_effects.effects.extend(eff.effects.clone()); + combined_effects + .consequences + .extend(eff.consequences.clone()); } + step_effects.push(eff); any_mutating |= act.is_mutating(); } combined_effects.recompute_digest(); let now = now_unix(); - let counter = PLAN_COUNTER.fetch_add(1, Ordering::SeqCst); - let plan_id = format!("plan-gen-{now}-{counter}"); + let plan_id = fresh_plan_id("gen"); let digest = compute_plan_digest(&assistant_plan.actions, None, &combined_effects); let rationale_strings: Vec = assistant_plan .rationale @@ -605,7 +1088,7 @@ pub fn plan_general( .map(|r| format!("{}: {}", r.action, r.reason)) .collect(); - let plan = PreparedPlan { + let mut plan = PreparedPlan { id: plan_id, created_unix: now, expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, @@ -619,14 +1102,18 @@ pub fn plan_general( warnings: Vec::new(), actions: assistant_plan.actions, effects: combined_effects, + step_effects, digest, verification: "verify execution of planned actions".into(), requires_root: any_mutating, source: "AI Assistant".into(), executed: false, + target_root: canonical_root(root), + initiator_uid: effective_uid(), + integrity: String::new(), }; - PlanStore::save(&plan)?; + plans.save(&mut plan)?; Ok(plan) } @@ -647,156 +1134,319 @@ impl Confirmation for ServiceConfirm { } } -/// Execute a prepared plan with full validation, elevation, verification, and transaction recording. +/// The single authoritative validation boundary. Runs immediately before any +/// privileged mutation, in both the unprivileged pre-check and the broker after +/// authentication. It binds the approval to the exact actions, effects, +/// candidate, target root and initiating user, re-derives the plan seal, and +/// revalidates live state. Plan files are untrusted input. +pub fn validate_prepared_plan( + exec: &Exec, + root: &Path, + plan: &PreparedPlan, + expected_digest: Option<&str>, + initiator_uid: u32, +) -> Result<()> { + if plan.integrity.is_empty() || plan.integrity != plan_integrity(plan) { + return Err(ExecError::operation( + "service", + "validate plan", + "plan integrity check failed; the plan was modified after it was reviewed", + )); + } + if !is_safe_plan_id(&plan.id) { + return Err(ExecError::operation( + "service", + "validate plan", + "plan has an invalid identifier", + )); + } + if plan.executed { + return Err(ExecError::operation( + "service", + "validate plan", + "plan has already been executed; replayed plans are rejected", + )); + } + if now_unix() > plan.expires_unix { + return Err(ExecError::operation( + "service", + "validate plan", + "plan has expired; review and approve a fresh plan", + )); + } + if let Some(digest) = expected_digest { + if !digest.is_empty() && plan.digest != digest { + return Err(ExecError::operation( + "service", + "validate plan", + "approval digest mismatch; the plan was altered or is not the one reviewed", + )); + } + } + if plan.target_root.is_empty() { + return Err(ExecError::operation( + "service", + "validate plan", + "plan does not record a target root; refusing to guess `/`", + )); + } + let want_root = canonical_root(root); + if plan.target_root != want_root { + return Err(ExecError::operation( + "service", + "validate plan", + format!( + "target root mismatch: the plan was reviewed for {} but execution targets {}", + plan.target_root, want_root + ), + )); + } + if plan.initiator_uid != initiator_uid { + return Err(ExecError::operation( + "service", + "validate plan", + format!( + "plan belongs to uid {} and cannot be executed by uid {initiator_uid}", + plan.initiator_uid + ), + )); + } + if plan.actions.is_empty() { + return Err(ExecError::operation( + "service", + "validate plan", + "plan proposes no actions", + )); + } + revalidate_plan_state(exec, root, plan) +} + +/// Revalidate a plan's material state against live metadata. A material change +/// invalidates the earlier approval. +fn revalidate_plan_state(exec: &Exec, root: &Path, plan: &PreparedPlan) -> Result<()> { + match plan.kind { + PlanKind::Install | PlanKind::LegacyInstall => { + let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) else { + return Err(ExecError::operation( + "service", + "revalidate", + "installation plan is missing its candidate or action", + )); + }; + let resolved = install::ResolvedInstall { + request: InstallRequest::new(plan.application.as_deref().unwrap_or("")), + candidate: cand.clone(), + action: act.clone(), + effects: plan.effects.clone(), + rationale: plan.rationale.clone(), + alternatives: plan.alternatives.clone(), + source: match plan.kind { + PlanKind::LegacyInstall => InstallSource::ExplicitBackend, + _ => InstallSource::AiRecommendation, + }, + warnings: plan.warnings.clone(), + verification: plan.verification.clone(), + }; + let current_digest = install::revalidate(exec, root, &resolved).map_err(|e| { + ExecError::operation( + "service", + "revalidate", + format!("the reviewed plan changed before execution ({e}); review again"), + ) + })?; + if current_digest != plan.digest { + return Err(ExecError::operation( + "service", + "revalidate", + "system state or package metadata changed materially since review; review again", + )); + } + } + PlanKind::Removal => { + let Some(app) = &plan.application else { + return Err(ExecError::operation( + "service", + "revalidate", + "removal plan has no application", + )); + }; + let check = chooser::installed_copies(exec, root, app); + if !check.copies.iter().any(|c| c.backend == plan.source) { + return Err(ExecError::operation( + "service", + "revalidate", + format!( + "`{app}` is no longer installed via {}; the removal plan is stale", + plan.source + ), + )); + } + if let Some(act) = plan.actions.first() { + let eff = actions::resolve_effects(exec, act, root)?; + if eff.established && plan.effects.established && eff.digest != plan.effects.digest + { + return Err(ExecError::operation( + "service", + "revalidate", + "the removal effects changed since review; review again", + )); + } + } + } + PlanKind::General | PlanKind::Undo => { + if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() { + // Compare each step against its own reviewed effects, never one + // action against the whole plan. + for (act, reviewed) in plan.actions.iter().zip(plan.step_effects.iter()) { + let eff = actions::resolve_effects(exec, act, root)?; + if reviewed.established && eff.established && reviewed.digest != eff.digest { + return Err(ExecError::operation( + "service", + "revalidate", + format!( + "effects for `{}` changed materially since review; review again", + act.describe() + ), + )); + } + } + } else { + // Older plans carried only the aggregate; recompute the same + // aggregate and compare, rather than mixing per-action digests. + let mut combined = ResolvedPlan { + established: true, + ..Default::default() + }; + for act in &plan.actions { + let eff = actions::resolve_effects(exec, act, root)?; + if eff.established { + combined.effects.extend(eff.effects); + combined.consequences.extend(eff.consequences); + } + } + combined.recompute_digest(); + if plan.effects.established && combined.digest != plan.effects.digest { + return Err(ExecError::operation( + "service", + "revalidate", + "system state or package effects changed materially since review; review again", + )); + } + } + } + } + Ok(()) +} + +/// Execute a prepared plan with full validation, elevation, verification, and +/// transaction recording. pub fn execute_plan( exec: &Exec, root: &Path, + plans: &PlanStore, plan_id: &str, expected_digest: &str, assume_yes: bool, ) -> Result { - let plan = PlanStore::load(plan_id)?; - - // 1. Replay check - if plan.executed { + let initiator = effective_uid(); + let plan = plans.load(plan_id)?; + validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator)?; + if plans.is_claimed(plan_id) { return Err(ExecError::operation( "service", "execute_plan", - "plan has already been executed; replayed plans are rejected", + "plan has already been consumed; retrying will not repeat the mutation", )); } - // 2. TTL expiration check - let now = now_unix(); - if now > plan.expires_unix { - return Err(ExecError::operation( - "service", - "execute_plan", - "plan has expired; review and approve a fresh plan", - )); + if plan.requires_root && initiator != 0 { + return elevate_and_execute(root, plan, initiator); } - - // 3. Digest check - if plan.digest != expected_digest { - return Err(ExecError::operation( - "service", - "execute_plan", - "approval digest mismatch; plan was altered or invalid", - )); - } - - // 4. Revalidate against current system state - if let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) { - let dummy_req = InstallRequest::new(plan.application.as_deref().unwrap_or("")); - let resolved = install::ResolvedInstall { - request: dummy_req, - candidate: cand.clone(), - action: act.clone(), - effects: plan.effects.clone(), - rationale: plan.rationale.clone(), - alternatives: plan.alternatives.clone(), - source: match plan.kind { - PlanKind::LegacyInstall => InstallSource::ExplicitBackend, - _ => InstallSource::AiRecommendation, - }, - warnings: plan.warnings.clone(), - verification: plan.verification.clone(), - }; - let current_digest = install::revalidate(exec, root, &resolved).map_err(|e| { - ExecError::operation( - "service", - "revalidate", - format!("the reviewed plan changed before execution ({e}); review again"), - ) - })?; - if current_digest != plan.digest { - return Err(ExecError::operation( - "service", - "execute_plan", - "system state or package metadata changed materially since review; review again", - )); - } - } else { - for act in &plan.actions { - let eff = actions::resolve_effects(exec, act, root)?; - if eff.established && eff.digest != plan.effects.digest { - // If established digest changed - return Err(ExecError::operation( - "service", - "execute_plan", - "system state or package effects changed materially since review; review again", - )); - } - } - } - - // 5. Check privileges / elevate via pkexec if needed - if plan.requires_root && effective_uid() != 0 { - // Unprivileged GUI / user caller: elevate via pkexec - let plan_file = PlanStore::save(&plan)?; - let sys_exe = - std::env::current_exe().unwrap_or_else(|_| PathBuf::from("/usr/local/bin/sys")); - let pkexec_cmd = std::process::Command::new("pkexec") - .arg(sys_exe) - .arg("--broker") - .arg("--execute-plan") - .arg(&plan_file) - .output(); - - match pkexec_cmd { - Ok(output) => { - if output.status.success() { - let out_str = String::from_utf8_lossy(&output.stdout); - if let Ok(outcome) = serde_json::from_str::(&out_str) { - return Ok(outcome); - } - return Ok(PlanExecutionOutcome { - completed: true, - snapshot: None, - result: "ok".into(), - verification: plan.verification, - output: Vec::new(), - }); - } - let code = output.status.code().unwrap_or(1); - if code == 126 || code == 127 { - return Err(ExecError::operation( - "service", - "authenticate", - "Authentication was cancelled by the user", - )); - } - let err_msg = String::from_utf8_lossy(&output.stderr); - return Err(ExecError::operation( - "service", - "pkexec", - format!( - "Privileged execution failed (code {code}): {}", - err_msg.trim() - ), - )); - } - Err(e) => { - return Err(ExecError::operation( - "service", - "pkexec", - format!("Could not spawn pkexec for root authorization: {e}"), - )); - } - } - } - - // Direct execution (already privileged) - execute_plan_direct(exec, root, plan, assume_yes) + execute_prepared(exec, root, plans, plan, assume_yes) } -/// Execute a plan directly without further elevation checks (caller has verified privileges). -pub fn execute_plan_direct( +/// The privileged broker entry point. It repeats the full validation after +/// authentication (never trusting the unprivileged caller) and then executes. +pub fn execute_plan_privileged( exec: &Exec, root: &Path, + plans: &PlanStore, + plan_id: &str, + initiator_uid: u32, + assume_yes: bool, +) -> Result { + let plan = plans.load(plan_id)?; + validate_prepared_plan(exec, root, &plan, None, initiator_uid)?; + execute_prepared(exec, root, plans, plan, assume_yes) +} + +fn elevate_and_execute( + root: &Path, + plan: PreparedPlan, + initiator: u32, +) -> Result { + let sys_exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("/usr/local/bin/sys")); + // The privileged broker is given the plan identifier and initiating uid, + // never an arbitrary path, and the exact target root. A dropped `--root` + // would (correctly) fail validation rather than execute against `/`. + let output = std::process::Command::new("pkexec") + .arg(sys_exe) + .arg("--broker") + .arg("--execute-plan") + .arg(&plan.id) + .arg("--plan-uid") + .arg(initiator.to_string()) + .arg("--root") + .arg(canonical_root(root)) + .output() + .map_err(|e| { + ExecError::operation( + "service", + "pkexec", + format!("could not spawn pkexec for root authorization: {e}"), + ) + })?; + + if output.status.success() { + let out_str = String::from_utf8_lossy(&output.stdout); + return serde_json::from_str::(out_str.trim()).map_err(|e| { + ExecError::operation( + "service", + "broker protocol", + format!("privileged execution reported success but returned malformed output: {e}"), + ) + }); + } + let code = output.status.code().unwrap_or(1); + if code == 126 || code == 127 { + return Err(ExecError::operation( + "service", + "authenticate", + "authentication was cancelled; no changes were made", + )); + } + let err_msg = String::from_utf8_lossy(&output.stderr); + Err(ExecError::operation( + "service", + "pkexec", + format!( + "privileged execution failed (code {code}): {}", + err_msg.trim() + ), + )) +} + +/// Claim a plan and run it, recording a truthful transaction outcome on every +/// exit path (success, action failure, verification failure, cancellation). +fn execute_prepared( + exec: &Exec, + root: &Path, + plans: &PlanStore, plan: PreparedPlan, assume_yes: bool, ) -> Result { + // Authentication/refusal happens before the claim, so a refused plan is not + // consumed and stays reviewable (until it expires). let confirm = ServiceConfirm { assume_yes }; let auth = if plan.requires_root { Some(authorize(&confirm, &plan.summary, "execute")?) @@ -804,6 +1454,9 @@ pub fn execute_plan_direct( None }; + // Atomic claim: at most one caller can proceed with this plan. + let _claim = plans.claim(&plan.id)?; + let record = TransactionRecord { id: 0, created_unix: now_unix(), @@ -813,7 +1466,7 @@ pub fn execute_plan_direct( _ => "assistant".into(), }, summary: plan.summary.clone(), - actions: vec![plan.summary.clone()], + actions: plan.actions.iter().map(|a| a.describe()).collect(), result: "in progress".into(), snapshot: None, digest: Some(plan.digest.clone()), @@ -821,25 +1474,28 @@ pub fn execute_plan_direct( }; let tx_id = transaction::begin(exec, root, record)?; - let mut approved_steps = Vec::new(); - for act in &plan.actions { - let eff = actions::resolve_effects(exec, act, root)?; - approved_steps.push((act.clone(), eff)); - } + // Re-resolve each action's effects at the execution boundary (the same + // path a manual action takes). `validate_prepared_plan` has already + // revalidated them against the reviewed state, so this cannot smuggle a + // changed plan past approval. + let approved_steps: Vec<(SystemAction, ResolvedPlan)> = plan + .actions + .iter() + .map(|act| actions::resolve_effects(exec, act, root).map(|eff| (act.clone(), eff))) + .collect::>>()?; let run = actions::execute_plan(exec, &approved_steps, auth.as_ref(), root); + if let Some((action_str, detail)) = &run.failure { - let _ = transaction::finish( + finish_or_report( exec, root, tx_id, format!("failed: {detail}"), run.snapshot.clone(), - vec![TransactionOutcome::failed( - action_str.clone(), - detail.clone(), - )], - ); + run.outcomes.clone(), + "the action failed", + )?; return Err(ExecError::operation( "service", "execute", @@ -847,7 +1503,8 @@ pub fn execute_plan_direct( )); } - // Post-execution verification + // Post-execution verification. A verification error finishes the + // transaction as a failed verification; it never leaves it "in progress". let verification_result = match plan.kind { PlanKind::Install | PlanKind::LegacyInstall => { if let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) { @@ -865,7 +1522,21 @@ pub fn execute_plan_direct( warnings: plan.warnings.clone(), verification: plan.verification.clone(), }; - install::verify_installed(exec, root, &resolved)? + match install::verify_installed(exec, root, &resolved) { + Ok(text) => text, + Err(e) => { + finish_or_report( + exec, + root, + tx_id, + format!("verify failed: {e}"), + run.snapshot.clone(), + run.outcomes.clone(), + "verification failed", + )?; + return Err(e); + } + } } else { "verified ok".into() } @@ -878,14 +1549,15 @@ pub fn execute_plan_direct( "removal reported success but `{app}` is still present in {} ({})", ref_copy.backend, ref_copy.id ); - let _ = transaction::finish( + finish_or_report( exec, root, tx_id, format!("verify failed: {err}"), run.snapshot.clone(), - vec![TransactionOutcome::completed(plan.summary.clone())], - ); + run.outcomes.clone(), + "verification failed", + )?; return Err(ExecError::operation("service", "verify removal", err)); } format!("verified: `{app}` removed from {}", plan.source) @@ -896,17 +1568,16 @@ pub fn execute_plan_direct( _ => "ok".into(), }; - // Mark plan executed - let _ = PlanStore::mark_executed(&plan.id); + let launch = detect_launch(root, &plan); - // Finish transaction - transaction::finish( + finish_or_report( exec, root, tx_id, "ok", run.snapshot.clone(), - vec![TransactionOutcome::completed(plan.summary.clone())], + run.outcomes.clone(), + "the transaction could not be recorded", )?; let outputs: Vec = run.completed.into_iter().map(|(_, out)| out).collect(); @@ -917,9 +1588,68 @@ pub fn execute_plan_direct( result: "ok".into(), verification: verification_result, output: outputs, + launch, }) } +/// Finish a transaction, surfacing a persistence failure instead of hiding it. +/// The execution result is preserved either way. +fn finish_or_report( + exec: &Exec, + root: &Path, + tx_id: u64, + result: impl Into, + snapshot: Option, + outcomes: Vec, + persistence_note: &str, +) -> Result<()> { + let result = result.into(); + match transaction::finish(exec, root, tx_id, result.clone(), snapshot, outcomes) { + Ok(()) => Ok(()), + Err(e) => Err(ExecError::operation( + "service", + "record transaction", + format!("{persistence_note}: {result} (history error: {e})"), + )), + } +} + +/// Identify a concrete launch command for a freshly installed application. +/// Only offered when a desktop entry (or an unambiguous Flatpak/Snap command) +/// is actually found; never guessed. +fn detect_launch(root: &Path, plan: &PreparedPlan) -> Option> { + let candidate = plan.candidate.as_ref()?; + match candidate.backend { + Backend::Flatpak => { + return Some(vec!["flatpak".into(), "run".into(), candidate.id.clone()]) + } + Backend::Snap => return Some(vec![candidate.id.clone()]), + _ => {} + } + let app = plan.application.as_deref().unwrap_or(""); + let stem = app.rsplit('/').next().unwrap_or(app).to_ascii_lowercase(); + if stem.is_empty() { + return None; + } + let dir = root.join("usr/share/applications"); + let entries = std::fs::read_dir(&dir).ok()?; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("desktop") { + continue; + } + let file_stem = path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + if file_stem == stem || file_stem.starts_with(&format!("{stem}.")) { + return Some(vec!["gtk-launch".into(), file_stem]); + } + } + None +} + #[cfg(test)] mod tests { use super::*; @@ -964,92 +1694,520 @@ mod tests { assert!(!rec.contains("avoids a lengthy build")); } - #[test] - fn test_plan_store_save_load_mark_executed() { - let temp_dir = tempdir().unwrap(); - std::env::set_var("PHOEBUS_PLANS_DIR", temp_dir.path()); - - let plan = PreparedPlan { - id: "test-plan-1".into(), + /// Build a sealed plan for validation tests. + fn sealed( + id: &str, + kind: PlanKind, + actions: Vec, + digest: &str, + target_root: &Path, + initiator_uid: u32, + ) -> PreparedPlan { + let mut plan = PreparedPlan { + id: id.into(), created_unix: now_unix(), expires_unix: now_unix() + 900, - kind: PlanKind::Install, - summary: "install firefox".into(), + kind, + summary: "test plan".into(), recommendation: "rec".into(), application: Some("firefox".into()), - candidate: Some(sample_candidate()), - alternatives: Vec::new(), - rationale: vec!["isolated".into()], - warnings: Vec::new(), - actions: vec![SystemAction::FlatpakList], - effects: ResolvedPlan::default(), - digest: "digest123".into(), - verification: "verify".into(), - requires_root: false, - source: "Flathub".into(), - executed: false, - }; - - PlanStore::save(&plan).unwrap(); - let loaded = PlanStore::load("test-plan-1").unwrap(); - assert_eq!(loaded.id, "test-plan-1"); - assert!(!loaded.executed); - - PlanStore::mark_executed("test-plan-1").unwrap(); - let loaded_after = PlanStore::load("test-plan-1").unwrap(); - assert!(loaded_after.executed); - } - - #[test] - fn test_execute_plan_rejects_replayed_and_expired() { - let temp = tempdir().unwrap(); - let root = temp.path(); - let exec = make_test_exec(root); - let plans_dir = tempdir().unwrap(); - std::env::set_var("PHOEBUS_PLANS_DIR", plans_dir.path()); - - // 1. Expired plan - let expired_plan = PreparedPlan { - id: "expired-plan".into(), - created_unix: 100, - expires_unix: 200, // in the past - kind: PlanKind::General, - summary: "history".into(), - recommendation: "rec".into(), - application: None, candidate: None, alternatives: Vec::new(), rationale: Vec::new(), warnings: Vec::new(), - actions: vec![SystemAction::History], + actions, effects: ResolvedPlan::default(), - digest: "digest-exp".into(), + step_effects: Vec::new(), + digest: digest.into(), verification: "verify".into(), requires_root: false, - source: "sys".into(), + source: "test".into(), executed: false, + target_root: canonical_root(target_root), + initiator_uid, + integrity: String::new(), }; - PlanStore::save(&expired_plan).unwrap(); - let err = execute_plan(&exec, root, "expired-plan", "digest-exp", true).unwrap_err(); - assert!(err.to_string().contains("expired")); + seal_plan(&mut plan); + plan + } - // 2. Replayed plan - let mut replayed_plan = expired_plan; - replayed_plan.id = "replayed-plan".into(); - replayed_plan.expires_unix = now_unix() + 900; - replayed_plan.executed = true; - replayed_plan.digest = "digest-rep".into(); - PlanStore::save(&replayed_plan).unwrap(); - let err = execute_plan(&exec, root, "replayed-plan", "digest-rep", true).unwrap_err(); - assert!(err.to_string().contains("already been executed")); + #[test] + fn plan_store_roundtrips_and_claims_once() { + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + let mut plan = sealed( + "plan-abc", + PlanKind::General, + vec![SystemAction::History], + "d", + Path::new("/tmp"), + 0, + ); + store.save(&mut plan).unwrap(); + let loaded = store.load("plan-abc").unwrap(); + assert_eq!(loaded.id, "plan-abc"); - // 3. Digest mismatch - let mut mismatch_plan = replayed_plan; - mismatch_plan.id = "mismatch-plan".into(); - mismatch_plan.executed = false; - mismatch_plan.digest = "correct-digest".into(); - PlanStore::save(&mismatch_plan).unwrap(); - let err = execute_plan(&exec, root, "mismatch-plan", "wrong-digest", true).unwrap_err(); - assert!(err.to_string().contains("digest mismatch")); + let _claim = store.claim("plan-abc").unwrap(); + assert!(store.is_claimed("plan-abc")); + // A second claim (or a retry after a crash) must not run the mutation. + assert!(store.claim("plan-abc").is_err()); + } + + #[test] + fn concurrent_claims_allow_at_most_one_execution() { + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + let mut plan = sealed( + "plan-race", + PlanKind::General, + vec![SystemAction::History], + "d", + Path::new("/tmp"), + 0, + ); + store.save(&mut plan).unwrap(); + + let handles: Vec<_> = (0..8) + .map(|_| { + let store = store.clone(); + std::thread::spawn(move || store.claim("plan-race").is_ok()) + }) + .collect(); + let successes = handles + .into_iter() + .map(|h| h.join().expect("claim thread panicked")) + .filter(|won| *won) + .count(); + assert_eq!(successes, 1, "exactly one claim may win"); + } + + #[test] + fn replacing_the_plan_after_review_is_rejected() { + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let uid = effective_uid(); + + let mut original = sealed( + "plan-replace", + PlanKind::General, + vec![SystemAction::History], + "reviewed-digest", + root.path(), + uid, + ); + store.save(&mut original).unwrap(); + + // An attacker (or a re-plan) replaces the stored plan under the same id. + let mut replacement = sealed( + "plan-replace", + PlanKind::General, + vec![SystemAction::EnableService { + name: "sshd".into(), + }], + "different-digest", + root.path(), + uid, + ); + replacement.requires_root = true; + seal_plan(&mut replacement); + store.save(&mut replacement).unwrap(); + + // The unprivileged caller's reviewed digest no longer matches. + let err = execute_plan( + &exec, + root.path(), + &store, + "plan-replace", + "reviewed-digest", + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("digest mismatch"), "{err}"); + // And nothing was consumed. + assert!(!store.is_claimed("plan-replace")); + } + + #[test] + fn plan_store_rejects_traversal_and_bad_ids() { + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + assert!(store.load("../escape").is_err()); + assert!(store.load("a/b").is_err()); + assert!(store.load("").is_err()); + } + + #[test] + fn plan_store_rejects_group_writable_files() { + use std::os::unix::fs::PermissionsExt; + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + let mut plan = sealed( + "plan-mode", + PlanKind::General, + vec![SystemAction::History], + "d", + Path::new("/tmp"), + 0, + ); + let path = store.save(&mut plan).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap(); + assert!(store.load("plan-mode").is_err()); + } + + #[test] + fn validation_rejects_tampering_expiry_replay_root_and_uid() { + let store_dir = tempdir().unwrap(); + let store = PlanStore::with_dir(store_dir.path()); + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let uid = effective_uid(); + + // Baseline validates. + let mut plan = sealed( + "plan-ok", + PlanKind::General, + vec![SystemAction::History], + "same-digest", + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + let loaded = store.load("plan-ok").unwrap(); + validate_prepared_plan(&exec, root.path(), &loaded, Some("same-digest"), uid).unwrap(); + + // Tampering with any reviewed field breaks the seal. + let path = store_dir.path().join("plan-ok.json"); + let mut raw: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + raw["summary"] = serde_json::json!("tampered"); + std::fs::write(&path, serde_json::to_string(&raw).unwrap()).unwrap(); + let tampered = store.load("plan-ok").unwrap(); + let err = validate_prepared_plan(&exec, root.path(), &tampered, None, uid).unwrap_err(); + assert!(err.to_string().contains("integrity"), "{err}"); + + // Expired. + let mut expired = sealed( + "plan-exp", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + expired.expires_unix = 10; + seal_plan(&mut expired); + store.save(&mut expired).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-exp").unwrap(), + None, + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("expired"), "{err}"); + + // Replayed. + let mut replayed = sealed( + "plan-rep", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + replayed.executed = true; + seal_plan(&mut replayed); + store.save(&mut replayed).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-rep").unwrap(), + None, + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("already been executed"), "{err}"); + + // Wrong target root: reviewed for /, executed against the temp root. + let mut wrong_root = sealed( + "plan-root", + PlanKind::General, + vec![SystemAction::History], + "d", + Path::new("/"), + uid, + ); + seal_plan(&mut wrong_root); + store.save(&mut wrong_root).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-root").unwrap(), + None, + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("target root mismatch"), "{err}"); + + // Wrong initiator uid. + let mut wrong_uid = sealed( + "plan-uid", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + seal_plan(&mut wrong_uid); + store.save(&mut wrong_uid).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-uid").unwrap(), + None, + uid.wrapping_add(4242), + ) + .unwrap_err(); + assert!( + err.to_string().contains("cannot be executed by uid"), + "{err}" + ); + } + + #[test] + fn validation_rejects_digest_mismatch_and_malformed_action_set() { + let store_dir = tempdir().unwrap(); + let store = PlanStore::with_dir(store_dir.path()); + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let uid = effective_uid(); + + let mut plan = sealed( + "plan-dig", + PlanKind::General, + vec![SystemAction::History], + "correct", + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-dig").unwrap(), + Some("wrong"), + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("digest mismatch"), "{err}"); + + let mut empty = sealed( + "plan-empty", + PlanKind::General, + Vec::new(), + "d", + root.path(), + uid, + ); + seal_plan(&mut empty); + store.save(&mut empty).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-empty").unwrap(), + None, + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("no actions"), "{err}"); + } + + struct FlatpakRunner { + installed: std::sync::Arc, + /// When true, a successful `flatpak install` marks the app installed, + /// so verification can succeed. When false, verification always fails. + mark_on_install: bool, + } + + impl phoebus_executor::command::ProcessRunner for FlatpakRunner { + fn execute( + &self, + spec: &phoebus_executor::command::CommandSpec, + ) -> Result { + use std::time::Duration; + let ok = |s: String| phoebus_executor::command::CommandOutput { + status: 0, + success: true, + stdout: s.into_bytes(), + stderr: Vec::new(), + duration: Duration::from_millis(1), + }; + let invokes_flatpak_install = spec.args.iter().any(|a| a == "install") + && (spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak")); + if invokes_flatpak_install { + if self.mark_on_install { + self.installed + .store(true, std::sync::atomic::Ordering::SeqCst); + } + return Ok(ok("installed\n".into())); + } + let installed = self.installed.load(std::sync::atomic::Ordering::SeqCst); + match spec.program.as_str() { + "flatpak" if spec.args.iter().any(|a| a == "search") => { + Ok(ok("org.mozilla.firefox 128\n".into())) + } + "flatpak" if spec.args.iter().any(|a| a == "list") => { + if !installed { + return Ok(ok(String::new())); + } + // `--columns=application` (verification) vs the richer + // `application,name,version` (discovery). + if spec.args.iter().any(|a| a == "--columns=application") { + Ok(ok("org.mozilla.firefox\n".into())) + } else { + Ok(ok("org.mozilla.firefox Firefox 128\n".into())) + } + } + _ => Ok(ok(String::new())), + } + } + } + + fn make_exec_with_runner( + root: &Path, + runner: Box, + ) -> Exec { + let temp = tempdir().unwrap().keep(); + let logger = Logger::open(temp.join("test.log"), Redactor::new(), false); + Exec::new(runner, logger, false, root.to_path_buf(), temp) + } + + #[test] + fn install_verification_failure_finishes_the_transaction_as_failed() { + let root = tempdir().unwrap(); + let installed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let exec = make_exec_with_runner( + root.path(), + Box::new(FlatpakRunner { + installed: installed.clone(), + mark_on_install: false, + }), + ); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + + let mut request = InstallRequest::new("firefox"); + request.backend = Some(Backend::Flatpak); + let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap(); + + // The install command "succeeds" but `flatpak list` never reports the + // app: verification must fail and the transaction must not say "ok". + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &plan.id, + plan.initiator_uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("Flatpak"), "{err}"); + + let log = transaction::read(root.path()).unwrap(); + assert_eq!( + log.records.len(), + 1, + "one transaction, not stuck in progress" + ); + assert!( + log.records[0].result.starts_with("verify failed"), + "{}", + log.records[0].result + ); + // The plan was consumed exactly once and cannot be retried. + assert!(execute_plan_privileged( + &exec, + root.path(), + &store, + &plan.id, + plan.initiator_uid, + true, + ) + .is_err()); + } + + #[test] + fn successful_install_finishes_ok_and_records_a_launch_command() { + let root = tempdir().unwrap(); + let installed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let exec = make_exec_with_runner( + root.path(), + Box::new(FlatpakRunner { + installed: installed.clone(), + mark_on_install: true, + }), + ); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let mut request = InstallRequest::new("firefox"); + request.backend = Some(Backend::Flatpak); + let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap(); + + let outcome = execute_plan_privileged( + &exec, + root.path(), + &store, + &plan.id, + plan.initiator_uid, + true, + ) + .unwrap(); + assert!(outcome.completed); + assert_eq!( + outcome.launch, + Some(vec![ + "flatpak".into(), + "run".into(), + "org.mozilla.firefox".into() + ]) + ); + let log = transaction::read(root.path()).unwrap(); + assert_eq!(log.records[0].result, "ok"); + } + + #[test] + fn explicit_refusal_does_not_mutate_or_consume_the_plan() { + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let mut plan = sealed( + "plan-refuse", + PlanKind::General, + vec![SystemAction::EnableService { + name: "sshd".into(), + }], + "d", + root.path(), + effective_uid(), + ); + plan.requires_root = true; + seal_plan(&mut plan); + store.save(&mut plan).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &plan.id, + plan.initiator_uid, + false, + ) + .unwrap_err(); + assert!(matches!(err, ExecError::NotAuthorized(_)), "{err}"); + assert!( + !store.is_claimed(&plan.id), + "a refused plan is not consumed" + ); } } diff --git a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml index ea0c03a..0a36cb3 100644 --- a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml +++ b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml @@ -132,6 +132,10 @@ Singleton { call("history", {}, cb); } + function clearConversation(cb) { + call("clear_conversation", {}, cb); + } + function undo(snapshot, cb) { call("undo", { snapshot: snapshot, yes: true }, cb); } diff --git a/installer/live/desktop/phoebus-assistant/shell.qml b/installer/live/desktop/phoebus-assistant/shell.qml index b4ee4e8..bed86b4 100644 --- a/installer/live/desktop/phoebus-assistant/shell.qml +++ b/installer/live/desktop/phoebus-assistant/shell.qml @@ -62,6 +62,20 @@ ShellRoot { const list = shell.conversation.slice(); list.push(item); shell.conversation = list; + return list.length - 1; + } + + // Replace one message in place so its original card updates after an + // approval, completion or failure instead of appending a new message. + function updateMessage(index, dataPatch) { + const list = shell.conversation.slice(); + if (index < 0 || index >= list.length) + return; + const current = list[index]; + const next = Object.assign({}, current); + next.data = Object.assign({}, current.data || {}, dataPatch || {}); + list[index] = next; + shell.conversation = list; } function submitPrompt(query) { @@ -76,47 +90,79 @@ ShellRoot { shell.busy = false; if (!reply.ok) { shell.statusText = "Error: " + reply.error; - addMessage("assistant", "Could not complete request: " + reply.error, null); + addMessage("assistant", "Could not complete request: " + reply.error, { + kind: "error", + state: "failed" + }); return; } - shell.statusText = "Plan prepared"; - const res = reply.result; - if (res.kind === "install") { - addMessage("assistant", res.recommendation, res); - } else if (res.kind === "plan") { - addMessage("assistant", res.summary, res); + const res = reply.result || {}; + const text = res.recommendation || res.summary || "Prepared for review."; + if (res.kind === "info") { + shell.statusText = "Ready"; + } else if (res.prepared) { + shell.statusText = "Plan ready for review"; } else { - addMessage("assistant", "Completed.", res); + shell.statusText = "Ready"; } + addMessage("assistant", text, res); }); } - function executePlan(planData) { + function executePlan(index) { + const list = shell.conversation.slice(); + if (index < 0 || index >= list.length) + return; + const data = list[index].data || {}; + if (!data.plan_id || !data.digest) { + shell.updateMessage(index, { state: "failed", error: "No reviewed plan to execute." }); + return; + } + // Only execute the referenced reviewed plan; the service revalidates it. shell.busy = true; shell.statusText = "Executing approved plan..."; - const planId = planData.plan_id || planData.id; - const digest = planData.digest; + shell.updateMessage(index, { state: "executing" }); - AssistantBridge.execute(planId, digest, true, reply => { + AssistantBridge.execute(data.plan_id, data.digest, true, reply => { shell.busy = false; if (!reply.ok) { shell.statusText = "Execution failed"; - addMessage("assistant", "Execution failed: " + reply.error, null); - } else { - shell.statusText = "Operation completed successfully"; - addMessage("assistant", "Operation completed successfully.", { - completed: true, - application: planData.application, - snapshot: reply.result ? reply.result.snapshot : null - }); - refreshStatus(); + shell.updateMessage(index, { state: "failed", error: reply.error }); + return; } + const r = reply.result || {}; + shell.statusText = "Operation completed and verified"; + shell.updateMessage(index, { + state: "completed", + completed: true, + verification: r.verification, + snapshot: r.snapshot, + launch: r.launch || null + }); + refreshStatus(); }); } - function launchApplication(app) { - if (!app) return; - Quickshell.execDetached(["gtk-launch", app]); + function cancelPlan(index) { + // Cancelling is purely local: nothing reaches the privileged broker. + shell.updateMessage(index, { state: "cancelled" }); + shell.statusText = "Cancelled — no changes were made"; + } + + function launchFromMessage(index) { + const list = shell.conversation.slice(); + if (index < 0 || index >= list.length) + return; + const cmd = list[index].data ? list[index].data.launch : null; + if (cmd && cmd.length > 0) + Quickshell.execDetached(cmd); + } + + function clearConversation() { + AssistantBridge.clearConversation(() => { + shell.conversation = []; + shell.statusText = "Conversation history cleared"; + }); } FloatingWindow { @@ -170,13 +216,13 @@ ShellRoot { spacing: 4 PhoebusButton { - text: "Assistant" + label: "Assistant" primary: shell.currentTab === "assistant" onClicked: shell.currentTab = "assistant" } PhoebusButton { - text: "Updates" + (shell.updateOverview && shell.updateOverview.sources ? " (" + shell.updateOverview.sources.reduce((a, c) => a + c.updates.length, 0) + ")" : "") + label: "Updates" + (shell.updateOverview && shell.updateOverview.sources ? " (" + shell.updateOverview.sources.reduce((a, c) => a + c.updates.length, 0) + ")" : "") primary: shell.currentTab === "updates" onClicked: { shell.currentTab = "updates"; @@ -185,13 +231,13 @@ ShellRoot { } PhoebusButton { - text: "Legacy Admin" + label: "Legacy Admin" primary: shell.currentTab === "legacy" onClicked: shell.currentTab = "legacy" } PhoebusButton { - text: "Alerts" + (shell.activeAlerts.length > 0 ? " (" + shell.activeAlerts.length + ")" : "") + label: "Alerts" + (shell.activeAlerts.length > 0 ? " (" + shell.activeAlerts.length + ")" : "") primary: shell.currentTab === "alerts" onClicked: { shell.currentTab = "alerts"; @@ -200,7 +246,7 @@ ShellRoot { } PhoebusButton { - text: "Preferences" + label: "Preferences" primary: shell.currentTab === "preferences" onClicked: { shell.currentTab = "preferences"; @@ -271,61 +317,159 @@ ShellRoot { wrapMode: Text.Wrap } - // Recommendation / Action Card + // Plan / review card. The same card serves every + // plan type; the shared service decides what is + // proposed and this only presents it. ColumnLayout { Layout.fillWidth: true visible: modelData.data !== null spacing: 8 - // Action buttons for installation + Label { + Layout.fillWidth: true + visible: modelData.data && modelData.data.kind + color: modelData.data && modelData.data.state === "failed" ? Theme.warning : Theme.muted + font.pixelSize: 12 + text: { + const d = modelData.data || {}; + const kindName = d.kind === "install" ? "Install plan" + : d.kind === "removal" ? "Removal plan" + : d.kind === "confirm" ? "Confirmation required" + : d.kind === "plan" ? "Administration plan" + : d.kind === "info" ? "Information" + : d.kind === "error" ? "Error" : "Result"; + const stateName = d.state === "prepared" ? "— awaiting your approval" + : d.state === "executing" ? "— executing" + : d.state === "completed" ? "— completed and verified" + : d.state === "failed" ? "— failed" + : d.state === "cancelled" ? "— cancelled" + : ""; + return kindName + " " + stateName; + } + } + + // Approval and cancellation for every plan type. RowLayout { Layout.fillWidth: true - visible: modelData.data && modelData.data.kind === "install" && !modelData.data.completed + visible: modelData.data && modelData.data.prepared && modelData.data.state === "prepared" spacing: 8 PhoebusButton { - text: "Install" + label: modelData.data && modelData.data.kind === "removal" ? "Approve & Remove" : "Approve & Execute" primary: true - enabled: !shell.busy - onClicked: shell.executePlan(modelData.data) + actionEnabled: !shell.busy + onClicked: shell.executePlan(index) + } + + PhoebusButton { + label: "Cancel" + actionEnabled: !shell.busy + onClicked: shell.cancelPlan(index) } PhoebusButton { id: detailsBtn property bool expanded: false - text: expanded ? "Hide Details" : "Compare Options" + label: expanded ? "Hide Details" : "Details" onClicked: expanded = !expanded } } - // Expandable candidate details + // Expandable reviewed details. ColumnLayout { Layout.fillWidth: true visible: detailsBtn && detailsBtn.expanded spacing: 4 Label { - text: "Resolved Source: " + (modelData.data ? modelData.data.backend + " (" + modelData.data.source + ")" : "") + Layout.fillWidth: true + wrapMode: Text.Wrap + visible: modelData.data ? !!modelData.data.recommendation : false + text: modelData.data ? modelData.data.recommendation : "" + color: Theme.text + font.pixelSize: 12 + } + Label { + text: "Source: " + (modelData.data ? (modelData.data.source || "-") : "-") color: Theme.muted font.pixelSize: 12 } Label { - text: "Plan Digest: " + (modelData.data ? modelData.data.digest : "") + Layout.fillWidth: true + wrapMode: Text.Wrap + visible: modelData.data && modelData.data.effects && modelData.data.effects.length > 0 + text: { + if (!modelData.data || !modelData.data.effects) + return ""; + return "Effects: " + modelData.data.effects.map(e => (e.kind || "?") + " " + e.target).join(", "); + } + color: Theme.muted + font.pixelSize: 12 + } + Label { + Layout.fillWidth: true + wrapMode: Text.Wrap + visible: modelData.data && modelData.data.warnings && modelData.data.warnings.length > 0 + text: modelData.data ? "Warnings: " + (modelData.data.warnings || []).join("; ") : "" + color: Theme.warning + font.pixelSize: 12 + } + Label { + Layout.fillWidth: true + wrapMode: Text.Wrap + text: "Plan digest: " + (modelData.data ? (modelData.data.digest || "") : "") color: Theme.muted font.pixelSize: 11 } } - // Completed follow-up action + Label { + Layout.fillWidth: true + wrapMode: Text.Wrap + visible: modelData.data && modelData.data.state === "executing" + text: "Executing the approved plan…" + color: Theme.accent + font.pixelSize: 12 + } + + Label { + Layout.fillWidth: true + wrapMode: Text.Wrap + visible: modelData.data && modelData.data.state === "failed" + text: "Failed: " + (modelData.data && modelData.data.error ? modelData.data.error : "unknown error") + color: Theme.warning + font.pixelSize: 12 + } + + Label { + Layout.fillWidth: true + wrapMode: Text.Wrap + visible: modelData.data && modelData.data.state === "cancelled" + text: "Cancelled — no changes were made." + color: Theme.muted + font.pixelSize: 12 + } + + Label { + Layout.fillWidth: true + wrapMode: Text.Wrap + visible: modelData.data && modelData.data.state === "completed" + text: modelData.data && modelData.data.verification ? modelData.data.verification : "Completed successfully." + color: Theme.text + font.pixelSize: 12 + } + + // Offer launch only when the service identified + // a concrete desktop entry/command. RowLayout { Layout.fillWidth: true - visible: modelData.data && modelData.data.completed && modelData.data.application + visible: modelData.data && modelData.data.state === "completed" && modelData.data.launch spacing: 8 PhoebusButton { - text: "Launch " + (modelData.data ? modelData.data.application : "App") + label: "Launch application" primary: true - onClicked: shell.launchApplication(modelData.data.application) + onClicked: shell.launchFromMessage(index) } } } @@ -363,14 +507,20 @@ ShellRoot { } PhoebusButton { - text: "Send" + label: "Send" primary: true - enabled: !shell.busy && promptField.text.trim().length > 0 + actionEnabled: !shell.busy && promptField.text.trim().length > 0 onClicked: { shell.submitPrompt(promptField.text); promptField.text = ""; } } + + PhoebusButton { + label: "Clear History" + actionEnabled: !shell.busy + onClicked: shell.clearConversation() + } } } @@ -446,11 +596,11 @@ ShellRoot { RowLayout { Layout.fillWidth: true PhoebusButton { - text: "Refresh Updates" + label: "Refresh Updates" onClicked: refreshStatus() } PhoebusButton { - text: "Apply All Updates" + label: "Apply All Updates" primary: true onClicked: shell.submitPrompt("update system") } @@ -497,16 +647,20 @@ ShellRoot { } PhoebusButton { - text: "Install Explicitly" + label: "Install Explicitly" primary: true - enabled: legacyAppField.text.trim().length > 0 + actionEnabled: legacyAppField.text.trim().length > 0 onClicked: { const app = legacyAppField.text.trim(); const lane = legacyLaneCombo.currentText; shell.statusText = "Resolving legacy install..."; AssistantBridge.legacyInstall(app, lane, reply => { if (reply.ok) { - shell.executePlan(reply.result); + // Show the reviewed plan and require approval; + // never execute merely because it was planned. + shell.currentTab = "assistant"; + addMessage("assistant", "Legacy plan for " + app + " (" + lane + ").", reply.result); + shell.statusText = "Legacy plan ready for review"; } else { shell.statusText = "Error: " + reply.error; } @@ -534,8 +688,8 @@ ShellRoot { } PhoebusButton { - text: "Execute Command" - enabled: legacyPhraseField.text.trim().length > 0 + label: "Execute Command" + actionEnabled: legacyPhraseField.text.trim().length > 0 onClicked: { const p = legacyPhraseField.text.trim(); AssistantBridge.legacyExecute(p, null, true, reply => { @@ -620,7 +774,7 @@ ShellRoot { spacing: 8 PhoebusButton { - text: "Act: " + (modelData.suggested_phrase || "Fix") + label: "Act: " + (modelData.suggested_phrase || "Fix") primary: true visible: modelData.suggested_phrase !== null onClicked: { @@ -630,14 +784,14 @@ ShellRoot { } PhoebusButton { - text: "Snooze 1h" + label: "Snooze 1h" onClicked: { AssistantBridge.snoozeAlerts(3600, () => refreshStatus()); } } PhoebusButton { - text: "Dismiss" + label: "Dismiss" onClicked: { AssistantBridge.dismissAlert(modelData.fingerprint, () => refreshStatus()); } @@ -680,7 +834,7 @@ ShellRoot { } PhoebusButton { - text: "Save Preferences" + label: "Save Preferences" primary: true onClicked: { if (shell.preferences) {