Compare commits
No commits in common. "4679f935e3f02ec2a25406c80b9f173ee52c9765" and "359f083bc2924b483fa632bcae44b6debab52a22" have entirely different histories.
4679f935e3
...
359f083bc2
20 changed files with 203 additions and 1964 deletions
|
|
@ -5,54 +5,6 @@ this file is the curated, human-readable summary.
|
|||
|
||||
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
|
||||
|
||||
### Added
|
||||
|
|
|
|||
|
|
@ -3,37 +3,36 @@
|
|||
Rolling note between work sessions. **Update this file before you finish**, then
|
||||
commit it. It should be short and current; use `git log` for detail.
|
||||
|
||||
- **Last updated:** this session (2026-09-22), `sys` administration hardening.
|
||||
- **Current focus:** Hardened `sys` into a reliable administration tool.
|
||||
(1) All package/service/Flatpak execution now honours `--root` through one
|
||||
`target_spec`/chroot path (offline `systemctl --root` for enable/disable),
|
||||
and runtime-only service operations are rejected before any command when an
|
||||
alternate root is requested. (2) Every action is validated at the execution
|
||||
boundary (`parse_natural` now validates its own output); option-like operands
|
||||
are rejected and operands are passed after `--`. (3) `sys ask` stops at the
|
||||
first failure, records completed/failed/unattempted actions, and exits
|
||||
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 updated:** this session (2026-09-22), OpenCode adapter.
|
||||
- **Current focus:** Implemented a real OpenCode agent-server adapter
|
||||
(`phoebus-executor::opencode_client`) that speaks the session/message protocol
|
||||
over curl and implements `ModelTransport`, wired into canonical config
|
||||
(`ai.backend = "opencode"`), the GUI ("OpenCode agent" + Test connection),
|
||||
the installer CLI (`--ai-backend opencode`, `--opencode-test`) and `sys ask`.
|
||||
The mandatory-AI gate now requires a validated interaction with invalidated
|
||||
state. The probe/transport were hardened (loopback/TLS policy, DNS pinning,
|
||||
status checks, auth), and the GUI harness gained exact-session and
|
||||
frontend-state assertions.
|
||||
- **Last verified (this session):**
|
||||
- 368 Rust tests green (including 3 new CLI integration tests) + 16 harness
|
||||
tests; `cargo fmt --all -- --check` and `cargo clippy --workspace
|
||||
--all-targets` clean (exit 0). Static `phoebus-installer`/`sys` build.
|
||||
- Unit/integration evidence for all six fixes: preview and execution both
|
||||
chroot to the same alternate root; runtime service ops reject an alternate
|
||||
root without invoking anything; invalid actions are refused by the manual,
|
||||
JSON and AI parsers and at the executor; `execute_plan` marks later actions
|
||||
unattempted after a failure; unparseable emerge output is refused while a
|
||||
real `0 packages` plan is accepted; a material plan change aborts before
|
||||
the mutation.
|
||||
- **Not yet verified this session:** the destructive **rollback VM
|
||||
acceptance** (`sys undo`). See the blocker below — rollback stays explicitly
|
||||
unverified. The OpenCode live tests are environment-gated and were skipped
|
||||
(no `PHOEBUS_OPENCODE_LIVE_*`), and the full graphical install past the AI
|
||||
gate and a separate physical computer remain unverified from the previous
|
||||
session.
|
||||
- 336 Rust tests + 16 harness tests green; fmt/clippy clean.
|
||||
- Real inference through `opencode 1.18.32` with `deepseek-v4-flash`;
|
||||
`--opencode-test` → `{"phoebus":"ok"}`; the GUI bridge `ai_check` applied 8
|
||||
reviewed changes; `sys ask` proposed and ran a read-only action.
|
||||
- Auth: none → `authentication_required`, wrong → `authentication_rejected`,
|
||||
correct → `model_catalog` + successful inference. Plain http to a LAN host
|
||||
→ `insecure_transport`, exit 1, no request sent.
|
||||
- 7 real-HTTP integration tests (status, chunked multibyte, oversize,
|
||||
redirect, disconnect, auth) and 2 env-gated live tests.
|
||||
- GUI acceptance in a disposable VM: `gui-driver.py opencode` passed 17/17
|
||||
(selected OpenCode, entered the endpoint/model through the UI, real model
|
||||
response + validated proposal); `gui-driver.py gui` passed 25/25.
|
||||
ISO `sha256 4db98db3…`, static binary `sha256 72c2dcd0…`.
|
||||
- **Not yet verified this session:** the full graphical **installation** through
|
||||
OpenCode past the AI gate (disk/account/review/ERASE/install/detached boot),
|
||||
and a separate physical computer. The pinned manifest is `v1.18.31` while the
|
||||
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>
|
||||
(remote `origin`, SSH port 2222).
|
||||
|
||||
|
|
@ -47,13 +46,9 @@ 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
|
||||
and verify the panel/launcher/terminal/audio/network/lock/idle, the dwl
|
||||
fallback, and the welcome/installer absence on the installed system.
|
||||
3. **Rollback VM acceptance (BLOCKED this session)**: deliberately break an
|
||||
update, run `sys undo`, reboot detached, verify `/var/db/pkg` matches `/`,
|
||||
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.
|
||||
3. **Rollback VM acceptance**: deliberately break an update, run `sys undo`,
|
||||
reboot detached, verify `/var/db/pkg` matches `/`, then boot the recovery
|
||||
entry with no network or model (ADR 0007).
|
||||
4. **Narrow the live broker privilege**: replace the live-only
|
||||
`NOPASSWD: ALL` rule for the GUI bridge with the smallest practical
|
||||
command-scoped rule once a safe sudoers form is verified (ADR 0011 context).
|
||||
|
|
@ -71,11 +66,8 @@ commit it. It should be short and current; use `git log` for detail.
|
|||
verified as a blocked prerequisite and with a fixture transport.
|
||||
- **Installed** Mango (GURU + compiled Quickshell/DMS) is not VM-verified; nor
|
||||
is the dwl fallback session.
|
||||
- **Rollback (`sys undo`) is implemented and unit-tested but NOT VM-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.
|
||||
- Rollback and the AI sandbox are implemented and unit-tested but not
|
||||
VM-verified. NVIDIA is not verified.
|
||||
- A **separate physical computer** for the OpenCode transport test is not
|
||||
available (BLOCKED); a forwarded-hop + unauthenticated-LAN-refusal host-local
|
||||
test was done instead.
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**.
|
|||
| 9 | Background update preparation | Partial | distfile fetch VM-verified; `--buildpkgonly` skipped while deps need merging (recorded Ready); activation explicit |
|
||||
| 10 | Snapshots / rollback | Partial | snapshot sets + history VM-verified on Btrfs; coordinated rollback, `sys undo`, recovery entry, retention and free-space gate implemented + unit-tested; destructive VM acceptance test pending |
|
||||
| 11 | AI privilege and privacy architecture | Partial | typed actions + enforced privacy boundary + guided proposal review + OS-level sandbox (systemd-run hardening) + approval-bound resolved effects; live call/sandbox not VM-verified |
|
||||
| 12 | `sys` operations | 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) |
|
||||
| 12 | `sys` operations | Partial | history, enable/disable, inspect, install, prepare-updates VM-verified; `undo`, `undo status`, `ask` added (unit-tested, VM gate pending) |
|
||||
| 13 | Kernel optimization policy | Later | conservative fragments only; SAFE/OPTIMIZED/AGGRESSIVE selection exists |
|
||||
| 14 | ISO / release pipeline | Partial | manifest/verify/assemble-plan tooling; release gates, atomic publish and signing helpers added; no CI runner has executed a gate |
|
||||
| 15 | Recovery environment | Later | recovery BLS entry generated; snapshot-based recovery entry written at install; full recovery image not built |
|
||||
|
|
|
|||
|
|
@ -84,13 +84,9 @@ still not VM-verified.
|
|||
| AI privacy boundary (facts only) | yes | yes | no | n/a |
|
||||
| AI OS sandbox (systemd hardened unit) | yes | yes | no | no |
|
||||
| Installed assistant (`sys ask`) | yes | yes | fixture path only (no live call) | n/a |
|
||||
| Resolved package effects + approval binding | yes | yes (empty vs unestablished) | no | n/a |
|
||||
| Transaction log (outcomes, protective snapshots) | yes | yes | no | no |
|
||||
| Resolved package effects + approval binding | yes | yes | no | n/a |
|
||||
| Transaction log | 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 |
|
||||
| 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 |
|
||||
|
|
@ -127,18 +123,13 @@ still not VM-verified.
|
|||
- **NVIDIA** is architecturally allowed but not verified on hardware.
|
||||
- **UKI** is deferred; the dracut UKI generator did not embed the kernel
|
||||
command line, so BLS is used (and verified).
|
||||
- **Rollback is NOT VM-verified.** It is implemented and unit-tested end to end
|
||||
at the command/text layer (snapshot sets, root/var generation, fstab and BLS
|
||||
rewriting, kernel selection, interruption resume, retention, free-space
|
||||
gate), but the destructive acceptance test (deliberately broken update ->
|
||||
`sys undo` -> detached reboot -> package-state check -> recovery with no
|
||||
network/model) was **not run in this session**. Blockers: (1) `make doctor`
|
||||
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.
|
||||
- **Rollback** is implemented and unit-tested end to end at the command/text
|
||||
layer (snapshot sets, root/var generation, fstab and BLS rewriting, kernel
|
||||
selection, interruption resume, retention, free-space gate), but the
|
||||
destructive VM acceptance test (deliberately broken update -> `sys undo` ->
|
||||
detached reboot -> package-state check -> recovery with no network/model) has
|
||||
not been run. `sys undo` is present; treat VM verification as the gate before
|
||||
relying on it.
|
||||
- **Mango + DankMaterialShell** is the default desktop
|
||||
(`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
|
||||
|
|
|
|||
|
|
@ -51,27 +51,6 @@ and passed in the graphical VM; the remaining stages are the long package
|
|||
installation. Two fresh-disk graphical installs and a separate physical machine
|
||||
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
|
||||
integration tests + 2 live tests (skipped offline, real inference when
|
||||
configured). Bridge gate tests: 5. Full suite: 336 Rust tests.
|
||||
|
|
|
|||
|
|
@ -399,14 +399,6 @@ Not yet verified for this baseline: `sys undo`, a deliberately broken update, a
|
|||
detached rollback reboot, and recovery with no network/model (the rollback
|
||||
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)
|
||||
|
||||
### Live ISO — graphical VM (verified 2026-09-21)
|
||||
|
|
|
|||
|
|
@ -66,8 +66,7 @@ pub fn action_tag(action: &SystemAction) -> String {
|
|||
/// there is no shell or file action.
|
||||
pub const ASSISTANT_PROMPT: &str = "\
|
||||
You are the Phoebus OS system assistant. You can ONLY propose actions from this \
|
||||
closed set: inspect_service, enable_service, disable_service, start_service, \
|
||||
stop_service, restart_service, inspect_package, \
|
||||
closed set: inspect_service, enable_service, disable_service, inspect_package, \
|
||||
install_package, remove_package, search_packages, flatpak_install, flatpak_remove, \
|
||||
flatpak_list, nix_prepare, create_snapshot, undo, rollback_status, history, \
|
||||
update_system, prepare_updates, inspect_updates.
|
||||
|
|
@ -271,12 +270,6 @@ mod tests {
|
|||
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"}]}"#;
|
||||
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]
|
||||
|
|
|
|||
|
|
@ -35,18 +35,6 @@ pub enum SystemAction {
|
|||
DisableService {
|
||||
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 {
|
||||
atom: String,
|
||||
},
|
||||
|
|
@ -96,9 +84,6 @@ impl SystemAction {
|
|||
SystemAction::DisableService { name } => {
|
||||
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::InstallPackage { atom } => format!("install package {atom}"),
|
||||
SystemAction::RemovePackage { atom } => format!("remove package {atom}"),
|
||||
|
|
@ -145,9 +130,6 @@ impl SystemAction {
|
|||
SystemAction::PrepareUpdates => Risk::Medium,
|
||||
SystemAction::EnableService { .. }
|
||||
| SystemAction::DisableService { .. }
|
||||
| SystemAction::StartService { .. }
|
||||
| SystemAction::StopService { .. }
|
||||
| SystemAction::RestartService { .. }
|
||||
| SystemAction::CreateSnapshot { .. }
|
||||
| SystemAction::FlatpakInstall { .. }
|
||||
| SystemAction::FlatpakRemove { .. }
|
||||
|
|
@ -178,19 +160,13 @@ impl SystemAction {
|
|||
let valid_token = |s: &str| {
|
||||
!s.is_empty()
|
||||
&& 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()
|
||||
.all(|c| c.is_ascii_alphanumeric() || "@._+-".contains(c))
|
||||
};
|
||||
match self {
|
||||
SystemAction::InspectService { name }
|
||||
| SystemAction::EnableService { name }
|
||||
| SystemAction::DisableService { name }
|
||||
| SystemAction::StartService { name }
|
||||
| SystemAction::StopService { name }
|
||||
| SystemAction::RestartService { name } => {
|
||||
| SystemAction::DisableService { name } => {
|
||||
if valid_token(name) {
|
||||
Ok(())
|
||||
} else {
|
||||
|
|
@ -265,11 +241,6 @@ pub fn valid_package_spec(spec: &str) -> bool {
|
|||
if spec.is_empty() || spec.len() > 128 {
|
||||
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 Some(first) = parts.next() else {
|
||||
return false;
|
||||
|
|
@ -280,10 +251,7 @@ pub fn valid_package_spec(spec: &str) -> bool {
|
|||
match parts.next() {
|
||||
None => true,
|
||||
Some(second) => {
|
||||
!second.is_empty()
|
||||
&& !second.starts_with('-')
|
||||
&& second.chars().all(is_atom_char)
|
||||
&& parts.next().is_none()
|
||||
!second.is_empty() && second.chars().all(is_atom_char) && parts.next().is_none()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -292,8 +260,6 @@ pub fn valid_package_spec(spec: &str) -> bool {
|
|||
pub fn valid_search_query(query: &str) -> bool {
|
||||
!query.is_empty()
|
||||
&& query.len() <= 128
|
||||
// Reject a leading dash so a query cannot become an option.
|
||||
&& !query.starts_with('-')
|
||||
&& query
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || " ._+@/-".contains(c))
|
||||
|
|
@ -325,29 +291,11 @@ pub fn valid_nix_attribute(value: &str) -> bool {
|
|||
&& !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.
|
||||
///
|
||||
/// 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
|
||||
/// (`--action-file`), which still produces the same typed schema.
|
||||
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
|
||||
// undo form from the original text before the general lowercasing.
|
||||
let raw = text.trim();
|
||||
|
|
@ -381,21 +329,6 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
|
|||
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 !atom.is_empty() {
|
||||
return Some(SystemAction::InstallPackage { atom });
|
||||
|
|
@ -419,62 +352,6 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
|
|||
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 id == "status" {
|
||||
return Some(SystemAction::RollbackStatus);
|
||||
|
|
@ -675,117 +552,4 @@ mod tests {
|
|||
assert!(valid_flatpak_app_id("com.spotify.Client"));
|
||||
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()
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,12 +59,6 @@ pub struct ResolvedPlan {
|
|||
pub consequences: Vec<String>,
|
||||
/// Stable digest of the effect list, used to bind approval to the review.
|
||||
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 {
|
||||
|
|
@ -282,12 +276,6 @@ pub fn parse_emerge_pretend(text: &str) -> ResolvedPlan {
|
|||
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);
|
||||
if plan.removals() > 0 {
|
||||
plan.consequences
|
||||
|
|
@ -380,29 +368,12 @@ Total: 5 packages (2 upgrades, 2 new, 1 uninstall), Size of downloads: 10,240 Ki
|
|||
fn empty_output_is_a_no_change_plan() {
|
||||
let plan = parse_emerge_pretend("Calculating dependencies... done!\n\nTotal: 0 packages\n");
|
||||
assert!(plan.effects.is_empty());
|
||||
assert!(plan.established, "a real 0-package plan is established");
|
||||
assert_eq!(plan.additions(), 0);
|
||||
assert!(plan.render().contains("no package changes"));
|
||||
// The digest is still defined.
|
||||
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]
|
||||
fn render_states_source_binary_and_consequences() {
|
||||
let plan = parse_emerge_pretend(PRETEND);
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ pub struct TransactionRecord {
|
|||
pub origin: String,
|
||||
/// A short human-readable summary.
|
||||
pub summary: String,
|
||||
/// The validated typed actions that were attempted, rendered.
|
||||
/// The validated typed actions, rendered.
|
||||
pub actions: Vec<String>,
|
||||
/// `ok` or a failure description.
|
||||
pub result: String,
|
||||
|
|
@ -26,54 +26,6 @@ pub struct TransactionRecord {
|
|||
pub snapshot: Option<String>,
|
||||
/// The reviewed plan digest, when effects were resolved.
|
||||
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 {
|
||||
|
|
@ -86,28 +38,10 @@ impl Default for TransactionRecord {
|
|||
result: "ok".into(),
|
||||
snapshot: 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)]
|
||||
#[serde(default)]
|
||||
pub struct TransactionLog {
|
||||
|
|
@ -158,20 +92,7 @@ impl TransactionLog {
|
|||
if let Some(snap) = &r.snapshot {
|
||||
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');
|
||||
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
|
||||
}
|
||||
|
|
@ -194,7 +115,6 @@ mod tests {
|
|||
result: "ok".into(),
|
||||
snapshot: Some("@-x".into()),
|
||||
digest: Some("abc".into()),
|
||||
outcomes: Vec::new(),
|
||||
});
|
||||
log.save(&path).unwrap();
|
||||
let loaded = TransactionLog::load(&path).unwrap();
|
||||
|
|
@ -215,50 +135,6 @@ mod tests {
|
|||
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]
|
||||
fn log_is_bounded() {
|
||||
let mut log = TransactionLog::default();
|
||||
|
|
|
|||
|
|
@ -7,13 +7,11 @@ use std::path::Path;
|
|||
|
||||
use phoebus_core::action::SystemAction;
|
||||
use phoebus_core::effects::{changed_materially, parse_emerge_pretend, ResolvedPlan};
|
||||
use phoebus_core::transaction::TransactionOutcome;
|
||||
|
||||
use crate::auth::DestructiveAuthorization;
|
||||
use crate::command::{CommandOutput, CommandSpec};
|
||||
use crate::command::CommandSpec;
|
||||
use crate::error::{ExecError, Result};
|
||||
use crate::exec::Exec;
|
||||
use crate::portage;
|
||||
use crate::snapshot;
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -35,105 +33,17 @@ pub fn preview(action: &SystemAction) -> String {
|
|||
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,
|
||||
/// or `None` when the action is not a Portage transaction.
|
||||
fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
|
||||
match action {
|
||||
SystemAction::InstallPackage { atom } => Some(vec![
|
||||
"--pretend".into(),
|
||||
"--color=n".into(),
|
||||
"--".into(),
|
||||
atom.clone(),
|
||||
]),
|
||||
SystemAction::InstallPackage { atom } => {
|
||||
Some(vec!["--pretend".into(), "--color=n".into(), atom.clone()])
|
||||
}
|
||||
SystemAction::RemovePackage { atom } => Some(vec![
|
||||
"--pretend".into(),
|
||||
"--unmerge".into(),
|
||||
"--color=n".into(),
|
||||
"--".into(),
|
||||
atom.clone(),
|
||||
]),
|
||||
SystemAction::UpdateSystem => Some(vec![
|
||||
|
|
@ -142,7 +52,6 @@ fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
|
|||
"--deep".into(),
|
||||
"--newuse".into(),
|
||||
"--color=n".into(),
|
||||
"--".into(),
|
||||
"@world".into(),
|
||||
]),
|
||||
_ => None,
|
||||
|
|
@ -152,25 +61,17 @@ fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
|
|||
/// 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.
|
||||
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 {
|
||||
return Ok(ResolvedPlan::default());
|
||||
};
|
||||
// Same rooting as execution, so the reviewed plan describes the action that
|
||||
// will actually run.
|
||||
let spec = target_spec(root, "sys", "resolve effects", "emerge", &args);
|
||||
let out = exec.run_capture(spec)?;
|
||||
let out = if root == Path::new("/") {
|
||||
exec.run_capture(CommandSpec::new("sys", "resolve effects", "emerge").args(args))?
|
||||
} else {
|
||||
let mut chroot_args = vec![root.to_string_lossy().to_string(), "emerge".to_string()];
|
||||
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());
|
||||
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() {
|
||||
plan.recovery_point = Some("a protective snapshot before the change".into());
|
||||
}
|
||||
|
|
@ -204,75 +105,12 @@ pub fn execute_checked(
|
|||
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(
|
||||
exec: &Exec,
|
||||
action: &SystemAction,
|
||||
auth: Option<&DestructiveAuthorization>,
|
||||
root: &Path,
|
||||
) -> 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() {
|
||||
return Err(ExecError::NotAuthorized(action.describe()));
|
||||
}
|
||||
|
|
@ -298,22 +136,14 @@ pub fn execute(
|
|||
});
|
||||
}
|
||||
|
||||
let mut snapshot_id = None;
|
||||
|
||||
// A protective snapshot must exist before a high-risk change. If the
|
||||
// snapshots subvolume is present but the snapshot cannot be created, fail
|
||||
// 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.
|
||||
// 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 root.join(snapshot::SNAPSHOT_DIR).is_dir() {
|
||||
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(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);
|
||||
snapshot::create_and_record(exec, auth, root, "/", &action.describe())?;
|
||||
} else {
|
||||
exec.logger.warn(format!(
|
||||
"no {}/ subvolume; proceeding without a protective snapshot",
|
||||
|
|
@ -322,147 +152,82 @@ pub fn execute(
|
|||
}
|
||||
}
|
||||
|
||||
let mut snapshot_id = None;
|
||||
let output = match action {
|
||||
SystemAction::InspectService { name } => {
|
||||
require_host_root(root, "inspect service")?;
|
||||
let out = capture_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"inspect service",
|
||||
"systemctl",
|
||||
&["status".into(), name.clone(), "--no-pager".into()],
|
||||
let out = exec.runner.execute(
|
||||
&CommandSpec::new("sys", "inspect service", "systemctl").args([
|
||||
"status",
|
||||
name,
|
||||
"--no-pager",
|
||||
]),
|
||||
)?;
|
||||
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
|
||||
}
|
||||
SystemAction::EnableService { name } => {
|
||||
let spec = systemctl_spec(root, "enable service", "enable", name);
|
||||
exec.run(spec)?;
|
||||
exec.run(
|
||||
CommandSpec::new("sys", "enable service", "systemctl").args(["enable", name]),
|
||||
)?;
|
||||
format!("enabled {name}")
|
||||
}
|
||||
SystemAction::DisableService { name } => {
|
||||
let spec = systemctl_spec(root, "disable service", "disable", name);
|
||||
exec.run(spec)?;
|
||||
exec.run(
|
||||
CommandSpec::new("sys", "disable service", "systemctl").args(["disable", 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 } => {
|
||||
let out = capture_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"inspect package",
|
||||
"emerge",
|
||||
&[
|
||||
"--pretend".into(),
|
||||
"--quiet".into(),
|
||||
"--".into(),
|
||||
atom.clone(),
|
||||
],
|
||||
let out = exec.runner.execute(
|
||||
&CommandSpec::new("sys", "inspect package", "emerge").args([
|
||||
"--pretend",
|
||||
"--quiet",
|
||||
atom,
|
||||
]),
|
||||
)?;
|
||||
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
|
||||
}
|
||||
SystemAction::InstallPackage { atom } => {
|
||||
// Portage resolves a bare name (`vim`) or a full atom.
|
||||
run_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"install package",
|
||||
"emerge",
|
||||
&["--ask=n".into(), "--".into(), atom.clone()],
|
||||
)?;
|
||||
exec.run(CommandSpec::new("sys", "install package", "emerge").args(["--ask=n", atom]))?;
|
||||
format!("installed {atom} (Portage)")
|
||||
}
|
||||
SystemAction::RemovePackage { atom } => {
|
||||
run_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"remove package",
|
||||
"emerge",
|
||||
&[
|
||||
"--unmerge".into(),
|
||||
"--ask=n".into(),
|
||||
"--".into(),
|
||||
atom.clone(),
|
||||
],
|
||||
)?;
|
||||
exec.run(CommandSpec::new("sys", "remove package", "emerge").args([
|
||||
"--unmerge",
|
||||
"--ask=n",
|
||||
atom,
|
||||
]))?;
|
||||
format!("removed {atom} (Portage)")
|
||||
}
|
||||
SystemAction::SearchPackages { query } => {
|
||||
let out = capture_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"search packages",
|
||||
"emerge",
|
||||
&[
|
||||
"--search".into(),
|
||||
"--quiet".into(),
|
||||
"--".into(),
|
||||
query.clone(),
|
||||
],
|
||||
let out = exec.runner.execute(
|
||||
&CommandSpec::new("sys", "search packages", "emerge")
|
||||
.args(["--search", "--quiet", query]),
|
||||
)?;
|
||||
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
|
||||
}
|
||||
SystemAction::FlatpakInstall { app_id } => {
|
||||
run_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"install flatpak",
|
||||
"flatpak",
|
||||
&[
|
||||
"install".into(),
|
||||
"-y".into(),
|
||||
"--".into(),
|
||||
"flathub".into(),
|
||||
app_id.clone(),
|
||||
],
|
||||
exec.run(
|
||||
CommandSpec::new("sys", "install flatpak", "flatpak")
|
||||
.args(["install", "-y", "flathub", app_id]),
|
||||
)?;
|
||||
format!("installed Flatpak app {app_id}")
|
||||
}
|
||||
SystemAction::FlatpakRemove { app_id } => {
|
||||
run_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"remove flatpak",
|
||||
"flatpak",
|
||||
&["uninstall".into(), "-y".into(), "--".into(), app_id.clone()],
|
||||
)?;
|
||||
exec.run(CommandSpec::new("sys", "remove flatpak", "flatpak").args([
|
||||
"uninstall",
|
||||
"-y",
|
||||
app_id,
|
||||
]))?;
|
||||
format!("removed Flatpak app {app_id}")
|
||||
}
|
||||
SystemAction::FlatpakList => {
|
||||
let out = capture_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"list flatpaks",
|
||||
"flatpak",
|
||||
&[
|
||||
"list".into(),
|
||||
"--app".into(),
|
||||
"--columns=application,version,branch".into(),
|
||||
],
|
||||
let out = exec.runner.execute(
|
||||
&CommandSpec::new("sys", "list flatpaks", "flatpak").args([
|
||||
"list",
|
||||
"--app",
|
||||
"--columns=application,version,branch",
|
||||
]),
|
||||
)?;
|
||||
let text = format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy());
|
||||
if text.trim().is_empty() {
|
||||
|
|
@ -476,26 +241,15 @@ pub fn execute(
|
|||
format!("realised Nix development packages: {}", prepared.join(", "))
|
||||
}
|
||||
SystemAction::UpdateSystem => {
|
||||
run_in_target(
|
||||
exec,
|
||||
root,
|
||||
"sys",
|
||||
"update system",
|
||||
"emerge",
|
||||
&[
|
||||
"--update".into(),
|
||||
"--deep".into(),
|
||||
"--newuse".into(),
|
||||
"--".into(),
|
||||
"@world".into(),
|
||||
],
|
||||
exec.run(
|
||||
CommandSpec::new("sys", "update system", "emerge")
|
||||
.args(["--update", "--deep", "--newuse", "@world"]),
|
||||
)?;
|
||||
"system update complete".to_string()
|
||||
}
|
||||
SystemAction::CreateSnapshot { operation } => {
|
||||
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
|
||||
let source = root.to_string_lossy().to_string();
|
||||
let record = snapshot::create_and_record(exec, auth, root, &source, operation)?;
|
||||
let auth = auth.expect("mutating action has auth");
|
||||
let record = snapshot::create_and_record(exec, auth, root, "/", operation)?;
|
||||
snapshot_id = Some(record.id.clone());
|
||||
format!("snapshot created: {}", record.id)
|
||||
}
|
||||
|
|
@ -557,27 +311,7 @@ mod tests {
|
|||
use super::*;
|
||||
use crate::command::RecordingRunner;
|
||||
use crate::log::Logger;
|
||||
use phoebus_core::transaction::ActionStatus;
|
||||
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 {
|
||||
let path = tempfile::tempdir().unwrap().keep();
|
||||
|
|
@ -585,27 +319,6 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
|
|||
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]
|
||||
fn mutating_action_requires_authorization() {
|
||||
let runner = RecordingRunner::new();
|
||||
|
|
@ -632,7 +345,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
|
|||
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 auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
|
||||
execute(
|
||||
&exec,
|
||||
&SystemAction::UpdateSystem,
|
||||
|
|
@ -640,46 +353,25 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
|
|||
Path::new(&exec.root),
|
||||
)
|
||||
.unwrap();
|
||||
let specs = runner.recorded();
|
||||
let btrfs = specs
|
||||
let programs = runner.programs();
|
||||
let btrfs = programs
|
||||
.iter()
|
||||
.position(|s| s.program == "btrfs")
|
||||
.position(|p| p == "btrfs")
|
||||
.expect("snapshot");
|
||||
let emerge = specs
|
||||
.iter()
|
||||
.position(|s| s.program == "emerge" || s.args.iter().any(|a| a == "emerge"))
|
||||
.expect("emerge");
|
||||
let emerge = programs.iter().position(|p| p == "emerge").expect("emerge");
|
||||
assert!(
|
||||
btrfs < emerge,
|
||||
"protective snapshot must precede the mutation: {:?}",
|
||||
runner.programs()
|
||||
"protective snapshot must precede the mutation: {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]
|
||||
fn high_risk_action_aborts_when_protective_snapshot_fails() {
|
||||
let runner = RecordingRunner::new();
|
||||
runner.fail("btrfs", "snapshot failed");
|
||||
let exec = make_exec(runner.clone());
|
||||
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
|
||||
let auth = auth();
|
||||
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
|
||||
let err = execute(
|
||||
&exec,
|
||||
&SystemAction::UpdateSystem,
|
||||
|
|
@ -710,15 +402,13 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
|
|||
fn remove_package_builds_unmerge() {
|
||||
let runner = RecordingRunner::new();
|
||||
let exec = make_exec(runner.clone());
|
||||
let auth = auth();
|
||||
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
|
||||
let action = SystemAction::RemovePackage { atom: "vim".into() };
|
||||
execute(&exec, &action, Some(&auth), Path::new(&exec.root)).unwrap();
|
||||
let recorded = runner.recorded();
|
||||
let spec = emerge_calls(&recorded)[0];
|
||||
let spec = &runner.recorded()[0];
|
||||
assert_eq!(spec.program, "emerge");
|
||||
assert!(spec.args.contains(&"--unmerge".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]
|
||||
|
|
@ -729,232 +419,26 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
|
|||
query: "firefox".into(),
|
||||
};
|
||||
execute(&exec, &action, None, Path::new(&exec.root)).unwrap();
|
||||
let recorded = runner.recorded();
|
||||
let spec = emerge_calls(&recorded)[0];
|
||||
let spec = &runner.recorded()[0];
|
||||
assert_eq!(spec.program, "emerge");
|
||||
assert!(spec.args.contains(&"--search".to_string()));
|
||||
assert!(spec.args.contains(&"firefox".to_string()));
|
||||
assert!(spec
|
||||
.args
|
||||
.windows(2)
|
||||
.any(|w| w[0] == "--" && w[1] == "firefox"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enable_builds_separate_arguments() {
|
||||
let runner = RecordingRunner::new();
|
||||
let exec = make_exec(runner.clone());
|
||||
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
|
||||
let action = SystemAction::EnableService {
|
||||
name: "sshd".into(),
|
||||
};
|
||||
execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap();
|
||||
execute(&exec, &action, Some(&auth), Path::new("/")).unwrap();
|
||||
let spec = &runner.recorded()[0];
|
||||
assert_eq!(spec.program, "systemctl");
|
||||
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]
|
||||
fn undo_requires_authorization() {
|
||||
let runner = RecordingRunner::new();
|
||||
|
|
|
|||
|
|
@ -551,21 +551,13 @@ impl<'a> OpenCodeClient<'a> {
|
|||
|
||||
fn error_for(&self, action: &str, response: &HttpResponse) -> AiError {
|
||||
let hint = match response.status {
|
||||
400 => "the server rejected the request (check the model id)".to_string(),
|
||||
401 => "authentication required".to_string(),
|
||||
403 => "authentication rejected".to_string(),
|
||||
404 => "endpoint not found (incompatible server?)".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),
|
||||
};
|
||||
// Name the provider:model so an invalid selection is obvious.
|
||||
AiError::Provider(format!(
|
||||
"OpenCode {action} failed for {}/{}: {hint}",
|
||||
self.provider, self.model
|
||||
))
|
||||
AiError::Provider(format!("OpenCode {action} failed: {hint}"))
|
||||
}
|
||||
|
||||
/// Fetch the provider/model catalog. Uses the metadata endpoint only.
|
||||
|
|
@ -1005,7 +997,7 @@ mod tests {
|
|||
(401u16, "authentication required"),
|
||||
(403, "authentication rejected"),
|
||||
(404, "not found"),
|
||||
(500, "internal error"),
|
||||
(500, "HTTP 500"),
|
||||
] {
|
||||
let http = FakeHttp::new(vec![FakeHttp::json(status, "{}")]);
|
||||
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");
|
||||
|
|
|
|||
|
|
@ -87,9 +87,7 @@ pub fn select_profile(exec: &Exec, config: &InstallConfig) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// 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(
|
||||
fn chroot_spec(
|
||||
stage: &str,
|
||||
operation: &str,
|
||||
root: &Path,
|
||||
|
|
|
|||
|
|
@ -6,14 +6,14 @@
|
|||
//! `--action-file`; it never receives a shell or the sudo password.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::Parser;
|
||||
use phoebus_ai::assistant::{complete_plan, AssistantPlan};
|
||||
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
||||
use phoebus_core::action::{parse_action, parse_natural, SystemAction};
|
||||
use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
|
||||
use phoebus_core::transaction::TransactionRecord;
|
||||
use phoebus_core::{AiBackend, InstallConfig, Redactor};
|
||||
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
|
||||
use phoebus_executor::{
|
||||
|
|
@ -114,26 +114,6 @@ 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 {
|
||||
std::process::Command::new("id")
|
||||
.arg("-u")
|
||||
|
|
@ -242,23 +222,6 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
|||
println!("protective snapshot: {id}");
|
||||
}
|
||||
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(())
|
||||
}
|
||||
|
||||
|
|
@ -480,45 +443,44 @@ fn run_ask(
|
|||
None
|
||||
};
|
||||
|
||||
// The reviewed plans and actions are executed through the shared,
|
||||
// failure-aware plan runner: it stops at the first failure and records the
|
||||
// remaining actions as unattempted.
|
||||
let digest = approved
|
||||
.iter()
|
||||
.find(|p| !p.digest.is_empty())
|
||||
.map(|p| p.digest.clone());
|
||||
let steps: Vec<(SystemAction, phoebus_core::effects::ResolvedPlan)> =
|
||||
plan.actions.iter().cloned().zip(approved).collect();
|
||||
let run = actions::execute_plan(exec, &steps, auth.as_ref(), &cli.root);
|
||||
for (_, output) in &run.completed {
|
||||
println!("{output}");
|
||||
let mut snapshot = None;
|
||||
let mut result = String::from("ok");
|
||||
let mut executed = Vec::new();
|
||||
for (action, resolved) in plan.actions.iter().zip(approved.iter()) {
|
||||
match actions::execute_checked(exec, action, auth.as_ref(), &cli.root, Some(resolved)) {
|
||||
Ok(outcome) => {
|
||||
if let Some(id) = &outcome.snapshot {
|
||||
snapshot = Some(id.clone());
|
||||
}
|
||||
executed.push(action.describe());
|
||||
println!("{}", outcome.output);
|
||||
}
|
||||
Err(e) => {
|
||||
result = format!("failed: {e}");
|
||||
executed.push(action.describe());
|
||||
eprintln!("action failed: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut attempted: Vec<String> = run.completed.iter().map(|(a, _)| a.clone()).collect();
|
||||
if let Some((action, detail)) = &run.failure {
|
||||
eprintln!("action failed: {action}: {detail}");
|
||||
attempted.push(action.clone());
|
||||
}
|
||||
|
||||
let result = match &run.failure {
|
||||
None => "ok".to_string(),
|
||||
Some((action, detail)) => format!("failed: {action}: {detail}"),
|
||||
};
|
||||
let record = TransactionRecord {
|
||||
created_unix: now_unix(),
|
||||
created_unix: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0),
|
||||
origin: "assistant".into(),
|
||||
summary: plan.summary.clone(),
|
||||
actions: attempted,
|
||||
actions: executed,
|
||||
result,
|
||||
snapshot: run.snapshot,
|
||||
digest,
|
||||
outcomes: run.outcomes,
|
||||
snapshot,
|
||||
digest: approved
|
||||
.iter()
|
||||
.find(|p| !p.digest.is_empty())
|
||||
.map(|p| p.digest.clone()),
|
||||
};
|
||||
record_transaction(exec, &cli.root, record)?;
|
||||
|
||||
// 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());
|
||||
if let Err(e) = transaction::append(exec, &cli.root, record) {
|
||||
eprintln!("could not record the transaction: {e}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -258,8 +258,6 @@ impl Bridge {
|
|||
let op = request.op.clone();
|
||||
let result = match request.op.as_str() {
|
||||
"handshake" => self.handshake(),
|
||||
"options" => self.options(),
|
||||
"ai_catalog" => self.ai_catalog(),
|
||||
"disks" => self.disks(),
|
||||
"set_config" => self.set_config(&request),
|
||||
"set_secrets" => self.set_secrets(&request),
|
||||
|
|
@ -314,109 +312,6 @@ 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> {
|
||||
self.installer.disks =
|
||||
phoebus_executor::probe::probe_disks(self.installer.exec.runner.as_ref());
|
||||
|
|
@ -523,15 +418,11 @@ impl Bridge {
|
|||
// backend concerns and not user-selectable from the GUI.
|
||||
config.runtime.dry_run = self.installer.config.runtime.dry_run;
|
||||
|
||||
let ai_before = ai_digest(&self.installer.config);
|
||||
self.installer.reconfigure(config);
|
||||
self.approved_digest = None;
|
||||
// Only a change to the AI connection settings invalidates the AI
|
||||
// validation. Choosing a disk, typing a hostname or similar must not
|
||||
// throw away a successful model interaction.
|
||||
if ai_digest(&self.installer.config) != ai_before {
|
||||
// A configuration change (provider, model, endpoint, server) invalidates
|
||||
// any previous AI validation.
|
||||
self.validated_ai = None;
|
||||
}
|
||||
let issues = self.installer.validate();
|
||||
Ok(json!({
|
||||
"accepted": true,
|
||||
|
|
@ -578,24 +469,18 @@ impl Bridge {
|
|||
self.installer.exec.register_secret(&s);
|
||||
self.root_password = Some(s);
|
||||
}
|
||||
let mut ai_credential_changed = false;
|
||||
if let Some(v) = &patch.ai_api_key {
|
||||
let s = SecretString::new(v.clone());
|
||||
self.installer.exec.register_secret(&s);
|
||||
self.api_key = Some(s);
|
||||
ai_credential_changed = true;
|
||||
}
|
||||
if let Some(v) = &patch.opencode_password {
|
||||
let s = SecretString::new(v.clone());
|
||||
self.installer.exec.register_secret(&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 {
|
||||
// A credential change invalidates any previous AI validation.
|
||||
self.validated_ai = None;
|
||||
}
|
||||
// Report only presence, never values.
|
||||
Ok(json!({
|
||||
"luks_set": self.luks.is_some(),
|
||||
|
|
@ -630,7 +515,7 @@ impl Bridge {
|
|||
self.approved_digest = None;
|
||||
// Bind the validated interaction to the exact configuration it was
|
||||
// validated against; any later change clears it.
|
||||
self.validated_ai = Some(ai_digest(&self.installer.config));
|
||||
self.validated_ai = Some(self.plan_digest());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
|
|
@ -710,7 +595,7 @@ impl Bridge {
|
|||
review_proposal(config, exec.redactor(), facts, api_key_present, transport)?
|
||||
};
|
||||
self.approved_digest = None;
|
||||
self.validated_ai = Some(ai_digest(&self.installer.config));
|
||||
self.validated_ai = Some(self.plan_digest());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
|
|
@ -782,8 +667,7 @@ impl Bridge {
|
|||
let break_glass = std::env::var("PHOEBUS_NO_AI")
|
||||
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
||||
.unwrap_or(false);
|
||||
let validated =
|
||||
self.validated_ai.as_deref() == Some(ai_digest(&self.installer.config).as_str());
|
||||
let validated = self.validated_ai.as_deref() == Some(current.as_str());
|
||||
if !validated && !break_glass {
|
||||
return Err(
|
||||
"installing Phoebus requires a successful, validated AI interaction for \
|
||||
|
|
@ -997,237 +881,6 @@ fn opencode_parts(config: &InstallConfig) -> Result<(String, String, String), St
|
|||
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>(
|
||||
exec: &'a Exec,
|
||||
config: &InstallConfig,
|
||||
|
|
@ -1308,29 +961,6 @@ 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
|
||||
/// and apply the reviewed proposal. This is the same `ai_guide` path the TUI
|
||||
/// uses.
|
||||
|
|
@ -1968,68 +1598,6 @@ mod tests {
|
|||
.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]
|
||||
fn a_secret_change_invalidates_the_validated_interaction() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
|
|
@ -2048,42 +1616,6 @@ mod tests {
|
|||
.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]
|
||||
fn ai_test_is_a_known_operation_and_fails_without_a_provider() {
|
||||
let mut bridge = test_bridge();
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
//! 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}"
|
||||
);
|
||||
}
|
||||
|
|
@ -105,12 +105,6 @@ Singleton {
|
|||
function listDisks(cb) {
|
||||
call("disks", {}, cb);
|
||||
}
|
||||
function options(cb) {
|
||||
call("options", {}, cb);
|
||||
}
|
||||
function aiCatalog(cb) {
|
||||
call("ai_catalog", {}, cb);
|
||||
}
|
||||
function setConfig(cfg, cb) {
|
||||
call("set_config", { config: cfg }, reply => {
|
||||
if (reply.ok)
|
||||
|
|
|
|||
|
|
@ -1,108 +0,0 @@
|
|||
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
|
||||
}
|
||||
}
|
||||
|
|
@ -7,5 +7,4 @@ PhoebusCard 1.0 PhoebusCard.qml
|
|||
PhoebusField 1.0 PhoebusField.qml
|
||||
PhoebusToggle 1.0 PhoebusToggle.qml
|
||||
PhoebusChoice 1.0 PhoebusChoice.qml
|
||||
PhoebusCombo 1.0 PhoebusCombo.qml
|
||||
PhoebusEmblem 1.0 PhoebusEmblem.qml
|
||||
|
|
|
|||
|
|
@ -21,11 +21,6 @@ ShellRoot {
|
|||
property string previewText: ""
|
||||
property string planDigest: ""
|
||||
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.
|
||||
property string userPw: ""
|
||||
|
|
@ -170,34 +165,12 @@ ShellRoot {
|
|||
shell.phase = "form";
|
||||
shell.status = "";
|
||||
shell.syncFields();
|
||||
shell.loadOptions();
|
||||
}
|
||||
|
||||
function refreshHandshake() {
|
||||
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) {
|
||||
if (!shell.cfg) {
|
||||
shell.status = "The installer backend is not ready yet.";
|
||||
|
|
@ -298,8 +271,6 @@ ShellRoot {
|
|||
}
|
||||
shell.syncFields();
|
||||
shell.touchConfig();
|
||||
if (s === 2)
|
||||
shell.loadAiCatalog();
|
||||
if (s === 3)
|
||||
refreshDisks();
|
||||
if (s === 5)
|
||||
|
|
@ -369,8 +340,6 @@ ShellRoot {
|
|||
endpointField.inputItem.text = shell.cfg.ai.endpoint;
|
||||
}
|
||||
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
|
||||
|
|
@ -711,34 +680,46 @@ ShellRoot {
|
|||
PhoebusCard {
|
||||
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 }
|
||||
PhoebusCombo {
|
||||
PhoebusField {
|
||||
id: localeField
|
||||
label: "Locale"
|
||||
placeholder: "en_US.UTF-8"
|
||||
options: shell.options.locales
|
||||
error: shell.issueFor("locale")
|
||||
onEdited: value => shell.cfg.system.locale = value
|
||||
onSelected: value => shell.cfg.system.locale = value
|
||||
Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.locale : ""
|
||||
}
|
||||
PhoebusCombo {
|
||||
PhoebusChoice {
|
||||
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
|
||||
label: "Keyboard layout"
|
||||
placeholder: "us"
|
||||
options: shell.options.keymaps
|
||||
error: shell.issueFor("keymap")
|
||||
onEdited: value => shell.cfg.system.keymap = value
|
||||
onSelected: value => shell.cfg.system.keymap = value
|
||||
Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.keymap : ""
|
||||
}
|
||||
PhoebusCombo {
|
||||
PhoebusChoice {
|
||||
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
|
||||
label: "Timezone"
|
||||
placeholder: "UTC"
|
||||
options: shell.options.timezones
|
||||
error: shell.issueFor("timezone")
|
||||
onEdited: value => shell.cfg.system.timezone = value
|
||||
onSelected: value => shell.cfg.system.timezone = value
|
||||
Component.onCompleted: inputItem.text = shell.cfg ? shell.cfg.system.timezone : ""
|
||||
}
|
||||
}
|
||||
|
|
@ -820,6 +801,15 @@ ShellRoot {
|
|||
visible: shell.cfg && !shell.isOpenCode && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai")
|
||||
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 {
|
||||
id: endpointField
|
||||
label: "Endpoint (local models)"
|
||||
|
|
@ -828,35 +818,6 @@ ShellRoot {
|
|||
onEdited: value => shell.cfg.ai.endpoint = value
|
||||
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 -----------------------------
|
||||
Text {
|
||||
width: parent.width
|
||||
|
|
@ -882,45 +843,19 @@ ShellRoot {
|
|||
visible: shell.isOpenCode
|
||||
onEdited: value => shell.opencodePassword = value
|
||||
}
|
||||
PhoebusCombo {
|
||||
PhoebusField {
|
||||
id: opencodeProviderField
|
||||
label: "Provider"
|
||||
placeholder: "choose a provider"
|
||||
options: shell.aiProviderIds
|
||||
placeholder: "deepseek"
|
||||
visible: shell.isOpenCode
|
||||
onEdited: value => shell.cfg.ai.opencode_provider = value
|
||||
onSelected: value => {
|
||||
shell.cfg.ai.opencode_provider = value;
|
||||
shell.loadAiCatalog();
|
||||
}
|
||||
}
|
||||
PhoebusCombo {
|
||||
PhoebusField {
|
||||
id: opencodeModelField
|
||||
label: "Model"
|
||||
placeholder: "choose a model"
|
||||
options: shell.aiCatalog.models
|
||||
placeholder: "deepseek-chat"
|
||||
visible: shell.isOpenCode
|
||||
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 {
|
||||
spacing: 12
|
||||
|
|
@ -1014,15 +949,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: 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: 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; placeholder: "Repeat the password"; error: shell.issueFor("password_confirm"); onEdited: value => shell.userPw2 = value }
|
||||
PhoebusField { id: pwField; label: "Password"; secret: true; 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 }
|
||||
}
|
||||
PhoebusCard {
|
||||
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: "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; placeholder: "At least 8 characters"; error: shell.issueFor("passphrase"); onEdited: value => shell.luksPw = value }
|
||||
PhoebusField { id: luks2Field; label: "Confirm passphrase"; secret: true; placeholder: "Repeat the passphrase"; error: shell.issueFor("passphrase_confirm"); onEdited: value => shell.luksPw2 = value }
|
||||
PhoebusField { id: luksField; label: "Encryption passphrase"; secret: true; 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 }
|
||||
}
|
||||
PhoebusCard {
|
||||
width: parent.width
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue