Compare commits

...

3 commits

Author SHA1 Message Date
4679f935e3 fix(sys): harden the administration broker and complete its command surface
Some checks are pending
ci / test (push) Waiting to run
2026-09-22 07:30:38 -07:00
b4935578ac fix(installer): do not discard the validated AI state on unrelated edits
A fully-validated OpenCode install was refused at the final step because
selecting a disk or setting the account/LUKS secrets cleared the AI
validation. Bind the validation to a digest of only the AI connection
settings: non-AI config changes preserve it, while an AI provider/model/
endpoint/server or AI-credential change invalidates it. Add regression
tests and password-length placeholder hints.
2026-09-22 04:13:31 -07:00
39c69d59cf feat(gui): pick timezone/locale/keymap and AI model from lists
The region and keyboard fields were free-text, so users had to know zone
names and layout names from memory, and the AI model had to be typed.
Add an 'options' bridge op (live timezones/locales/keymaps) and an
'ai_catalog' op (the OpenCode provider/model catalog, or an
OpenAI-compatible /models list), and a searchable PhoebusCombo picker.
Also name provider/model in OpenCode errors instead of an opaque HTTP
code. Record the user-trial findings U1-U5.
2026-09-22 03:57:01 -07:00
20 changed files with 1964 additions and 203 deletions

View file

@ -5,6 +5,54 @@ this file is the curated, human-readable summary.
Format: Keep a Changelog. Dates are UTC. Format: Keep a Changelog. Dates are UTC.
## 2026-09-22 — `sys` administration hardening
Correctness work on the deterministic `sys` broker and the assistant path that
shares it. Every change is covered by unit tests (368 Rust tests pass); the
destructive rollback VM acceptance remains unverified (see below).
### Fixed
- **Alternate-root execution now targets the requested system.** Package
execution, service enable/disable and Flatpak operations previously ignored
`--root` and ran against the host, while `emerge --pretend` previews already
ran in the target. All of them now go through one `target_spec`/chroot path,
and operations that cannot be confined to a non-running root (service status,
start, stop, restart) are **rejected before any command is built**.
`systemctl --root` is used for offline enable/disable. Regression tests prove
preview and execution both emit a chroot confined to the same root, and that
a rejected operation invokes nothing.
- **Validation at the execution boundary.** `parse_natural` emitted actions
that were never validated, so a manual `sys install --color=n` could pass an
option through. `parse_natural` now validates its own output, `resolve_effects`
and `execute` validate every action before touching a command, and
option-like operands (leading `-`) are rejected for services, packages and
search. `emerge`/`flatpak` operands are passed after an explicit `--`
separator. Manual, JSON and AI entry paths are all covered.
- **`sys ask` reports failure truthfully.** A failing action now stops the plan,
records the completed/failed/unattempted actions, and exits nonzero instead of
returning success.
- **Complete transaction history.** Ordinary mutating `sys` commands are
recorded (previously only assistant plans were), the protective snapshot id
created by the generic high-risk path is preserved and recorded, and a
recording failure is surfaced instead of being swallowed.
- **Reliable package approval.** `emerge --pretend` output is now classified as
*established* (a real plan, including a genuine `0 packages`) or
*unestablished*; `sys` refuses to proceed when the effects cannot be
established rather than treating unparseable output as "nothing to do". A
material change between review and execution still aborts.
### Added
- Typed service lifecycle actions `start_service`, `stop_service`,
`restart_service`, and ordinary commands for the existing bounded verbs:
`sys flatpak install|remove|list`, `sys nix prepare …`, `sys snapshot [op]`,
`sys start|stop|restart <unit>`. The AI prompt exposes the new verbs, so the
manual and AI interfaces share one validated execution path.
- `phoebus-executor::actions::execute_plan` runs a reviewed multi-action plan,
stopping at the first failure and marking the rest unattempted, so the
assistant and any multi-step caller report partial failure consistently.
- CLI integration tests (`tests/sys_cli.rs`) cover the manual and JSON entry
paths and exit codes.
## Unreleased ## Unreleased
### Added ### Added

View file

@ -3,36 +3,37 @@
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-22), OpenCode adapter. - **Last updated:** this session (2026-09-22), `sys` administration hardening.
- **Current focus:** Implemented a real OpenCode agent-server adapter - **Current focus:** Hardened `sys` into a reliable administration tool.
(`phoebus-executor::opencode_client`) that speaks the session/message protocol (1) All package/service/Flatpak execution now honours `--root` through one
over curl and implements `ModelTransport`, wired into canonical config `target_spec`/chroot path (offline `systemctl --root` for enable/disable),
(`ai.backend = "opencode"`), the GUI ("OpenCode agent" + Test connection), and runtime-only service operations are rejected before any command when an
the installer CLI (`--ai-backend opencode`, `--opencode-test`) and `sys ask`. alternate root is requested. (2) Every action is validated at the execution
The mandatory-AI gate now requires a validated interaction with invalidated boundary (`parse_natural` now validates its own output); option-like operands
state. The probe/transport were hardened (loopback/TLS policy, DNS pinning, are rejected and operands are passed after `--`. (3) `sys ask` stops at the
status checks, auth), and the GUI harness gained exact-session and first failure, records completed/failed/unattempted actions, and exits
frontend-state assertions. nonzero. (4) Ordinary mutating commands are recorded, the generic protective
snapshot id is preserved, and recording failures are visible. (5) A genuinely
empty package plan is distinguished from unparseable emerge output, which is
refused. (6) Added typed `start/stop/restart_service` and ordinary commands
for Flatpak, Nix preparation and snapshots.
- **Last verified (this session):** - **Last verified (this session):**
- 336 Rust tests + 16 harness tests green; fmt/clippy clean. - 368 Rust tests green (including 3 new CLI integration tests) + 16 harness
- Real inference through `opencode 1.18.32` with `deepseek-v4-flash`; tests; `cargo fmt --all -- --check` and `cargo clippy --workspace
`--opencode-test` → `{"phoebus":"ok"}`; the GUI bridge `ai_check` applied 8 --all-targets` clean (exit 0). Static `phoebus-installer`/`sys` build.
reviewed changes; `sys ask` proposed and ran a read-only action. - Unit/integration evidence for all six fixes: preview and execution both
- Auth: none → `authentication_required`, wrong → `authentication_rejected`, chroot to the same alternate root; runtime service ops reject an alternate
correct → `model_catalog` + successful inference. Plain http to a LAN host root without invoking anything; invalid actions are refused by the manual,
→ `insecure_transport`, exit 1, no request sent. JSON and AI parsers and at the executor; `execute_plan` marks later actions
- 7 real-HTTP integration tests (status, chunked multibyte, oversize, unattempted after a failure; unparseable emerge output is refused while a
redirect, disconnect, auth) and 2 env-gated live tests. real `0 packages` plan is accepted; a material plan change aborts before
- GUI acceptance in a disposable VM: `gui-driver.py opencode` passed 17/17 the mutation.
(selected OpenCode, entered the endpoint/model through the UI, real model - **Not yet verified this session:** the destructive **rollback VM
response + validated proposal); `gui-driver.py gui` passed 25/25. acceptance** (`sys undo`). See the blocker below — rollback stays explicitly
ISO `sha256 4db98db3…`, static binary `sha256 72c2dcd0…`. unverified. The OpenCode live tests are environment-gated and were skipped
- **Not yet verified this session:** the full graphical **installation** through (no `PHOEBUS_OPENCODE_LIVE_*`), and the full graphical install past the AI
OpenCode past the AI gate (disk/account/review/ERASE/install/detached boot), gate and a separate physical computer remain unverified from the previous
and a separate physical computer. The pinned manifest is `v1.18.31` while the session.
tested binary is `1.18.32`. On this server use `deepseek-flash`; the model
must match the server's catalog (the GUI default `deepseek-chat` does not
exist on it).
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os> - **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
(remote `origin`, SSH port 2222). (remote `origin`, SSH port 2222).
@ -46,9 +47,13 @@ commit it. It should be short and current; use `git log` for detail.
2. **Installed Mango desktop**: install the default profile in a graphical VM 2. **Installed Mango desktop**: install the default profile in a graphical VM
and verify the panel/launcher/terminal/audio/network/lock/idle, the dwl and verify the panel/launcher/terminal/audio/network/lock/idle, the dwl
fallback, and the welcome/installer absence on the installed system. fallback, and the welcome/installer absence on the installed system.
3. **Rollback VM acceptance**: deliberately break an update, run `sys undo`, 3. **Rollback VM acceptance (BLOCKED this session)**: deliberately break an
reboot detached, verify `/var/db/pkg` matches `/`, then boot the recovery update, run `sys undo`, reboot detached, verify `/var/db/pkg` matches `/`,
entry with no network or model (ADR 0007). then boot the recovery entry with no network or model (ADR 0007). Needed:
(a) free the >=20 GiB `make doctor` wants for the harness (the root fs has
~12 GiB free); (b) an automated driver for the break-update/undo/recovery
sequence — `appliance-driver.py` only implements `install`/`boot`. Until
both exist, `sys undo` stays unverified.
4. **Narrow the live broker privilege**: replace the live-only 4. **Narrow the live broker privilege**: replace the live-only
`NOPASSWD: ALL` rule for the GUI bridge with the smallest practical `NOPASSWD: ALL` rule for the GUI bridge with the smallest practical
command-scoped rule once a safe sudoers form is verified (ADR 0011 context). command-scoped rule once a safe sudoers form is verified (ADR 0011 context).
@ -66,8 +71,11 @@ commit it. It should be short and current; use `git log` for detail.
verified as a blocked prerequisite and with a fixture transport. verified as a blocked prerequisite and with a fixture transport.
- **Installed** Mango (GURU + compiled Quickshell/DMS) is not VM-verified; nor - **Installed** Mango (GURU + compiled Quickshell/DMS) is not VM-verified; nor
is the dwl fallback session. is the dwl fallback session.
- Rollback and the AI sandbox are implemented and unit-tested but not - **Rollback (`sys undo`) is implemented and unit-tested but NOT VM-verified
VM-verified. NVIDIA is not verified. (BLOCKED).** Exact blockers: `make doctor` reports ~13 GiB free versus the
>=20 GiB the harness wants (root fs ~12 GiB free), and the harness has no
automated break-update/undo/recovery-boot mode. The AI sandbox is likewise
implemented/unit-tested but not VM-verified. NVIDIA is not verified.
- A **separate physical computer** for the OpenCode transport test is not - A **separate physical computer** for the OpenCode transport test is not
available (BLOCKED); a forwarded-hop + unauthenticated-LAN-refusal host-local available (BLOCKED); a forwarded-hop + unauthenticated-LAN-refusal host-local
test was done instead. test was done instead.

View file

@ -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 | Partial | history, enable/disable, inspect, install, prepare-updates VM-verified; `undo`, `undo status`, `ask` added (unit-tested, VM gate pending) | | 12 | `sys` operations | Partial | 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, and start/stop/restart + flatpak/nix/snapshot commands added (unit/integration-tested; VM gate pending) |
| 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 |

View file

@ -84,9 +84,13 @@ still not VM-verified.
| AI privacy boundary (facts only) | yes | yes | no | n/a | | AI privacy boundary (facts only) | yes | yes | no | n/a |
| AI OS sandbox (systemd hardened unit) | yes | yes | no | no | | AI OS sandbox (systemd hardened unit) | yes | yes | no | no |
| Installed assistant (`sys ask`) | yes | yes | fixture path only (no live call) | n/a | | Installed assistant (`sys ask`) | yes | yes | fixture path only (no live call) | n/a |
| Resolved package effects + approval binding | yes | yes | no | n/a | | Resolved package effects + approval binding | yes | yes (empty vs unestablished) | no | n/a |
| Transaction log | yes | yes | no | no | | Transaction log (outcomes, protective snapshots) | yes | yes | no | no |
| Flatpak/Nix bounded typed actions | yes | yes | no | no | | Flatpak/Nix bounded typed actions | yes | yes | no | no |
| `sys` consistent target-root execution | yes | yes | no | no |
| `sys` validation at the execution boundary | yes | yes | no | n/a |
| `sys ask` truthful failure (nonzero, stop, record) | yes | yes | no | n/a |
| Service start/stop/restart + flatpak/nix/snapshot commands | yes | yes | no | no |
| Desktop session helpers (menu/lock/idle) | yes | yes | functional test (stubs) | no | | Desktop session helpers (menu/lock/idle) | yes | yes | functional test (stubs) | no |
| Mango + DankMaterialShell profile | yes | yes | live graphical VM yes; installed no | no | | Mango + DankMaterialShell profile | yes | yes | live graphical VM yes; installed no | no |
| Mango is the default desktop | yes | yes | live graphical VM yes; installed install pending | no | | Mango is the default desktop | yes | yes | live graphical VM yes; installed install pending | no |
@ -123,13 +127,18 @@ still not VM-verified.
- **NVIDIA** is architecturally allowed but not verified on hardware. - **NVIDIA** is architecturally allowed but not verified on hardware.
- **UKI** is deferred; the dracut UKI generator did not embed the kernel - **UKI** is deferred; the dracut UKI generator did not embed the kernel
command line, so BLS is used (and verified). command line, so BLS is used (and verified).
- **Rollback** is implemented and unit-tested end to end at the command/text - **Rollback is NOT VM-verified.** It is implemented and unit-tested end to end
layer (snapshot sets, root/var generation, fstab and BLS rewriting, kernel at the command/text layer (snapshot sets, root/var generation, fstab and BLS
selection, interruption resume, retention, free-space gate), but the rewriting, kernel selection, interruption resume, retention, free-space
destructive VM acceptance test (deliberately broken update -> `sys undo` -> gate), but the destructive acceptance test (deliberately broken update ->
detached reboot -> package-state check -> recovery with no network/model) has `sys undo` -> detached reboot -> package-state check -> recovery with no
not been run. `sys undo` is present; treat VM verification as the gate before network/model) was **not run in this session**. Blockers: (1) `make doctor`
relying on it. reports only ~13 GiB free versus the >=20 GiB the VM harness wants, and the
root filesystem has ~12 GiB free; (2) the committed appliance/serial harness
only implements `install` and `boot` modes — there is no automated driver for
the break-update / `sys undo` / recovery-boot sequence, which is documented as
an interactive procedure. `sys undo` is present; treat VM verification as the
gate before relying on it.
- **Mango + DankMaterialShell** is the default desktop - **Mango + DankMaterialShell** is the default desktop
(`desktop.profile = "mango"`, Flatpak on). It is implemented with Mango (`desktop.profile = "mango"`, Flatpak on). It is implemented with Mango
0.17.2, DMS (pinned release), Quickshell 0.3.1 and scenefx 0.5 from the GURU 0.17.2, DMS (pinned release), Quickshell 0.3.1 and scenefx 0.5 from the GURU

View file

@ -51,6 +51,27 @@ and passed in the graphical VM; the remaining stages are the long package
installation. Two fresh-disk graphical installs and a separate physical machine installation. Two fresh-disk graphical installs and a separate physical machine
remain unverified. remain unverified.
### User trial findings (interactive VM, 2026-09-22)
Observed while a user drove the live ISO by hand (run
`/var/tmp/phoebus-vm/user-session*`):
| ID | Finding | Status |
|----|---------|--------|
| U1 | Timezone (and locale, keyboard) were **free-text**: the user was expected to know `America/New_York` etc. Only ~5 keymap presets were offered, then manual entry. | **Fixed**: searchable pickers populated from the live system (418 timezones from `zone.tab`, 513 locales, 82 keymaps), type-to-filter and click-to-choose; a custom value is still accepted. |
| U2 | The AI **provider/model** fields were free-text; the user had to know the exact model id. | **Fixed**: `ai_catalog` bridge op returns the OpenCode catalog (223 providers, real model ids) or an OpenAI-compatible `/models` list; the GUI shows selectable Provider/Model combos with a "Load list" action. |
| U3 | An invalid model produced only `OpenCode message failed: HTTP 500` — opaque. | **Fixed in source**: the error now names `provider/model` and says to check the model exists and the credentials are valid. (Needs the next ISO.) |
| U4 | At first boot the DMS app-launcher/overview overlay was open on top of the welcome window, hiding the primary action until dismissed. | **Open**: reproduced once; investigating whether it is a DMS first-run behaviour or a focus race. |
| U5 | The OpenCode model default `deepseek-chat` is not present on every server, so the first attempt failed. | **Mitigated**: the picker now lists only real models. Considering defaulting the model to unset and requiring a pick. |
| U6 | **Showstopper.** A fully-validated OpenCode install was refused at the final step with *"installing Phoebus requires a successful, validated AI interaction"*. The validated state was cleared by **unrelated** configuration and secret changes (selecting a disk, typing the account password, setting the LUKS passphrase). | **Fixed**: the AI validation is now bound to a digest of only the AI connection settings; non-AI config changes preserve it, and only an AI provider/model/endpoint/server change or an AI credential change invalidates it. Regression tests: `a_non_ai_config_change_keeps_the_validated_interaction`, `an_account_secret_does_not_invalidate_but_an_ai_key_does`. |
| U7 | The account/encryption step required several attempts; the password/passphrase minimum was only revealed as a red error after pressing Next, and the offending fields could be scrolled off-screen. | **Mitigated**: password/passphrase fields now carry an "At least 8 characters" / "Repeat …" placeholder hint before submission. |
U6 blocked a real install; U1–U3 and U6–U7 are implemented, U4 remains open.
The user's session reached the AI step, obtained and applied a validated
OpenCode proposal, selected the disk, completed the account step and the
review — and only then hit U6. Evidence: `/var/tmp/phoebus-vm/user-session3/`
(`shots/0008`–`0016`, `observations.log`).
OpenCode protocol/transport tests: 26 executor unit tests + 7 real-HTTP OpenCode protocol/transport tests: 26 executor unit tests + 7 real-HTTP
integration tests + 2 live tests (skipped offline, real inference when integration tests + 2 live tests (skipped offline, real inference when
configured). Bridge gate tests: 5. Full suite: 336 Rust tests. configured). Bridge gate tests: 5. Full suite: 336 Rust tests.

View file

@ -399,6 +399,14 @@ Not yet verified for this baseline: `sys undo`, a deliberately broken update, a
detached rollback reboot, and recovery with no network/model (the rollback detached rollback reboot, and recovery with no network/model (the rollback
acceptance gate). acceptance gate).
**2026-09-22 update — rollback acceptance still NOT run.** A session of `sys`
administration hardening did not run the destructive acceptance test. The
blockers are unchanged and exact: `make doctor` reports ~13 GiB free versus the
>=20 GiB the VM harness requires (the root filesystem has ~12 GiB free), and the
committed harness (`appliance-driver.py`, `serial-driver.py`) implements only
`install` and `boot`, with no automated break-update / `sys undo` /
recovery-boot mode. `sys undo` therefore remains **unverified**, not passing.
## Mango + DankMaterialShell verification (IN PROGRESS) ## Mango + DankMaterialShell verification (IN PROGRESS)
### Live ISO — graphical VM (verified 2026-09-21) ### Live ISO — graphical VM (verified 2026-09-21)

View file

@ -66,7 +66,8 @@ pub fn action_tag(action: &SystemAction) -> String {
/// there is no shell or file action. /// there is no shell or file action.
pub const ASSISTANT_PROMPT: &str = "\ pub const ASSISTANT_PROMPT: &str = "\
You are the Phoebus OS system assistant. You can ONLY propose actions from this \ You are the Phoebus OS system assistant. You can ONLY propose actions from this \
closed set: inspect_service, enable_service, disable_service, inspect_package, \ closed set: inspect_service, enable_service, disable_service, start_service, \
stop_service, restart_service, inspect_package, \
install_package, remove_package, search_packages, flatpak_install, flatpak_remove, \ install_package, remove_package, search_packages, flatpak_install, flatpak_remove, \
flatpak_list, nix_prepare, create_snapshot, undo, rollback_status, history, \ flatpak_list, nix_prepare, create_snapshot, undo, rollback_status, history, \
update_system, prepare_updates, inspect_updates. update_system, prepare_updates, inspect_updates.
@ -270,6 +271,12 @@ mod tests {
fn invalid_values_are_rejected() { fn invalid_values_are_rejected() {
let text = r#"{"version":1,"summary":"x","actions":[{"action":"install_package","atom":"bad atom"}],"rationale":[{"action":"install_package","reason":"x"}]}"#; let text = r#"{"version":1,"summary":"x","actions":[{"action":"install_package","atom":"bad atom"}],"rationale":[{"action":"install_package","reason":"x"}]}"#;
assert!(parse_plan(text).is_err()); assert!(parse_plan(text).is_err());
// The AI path rejects option-like operands exactly like the manual and
// JSON paths, so a model cannot smuggle a command-line option.
let option = r#"{"version":1,"summary":"x","actions":[{"action":"install_package","atom":"-C"}],"rationale":[{"action":"install_package","reason":"x"}]}"#;
assert!(parse_plan(option).is_err());
let service = r#"{"version":1,"summary":"x","actions":[{"action":"start_service","name":"--now"}],"rationale":[{"action":"start_service","reason":"x"}]}"#;
assert!(parse_plan(service).is_err());
} }
#[test] #[test]

View file

@ -35,6 +35,18 @@ pub enum SystemAction {
DisableService { DisableService {
name: String, name: String,
}, },
/// Start a service now (runtime, not boot persistence).
StartService {
name: String,
},
/// Stop a running service now.
StopService {
name: String,
},
/// Restart a running service now.
RestartService {
name: String,
},
InspectPackage { InspectPackage {
atom: String, atom: String,
}, },
@ -84,6 +96,9 @@ impl SystemAction {
SystemAction::DisableService { name } => { SystemAction::DisableService { name } => {
format!("disable service {name} at boot") format!("disable service {name} at boot")
} }
SystemAction::StartService { name } => format!("start service {name}"),
SystemAction::StopService { name } => format!("stop service {name}"),
SystemAction::RestartService { name } => format!("restart service {name}"),
SystemAction::InspectPackage { atom } => format!("inspect package {atom}"), SystemAction::InspectPackage { atom } => format!("inspect package {atom}"),
SystemAction::InstallPackage { atom } => format!("install package {atom}"), SystemAction::InstallPackage { atom } => format!("install package {atom}"),
SystemAction::RemovePackage { atom } => format!("remove package {atom}"), SystemAction::RemovePackage { atom } => format!("remove package {atom}"),
@ -130,6 +145,9 @@ impl SystemAction {
SystemAction::PrepareUpdates => Risk::Medium, SystemAction::PrepareUpdates => Risk::Medium,
SystemAction::EnableService { .. } SystemAction::EnableService { .. }
| SystemAction::DisableService { .. } | SystemAction::DisableService { .. }
| SystemAction::StartService { .. }
| SystemAction::StopService { .. }
| SystemAction::RestartService { .. }
| SystemAction::CreateSnapshot { .. } | SystemAction::CreateSnapshot { .. }
| SystemAction::FlatpakInstall { .. } | SystemAction::FlatpakInstall { .. }
| SystemAction::FlatpakRemove { .. } | SystemAction::FlatpakRemove { .. }
@ -160,13 +178,19 @@ impl SystemAction {
let valid_token = |s: &str| { let valid_token = |s: &str| {
!s.is_empty() !s.is_empty()
&& s.len() <= 128 && s.len() <= 128
// A leading dash would be parsed by the target command as an
// option, so it is never a service/unit name.
&& !s.starts_with('-')
&& s.chars() && s.chars()
.all(|c| c.is_ascii_alphanumeric() || "@._+-".contains(c)) .all(|c| c.is_ascii_alphanumeric() || "@._+-".contains(c))
}; };
match self { match self {
SystemAction::InspectService { name } SystemAction::InspectService { name }
| SystemAction::EnableService { name } | SystemAction::EnableService { name }
| SystemAction::DisableService { name } => { | SystemAction::DisableService { name }
| SystemAction::StartService { name }
| SystemAction::StopService { name }
| SystemAction::RestartService { name } => {
if valid_token(name) { if valid_token(name) {
Ok(()) Ok(())
} else { } else {
@ -241,6 +265,11 @@ pub fn valid_package_spec(spec: &str) -> bool {
if spec.is_empty() || spec.len() > 128 { if spec.is_empty() || spec.len() > 128 {
return false; return false;
} }
// A leading dash would be consumed by `emerge` as an option (e.g.
// `--color=n` or `-C`), so it is rejected before any command is built.
if spec.starts_with('-') {
return false;
}
let mut parts = spec.split('/'); let mut parts = spec.split('/');
let Some(first) = parts.next() else { let Some(first) = parts.next() else {
return false; return false;
@ -251,7 +280,10 @@ pub fn valid_package_spec(spec: &str) -> bool {
match parts.next() { match parts.next() {
None => true, None => true,
Some(second) => { Some(second) => {
!second.is_empty() && second.chars().all(is_atom_char) && parts.next().is_none() !second.is_empty()
&& !second.starts_with('-')
&& second.chars().all(is_atom_char)
&& parts.next().is_none()
} }
} }
} }
@ -260,6 +292,8 @@ pub fn valid_package_spec(spec: &str) -> bool {
pub fn valid_search_query(query: &str) -> bool { pub fn valid_search_query(query: &str) -> bool {
!query.is_empty() !query.is_empty()
&& query.len() <= 128 && query.len() <= 128
// Reject a leading dash so a query cannot become an option.
&& !query.starts_with('-')
&& query && query
.chars() .chars()
.all(|c| c.is_ascii_alphanumeric() || " ._+@/-".contains(c)) .all(|c| c.is_ascii_alphanumeric() || " ._+@/-".contains(c))
@ -291,11 +325,29 @@ pub fn valid_nix_attribute(value: &str) -> bool {
&& !value.contains(':') && !value.contains(':')
} }
/// Strip a case-insensitive ASCII prefix, returning the remainder. Used where
/// the operand after the verb is case-sensitive (Flatpak app ids).
fn strip_prefix_ascii_ci<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
// `get` (not `split_at`) so a prefix length that lands inside a multibyte
// character is simply "no match" rather than a panic.
let head = text.get(..prefix.len())?;
head.eq_ignore_ascii_case(prefix)
.then(|| &text[prefix.len()..])
}
/// A small deterministic parser for common `sys` phrases. /// A small deterministic parser for common `sys` phrases.
/// ///
/// The parser validates its own output, so the deterministic (manual) entry
/// path cannot emit an invalid action — exactly like the JSON and AI paths.
/// Free-form requests that do not match are left to the AI path /// Free-form requests that do not match are left to the AI path
/// (`--action-file`), which still produces the same typed schema. /// (`--action-file`), which still produces the same typed schema.
pub fn parse_natural(text: &str) -> Option<SystemAction> { pub fn parse_natural(text: &str) -> Option<SystemAction> {
let action = parse_natural_raw(text)?;
action.validate().ok()?;
Some(action)
}
fn parse_natural_raw(text: &str) -> Option<SystemAction> {
// Snapshot ids are case-sensitive (`@-20260101T000000-...`), so parse the // Snapshot ids are case-sensitive (`@-20260101T000000-...`), so parse the
// undo form from the original text before the general lowercasing. // undo form from the original text before the general lowercasing.
let raw = text.trim(); let raw = text.trim();
@ -329,6 +381,21 @@ pub fn parse_natural(text: &str) -> Option<SystemAction> {
return Some(SystemAction::DisableService { name }); return Some(SystemAction::DisableService { name });
} }
} }
if let Some(name) = rest("start ") {
if !name.is_empty() {
return Some(SystemAction::StartService { name });
}
}
if let Some(name) = rest("stop ") {
if !name.is_empty() {
return Some(SystemAction::StopService { name });
}
}
if let Some(name) = rest("restart ") {
if !name.is_empty() {
return Some(SystemAction::RestartService { name });
}
}
if let Some(atom) = rest("install ").or_else(|| rest("add ")) { if let Some(atom) = rest("install ").or_else(|| rest("add ")) {
if !atom.is_empty() { if !atom.is_empty() {
return Some(SystemAction::InstallPackage { atom }); return Some(SystemAction::InstallPackage { atom });
@ -352,6 +419,62 @@ pub fn parse_natural(text: &str) -> Option<SystemAction> {
return Some(SystemAction::InspectService { name }); return Some(SystemAction::InspectService { name });
} }
} }
// Flatpak verbs. App ids are case-sensitive (`org.chromium.Chromium`), so
// the operands are read from the original text, not the lowercased copy.
if let Some(rest) = strip_prefix_ascii_ci(raw, "flatpak ") {
let rest = rest.trim();
if let Some(id) = strip_prefix_ascii_ci(rest, "install ") {
let id = id.trim();
if !id.is_empty() {
return Some(SystemAction::FlatpakInstall {
app_id: id.to_string(),
});
}
}
if let Some(id) = strip_prefix_ascii_ci(rest, "remove ")
.or_else(|| strip_prefix_ascii_ci(rest, "uninstall "))
{
let id = id.trim();
if !id.is_empty() {
return Some(SystemAction::FlatpakRemove {
app_id: id.to_string(),
});
}
}
if rest.eq_ignore_ascii_case("list") || rest.eq_ignore_ascii_case("apps") {
return Some(SystemAction::FlatpakList);
}
}
if t == "flatpaks" {
return Some(SystemAction::FlatpakList);
}
// Nix development packages.
if let Some(packages) = rest("nix prepare ").or_else(|| rest("nix realise ")) {
let packages: Vec<String> = packages.split_whitespace().map(str::to_string).collect();
if !packages.is_empty() {
return Some(SystemAction::NixPrepare { packages });
}
}
if let Some(packages) = rest("nix install ") {
let packages: Vec<String> = packages.split_whitespace().map(str::to_string).collect();
if !packages.is_empty() {
return Some(SystemAction::NixPrepare { packages });
}
}
// Protective snapshot.
if t == "snapshot" || t.starts_with("snapshot ") {
let operation = t.strip_prefix("snapshot").unwrap_or("").trim();
let operation = if operation.is_empty() {
"manual snapshot".to_string()
} else {
operation.to_string()
};
return Some(SystemAction::CreateSnapshot { operation });
}
if let Some(id) = rest("undo ").or_else(|| rest("rollback ")) { if let Some(id) = rest("undo ").or_else(|| rest("rollback ")) {
if id == "status" { if id == "status" {
return Some(SystemAction::RollbackStatus); return Some(SystemAction::RollbackStatus);
@ -552,4 +675,117 @@ mod tests {
assert!(valid_flatpak_app_id("com.spotify.Client")); assert!(valid_flatpak_app_id("com.spotify.Client"));
assert!(!valid_flatpak_app_id("com/spotify")); assert!(!valid_flatpak_app_id("com/spotify"));
} }
#[test]
fn service_lifecycle_actions_are_typed_and_medium_risk() {
for (json, expected) in [
(
r#"{"action":"start_service","name":"sshd"}"#,
SystemAction::StartService {
name: "sshd".into(),
},
),
(
r#"{"action":"stop_service","name":"sshd"}"#,
SystemAction::StopService {
name: "sshd".into(),
},
),
(
r#"{"action":"restart_service","name":"sshd.service"}"#,
SystemAction::RestartService {
name: "sshd.service".into(),
},
),
] {
let action = parse_action(json).unwrap();
assert_eq!(action, expected);
assert!(action.is_mutating());
assert_eq!(action.risk(), Risk::Medium);
}
assert!(parse_action(r#"{"action":"start_service","name":"--now"}"#).is_err());
assert_eq!(
parse_natural("restart sshd"),
Some(SystemAction::RestartService {
name: "sshd".into()
})
);
assert_eq!(
parse_natural("stop bluetooth"),
Some(SystemAction::StopService {
name: "bluetooth".into()
})
);
}
/// The manual (natural), JSON and AI entry paths all reject an option-like
/// operand, so no entry path can smuggle an option into a command.
#[test]
fn option_like_operands_are_rejected_on_every_entry_path() {
// Manual path: the deterministic parser validates its own output.
assert_eq!(parse_natural("install --color=n"), None);
assert_eq!(parse_natural("enable --now"), None);
assert_eq!(parse_natural("search -C"), None);
assert_eq!(parse_natural("start --force"), None);
// JSON path.
assert!(parse_action(r#"{"action":"install_package","atom":"--color=n"}"#).is_err());
assert!(parse_action(r#"{"action":"enable_service","name":"--now"}"#).is_err());
assert!(parse_action(r#"{"action":"search_packages","query":"-C"}"#).is_err());
assert!(parse_action(r#"{"action":"install_package","atom":"app/--evil"}"#).is_err());
// The AI plan parser runs this same `validate` (covered in
// `phoebus-ai::assistant::tests`).
}
#[test]
fn case_insensitive_prefix_never_panics_on_multibyte() {
assert_eq!(
strip_prefix_ascii_ci("FLATPAK install x", "flatpak "),
Some("install x")
);
assert_eq!(strip_prefix_ascii_ci("notaflatpak", "flatpak "), None);
// The split point lands inside a multibyte character: no panic.
assert_eq!(strip_prefix_ascii_ci("aaa€€", "flatpak "), None);
assert_eq!(parse_natural("aaa€€ install x"), None);
}
#[test]
fn natural_flatpak_nix_and_snapshot_phrases() {
// Flatpak app ids are case-sensitive and must survive parsing.
assert_eq!(
parse_natural("flatpak install org.chromium.Chromium"),
Some(SystemAction::FlatpakInstall {
app_id: "org.chromium.Chromium".into()
})
);
assert_eq!(
parse_natural("flatpak remove org.chromium.Chromium"),
Some(SystemAction::FlatpakRemove {
app_id: "org.chromium.Chromium".into()
})
);
assert_eq!(
parse_natural("flatpak list"),
Some(SystemAction::FlatpakList)
);
assert_eq!(
parse_natural("nix prepare nodejs python312"),
Some(SystemAction::NixPrepare {
packages: vec!["nodejs".into(), "python312".into()]
})
);
assert_eq!(
parse_natural("snapshot before update"),
Some(SystemAction::CreateSnapshot {
operation: "before update".into()
})
);
assert_eq!(
parse_natural("snapshot"),
Some(SystemAction::CreateSnapshot {
operation: "manual snapshot".into()
})
);
}
} }

View file

@ -59,6 +59,12 @@ pub struct ResolvedPlan {
pub consequences: Vec<String>, pub consequences: Vec<String>,
/// Stable digest of the effect list, used to bind approval to the review. /// Stable digest of the effect list, used to bind approval to the review.
pub digest: String, pub digest: String,
/// Whether the effect set was actually established from the package
/// manager. A genuinely empty plan (`0 packages`) is `true` with no
/// effects; output that could not be recognised is `false`, and callers
/// must refuse to proceed rather than treat it as "nothing to do".
#[serde(default)]
pub established: bool,
} }
impl ResolvedPlan { impl ResolvedPlan {
@ -276,6 +282,12 @@ pub fn parse_emerge_pretend(text: &str) -> ResolvedPlan {
source, source,
}); });
} }
// Distinguish a real "0 packages" plan from output we could not parse. A
// Portage pretend run always prints a recognisable header or totals line.
plan.established = !plan.effects.is_empty()
|| text.contains("These are the packages that would be merged")
|| text.contains("Calculating dependencies")
|| text.lines().any(|l| l.trim_start().starts_with("Total:"));
plan.download_bytes = parse_download_bytes(text); plan.download_bytes = parse_download_bytes(text);
if plan.removals() > 0 { if plan.removals() > 0 {
plan.consequences plan.consequences
@ -368,12 +380,29 @@ Total: 5 packages (2 upgrades, 2 new, 1 uninstall), Size of downloads: 10,240 Ki
fn empty_output_is_a_no_change_plan() { fn empty_output_is_a_no_change_plan() {
let plan = parse_emerge_pretend("Calculating dependencies... done!\n\nTotal: 0 packages\n"); let plan = parse_emerge_pretend("Calculating dependencies... done!\n\nTotal: 0 packages\n");
assert!(plan.effects.is_empty()); assert!(plan.effects.is_empty());
assert!(plan.established, "a real 0-package plan is established");
assert_eq!(plan.additions(), 0); assert_eq!(plan.additions(), 0);
assert!(plan.render().contains("no package changes")); assert!(plan.render().contains("no package changes"));
// The digest is still defined. // The digest is still defined.
assert_eq!(plan.digest.len(), 64); assert_eq!(plan.digest.len(), 64);
} }
#[test]
fn unparseable_output_is_not_an_empty_plan() {
// A genuinely empty plan and output we cannot parse must be
// distinguishable: the latter has `established == false`.
let garbage = parse_emerge_pretend("something went sideways\nno totals here\n");
assert!(garbage.effects.is_empty());
assert!(
!garbage.established,
"unrecognised output must not masquerade as 0 packages"
);
let real = parse_emerge_pretend(PRETEND);
assert!(real.established);
assert!(!real.effects.is_empty());
}
#[test] #[test]
fn render_states_source_binary_and_consequences() { fn render_states_source_binary_and_consequences() {
let plan = parse_emerge_pretend(PRETEND); let plan = parse_emerge_pretend(PRETEND);

View file

@ -18,7 +18,7 @@ pub struct TransactionRecord {
pub origin: String, pub origin: String,
/// A short human-readable summary. /// A short human-readable summary.
pub summary: String, pub summary: String,
/// The validated typed actions, rendered. /// The validated typed actions that were attempted, rendered.
pub actions: Vec<String>, pub actions: Vec<String>,
/// `ok` or a failure description. /// `ok` or a failure description.
pub result: String, pub result: String,
@ -26,6 +26,54 @@ pub struct TransactionRecord {
pub snapshot: Option<String>, pub snapshot: Option<String>,
/// The reviewed plan digest, when effects were resolved. /// The reviewed plan digest, when effects were resolved.
pub digest: Option<String>, pub digest: Option<String>,
/// Per-action outcomes in execution order: what completed, what failed and
/// what was never attempted (because an earlier action aborted the plan).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub outcomes: Vec<TransactionOutcome>,
}
/// The status of one action within a recorded transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionStatus {
Completed,
Failed,
Unattempted,
}
/// One action's outcome. `detail` carries the failure reason for `failed`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionOutcome {
pub action: String,
pub status: ActionStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
impl TransactionOutcome {
pub fn completed(action: impl Into<String>) -> Self {
Self {
action: action.into(),
status: ActionStatus::Completed,
detail: None,
}
}
pub fn failed(action: impl Into<String>, detail: impl Into<String>) -> Self {
Self {
action: action.into(),
status: ActionStatus::Failed,
detail: Some(detail.into()),
}
}
pub fn unattempted(action: impl Into<String>) -> Self {
Self {
action: action.into(),
status: ActionStatus::Unattempted,
detail: None,
}
}
} }
impl Default for TransactionRecord { impl Default for TransactionRecord {
@ -38,10 +86,28 @@ impl Default for TransactionRecord {
result: "ok".into(), result: "ok".into(),
snapshot: None, snapshot: None,
digest: None, digest: None,
outcomes: Vec::new(),
} }
} }
} }
impl TransactionRecord {
/// `(completed, failed, unattempted)` counts for the recorded outcomes.
pub fn outcome_counts(&self) -> (usize, usize, usize) {
let mut completed = 0;
let mut failed = 0;
let mut unattempted = 0;
for outcome in &self.outcomes {
match outcome.status {
ActionStatus::Completed => completed += 1,
ActionStatus::Failed => failed += 1,
ActionStatus::Unattempted => unattempted += 1,
}
}
(completed, failed, unattempted)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)] #[serde(default)]
pub struct TransactionLog { pub struct TransactionLog {
@ -92,7 +158,20 @@ impl TransactionLog {
if let Some(snap) = &r.snapshot { if let Some(snap) = &r.snapshot {
out.push_str(&format!(" [snapshot {snap}]")); out.push_str(&format!(" [snapshot {snap}]"));
} }
if !r.outcomes.is_empty() {
let (done, failed, skipped) = r.outcome_counts();
out.push_str(&format!(
" [{done} completed, {failed} failed, {skipped} unattempted]"
));
}
out.push('\n'); out.push('\n');
for outcome in &r.outcomes {
out.push_str(&format!(" - {:?} {}", outcome.status, outcome.action));
if let Some(detail) = &outcome.detail {
out.push_str(&format!(": {detail}"));
}
out.push('\n');
}
} }
out out
} }
@ -115,6 +194,7 @@ mod tests {
result: "ok".into(), result: "ok".into(),
snapshot: Some("@-x".into()), snapshot: Some("@-x".into()),
digest: Some("abc".into()), digest: Some("abc".into()),
outcomes: Vec::new(),
}); });
log.save(&path).unwrap(); log.save(&path).unwrap();
let loaded = TransactionLog::load(&path).unwrap(); let loaded = TransactionLog::load(&path).unwrap();
@ -135,6 +215,50 @@ mod tests {
assert!(TransactionLog::load(&path).is_err()); assert!(TransactionLog::load(&path).is_err());
} }
#[test]
fn outcomes_roundtrip_and_render() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("transactions.toml");
let mut log = TransactionLog::default();
log.append(TransactionRecord {
created_unix: 20,
origin: "assistant".into(),
summary: "install two".into(),
actions: vec!["install package a".into(), "install package b".into()],
result: "failed: boom".into(),
snapshot: Some("@-snap".into()),
digest: None,
outcomes: vec![
TransactionOutcome::completed("install package a"),
TransactionOutcome::failed("install package b", "boom"),
TransactionOutcome::unattempted("enable service c"),
],
});
log.save(&path).unwrap();
let loaded = TransactionLog::load(&path).unwrap();
assert_eq!(loaded, log);
assert_eq!(loaded.records[0].outcome_counts(), (1, 1, 1));
let text = loaded.render();
assert!(text.contains("1 completed, 1 failed, 1 unattempted"));
assert!(text.contains("Unattempted"));
}
#[test]
fn records_without_outcomes_still_load() {
// Backward compatibility: an older log has no `outcomes` key.
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("old.toml");
std::fs::write(
&path,
"[[records]]\ncreated_unix = 1\norigin = \"sys\"\nsummary = \"x\"\nresult = \"ok\"\n",
)
.unwrap();
let log = TransactionLog::load(&path).unwrap();
assert_eq!(log.records.len(), 1);
assert!(log.records[0].outcomes.is_empty());
assert_eq!(log.records[0].outcome_counts(), (0, 0, 0));
}
#[test] #[test]
fn log_is_bounded() { fn log_is_bounded() {
let mut log = TransactionLog::default(); let mut log = TransactionLog::default();

View file

@ -7,11 +7,13 @@ use std::path::Path;
use phoebus_core::action::SystemAction; use phoebus_core::action::SystemAction;
use phoebus_core::effects::{changed_materially, parse_emerge_pretend, ResolvedPlan}; use phoebus_core::effects::{changed_materially, parse_emerge_pretend, ResolvedPlan};
use phoebus_core::transaction::TransactionOutcome;
use crate::auth::DestructiveAuthorization; use crate::auth::DestructiveAuthorization;
use crate::command::CommandSpec; use crate::command::{CommandOutput, CommandSpec};
use crate::error::{ExecError, Result}; use crate::error::{ExecError, Result};
use crate::exec::Exec; use crate::exec::Exec;
use crate::portage;
use crate::snapshot; use crate::snapshot;
#[derive(Debug)] #[derive(Debug)]
@ -33,17 +35,105 @@ pub fn preview(action: &SystemAction) -> String {
out out
} }
/// Whether the command acts on the running system (`/`) rather than a mounted
/// alternate target.
fn is_host_root(root: &Path) -> bool {
root == Path::new("/")
}
/// Build a command that acts on the intended system: directly for the running
/// root, or inside the target chroot for an alternate root. This is the single
/// place package, service and Flatpak commands are rooted, so preview and
/// execution always target the same system.
fn target_spec(
root: &Path,
stage: &str,
operation: &str,
program: &str,
args: &[String],
) -> CommandSpec {
if is_host_root(root) {
CommandSpec::new(stage, operation, program).args(args.iter().cloned())
} else {
portage::chroot_spec(stage, operation, root, program, args)
}
}
/// Refuse an operation that genuinely needs the running system (e.g. service
/// status, start, stop, restart) when an alternate root was requested. This
/// runs before any command is built, so nothing is invoked against the host.
fn require_host_root(root: &Path, operation: &str) -> Result<()> {
if is_host_root(root) {
Ok(())
} else {
Err(ExecError::operation(
"sys",
operation,
format!(
"cannot target the alternate root {}; this operation needs the \
running system",
root.display()
),
))
}
}
/// Run a mutating command against the intended system.
fn run_in_target(
exec: &Exec,
root: &Path,
stage: &str,
operation: &str,
program: &str,
args: &[String],
) -> Result<CommandOutput> {
exec.run(target_spec(root, stage, operation, program, args))
}
/// Capture a read-only command against the intended system. Output is returned
/// regardless of exit status (inspection commands report state, not failure).
fn capture_in_target(
exec: &Exec,
root: &Path,
stage: &str,
operation: &str,
program: &str,
args: &[String],
) -> Result<CommandOutput> {
exec.runner
.execute(&target_spec(root, stage, operation, program, args))
}
/// `systemctl` for boot enable/disable. On the host it acts on PID 1; on an
/// alternate root it uses `--root`, which only writes symlinks under the
/// target, so the host's service state is never touched.
fn systemctl_spec(root: &Path, operation: &str, verb: &str, name: &str) -> CommandSpec {
if is_host_root(root) {
CommandSpec::new("sys", operation, "systemctl").args([verb, name])
} else {
CommandSpec::new("sys", operation, "systemctl")
.arg("--root")
.arg(root.to_string_lossy().to_string())
.arg(verb)
.arg(name)
}
}
/// The Portage arguments that produce a resolved pretend plan for an action, /// The Portage arguments that produce a resolved pretend plan for an action,
/// or `None` when the action is not a Portage transaction. /// or `None` when the action is not a Portage transaction.
fn pretend_args(action: &SystemAction) -> Option<Vec<String>> { fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
match action { match action {
SystemAction::InstallPackage { atom } => { SystemAction::InstallPackage { atom } => Some(vec![
Some(vec!["--pretend".into(), "--color=n".into(), atom.clone()]) "--pretend".into(),
} "--color=n".into(),
"--".into(),
atom.clone(),
]),
SystemAction::RemovePackage { atom } => Some(vec![ SystemAction::RemovePackage { atom } => Some(vec![
"--pretend".into(), "--pretend".into(),
"--unmerge".into(), "--unmerge".into(),
"--color=n".into(), "--color=n".into(),
"--".into(),
atom.clone(), atom.clone(),
]), ]),
SystemAction::UpdateSystem => Some(vec![ SystemAction::UpdateSystem => Some(vec![
@ -52,6 +142,7 @@ fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
"--deep".into(), "--deep".into(),
"--newuse".into(), "--newuse".into(),
"--color=n".into(), "--color=n".into(),
"--".into(),
"@world".into(), "@world".into(),
]), ]),
_ => None, _ => None,
@ -61,17 +152,25 @@ fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
/// Resolve exactly what a package action will do. Non-Portage actions yield an /// Resolve exactly what a package action will do. Non-Portage actions yield an
/// empty plan. A plan's digest can be bound to an approval. /// empty plan. A plan's digest can be bound to an approval.
pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Result<ResolvedPlan> { pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Result<ResolvedPlan> {
action
.validate()
.map_err(|e| ExecError::operation("sys", "validate action", e))?;
let Some(args) = pretend_args(action) else { let Some(args) = pretend_args(action) else {
return Ok(ResolvedPlan::default()); return Ok(ResolvedPlan::default());
}; };
let out = if root == Path::new("/") { // Same rooting as execution, so the reviewed plan describes the action that
exec.run_capture(CommandSpec::new("sys", "resolve effects", "emerge").args(args))? // will actually run.
} else { let spec = target_spec(root, "sys", "resolve effects", "emerge", &args);
let mut chroot_args = vec![root.to_string_lossy().to_string(), "emerge".to_string()]; let out = exec.run_capture(spec)?;
chroot_args.extend(args);
exec.run_capture(CommandSpec::new("sys", "resolve effects", "chroot").args(chroot_args))?
};
let mut plan = parse_emerge_pretend(&out.stdout_lossy()); let mut plan = parse_emerge_pretend(&out.stdout_lossy());
if !plan.established {
return Err(ExecError::operation(
"sys",
"resolve effects",
"could not establish the package plan from emerge --pretend; \
refusing to proceed unreviewed",
));
}
if root.join(snapshot::SNAPSHOT_DIR).is_dir() { if root.join(snapshot::SNAPSHOT_DIR).is_dir() {
plan.recovery_point = Some("a protective snapshot before the change".into()); plan.recovery_point = Some("a protective snapshot before the change".into());
} }
@ -105,12 +204,75 @@ pub fn execute_checked(
execute(exec, action, auth, root) execute(exec, action, auth, root)
} }
/// The result of running a reviewed multi-action plan.
#[derive(Debug, Default)]
pub struct PlanOutcome {
/// `(action, output)` for actions that completed, in execution order.
pub completed: Vec<(String, String)>,
/// `(action, error)` for the action that failed, if any.
pub failure: Option<(String, String)>,
/// Every action's status in order, including the ones never attempted
/// because an earlier action aborted the plan.
pub outcomes: Vec<TransactionOutcome>,
/// The most recent protective snapshot reported by an action.
pub snapshot: Option<String>,
}
/// Execute a reviewed plan action by action, stopping at the first failure and
/// recording later actions as unattempted. This is the single execution path
/// shared by the assistant and any multi-step caller, so partial failure is
/// reported truthfully rather than as success.
pub fn execute_plan(
exec: &Exec,
steps: &[(SystemAction, ResolvedPlan)],
auth: Option<&DestructiveAuthorization>,
root: &Path,
) -> PlanOutcome {
let mut outcome = PlanOutcome::default();
for (action, resolved) in steps {
let described = action.describe();
if outcome.failure.is_some() {
outcome
.outcomes
.push(TransactionOutcome::unattempted(described));
continue;
}
match execute_checked(exec, action, auth, root, Some(resolved)) {
Ok(result) => {
if result.snapshot.is_some() {
outcome.snapshot = result.snapshot;
}
outcome
.outcomes
.push(TransactionOutcome::completed(described.clone()));
outcome.completed.push((described, result.output));
}
Err(e) => {
let detail = e.to_string();
outcome.outcomes.push(TransactionOutcome::failed(
described.clone(),
detail.clone(),
));
outcome.failure = Some((described, detail));
}
}
}
outcome
}
pub fn execute( pub fn execute(
exec: &Exec, exec: &Exec,
action: &SystemAction, action: &SystemAction,
auth: Option<&DestructiveAuthorization>, auth: Option<&DestructiveAuthorization>,
root: &Path, root: &Path,
) -> Result<ActionOutcome> { ) -> Result<ActionOutcome> {
// The execution boundary validates every action regardless of its source
// (manual phrase, JSON, or AI plan), so an invalid value can never reach a
// command.
action
.validate()
.map_err(|e| ExecError::operation("sys", "validate action", e))?;
if action.is_mutating() && auth.is_none() { if action.is_mutating() && auth.is_none() {
return Err(ExecError::NotAuthorized(action.describe())); return Err(ExecError::NotAuthorized(action.describe()));
} }
@ -136,14 +298,22 @@ pub fn execute(
}); });
} }
let mut snapshot_id = None;
// A protective snapshot must exist before a high-risk change. If the // A protective snapshot must exist before a high-risk change. If the
// snapshots subvolume is present but the snapshot cannot be created, fail // snapshots subvolume is present but the snapshot cannot be created, fail
// closed rather than proceed without a recovery point. A system without a // closed rather than proceed without a recovery point. A system without a
// `.snapshots` subvolume (e.g. a non-Btrfs root) is a warning, not a block. // `.snapshots` subvolume (e.g. a non-Btrfs root) is a warning, not a block.
// The snapshot source is the target root itself, so an alternate root
// snapshots the target, never the host.
if action.risk() == phoebus_core::action::Risk::High && !exec.dry_run { if action.risk() == phoebus_core::action::Risk::High && !exec.dry_run {
if root.join(snapshot::SNAPSHOT_DIR).is_dir() { if root.join(snapshot::SNAPSHOT_DIR).is_dir() {
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?; let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
snapshot::create_and_record(exec, auth, root, "/", &action.describe())?; let source = root.to_string_lossy().to_string();
let record =
snapshot::create_and_record(exec, auth, root, &source, &action.describe())?;
// Preserve the recovery point so callers can record it.
snapshot_id = Some(record.id);
} else { } else {
exec.logger.warn(format!( exec.logger.warn(format!(
"no {}/ subvolume; proceeding without a protective snapshot", "no {}/ subvolume; proceeding without a protective snapshot",
@ -152,82 +322,147 @@ pub fn execute(
} }
} }
let mut snapshot_id = None;
let output = match action { let output = match action {
SystemAction::InspectService { name } => { SystemAction::InspectService { name } => {
let out = exec.runner.execute( require_host_root(root, "inspect service")?;
&CommandSpec::new("sys", "inspect service", "systemctl").args([ let out = capture_in_target(
"status", exec,
name, root,
"--no-pager", "sys",
]), "inspect service",
"systemctl",
&["status".into(), name.clone(), "--no-pager".into()],
)?; )?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
} }
SystemAction::EnableService { name } => { SystemAction::EnableService { name } => {
exec.run( let spec = systemctl_spec(root, "enable service", "enable", name);
CommandSpec::new("sys", "enable service", "systemctl").args(["enable", name]), exec.run(spec)?;
)?;
format!("enabled {name}") format!("enabled {name}")
} }
SystemAction::DisableService { name } => { SystemAction::DisableService { name } => {
exec.run( let spec = systemctl_spec(root, "disable service", "disable", name);
CommandSpec::new("sys", "disable service", "systemctl").args(["disable", name]), exec.run(spec)?;
)?;
format!("disabled {name}") format!("disabled {name}")
} }
SystemAction::StartService { name } => {
require_host_root(root, "start service")?;
let spec = systemctl_spec(root, "start service", "start", name);
exec.run(spec)?;
format!("started {name}")
}
SystemAction::StopService { name } => {
require_host_root(root, "stop service")?;
let spec = systemctl_spec(root, "stop service", "stop", name);
exec.run(spec)?;
format!("stopped {name}")
}
SystemAction::RestartService { name } => {
require_host_root(root, "restart service")?;
let spec = systemctl_spec(root, "restart service", "restart", name);
exec.run(spec)?;
format!("restarted {name}")
}
SystemAction::InspectPackage { atom } => { SystemAction::InspectPackage { atom } => {
let out = exec.runner.execute( let out = capture_in_target(
&CommandSpec::new("sys", "inspect package", "emerge").args([ exec,
"--pretend", root,
"--quiet", "sys",
atom, "inspect package",
]), "emerge",
&[
"--pretend".into(),
"--quiet".into(),
"--".into(),
atom.clone(),
],
)?; )?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
} }
SystemAction::InstallPackage { atom } => { SystemAction::InstallPackage { atom } => {
// Portage resolves a bare name (`vim`) or a full atom. // Portage resolves a bare name (`vim`) or a full atom.
exec.run(CommandSpec::new("sys", "install package", "emerge").args(["--ask=n", atom]))?; run_in_target(
exec,
root,
"sys",
"install package",
"emerge",
&["--ask=n".into(), "--".into(), atom.clone()],
)?;
format!("installed {atom} (Portage)") format!("installed {atom} (Portage)")
} }
SystemAction::RemovePackage { atom } => { SystemAction::RemovePackage { atom } => {
exec.run(CommandSpec::new("sys", "remove package", "emerge").args([ run_in_target(
"--unmerge", exec,
"--ask=n", root,
atom, "sys",
]))?; "remove package",
"emerge",
&[
"--unmerge".into(),
"--ask=n".into(),
"--".into(),
atom.clone(),
],
)?;
format!("removed {atom} (Portage)") format!("removed {atom} (Portage)")
} }
SystemAction::SearchPackages { query } => { SystemAction::SearchPackages { query } => {
let out = exec.runner.execute( let out = capture_in_target(
&CommandSpec::new("sys", "search packages", "emerge") exec,
.args(["--search", "--quiet", query]), root,
"sys",
"search packages",
"emerge",
&[
"--search".into(),
"--quiet".into(),
"--".into(),
query.clone(),
],
)?; )?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
} }
SystemAction::FlatpakInstall { app_id } => { SystemAction::FlatpakInstall { app_id } => {
exec.run( run_in_target(
CommandSpec::new("sys", "install flatpak", "flatpak") exec,
.args(["install", "-y", "flathub", app_id]), root,
"sys",
"install flatpak",
"flatpak",
&[
"install".into(),
"-y".into(),
"--".into(),
"flathub".into(),
app_id.clone(),
],
)?; )?;
format!("installed Flatpak app {app_id}") format!("installed Flatpak app {app_id}")
} }
SystemAction::FlatpakRemove { app_id } => { SystemAction::FlatpakRemove { app_id } => {
exec.run(CommandSpec::new("sys", "remove flatpak", "flatpak").args([ run_in_target(
"uninstall", exec,
"-y", root,
app_id, "sys",
]))?; "remove flatpak",
"flatpak",
&["uninstall".into(), "-y".into(), "--".into(), app_id.clone()],
)?;
format!("removed Flatpak app {app_id}") format!("removed Flatpak app {app_id}")
} }
SystemAction::FlatpakList => { SystemAction::FlatpakList => {
let out = exec.runner.execute( let out = capture_in_target(
&CommandSpec::new("sys", "list flatpaks", "flatpak").args([ exec,
"list", root,
"--app", "sys",
"--columns=application,version,branch", "list flatpaks",
]), "flatpak",
&[
"list".into(),
"--app".into(),
"--columns=application,version,branch".into(),
],
)?; )?;
let text = format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()); let text = format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy());
if text.trim().is_empty() { if text.trim().is_empty() {
@ -241,15 +476,26 @@ pub fn execute(
format!("realised Nix development packages: {}", prepared.join(", ")) format!("realised Nix development packages: {}", prepared.join(", "))
} }
SystemAction::UpdateSystem => { SystemAction::UpdateSystem => {
exec.run( run_in_target(
CommandSpec::new("sys", "update system", "emerge") exec,
.args(["--update", "--deep", "--newuse", "@world"]), root,
"sys",
"update system",
"emerge",
&[
"--update".into(),
"--deep".into(),
"--newuse".into(),
"--".into(),
"@world".into(),
],
)?; )?;
"system update complete".to_string() "system update complete".to_string()
} }
SystemAction::CreateSnapshot { operation } => { SystemAction::CreateSnapshot { operation } => {
let auth = auth.expect("mutating action has auth"); let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
let record = snapshot::create_and_record(exec, auth, root, "/", operation)?; let source = root.to_string_lossy().to_string();
let record = snapshot::create_and_record(exec, auth, root, &source, operation)?;
snapshot_id = Some(record.id.clone()); snapshot_id = Some(record.id.clone());
format!("snapshot created: {}", record.id) format!("snapshot created: {}", record.id)
} }
@ -311,7 +557,27 @@ mod tests {
use super::*; use super::*;
use crate::command::RecordingRunner; use crate::command::RecordingRunner;
use crate::log::Logger; use crate::log::Logger;
use phoebus_core::transaction::ActionStatus;
use phoebus_core::Redactor; use phoebus_core::Redactor;
use std::time::Duration;
const PRETEND_VIM: &str = "\
These are the packages that would be merged, in order:
Calculating dependencies... done!
[ebuild N ] app-editors/vim-9.1.0
Total: 1 package (1 new), Size of downloads: 1,024 KiB
";
const PRETEND_WGET: &str = "\
These are the packages that would be merged, in order:
Calculating dependencies... done!
[ebuild N ] net-misc/wget-1.24.5
Total: 1 package (1 new), Size of downloads: 512 KiB
";
fn make_exec(runner: RecordingRunner) -> Exec { fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep(); let path = tempfile::tempdir().unwrap().keep();
@ -319,6 +585,27 @@ mod tests {
Exec::new(Box::new(runner), logger, false, path.join("root"), path) Exec::new(Box::new(runner), logger, false, path.join("root"), path)
} }
fn auth() -> DestructiveAuthorization {
crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap()
}
fn response(stdout: &str) -> CommandOutput {
CommandOutput {
status: 0,
success: true,
stdout: stdout.as_bytes().to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
}
}
fn emerge_calls(specs: &[CommandSpec]) -> Vec<&CommandSpec> {
specs
.iter()
.filter(|s| s.program == "emerge" || s.args.iter().any(|a| a == "emerge"))
.collect()
}
#[test] #[test]
fn mutating_action_requires_authorization() { fn mutating_action_requires_authorization() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
@ -345,7 +632,7 @@ mod tests {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
let exec = make_exec(runner.clone()); let exec = make_exec(runner.clone());
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap(); std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); let auth = auth();
execute( execute(
&exec, &exec,
&SystemAction::UpdateSystem, &SystemAction::UpdateSystem,
@ -353,25 +640,46 @@ mod tests {
Path::new(&exec.root), Path::new(&exec.root),
) )
.unwrap(); .unwrap();
let programs = runner.programs(); let specs = runner.recorded();
let btrfs = programs let btrfs = specs
.iter() .iter()
.position(|p| p == "btrfs") .position(|s| s.program == "btrfs")
.expect("snapshot"); .expect("snapshot");
let emerge = programs.iter().position(|p| p == "emerge").expect("emerge"); let emerge = specs
.iter()
.position(|s| s.program == "emerge" || s.args.iter().any(|a| a == "emerge"))
.expect("emerge");
assert!( assert!(
btrfs < emerge, btrfs < emerge,
"protective snapshot must precede the mutation: {programs:?}" "protective snapshot must precede the mutation: {:?}",
runner.programs()
); );
} }
#[test]
fn protective_snapshot_id_is_preserved_in_the_outcome() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
let auth = auth();
let outcome = execute(
&exec,
&SystemAction::UpdateSystem,
Some(&auth),
Path::new(&exec.root),
)
.unwrap();
// The generic protective-snapshot path must report its id, not drop it.
assert!(outcome.snapshot.is_some(), "protective snapshot id lost");
}
#[test] #[test]
fn high_risk_action_aborts_when_protective_snapshot_fails() { fn high_risk_action_aborts_when_protective_snapshot_fails() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
runner.fail("btrfs", "snapshot failed"); runner.fail("btrfs", "snapshot failed");
let exec = make_exec(runner.clone()); let exec = make_exec(runner.clone());
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap(); std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); let auth = auth();
let err = execute( let err = execute(
&exec, &exec,
&SystemAction::UpdateSystem, &SystemAction::UpdateSystem,
@ -402,13 +710,15 @@ mod tests {
fn remove_package_builds_unmerge() { fn remove_package_builds_unmerge() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
let exec = make_exec(runner.clone()); let exec = make_exec(runner.clone());
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); let auth = auth();
let action = SystemAction::RemovePackage { atom: "vim".into() }; let action = SystemAction::RemovePackage { atom: "vim".into() };
execute(&exec, &action, Some(&auth), Path::new(&exec.root)).unwrap(); execute(&exec, &action, Some(&auth), Path::new(&exec.root)).unwrap();
let spec = &runner.recorded()[0]; let recorded = runner.recorded();
assert_eq!(spec.program, "emerge"); let spec = emerge_calls(&recorded)[0];
assert!(spec.args.contains(&"--unmerge".to_string())); assert!(spec.args.contains(&"--unmerge".to_string()));
assert!(spec.args.contains(&"vim".to_string())); assert!(spec.args.contains(&"vim".to_string()));
// The operand follows the option terminator.
assert!(spec.args.windows(2).any(|w| w[0] == "--" && w[1] == "vim"));
} }
#[test] #[test]
@ -419,26 +729,232 @@ mod tests {
query: "firefox".into(), query: "firefox".into(),
}; };
execute(&exec, &action, None, Path::new(&exec.root)).unwrap(); execute(&exec, &action, None, Path::new(&exec.root)).unwrap();
let spec = &runner.recorded()[0]; let recorded = runner.recorded();
assert_eq!(spec.program, "emerge"); let spec = emerge_calls(&recorded)[0];
assert!(spec.args.contains(&"--search".to_string())); assert!(spec.args.contains(&"--search".to_string()));
assert!(spec.args.contains(&"firefox".to_string())); assert!(spec.args.contains(&"firefox".to_string()));
assert!(spec
.args
.windows(2)
.any(|w| w[0] == "--" && w[1] == "firefox"));
} }
#[test] #[test]
fn enable_builds_separate_arguments() { fn enable_builds_separate_arguments() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
let exec = make_exec(runner.clone()); let exec = make_exec(runner.clone());
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let action = SystemAction::EnableService { let action = SystemAction::EnableService {
name: "sshd".into(), name: "sshd".into(),
}; };
execute(&exec, &action, Some(&auth), Path::new("/")).unwrap(); execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap();
let spec = &runner.recorded()[0]; let spec = &runner.recorded()[0];
assert_eq!(spec.program, "systemctl"); assert_eq!(spec.program, "systemctl");
assert_eq!(spec.args, vec!["enable", "sshd"]); assert_eq!(spec.args, vec!["enable", "sshd"]);
} }
#[test]
fn service_lifecycle_runs_on_the_host() {
for (action, verb) in [
(
SystemAction::StartService {
name: "sshd".into(),
},
"start",
),
(
SystemAction::StopService {
name: "sshd".into(),
},
"stop",
),
(
SystemAction::RestartService {
name: "sshd".into(),
},
"restart",
),
] {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap();
let spec = &runner.recorded()[0];
assert_eq!(spec.program, "systemctl");
assert_eq!(spec.args, vec![verb.to_string(), "sshd".to_string()]);
}
}
#[test]
fn service_enable_on_an_alternate_root_uses_root_flag() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let root = Path::new("/tmp/phoebus-alt");
execute(
&exec,
&SystemAction::EnableService {
name: "sshd".into(),
},
Some(&auth()),
root,
)
.unwrap();
let spec = &runner.recorded()[0];
assert_eq!(spec.program, "systemctl");
assert_eq!(
spec.args,
vec!["--root", "/tmp/phoebus-alt", "enable", "sshd"]
);
}
#[test]
fn runtime_service_operations_reject_an_alternate_root() {
let root = Path::new("/tmp/phoebus-alt");
for action in [
SystemAction::InspectService {
name: "sshd".into(),
},
SystemAction::StartService {
name: "sshd".into(),
},
SystemAction::StopService {
name: "sshd".into(),
},
SystemAction::RestartService {
name: "sshd".into(),
},
] {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let err = execute(&exec, &action, Some(&auth()), root).unwrap_err();
assert!(
err.to_string().contains("cannot target the alternate root"),
"got {err}"
);
// Nothing may be invoked against the host.
assert!(runner.recorded().is_empty(), "{:?}", runner.programs());
}
}
#[test]
fn preview_and_execution_use_the_same_alternate_root() {
let runner = RecordingRunner::new();
runner.set_response("chroot", response(PRETEND_VIM));
let exec = make_exec(runner.clone());
let root = Path::new("/mnt/phoebus-target");
let action = SystemAction::InstallPackage {
atom: "app-editors/vim".into(),
};
let plan = resolve_effects(&exec, &action, root).unwrap();
assert!(!plan.effects.is_empty());
let outcome = execute_checked(&exec, &action, Some(&auth()), root, Some(&plan)).unwrap();
assert!(outcome.output.contains("installed"));
let recorded = runner.recorded();
let calls = emerge_calls(&recorded);
assert!(calls.len() >= 2, "preview + execution: {:?}", calls);
for spec in calls {
assert_eq!(spec.program, "chroot", "execution escaped the target");
assert_eq!(spec.args[0], "/mnt/phoebus-target");
}
}
#[test]
fn execution_validates_before_any_command() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let action = SystemAction::InstallPackage {
atom: "--color=n".into(),
};
// The read path refuses too.
assert!(resolve_effects(&exec, &action, Path::new("/")).is_err());
let err = execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap_err();
assert!(err.to_string().contains("invalid"), "got {err}");
assert!(runner.recorded().is_empty());
}
#[test]
fn resolve_effects_refuses_unparseable_output() {
let runner = RecordingRunner::new();
runner.set_response("emerge", response("something went sideways\n"));
let exec = make_exec(runner.clone());
let action = SystemAction::InstallPackage {
atom: "app-editors/vim".into(),
};
let err = resolve_effects(&exec, &action, Path::new("/")).unwrap_err();
assert!(err.to_string().contains("could not establish"), "got {err}");
}
#[test]
fn resolve_effects_accepts_a_genuinely_empty_plan() {
let runner = RecordingRunner::new();
runner.set_response(
"emerge",
response("Calculating dependencies... done!\n\nTotal: 0 packages\n"),
);
let exec = make_exec(runner.clone());
let action = SystemAction::InstallPackage {
atom: "app-editors/vim".into(),
};
let plan = resolve_effects(&exec, &action, Path::new("/")).unwrap();
assert!(plan.effects.is_empty());
assert!(plan.established);
}
#[test]
fn a_material_change_invalidates_the_reviewed_plan() {
let runner = RecordingRunner::new();
runner.set_response("emerge", response(PRETEND_WGET));
let exec = make_exec(runner.clone());
let approved = phoebus_core::effects::parse_emerge_pretend(PRETEND_VIM);
let action = SystemAction::InstallPackage {
atom: "net-misc/wget".into(),
};
let err = execute_checked(
&exec,
&action,
Some(&auth()),
Path::new("/"),
Some(&approved),
)
.unwrap_err();
assert!(err.to_string().contains("plan changed"), "got {err}");
// The unapproved mutation must not run.
assert!(!runner
.recorded()
.iter()
.any(|s| s.args.iter().any(|a| a == "--ask=n")));
}
#[test]
fn plan_stops_at_the_first_failure_and_marks_the_rest_unattempted() {
let runner = RecordingRunner::new();
runner.fail("emerge", "boom");
let exec = make_exec(runner.clone());
let steps = vec![
(SystemAction::History, ResolvedPlan::default()),
(
SystemAction::InstallPackage {
atom: "app-editors/vim".into(),
},
ResolvedPlan::default(),
),
(
SystemAction::EnableService {
name: "sshd".into(),
},
ResolvedPlan::default(),
),
];
let run = execute_plan(&exec, &steps, Some(&auth()), Path::new("/"));
assert_eq!(run.completed.len(), 1);
assert!(run.failure.is_some());
assert_eq!(run.outcomes.len(), 3);
assert_eq!(run.outcomes[0].status, ActionStatus::Completed);
assert_eq!(run.outcomes[1].status, ActionStatus::Failed);
assert_eq!(run.outcomes[2].status, ActionStatus::Unattempted);
// The third action must never reach the system.
assert!(!runner.programs().iter().any(|p| p == "systemctl"));
}
#[test] #[test]
fn undo_requires_authorization() { fn undo_requires_authorization() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();

View file

@ -551,13 +551,21 @@ impl<'a> OpenCodeClient<'a> {
fn error_for(&self, action: &str, response: &HttpResponse) -> AiError { fn error_for(&self, action: &str, response: &HttpResponse) -> AiError {
let hint = match response.status { let hint = match response.status {
400 => "the server rejected the request (check the model id)".to_string(),
401 => "authentication required".to_string(), 401 => "authentication required".to_string(),
403 => "authentication rejected".to_string(), 403 => "authentication rejected".to_string(),
404 => "endpoint not found (incompatible server?)".to_string(), 404 => "endpoint not found (incompatible server?)".to_string(),
429 => "rate limited".to_string(), 429 => "rate limited".to_string(),
500..=599 => "the server returned an internal error (check that the model \
exists and the provider credentials are valid)"
.to_string(),
_ => format!("HTTP {}", response.status), _ => format!("HTTP {}", response.status),
}; };
AiError::Provider(format!("OpenCode {action} failed: {hint}")) // Name the provider:model so an invalid selection is obvious.
AiError::Provider(format!(
"OpenCode {action} failed for {}/{}: {hint}",
self.provider, self.model
))
} }
/// Fetch the provider/model catalog. Uses the metadata endpoint only. /// Fetch the provider/model catalog. Uses the metadata endpoint only.
@ -997,7 +1005,7 @@ mod tests {
(401u16, "authentication required"), (401u16, "authentication required"),
(403, "authentication rejected"), (403, "authentication rejected"),
(404, "not found"), (404, "not found"),
(500, "HTTP 500"), (500, "internal error"),
] { ] {
let http = FakeHttp::new(vec![FakeHttp::json(status, "{}")]); let http = FakeHttp::new(vec![FakeHttp::json(status, "{}")]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m"); let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");

View file

@ -87,7 +87,9 @@ pub fn select_profile(exec: &Exec, config: &InstallConfig) -> Result<()> {
Ok(()) Ok(())
} }
fn chroot_spec( /// Build a `chroot <root> env -i ... <program>` command. Shared with the `sys`
/// action broker so preview and execution target the same root.
pub(crate) fn chroot_spec(
stage: &str, stage: &str,
operation: &str, operation: &str,
root: &Path, root: &Path,

View file

@ -6,14 +6,14 @@
//! `--action-file`; it never receives a shell or the sudo password. //! `--action-file`; it never receives a shell or the sudo password.
use std::io::Write; use std::io::Write;
use std::path::PathBuf; 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::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::transaction::TransactionRecord; use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
use phoebus_core::{AiBackend, InstallConfig, Redactor}; use phoebus_core::{AiBackend, InstallConfig, Redactor};
use phoebus_executor::opencode_client::ExecOpenCodeTransport; use phoebus_executor::opencode_client::ExecOpenCodeTransport;
use phoebus_executor::{ use phoebus_executor::{
@ -114,6 +114,26 @@ impl Confirmation for SysConfirm {
} }
} }
fn now_unix() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
/// Append a transaction and make a recording failure visible instead of
/// silently claiming success. The system change (if any) has already happened,
/// so the message says so explicitly.
fn record_transaction(
exec: &Exec,
root: &Path,
record: TransactionRecord,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
transaction::append(exec, root, record).map_err(|e| {
format!("the action completed but its transaction could not be recorded: {e}").into()
})
}
fn effective_uid() -> u32 { fn effective_uid() -> u32 {
std::process::Command::new("id") std::process::Command::new("id")
.arg("-u") .arg("-u")
@ -222,6 +242,23 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
println!("protective snapshot: {id}"); println!("protective snapshot: {id}");
} }
println!("{}", outcome.output); println!("{}", outcome.output);
// Ordinary mutating commands are part of the same audited history as
// assistant actions, including their protective snapshot and outcome.
if action.is_mutating() {
let described = action.describe();
let record = TransactionRecord {
created_unix: now_unix(),
origin: "sys".into(),
summary: described.clone(),
actions: vec![described.clone()],
result: "ok".into(),
snapshot: outcome.snapshot.clone(),
digest: approved.as_ref().map(|p| p.digest.clone()),
outcomes: vec![TransactionOutcome::completed(described)],
};
record_transaction(&exec, &cli.root, record)?;
}
Ok(()) Ok(())
} }
@ -443,44 +480,45 @@ fn run_ask(
None None
}; };
let mut snapshot = None; // The reviewed plans and actions are executed through the shared,
let mut result = String::from("ok"); // failure-aware plan runner: it stops at the first failure and records the
let mut executed = Vec::new(); // remaining actions as unattempted.
for (action, resolved) in plan.actions.iter().zip(approved.iter()) { let digest = approved
match actions::execute_checked(exec, action, auth.as_ref(), &cli.root, Some(resolved)) { .iter()
Ok(outcome) => { .find(|p| !p.digest.is_empty())
if let Some(id) = &outcome.snapshot { .map(|p| p.digest.clone());
snapshot = Some(id.clone()); let steps: Vec<(SystemAction, phoebus_core::effects::ResolvedPlan)> =
} plan.actions.iter().cloned().zip(approved).collect();
executed.push(action.describe()); let run = actions::execute_plan(exec, &steps, auth.as_ref(), &cli.root);
println!("{}", outcome.output); for (_, output) in &run.completed {
} println!("{output}");
Err(e) => { }
result = format!("failed: {e}"); let mut attempted: Vec<String> = run.completed.iter().map(|(a, _)| a.clone()).collect();
executed.push(action.describe()); if let Some((action, detail)) = &run.failure {
eprintln!("action failed: {e}"); eprintln!("action failed: {action}: {detail}");
break; attempted.push(action.clone());
}
}
} }
let result = match &run.failure {
None => "ok".to_string(),
Some((action, detail)) => format!("failed: {action}: {detail}"),
};
let record = TransactionRecord { let record = TransactionRecord {
created_unix: std::time::SystemTime::now() created_unix: now_unix(),
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
origin: "assistant".into(), origin: "assistant".into(),
summary: plan.summary.clone(), summary: plan.summary.clone(),
actions: executed, actions: attempted,
result, result,
snapshot, snapshot: run.snapshot,
digest: approved digest,
.iter() outcomes: run.outcomes,
.find(|p| !p.digest.is_empty())
.map(|p| p.digest.clone()),
}; };
if let Err(e) = transaction::append(exec, &cli.root, record) { record_transaction(exec, &cli.root, record)?;
eprintln!("could not record the transaction: {e}");
// A plan that did not fully apply is a failure: nonzero exit, so scripts
// and the GUI cannot mistake it for success.
if let Some((action, detail)) = run.failure {
return Err(format!("the assistant plan did not complete: {action}: {detail}").into());
} }
Ok(()) Ok(())
} }

View file

@ -258,6 +258,8 @@ impl Bridge {
let op = request.op.clone(); let op = request.op.clone();
let result = match request.op.as_str() { let result = match request.op.as_str() {
"handshake" => self.handshake(), "handshake" => self.handshake(),
"options" => self.options(),
"ai_catalog" => self.ai_catalog(),
"disks" => self.disks(), "disks" => self.disks(),
"set_config" => self.set_config(&request), "set_config" => self.set_config(&request),
"set_secrets" => self.set_secrets(&request), "set_secrets" => self.set_secrets(&request),
@ -312,6 +314,109 @@ impl Bridge {
})) }))
} }
/// Selectable options for the language/region step. Reading these from the
/// live system means the user picks from the real timezones, locales and
/// keymaps instead of typing them from memory.
fn options(&self) -> Result<Value, String> {
Ok(json!({
"timezones": system_timezones(),
"locales": system_locales(),
"keymaps": system_keymaps(),
}))
}
/// The providers and models the configured AI connection actually offers:
/// the OpenCode catalog, or an OpenAI-compatible `/models` list. Read-only;
/// never returns provider credentials.
fn ai_catalog(&self) -> Result<Value, String> {
use phoebus_executor::opencode_client::{CurlHttpClient, HttpClient, OpenCodeClient};
use phoebus_executor::opencode_server::Endpoint;
let redact = self.installer.exec.redactor();
match self.installer.config.ai.backend {
AiBackend::OpenCode => {
// The catalog only needs the server; the model is optional.
let server = self.installer.config.ai.opencode_server.trim().to_string();
if server.is_empty() {
return Err("OpenCode requires a server URL".into());
}
let provider = self
.installer
.config
.ai
.opencode_provider
.trim()
.to_string();
let model = self.installer.config.ai.opencode_model.trim().to_string();
let endpoint = Endpoint::parse(&server)
.map_err(|e| format!("invalid OpenCode endpoint: {e}"))?;
let target = endpoint
.checked_target()
.map_err(|e| redact.redact(&e.to_string()))?;
let http = CurlHttpClient::new(&self.installer.exec);
// The provider catalog can be several MiB on a busy server.
let client = OpenCodeClient::new(&http, endpoint.base(), &provider, &model)
.with_auth(self.opencode_password.clone())
.with_max_body(16 * 1024 * 1024)
.with_resolve(Some((endpoint.host.clone(), endpoint.port, target.ip())));
match client.catalog() {
Ok(catalog) => {
let providers: Vec<Value> = catalog
.providers
.iter()
.map(
|p| json!({ "id": p.id, "name": p.name, "connected": p.connected }),
)
.collect();
let models = catalog
.providers
.iter()
.find(|p| p.id == provider)
.or_else(|| catalog.providers.iter().find(|p| !p.models.is_empty()))
.map(|p| p.models.clone())
.unwrap_or_default();
Ok(json!({
"backend": "opencode",
"providers": providers,
"models": models,
}))
}
Err(e) => Err(redact.redact(&e.to_string())),
}
}
AiBackend::Direct => {
let raw = self.installer.config.ai.provider.clone();
let provider = ProviderKind::parse(&raw)
.ok_or_else(|| format!("unknown AI provider `{raw}`"))?;
if provider == ProviderKind::None {
return Err("no AI provider selected".into());
}
let endpoint = if self.installer.config.ai.endpoint.is_empty() {
provider.endpoint().to_string()
} else {
self.installer.config.ai.endpoint.clone()
};
let url = models_url(&endpoint);
let mut request = phoebus_executor::opencode_client::HttpRequest::get(url);
request.auth_user = String::new(); // OpenAI-compatible: Bearer
request.auth = self.api_key.clone();
let http = CurlHttpClient::new(&self.installer.exec);
match http.request(&request) {
Ok(response) if response.is_success() => {
let models = parse_model_ids(&response.body);
Ok(json!({
"backend": "direct",
"providers": [ { "id": provider.as_str(), "name": provider.as_str(), "connected": true } ],
"models": models,
}))
}
Ok(response) => Err(format!("model list returned HTTP {}", response.status)),
Err(e) => Err(redact.redact(&e.to_string())),
}
}
}
}
fn disks(&mut self) -> Result<Value, String> { fn disks(&mut self) -> Result<Value, String> {
self.installer.disks = self.installer.disks =
phoebus_executor::probe::probe_disks(self.installer.exec.runner.as_ref()); phoebus_executor::probe::probe_disks(self.installer.exec.runner.as_ref());
@ -418,11 +523,15 @@ impl Bridge {
// backend concerns and not user-selectable from the GUI. // backend concerns and not user-selectable from the GUI.
config.runtime.dry_run = self.installer.config.runtime.dry_run; config.runtime.dry_run = self.installer.config.runtime.dry_run;
let ai_before = ai_digest(&self.installer.config);
self.installer.reconfigure(config); self.installer.reconfigure(config);
self.approved_digest = None; self.approved_digest = None;
// A configuration change (provider, model, endpoint, server) invalidates // Only a change to the AI connection settings invalidates the AI
// any previous AI validation. // validation. Choosing a disk, typing a hostname or similar must not
self.validated_ai = None; // throw away a successful model interaction.
if ai_digest(&self.installer.config) != ai_before {
self.validated_ai = None;
}
let issues = self.installer.validate(); let issues = self.installer.validate();
Ok(json!({ Ok(json!({
"accepted": true, "accepted": true,
@ -469,18 +578,24 @@ impl Bridge {
self.installer.exec.register_secret(&s); self.installer.exec.register_secret(&s);
self.root_password = Some(s); self.root_password = Some(s);
} }
let mut ai_credential_changed = false;
if let Some(v) = &patch.ai_api_key { if let Some(v) = &patch.ai_api_key {
let s = SecretString::new(v.clone()); let s = SecretString::new(v.clone());
self.installer.exec.register_secret(&s); self.installer.exec.register_secret(&s);
self.api_key = Some(s); self.api_key = Some(s);
ai_credential_changed = true;
} }
if let Some(v) = &patch.opencode_password { if let Some(v) = &patch.opencode_password {
let s = SecretString::new(v.clone()); let s = SecretString::new(v.clone());
self.installer.exec.register_secret(&s); self.installer.exec.register_secret(&s);
self.opencode_password = Some(s); self.opencode_password = Some(s);
ai_credential_changed = true;
}
// Only an AI credential change invalidates the AI validation; account
// and disk secrets do not.
if ai_credential_changed {
self.validated_ai = None;
} }
// A credential change invalidates any previous AI validation.
self.validated_ai = None;
// Report only presence, never values. // Report only presence, never values.
Ok(json!({ Ok(json!({
"luks_set": self.luks.is_some(), "luks_set": self.luks.is_some(),
@ -515,7 +630,7 @@ impl Bridge {
self.approved_digest = None; self.approved_digest = None;
// Bind the validated interaction to the exact configuration it was // Bind the validated interaction to the exact configuration it was
// validated against; any later change clears it. // validated against; any later change clears it.
self.validated_ai = Some(self.plan_digest()); self.validated_ai = Some(ai_digest(&self.installer.config));
Ok(value) Ok(value)
} }
@ -595,7 +710,7 @@ impl Bridge {
review_proposal(config, exec.redactor(), facts, api_key_present, transport)? review_proposal(config, exec.redactor(), facts, api_key_present, transport)?
}; };
self.approved_digest = None; self.approved_digest = None;
self.validated_ai = Some(self.plan_digest()); self.validated_ai = Some(ai_digest(&self.installer.config));
Ok(value) Ok(value)
} }
@ -667,7 +782,8 @@ impl Bridge {
let break_glass = std::env::var("PHOEBUS_NO_AI") let break_glass = std::env::var("PHOEBUS_NO_AI")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true")) .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
.unwrap_or(false); .unwrap_or(false);
let validated = self.validated_ai.as_deref() == Some(current.as_str()); let validated =
self.validated_ai.as_deref() == Some(ai_digest(&self.installer.config).as_str());
if !validated && !break_glass { if !validated && !break_glass {
return Err( return Err(
"installing Phoebus requires a successful, validated AI interaction for \ "installing Phoebus requires a successful, validated AI interaction for \
@ -881,6 +997,237 @@ fn opencode_parts(config: &InstallConfig) -> Result<(String, String, String), St
Ok((server, provider, model)) Ok((server, provider, model))
} }
/// Time zones offered by the live system, from the zoneinfo database.
fn system_timezones() -> Vec<String> {
let mut zones: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
if let Ok(text) = std::fs::read_to_string("/usr/share/zoneinfo/zone.tab") {
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some(tz) = line.split_whitespace().nth(2) {
zones.insert(tz.to_string());
}
}
}
if zones.is_empty() {
for zone in [
"UTC",
"Europe/London",
"Europe/Berlin",
"Europe/Paris",
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Los_Angeles",
"Asia/Tokyo",
"Asia/Shanghai",
"Asia/Kolkata",
"Australia/Sydney",
] {
zones.insert(zone.to_string());
}
}
zones.into_iter().take(2000).collect()
}
/// Locales from the system's i18n database (or a common fallback set).
fn system_locales() -> Vec<String> {
let mut locales: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
if let Ok(text) = std::fs::read_to_string("/usr/share/i18n/SUPPORTED") {
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some(locale) = line.split_whitespace().next() {
// Prefer UTF-8 variants; keep the rest too.
locales.insert(locale.to_string());
}
}
}
if locales.is_empty() {
for locale in [
"en_US.UTF-8",
"en_GB.UTF-8",
"de_DE.UTF-8",
"fr_FR.UTF-8",
"es_ES.UTF-8",
"it_IT.UTF-8",
"pt_BR.UTF-8",
"ja_JP.UTF-8",
"zh_CN.UTF-8",
] {
locales.insert(locale.to_string());
}
}
locales.into_iter().take(2000).collect()
}
/// Console keymaps from the system's keymap trees.
fn system_keymaps() -> Vec<String> {
let mut keymaps: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
for root in ["/usr/share/keymaps", "/usr/share/kbd/keymaps"] {
collect_keymaps(std::path::Path::new(root), &mut keymaps, 0);
}
if keymaps.is_empty() {
// The live medium does not always ship the kbd keymap tree, so fall
// back to the common console keymaps. The combo still accepts a
// custom value.
for name in [
"us",
"us-acentos",
"uk",
"gb",
"de",
"de-latin1",
"de-latin1-nodeadkeys",
"de-nodeadkeys",
"fr",
"fr-latin9",
"fr-latin1",
"fr-pc",
"es",
"es-cp850",
"it",
"it2",
"pt",
"pt-latin1",
"nl",
"nl2",
"be",
"dk",
"dk-latin1",
"no",
"no-latin1",
"se",
"fi",
"is",
"ie",
"ie-Gaelic",
"pl",
"pl2",
"cz",
"cz-us-qwertz",
"sk",
"hu",
"hu101",
"ro",
"bg",
"gr",
"gr-pc",
"ru",
"ruwin_alt-UTF-8",
"ua-utf",
"tr",
"trq",
"il",
"ara",
"in",
"jp106",
"kr",
"kr-utf",
"cn",
"tw",
"br-abnt2",
"latam",
"ca",
"cf",
"ch",
"ch-fr",
"at",
"si",
"hr",
"ee",
"lt",
"lv",
"mk",
"rs",
"by",
"kz",
"us-dvorak",
"dvorak",
"colemak",
"mac-us",
"sun-pl",
"sg",
"th",
"vn",
"fa",
"az",
"ge",
"am",
] {
keymaps.insert(name.to_string());
}
}
keymaps.into_iter().take(2000).collect()
}
fn collect_keymaps(
dir: &std::path::Path,
out: &mut std::collections::BTreeSet<String>,
depth: usize,
) {
if depth > 6 {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_keymaps(&path, out, depth + 1);
} else if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
for suffix in [".map.gz", ".map"] {
if let Some(stem) = name.strip_suffix(suffix) {
out.insert(stem.to_string());
}
}
}
}
}
/// The OpenAI-compatible model-list URL for a chat-completions endpoint.
fn models_url(endpoint: &str) -> String {
let trimmed = endpoint.trim().trim_end_matches('/');
if let Some(base) = trimmed.strip_suffix("/chat/completions") {
format!("{base}/models")
} else {
format!("{trimmed}/models")
}
}
/// Extract model ids from an OpenAI-compatible `/models` response.
fn parse_model_ids(body: &str) -> Vec<String> {
let mut ids: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
if let Ok(value) = serde_json::from_str::<Value>(body) {
if let Some(data) = value.get("data").and_then(|d| d.as_array()) {
for item in data {
if let Some(id) = item.get("id").and_then(|v| v.as_str()) {
ids.insert(id.to_string());
}
}
}
if ids.is_empty() {
if let Some(models) = value.get("models").and_then(|m| m.as_array()) {
for item in models {
if let Some(id) = item
.get("id")
.and_then(|v| v.as_str())
.or_else(|| item.get("name").and_then(|v| v.as_str()))
{
ids.insert(id.to_string());
}
}
}
}
}
ids.into_iter().collect()
}
fn opencode_transport<'a>( fn opencode_transport<'a>(
exec: &'a Exec, exec: &'a Exec,
config: &InstallConfig, config: &InstallConfig,
@ -961,6 +1308,29 @@ fn review_opencode(
) )
} }
/// A deterministic digest of only the AI connection settings. The mandatory-AI
/// validation is bound to this, so choosing a disk or typing an account
/// password does not discard a successful model interaction, while changing the
/// provider, model, endpoint or server does.
fn ai_digest(config: &InstallConfig) -> String {
use sha2::{Digest, Sha256};
let ai = &config.ai;
let mut hasher = Sha256::new();
for field in [
ai.backend.as_str(),
ai.provider.as_str(),
ai.model.as_str(),
ai.endpoint.as_str(),
ai.opencode_server.as_str(),
ai.opencode_provider.as_str(),
ai.opencode_model.as_str(),
] {
hasher.update(field.as_bytes());
hasher.update([0u8]);
}
format!("{:x}", hasher.finalize())
}
/// Parse the direct provider from the configuration, validate the connection /// Parse the direct provider from the configuration, validate the connection
/// and apply the reviewed proposal. This is the same `ai_guide` path the TUI /// and apply the reviewed proposal. This is the same `ai_guide` path the TUI
/// uses. /// uses.
@ -1598,6 +1968,68 @@ mod tests {
.contains("validated AI interaction")); .contains("validated AI interaction"));
} }
#[test]
fn a_non_ai_config_change_keeps_the_validated_interaction() {
// Choosing a disk or editing the account must not discard a successful
// model interaction: this was the bug that refused a fully-validated
// install at the final step.
let mut bridge = test_bridge_non_dry();
set_valid_config(&mut bridge);
arm_ai(&mut bridge);
let mut c = config_json(&bridge);
c["system"]["hostname"] = json!("renamed-box");
let _ = call(
&mut bridge,
&json!({ "id": 60, "op": "set_config", "config": c }).to_string(),
);
let (digest, _) = approve(&mut bridge);
let resp = start(&mut bridge, &digest);
assert!(
!resp["error"]
.as_str()
.unwrap_or("")
.contains("validated AI interaction"),
"a non-AI change wrongly invalidated the interaction: {}",
resp["error"]
);
}
#[test]
fn an_account_secret_does_not_invalidate_but_an_ai_key_does() {
let mut bridge = test_bridge_non_dry();
set_valid_config(&mut bridge);
arm_ai(&mut bridge);
let _ = call(
&mut bridge,
r#"{"id":61,"op":"set_secrets","secrets":{"user_password":"secret-pass-1","luks":"luks-pass-1234"}}"#,
);
let (digest, _) = approve(&mut bridge);
let resp = start(&mut bridge, &digest);
assert!(
!resp["error"]
.as_str()
.unwrap_or("")
.contains("validated AI interaction"),
"an account secret wrongly invalidated the interaction: {}",
resp["error"]
);
// A changed AI credential must invalidate it.
let mut bridge = test_bridge_non_dry();
set_valid_config(&mut bridge);
arm_ai(&mut bridge);
let _ = call(
&mut bridge,
r#"{"id":62,"op":"set_secrets","secrets":{"ai_api_key":"a-different-key"}}"#,
);
let (digest, _) = approve(&mut bridge);
let resp = start(&mut bridge, &digest);
assert!(resp["error"]
.as_str()
.unwrap()
.contains("validated AI interaction"));
}
#[test] #[test]
fn a_secret_change_invalidates_the_validated_interaction() { fn a_secret_change_invalidates_the_validated_interaction() {
let mut bridge = test_bridge_non_dry(); let mut bridge = test_bridge_non_dry();
@ -1616,6 +2048,42 @@ mod tests {
.contains("validated AI interaction")); .contains("validated AI interaction"));
} }
#[test]
fn options_are_available_for_the_region_pickers() {
let mut bridge = test_bridge();
let lines = call(&mut bridge, r#"{"id":50,"op":"options"}"#);
let data = &response(&lines)["data"];
assert!(!data["timezones"].as_array().unwrap().is_empty());
assert!(!data["locales"].as_array().unwrap().is_empty());
assert!(!data["keymaps"].as_array().unwrap().is_empty());
}
#[test]
fn models_url_is_derived_from_the_chat_endpoint() {
assert_eq!(
models_url("https://api.deepseek.com/chat/completions"),
"https://api.deepseek.com/models"
);
assert_eq!(
models_url("https://api.openai.com/v1/chat/completions"),
"https://api.openai.com/v1/models"
);
assert_eq!(
models_url("http://127.0.0.1:11434/v1/chat/completions"),
"http://127.0.0.1:11434/v1/models"
);
}
#[test]
fn parse_model_ids_reads_common_shapes() {
assert_eq!(
parse_model_ids(r#"{"data":[{"id":"b"},{"id":"a"},{"id":"a"}]}"#),
vec!["a", "b"]
);
assert_eq!(parse_model_ids(r#"{"models":[{"name":"m"}]}"#), vec!["m"]);
assert!(parse_model_ids("<html>").is_empty());
}
#[test] #[test]
fn ai_test_is_a_known_operation_and_fails_without_a_provider() { fn ai_test_is_a_known_operation_and_fails_without_a_provider() {
let mut bridge = test_bridge(); let mut bridge = test_bridge();

View file

@ -0,0 +1,59 @@
//! CLI-level regression tests for the `sys` entry paths.
//!
//! These exercise the real binary so the deterministic (manual) and JSON paths
//! are proven to fail closed on invalid input and to exit nonzero on failure.
//! They never mutate the system: the invalid cases are refused before any
//! command is built, and the read-only case targets a temporary root.
use std::process::Command;
fn sys() -> Command {
Command::new(env!("CARGO_BIN_EXE_sys"))
}
#[test]
fn natural_option_like_operand_is_rejected() {
// `--` stops clap option parsing, so the operand reaches the parser intact.
let out = sys()
.args(["--", "install", "--color=n"])
.output()
.expect("run sys");
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("could not parse") || stderr.contains("invalid"),
"stderr: {stderr}"
);
}
#[test]
fn json_option_like_operand_is_rejected() {
let out = sys()
.args(["--action", r#"{"action":"install_package","atom":"-C"}"#])
.output()
.expect("run sys");
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("invalid"), "stderr: {stderr}");
}
#[test]
fn read_only_history_succeeds_against_a_temporary_root() {
let root = tempfile::tempdir().expect("temp root");
let out = sys()
.arg("--root")
.arg(root.path())
.arg("history")
.output()
.expect("run sys");
assert!(
out.status.success(),
"stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("no snapshot history") || stdout.contains("snapshots:"),
"stdout: {stdout}"
);
}

View file

@ -105,6 +105,12 @@ Singleton {
function listDisks(cb) { function listDisks(cb) {
call("disks", {}, cb); call("disks", {}, cb);
} }
function options(cb) {
call("options", {}, cb);
}
function aiCatalog(cb) {
call("ai_catalog", {}, cb);
}
function setConfig(cfg, cb) { function setConfig(cfg, cb) {
call("set_config", { config: cfg }, reply => { call("set_config", { config: cfg }, reply => {
if (reply.ok) if (reply.ok)

View file

@ -0,0 +1,108 @@
import QtQuick
// A labelled input with an inline, filtered suggestion list. The user can type
// to narrow the list or click an entry to choose it, and a custom value is
// still allowed. Used for timezone, locale, keymap, provider and model so the
// user picks from what the system actually offers instead of typing from
// memory.
Column {
id: combo
property string label: ""
property string placeholder: ""
property string error: ""
property var options: []
property int maxVisible: 8
property string hint: "Type to filter, click to choose"
property alias text: field.text
property alias inputItem: field.inputItem
property var suggestions: []
signal edited(string value)
signal selected(string value)
width: parent ? parent.width : implicitWidth
spacing: 4
function refresh() {
const query = (field.text || "").toLowerCase();
const all = combo.options || [];
const out = [];
for (let i = 0; i < all.length && out.length < combo.maxVisible; i++) {
const option = "" + all[i];
if (query.length === 0 || option.toLowerCase().indexOf(query) !== -1)
out.push(option);
}
combo.suggestions = out;
}
onOptionsChanged: combo.refresh()
Component.onCompleted: combo.refresh()
PhoebusField {
id: field
width: parent.width
label: combo.label
placeholder: combo.placeholder
error: combo.error
onEdited: value => { combo.edited(value); combo.refresh(); }
}
// Show the first suggestions as soon as the field takes focus.
Connections {
target: field.inputItem
function onActiveFocusChanged() {
if (field.inputItem.activeFocus)
combo.refresh();
}
}
Column {
width: parent.width
spacing: 0
visible: field.inputItem.activeFocus && combo.suggestions.length > 0
Repeater {
model: field.inputItem.activeFocus ? combo.suggestions : []
delegate: Rectangle {
required property var modelData
width: parent.width
height: 30
color: hover.containsMouse ? Theme.surfaceRaised : Theme.surface
border.width: 1
border.color: Theme.border
Text {
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
anchors.right: parent.right
anchors.leftMargin: 12
anchors.rightMargin: 12
text: modelData
elide: Text.ElideRight
color: Theme.warmWhite
font.family: Theme.family
font.pixelSize: Theme.fontSmall
}
MouseArea {
id: hover
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: {
field.inputItem.text = modelData;
combo.selected(modelData);
combo.suggestions = [];
}
}
}
}
}
Text {
width: parent.width
visible: field.inputItem.activeFocus && combo.options.length > 0
text: combo.hint
color: Theme.muted
font.family: Theme.family
font.pixelSize: Theme.fontSmall
}
}

View file

@ -7,4 +7,5 @@ PhoebusCard 1.0 PhoebusCard.qml
PhoebusField 1.0 PhoebusField.qml PhoebusField 1.0 PhoebusField.qml
PhoebusToggle 1.0 PhoebusToggle.qml PhoebusToggle 1.0 PhoebusToggle.qml
PhoebusChoice 1.0 PhoebusChoice.qml PhoebusChoice 1.0 PhoebusChoice.qml
PhoebusCombo 1.0 PhoebusCombo.qml
PhoebusEmblem 1.0 PhoebusEmblem.qml PhoebusEmblem 1.0 PhoebusEmblem.qml

View file

@ -21,6 +21,11 @@ ShellRoot {
property string previewText: "" property string previewText: ""
property string planDigest: "" property string planDigest: ""
property var handshake: null property var handshake: null
// Selectable system lists (timezones/locales/keymaps) and the AI catalog.
property var options: ({ timezones: [], locales: [], keymaps: [] })
property var aiCatalog: ({ providers: [], models: [] })
property string aiCatalogError: ""
readonly property var aiProviderIds: (shell.aiCatalog.providers || []).map(p => p.id)
// Secrets: held in memory only, sent over the bridge stdin, never in cfg. // Secrets: held in memory only, sent over the bridge stdin, never in cfg.
property string userPw: "" property string userPw: ""
@ -165,12 +170,34 @@ ShellRoot {
shell.phase = "form"; shell.phase = "form";
shell.status = ""; shell.status = "";
shell.syncFields(); shell.syncFields();
shell.loadOptions();
} }
function refreshHandshake() { function refreshHandshake() {
Bridge.refreshHandshake(null); Bridge.refreshHandshake(null);
} }
// Fetch the real timezones/locales/keymaps the live system offers.
function loadOptions() {
Bridge.options(reply => {
if (reply.ok)
shell.options = reply.data;
});
}
// Fetch the providers/models the configured AI connection offers.
function loadAiCatalog() {
Bridge.aiCatalog(reply => {
if (reply.ok) {
shell.aiCatalog = reply.data;
shell.aiCatalogError = "";
} else {
shell.aiCatalog = { providers: [], models: [] };
shell.aiCatalogError = reply.error;
}
});
}
function applyConfig(then) { function applyConfig(then) {
if (!shell.cfg) { if (!shell.cfg) {
shell.status = "The installer backend is not ready yet."; shell.status = "The installer backend is not ready yet.";
@ -271,6 +298,8 @@ ShellRoot {
} }
shell.syncFields(); shell.syncFields();
shell.touchConfig(); shell.touchConfig();
if (s === 2)
shell.loadAiCatalog();
if (s === 3) if (s === 3)
refreshDisks(); refreshDisks();
if (s === 5) if (s === 5)
@ -340,6 +369,8 @@ ShellRoot {
endpointField.inputItem.text = shell.cfg.ai.endpoint; endpointField.inputItem.text = shell.cfg.ai.endpoint;
} }
shell.touchConfig(); shell.touchConfig();
// Populate the provider/model choices for the newly selected backend.
shell.loadAiCatalog();
} }
// A lightweight real interaction used by "Test connection": it obtains and // A lightweight real interaction used by "Test connection": it obtains and
@ -680,46 +711,34 @@ ShellRoot {
PhoebusCard { PhoebusCard {
width: parent.width width: parent.width
Text { width: parent.width; text: "Language and region"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } Text { width: parent.width; text: "Language and region"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold }
PhoebusField { PhoebusCombo {
id: localeField id: localeField
label: "Locale" label: "Locale"
placeholder: "en_US.UTF-8" placeholder: "en_US.UTF-8"
options: shell.options.locales
error: shell.issueFor("locale") error: shell.issueFor("locale")
onEdited: value => shell.cfg.system.locale = value onEdited: value => shell.cfg.system.locale = value
onSelected: value => shell.cfg.system.locale = value
Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.locale : "" Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.locale : ""
} }
PhoebusChoice { PhoebusCombo {
id: localePresets
options: [
{ value: "en_US.UTF-8", label: "English (US)" },
{ value: "en_GB.UTF-8", label: "English (UK)" },
{ value: "de_DE.UTF-8", label: "Deutsch" },
{ value: "fr_FR.UTF-8", label: "Français" },
{ value: "es_ES.UTF-8", label: "Español" }
]
value: shell.cfg ? shell.cfg.system.locale : ""
onSelected: value => { shell.cfg.system.locale = value; localeField.inputItem.text = value; shell.touchConfig(); }
}
PhoebusField {
id: keymapField id: keymapField
label: "Keyboard layout" label: "Keyboard layout"
placeholder: "us" placeholder: "us"
options: shell.options.keymaps
error: shell.issueFor("keymap") error: shell.issueFor("keymap")
onEdited: value => shell.cfg.system.keymap = value onEdited: value => shell.cfg.system.keymap = value
onSelected: value => shell.cfg.system.keymap = value
Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.keymap : "" Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.keymap : ""
} }
PhoebusChoice { PhoebusCombo {
id: keymapPresets
options: ["us", "gb", "de", "fr", "es", "dvorak"]
value: shell.cfg ? shell.cfg.system.keymap : ""
onSelected: value => { shell.cfg.system.keymap = value; keymapField.inputItem.text = value; shell.touchConfig(); }
}
PhoebusField {
id: tzField id: tzField
label: "Timezone" label: "Timezone"
placeholder: "UTC" placeholder: "UTC"
options: shell.options.timezones
error: shell.issueFor("timezone") error: shell.issueFor("timezone")
onEdited: value => shell.cfg.system.timezone = value onEdited: value => shell.cfg.system.timezone = value
onSelected: value => shell.cfg.system.timezone = value
Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.timezone : "" Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.timezone : ""
} }
} }
@ -801,15 +820,6 @@ ShellRoot {
visible: shell.cfg && !shell.isOpenCode && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai") visible: shell.cfg && !shell.isOpenCode && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai")
onEdited: value => shell.apiKey = value onEdited: value => shell.apiKey = value
} }
PhoebusField {
id: modelField
label: "Model"
placeholder: "model name"
error: ""
visible: shell.cfg && !shell.isOpenCode
onEdited: value => shell.cfg.ai.model = value
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.model ? shell.cfg.ai.model : ""
}
PhoebusField { PhoebusField {
id: endpointField id: endpointField
label: "Endpoint (local models)" label: "Endpoint (local models)"
@ -818,6 +828,35 @@ ShellRoot {
onEdited: value => shell.cfg.ai.endpoint = value onEdited: value => shell.cfg.ai.endpoint = value
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.endpoint ? shell.cfg.ai.endpoint : "" Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.endpoint ? shell.cfg.ai.endpoint : ""
} }
PhoebusCombo {
id: modelField
label: "Model"
placeholder: "choose a model or type one"
options: shell.aiCatalog.models
visible: shell.cfg && !shell.isOpenCode
onEdited: value => shell.cfg.ai.model = value
onSelected: value => shell.cfg.ai.model = value
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.model ? shell.cfg.ai.model : ""
}
Row {
spacing: 12
visible: shell.cfg && !shell.isOpenCode
PhoebusButton {
label: shell.aiChecking ? "Loading…" : "Load model list"
compact: true
onClicked: shell.loadAiCatalog()
}
Text {
anchors.verticalCenter: parent.verticalCenter
visible: shell.aiCatalogError.length > 0
text: shell.aiCatalogError
color: Theme.danger
font.family: Theme.family
font.pixelSize: Theme.fontSmall
width: parent.width - 200
elide: Text.ElideRight
}
}
// -- OpenCode agent server ----------------------------- // -- OpenCode agent server -----------------------------
Text { Text {
width: parent.width width: parent.width
@ -843,19 +882,45 @@ ShellRoot {
visible: shell.isOpenCode visible: shell.isOpenCode
onEdited: value => shell.opencodePassword = value onEdited: value => shell.opencodePassword = value
} }
PhoebusField { PhoebusCombo {
id: opencodeProviderField id: opencodeProviderField
label: "Provider" label: "Provider"
placeholder: "deepseek" placeholder: "choose a provider"
options: shell.aiProviderIds
visible: shell.isOpenCode visible: shell.isOpenCode
onEdited: value => shell.cfg.ai.opencode_provider = value onEdited: value => shell.cfg.ai.opencode_provider = value
onSelected: value => {
shell.cfg.ai.opencode_provider = value;
shell.loadAiCatalog();
}
} }
PhoebusField { PhoebusCombo {
id: opencodeModelField id: opencodeModelField
label: "Model" label: "Model"
placeholder: "deepseek-chat" placeholder: "choose a model"
options: shell.aiCatalog.models
visible: shell.isOpenCode visible: shell.isOpenCode
onEdited: value => shell.cfg.ai.opencode_model = value onEdited: value => shell.cfg.ai.opencode_model = value
onSelected: value => shell.cfg.ai.opencode_model = value
}
Row {
spacing: 12
visible: shell.isOpenCode
PhoebusButton {
label: "Load provider/model list"
compact: true
onClicked: shell.loadAiCatalog()
}
Text {
anchors.verticalCenter: parent.verticalCenter
visible: shell.aiCatalogError.length > 0
text: shell.aiCatalogError
color: Theme.danger
font.family: Theme.family
font.pixelSize: Theme.fontSmall
width: parent.width - 240
elide: Text.ElideRight
}
} }
Row { Row {
spacing: 12 spacing: 12
@ -949,15 +1014,15 @@ ShellRoot {
PhoebusField { id: fullnameField; label: "Full name"; onEdited: value => shell.cfg.user.fullname = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.user.fullname : "" } PhoebusField { id: fullnameField; label: "Full name"; onEdited: value => shell.cfg.user.fullname = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.user.fullname : "" }
PhoebusField { id: userField; label: "Username"; placeholder: "lowercase"; error: shell.issueFor("username"); onEdited: value => shell.cfg.user.username = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.user.username : "" } PhoebusField { id: userField; label: "Username"; placeholder: "lowercase"; error: shell.issueFor("username"); onEdited: value => shell.cfg.user.username = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.user.username : "" }
PhoebusField { id: hostField; label: "Computer name"; placeholder: "phoebus"; error: shell.issueFor("hostname"); onEdited: value => shell.cfg.system.hostname = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.hostname : "" } PhoebusField { id: hostField; label: "Computer name"; placeholder: "phoebus"; error: shell.issueFor("hostname"); onEdited: value => shell.cfg.system.hostname = value; Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.hostname : "" }
PhoebusField { id: pwField; label: "Password"; secret: true; error: shell.issueFor("password"); onEdited: value => shell.userPw = value } PhoebusField { id: pwField; label: "Password"; secret: true; placeholder: "At least 8 characters"; error: shell.issueFor("password"); onEdited: value => shell.userPw = value }
PhoebusField { id: pw2Field; label: "Confirm password"; secret: true; error: shell.issueFor("password_confirm"); onEdited: value => shell.userPw2 = value } PhoebusField { id: pw2Field; label: "Confirm password"; secret: true; placeholder: "Repeat the password"; error: shell.issueFor("password_confirm"); onEdited: value => shell.userPw2 = value }
} }
PhoebusCard { PhoebusCard {
width: parent.width width: parent.width
Text { width: parent.width; text: "Disk encryption"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold } Text { width: parent.width; text: "Disk encryption"; color: Theme.warmWhite; font.family: Theme.family; font.pixelSize: Theme.fontHeading; font.weight: Font.DemiBold }
Text { width: parent.width; text: "LUKS2 whole-disk encryption protects your data at rest. Keep this passphrase safe: without it the disk cannot be unlocked."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap } Text { width: parent.width; text: "LUKS2 whole-disk encryption protects your data at rest. Keep this passphrase safe: without it the disk cannot be unlocked."; color: Theme.muted; font.family: Theme.family; font.pixelSize: Theme.fontSmall; wrapMode: Text.WordWrap }
PhoebusField { id: luksField; label: "Encryption passphrase"; secret: true; error: shell.issueFor("passphrase"); onEdited: value => shell.luksPw = value } PhoebusField { id: luksField; label: "Encryption passphrase"; secret: true; placeholder: "At least 8 characters"; error: shell.issueFor("passphrase"); onEdited: value => shell.luksPw = value }
PhoebusField { id: luks2Field; label: "Confirm passphrase"; secret: true; error: shell.issueFor("passphrase_confirm"); onEdited: value => shell.luksPw2 = value } PhoebusField { id: luks2Field; label: "Confirm passphrase"; secret: true; placeholder: "Repeat the passphrase"; error: shell.issueFor("passphrase_confirm"); onEdited: value => shell.luksPw2 = value }
} }
PhoebusCard { PhoebusCard {
width: parent.width width: parent.width