feat(ai,desktop): unify administration layer, provision QML, and add conversation continuity
Some checks are pending
ci / test (push) Waiting to run
Some checks are pending
ci / test (push) Waiting to run
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).
This commit is contained in:
parent
f30b99d272
commit
7ebb616c99
17 changed files with 2302 additions and 544 deletions
|
|
@ -101,6 +101,8 @@ The only crate that runs privileged commands.
|
||||||
### phoebus-installer
|
### phoebus-installer
|
||||||
|
|
||||||
- `orchestrate` — `Installer` runs the plan stages and stops on first failure.
|
- `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.
|
- `assistant_bridge` — JSON-RPC stdio bridge serving the Quickshell desktop assistant.
|
||||||
- `release` — `ReleaseManifest` create/verify, candidate gates, atomic publish
|
- `release` — `ReleaseManifest` create/verify, candidate gates, atomic publish
|
||||||
and signing command helpers.
|
and signing command helpers.
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,34 @@
|
||||||
All notable changes are recorded here. The authoritative history is `git log`;
|
All notable changes are recorded here. The authoritative history is `git log`;
|
||||||
this file is the curated, human-readable summary.
|
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 <plan-path>` 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 <app> --legacy --<source>`).
|
||||||
|
- 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
|
## 2026-09-24 — AI-first administration experience across CLI and GUI, package correctness, and shared recovery
|
||||||
|
|
||||||
- **Unified AI-First Administration Contract (`sys` & `phoebus-assistant`):**
|
- **Unified AI-First Administration Contract (`sys` & `phoebus-assistant`):**
|
||||||
|
|
|
||||||
|
|
@ -3,53 +3,39 @@
|
||||||
Rolling note between work sessions. **Update this file before you finish**, then
|
Rolling note between work sessions. **Update this file before you finish**, then
|
||||||
commit it. It should be short and current; use `git log` for detail.
|
commit it. It should be short and current; use `git log` for detail.
|
||||||
|
|
||||||
- **Last updated:** this session (2026-09-24), AI-First Administration & Desktop Assistant:
|
- **Last updated:** this session (2026-09-24), AI-First Administration & Desktop Assistant Remediation:
|
||||||
Unified AI-first administration across the CLI (`sys`) and desktop GUI (`phoebus-assistant`),
|
Shared planning service layer (`phoebus_installer::service`), reviewable plan staging with
|
||||||
backed by package correctness guarantees, quiet proactive monitoring, user preferences,
|
cryptographic digests (`PreparedPlan`, `PlanStore`), target desktop QML and Polkit policy
|
||||||
and a 22-case verified VM acceptance suite.
|
provisioning, unprivileged GUI execution with Polkit elevation (`pkexec`), contextual conversation
|
||||||
|
continuity (`conversation::*`), and cross-source application removal with user data preservation.
|
||||||
- **Current focus:**
|
- **Current focus:**
|
||||||
1. **Unified AI-first administration contract**:
|
1. **Shared planning and execution layer (`phoebus_installer::service`)**:
|
||||||
- Natural language is the default interaction: `sys install <pkg>`, `sys please install <pkg>`,
|
- Both CLI (`sys`) and desktop GUI (`phoebus-assistant` via `assistant_bridge.rs`) share one unified
|
||||||
and `sys ask "<request>"` all enter the identical AI workflow.
|
administration pipeline for investigation, recommendation, effect resolution, authorization, execution, and verification.
|
||||||
- Source flags (`--flatpak`, `--portage`, `--nix`, `--snap`, `--appimage`, `--ebuild`)
|
- Reviewable plans staged as `PreparedPlan` with cryptographic digests (`Sha256`), 15-minute TTL, and replay rejection.
|
||||||
constrain AI candidate evaluation without bypassing the model.
|
- System state revalidation before mutation; material alterations invalidate previous approvals and abort.
|
||||||
- Deterministic administration explicitly selected via `--legacy`:
|
- Honest recommendation formatting with verified provenance (no false "avoids a lengthy build" claims).
|
||||||
`sys install <pkg> --legacy --<source>`, `sys history --legacy`, `sys undo --legacy`.
|
- In-progress transaction recording (`begin`) before mutation; completed verification (`finish`) after mutation.
|
||||||
`sys install <pkg> --legacy` without a source refuses execution and displays available sources.
|
2. **Target desktop & QML asset provisioning**:
|
||||||
- Audited entry points: `--action` and `--action-file` fail closed unless invoked with
|
- `gui-apps/quickshell` added to canonical Mango desktop package list.
|
||||||
`--legacy` (for deterministic administration) or `--broker` (for internal UI/bridge calls).
|
- Embedded all 13 QML and policy assets into `/usr/share/phoebus/assistant/` via `TargetRoot` in `write_session_script`.
|
||||||
- Missing or failed model: halts AI execution cleanly and provides actionable `--legacy`
|
- Polkit policy (`club.phoebus.sys.policy`) enables desktop users to elevate mutating plans via `pkexec` without passwordless sudo.
|
||||||
alternatives without silently mutating the system or falling back across sources.
|
3. **Desktop assistant responsiveness**:
|
||||||
2. **Package correctness and safety guarantees**:
|
- Eliminated startup polling freeze; update checks are on-demand when switching to the Updates tab.
|
||||||
- Nix attribute evaluation probe (`nix-instantiate`) verifies attribute existence in nixpkgs.
|
- Fast deterministic status checking on startup (reboot-required marker).
|
||||||
- Portage binary binhost check (`emerge -p --usepkgonly`) verifies binary availability;
|
4. **Contextual conversation continuity (`phoebus_installer::conversation`)**:
|
||||||
aborts if an action changes to source compilation (`EffectSource::Source`), invalidating
|
- Bounded 10-turn history with secret redaction.
|
||||||
prior approval.
|
- Follow-up resolution for comparative questions, backend switching, and plan confirmations.
|
||||||
- Cross-source installed application ownership tracking detects duplicates and targets the
|
5. **Cross-source removal**:
|
||||||
correct installation during update or removal.
|
- Unified removal planning (`plan_removal`) across Flatpak, Snap, AppImage, and Portage.
|
||||||
- User data preserved by default on application removal.
|
- Requires explicit lane flag if ambiguous duplicate copies exist; preserves user home data by default.
|
||||||
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).
|
|
||||||
- **Last verified (this session):**
|
- **Last verified (this session):**
|
||||||
- `cargo fmt --all -- --check` clean.
|
- `cargo fmt --all -- --check` clean.
|
||||||
- `cargo clippy --workspace --all-targets` clean (0 warnings).
|
- `cargo clippy --workspace --all-targets` clean (0 errors, 0 custom warnings).
|
||||||
- `cargo test --workspace` (all 481 crate unit/integration tests pass: 173 phoebus-core, 205 phoebus-executor, 103 phoebus-installer).
|
- `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.
|
- `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:**
|
- **Not yet verified this session:**
|
||||||
- AI-selected live installation against a remote production provider with live credentials
|
- AI-selected live installation against a remote production provider with live credentials
|
||||||
(fixture and mock paths fully verified).
|
(fixture and mock paths fully verified).
|
||||||
|
|
|
||||||
|
|
@ -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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| — | 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 |
|
| — | 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) |
|
| — | 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/` |
|
| — | Git workflow + agent guide | Done | this `docs/` set, `.githooks/`, `scripts/` |
|
||||||
|
|
||||||
## Immediate next steps
|
## Immediate next steps
|
||||||
|
|
|
||||||
|
|
@ -140,10 +140,15 @@ still not VM-verified.
|
||||||
| Audited action execution (`--legacy`/`--broker` enforcement) | yes | yes | yes (acceptance matrix) | n/a |
|
| Audited action execution (`--legacy`/`--broker` enforcement) | yes | yes | yes (acceptance matrix) | n/a |
|
||||||
| Nix attribute verification probe | yes | yes | no | n/a |
|
| Nix attribute verification probe | yes | yes | no | n/a |
|
||||||
| Portage binary binhost verification + compile abort guard | 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 |
|
| Unified multi-source update management | yes | yes | no | no |
|
||||||
| Quiet proactive assistance monitor & deduplicated alerting | 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 |
|
| 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 |
|
| UKI | no (deferred) | no | no | no |
|
||||||
|
|
||||||
## Known limitations
|
## Known limitations
|
||||||
|
|
|
||||||
47
docs/SYS.md
47
docs/SYS.md
|
|
@ -262,26 +262,27 @@ with no network and no model.
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| 1 | Identity | `sys --version` | prints the version, exit 0 |
|
| 1 | Identity | `sys --version` | prints the version, exit 0 |
|
||||||
| 2 | Read-only history (legacy) | `sys history --legacy` | state, exit 0, no mutation |
|
| 2 | Read-only history (legacy) | `sys history --legacy` | state, exit 0, no mutation |
|
||||||
| 3 | Undo (legacy) | `sys undo --legacy` | requires root or executes cleanly |
|
| 3 | Undo status (legacy) | `sys undo status --legacy` | idle rollback state, exit 0 |
|
||||||
| 4 | AppImage inventory (empty) | `sys --legacy appimage list` | "no managed AppImages", exit 0 |
|
| 4 | Non-root undo | `sys undo --legacy` (non-root) | requires root, exit nonzero |
|
||||||
| 5 | Ebuild inventory (empty) | `sys --legacy ebuilds` | "no custom ebuilds", exit 0 |
|
| 5 | AppImage inventory (empty) | `sys --legacy appimage list` | "no managed AppImages", exit 0 |
|
||||||
| 6 | Invalid natural operand | `sys --legacy -- install --color=n` | rejected, nonzero |
|
| 6 | Ebuild inventory (empty) | `sys --legacy ebuilds` | "no custom ebuilds", exit 0 |
|
||||||
| 7 | Unknown phrase | `sys --legacy frobnicate` | rejected, nonzero, examples shown |
|
| 7 | Invalid natural operand | `sys --legacy -- install --color=n` | rejected, nonzero |
|
||||||
| 8 | Audited action without legacy/broker | `sys --action '{"action":"history"}'` | fail closed, requires `--legacy` or `--broker` |
|
| 8 | Unknown phrase | `sys --legacy frobnicate` | rejected, nonzero, examples shown |
|
||||||
| 9 | Legacy install without source | `sys install firefox --legacy` | refused: requires explicit source flag |
|
| 9 | Audited action without legacy/broker | `sys --action '{"action":"history"}'` | fail closed, requires `--legacy` or `--broker` |
|
||||||
| 10 | JSON unknown action | `--legacy --action '{"action":"run_shell"}'` | fail closed, nonzero |
|
| 10 | Legacy install without source | `sys install firefox --legacy` | refused: requires explicit source flag |
|
||||||
| 11 | JSON unknown field | `--legacy --action '{"action":"history","x":1}'` | fail closed, nonzero |
|
| 11 | JSON unknown action | `--legacy --action '{"action":"run_shell"}'` | fail closed, nonzero |
|
||||||
| 12 | Option-like operand (JSON) | `install_package atom="-C"` | rejected before any command |
|
| 12 | JSON unknown field | `--legacy --action '{"action":"history","x":1}'` | fail closed, nonzero |
|
||||||
| 13 | Invalid Snap name | `snap_install name="Bad Name"` | rejected, nonzero |
|
| 13 | Option-like operand (JSON) | `install_package atom="-C"` | rejected before any command |
|
||||||
| 14 | Invalid AppImage hash | `appimage_acquire sha256="00"` | rejected, nonzero |
|
| 14 | Invalid Snap name | `snap_install name="Bad Name"` | rejected, nonzero |
|
||||||
| 15 | Ebuild path traversal | `custom_ebuild_prepare atom="../../x"` | rejected, nonzero |
|
| 15 | Invalid AppImage hash | `appimage_acquire sha256="00"` | rejected, nonzero |
|
||||||
| 16 | Mutating as non-root | `set_package_preference` | refused: needs root |
|
| 16 | Ebuild path traversal | `custom_ebuild_prepare atom="../../x"` | rejected, nonzero |
|
||||||
| 17 | Offline `sys ask` | `sys ask "<request>"` with no provider | deterministic fallback, nonzero |
|
| 17 | Mutating as non-root | `set_package_preference` | refused: needs root |
|
||||||
| 18 | Choose with no lane | `sys --root / choose unused-xyz --legacy` | selection or clear failure, never invented |
|
| 18 | Offline `sys ask` | `sys ask "<request>"` with no provider | deterministic fallback, nonzero |
|
||||||
| 19 | Conflicting backend flags | `sys install x --flatpak --nix` | rejected by CLI |
|
| 19 | Choose with no lane | `sys --root / choose unused-xyz --legacy` | selection or clear failure, never invented |
|
||||||
| 20 | Source flag without install | `sys --flatpak history --legacy` | rejected by CLI |
|
| 20 | Conflicting backend flags | `sys install x --flatpak --nix` | rejected by CLI |
|
||||||
| 21 | Unqualified with no model | `sys install firefox` (no provider) | deterministic offer printed, nothing installed |
|
| 21 | Source flag without install | `sys --flatpak history --legacy` | rejected by CLI |
|
||||||
| 22 | Read-only investigation | `--legacy --action '{"action":"check_backend",...}'` | structured JSON evidence returned |
|
| 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)
|
### 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-remove`: `sys -y remove app-misc/hello --legacy` uninstalls cleanly.
|
||||||
- `mutate-history`: `sys history --legacy` confirms both install and remove are logged.
|
- `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
|
All 23 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
|
(`installer/tests/vm/sys-acceptance.sh` reports `PASS=23 FAIL=0`). Host unit and
|
||||||
integration tests in `crates/phoebus-installer/tests/sys_cli.rs`,
|
integration tests in `crates/phoebus-installer/tests/sys_cli.rs`,
|
||||||
`crates/phoebus-core/`, and `crates/phoebus-executor/` cover proposal validation,
|
`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
|
## Security properties
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,7 @@ pub fn mango_desktop_packages() -> Vec<&'static str> {
|
||||||
"gui-wm/mangowm",
|
"gui-wm/mangowm",
|
||||||
"gui-apps/dankmaterialshell",
|
"gui-apps/dankmaterialshell",
|
||||||
"gui-apps/danksearch",
|
"gui-apps/danksearch",
|
||||||
|
"gui-apps/quickshell",
|
||||||
"dev-vcs/git",
|
"dev-vcs/git",
|
||||||
"sys-apps/accountsservice",
|
"sys-apps/accountsservice",
|
||||||
"sys-power/upower",
|
"sys-power/upower",
|
||||||
|
|
@ -899,6 +900,91 @@ Categories=System;Settings;
|
||||||
Keywords=system;admin;assistant;ai;sys;install;update;
|
Keywords=system;admin;assistant;ai;sys;install;update;
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
|
pub const PHOEBUS_POLKIT_POLICY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE policyconfig PUBLIC
|
||||||
|
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
|
||||||
|
"http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
|
||||||
|
<policyconfig>
|
||||||
|
<vendor>Phoebus OS</vendor>
|
||||||
|
<vendor_url>https://phoebus.club</vendor_url>
|
||||||
|
<icon_name>system-help</icon_name>
|
||||||
|
<action id="club.phoebus.sys.exec">
|
||||||
|
<description>Execute Phoebus system administration plan</description>
|
||||||
|
<message>Authentication is required to apply the system administration plan</message>
|
||||||
|
<defaults>
|
||||||
|
<allow_any>auth_admin</allow_any>
|
||||||
|
<allow_inactive>auth_admin</allow_inactive>
|
||||||
|
<allow_active>auth_admin_keep</allow_active>
|
||||||
|
</defaults>
|
||||||
|
<annotate key="org.freedesktop.policykit.exec.path">/usr/local/bin/sys</annotate>
|
||||||
|
<annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate>
|
||||||
|
</action>
|
||||||
|
</policyconfig>
|
||||||
|
"#;
|
||||||
|
|
||||||
|
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`.
|
/// A Wayland session entry for `/usr/share/wayland-sessions`.
|
||||||
pub fn wayland_session_entry(profile: DesktopProfile) -> Option<(&'static str, String)> {
|
pub fn wayland_session_entry(profile: DesktopProfile) -> Option<(&'static str, String)> {
|
||||||
match profile {
|
match profile {
|
||||||
|
|
|
||||||
|
|
@ -69,6 +69,11 @@ pub fn write_session_script(exec: &Exec, config: &InstallConfig) -> Result<()> {
|
||||||
sysgen::PHOEBUS_ASSISTANT_DESKTOP_ENTRY,
|
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
|
// The "Install Phoebus OS" entry point and welcome launcher are live-medium
|
||||||
// only: an installed system has no business offering to reinstall itself.
|
// only: an installed system has no business offering to reinstall itself.
|
||||||
// They are installed by the live build, not here.
|
// They are installed by the live build, not here.
|
||||||
|
|
@ -344,4 +349,35 @@ mod tests {
|
||||||
configure_login(&exec, &cfg).unwrap();
|
configure_login(&exec, &cfg).unwrap();
|
||||||
assert!(!exec.root.join("etc/greetd/config.toml").exists());
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,27 +2,28 @@
|
||||||
//!
|
//!
|
||||||
//! Exposes the exact same AI investigation, deterministic resolution,
|
//! Exposes the exact same AI investigation, deterministic resolution,
|
||||||
//! policy checks, authorization boundary, and transaction recording to the
|
//! 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::io::{BufRead, Write};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use phoebus_ai::assistant::complete_plan;
|
use phoebus_ai::install::{Evidence, InstallSession};
|
||||||
use phoebus_ai::provider::{ProviderKind, SystemFacts};
|
use phoebus_ai::provider::{ProviderKind, SystemFacts};
|
||||||
use phoebus_core::action::{parse_natural, SystemAction};
|
use phoebus_core::action::{parse_natural, SystemAction};
|
||||||
use phoebus_core::selection::Backend;
|
use phoebus_core::selection::Backend;
|
||||||
use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
|
|
||||||
use phoebus_core::{AiBackend, InstallConfig, Preferences};
|
use phoebus_core::{AiBackend, InstallConfig, Preferences};
|
||||||
use phoebus_executor::ai::CurlTransport;
|
use phoebus_executor::ai::CurlTransport;
|
||||||
use phoebus_executor::auth::{authorize, Confirmation};
|
|
||||||
use phoebus_executor::chooser;
|
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::opencode_client::ExecOpenCodeTransport;
|
||||||
use phoebus_executor::proactive;
|
use phoebus_executor::proactive;
|
||||||
use phoebus_executor::probe;
|
use phoebus_executor::probe;
|
||||||
use phoebus_executor::transaction;
|
use phoebus_executor::transaction;
|
||||||
use phoebus_executor::update::check_unified_updates;
|
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::{Deserialize, Serialize};
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
|
|
@ -43,6 +44,8 @@ pub struct BridgeRequest {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub phrase: Option<String>,
|
pub phrase: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub plan_id: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
pub action: Option<Value>,
|
pub action: Option<Value>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub actions: Option<Vec<Value>>,
|
pub actions: Option<Vec<Value>>,
|
||||||
|
|
@ -90,19 +93,6 @@ impl BridgeResponse {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct BridgeConfirm {
|
|
||||||
assume_yes: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Confirmation for BridgeConfirm {
|
|
||||||
fn confirm_erase(&self, _preview: &str) -> ExecResult<bool> {
|
|
||||||
Ok(self.assume_yes)
|
|
||||||
}
|
|
||||||
fn confirm_final(&self, _message: &str) -> ExecResult<bool> {
|
|
||||||
Ok(self.assume_yes)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn now_unix() -> u64 {
|
fn now_unix() -> u64 {
|
||||||
std::time::SystemTime::now()
|
std::time::SystemTime::now()
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
|
@ -145,6 +135,33 @@ fn gather_facts(exec: &Exec, root: &Path) -> SystemFacts {
|
||||||
facts
|
facts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct BridgeSession<'a> {
|
||||||
|
exec: &'a Exec,
|
||||||
|
root: &'a Path,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InstallSession for BridgeSession<'_> {
|
||||||
|
fn investigate(&self, requests: &[SystemAction]) -> Vec<Evidence> {
|
||||||
|
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<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeResponse {
|
pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeResponse {
|
||||||
let id = req.id;
|
let id = req.id;
|
||||||
match req.op.as_str() {
|
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 ai_conf = load_installed_ai_config(root);
|
||||||
let prefs = chooser::load_preferences(root);
|
let prefs = chooser::load_preferences(root);
|
||||||
let (alerts, _) = proactive::active_alerts(exec, 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(
|
BridgeResponse::ok(
|
||||||
id,
|
id,
|
||||||
json!({
|
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"),
|
"ai_backend": ai_conf.as_ref().map(|c| c.backend.as_str()).unwrap_or("direct"),
|
||||||
"preferences": prefs,
|
"preferences": prefs,
|
||||||
"active_alerts_count": alerts.len(),
|
"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);
|
let mut install_req = InstallRequest::new(&app);
|
||||||
install_req.backend = Some(backend_enum);
|
install_req.backend = Some(backend_enum);
|
||||||
match install::resolve_explicit(exec, root, &install_req) {
|
match service::plan_legacy_install(exec, root, &install_req) {
|
||||||
Ok(resolved) => BridgeResponse::ok(
|
Ok(plan) => BridgeResponse::ok(
|
||||||
id,
|
id,
|
||||||
json!({
|
json!({
|
||||||
"kind": "install",
|
"kind": "install",
|
||||||
"application": resolved.request.application,
|
"plan_id": plan.id,
|
||||||
"backend": resolved.candidate.backend.as_str(),
|
"application": plan.application,
|
||||||
"source": resolved.source.as_str(),
|
"backend": plan.candidate.as_ref().map(|c| c.backend.as_str()),
|
||||||
"recommendation": format!("Install {} from {}.", resolved.request.application, resolved.source.as_str()),
|
"source": plan.source,
|
||||||
"action": resolved.action,
|
"recommendation": plan.recommendation,
|
||||||
"digest": resolved.approval_digest(),
|
"action": plan.actions.first(),
|
||||||
"effects": resolved.effects.effects,
|
"digest": plan.digest,
|
||||||
"requires_root": resolved.action.is_mutating(),
|
"effects": plan.effects.effects,
|
||||||
|
"requires_root": plan.requires_root,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
Err(e) => BridgeResponse::err(id, e.to_string()),
|
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");
|
return BridgeResponse::err(id, "empty request");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if it's an install request
|
let conv_path = conversation::history_path();
|
||||||
let constrained_backend = req.backend.as_deref().and_then(Backend::parse);
|
let history = conversation::load_history(&conv_path);
|
||||||
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
|
|
||||||
);
|
|
||||||
|
|
||||||
|
// 1. Contextual follow-up check
|
||||||
|
if let Some(followup) = conversation::resolve_followup(&query, &history) {
|
||||||
|
match followup {
|
||||||
|
FollowupResolution::Comparison {
|
||||||
|
application,
|
||||||
|
explanation,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
return BridgeResponse::ok(
|
return BridgeResponse::ok(
|
||||||
id,
|
id,
|
||||||
json!({
|
json!({
|
||||||
"kind": "install",
|
"kind": "info",
|
||||||
"application": resolved.request.application,
|
"application": application,
|
||||||
"backend": resolved.candidate.backend.as_str(),
|
"summary": explanation.clone(),
|
||||||
"source": resolved.source.as_str(),
|
"recommendation": explanation,
|
||||||
"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(),
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
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,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// General natural language request via connected model
|
// 2. Install request
|
||||||
|
let constrained_backend = req.backend.as_deref().and_then(Backend::parse);
|
||||||
|
if let Some(app) = parse_install_phrase(&query) {
|
||||||
|
return plan_and_respond_install(
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
id,
|
||||||
|
&app,
|
||||||
|
constrained_backend,
|
||||||
|
&query,
|
||||||
|
&conv_path,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 facts = gather_facts(exec, root);
|
||||||
let conf = load_installed_ai_config(root);
|
let conf = load_installed_ai_config(root);
|
||||||
let ai_backend = conf
|
let ai_backend = conf
|
||||||
|
|
@ -353,7 +412,10 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
|
||||||
.map(|c| c.backend)
|
.map(|c| c.backend)
|
||||||
.unwrap_or(AiBackend::Direct);
|
.unwrap_or(AiBackend::Direct);
|
||||||
|
|
||||||
let plan = match ai_backend {
|
let (provider, endpoint, model);
|
||||||
|
let transport: Box<dyn phoebus_ai::provider::ModelTransport>;
|
||||||
|
|
||||||
|
match ai_backend {
|
||||||
AiBackend::OpenCode => {
|
AiBackend::OpenCode => {
|
||||||
let server = conf
|
let server = conf
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
|
@ -363,174 +425,240 @@ pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeRes
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|c| c.opencode_provider.clone())
|
.map(|c| c.opencode_provider.clone())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let model = conf
|
let op_model = conf
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|c| c.opencode_model.clone())
|
.map(|c| c.opencode_model.clone())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
if server.is_empty() || model.is_empty() {
|
if server.is_empty() || op_model.is_empty() {
|
||||||
return BridgeResponse::err(
|
return BridgeResponse::err(
|
||||||
id,
|
id,
|
||||||
"OpenCode is not configured. Configure model or use legacy mode.",
|
"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,
|
exec,
|
||||||
server.clone(),
|
server,
|
||||||
op_provider,
|
op_provider,
|
||||||
model.clone(),
|
op_model,
|
||||||
);
|
));
|
||||||
match complete_plan(
|
|
||||||
ProviderKind::Local,
|
|
||||||
&server,
|
|
||||||
&model,
|
|
||||||
&facts,
|
|
||||||
&query,
|
|
||||||
&transport,
|
|
||||||
) {
|
|
||||||
Ok(p) => p,
|
|
||||||
Err(e) => {
|
|
||||||
return BridgeResponse::err(id, format!("OpenCode plan failed: {e}"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
AiBackend::Direct => {
|
AiBackend::Direct => {
|
||||||
let provider = conf
|
let p = conf
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|c| ProviderKind::parse(&c.provider))
|
.and_then(|c| ProviderKind::parse(&c.provider))
|
||||||
.unwrap_or(ProviderKind::None);
|
.unwrap_or(ProviderKind::None);
|
||||||
if provider == ProviderKind::None {
|
if p == ProviderKind::None {
|
||||||
return BridgeResponse::err(id, "No AI model is connected. Use legacy mode for deterministic administration.");
|
return BridgeResponse::err(
|
||||||
|
id,
|
||||||
|
"No AI model is connected. Use legacy mode for deterministic administration.",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let endpoint = conf
|
endpoint = conf
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|c| c.endpoint.clone())
|
.map(|c| c.endpoint.clone())
|
||||||
.filter(|s| !s.trim().is_empty())
|
.filter(|s| !s.trim().is_empty())
|
||||||
.unwrap_or_else(|| provider.endpoint().to_string());
|
.unwrap_or_else(|| p.endpoint().to_string());
|
||||||
let model = conf.as_ref().map(|c| c.model.clone()).unwrap_or_default();
|
model = conf.as_ref().map(|c| c.model.clone()).unwrap_or_default();
|
||||||
let transport = CurlTransport::new(exec, None);
|
provider = p;
|
||||||
match complete_plan(
|
let direct = CurlTransport::new(exec, None);
|
||||||
|
transport = Box::new(direct.sandboxed());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let ai = AiInstall {
|
||||||
provider,
|
provider,
|
||||||
&endpoint,
|
endpoint,
|
||||||
&model,
|
model,
|
||||||
&facts,
|
transport: transport.as_ref(),
|
||||||
&query,
|
limits: phoebus_ai::install::Limits::default(),
|
||||||
&transport.sandboxed(),
|
|
||||||
) {
|
|
||||||
Ok(p) => p,
|
|
||||||
Err(e) => {
|
|
||||||
return BridgeResponse::err(id, format!("AI investigation failed: {e}"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Resolve effects
|
match service::plan_general(exec, root, &query, &facts, &ai) {
|
||||||
let mut resolved_actions = Vec::new();
|
Ok(plan) => {
|
||||||
let mut any_mutating = false;
|
conversation::save_turn(
|
||||||
for act in &plan.actions {
|
&conv_path,
|
||||||
let eff = actions::resolve_effects(exec, act, root).ok();
|
ConversationTurn {
|
||||||
any_mutating |= act.is_mutating();
|
timestamp_unix: now_unix(),
|
||||||
resolved_actions.push(json!({
|
query,
|
||||||
"action": act,
|
response_kind: "plan".into(),
|
||||||
"effects": eff.map(|e| e.effects).unwrap_or_default(),
|
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(
|
BridgeResponse::ok(
|
||||||
id,
|
id,
|
||||||
json!({
|
json!({
|
||||||
"kind": "plan",
|
"kind": "plan",
|
||||||
|
"plan_id": plan.id,
|
||||||
"summary": plan.summary,
|
"summary": plan.summary,
|
||||||
"actions": resolved_actions,
|
"actions": plan.actions,
|
||||||
"requires_root": any_mutating,
|
"digest": plan.digest,
|
||||||
|
"effects": plan.effects.effects,
|
||||||
|
"requires_root": plan.requires_root,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
Err(e) => BridgeResponse::err(id, e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
"execute" => {
|
"execute" => {
|
||||||
let actions_val = match req.actions {
|
let plan_id = match req.plan_id.as_deref() {
|
||||||
Some(a) => a,
|
Some(p) => p,
|
||||||
None => return BridgeResponse::err(id, "missing actions array"),
|
None => return BridgeResponse::err(id, "missing plan_id parameter"),
|
||||||
};
|
};
|
||||||
let mut parsed_actions = Vec::new();
|
let digest = match req.digest.as_deref() {
|
||||||
let mut any_mutating = false;
|
Some(d) => d,
|
||||||
for val in actions_val {
|
None => return BridgeResponse::err(id, "missing digest parameter"),
|
||||||
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();
|
match service::execute_plan(exec, root, plan_id, digest, req.yes.unwrap_or(false)) {
|
||||||
for act in &parsed_actions {
|
Ok(outcome) => BridgeResponse::ok(
|
||||||
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<String> = 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,
|
id,
|
||||||
json!({
|
json!({
|
||||||
"completed": true,
|
"completed": outcome.completed,
|
||||||
"snapshot": run.snapshot,
|
"snapshot": outcome.snapshot,
|
||||||
"result": result_str,
|
"result": outcome.result,
|
||||||
|
"verification": outcome.verification,
|
||||||
}),
|
}),
|
||||||
)
|
),
|
||||||
|
Err(e) => BridgeResponse::err(id, e.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
unknown => BridgeResponse::err(id, format!("unknown bridge op: {unknown}")),
|
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<Backend>,
|
||||||
|
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<dyn phoebus_ai::provider::ModelTransport>;
|
||||||
|
|
||||||
|
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 <app> --legacy --<source>).",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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": "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,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Err(e) => BridgeResponse::err(id, e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn execute_action_helper(
|
fn execute_action_helper(
|
||||||
exec: &Exec,
|
exec: &Exec,
|
||||||
root: &Path,
|
root: &Path,
|
||||||
|
|
@ -538,50 +666,48 @@ fn execute_action_helper(
|
||||||
action: SystemAction,
|
action: SystemAction,
|
||||||
assume_yes: bool,
|
assume_yes: bool,
|
||||||
) -> BridgeResponse {
|
) -> BridgeResponse {
|
||||||
let approved = match actions::resolve_effects(exec, &action, root) {
|
let effects = match actions::resolve_effects(exec, &action, root) {
|
||||||
Ok(plan) => Some(plan),
|
Ok(plan) => plan,
|
||||||
Err(e) => return BridgeResponse::err(id, format!("could not resolve effects: {e}")),
|
Err(e) => return BridgeResponse::err(id, format!("could not resolve effects: {e}")),
|
||||||
};
|
};
|
||||||
|
|
||||||
let confirm = BridgeConfirm { assume_yes };
|
let now = now_unix();
|
||||||
let auth = if action.is_mutating() {
|
let actions_vec = vec![action.clone()];
|
||||||
match authorize(&confirm, &actions::preview(&action), "execute") {
|
let digest = service::compute_plan_digest(&actions_vec, None, &effects);
|
||||||
Ok(a) => Some(a),
|
let plan = PreparedPlan {
|
||||||
Err(e) => return BridgeResponse::err(id, format!("authorization denied: {e}")),
|
id: format!("plan-act-{now}"),
|
||||||
}
|
created_unix: now,
|
||||||
} else {
|
expires_unix: now + service::DEFAULT_PLAN_TTL_SECONDS,
|
||||||
None
|
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,
|
||||||
};
|
};
|
||||||
|
if let Err(e) = service::PlanStore::save(&plan) {
|
||||||
let outcome =
|
return BridgeResponse::err(id, format!("could not stage plan: {e}"));
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
BridgeResponse::ok(
|
match service::execute_plan(exec, root, &plan.id, &digest, assume_yes) {
|
||||||
|
Ok(outcome) => BridgeResponse::ok(
|
||||||
id,
|
id,
|
||||||
json!({
|
json!({
|
||||||
"output": outcome.output,
|
"output": outcome.result,
|
||||||
"snapshot": outcome.snapshot,
|
"snapshot": outcome.snapshot,
|
||||||
}),
|
}),
|
||||||
)
|
),
|
||||||
|
Err(e) => BridgeResponse::err(id, e.to_string()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_install_phrase(text: &str) -> Option<String> {
|
fn parse_install_phrase(text: &str) -> Option<String> {
|
||||||
|
|
@ -604,6 +730,26 @@ fn parse_install_phrase(text: &str) -> Option<String> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn parse_removal_phrase(text: &str) -> Option<String> {
|
||||||
|
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.
|
/// Run line-delimited JSON-RPC loop on stdio.
|
||||||
pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
let stdin = std::io::stdin();
|
let stdin = std::io::stdin();
|
||||||
|
|
@ -665,6 +811,7 @@ mod tests {
|
||||||
application: None,
|
application: None,
|
||||||
backend: None,
|
backend: None,
|
||||||
phrase: None,
|
phrase: None,
|
||||||
|
plan_id: None,
|
||||||
action: None,
|
action: None,
|
||||||
actions: None,
|
actions: None,
|
||||||
digest: None,
|
digest: None,
|
||||||
|
|
@ -689,6 +836,7 @@ mod tests {
|
||||||
application: None,
|
application: None,
|
||||||
backend: None,
|
backend: None,
|
||||||
phrase: None,
|
phrase: None,
|
||||||
|
plan_id: None,
|
||||||
action: None,
|
action: None,
|
||||||
actions: None,
|
actions: None,
|
||||||
digest: None,
|
digest: None,
|
||||||
|
|
@ -715,4 +863,18 @@ mod tests {
|
||||||
assert_eq!(parse_install_phrase("add vlc"), Some("vlc".into()));
|
assert_eq!(parse_install_phrase("add vlc"), Some("vlc".into()));
|
||||||
assert_eq!(parse_install_phrase("why is audio broken"), None);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,18 +11,19 @@ use std::path::{Path, PathBuf};
|
||||||
use std::process::ExitCode;
|
use std::process::ExitCode;
|
||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use phoebus_ai::assistant::{complete_plan, AssistantPlan};
|
|
||||||
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
||||||
use phoebus_core::action::{parse_action, parse_natural, SystemAction};
|
use phoebus_core::action::{parse_action, parse_natural, SystemAction};
|
||||||
use phoebus_core::selection::Backend;
|
use phoebus_core::selection::Backend;
|
||||||
use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
|
use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
|
||||||
use phoebus_core::{AiBackend, InstallConfig, Redactor};
|
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::opencode_client::ExecOpenCodeTransport;
|
||||||
use phoebus_executor::{
|
use phoebus_executor::{
|
||||||
actions, authorize, chooser, probe, transaction, AutoConfirm, Confirmation,
|
actions, authorize, chooser, probe, transaction, AutoConfirm, Confirmation,
|
||||||
DestructiveAuthorization, Exec, Logger, RealRunner, Result,
|
DestructiveAuthorization, Exec, Logger, RealRunner, Result,
|
||||||
};
|
};
|
||||||
|
use phoebus_installer::conversation::{self, ConversationTurn, FollowupResolution};
|
||||||
|
use phoebus_installer::service::{self, PreparedPlan};
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(
|
#[command(
|
||||||
|
|
@ -57,6 +58,10 @@ struct Cli {
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
action_file: Option<PathBuf>,
|
action_file: Option<PathBuf>,
|
||||||
|
|
||||||
|
/// Execute a prepared plan file directly (internal broker invocation).
|
||||||
|
#[arg(long, value_name = "PATH")]
|
||||||
|
execute_plan: Option<PathBuf>,
|
||||||
|
|
||||||
/// Auto-approve (unattended); still requires root.
|
/// Auto-approve (unattended); still requires root.
|
||||||
#[arg(long, short = 'y')]
|
#[arg(long, short = 'y')]
|
||||||
yes: bool,
|
yes: bool,
|
||||||
|
|
@ -218,7 +223,21 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
return phoebus_installer::assistant_bridge::run_stdio(&exec, &cli.root);
|
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.action.is_some() || cli.action_file.is_some() {
|
||||||
if !cli.legacy && !cli.broker {
|
if !cli.legacy && !cli.broker {
|
||||||
return Err(
|
return Err(
|
||||||
|
|
@ -241,14 +260,14 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
let backend = backend_flag(&cli);
|
let backend = backend_flag(&cli);
|
||||||
let full_phrase = cli.text.join(" ");
|
let full_phrase = cli.text.join(" ");
|
||||||
|
|
||||||
// 3. Explicit legacy mode (--legacy)
|
// 4. Explicit legacy mode (--legacy)
|
||||||
if cli.legacy {
|
if cli.legacy {
|
||||||
if let Some(application) = parse_install_text(&full_phrase) {
|
if let Some(application) = parse_install_text(&full_phrase) {
|
||||||
if let Some(b) = backend {
|
if let Some(b) = backend {
|
||||||
let mut request = InstallRequest::new(&application);
|
let mut request = InstallRequest::new(&application);
|
||||||
request.backend = Some(b);
|
request.backend = Some(b);
|
||||||
let resolved = install::resolve_explicit(&exec, &cli.root, &request)?;
|
let plan = service::plan_legacy_install(&exec, &cli.root, &request)?;
|
||||||
return execute_resolved(&cli, &exec, resolved);
|
return render_and_execute_plan(&cli, &exec, plan);
|
||||||
} else {
|
} else {
|
||||||
eprintln!("sys: legacy install requires an explicit package source flag.");
|
eprintln!("sys: legacy install requires an explicit package source flag.");
|
||||||
eprintln!("Specify one of:");
|
eprintln!("Specify one of:");
|
||||||
|
|
@ -261,10 +280,14 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
return Err("legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)".into());
|
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() {
|
if backend.is_some() {
|
||||||
return Err(
|
return Err(
|
||||||
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \
|
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \
|
||||||
`sys install <application>`"
|
`sys install <application>` or `sys remove <application>`"
|
||||||
.into(),
|
.into(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -277,6 +300,7 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
eprintln!("sys: could not parse `{full_phrase}` in legacy mode.");
|
eprintln!("sys: could not parse `{full_phrase}` in legacy mode.");
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Legacy mode grammar: sys install <app> --legacy --<source> | \
|
"Legacy mode grammar: sys install <app> --legacy --<source> | \
|
||||||
|
sys remove <app> --legacy [--<source>] | \
|
||||||
sys history --legacy | sys undo --legacy | sys enable <service> --legacy | \
|
sys history --legacy | sys undo --legacy | sys enable <service> --legacy | \
|
||||||
sys disable <service> --legacy | sys choose <app> --legacy"
|
sys disable <service> --legacy | sys choose <app> --legacy"
|
||||||
);
|
);
|
||||||
|
|
@ -285,15 +309,17 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Default AI mode (natural language)
|
// 5. Default AI mode (natural language)
|
||||||
if cli.text.is_empty() {
|
if cli.text.is_empty() {
|
||||||
eprintln!("sys: no instruction provided.");
|
eprintln!("sys: no instruction provided.");
|
||||||
eprintln!("Natural language administration is the default:");
|
eprintln!("Natural language administration is the default:");
|
||||||
eprintln!(" sys install <application>");
|
eprintln!(" sys install <application>");
|
||||||
eprintln!(" sys please install <application>");
|
eprintln!(" sys please install <application>");
|
||||||
|
eprintln!(" sys remove <application>");
|
||||||
eprintln!(" sys ask \"<request>\"");
|
eprintln!(" sys ask \"<request>\"");
|
||||||
eprintln!("Or select deterministic legacy administration:");
|
eprintln!("Or select deterministic legacy administration:");
|
||||||
eprintln!(" sys install <application> --legacy --<source>");
|
eprintln!(" sys install <application> --legacy --<source>");
|
||||||
|
eprintln!(" sys remove <application> --legacy [--<source>]");
|
||||||
eprintln!(" sys history --legacy");
|
eprintln!(" sys history --legacy");
|
||||||
eprintln!(" sys undo --legacy");
|
eprintln!(" sys undo --legacy");
|
||||||
return Err("missing instruction".into());
|
return Err("missing instruction".into());
|
||||||
|
|
@ -313,10 +339,15 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
return run_install(&cli, &exec, &application, backend);
|
return run_install(&cli, &exec, &application, backend);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Natural `sys remove <app>` / `sys please remove <app>`
|
||||||
|
if let Some(application) = parse_removal_text(&full_phrase) {
|
||||||
|
return run_remove(&cli, &exec, &application, backend);
|
||||||
|
}
|
||||||
|
|
||||||
if backend.is_some() {
|
if backend.is_some() {
|
||||||
return Err(
|
return Err(
|
||||||
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \
|
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \
|
||||||
`sys install <application>`"
|
`sys install <application>` or `sys remove <application>`"
|
||||||
.into(),
|
.into(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -442,6 +473,27 @@ fn parse_install_text(text: &str) -> Option<String> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Parse `remove <application>` / `uninstall <application>` / `delete <application>` / `please remove <application>`.
|
||||||
|
fn parse_removal_text(text: &str) -> Option<String> {
|
||||||
|
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.
|
/// Load the installed system's configuration instead of assuming defaults.
|
||||||
fn load_installed_config(root: &Path) -> InstallConfig {
|
fn load_installed_config(root: &Path) -> InstallConfig {
|
||||||
let path = root.join("etc/phoebus/install.toml");
|
let path = root.join("etc/phoebus/install.toml");
|
||||||
|
|
@ -643,9 +695,8 @@ fn run_install(
|
||||||
root: &cli.root,
|
root: &cli.root,
|
||||||
ask: asker.as_deref(),
|
ask: asker.as_deref(),
|
||||||
};
|
};
|
||||||
let resolved = match install::resolve_with_ai(exec, &cli.root, &request, &session, &ai, &facts)
|
let plan = match service::plan_install(exec, &cli.root, &request, &session, Some(&ai), &facts) {
|
||||||
{
|
Ok(plan) => plan,
|
||||||
Ok(resolved) => resolved,
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
// The model failed: offer the actionable legacy alternative and stop;
|
// The model failed: offer the actionable legacy alternative and stop;
|
||||||
// do not install through any backend.
|
// do not install through any backend.
|
||||||
|
|
@ -662,120 +713,88 @@ fn run_install(
|
||||||
return Err(format!("the AI investigation did not produce a plan: {e}").into());
|
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
|
fn run_remove(
|
||||||
/// is the single execution path for AI-, explicit- and deterministic-selected
|
|
||||||
/// installs.
|
|
||||||
fn execute_resolved(
|
|
||||||
cli: &Cli,
|
cli: &Cli,
|
||||||
exec: &Exec,
|
exec: &Exec,
|
||||||
resolved: install::ResolvedInstall,
|
application: &str,
|
||||||
|
backend: Option<Backend>,
|
||||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
println!("{}", resolved.render());
|
let plan = service::plan_removal(exec, &cli.root, application, backend)?;
|
||||||
|
let conv_path = conversation::history_path();
|
||||||
if effective_uid() != 0 {
|
conversation::save_turn(
|
||||||
return Err(format!(
|
&conv_path,
|
||||||
"installing `{}` requires root; run `sudo sys install {}`",
|
ConversationTurn {
|
||||||
resolved.request.application, resolved.request.application
|
timestamp_unix: now_unix(),
|
||||||
)
|
query: format!("remove {application}"),
|
||||||
.into());
|
response_kind: "removal".into(),
|
||||||
}
|
application: Some(application.to_string()),
|
||||||
let confirmation = SysConfirm {
|
chosen_candidate: None,
|
||||||
action: resolved.action.clone(),
|
alternatives: Vec::new(),
|
||||||
assume_yes: cli.yes,
|
plan_id: Some(plan.id.clone()),
|
||||||
};
|
plan_digest: Some(plan.digest.clone()),
|
||||||
let auth = authorize(&confirmation, &resolved.render(), "install")?;
|
rationale: plan.rationale.clone(),
|
||||||
|
|
||||||
// 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()
|
|
||||||
},
|
},
|
||||||
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)?;
|
|
||||||
|
|
||||||
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());
|
render_and_execute_plan(cli, exec, plan)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn render_and_execute_plan(
|
||||||
|
cli: &Cli,
|
||||||
|
exec: &Exec,
|
||||||
|
plan: PreparedPlan,
|
||||||
|
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
|
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,
|
||||||
};
|
};
|
||||||
if let Some(snapshot) = &outcome.snapshot {
|
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!("protective snapshot: {snapshot}");
|
||||||
}
|
}
|
||||||
println!("{}", outcome.output);
|
for line in &outcome.output {
|
||||||
|
if !line.trim().is_empty() {
|
||||||
match install::verify_installed(exec, &cli.root, &resolved) {
|
println!("{line}");
|
||||||
Ok(verification) => {
|
}
|
||||||
println!("{verification}");
|
}
|
||||||
transaction::finish(
|
if !outcome.verification.is_empty() {
|
||||||
exec,
|
println!("{}", outcome.verification);
|
||||||
&cli.root,
|
}
|
||||||
id,
|
|
||||||
"ok",
|
|
||||||
outcome.snapshot.clone(),
|
|
||||||
vec![TransactionOutcome::completed(described.clone())],
|
|
||||||
)?;
|
|
||||||
Ok(())
|
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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bounded system facts for the assistant: hardware, selected profile and
|
/// Bounded system facts for the assistant: hardware, selected profile and
|
||||||
/// measured compile times. No personal files, credentials or command history.
|
/// measured compile times. No personal files, credentials or command history.
|
||||||
|
|
@ -898,6 +917,33 @@ fn run_ask(
|
||||||
if let Some(application) = parse_install_text(instruction) {
|
if let Some(application) = parse_install_text(instruction) {
|
||||||
return run_install(cli, exec, &application, backend);
|
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 facts = gather_facts(exec);
|
||||||
let conf = load_installed_ai_config(&cli.root);
|
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,
|
provider,
|
||||||
&endpoint,
|
endpoint,
|
||||||
&model,
|
model,
|
||||||
&facts,
|
transport: transport.as_ref(),
|
||||||
instruction,
|
limits: phoebus_ai::install::Limits::default(),
|
||||||
transport.as_ref(),
|
};
|
||||||
) {
|
|
||||||
|
let plan = match service::plan_general(exec, &cli.root, instruction, &facts, &ai) {
|
||||||
Ok(plan) => plan,
|
Ok(plan) => plan,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("The model is unavailable or returned an unusable plan: {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();
|
render_and_execute_plan(cli, exec, plan)
|
||||||
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<DestructiveAuthorization> = 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<String> = 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(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
|
|
||||||
313
installer-rs/crates/phoebus-installer/src/conversation.rs
Normal file
313
installer-rs/crates/phoebus-installer/src/conversation.rs
Normal file
|
|
@ -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<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub chosen_candidate: Option<Candidate>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub alternatives: Vec<Rejected>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub plan_id: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub plan_digest: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub rationale: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
|
pub struct ConversationHistory {
|
||||||
|
pub turns: Vec<ConversationTurn>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum FollowupResolution {
|
||||||
|
/// Explain the tradeoffs between the chosen candidate and alternative backend.
|
||||||
|
Comparison {
|
||||||
|
application: String,
|
||||||
|
target_backend: Option<Backend>,
|
||||||
|
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<FollowupResolution> {
|
||||||
|
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(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,8 +2,10 @@
|
||||||
|
|
||||||
pub mod ai_guide;
|
pub mod ai_guide;
|
||||||
pub mod assistant_bridge;
|
pub mod assistant_bridge;
|
||||||
|
pub mod conversation;
|
||||||
pub mod gui_bridge;
|
pub mod gui_bridge;
|
||||||
pub mod orchestrate;
|
pub mod orchestrate;
|
||||||
pub mod release;
|
pub mod release;
|
||||||
|
pub mod service;
|
||||||
|
|
||||||
pub use orchestrate::{InstallObserver, Installer, NoopObserver};
|
pub use orchestrate::{InstallObserver, Installer, NoopObserver};
|
||||||
|
|
|
||||||
1055
installer-rs/crates/phoebus-installer/src/service.rs
Normal file
1055
installer-rs/crates/phoebus-installer/src/service.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -373,7 +373,9 @@ fn the_help_lists_every_backend_flag() {
|
||||||
#[test]
|
#[test]
|
||||||
fn choose_never_invents_a_candidate() {
|
fn choose_never_invents_a_candidate() {
|
||||||
let root = tempfile::tempdir().expect("temp root");
|
let root = tempfile::tempdir().expect("temp root");
|
||||||
|
let empty = tempfile::tempdir().expect("empty PATH");
|
||||||
let out = sys()
|
let out = sys()
|
||||||
|
.env("PATH", empty.path())
|
||||||
.arg("--root")
|
.arg("--root")
|
||||||
.arg(root.path())
|
.arg(root.path())
|
||||||
.args(["choose", "some-package", "--legacy"])
|
.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());
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -23,12 +23,12 @@ Singleton {
|
||||||
const override = Quickshell.env("PHOEBUS_ASSISTANT_BRIDGE_CMD");
|
const override = Quickshell.env("PHOEBUS_ASSISTANT_BRIDGE_CMD");
|
||||||
if (override && override.length > 0)
|
if (override && override.length > 0)
|
||||||
return override.split(" ").filter(part => part.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 {
|
Timer {
|
||||||
interval: 400
|
interval: 100
|
||||||
repeat: true
|
repeat: false
|
||||||
running: proc.running && root.handshake === null
|
running: proc.running && root.handshake === null
|
||||||
onTriggered: root.refreshHandshake(null)
|
onTriggered: root.refreshHandshake(null)
|
||||||
}
|
}
|
||||||
|
|
@ -92,8 +92,8 @@ Singleton {
|
||||||
call("ask", { request: query, backend: backend }, cb);
|
call("ask", { request: query, backend: backend }, cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
function execute(actions, digest, yes, cb) {
|
function execute(planId, digest, yes, cb) {
|
||||||
call("execute", { actions: actions, digest: digest, yes: yes }, cb);
|
call("execute", { plan_id: planId, digest: digest, yes: yes }, cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
function legacyInstall(application, backend, cb) {
|
function legacyInstall(application, backend, cb) {
|
||||||
|
|
|
||||||
|
|
@ -21,17 +21,18 @@ ShellRoot {
|
||||||
refreshStatus();
|
refreshStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
onCurrentTabChanged: {
|
||||||
|
if (currentTab === "updates" && !shell.updateOverview && !shell.busy) {
|
||||||
|
checkUpdates();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function refreshStatus() {
|
function refreshStatus() {
|
||||||
AssistantBridge.getProactiveAlerts(reply => {
|
AssistantBridge.getProactiveAlerts(reply => {
|
||||||
if (reply.ok && reply.result) {
|
if (reply.ok && reply.result) {
|
||||||
shell.activeAlerts = reply.result.alerts || [];
|
shell.activeAlerts = reply.result.alerts || [];
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
AssistantBridge.getUpdates(reply => {
|
|
||||||
if (reply.ok && reply.result) {
|
|
||||||
shell.updateOverview = reply.result;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
AssistantBridge.getPreferences(reply => {
|
AssistantBridge.getPreferences(reply => {
|
||||||
if (reply.ok && reply.result) {
|
if (reply.ok && reply.result) {
|
||||||
shell.preferences = 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) {
|
function addMessage(sender, text, data) {
|
||||||
const item = {
|
const item = {
|
||||||
sender: sender,
|
sender: sender,
|
||||||
|
|
@ -81,15 +94,16 @@ ShellRoot {
|
||||||
function executePlan(planData) {
|
function executePlan(planData) {
|
||||||
shell.busy = true;
|
shell.busy = true;
|
||||||
shell.statusText = "Executing approved plan...";
|
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;
|
shell.busy = false;
|
||||||
if (!reply.ok) {
|
if (!reply.ok) {
|
||||||
shell.statusText = "Execution failed";
|
shell.statusText = "Execution failed";
|
||||||
addMessage("assistant", "Execution failed: " + reply.error, null);
|
addMessage("assistant", "Execution failed: " + reply.error, null);
|
||||||
} else {
|
} else {
|
||||||
shell.statusText = "Installed successfully";
|
shell.statusText = "Operation completed successfully";
|
||||||
addMessage("assistant", "Operation completed successfully.", {
|
addMessage("assistant", "Operation completed successfully.", {
|
||||||
completed: true,
|
completed: true,
|
||||||
application: planData.application,
|
application: planData.application,
|
||||||
|
|
|
||||||
|
|
@ -65,9 +65,8 @@ echo "sys-acceptance: SYS=$SYS MUTATE=$MUTATE"
|
||||||
# --- Read-only deterministic and JSON paths -------------------------------
|
# --- Read-only deterministic and JSON paths -------------------------------
|
||||||
run_expect_zero identity --version
|
run_expect_zero identity --version
|
||||||
run_expect_zero history-legacy history --legacy
|
run_expect_zero history-legacy history --legacy
|
||||||
if [[ "$(id -u)" -eq 0 ]]; then
|
run_expect_zero undo-status-legacy undo status --legacy
|
||||||
run_expect_zero undo-legacy undo --legacy
|
if [[ "$(id -u)" -ne 0 ]]; then
|
||||||
else
|
|
||||||
run_expect_nonzero nonroot-undo "mutating actions require root" undo --legacy
|
run_expect_nonzero nonroot-undo "mutating actions require root" undo --legacy
|
||||||
fi
|
fi
|
||||||
run_expect_zero appimage-empty --root / --legacy appimage list
|
run_expect_zero appimage-empty --root / --legacy appimage list
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue