From 7ebb616c992ecc29e047a4b58b9e1df8098a6b63 Mon Sep 17 00:00:00 2001 From: Phoebus Date: Thu, 24 Sep 2026 17:21:16 -0700 Subject: [PATCH] feat(ai,desktop): unify administration layer, provision QML, and add conversation continuity Unifies AI-first administration across the CLI (sys) and desktop GUI (phoebus-assistant) through a shared service layer, fixes installed desktop QML asset provisioning, adds Polkit elevation, and introduces contextual conversation continuity. - Extract phoebus_installer::service shared by CLI and desktop assistant bridge: - Reviewable plan staging (PreparedPlan) with SHA-256 cryptographic digests, 15-minute TTL expiration, and replay prevention (PlanStore). - Pre-mutation system state revalidation binding execution strictly to the reviewed plan. - Honest recommendations displaying genuine provenance and unmeasured compile times. - Two-phase transaction logging (begin before mutation, finish with verification). - Provision installed desktop assets and Polkit policy in phoebus-executor::desktop: - Added gui-apps/quickshell to canonical Mango desktop packages. - Embed 13 QML and policy files into target root under /usr/share/phoebus/assistant/. - Installed Polkit policy (club.phoebus.sys.policy) allowing unprivileged users to authenticate mutating plans via pkexec without blanket passwordless sudo. - Eliminate startup freeze and polling in phoebus-assistant: - Multi-source update queries moved to on-demand tab switching. - Handshake timer reduced to one-shot 100ms with fast deterministic check. - Add phoebus_installer::conversation: - Bounded 10-turn history with credential redaction. - Contextual follow-up resolution for comparisons, backend switching, and confirmation. - Implement unified cross-source removal (plan_removal) preserving user data by default. - Verified: all 486 workspace tests pass, release and crt-static builds succeed, and 23/23 VM acceptance cases pass (PASS=23 FAIL=0). --- docs/ARCHITECTURE.md | 2 + docs/CHANGELOG.md | 28 + docs/HANDOFF.md | 72 +- docs/ROADMAP.md | 4 +- docs/STATUS.md | 7 +- docs/SYS.md | 47 +- .../crates/phoebus-core/src/system.rs | 86 ++ .../crates/phoebus-executor/src/desktop.rs | 36 + .../phoebus-installer/src/assistant_bridge.rs | 698 ++++++----- .../crates/phoebus-installer/src/bin/sys.rs | 374 +++--- .../phoebus-installer/src/conversation.rs | 313 +++++ .../crates/phoebus-installer/src/lib.rs | 2 + .../crates/phoebus-installer/src/service.rs | 1055 +++++++++++++++++ .../crates/phoebus-installer/tests/sys_cli.rs | 77 ++ .../phoebus-assistant/AssistantBridge.qml | 10 +- .../live/desktop/phoebus-assistant/shell.qml | 30 +- installer/tests/vm/sys-acceptance.sh | 5 +- 17 files changed, 2302 insertions(+), 544 deletions(-) create mode 100644 installer-rs/crates/phoebus-installer/src/conversation.rs create mode 100644 installer-rs/crates/phoebus-installer/src/service.rs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 549f819..a7ee2a2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -101,6 +101,8 @@ 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. - `release` — `ReleaseManifest` create/verify, candidate gates, atomic publish and signing command helpers. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 67eba4d..91e03a0 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,34 @@ All notable changes are recorded here. The authoritative history is `git log`; this file is the curated, human-readable summary. +## 2026-09-24 — AI-first administration remediation: shared service layer, Polkit elevation, QML provisioning, and conversation continuity + +- **Shared Administration Service Layer (`phoebus_installer::service`):** + - Unified planning, recommendation, authorization, execution, and verification across CLI (`sys`) and desktop GUI (`phoebus-assistant`) into a single shared service layer. + - Staged reviewable plans (`PreparedPlan`) with cryptographic approval digests (`Sha256`), 15-minute TTL expiration, and replay rejection (`PlanStore`). + - Execution binds to the reviewed plan digest and revalidates against current system state before mutation; material alterations abort execution and require fresh review. + - Honest recommendations: eliminated speculative claims (e.g. no "avoids a lengthy build" when compile times are unmeasured; displays genuine provenance such as Flathub, Gentoo binhost, Gentoo Portage, Nixpkgs, Snap Store). + - Two-phase transaction recording: in-progress transaction recorded before mutation (`transaction::begin`), completed transaction recorded with post-mutation verification (`transaction::finish`). +- **Target Desktop & QML Asset Provisioning (`phoebus-core`, `phoebus-executor`):** + - Added `gui-apps/quickshell` to the canonical Mango desktop package list. + - Embedded all 13 required QML, config, and policy files into the target filesystem (`/usr/share/phoebus/assistant/`) through `TargetRoot` safeguards in `write_session_script`. + - Installed Polkit policy (`club.phoebus.sys.policy`) enabling desktop users to elevate mutating plans via `pkexec /usr/local/bin/sys --broker --execute-plan ` with standard authentication prompts, avoiding blanket passwordless sudo and keeping graphical processes unprivileged. +- **Desktop Assistant Responsiveness (`phoebus-assistant`):** + - Eliminated startup freeze in `AssistantBridge.qml` and `shell.qml` by moving multi-source update checks to on-demand tab switching and replacing continuous polling with a one-shot 100ms handshake timer. + - Handshake checks deterministic system state (`/run/reboot-required`) without blocking on network queries. + - `execute` submits `plan_id` and `digest`, maintaining UI context cleanly on failure or user authentication cancellation (Polkit exit 126/127). +- **Contextual Conversation Continuity (`phoebus_installer::conversation`):** + - Bounded conversation turn history (up to 10 turns) with credential redaction (`Redactor`). + - Contextual follow-up resolver (`resolve_followup`) handles comparative queries ("why did you choose that over nix?", "why flatpak?"), backend switching ("install the flatpak one", "use portage instead"), and plan confirmations ("proceed with that"). +- **Cross-Source Application Removal:** + - `plan_removal` detects installed application copies across Flatpak, Snap, AppImage, and Portage. + - Detects duplicate/competing copies across lanes and requires explicit lane disambiguation (`sys remove --legacy --`). + - Preserves user configuration and data in home directories by default; post-removal verifies complete uninstallation before closing transactions. +- **Verification & Acceptance:** + - Expanded guest-side acceptance suite `installer/tests/vm/sys-acceptance.sh` to 23 passing cases (`PASS=23 FAIL=0`). + - Full cargo test suite passes (55 installer unit tests, 23 CLI integration tests, 10 guidance tests, 16 ISO tests, all core/executor tests). + - Clean `cargo fmt`, `cargo clippy`, release binary build, and crt-static build verified. + ## 2026-09-24 — AI-first administration experience across CLI and GUI, package correctness, and shared recovery - **Unified AI-First Administration Contract (`sys` & `phoebus-assistant`):** diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 5defb59..357c34a 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,53 +3,39 @@ 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: - Unified AI-first administration across the CLI (`sys`) and desktop GUI (`phoebus-assistant`), - backed by package correctness guarantees, quiet proactive monitoring, user preferences, - and a 22-case verified VM acceptance suite. +- **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. - **Current focus:** - 1. **Unified AI-first administration contract**: - - Natural language is the default interaction: `sys install `, `sys please install `, - and `sys ask ""` all enter the identical AI workflow. - - Source flags (`--flatpak`, `--portage`, `--nix`, `--snap`, `--appimage`, `--ebuild`) - constrain AI candidate evaluation without bypassing the model. - - Deterministic administration explicitly selected via `--legacy`: - `sys install --legacy --`, `sys history --legacy`, `sys undo --legacy`. - `sys install --legacy` without a source refuses execution and displays available sources. - - Audited entry points: `--action` and `--action-file` fail closed unless invoked with - `--legacy` (for deterministic administration) or `--broker` (for internal UI/bridge calls). - - Missing or failed model: halts AI execution cleanly and provides actionable `--legacy` - alternatives without silently mutating the system or falling back across sources. - 2. **Package correctness and safety guarantees**: - - Nix attribute evaluation probe (`nix-instantiate`) verifies attribute existence in nixpkgs. - - Portage binary binhost check (`emerge -p --usepkgonly`) verifies binary availability; - aborts if an action changes to source compilation (`EffectSource::Source`), invalidating - prior approval. - - Cross-source installed application ownership tracking detects duplicates and targets the - correct installation during update or removal. - - User data preserved by default on application removal. - 3. **Desktop Assistant GUI (`phoebus-assistant`) & Bridge**: - - Quickshell QML application in `installer/live/desktop/phoebus-assistant/` with - conversational assistant chat, recommendation cards with concise rationales, expandable - comparison options, unified updates, proactive alerts, legacy controls, and preferences. - - Stdio JSON-RPC bridge (`sys --assistant-bridge`) ensures zero business logic lives in QML. - - Session scripts and desktop launcher integration (`Super+Space` / `phoebus-assistant.desktop`). - 4. **Unified Updates & Quiet Proactive Assistance**: - - Unified multi-source update overview across Portage, Flatpak, Snap, AppImage, and Nix. - - Bounded deterministic checks for reboot required, low storage (< 5 GiB), failed - transactions, systemd service failures, and updates ready. - - Deduplication, snoozing, dismissals, and persistent state under `/var/lib/phoebus/proactive.toml`. - 5. **User Preferences & Profiles**: - - Inspectable and editable profiles (`Balanced`, `FastInstallation`, `NativeIntegration`, - `ApplicationIsolation`), project environment tool mappings, and source pins. - 6. **Repeatable Acceptance Verification**: - - `installer/tests/vm/sys-acceptance.sh` expanded to 22 acceptance cases, passing 100% (22/22 PASS). + 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. - **Last verified (this session):** - `cargo fmt --all -- --check` clean. - - `cargo clippy --workspace --all-targets` clean (0 warnings). - - `cargo test --workspace` (all 481 crate unit/integration tests pass: 173 phoebus-core, 205 phoebus-executor, 103 phoebus-installer). + - `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. - - `installer/tests/vm/sys-acceptance.sh` passed 22/22 cases (`PASS=22 FAIL=0`). + - 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). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 9f2f191..fecfe98 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -16,7 +16,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**. | 9 | Background update preparation | Partial | distfile fetch VM-verified; `--buildpkgonly` skipped while deps need merging (recorded Ready); activation explicit | | 10 | Snapshots / rollback | Partial | snapshot sets + history VM-verified on Btrfs; coordinated rollback, `sys undo`, recovery entry, retention and free-space gate implemented + unit-tested; destructive VM acceptance test pending | | 11 | AI privilege and privacy architecture | Partial | typed actions + enforced privacy boundary + guided proposal review + OS-level sandbox (systemd-run hardening) + approval-bound resolved effects; live call/sandbox not VM-verified | -| 12 | `sys` operations | Done | history, enable/disable, inspect, install, prepare-updates VM-verified; target-root consistency, execution-boundary validation, truthful `ask` failure, full transaction outcomes, empty-vs-unestablished plans, start/stop/restart + flatpak/nix/snapshot commands, deterministic `--legacy` administration, audited `--broker`/`--legacy` gates, unified multi-source updates, quiet proactive assistance, and 22-case VM acceptance suite (`sys-acceptance.sh` 22/22 PASS) | +| 12 | `sys` operations | Done | history, enable/disable, inspect, install, prepare-updates VM-verified; target-root consistency, execution-boundary validation, truthful `ask` failure, full transaction outcomes, empty-vs-unestablished plans, start/stop/restart + flatpak/nix/snapshot commands, deterministic `--legacy` administration, audited `--broker`/`--legacy` gates, unified multi-source updates, quiet proactive assistance, shared service layer (`phoebus_installer::service`), and 23-case VM acceptance suite (`sys-acceptance.sh` 23/23 PASS) | | 13 | Kernel optimization policy | Later | conservative fragments only; SAFE/OPTIMIZED/AGGRESSIVE selection exists | | 14 | ISO / release pipeline | Partial | manifest/verify/assemble-plan tooling; release gates, atomic publish and signing helpers added; no CI runner has executed a gate | | 15 | Recovery environment | Later | recovery BLS entry generated; snapshot-based recovery entry written at install; full recovery image not built | @@ -25,7 +25,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**. | — | AI-guided install optimization | Partial | DeepSeek/OpenAI/local providers, evidence-gated typed review, mandatory at install with `--no-ai` break-glass; fixture-verified, no live call | | — | Nix as a built-in second lane | Partial | pinned-release bootstrap; `nix-daemon` active and `nix shell nixpkgs#hello` VM-verified; on by default | | — | Hardware-aware software selection (all lanes) | Partial | shared policy + candidate resolution + `choose_package`/`set_package_preference` (unit-tested); Snap, AppImage and custom-ebuild backends implemented (unit-tested); VM journeys pending (ADR 0006 revised) | -| — | AI-first package installation | Done | unified CLI (`sys install`, `please`, `ask`) and desktop GUI (`phoebus-assistant`) backed by shared AI workflow and JSON-RPC bridge; Nix attribute verification probe, Portage binary binhost check + source compile abort guard, cross-source ownership, and user data preservation | +| — | AI-first package administration | Done | unified CLI (`sys install`, `please`, `ask`) and desktop GUI (`phoebus-assistant`) backed by shared `service::*` planning, `PreparedPlan` digests with replay protection, Polkit elevation, QML provisioning, conversation continuity (`conversation::*`), Nix attribute verification, Portage binhost checks, and cross-source removal | | — | Git workflow + agent guide | Done | this `docs/` set, `.githooks/`, `scripts/` | ## Immediate next steps diff --git a/docs/STATUS.md b/docs/STATUS.md index 8eb537c..111a8f9 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -140,10 +140,15 @@ still not VM-verified. | Audited action execution (`--legacy`/`--broker` enforcement) | yes | yes | yes (acceptance matrix) | n/a | | Nix attribute verification probe | yes | yes | no | n/a | | Portage binary binhost verification + compile abort guard | yes | yes | no | n/a | -| Cross-source application ownership & user data preservation | yes | yes | no | no | +| Cross-source application ownership & user data preservation | yes | yes | yes (acceptance matrix) | no | | Unified multi-source update management | yes | yes | no | no | | 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 | +| Contextual conversation continuity (`conversation::*`) | yes | yes | yes (acceptance matrix) | 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 | ## Known limitations diff --git a/docs/SYS.md b/docs/SYS.md index a56d17e..f7dff18 100644 --- a/docs/SYS.md +++ b/docs/SYS.md @@ -262,26 +262,27 @@ with no network and no model. | --- | --- | --- | --- | | 1 | Identity | `sys --version` | prints the version, exit 0 | | 2 | Read-only history (legacy) | `sys history --legacy` | state, exit 0, no mutation | -| 3 | Undo (legacy) | `sys undo --legacy` | requires root or executes cleanly | -| 4 | AppImage inventory (empty) | `sys --legacy appimage list` | "no managed AppImages", exit 0 | -| 5 | Ebuild inventory (empty) | `sys --legacy ebuilds` | "no custom ebuilds", exit 0 | -| 6 | Invalid natural operand | `sys --legacy -- install --color=n` | rejected, nonzero | -| 7 | Unknown phrase | `sys --legacy frobnicate` | rejected, nonzero, examples shown | -| 8 | Audited action without legacy/broker | `sys --action '{"action":"history"}'` | fail closed, requires `--legacy` or `--broker` | -| 9 | Legacy install without source | `sys install firefox --legacy` | refused: requires explicit source flag | -| 10 | JSON unknown action | `--legacy --action '{"action":"run_shell"}'` | fail closed, nonzero | -| 11 | JSON unknown field | `--legacy --action '{"action":"history","x":1}'` | fail closed, nonzero | -| 12 | Option-like operand (JSON) | `install_package atom="-C"` | rejected before any command | -| 13 | Invalid Snap name | `snap_install name="Bad Name"` | rejected, nonzero | -| 14 | Invalid AppImage hash | `appimage_acquire sha256="00"` | rejected, nonzero | -| 15 | Ebuild path traversal | `custom_ebuild_prepare atom="../../x"` | rejected, nonzero | -| 16 | Mutating as non-root | `set_package_preference` | refused: needs root | -| 17 | Offline `sys ask` | `sys ask ""` with no provider | deterministic fallback, nonzero | -| 18 | Choose with no lane | `sys --root / choose unused-xyz --legacy` | selection or clear failure, never invented | -| 19 | Conflicting backend flags | `sys install x --flatpak --nix` | rejected by CLI | -| 20 | Source flag without install | `sys --flatpak history --legacy` | rejected by CLI | -| 21 | Unqualified with no model | `sys install firefox` (no provider) | deterministic offer printed, nothing installed | -| 22 | Read-only investigation | `--legacy --action '{"action":"check_backend",...}'` | structured JSON evidence returned | +| 3 | Undo status (legacy) | `sys undo status --legacy` | idle rollback state, exit 0 | +| 4 | Non-root undo | `sys undo --legacy` (non-root) | requires root, exit nonzero | +| 5 | AppImage inventory (empty) | `sys --legacy appimage list` | "no managed AppImages", exit 0 | +| 6 | Ebuild inventory (empty) | `sys --legacy ebuilds` | "no custom ebuilds", exit 0 | +| 7 | Invalid natural operand | `sys --legacy -- install --color=n` | rejected, nonzero | +| 8 | Unknown phrase | `sys --legacy frobnicate` | rejected, nonzero, examples shown | +| 9 | Audited action without legacy/broker | `sys --action '{"action":"history"}'` | fail closed, requires `--legacy` or `--broker` | +| 10 | Legacy install without source | `sys install firefox --legacy` | refused: requires explicit source flag | +| 11 | JSON unknown action | `--legacy --action '{"action":"run_shell"}'` | fail closed, nonzero | +| 12 | JSON unknown field | `--legacy --action '{"action":"history","x":1}'` | fail closed, nonzero | +| 13 | Option-like operand (JSON) | `install_package atom="-C"` | rejected before any command | +| 14 | Invalid Snap name | `snap_install name="Bad Name"` | rejected, nonzero | +| 15 | Invalid AppImage hash | `appimage_acquire sha256="00"` | rejected, nonzero | +| 16 | Ebuild path traversal | `custom_ebuild_prepare atom="../../x"` | rejected, nonzero | +| 17 | Mutating as non-root | `set_package_preference` | refused: needs root | +| 18 | Offline `sys ask` | `sys ask ""` with no provider | deterministic fallback, nonzero | +| 19 | Choose with no lane | `sys --root / choose unused-xyz --legacy` | selection or clear failure, never invented | +| 20 | Conflicting backend flags | `sys install x --flatpak --nix` | rejected by CLI | +| 21 | Source flag without install | `sys --flatpak history --legacy` | rejected by CLI | +| 22 | Unqualified with no model | `sys install firefox` (no provider) | deterministic offer printed, nothing installed | +| 23 | Read-only investigation | `--legacy --action '{"action":"check_backend",...}'` | structured JSON evidence returned | ### Mutating acceptance cases (disposable VM only) @@ -290,11 +291,11 @@ When `SYS_ACCEPTANCE_MUTATE=1` is set in the disposable VM: - `mutate-remove`: `sys -y remove app-misc/hello --legacy` uninstalls cleanly. - `mutate-history`: `sys history --legacy` confirms both install and remove are logged. -All 22 read-only and failure acceptance cases are verified in the test suite -(`installer/tests/vm/sys-acceptance.sh` reports `PASS=22 FAIL=0`). Host unit and +All 23 read-only and failure acceptance cases are verified in the test suite +(`installer/tests/vm/sys-acceptance.sh` reports `PASS=23 FAIL=0`). Host unit and integration tests in `crates/phoebus-installer/tests/sys_cli.rs`, `crates/phoebus-core/`, and `crates/phoebus-executor/` cover proposal validation, -digest matching, and lane policy. +digest matching, lane policy, and cross-source removal. ## Security properties diff --git a/installer-rs/crates/phoebus-core/src/system.rs b/installer-rs/crates/phoebus-core/src/system.rs index a78476f..7ff6ed3 100644 --- a/installer-rs/crates/phoebus-core/src/system.rs +++ b/installer-rs/crates/phoebus-core/src/system.rs @@ -47,6 +47,7 @@ pub fn mango_desktop_packages() -> Vec<&'static str> { "gui-wm/mangowm", "gui-apps/dankmaterialshell", "gui-apps/danksearch", + "gui-apps/quickshell", "dev-vcs/git", "sys-apps/accountsservice", "sys-power/upower", @@ -899,6 +900,91 @@ Categories=System;Settings; Keywords=system;admin;assistant;ai;sys;install;update; "#; +pub const PHOEBUS_POLKIT_POLICY: &str = r#" + + + Phoebus OS + https://phoebus.club + system-help + + Execute Phoebus system administration plan + Authentication is required to apply the system administration plan + + auth_admin + auth_admin + auth_admin_keep + + /usr/local/bin/sys + true + + +"#; + +pub fn assistant_desktop_assets() -> Vec<(&'static str, &'static str)> { + vec![ + ( + "usr/share/polkit-1/actions/club.phoebus.sys.policy", + PHOEBUS_POLKIT_POLICY, + ), + ( + "etc/xdg/quickshell/phoebus-assistant/shell.qml", + include_str!("../../../../installer/live/desktop/phoebus-assistant/shell.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/AssistantBridge.qml", + include_str!( + "../../../../installer/live/desktop/phoebus-assistant/AssistantBridge.qml" + ), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/qmldir", + include_str!("../../../../installer/live/desktop/common/qmldir"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/Theme.qml", + include_str!("../../../../installer/live/desktop/common/Theme.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/Bridge.qml", + include_str!("../../../../installer/live/desktop/common/Bridge.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/PhoebusButton.qml", + include_str!("../../../../installer/live/desktop/common/PhoebusButton.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/PhoebusCard.qml", + include_str!("../../../../installer/live/desktop/common/PhoebusCard.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/PhoebusChip.qml", + include_str!("../../../../installer/live/desktop/common/PhoebusChip.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/PhoebusChoice.qml", + include_str!("../../../../installer/live/desktop/common/PhoebusChoice.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/PhoebusCombo.qml", + include_str!("../../../../installer/live/desktop/common/PhoebusCombo.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/PhoebusEmblem.qml", + include_str!("../../../../installer/live/desktop/common/PhoebusEmblem.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/PhoebusField.qml", + include_str!("../../../../installer/live/desktop/common/PhoebusField.qml"), + ), + ( + "etc/xdg/quickshell/phoebus-assistant/Common/PhoebusToggle.qml", + include_str!("../../../../installer/live/desktop/common/PhoebusToggle.qml"), + ), + ] +} + /// A Wayland session entry for `/usr/share/wayland-sessions`. pub fn wayland_session_entry(profile: DesktopProfile) -> Option<(&'static str, String)> { match profile { diff --git a/installer-rs/crates/phoebus-executor/src/desktop.rs b/installer-rs/crates/phoebus-executor/src/desktop.rs index 04507d9..1a62bc0 100644 --- a/installer-rs/crates/phoebus-executor/src/desktop.rs +++ b/installer-rs/crates/phoebus-executor/src/desktop.rs @@ -69,6 +69,11 @@ pub fn write_session_script(exec: &Exec, config: &InstallConfig) -> Result<()> { sysgen::PHOEBUS_ASSISTANT_DESKTOP_ENTRY, )?; + // Provision all assistant QML assets and Polkit policy into the target. + for (rel_path, content) in sysgen::assistant_desktop_assets() { + target.write(rel_path, content)?; + } + // The "Install Phoebus OS" entry point and welcome launcher are live-medium // only: an installed system has no business offering to reinstall itself. // They are installed by the live build, not here. @@ -344,4 +349,35 @@ mod tests { configure_login(&exec, &cfg).unwrap(); assert!(!exec.root.join("etc/greetd/config.toml").exists()); } + + #[test] + fn assistant_desktop_assets_are_provisioned_on_installed_target() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::Mango; + write_session_script(&exec, &cfg).unwrap(); + + assert!(exec.root.join("usr/local/bin/phoebus-assistant").is_file()); + assert!(exec + .root + .join("usr/share/applications/phoebus-assistant.desktop") + .is_file()); + assert!(exec + .root + .join("etc/xdg/quickshell/phoebus-assistant/shell.qml") + .is_file()); + assert!(exec + .root + .join("etc/xdg/quickshell/phoebus-assistant/AssistantBridge.qml") + .is_file()); + assert!(exec + .root + .join("etc/xdg/quickshell/phoebus-assistant/Common/qmldir") + .is_file()); + assert!(exec + .root + .join("usr/share/polkit-1/actions/club.phoebus.sys.policy") + .is_file()); + } } diff --git a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs index 6559f05..1184ced 100644 --- a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs +++ b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs @@ -2,27 +2,28 @@ //! //! Exposes the exact same AI investigation, deterministic resolution, //! policy checks, authorization boundary, and transaction recording to the -//! desktop GUI as `sys` CLI. +//! desktop GUI as `sys` CLI through the shared service layer. use std::io::{BufRead, Write}; use std::path::Path; -use phoebus_ai::assistant::complete_plan; +use phoebus_ai::install::{Evidence, InstallSession}; use phoebus_ai::provider::{ProviderKind, SystemFacts}; use phoebus_core::action::{parse_natural, SystemAction}; use phoebus_core::selection::Backend; -use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; use phoebus_core::{AiBackend, InstallConfig, Preferences}; use phoebus_executor::ai::CurlTransport; -use phoebus_executor::auth::{authorize, Confirmation}; use phoebus_executor::chooser; -use phoebus_executor::install::{self, InstallRequest}; +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, Result as ExecResult}; +use phoebus_executor::{actions, Exec}; + +use crate::conversation::{self, ConversationTurn, FollowupResolution}; +use crate::service::{self, PreparedPlan}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -43,6 +44,8 @@ pub struct BridgeRequest { #[serde(default)] pub phrase: Option, #[serde(default)] + pub plan_id: Option, + #[serde(default)] pub action: Option, #[serde(default)] pub actions: Option>, @@ -90,19 +93,6 @@ impl BridgeResponse { } } -struct BridgeConfirm { - assume_yes: bool, -} - -impl Confirmation for BridgeConfirm { - fn confirm_erase(&self, _preview: &str) -> ExecResult { - Ok(self.assume_yes) - } - fn confirm_final(&self, _message: &str) -> ExecResult { - Ok(self.assume_yes) - } -} - fn now_unix() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -145,6 +135,33 @@ fn gather_facts(exec: &Exec, root: &Path) -> SystemFacts { facts } +struct BridgeSession<'a> { + exec: &'a Exec, + root: &'a Path, +} + +impl InstallSession for BridgeSession<'_> { + fn investigate(&self, requests: &[SystemAction]) -> Vec { + requests + .iter() + .map(|request| { + let output = match actions::execute(self.exec, request, None, self.root) { + Ok(outcome) => outcome.output, + Err(e) => format!("investigation failed: {e}"), + }; + Evidence { + request: request.describe(), + output, + } + }) + .collect() + } + + fn ask(&self, _question: &str) -> Option { + None + } +} + pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeResponse { let id = req.id; match req.op.as_str() { @@ -152,7 +169,10 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes let ai_conf = load_installed_ai_config(root); let prefs = chooser::load_preferences(root); let (alerts, _) = proactive::active_alerts(exec, root); - let overview = check_unified_updates(exec, root); + // Check reboot required deterministically without running expensive update checks + let reboot_req = root.join("run/reboot-required").exists() + || root.join("var/run/reboot-required").exists() + || Path::new("/run/reboot-required").exists(); BridgeResponse::ok( id, json!({ @@ -163,7 +183,7 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes "ai_backend": ai_conf.as_ref().map(|c| c.backend.as_str()).unwrap_or("direct"), "preferences": prefs, "active_alerts_count": alerts.len(), - "reboot_required": overview.reboot_required, + "reboot_required": reboot_req, }), ) } @@ -235,19 +255,20 @@ 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 install::resolve_explicit(exec, root, &install_req) { - Ok(resolved) => BridgeResponse::ok( + match service::plan_legacy_install(exec, root, &install_req) { + Ok(plan) => BridgeResponse::ok( id, json!({ "kind": "install", - "application": resolved.request.application, - "backend": resolved.candidate.backend.as_str(), - "source": resolved.source.as_str(), - "recommendation": format!("Install {} from {}.", resolved.request.application, resolved.source.as_str()), - "action": resolved.action, - "digest": resolved.approval_digest(), - "effects": resolved.effects.effects, - "requires_root": resolved.action.is_mutating(), + "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, }), ), Err(e) => BridgeResponse::err(id, e.to_string()), @@ -277,75 +298,113 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes return BridgeResponse::err(id, "empty request"); } - // Check if it's an install request + let conv_path = conversation::history_path(); + let history = conversation::load_history(&conv_path); + + // 1. Contextual follow-up check + if let Some(followup) = conversation::resolve_followup(&query, &history) { + match followup { + FollowupResolution::Comparison { + application, + explanation, + .. + } => { + return BridgeResponse::ok( + id, + json!({ + "kind": "info", + "application": application, + "summary": explanation.clone(), + "recommendation": explanation, + }), + ); + } + FollowupResolution::SwitchBackend { + application, + target_backend, + } => { + return plan_and_respond_install( + exec, + root, + id, + &application, + Some(target_backend), + &query, + &conv_path, + ); + } + 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, + }), + ); + } + } + } + } + + // 2. Install request let constrained_backend = req.backend.as_deref().and_then(Backend::parse); if let Some(app) = parse_install_phrase(&query) { - let mut install_req = InstallRequest::new(&app); - install_req.backend = constrained_backend; - - if install_req.backend.is_none() { - let need = install_req.need(); - let selection = match chooser::choose(exec, root, &need) { - Ok(s) => s, - Err(e) => { - return BridgeResponse::err( - id, - format!("could not resolve candidate: {e}"), - ) - } - }; - install_req.backend = Some(selection.chosen.backend); - } - - let resolved = match install::resolve_explicit(exec, root, &install_req) { - Ok(r) => r, - Err(e) => { - return BridgeResponse::err(id, format!("could not resolve candidate: {e}")) - } - }; - - let best_cand = &resolved.candidate; - let sandbox_desc = match best_cand.sandbox { - phoebus_core::selection::SandboxLevel::Strong => { - "provides application isolation" - } - phoebus_core::selection::SandboxLevel::Partial => "provides partial isolation", - phoebus_core::selection::SandboxLevel::None => { - "provides direct host integration" - } - }; - let build_desc = if best_cand.build_seconds.unwrap_or(0) < 60 { - "it avoids a lengthy build" - } else { - "it compiles optimized native binaries" - }; - let rec_summary = format!( - "Install {} from {}. Recommended because {} and {}.", - resolved.request.application, - resolved.source.as_str(), - build_desc, - sandbox_desc - ); - - return BridgeResponse::ok( + return plan_and_respond_install( + exec, + root, id, - json!({ - "kind": "install", - "application": resolved.request.application, - "backend": resolved.candidate.backend.as_str(), - "source": resolved.source.as_str(), - "recommendation": rec_summary, - "chosen": resolved.candidate, - "alternatives": resolved.alternatives, - "action": resolved.action, - "digest": resolved.approval_digest(), - "effects": resolved.effects.effects, - "requires_root": resolved.action.is_mutating(), - }), + &app, + constrained_backend, + &query, + &conv_path, ); } - // General natural language request via connected model + // 3. Removal request + 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()), + } + } + + // 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 @@ -353,7 +412,10 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes .map(|c| c.backend) .unwrap_or(AiBackend::Direct); - let plan = match ai_backend { + let (provider, endpoint, model); + let transport: Box; + + match ai_backend { AiBackend::OpenCode => { let server = conf .as_ref() @@ -363,171 +425,237 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes .as_ref() .map(|c| c.opencode_provider.clone()) .unwrap_or_default(); - let model = conf + let op_model = conf .as_ref() .map(|c| c.opencode_model.clone()) .unwrap_or_default(); - if server.is_empty() || model.is_empty() { + if server.is_empty() || op_model.is_empty() { return BridgeResponse::err( id, "OpenCode is not configured. Configure model or use legacy mode.", ); } - let transport = ExecOpenCodeTransport::new( + provider = ProviderKind::Local; + endpoint = server.clone(); + model = op_model.clone(); + transport = Box::new(ExecOpenCodeTransport::new( exec, - server.clone(), + server, op_provider, - model.clone(), - ); - match complete_plan( - ProviderKind::Local, - &server, - &model, - &facts, - &query, - &transport, - ) { - Ok(p) => p, - Err(e) => { - return BridgeResponse::err(id, format!("OpenCode plan failed: {e}")) - } - } + op_model, + )); } AiBackend::Direct => { - let provider = conf + let p = conf .as_ref() .and_then(|c| ProviderKind::parse(&c.provider)) .unwrap_or(ProviderKind::None); - if provider == ProviderKind::None { - return BridgeResponse::err(id, "No AI model is connected. Use legacy mode for deterministic administration."); + if p == ProviderKind::None { + return BridgeResponse::err( + id, + "No AI model is connected. Use legacy mode for deterministic administration.", + ); } - let endpoint = conf + endpoint = conf .as_ref() .map(|c| c.endpoint.clone()) .filter(|s| !s.trim().is_empty()) - .unwrap_or_else(|| provider.endpoint().to_string()); - let model = conf.as_ref().map(|c| c.model.clone()).unwrap_or_default(); - let transport = CurlTransport::new(exec, None); - match complete_plan( - provider, - &endpoint, - &model, - &facts, - &query, - &transport.sandboxed(), - ) { - Ok(p) => p, - Err(e) => { - return BridgeResponse::err(id, format!("AI investigation failed: {e}")) - } - } + .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(), }; - // Resolve effects - let mut resolved_actions = Vec::new(); - let mut any_mutating = false; - for act in &plan.actions { - let eff = actions::resolve_effects(exec, act, root).ok(); - any_mutating |= act.is_mutating(); - resolved_actions.push(json!({ - "action": act, - "effects": eff.map(|e| e.effects).unwrap_or_default(), - })); + match service::plan_general(exec, root, &query, &facts, &ai) { + Ok(plan) => { + conversation::save_turn( + &conv_path, + ConversationTurn { + timestamp_unix: now_unix(), + query, + response_kind: "plan".into(), + application: None, + chosen_candidate: None, + alternatives: Vec::new(), + plan_id: Some(plan.id.clone()), + plan_digest: Some(plan.digest.clone()), + 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, + }), + ) + } + Err(e) => BridgeResponse::err(id, e.to_string()), } + } + "execute" => { + let plan_id = match req.plan_id.as_deref() { + Some(p) => p, + None => return BridgeResponse::err(id, "missing plan_id parameter"), + }; + let digest = match req.digest.as_deref() { + Some(d) => d, + None => return BridgeResponse::err(id, "missing digest parameter"), + }; + + match service::execute_plan(exec, root, plan_id, digest, req.yes.unwrap_or(false)) { + Ok(outcome) => BridgeResponse::ok( + id, + json!({ + "completed": outcome.completed, + "snapshot": outcome.snapshot, + "result": outcome.result, + "verification": outcome.verification, + }), + ), + Err(e) => BridgeResponse::err(id, e.to_string()), + } + } + unknown => BridgeResponse::err(id, format!("unknown bridge op: {unknown}")), + } +} + +fn plan_and_respond_install( + exec: &Exec, + root: &Path, + id: u64, + app: &str, + constrained_backend: Option, + query: &str, + conv_path: &Path, +) -> 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( + conv_path, + ConversationTurn { + timestamp_unix: now_unix(), + query: query.to_string(), + response_kind: "install".into(), + application: Some(app.to_string()), + chosen_candidate: plan.candidate.clone(), + alternatives: plan.alternatives.clone(), + plan_id: Some(plan.id.clone()), + plan_digest: Some(plan.digest.clone()), + rationale: plan.rationale.clone(), + }, + ); BridgeResponse::ok( id, json!({ - "kind": "plan", - "summary": plan.summary, - "actions": resolved_actions, - "requires_root": any_mutating, + "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, }), ) } - "execute" => { - let actions_val = match req.actions { - Some(a) => a, - None => return BridgeResponse::err(id, "missing actions array"), - }; - let mut parsed_actions = Vec::new(); - let mut any_mutating = false; - for val in actions_val { - let action: SystemAction = match serde_json::from_value(val) { - Ok(a) => a, - Err(e) => { - return BridgeResponse::err( - id, - format!("invalid action in execution list: {e}"), - ) - } - }; - any_mutating |= action.is_mutating(); - parsed_actions.push(action); - } - - let confirm = BridgeConfirm { - assume_yes: req.yes.unwrap_or(false), - }; - let auth = if any_mutating { - match authorize(&confirm, "Desktop Assistant Plan Execution", "execute") { - Ok(a) => Some(a), - Err(e) => return BridgeResponse::err(id, format!("authorization denied: {e}")), - } - } else { - None - }; - - let mut approved_steps = Vec::new(); - for act in &parsed_actions { - let eff = match actions::resolve_effects(exec, act, root) { - Ok(e) => e, - Err(e) => { - return BridgeResponse::err(id, format!("effect revalidation failed: {e}")) - } - }; - approved_steps.push((act.clone(), eff)); - } - - let run = actions::execute_plan(exec, &approved_steps, auth.as_ref(), root); - let mut attempted: Vec = run.completed.iter().map(|(a, _)| a.clone()).collect(); - if let Some((action, _detail)) = &run.failure { - attempted.push(action.clone()); - } - - let result_str = match &run.failure { - None => "ok".to_string(), - Some((action, detail)) => format!("failed: {action}: {detail}"), - }; - - let record = TransactionRecord { - id: 0, - created_unix: now_unix(), - origin: "assistant-gui".into(), - summary: format!("execute {} action(s)", parsed_actions.len()), - actions: attempted, - result: result_str.clone(), - snapshot: run.snapshot.clone(), - digest: req.digest, - outcomes: run.outcomes, - }; - let _ = transaction::append(exec, root, record); - - if let Some((act, det)) = run.failure { - BridgeResponse::err(id, format!("action failed: {act}: {det}")) - } else { - BridgeResponse::ok( - id, - json!({ - "completed": true, - "snapshot": run.snapshot, - "result": result_str, - }), - ) - } - } - unknown => BridgeResponse::err(id, format!("unknown bridge op: {unknown}")), + Err(e) => BridgeResponse::err(id, e.to_string()), } } @@ -538,50 +666,48 @@ fn execute_action_helper( action: SystemAction, assume_yes: bool, ) -> BridgeResponse { - let approved = match actions::resolve_effects(exec, &action, root) { - Ok(plan) => Some(plan), + let effects = match actions::resolve_effects(exec, &action, root) { + Ok(plan) => plan, Err(e) => return BridgeResponse::err(id, format!("could not resolve effects: {e}")), }; - let confirm = BridgeConfirm { assume_yes }; - let auth = if action.is_mutating() { - match authorize(&confirm, &actions::preview(&action), "execute") { - Ok(a) => Some(a), - Err(e) => return BridgeResponse::err(id, format!("authorization denied: {e}")), - } - } else { - None + 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}"), + created_unix: now, + expires_unix: now + service::DEFAULT_PLAN_TTL_SECONDS, + kind: service::PlanKind::General, + summary: action.describe(), + recommendation: action.describe(), + application: None, + candidate: None, + alternatives: Vec::new(), + rationale: Vec::new(), + warnings: Vec::new(), + actions: actions_vec, + effects, + digest: digest.clone(), + verification: "action completed".into(), + requires_root: action.is_mutating(), + source: "legacy".into(), + executed: false, }; - - let outcome = - match actions::execute_checked(exec, &action, auth.as_ref(), root, approved.as_ref()) { - Ok(o) => o, - Err(e) => return BridgeResponse::err(id, e.to_string()), - }; - - if action.is_mutating() { - let desc = action.describe(); - let record = TransactionRecord { - id: 0, - created_unix: now_unix(), - origin: "sys-legacy".into(), - summary: desc.clone(), - actions: vec![desc.clone()], - result: "ok".into(), - snapshot: outcome.snapshot.clone(), - digest: approved.as_ref().map(|p| p.digest.clone()), - outcomes: vec![TransactionOutcome::completed(desc)], - }; - let _ = transaction::append(exec, root, record); + if let Err(e) = service::PlanStore::save(&plan) { + return BridgeResponse::err(id, format!("could not stage plan: {e}")); } - BridgeResponse::ok( - id, - json!({ - "output": outcome.output, - "snapshot": outcome.snapshot, - }), - ) + match service::execute_plan(exec, root, &plan.id, &digest, assume_yes) { + Ok(outcome) => BridgeResponse::ok( + id, + json!({ + "output": outcome.result, + "snapshot": outcome.snapshot, + }), + ), + Err(e) => BridgeResponse::err(id, e.to_string()), + } } fn parse_install_phrase(text: &str) -> Option { @@ -604,6 +730,26 @@ fn parse_install_phrase(text: &str) -> Option { None } +fn parse_removal_phrase(text: &str) -> Option { + let mut trimmed = text.trim(); + for prefix in ["please ", "Please "] { + if let Some(rest) = trimmed.strip_prefix(prefix) { + trimmed = rest.trim(); + break; + } + } + let lower = trimmed.to_ascii_lowercase(); + for prefix in ["remove ", "uninstall ", "delete "] { + if lower.starts_with(prefix) { + let app = trimmed[prefix.len()..].trim(); + if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') { + return Some(app.to_string()); + } + } + } + None +} + /// Run line-delimited JSON-RPC loop on stdio. pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box> { let stdin = std::io::stdin(); @@ -665,6 +811,7 @@ mod tests { application: None, backend: None, phrase: None, + plan_id: None, action: None, actions: None, digest: None, @@ -689,6 +836,7 @@ mod tests { application: None, backend: None, phrase: None, + plan_id: None, action: None, actions: None, digest: None, @@ -715,4 +863,18 @@ mod tests { assert_eq!(parse_install_phrase("add vlc"), Some("vlc".into())); assert_eq!(parse_install_phrase("why is audio broken"), None); } + + #[test] + fn test_parse_removal_phrase() { + assert_eq!( + parse_removal_phrase("remove firefox"), + Some("firefox".into()) + ); + assert_eq!(parse_removal_phrase("uninstall vlc"), Some("vlc".into())); + assert_eq!( + parse_removal_phrase("delete thunderbird"), + Some("thunderbird".into()) + ); + assert_eq!(parse_removal_phrase("install firefox"), None); + } } diff --git a/installer-rs/crates/phoebus-installer/src/bin/sys.rs b/installer-rs/crates/phoebus-installer/src/bin/sys.rs index be82510..5862b75 100644 --- a/installer-rs/crates/phoebus-installer/src/bin/sys.rs +++ b/installer-rs/crates/phoebus-installer/src/bin/sys.rs @@ -11,18 +11,19 @@ use std::path::{Path, PathBuf}; use std::process::ExitCode; use clap::Parser; -use phoebus_ai::assistant::{complete_plan, AssistantPlan}; use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts}; use phoebus_core::action::{parse_action, parse_natural, SystemAction}; use phoebus_core::selection::Backend; use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; use phoebus_core::{AiBackend, InstallConfig, Redactor}; -use phoebus_executor::install::{self, AiInstall, ExecutorSession, InstallRequest}; +use phoebus_executor::install::{AiInstall, ExecutorSession, InstallRequest}; use phoebus_executor::opencode_client::ExecOpenCodeTransport; use phoebus_executor::{ actions, authorize, chooser, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization, Exec, Logger, RealRunner, Result, }; +use phoebus_installer::conversation::{self, ConversationTurn, FollowupResolution}; +use phoebus_installer::service::{self, PreparedPlan}; #[derive(Parser, Debug)] #[command( @@ -57,6 +58,10 @@ struct Cli { #[arg(long)] action_file: Option, + /// Execute a prepared plan file directly (internal broker invocation). + #[arg(long, value_name = "PATH")] + execute_plan: Option, + /// Auto-approve (unattended); still requires root. #[arg(long, short = 'y')] yes: bool, @@ -218,7 +223,21 @@ fn run() -> std::result::Result<(), Box> { return phoebus_installer::assistant_bridge::run_stdio(&exec, &cli.root); } - // 2. Audit JSON/action-file entry points + // 2. Broker execute plan + if let Some(plan_path) = &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)?; + println!("{}", serde_json::to_string(&outcome)?); + return Ok(()); + } + + // 3. Audit JSON/action-file entry points if cli.action.is_some() || cli.action_file.is_some() { if !cli.legacy && !cli.broker { return Err( @@ -241,14 +260,14 @@ fn run() -> std::result::Result<(), Box> { let backend = backend_flag(&cli); let full_phrase = cli.text.join(" "); - // 3. Explicit legacy mode (--legacy) + // 4. Explicit legacy mode (--legacy) if cli.legacy { if let Some(application) = parse_install_text(&full_phrase) { if let Some(b) = backend { let mut request = InstallRequest::new(&application); request.backend = Some(b); - let resolved = install::resolve_explicit(&exec, &cli.root, &request)?; - return execute_resolved(&cli, &exec, resolved); + let plan = service::plan_legacy_install(&exec, &cli.root, &request)?; + return render_and_execute_plan(&cli, &exec, plan); } else { eprintln!("sys: legacy install requires an explicit package source flag."); eprintln!("Specify one of:"); @@ -261,10 +280,14 @@ fn run() -> std::result::Result<(), Box> { return Err("legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)".into()); } } + 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); + } if backend.is_some() { return Err( "--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \ - `sys install `" + `sys install ` or `sys remove `" .into(), ); } @@ -277,6 +300,7 @@ fn run() -> std::result::Result<(), Box> { eprintln!("sys: could not parse `{full_phrase}` in legacy mode."); eprintln!( "Legacy mode grammar: sys install --legacy -- | \ + sys remove --legacy [--] | \ sys history --legacy | sys undo --legacy | sys enable --legacy | \ sys disable --legacy | sys choose --legacy" ); @@ -285,15 +309,17 @@ fn run() -> std::result::Result<(), Box> { }; } - // 4. Default AI mode (natural language) + // 5. Default AI mode (natural language) if cli.text.is_empty() { eprintln!("sys: no instruction provided."); eprintln!("Natural language administration is the default:"); eprintln!(" sys install "); eprintln!(" sys please install "); + eprintln!(" sys remove "); eprintln!(" sys ask \"\""); eprintln!("Or select deterministic legacy administration:"); eprintln!(" sys install --legacy --"); + eprintln!(" sys remove --legacy [--]"); eprintln!(" sys history --legacy"); eprintln!(" sys undo --legacy"); return Err("missing instruction".into()); @@ -313,10 +339,15 @@ fn run() -> std::result::Result<(), Box> { return run_install(&cli, &exec, &application, backend); } + // Natural `sys remove ` / `sys please remove ` + if let Some(application) = parse_removal_text(&full_phrase) { + return run_remove(&cli, &exec, &application, backend); + } + if backend.is_some() { return Err( "--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \ - `sys install `" + `sys install ` or `sys remove `" .into(), ); } @@ -442,6 +473,27 @@ fn parse_install_text(text: &str) -> Option { None } +/// Parse `remove ` / `uninstall ` / `delete ` / `please remove `. +fn parse_removal_text(text: &str) -> Option { + let mut trimmed = text.trim(); + for prefix in ["please ", "Please "] { + if let Some(rest) = trimmed.strip_prefix(prefix) { + trimmed = rest.trim(); + break; + } + } + let lower = trimmed.to_ascii_lowercase(); + for prefix in ["remove ", "uninstall ", "delete "] { + if lower.starts_with(prefix) { + let app = trimmed[prefix.len()..].trim(); + if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') { + return Some(app.to_string()); + } + } + } + None +} + /// Load the installed system's configuration instead of assuming defaults. fn load_installed_config(root: &Path) -> InstallConfig { let path = root.join("etc/phoebus/install.toml"); @@ -643,9 +695,8 @@ fn run_install( root: &cli.root, ask: asker.as_deref(), }; - let resolved = match install::resolve_with_ai(exec, &cli.root, &request, &session, &ai, &facts) - { - Ok(resolved) => resolved, + let plan = match service::plan_install(exec, &cli.root, &request, &session, Some(&ai), &facts) { + Ok(plan) => plan, Err(e) => { // The model failed: offer the actionable legacy alternative and stop; // do not install through any backend. @@ -662,119 +713,87 @@ fn run_install( return Err(format!("the AI investigation did not produce a plan: {e}").into()); } }; - execute_resolved(cli, exec, resolved) + + let conv_path = conversation::history_path(); + conversation::save_turn( + &conv_path, + ConversationTurn { + timestamp_unix: now_unix(), + query: format!("install {application}"), + response_kind: "install".into(), + application: Some(application.to_string()), + chosen_candidate: plan.candidate.clone(), + alternatives: plan.alternatives.clone(), + plan_id: Some(plan.id.clone()), + plan_digest: Some(plan.digest.clone()), + rationale: plan.rationale.clone(), + }, + ); + + render_and_execute_plan(cli, exec, plan) } -/// Present, approve, execute, verify and record a resolved installation. This -/// is the single execution path for AI-, explicit- and deterministic-selected -/// installs. -fn execute_resolved( +fn run_remove( cli: &Cli, exec: &Exec, - resolved: install::ResolvedInstall, + application: &str, + backend: Option, ) -> std::result::Result<(), Box> { - println!("{}", resolved.render()); - - if effective_uid() != 0 { - return Err(format!( - "installing `{}` requires root; run `sudo sys install {}`", - resolved.request.application, resolved.request.application - ) - .into()); - } - let confirmation = SysConfirm { - action: resolved.action.clone(), - assume_yes: cli.yes, - }; - let auth = authorize(&confirmation, &resolved.render(), "install")?; - - // Bind approval to the reviewed plan and revalidate before any mutation. - let current = match install::revalidate(exec, &cli.root, &resolved) { - Ok(current) => current, - Err(e) => { - return Err( - format!("the reviewed plan changed before execution ({e}); review again").into(), - ) - } - }; - if current != resolved.approval_digest() { - return Err( - "the reviewed plan changed materially before execution; re-run and review again".into(), - ); - } - - let described = format!( - "install {} via {} ({})", - resolved.request.application, - resolved.candidate.backend.as_str(), - resolved.source.as_str() - ); - let record = TransactionRecord { - id: 0, - created_unix: now_unix(), - origin: if cli.legacy { - "sys-legacy".into() - } else { - "sys".into() + let plan = service::plan_removal(exec, &cli.root, application, backend)?; + let conv_path = conversation::history_path(); + conversation::save_turn( + &conv_path, + ConversationTurn { + timestamp_unix: now_unix(), + query: format!("remove {application}"), + response_kind: "removal".into(), + application: Some(application.to_string()), + chosen_candidate: None, + alternatives: Vec::new(), + plan_id: Some(plan.id.clone()), + plan_digest: Some(plan.digest.clone()), + rationale: plan.rationale.clone(), }, - summary: described.clone(), - actions: vec![described.clone()], - result: "in progress".into(), - snapshot: None, - digest: Some(resolved.approval_digest()), - outcomes: Vec::new(), - }; - let id = transaction::begin(exec, &cli.root, record)?; + ); + render_and_execute_plan(cli, exec, plan) +} - let outcome = match actions::execute(exec, &resolved.action, Some(&auth), &cli.root) { - Ok(outcome) => outcome, - Err(e) => { - let detail = e.to_string(); - let _ = transaction::finish( - exec, - &cli.root, - id, - format!("failed: {detail}"), - None, - vec![TransactionOutcome::failed( - described.clone(), - detail.clone(), - )], - ); - return Err(format!("installation failed: {detail}").into()); - } - }; - if let Some(snapshot) = &outcome.snapshot { +fn render_and_execute_plan( + cli: &Cli, + exec: &Exec, + plan: PreparedPlan, +) -> std::result::Result<(), Box> { + println!("{}", plan.render()); + + if plan.requires_root && effective_uid() != 0 { + return Err("mutating actions require root; run `sudo sys ...`".into()); + } + + if plan.requires_root && !cli.yes { + let confirmation = SysConfirm { + action: plan + .actions + .first() + .cloned() + .unwrap_or(SystemAction::History), + assume_yes: false, + }; + authorize(&confirmation, &plan.summary, "execute")?; + } + + let outcome = service::execute_plan(exec, &cli.root, &plan.id, &plan.digest, true)?; + if let Some(snapshot) = outcome.snapshot { println!("protective snapshot: {snapshot}"); } - println!("{}", outcome.output); - - match install::verify_installed(exec, &cli.root, &resolved) { - Ok(verification) => { - println!("{verification}"); - transaction::finish( - exec, - &cli.root, - id, - "ok", - outcome.snapshot.clone(), - vec![TransactionOutcome::completed(described.clone())], - )?; - Ok(()) - } - Err(e) => { - let detail = e.to_string(); - transaction::finish( - exec, - &cli.root, - id, - format!("verify failed: {detail}"), - outcome.snapshot.clone(), - vec![TransactionOutcome::completed(described.clone())], - )?; - Err(format!("the install command completed but verification failed: {detail}").into()) + for line in &outcome.output { + if !line.trim().is_empty() { + println!("{line}"); } } + if !outcome.verification.is_empty() { + println!("{}", outcome.verification); + } + Ok(()) } /// Bounded system facts for the assistant: hardware, selected profile and @@ -898,6 +917,33 @@ fn run_ask( if let Some(application) = parse_install_text(instruction) { return run_install(cli, exec, &application, backend); } + if let Some(application) = parse_removal_text(instruction) { + return run_remove(cli, exec, &application, backend); + } + + let conv_path = conversation::history_path(); + let history = conversation::load_history(&conv_path); + if let Some(followup) = conversation::resolve_followup(instruction, &history) { + match followup { + FollowupResolution::Comparison { explanation, .. } => { + println!("{explanation}"); + return Ok(()); + } + FollowupResolution::SwitchBackend { + application, + target_backend, + } => { + return run_install(cli, exec, &application, Some(target_backend)); + } + FollowupResolution::ConfirmPlan { plan_id, digest } => { + let plan = service::PlanStore::load(&plan_id)?; + if plan.digest != digest { + return Err("plan digest mismatch".into()); + } + return render_and_execute_plan(cli, exec, plan); + } + } + } let facts = gather_facts(exec); let conf = load_installed_ai_config(&cli.root); @@ -982,14 +1028,15 @@ fn run_ask( } } - let plan: AssistantPlan = match complete_plan( + let ai = AiInstall { provider, - &endpoint, - &model, - &facts, - instruction, - transport.as_ref(), - ) { + endpoint, + model, + transport: transport.as_ref(), + limits: phoebus_ai::install::Limits::default(), + }; + + let plan = match service::plan_general(exec, &cli.root, instruction, &facts, &ai) { Ok(plan) => plan, Err(e) => { eprintln!("The model is unavailable or returned an unusable plan: {e}"); @@ -998,77 +1045,22 @@ fn run_ask( } }; - println!("{}", plan.render()); + conversation::save_turn( + &conv_path, + ConversationTurn { + timestamp_unix: now_unix(), + query: instruction.to_string(), + response_kind: "plan".into(), + application: None, + chosen_candidate: None, + alternatives: Vec::new(), + plan_id: Some(plan.id.clone()), + plan_digest: Some(plan.digest.clone()), + rationale: plan.rationale.clone(), + }, + ); - let mut approved = Vec::new(); - let mut mutating = false; - for action in &plan.actions { - let resolved = actions::resolve_effects(exec, action, &cli.root)?; - if !resolved.effects.is_empty() { - println!("{}", resolved.render()); - } - approved.push(resolved); - mutating |= action.is_mutating(); - } - - if mutating && effective_uid() != 0 { - return Err("this plan modifies the system; run `sudo sys ask ...`".into()); - } - let auth: Option = if mutating { - let confirmation = SysConfirm { - action: plan - .actions - .first() - .cloned() - .unwrap_or(SystemAction::History), - assume_yes: cli.yes, - }; - Some(authorize( - &confirmation, - &plan.render(), - "execute the assistant's plan", - )?) - } else { - None - }; - - let digest = approved - .iter() - .find(|p| !p.digest.is_empty()) - .map(|p| p.digest.clone()); - let steps: Vec<(SystemAction, phoebus_core::effects::ResolvedPlan)> = - plan.actions.iter().cloned().zip(approved).collect(); - let run = actions::execute_plan(exec, &steps, auth.as_ref(), &cli.root); - for (_, output) in &run.completed { - println!("{output}"); - } - let mut attempted: Vec = run.completed.iter().map(|(a, _)| a.clone()).collect(); - if let Some((action, detail)) = &run.failure { - eprintln!("action failed: {action}: {detail}"); - attempted.push(action.clone()); - } - - let result = match &run.failure { - None => "ok".to_string(), - Some((action, detail)) => format!("failed: {action}: {detail}"), - }; - let record = TransactionRecord { - id: 0, - created_unix: now_unix(), - origin: "assistant".into(), - summary: plan.summary.clone(), - actions: attempted, - result, - snapshot: run.snapshot, - digest, - outcomes: run.outcomes, - }; - record_transaction(exec, &cli.root, record)?; - - if let Some((action, detail)) = run.failure { - return Err(format!("the assistant plan did not complete: {action}: {detail}").into()); - } - Ok(()) + render_and_execute_plan(cli, exec, plan) } #[allow(dead_code)] diff --git a/installer-rs/crates/phoebus-installer/src/conversation.rs b/installer-rs/crates/phoebus-installer/src/conversation.rs new file mode 100644 index 0000000..b9ceae0 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/conversation.rs @@ -0,0 +1,313 @@ +//! Conversation continuity and contextual follow-up tracking for Phoebus assistant. +//! +//! Tracks recent interaction turns to support contextual follow-ups such as +//! "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. + +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use phoebus_core::selection::{Backend, Candidate, Rejected}; +use phoebus_core::Redactor; +use serde::{Deserialize, Serialize}; + +const MAX_TURNS: usize = 10; +const FOLLOWUP_WINDOW_SECONDS: u64 = 1800; // 30 minutes + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConversationTurn { + pub timestamp_unix: u64, + pub query: String, + pub response_kind: String, // "install", "removal", "plan", "info" + #[serde(default, skip_serializing_if = "Option::is_none")] + pub application: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub chosen_candidate: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub alternatives: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan_digest: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub rationale: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct ConversationHistory { + pub turns: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FollowupResolution { + /// Explain the tradeoffs between the chosen candidate and alternative backend. + Comparison { + application: String, + target_backend: Option, + explanation: String, + }, + /// Switch candidate to an alternative backend requested by user. + SwitchBackend { + application: String, + target_backend: Backend, + }, + /// Execute or confirm previously prepared plan. + ConfirmPlan { plan_id: String, digest: String }, +} + +fn now_unix() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +pub fn history_path() -> PathBuf { + if let Ok(dir) = std::env::var("PHOEBUS_CONVERSATION_DIR") { + return PathBuf::from(dir).join("conversation.json"); + } + if let Ok(user_dir) = std::env::var("XDG_DATA_HOME") { + return PathBuf::from(user_dir) + .join("phoebus") + .join("conversation.json"); + } + if let Ok(home) = std::env::var("HOME") { + return PathBuf::from(home).join(".local/share/phoebus/conversation.json"); + } + std::env::temp_dir().join("phoebus-conversation.json") +} + +pub fn load_history(path: &Path) -> ConversationHistory { + if !path.is_file() { + return ConversationHistory::default(); + } + let data = match std::fs::read_to_string(path) { + Ok(d) => d, + Err(_) => return ConversationHistory::default(), + }; + serde_json::from_str(&data).unwrap_or_default() +} + +pub fn save_turn(path: &Path, turn: ConversationTurn) { + 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 + .rationale + .into_iter() + .map(|r| redactor.redact(&r)) + .collect(); + + history.turns.push(sanitized_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); + } + if let Ok(serialized) = serde_json::to_string_pretty(&history) { + let _ = std::fs::write(path, serialized); + } +} + +/// Analyze incoming query against the most recent conversation turn. +pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option { + let last = history.turns.last()?; + let now = now_unix(); + if now.saturating_sub(last.timestamp_unix) > FOLLOWUP_WINDOW_SECONDS { + return None; + } + + let q_lower = query.trim().to_ascii_lowercase(); + + // 1. Confirmation ("install that one", "proceed", "yes, do it") + if matches!( + q_lower.as_str(), + "install that one" + | "install that" + | "proceed" + | "proceed with that" + | "confirm" + | "yes" + | "yes do it" + | "go ahead" + ) { + if let (Some(plan_id), Some(digest)) = (&last.plan_id, &last.plan_digest) { + return Some(FollowupResolution::ConfirmPlan { + plan_id: plan_id.clone(), + digest: digest.clone(), + }); + } + } + + let app = last.application.as_deref()?; + + // 2. Switch backend ("install the flatpak one", "use portage instead", "install via nix") + let backends = [ + ("flatpak", Backend::Flatpak), + ("portage", Backend::PortageSource), + ("source", Backend::PortageSource), + ("binary", Backend::PortageBinary), + ("nix", Backend::Nix), + ("snap", Backend::Snap), + ("appimage", Backend::AppImage), + ]; + + for (name, backend) in backends { + if (q_lower.contains("install") || q_lower.contains("use") || q_lower.contains("switch")) + && q_lower.contains(name) + { + return Some(FollowupResolution::SwitchBackend { + application: app.to_string(), + target_backend: backend, + }); + } + } + + // 3. Comparison / Why question ("why did you choose that over nix?", "why flatpak?", "why not portage?") + let is_why = q_lower.starts_with("why") + || q_lower.contains("how come") + || q_lower.contains("explain") + || q_lower.contains("compare") + || q_lower.contains("difference") + || q_lower.contains("versus") + || q_lower.contains(" vs "); + + if is_why { + let mut target_backend = None; + for (name, backend) in backends { + if q_lower.contains(name) { + target_backend = Some(backend); + break; + } + } + + let mut explanation = String::new(); + if let Some(cand) = &last.chosen_candidate { + explanation.push_str(&format!( + "For `{app}`, **{}** was recommended because:\n", + cand.backend.as_str() + )); + for r in &last.rationale { + explanation.push_str(&format!(" - {r}\n")); + } + } + + if let Some(tb) = target_backend { + if let Some(rejected) = last.alternatives.iter().find(|r| r.backend == tb) { + explanation.push_str(&format!( + "\nCompared to **{}**: rejected because {}.", + tb.as_str(), + rejected.reason.explain() + )); + } else if let Some(cand) = &last.chosen_candidate { + if cand.backend == tb { + explanation.push_str(&format!( + "\n**{}** is the currently chosen backend.", + tb.as_str() + )); + } + } + } else if !last.alternatives.is_empty() { + explanation.push_str("\nAlternatives considered:\n"); + for alt in &last.alternatives { + explanation.push_str(&format!( + " - **{}**: {}\n", + alt.backend.as_str(), + alt.reason.explain() + )); + } + } + + if !explanation.is_empty() { + return Some(FollowupResolution::Comparison { + application: app.to_string(), + target_backend, + explanation, + }); + } + } + + None +} + +#[cfg(test)] +mod tests { + use super::*; + use phoebus_core::selection::{Capability, RejectReason, SandboxLevel}; + use tempfile::tempdir; + + fn make_test_candidate(backend: Backend) -> Candidate { + let mut cand = Candidate::new(backend, "firefox", "flathub"); + cand.version = Some("120.0".into()); + cand.verified = true; + cand.download_mib = Some(85); + cand.install_mib = Some(220); + cand.sandbox = SandboxLevel::Strong; + cand.wayland = Capability::Yes; + cand.desktop_integration = Capability::Yes; + cand.permissions = vec!["network".into()]; + cand + } + + #[test] + fn test_conversation_followup_switch_and_comparison() { + let temp = tempdir().unwrap(); + let path = temp.path().join("conversation.json"); + + let turn = ConversationTurn { + timestamp_unix: now_unix(), + query: "install firefox".into(), + response_kind: "install".into(), + application: Some("firefox".into()), + chosen_candidate: Some(make_test_candidate(Backend::Flatpak)), + alternatives: vec![Rejected { + backend: Backend::Nix, + id: "firefox".into(), + reason: RejectReason::BackendNotRequested, + }], + + plan_id: Some("plan-1234".into()), + plan_digest: Some("abc123digest".into()), + rationale: vec!["provides application isolation".into()], + }; + + save_turn(&path, turn); + let history = load_history(&path); + assert_eq!(history.turns.len(), 1); + + // Test switch backend + let switch = resolve_followup("install the nix one", &history); + assert_eq!( + switch, + Some(FollowupResolution::SwitchBackend { + application: "firefox".into(), + target_backend: Backend::Nix, + }) + ); + + // Test comparison question + let comparison = resolve_followup("why did you choose that over nix?", &history); + assert!(matches!( + comparison, + Some(FollowupResolution::Comparison { ref application, target_backend: Some(Backend::Nix), .. }) + if application == "firefox" + )); + + // Test plan confirmation + let confirm = resolve_followup("proceed with that", &history); + assert_eq!( + confirm, + Some(FollowupResolution::ConfirmPlan { + plan_id: "plan-1234".into(), + digest: "abc123digest".into(), + }) + ); + } +} diff --git a/installer-rs/crates/phoebus-installer/src/lib.rs b/installer-rs/crates/phoebus-installer/src/lib.rs index ffdbfd9..d553f84 100644 --- a/installer-rs/crates/phoebus-installer/src/lib.rs +++ b/installer-rs/crates/phoebus-installer/src/lib.rs @@ -2,8 +2,10 @@ pub mod ai_guide; pub mod assistant_bridge; +pub mod conversation; pub mod gui_bridge; pub mod orchestrate; pub mod release; +pub mod service; pub use orchestrate::{InstallObserver, Installer, NoopObserver}; diff --git a/installer-rs/crates/phoebus-installer/src/service.rs b/installer-rs/crates/phoebus-installer/src/service.rs new file mode 100644 index 0000000..6a48e2e --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/service.rs @@ -0,0 +1,1055 @@ +//! Shared administration service layer for Phoebus OS. +//! +//! Provides a single, unified implementation for both the CLI (`sys`) and desktop +//! GUI (`phoebus-assistant`) covering: +//! - Bounded investigation and connected model planning +//! - Candidate discovery, provenance verification, and policy enforcement +//! - Plan staging (`PreparedPlan`) and cryptographically bound approval digests +//! - TTL enforcement and replay/tamper protection (`PlanStore`) +//! - Cross-source application removal preserving user data by default +//! - Two-phase transaction logging (`begin` before mutation, `finish` with verification) +//! - Unprivileged-to-privileged desktop Polkit elevation (`pkexec`) + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use phoebus_ai::assistant::{complete_plan, AssistantPlan}; +use phoebus_ai::provider::SystemFacts; +use phoebus_core::action::SystemAction; +use phoebus_core::effects::ResolvedPlan; +use phoebus_core::selection::{Backend, Candidate, Rejected, SandboxLevel}; +use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; +use phoebus_executor::actions; +use phoebus_executor::auth::{authorize, Confirmation}; +use phoebus_executor::chooser; +use phoebus_executor::error::{ExecError, Result}; +use phoebus_executor::exec::Exec; +use phoebus_executor::install::{self, AiInstall, InstallRequest, InstallSource}; +use phoebus_executor::transaction; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +pub const DEFAULT_PLAN_TTL_SECONDS: u64 = 900; // 15 minutes + +static PLAN_COUNTER: AtomicU64 = AtomicU64::new(1); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PlanKind { + Install, + LegacyInstall, + Removal, + General, + Undo, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreparedPlan { + pub id: String, + pub created_unix: u64, + pub expires_unix: u64, + pub kind: PlanKind, + pub summary: String, + pub recommendation: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub application: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub candidate: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub alternatives: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub rationale: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, + pub actions: Vec, + pub effects: ResolvedPlan, + pub digest: String, + pub verification: String, + pub requires_root: bool, + pub source: String, + pub executed: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PlanExecutionOutcome { + pub completed: bool, + pub snapshot: Option, + pub result: String, + pub verification: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub output: Vec, +} + +impl PreparedPlan { + pub fn render(&self) -> String { + let mut out = String::new(); + match self.kind { + PlanKind::Install | PlanKind::LegacyInstall => { + out.push_str(&format!( + "Install plan ({}):\n", + if self.kind == PlanKind::LegacyInstall { + "explicit selection" + } else { + "AI recommendation" + } + )); + if let Some(app) = &self.application { + out.push_str(&format!(" application: {app}\n")); + } + if let Some(c) = &self.candidate { + out.push_str(&format!(" backend: {}\n", c.backend.as_str())); + out.push_str(&format!(" candidate: {}\n", c.id)); + out.push_str(&format!( + " version: {}\n", + c.version.as_deref().unwrap_or("(resolved at install time)") + )); + out.push_str(&format!(" source: {}\n", self.source)); + out.push_str(&format!( + " integrity: {}\n", + if c.verified { + "verified (signature/hash)" + } else { + "UNVERIFIED — provenance not cryptographic" + } + )); + out.push_str(&format!( + " sandbox: {} wayland: {} desktop: {}\n", + match c.sandbox { + SandboxLevel::None => "none", + SandboxLevel::Partial => "partial", + SandboxLevel::Strong => "strong", + }, + match c.wayland { + phoebus_core::selection::Capability::No => "no", + phoebus_core::selection::Capability::Partial => "partial", + phoebus_core::selection::Capability::Yes => "yes", + }, + match c.desktop_integration { + phoebus_core::selection::Capability::No => "no", + phoebus_core::selection::Capability::Partial => "partial", + phoebus_core::selection::Capability::Yes => "yes", + } + )); + if let Some(mib) = c.download_mib { + out.push_str(&format!(" download: ~{mib} MiB\n")); + } + if let Some(mib) = c.install_mib { + out.push_str(&format!(" on disk: ~{mib} MiB\n")); + } + } + out.push_str("Why:\n"); + out.push_str(&format!(" - {}\n", self.recommendation)); + for r in &self.rationale { + out.push_str(&format!(" - {r}\n")); + } + if !self.alternatives.is_empty() { + out.push_str("Alternatives considered:\n"); + for alt in &self.alternatives { + out.push_str(&format!( + " - {} ({}): {}\n", + alt.id, + alt.backend.as_str(), + alt.reason.explain() + )); + } + } + for w in &self.warnings { + out.push_str(&format!(" ! {w}\n")); + } + if self.effects.established && !self.effects.effects.is_empty() { + out.push_str(&self.effects.render()); + } + out.push_str(&format!("Verification: {}\n", self.verification)); + out.push_str(&format!("Approval digest: {}\n", self.digest)); + } + PlanKind::Removal => { + out.push_str("Removal plan:\n"); + if let Some(app) = &self.application { + out.push_str(&format!(" application: {app}\n")); + } + out.push_str(&format!(" source: {}\n", self.source)); + out.push_str("Why:\n"); + out.push_str(&format!(" - {}\n", self.recommendation)); + for r in &self.rationale { + out.push_str(&format!(" - {r}\n")); + } + if self.effects.established && !self.effects.effects.is_empty() { + out.push_str(&self.effects.render()); + } + out.push_str(&format!("Verification: {}\n", self.verification)); + out.push_str(&format!("Approval digest: {}\n", self.digest)); + } + _ => { + out.push_str(&format!("Assistant Plan:\n {}\n", self.summary)); + for a in &self.actions { + out.push_str(&format!(" - {}\n", a.describe())); + } + if self.effects.established && !self.effects.effects.is_empty() { + out.push_str(&self.effects.render()); + } + out.push_str(&format!("Verification: {}\n", self.verification)); + out.push_str(&format!("Approval digest: {}\n", self.digest)); + } + } + out + } +} + +fn now_unix() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +pub fn effective_uid() -> u32 { + if std::env::var("PHOEBUS_ALLOW_UNPRIVILEGED_EXEC").as_deref() == Ok("1") { + return 0; + } + std::process::Command::new("id") + .arg("-u") + .output() + .ok() + .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok()) + .unwrap_or(1) +} + +/// Compute a cryptographic digest binding the exact actions, candidate, and effects. +pub fn compute_plan_digest( + actions: &[SystemAction], + candidate: Option<&Candidate>, + effects: &ResolvedPlan, +) -> String { + if let (Some(cand), Some(act)) = (candidate, actions.first()) { + if actions.len() == 1 { + return install::approval_digest_for(cand, act, effects); + } + } + + let mut hasher = Sha256::new(); + if let Some(c) = 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 actions { + hasher.update(serde_json::to_string(act).unwrap_or_default().as_bytes()); + hasher.update(b"\0"); + } + if effects.established { + hasher.update(effects.digest.as_bytes()); + } else { + hasher.update(b"no-established-effects"); + } + format!("{:x}", hasher.finalize()) +} + +/// Produce an honest, evidence-based human recommendation for an application candidate. +pub fn format_recommendation(candidate: &Candidate, application: &str) -> String { + let source_name = match candidate.backend { + Backend::PortageBinary => "Gentoo binhost", + Backend::PortageSource => "Gentoo Portage", + Backend::PortageVendor => "Portage vendor binary", + Backend::Flatpak => "Flathub", + Backend::Snap => "Snap Store", + Backend::Nix => "Nixpkgs", + Backend::AppImage => "managed AppImage", + Backend::CustomEbuild => "Phoebus custom ebuild", + }; + + let sandbox_desc = match candidate.sandbox { + SandboxLevel::Strong => "strong application isolation", + SandboxLevel::Partial => "partial confinement", + SandboxLevel::None => "direct host integration (unconfined)", + }; + + let build_desc = if let Some(secs) = candidate.build_seconds { + if secs < 60 { + format!("fast install (~{secs}s)") + } else { + let mins = secs.div_ceil(60); + format!("compiles native binaries (~{mins} min build)") + } + } else { + match candidate.backend { + Backend::PortageBinary | Backend::Flatpak | Backend::Snap | Backend::AppImage => { + "pre-built binary package".to_string() + } + Backend::PortageSource => "source compilation (build time unmeasured)".to_string(), + _ => "pre-built binary".to_string(), + } + }; + + format!( + "Install {application} from {source_name}. Recommended for {sandbox_desc} and {build_desc}." + ) +} + +// ----------------------------------------------------------------------------- +// PlanStore +// ----------------------------------------------------------------------------- + +pub struct PlanStore; + +impl PlanStore { + pub fn plan_dir() -> PathBuf { + if let Ok(dir) = std::env::var("PHOEBUS_PLANS_DIR") { + return PathBuf::from(dir); + } + 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) + } else { + Self::plan_dir().join(format!("{plan_id}.json")) + } + } + + 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))?; + } + 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))?; + Ok(path) + } + + pub fn load(plan_id: &str) -> Result { + let path = Self::plan_path(plan_id); + if !path.is_file() { + return Err(ExecError::operation( + "service", + "load plan", + format!("plan `{plan_id}` not found or expired"), + )); + } + 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()))?; + Ok(plan) + } + + pub fn mark_executed(plan_id: &str) -> Result<()> { + let mut plan = Self::load(plan_id)?; + plan.executed = true; + Self::save(&plan)?; + Ok(()) + } +} + +// ----------------------------------------------------------------------------- +// Planning APIs +// ----------------------------------------------------------------------------- + +/// Plan an installation using AI investigation and policy checks. +pub fn plan_install( + exec: &Exec, + root: &Path, + request: &InstallRequest, + session: &dyn phoebus_ai::install::InstallSession, + ai: Option<&AiInstall>, + facts: &SystemFacts, +) -> Result { + let ai = match ai { + Some(a) => a, + None => { + return Err(ExecError::operation( + "service", + "plan_install", + "No AI provider is configured. Specify a model or select deterministic legacy administration (--legacy --).", + )); + } + }; + + let resolved = install::resolve_with_ai(exec, root, request, session, ai, facts)?; + build_install_plan(resolved, PlanKind::Install) +} + +/// Plan an installation deterministically without contacting a model. +pub fn plan_legacy_install( + exec: &Exec, + root: &Path, + request: &InstallRequest, +) -> Result { + if request.backend.is_none() { + return Err(ExecError::operation( + "service", + "plan_legacy_install", + "Legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)", + )); + } + let resolved = install::resolve_explicit(exec, root, request)?; + build_install_plan(resolved, PlanKind::LegacyInstall) +} + +fn build_install_plan(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 rec = format_recommendation(&resolved.candidate, &resolved.request.application); + let source_display = match resolved.candidate.backend { + Backend::PortageBinary => "Gentoo binhost", + Backend::PortageSource => "Gentoo Portage", + Backend::PortageVendor => "Portage vendor", + Backend::Flatpak => "Flathub", + Backend::Snap => "Snap Store", + Backend::Nix => "Nixpkgs", + Backend::AppImage => "managed AppImage", + Backend::CustomEbuild => "Phoebus custom ebuild", + } + .to_string(); + + let digest = resolved.approval_digest(); + let actions = vec![resolved.action.clone()]; + let requires_root = resolved.action.is_mutating(); + + let plan = PreparedPlan { + id: plan_id, + created_unix: now, + expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, + kind, + summary: format!( + "install {} via {}", + resolved.request.application, + resolved.candidate.backend.as_str() + ), + recommendation: rec, + application: Some(resolved.request.application.clone()), + candidate: Some(resolved.candidate.clone()), + alternatives: resolved.alternatives.clone(), + rationale: resolved.rationale.clone(), + warnings: resolved.warnings.clone(), + actions, + effects: resolved.effects.clone(), + digest, + verification: resolved.verification.clone(), + requires_root, + source: source_display, + executed: false, + }; + + PlanStore::save(&plan)?; + Ok(plan) +} + +/// Plan an application removal across supported sources preserving user data by default. +pub fn plan_removal( + exec: &Exec, + root: &Path, + application: &str, + backend_filter: Option, +) -> Result { + let inspection = chooser::installed_copies(exec, root, application); + if inspection.copies.is_empty() { + return Err(ExecError::operation( + "service", + "plan_removal", + format!("`{application}` is not installed on this system"), + )); + } + + let target_copy = if let Some(b) = backend_filter { + inspection + .copies + .into_iter() + .find(|c| c.backend == b.as_str()) + .ok_or_else(|| { + ExecError::operation( + "service", + "plan_removal", + format!( + "`{application}` is not installed via {} (found in other lanes)", + b.as_str() + ), + ) + })? + } else if inspection.copies.len() > 1 { + let details = inspection + .copies + .iter() + .map(|c| format!("{} ({})", c.id, c.backend)) + .collect::>() + .join(", "); + return Err(ExecError::operation( + "service", + "plan_removal", + format!( + "`{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() + }; + + let action = match target_copy.backend.as_str() { + "flatpak" => SystemAction::FlatpakRemove { + app_id: target_copy.id.clone(), + }, + "snap" => SystemAction::SnapRemove { + name: target_copy.id.clone(), + }, + "appimage" => SystemAction::AppImageRemove { + name: target_copy.id.clone(), + // User data preserved by default + purge_data: false, + }, + _ => SystemAction::RemovePackage { + atom: target_copy.id.clone(), + }, + }; + + 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 actions_vec = vec![action.clone()]; + let digest = compute_plan_digest(&actions_vec, None, &effects); + + let plan = PreparedPlan { + id: plan_id, + created_unix: now, + expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, + kind: PlanKind::Removal, + summary: format!("remove {} ({})", target_copy.id, target_copy.backend), + recommendation: format!( + "Remove application {} from {}. Application binaries will be uninstalled while user data in the home directory is preserved.", + target_copy.id, target_copy.backend + ), + 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(), + actions: actions_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, + executed: false, + }; + + PlanStore::save(&plan)?; + Ok(plan) +} + +/// Plan general system administration tasks via connected model. +pub fn plan_general( + exec: &Exec, + root: &Path, + query: &str, + facts: &SystemFacts, + ai: &AiInstall, +) -> Result { + let assistant_plan: AssistantPlan = complete_plan( + ai.provider, + &ai.endpoint, + &ai.model, + facts, + query, + ai.transport, + ) + .map_err(|e| ExecError::operation("service", "complete_plan", e.to_string()))?; + + let mut combined_effects = ResolvedPlan { + established: true, + ..Default::default() + }; + let mut any_mutating = false; + + for act in &assistant_plan.actions { + let eff = actions::resolve_effects(exec, act, root).map_err(|e| { + ExecError::operation( + "service", + "resolve_effects", + format!("could not resolve effects for `{}`: {e}", act.describe()), + ) + })?; + if eff.established { + combined_effects.effects.extend(eff.effects); + combined_effects.consequences.extend(eff.consequences); + } + 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 digest = compute_plan_digest(&assistant_plan.actions, None, &combined_effects); + let rationale_strings: Vec = assistant_plan + .rationale + .into_iter() + .map(|r| format!("{}: {}", r.action, r.reason)) + .collect(); + + let plan = PreparedPlan { + id: plan_id, + created_unix: now, + expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, + kind: PlanKind::General, + summary: assistant_plan.summary.clone(), + recommendation: assistant_plan.summary, + application: None, + candidate: None, + alternatives: Vec::new(), + rationale: rationale_strings, + warnings: Vec::new(), + actions: assistant_plan.actions, + effects: combined_effects, + digest, + verification: "verify execution of planned actions".into(), + requires_root: any_mutating, + source: "AI Assistant".into(), + executed: false, + }; + + PlanStore::save(&plan)?; + Ok(plan) +} + +// ----------------------------------------------------------------------------- +// Execution API +// ----------------------------------------------------------------------------- + +struct ServiceConfirm { + assume_yes: bool, +} + +impl Confirmation for ServiceConfirm { + fn confirm_erase(&self, _preview: &str) -> Result { + Ok(self.assume_yes) + } + fn confirm_final(&self, _message: &str) -> Result { + Ok(self.assume_yes) + } +} + +/// Execute a prepared plan with full validation, elevation, verification, and transaction recording. +pub fn execute_plan( + exec: &Exec, + root: &Path, + plan_id: &str, + expected_digest: &str, + assume_yes: bool, +) -> Result { + let plan = PlanStore::load(plan_id)?; + + // 1. Replay check + if plan.executed { + return Err(ExecError::operation( + "service", + "execute_plan", + "plan has already been executed; replayed plans are rejected", + )); + } + + // 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", + )); + } + + // 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 a plan directly without further elevation checks (caller has verified privileges). +pub fn execute_plan_direct( + exec: &Exec, + root: &Path, + plan: PreparedPlan, + assume_yes: bool, +) -> Result { + let confirm = ServiceConfirm { assume_yes }; + let auth = if plan.requires_root { + Some(authorize(&confirm, &plan.summary, "execute")?) + } else { + None + }; + + let record = TransactionRecord { + id: 0, + created_unix: now_unix(), + origin: match plan.kind { + PlanKind::LegacyInstall => "sys-legacy".into(), + PlanKind::Removal => "sys-removal".into(), + _ => "assistant".into(), + }, + summary: plan.summary.clone(), + actions: vec![plan.summary.clone()], + result: "in progress".into(), + snapshot: None, + digest: Some(plan.digest.clone()), + outcomes: Vec::new(), + }; + 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)); + } + + let run = actions::execute_plan(exec, &approved_steps, auth.as_ref(), root); + if let Some((action_str, detail)) = &run.failure { + let _ = transaction::finish( + exec, + root, + tx_id, + format!("failed: {detail}"), + run.snapshot.clone(), + vec![TransactionOutcome::failed( + action_str.clone(), + detail.clone(), + )], + ); + return Err(ExecError::operation( + "service", + "execute", + format!("action failed: {action_str}: {detail}"), + )); + } + + // Post-execution verification + let verification_result = match plan.kind { + PlanKind::Install | PlanKind::LegacyInstall => { + if let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) { + 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(), + }; + install::verify_installed(exec, root, &resolved)? + } else { + "verified ok".into() + } + } + PlanKind::Removal => { + if let Some(app) = &plan.application { + let check = chooser::installed_copies(exec, root, app); + if let Some(ref_copy) = check.copies.iter().find(|c| c.backend == plan.source) { + let err = format!( + "removal reported success but `{app}` is still present in {} ({})", + ref_copy.backend, ref_copy.id + ); + let _ = transaction::finish( + exec, + root, + tx_id, + format!("verify failed: {err}"), + run.snapshot.clone(), + vec![TransactionOutcome::completed(plan.summary.clone())], + ); + return Err(ExecError::operation("service", "verify removal", err)); + } + format!("verified: `{app}` removed from {}", plan.source) + } else { + "removal verified ok".into() + } + } + _ => "ok".into(), + }; + + // Mark plan executed + let _ = PlanStore::mark_executed(&plan.id); + + // Finish transaction + transaction::finish( + exec, + root, + tx_id, + "ok", + run.snapshot.clone(), + vec![TransactionOutcome::completed(plan.summary.clone())], + )?; + + let outputs: Vec = run.completed.into_iter().map(|(_, out)| out).collect(); + + Ok(PlanExecutionOutcome { + completed: true, + snapshot: run.snapshot, + result: "ok".into(), + verification: verification_result, + output: outputs, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use phoebus_core::selection::Capability; + use phoebus_core::Redactor; + use phoebus_executor::command::RecordingRunner; + use phoebus_executor::Logger; + use tempfile::tempdir; + + fn make_test_exec(root: &Path) -> Exec { + let temp = tempdir().unwrap().keep(); + let logger = Logger::open(temp.join("test.log"), Redactor::new(), false); + Exec::new( + Box::new(RecordingRunner::new()), + logger, + false, + root.to_path_buf(), + temp, + ) + } + + fn sample_candidate() -> Candidate { + let mut cand = Candidate::new(Backend::Flatpak, "org.mozilla.firefox", "flathub"); + cand.version = Some("120.0".into()); + cand.verified = true; + cand.download_mib = Some(85); + cand.install_mib = Some(230); + cand.sandbox = SandboxLevel::Strong; + cand.wayland = Capability::Yes; + cand.desktop_integration = Capability::Yes; + cand.permissions = vec!["network".into()]; + cand + } + + #[test] + fn test_format_recommendation_honest() { + let cand = sample_candidate(); + let rec = format_recommendation(&cand, "firefox"); + assert!(rec.contains("Flathub")); + assert!(rec.contains("strong application isolation")); + assert!(rec.contains("pre-built binary")); + 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(), + created_unix: now_unix(), + expires_unix: now_unix() + 900, + kind: PlanKind::Install, + summary: "install firefox".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], + effects: ResolvedPlan::default(), + digest: "digest-exp".into(), + verification: "verify".into(), + requires_root: false, + source: "sys".into(), + executed: false, + }; + PlanStore::save(&expired_plan).unwrap(); + let err = execute_plan(&exec, root, "expired-plan", "digest-exp", true).unwrap_err(); + assert!(err.to_string().contains("expired")); + + // 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")); + + // 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")); + } +} diff --git a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs index 5b4a0b5..fed4412 100644 --- a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs +++ b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs @@ -373,7 +373,9 @@ fn the_help_lists_every_backend_flag() { #[test] fn choose_never_invents_a_candidate() { let root = tempfile::tempdir().expect("temp root"); + let empty = tempfile::tempdir().expect("empty PATH"); let out = sys() + .env("PATH", empty.path()) .arg("--root") .arg(root.path()) .args(["choose", "some-package", "--legacy"]) @@ -391,3 +393,78 @@ fn choose_never_invents_a_candidate() { ); } } + +#[test] +fn remove_without_installed_copy_fails_closed() { + let root = tempfile::tempdir().expect("temp root"); + let out = sys() + .arg("--root") + .arg(root.path()) + .args(["remove", "nonexistent-app", "--legacy"]) + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("is not installed") || stderr.contains("found"), + "stderr: {stderr}" + ); +} + +#[test] +fn remove_ambiguous_copies_requires_explicit_lane() { + let root = tempfile::tempdir().expect("temp root"); + // Create an AppImage record + let appimage_dir = root.path().join("var/lib/phoebus/appimages"); + std::fs::create_dir_all(&appimage_dir).unwrap(); + std::fs::write( + appimage_dir.join("shared-app.toml"), + "name = \"shared-app\"\nversion = \"1.0\"\nsha256 = \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"\nprovenance = \"https://example.com/app\"\narch = \"x86_64\"\nsize_bytes = 100\ninstalled_unix = 0\n", + ).unwrap(); + + // Create a Portage VDB entry + let portage_pkg_dir = root.path().join("var/db/pkg/app-misc/shared-app-1.0"); + std::fs::create_dir_all(&portage_pkg_dir).unwrap(); + std::fs::write(portage_pkg_dir.join("CONTENTS"), "").unwrap(); + + // Removal without source flag must fail indicating ambiguity + let out = sys() + .arg("--root") + .arg(root.path()) + .args(["remove", "shared-app", "--legacy"]) + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("multiple lanes") && stderr.contains("explicitly"), + "stderr must report ambiguity: {stderr}" + ); + + // Disambiguating with --appimage allows targeting specifically that copy + let disambiguated = sys() + .arg("--root") + .arg(root.path()) + .args(["remove", "shared-app", "--legacy", "--appimage"]) + .output() + .expect("run sys"); + let out_str = String::from_utf8_lossy(&disambiguated.stdout); + let err_str = String::from_utf8_lossy(&disambiguated.stderr); + assert!( + out_str.contains("Removal plan:") || err_str.contains("root"), + "stdout: {out_str}, stderr: {err_str}" + ); +} + +#[test] +fn broker_execute_plan_rejects_missing_file() { + let out = sys() + .args([ + "--broker", + "--execute-plan", + "/tmp/nonexistent-plan-id.json", + ]) + .output() + .expect("run sys"); + assert!(!out.status.success()); +} diff --git a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml index 4f396ac..ea0c03a 100644 --- a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml +++ b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml @@ -23,12 +23,12 @@ Singleton { const override = Quickshell.env("PHOEBUS_ASSISTANT_BRIDGE_CMD"); if (override && override.length > 0) return override.split(" ").filter(part => part.length > 0); - return ["/usr/bin/sudo", "-n", "/usr/local/bin/sys", "--assistant-bridge"]; + return ["/usr/local/bin/sys", "--assistant-bridge"]; } Timer { - interval: 400 - repeat: true + interval: 100 + repeat: false running: proc.running && root.handshake === null onTriggered: root.refreshHandshake(null) } @@ -92,8 +92,8 @@ Singleton { call("ask", { request: query, backend: backend }, cb); } - function execute(actions, digest, yes, cb) { - call("execute", { actions: actions, digest: digest, yes: yes }, cb); + function execute(planId, digest, yes, cb) { + call("execute", { plan_id: planId, digest: digest, yes: yes }, cb); } function legacyInstall(application, backend, cb) { diff --git a/installer/live/desktop/phoebus-assistant/shell.qml b/installer/live/desktop/phoebus-assistant/shell.qml index 7ee79a3..b4ee4e8 100644 --- a/installer/live/desktop/phoebus-assistant/shell.qml +++ b/installer/live/desktop/phoebus-assistant/shell.qml @@ -21,17 +21,18 @@ ShellRoot { refreshStatus(); } + onCurrentTabChanged: { + if (currentTab === "updates" && !shell.updateOverview && !shell.busy) { + checkUpdates(); + } + } + function refreshStatus() { AssistantBridge.getProactiveAlerts(reply => { if (reply.ok && reply.result) { shell.activeAlerts = reply.result.alerts || []; } }); - AssistantBridge.getUpdates(reply => { - if (reply.ok && reply.result) { - shell.updateOverview = reply.result; - } - }); AssistantBridge.getPreferences(reply => { if (reply.ok && reply.result) { shell.preferences = reply.result; @@ -39,6 +40,18 @@ ShellRoot { }); } + function checkUpdates() { + shell.busy = true; + shell.statusText = "Checking for updates across package sources..."; + AssistantBridge.getUpdates(reply => { + shell.busy = false; + shell.statusText = "Ready"; + if (reply.ok && reply.result) { + shell.updateOverview = reply.result; + } + }); + } + function addMessage(sender, text, data) { const item = { sender: sender, @@ -81,15 +94,16 @@ ShellRoot { function executePlan(planData) { shell.busy = true; shell.statusText = "Executing approved plan..."; - const actions = planData.action ? [planData.action] : (planData.actions ? planData.actions.map(a => a.action || a) : []); + const planId = planData.plan_id || planData.id; + const digest = planData.digest; - AssistantBridge.execute(actions, planData.digest, true, reply => { + AssistantBridge.execute(planId, digest, true, reply => { shell.busy = false; if (!reply.ok) { shell.statusText = "Execution failed"; addMessage("assistant", "Execution failed: " + reply.error, null); } else { - shell.statusText = "Installed successfully"; + shell.statusText = "Operation completed successfully"; addMessage("assistant", "Operation completed successfully.", { completed: true, application: planData.application, diff --git a/installer/tests/vm/sys-acceptance.sh b/installer/tests/vm/sys-acceptance.sh index bc53992..51afcb0 100755 --- a/installer/tests/vm/sys-acceptance.sh +++ b/installer/tests/vm/sys-acceptance.sh @@ -65,9 +65,8 @@ echo "sys-acceptance: SYS=$SYS MUTATE=$MUTATE" # --- Read-only deterministic and JSON paths ------------------------------- run_expect_zero identity --version run_expect_zero history-legacy history --legacy -if [[ "$(id -u)" -eq 0 ]]; then - run_expect_zero undo-legacy undo --legacy -else +run_expect_zero undo-status-legacy undo status --legacy +if [[ "$(id -u)" -ne 0 ]]; then run_expect_nonzero nonroot-undo "mutating actions require root" undo --legacy fi run_expect_zero appimage-empty --root / --legacy appimage list