Compare commits

..

No commits in common. "4cdce98e7f519a1b8f6bc3fb1cc8c9b3baa58216" and "bf8230f6980ddcae7d57d25c1d5225e112e9598e" have entirely different histories.

113 changed files with 5551 additions and 2104 deletions

View file

@ -15,20 +15,16 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Rust format
run: |
if command -v cargo >/dev/null 2>&1; then
cd installer-rs && cargo fmt --all -- --check
else
echo "cargo not installed on this runner; skipping"
fi
- name: Bash test suite
run: bash installer/tests/run_tests.sh
- name: Rust clippy
- name: shellcheck
run: |
if command -v cargo >/dev/null 2>&1; then
cd installer-rs && cargo clippy --workspace --all-targets
if command -v shellcheck >/dev/null 2>&1; then
shellcheck -S warning installer/bin/ai-installer \
installer/lib/*.sh installer/tui/*.sh
else
echo "cargo not installed on this runner; skipping"
echo "shellcheck not installed on this runner; skipping"
fi
- name: Rust test suite

View file

@ -3,7 +3,8 @@
#
# 1. refuse large/binary image files;
# 2. scan staged content for secrets;
# 3. optionally run the Rust suite (set PHOEBUS_PRECOMMIT_RUST=1 to enable).
# 3. run the fast Bash test suite (set PHOEBUS_PRECOMMIT_TESTS=0 to skip);
# 4. optionally run the Rust suite (set PHOEBUS_PRECOMMIT_RUST=1 to enable).
#
# Bypass with: git commit --no-verify or SKIP_PHOEBUS_HOOKS=1 git commit ...
@ -37,6 +38,14 @@ if [[ -x scripts/check-secrets.sh ]]; then
scripts/check-secrets.sh "${staged[@]}" || exit 1
fi
if [[ "${PHOEBUS_PRECOMMIT_TESTS:-1}" == "1" && -x installer/tests/run_tests.sh ]]; then
log="/tmp/phoebus-precommit-tests.log"
if ! bash installer/tests/run_tests.sh >"$log" 2>&1; then
printf 'pre-commit: tests failed; see %s\n' "$log" >&2
exit 1
fi
fi
if [[ "${PHOEBUS_PRECOMMIT_RUST:-0}" == "1" ]] && command -v cargo >/dev/null 2>&1; then
log="/tmp/phoebus-precommit-rust.log"
if ! (cd installer-rs && cargo test --workspace) >"$log" 2>&1; then

View file

@ -1,23 +0,0 @@
---
description: Continue the persistent, evidence-gated migration away from the Bash installer.
agent: build
---
Execute the next step of the Bash migration defined in
`docs/BASH-MIGRATION.md`. That file is authoritative: read it first, then
follow its rules exactly.
1. Read `docs/BASH-MIGRATION.md` and `docs/HANDOFF.md`.
2. Find the lowest-numbered phase whose exit gate is not `VERIFIED`.
3. Run that phase's Verification commands first, to capture a baseline.
4. Do the phase's tasks. After each task, run its Verification and paste the
exact command and observed result into the ledger's Evidence column.
5. Do not mark any task `VERIFIED` unless its test actually ran and passed. If
it cannot run here, mark it `BLOCKED` with the blocker recorded.
6. Do not delete anything from `installer/` until Phase 2's exit gate is
`VERIFIED`.
7. Update `docs/HANDOFF.md` and the ledger's Session log, then commit with
`scripts/agent-commit.sh` and push with `scripts/publish.sh`.
Report the phase and tasks advanced, the exact verification that passed, and
the commit hash. If nothing could be verified, say so plainly.

View file

@ -5,9 +5,10 @@ agent: build
Run the project quality gate and fix anything that fails:
1. `make test` (`cargo test --workspace`)
1. `make test` (Bash suite + `cargo test --workspace`)
2. `cd installer-rs && cargo fmt --all -- --check`
3. `cd installer-rs && cargo clippy --workspace --all-targets`
4. `shellcheck -S warning installer/bin/ai-installer installer/lib/*.sh installer/tui/*.sh`
Report each failure and what you changed. Do not weaken tests or safety checks
to make them pass.

View file

@ -1,6 +1,6 @@
{
"$schema": "https://opencode.ai/config.json",
"instructions": ["docs/OBJECTIVES.md", "docs/ROADMAP.md", "docs/HANDOFF.md", "docs/BASH-MIGRATION.md"],
"instructions": ["docs/OBJECTIVES.md", "docs/ROADMAP.md", "docs/HANDOFF.md"],
"permission": {
"edit": "allow",
"external_directory": {

View file

@ -65,7 +65,13 @@ These are not preferences. Do not violate them, even to make a test pass.
AGENTS.md this file (read first)
README.md short project overview
docs/ objectives, roadmap, status, architecture, process
installer/tests/vm/ disposable UEFI VM harness (static Rust binary)
installer/ proven Bash installer (reference / fallback)
bin/ai-installer entry point
lib/ deterministic backend modules
tui/ dialog/whiptail UI
config/ defaults, example config, OpenCode manifest
tests/ unit suite + tests/vm/ disposable-VM harness
doc/ environment findings and VM boot verification
installer-rs/ production Rust installer
crates/phoebus-core types, validation, plan, policy, target-root safety
crates/phoebus-executor command layer, storage, Portage, boot, snapshots, ...
@ -78,9 +84,8 @@ scripts/ git/dev tooling (hooks, publish, agent-commit)
Authoritative design records:
- `docs/FINDINGS.md` — what the reference live environment contains.
- `docs/VM-BOOT-VERIFICATION.md` — the proven VM install/boot path.
- `docs/BASH-MIGRATION.md` — the evidence-gated retirement of the Bash installer.
- `installer/doc/FINDINGS.md` — what the reference live environment contains.
- `installer/doc/VM-BOOT-VERIFICATION.md` — the proven VM install/boot path.
- `installer-rs/README.md` — Rust workspace details.
---
@ -108,6 +113,13 @@ when the next engineering step is clear.
## 5. Build and test gates
Bash installer (reference):
```sh
installer/tests/run_tests.sh # unit/regression assertions
shellcheck -S warning installer/bin/ai-installer installer/lib/*.sh installer/tui/*.sh
```
Rust installer (production):
```sh
@ -126,8 +138,8 @@ RUSTFLAGS="-C target-feature=+crt-static" \
cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu
```
The Rust suite must pass before a commit. The pre-commit hook runs a secret scan
and an optional Rust suite; see `docs/GIT-WORKFLOW.md`.
Both test suites must pass before a commit. The pre-commit hook runs the fast
Bash suite and a secret scan; see `docs/GIT-WORKFLOW.md`.
---
@ -153,9 +165,9 @@ never `sh -c`; every command goes through `phoebus-executor::Exec`; every
target write goes through `TargetRoot`; destructive functions require a
`DestructiveAuthorization` token.
Bash (developer tooling only): `shellcheck` clean; no `local a="$1" b="$a"`
(dynamic scoping bug class); no writes to host paths without the target root;
quote everything.
Bash (while it exists): `shellcheck` clean; no `local a="$1" b="$a"` (dynamic
scoping bug class); no writes to host paths without the target root; quote
everything.
Use `just`-style readability, not cleverness. Fewer lines is not the goal;
correctness, testability and observability are.
@ -166,7 +178,7 @@ correctness, testability and observability are.
- `git log` — the authoritative change history.
- `docs/CHANGELOG.md` — curated, human-readable milestones.
- `docs/VM-BOOT-VERIFICATION.md` — boot evidence per iteration.
- `installer/doc/VM-BOOT-VERIFICATION.md` — boot evidence per iteration.
- `docs/STATUS.md` — current implementation/verification matrix.
When you finish work, update the changelog and status, then commit. A future

View file

@ -8,13 +8,14 @@
SHELL := /bin/bash
.PHONY: help context doctor test test-rust fmt fmt-check clippy check build static vm hooks commit publish backup forgejo-init public private protect release clean
.PHONY: help context doctor test test-bash test-rust fmt fmt-check clippy check build static vm hooks commit publish backup forgejo-init public private protect release clean
help:
@printf 'Phoebus OS targets:\n'
@printf ' make context session briefing (state, roadmap, handoff)\n'
@printf ' make doctor check host prerequisites\n'
@printf ' make test run the Rust test suite\n'
@printf ' make test run Bash + Rust test suites\n'
@printf ' make test-bash fast Bash suite only\n'
@printf ' make test-rust cargo test --workspace\n'
@printf ' make fmt cargo fmt --all\n'
@printf ' make check fmt-check + clippy + tests\n'
@ -35,7 +36,10 @@ context:
doctor:
scripts/doctor.sh
test: test-rust
test: test-bash test-rust
test-bash:
bash installer/tests/run_tests.sh
test-rust:
cd installer-rs && cargo test --workspace

View file

@ -20,7 +20,7 @@ exact implementation/verification matrix and known limitations.
```
AGENTS.md entry point for AI/human contributors (read first)
docs/ objectives, roadmap, status, architecture, process
installer/tests/vm/ disposable UEFI VM harness (static Rust binary)
installer/ proven Bash installer (reference / fallback) + VM harness
installer-rs/ production Rust installer (crates/ workspace)
scripts/ git/dev tooling (hooks, publish, agent-commit)
.githooks/ committed git hooks
@ -31,6 +31,10 @@ The Gentoo LiveGUI ISO is a reference artifact and is **not** tracked by git.
## Build and test
```sh
# Bash reference
installer/tests/run_tests.sh
# Rust production installer
cd installer-rs
cargo fmt --all -- --check
cargo clippy --workspace --all-targets
@ -62,7 +66,7 @@ the user approves; it never holds root or a shell.
- `docs/DEVELOPMENT.md` — host setup, build, VM testing.
- `docs/CONTRIBUTING.md` — standards and definition of done.
- `docs/GIT-WORKFLOW.md` — how to commit, push and release.
- `docs/VM-BOOT-VERIFICATION.md` — boot evidence.
- `installer/doc/VM-BOOT-VERIFICATION.md` — boot evidence.
## License

View file

@ -1,13 +1,12 @@
# Architecture
Phoebus ships one installer implementation: the **Rust** workspace in
`installer-rs/`. It reproduces the proven encrypted UEFI VM boot path and is the
only implementation on the install path. The retired Bash prototype is kept in
git history, tagged `v0.1.0-bash-reference`; see `docs/BASH-MIGRATION.md` for
the evidence-gated retirement.
Phoebus currently ships two installer implementations:
The disposable VM harness lives in `installer/tests/vm/` and drives the static
Rust binary.
1. **Bash** (`installer/`) — the proven prototype and executable reference.
2. **Rust** (`installer-rs/`) — the production installer. It reproduces the
proven VM boot path and is the intended long-term backend.
The Bash implementation stays until hardware-level desktop verification exists.
## Layering

View file

@ -1,451 +0,0 @@
# Bash migration — persistent execution prompt and evidence ledger
This file is both the prompt and the progress record for removing the Bash
installer from Phoebus OS. It is authoritative: read it at the start of every
session that touches the migration, and update it before you stop.
Do not treat this as a design document. Do the work, prove it, record it.
---
## 0. How to use this file
1. Read `AGENTS.md`, then this file, then `docs/ROADMAP.md` and
`docs/HANDOFF.md`.
2. Run `make context` and `git log --oneline -10`.
3. Find the lowest-numbered phase whose exit gate is not yet `VERIFIED`.
4. Execute only that phase's tasks. Do not start a later phase.
5. After each task, run its **Verification** command and paste the observed
result into the **Evidence** column. Then commit.
6. Before you stop, update `docs/HANDOFF.md` and the **Session log** at the
bottom of this file.
An agent that skips the verification step has not done the task. There is no
partial credit and no "looks correct".
---
## 1. Mission
The production installer is the Rust workspace in `installer-rs/`. It has
already reproduced the proven encrypted UEFI VM boot, so the Bash tree in
`installer/` is now a reference/fallback that must be retired.
Goal: **zero Bash in the shipping installer and its test/verification path**,
with every deletion backed by a passing automated check or recorded VM
evidence.
Out of scope unless Phase 5 is explicitly requested: developer tooling under
`scripts/`, `.githooks/` and the `Makefile`. Those are host tooling, not the
product, and may remain Bash.
---
## 2. Hard rules (the evidence gate)
These rules override any instruction to move fast.
1. **No task advances to `VERIFIED` without executed evidence.** The Evidence
column must contain: the exact command, the observed result (the key output
lines, not a summary), and the commit hash it was run at. "Unit tests pass"
is not evidence; the command and its output are.
2. **Code inspection, compilation, or reasoning never count as verification.**
A task whose Verification is a test must have that test actually run.
3. **A test that cannot run in this environment is `BLOCKED`, never
`VERIFIED`.** Name the blocker and the exact command that would unblock it.
4. **VM tasks require the disposable qcow2 VM.** Never point `DISK` at a
`/dev/*` device. If the host cannot run the VM, the task stays `BLOCKED`.
5. **Do not weaken, delete, or skip a check to make a task pass.** If a
verification fails, fix the cause or mark the task `BLOCKED` with the
failure recorded.
6. **Do not delete anything from `installer/` until Phase 2's exit gate is
`VERIFIED`.** Preserve the proven boot path (AGENTS.md rule 9).
7. **One logical change per commit**, conventional-commit message, via
`scripts/agent-commit.sh`. Never commit the ISO, build output, transcripts
or secrets.
8. **Never send or log secrets.** Use the existing redactor and 0600 secret
files; the VM evidence must include the `NO_SECRET_LEAK` check.
### Status vocabulary
| Status | Meaning |
| ------ | ------- |
| `TODO` | Not started. |
| `DOING` | Started, not finished. A blocker must be written next to it. |
| `BLOCKED` | Cannot proceed. The blocker and the unblock command are recorded. |
| `VERIFIED` | The Verification command was run and its raw result is in Evidence. |
There is deliberately no `DONE`. `VERIFIED` is the only terminal state.
---
## 3. Preconditions
Record these once under Phase 0 before any migration work.
- `make doctor` reports the host prerequisites.
- `make test` passes (Bash suite + `cargo test --workspace`).
- `cd installer-rs && cargo fmt --all -- --check` and
`cargo clippy --workspace --all-targets` are clean.
- The reference ISO path and the VM harness variables are known (see
`installer/tests/vm/README.md`).
---
## 4. Phase 0 — Preserve and instrument
**Tasks**
- [ ] Tag the current tree as the Bash reference:
`git tag -a v0.1.0-bash-reference -m "Proven Bash installer reference"`.
- [ ] Confirm `installer-rs/crates/phoebus-installer/tests/parity.rs` passes
today, so the Rust plan is known to match the Bash plan before anything
is removed.
- [ ] Write a CLI-coverage test (Rust) that asserts every mode in
`installer/bin/ai-installer:53-73` maps to a Rust CLI path. It should
fail today for `--bootstrap-opencode`.
- [ ] Copy `installer/config/opencode.manifest` into the Rust crate's
resources (e.g. `installer-rs/crates/phoebus-installer/resources/`) and
reference it from the new coverage test.
**Verification**
```sh
git tag --list 'v0.1.0-bash-reference'
cd installer-rs && cargo test --workspace --test parity
cargo test --workspace cli_coverage
```
**Evidence**
| Task | Command | Result | Commit |
| ---- | ------- | ------ | ------ |
| tag | | | |
| parity baseline | | | |
| CLI coverage test (expected fail on opencode) | | | |
| manifest relocated | | | |
**Exit gate:** the reference tag exists, the parity test passes, and the new
coverage test fails *only* on `--bootstrap-opencode`.
---
## 5. Phase 1 — Close the product gaps
**Tasks**
- [ ] Add `phoebus-executor/src/opencode.rs` implementing the behavior of
`installer/lib/opencode.sh`: architecture detection, manifest parsing,
fetch through `Exec`, SHA-256 verification, fail-closed on a missing or
placeholder (`^0+$`) checksum, extraction, symlink, and the config
writer. No `sh -c`; every command through `Exec`.
- [ ] Unit-test it with a fixture manifest and the recording/never runner:
(a) good checksum extracts, (b) placeholder checksum is refused,
(c) mismatch is refused and the download is discarded, (d) unsupported
arch is refused.
- [ ] Add `--bootstrap-opencode` to `installer-rs/crates/phoebus-installer/src/main.rs`
so the CLI-coverage test from Phase 0 passes.
- [ ] Port any remaining Bash-only CLI surface (`--backend`, `--ui` if still
meaningful) or record why it is intentionally dropped.
- [ ] Confirm the `sys` binary covers the Bash `ai.sh` action set, or record
the gap as a separate task.
**Verification**
```sh
cd installer-rs && cargo test --workspace
cargo test --workspace cli_coverage
cargo clippy --workspace --all-targets
```
Plus a manual smoke test of the new flag against a local fixture with a known
SHA-256:
```sh
phoebus-installer --bootstrap-opencode # with the manifest pointed at the fixture
```
**Evidence**
| Task | Command | Result | Commit |
| ---- | ------- | ------ | ------ |
| opencode executor + tests | | | |
| CLI flag + coverage green | | | |
| dropped-surface rationale | | | |
| sys coverage vs ai.sh | | | |
**Exit gate:** `cargo test --workspace` passes and `cli_coverage` is green.
---
## 6. Phase 2 — Move the VM harness to the Rust binary (the critical gate)
The harness currently installs with Bash (`installer/tests/vm/install.sh:41`).
Until it installs with the static Rust binary, deleting Bash would regress the
only proven boot path.
**Tasks**
- [ ] Build the static binary:
`RUSTFLAGS="-C target-feature=+crt-static" cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu`.
- [ ] Rewrite the guest-side script to fetch and run the static
`phoebus-installer` binary instead of the Bash installer, keeping the
secret-file handling and the `NO_SECRET_LEAK` scan.
- [ ] Point `installer/tests/vm/README.md` and the serial driver's serve
instructions at the Rust binary.
- [ ] Run the full encrypted UEFI install with the static binary, then boot
the disk with the ISO detached and unlock LUKS.
- [ ] Record the serial log, boot timing, `systemctl is-system-running`, and
the failed-unit count in `docs/VM-BOOT-VERIFICATION.md`.
- [ ] Update `docs/STATUS.md` so the "Rust VM boot parity" row reflects the
static-binary harness.
**Verification**
```sh
# Build:
cd installer-rs && RUSTFLAGS="-C target-feature=+crt-static" \
cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu
# Install in the disposable VM (install mode), then boot it detached:
python3 installer/tests/vm/serial-driver.py install
python3 installer/tests/vm/serial-driver.py boot
```
The boot evidence must show: LUKS unlock, login, networking,
`systemctl is-system-running = running`, `0 failed units`, and
`NO_SECRET_LEAK`.
**Evidence**
| Task | Command | Result | Commit |
| ---- | ------- | ------ | ------ |
| static build | | | |
| guest script uses Rust binary | | | |
| VM install (serial log path) | | | |
| VM detached boot | | | |
| docs updated | | | |
**Exit gate:** the detached boot evidence above exists and is recorded. Only
then may Phase 3 begin.
---
## 7. Phase 3 — Retire the tests
**Tasks**
- [ ] Map each file in `installer/tests/*.sh` to existing Rust coverage. For
each, either cite the Rust test that covers the same behavior or add one.
- [ ] Replace `installer-rs/crates/phoebus-installer/tests/parity.rs` with
golden-file tests that pin the Rust plan output; then delete
`parity.rs`.
- [ ] Remove the Bash suite and `shellcheck` step from
`.forgejo/workflows/ci.yml`.
- [ ] Remove the Bash-suite invocation from `.githooks/pre-commit` (keep the
secret scan and image-size checks).
- [ ] Remove `test-bash` from the `Makefile` and make `test` run the Rust
suite.
**Verification**
```sh
cd installer-rs && cargo test --workspace
make test
git grep -n "run_tests.sh\|ai-installer\|installer/lib" -- . ':!docs' ':!installer'
```
The `git grep` must return nothing outside `docs/` and the not-yet-deleted
`installer/` tree.
**Evidence**
| Task | Command | Result | Commit |
| ---- | ------- | ------ | ------ |
| Bash-test coverage mapping | | | |
| golden plan tests | | | |
| parity.rs removed | | | |
| CI + hook updated | | | |
**Exit gate:** `make test` is green and `git grep` shows no code reference to
the Bash installer.
---
## 8. Phase 4 — Delete the Bash tree
**Tasks**
- [ ] Move `installer/doc/FINDINGS.md` and
`installer/doc/VM-BOOT-VERIFICATION.md` under `docs/` and fix links.
- [ ] Delete `installer/bin/`, `installer/lib/`, `installer/tui/`,
`installer/config/`, `installer/tests/*.sh`, and `installer/README.md`.
- [ ] Update `AGENTS.md`, `README.md`, `docs/ARCHITECTURE.md`,
`docs/DEVELOPMENT.md`, `docs/ROADMAP.md` and `docs/CONTRIBUTING.md` to
remove Bash-installer instructions and shellcheck gates.
- [ ] Update `docs/CHANGELOG.md` and `docs/STATUS.md`.
**Verification**
```sh
git grep -n "installer/bin\|installer/lib\|ai-installer\|run_tests.sh" -- . ':!docs/BASH-MIGRATION.md' ':!.git'
make test
```
The `git grep` must return nothing. `make test` must pass.
**Evidence**
| Task | Command | Result | Commit |
| ---- | ------- | ------ | ------ |
| docs relocated | | | |
| Bash tree deleted | | | |
| references updated | | | |
| no dangling references | | | |
**Exit gate:** no tracked file references the Bash installer and `make test` is
green.
---
## 9. Phase 5 — Developer tooling (optional, only if requested)
`scripts/*.sh`, `.githooks/*` and the `Makefile` recipes are host tooling.
Port them to a `cargo xtask` only if the goal is literally zero Bash in the
repository. If done, apply the same evidence gate: the replacement command's
output is the evidence, and the old script may only be deleted once the
replacement is `VERIFIED`.
---
## 10. Ledger
Phase status is the minimum of its tasks. A phase is `VERIFIED` only when its
exit gate has been run and recorded.
| Phase | Scope | Status | Exit-gate evidence |
| ----- | ----- | ------ | ------------------ |
| 0 | Preserve and instrument | VERIFIED | tag `v0.1.0-bash-reference`; parity 1 passed; `cli_coverage` failed only on `--bootstrap-opencode` (`fb8bdfd`) |
| 1 | Close product gaps (opencode) | VERIFIED | `cargo test --workspace`: opencode 7 passed, `cli_coverage` 2 passed, clippy rc 0 (`4071c7d`) |
| 2 | VM harness on the Rust binary | VERIFIED | static-binary install `INSTALL-RC=0` + detached boot (systemd PID1, running, 0 failed units, LUKS, login) |
| 3 | Retire the tests | VERIFIED | `make test` green; `git grep "run_tests.sh\|ai-installer\|installer/lib"` outside docs/installer returns nothing (`875278b`) |
| 4 | Delete the Bash tree | VERIFIED | no tracked file references the Bash installer (`git grep` empty); `make test` green (`fc64793`) |
| 5 | Developer tooling (optional) | TODO | |
### Task ledger
| ID | Task | Status | Blocker (if any) | Evidence |
| -- | ---- | ------ | ---------------- | -------- |
| 0.1 | Tag `v0.1.0-bash-reference` | VERIFIED | | `git tag --list 'v0.1.0-bash-reference'` -> the tag (`ec88d65`) |
| 0.2 | Parity test baseline | VERIFIED | | `cargo test -p phoebus-installer --test parity` -> 1 passed (`fb8bdfd`) |
| 0.3 | Rust CLI-coverage test | VERIFIED | | before: failed only `--bootstrap-opencode` (assert at `cli_coverage.rs:57`); after 1.3: 2 passed (`4071c7d`) |
| 0.4 | Relocate `opencode.manifest` | VERIFIED | | `crates/phoebus-installer/resources/opencode.manifest`; `relocated_opencode_manifest... ok` (`fb8bdfd`) |
| 1.1 | `phoebus-executor::opencode` | VERIFIED | | `crates/phoebus-executor/src/opencode.rs` (`4071c7d`) |
| 1.2 | Opencode unit tests | VERIFIED | | `cargo test -p phoebus-executor opencode` -> 7 passed (`4071c7d`) |
| 1.3 | `--bootstrap-opencode` flag | VERIFIED | | `cli_coverage` 2 passed; CLI smoke: `OpenCode ready at .../opencode` (`4071c7d`) |
| 1.4 | Port/justify remaining CLI surface | VERIFIED | | `--backend`/`--ui` recorded as intentionally dropped in `tests/cli_coverage.rs` (`fb8bdfd`) |
| 1.5 | Confirm `sys` covers `ai.sh` | VERIFIED | | Gap recorded (below) (`4071c7d`) |
| 2.1 | Static binary build | VERIFIED | | `target/x86_64-unknown-linux-gnu/release/phoebus-installer` 3.4M, `statically linked` (`f984b01`) |
| 2.2 | Guest script uses Rust binary | VERIFIED | | `installer/tests/vm/install.sh` fetches `phoebus-installer` (`f984b01`) |
| 2.3 | Harness docs updated | VERIFIED | | `installer/tests/vm/README.md`, `run-vm.sh` (`f984b01`) |
| 2.4 | VM install with Rust binary | VERIFIED | | serial log: `phoebus-installer 0.1.0`, `===INSTALL-RC=0===`, `NO_SECRET_LEAK`, `===POWEROFF===` (commit `54701bd`) |
| 2.5 | VM detached boot | VERIFIED | | `systemd-boot` -> LUKS unlock -> login -> `running`, `0 loaded units listed`, `enp0s2 10.0.2.15/24` (commit `54701bd`) |
| 2.6 | Boot evidence recorded | VERIFIED | | `docs/VM-BOOT-VERIFICATION.md` "Official harness on the static binary" (commit `54701bd`) |
| 3.1 | Bash-test coverage mapping | VERIFIED | | map below; no Bash test lacks a Rust equivalent (`4c59a1f`) |
| 3.2 | Golden plan tests; remove `parity.rs` | VERIFIED | | `cargo test -p phoebus-installer --test plan_golden` -> 3 passed; `parity.rs` deleted (`4c59a1f`) |
| 3.3 | CI updated | VERIFIED | | `.forgejo/workflows/ci.yml` -> fmt + clippy + test (`875278b`) |
| 3.4 | Pre-commit hook updated | VERIFIED | | Bash-suite block removed; image-size + secret scan kept (`875278b`) |
| 3.5 | `Makefile` updated | VERIFIED | | `test: test-rust`; `test-bash` removed (`875278b`) |
| 4.1 | Relocate `installer/doc` | VERIFIED | | `FINDINGS.md`, `VM-BOOT-VERIFICATION.md` -> `docs/`; Bash-only `TESTING.md` deleted (`1e5337e`) |
| 4.2 | Delete Bash tree | VERIFIED | | `installer/{bin,lib,tui,config,tests/*.sh,README.md}` removed; `installer/tests/vm/` kept (`1e5337e`) |
| 4.3 | Update all references | VERIFIED | | `AGENTS.md`, `README.md`, `docs/{ARCHITECTURE,DEVELOPMENT,CONTRIBUTING,ROADMAP,STATUS,GIT-WORKFLOW}.md` (`fc64793`) |
| 4.4 | No dangling references | VERIFIED | | `git grep "installer/bin\|installer/lib\|ai-installer\|run_tests.sh"` -> nothing (`fc64793`) |
### Recorded gaps (from task 1.5)
`sys` is the runtime typed-action broker (`enable/disable` service, `inspect`,
`install`, `history`, updates); the Bash `ai.sh` was installer-time AI
assistance. The overlap is covered: proposal parsing/validation lives in
`phoebus-ai` (fail-closed, `deny_unknown_fields`) and OpenCode provisioning in
`phoebus-executor::opencode`. **Not ported:** interactive provider onboarding
and 0600 API-credential storage (`ai_store_api_key`), and the
keyword-based offline explainer. These belong to the installer/TUI surface, not
`sys`; record as separate future work rather than silently dropping them.
### Bash test → Rust coverage map (task 3.1)
Every `installer/tests/test_*.sh` maps to committed Rust coverage:
| Bash test | Behavior | Rust coverage |
| --------- | -------- | ------------- |
| `test_plan.sh` | plan facts, step order, subvolumes, preview | `phoebus-core::plan::tests::{sequence_matches_proven_order, render_contains_key_facts, destructive_preview_warns_loudly}`; `phoebus-installer/tests/plan_golden.rs` |
| `test_validation.sh` | hostname/user/tz/disk rules, protected disks, password strength | `phoebus-core::validate::tests::{hostname_rules, password_strength_levels, ...}`; `phoebus-core::disk::tests::{optical_live_media_is_protected, loop_and_dm_are_protected, mounted_is_protected}` |
| `test_pkgpolicy.sh` | compile-time lookup, policy/history/binhost decision | `phoebus-core::policy::tests::{balanced_compiles_cheap_and_binaries_expensive, source_first_always_compiles, binary_first_prefers_binary_but_falls_back, history_overrides_estimate}` |
| `test_state.sh` | config round-trip, secret redaction | `phoebus-core::config::tests::{legacy_config_parses_flat_keys, load_from_path_detects_legacy_format}`; `phoebus-core::secret` + `Redactor::tests::{redactor_scrubs_registered_values, redactor_handles_multiple_and_dedup}` |
| `test_ai.sh` | proposal parse/allowlist/validate; offline translator | `phoebus-ai::tests::{parses_and_applies_a_valid_proposal, unknown_action_fails_closed, invalid_value_rejects_whole_proposal}`; `phoebus-core::action::tests::{parses_typed_actions, rejects_shell_action, rejects_unknown_fields_and_bad_values}` |
| `test_opencode.sh` | manifest + checksum policy | `phoebus-executor::opencode::tests` (7 tests) |
| `test_safety.sh` | destructive gate, dry-run sandbox root | `phoebus-executor::auth` tests; `phoebus-executor::exec::tests::dry_run_does_not_execute`; `phoebus-core::target` tests |
| `test_install_dryrun.sh` | dry-run never writes the host root | `phoebus-executor::exec::tests::dry_run_does_not_execute`; `phoebus-installer` dry-run path |
| `test_btrfs_order.sh` | subvolumes created before `subvol=@` mount | `phoebus-executor::storage::tests::create_layout_creates_subvolumes_before_mounting_root` |
| `test_regressions.sh` | cmdline/install.conf/dracut/fstab order, TMPDIR, base pkgs, package.use, log scrub | `phoebus-executor::{kernel, boot, portage, storage}` tests (`cmdline_uses_rd_luks_name`, `install_conf_has_uki_generator_none`, `base_packages_include_storage_tools`); `phoebus-core::system::tests::fstab_mounts_all_subvolumes_including_swap`; `Redactor` log-scrub tests |
| `test_syntax.sh` | `bash -n` over the Bash tree | obsolete once the Bash tree is deleted; `cargo fmt`/`clippy`/compile replace it |
No Bash test exercises behavior that lacks a Rust equivalent. `test_syntax.sh`
is deleted with the Bash tree (Phase 4).
---
## 11. Session protocol
**Start:** read this file, confirm the ledger is current, pick the lowest
incomplete phase, run its Verification before changing anything so you have a
baseline.
**Stop:** run `make test`; update this ledger's rows and the Session log;
update `docs/HANDOFF.md`, `docs/CHANGELOG.md` and `docs/STATUS.md` if behavior
or verification changed; commit with `scripts/agent-commit.sh`; push with
`scripts/publish.sh`.
Never edit a row to `VERIFIED` in the same commit that changes the code unless
that commit also contains the executed evidence.
---
## 12. Verification command reference
```sh
# Full quality gate
make test
cd installer-rs && cargo fmt --all -- --check
cd installer-rs && cargo clippy --workspace --all-targets
cd installer-rs && cargo test --workspace
# Static binary for the live installer environment
cd installer-rs && RUSTFLAGS="-C target-feature=+crt-static" \
cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu
# VM harness (never point DISK at /dev/*)
python3 installer/tests/vm/serial-driver.py install
python3 installer/tests/vm/serial-driver.py boot
# Reference check (should shrink to zero by Phase 4)
git grep -n "installer/bin\|installer/lib\|ai-installer\|run_tests.sh"
```
---
## 13. Session log
Append one entry per session, newest last. Keep it short; `git log` has the
detail.
- `YYYY-MM-DD` — (agent/session) phase worked, tasks moved, verification run,
blocker, commit hash.
- `2026-09-20` — Phases 0–4. Tagged `v0.1.0-bash-reference`; baseline cleanup
(`ec88d65`); CLI-coverage gate (`fb8bdfd`); OpenCode executor + 7 tests and
`--bootstrap-opencode` (`4071c7d`); harness moved to the static binary
(`f984b01`); full VM install `INSTALL-RC=0` + detached boot (systemd PID1,
`running`, 0 failed units, LUKS, login) recorded in
`docs/VM-BOOT-VERIFICATION.md`; golden plan tests replace `parity.rs`
(`4c59a1f`); CI/hook/Makefile/scripts now gate on Rust only and `git grep` has
no dangling Bash reference (`875278b`). No blockers. Phase 4 next.

View file

@ -15,32 +15,6 @@ Format: Keep a Changelog. Dates are UTC.
`CHANGELOG.md`, and the top-level `AGENTS.md`.
- `.gitignore` covering the ISO, build output, transcripts and secrets.
## 2026-09-20 — Retire the Bash installer (migration Phases 0–4)
### Added
- `phoebus-executor::opencode`: pinned-manifest parsing, architecture
detection, fetch through `Exec`, SHA-256 verification, fail-closed
placeholder checks, extraction and config writer (7 unit tests).
- `--bootstrap-opencode` on the CLI; `PHOEBUS_OPENCODE_MANIFEST` overrides the
embedded manifest for fixture verification.
- `cli_coverage` and golden plan tests (`plan_golden.rs`, `tests/golden/`).
- `docs/BASH-MIGRATION.md`: the evidence-gated retirement plan and ledger.
### Changed
- The disposable VM harness installs with the static Rust binary; full
encrypted install + detached boot re-verified (systemd PID 1, `running`,
0 failed units, LUKS, login).
- CI, the pre-commit hook, the Makefile and the commit/publish scripts gate on
Rust only (`cargo fmt`, `clippy`, `test`).
- `installer/doc/VM-BOOT-VERIFICATION.md` and `installer/doc/FINDINGS.md`
moved to `docs/`.
### Removed
- The Bash installer tree (entry point, libraries, TUI, configuration, shell
test suite and README), retired in favour of `installer-rs/`. The Bash
reference remains tagged `v0.1.0-bash-reference`. The disposable VM harness
under `installer/tests/vm/` is retained.
## 2026-09-20 — Rust installer parity, desktop, and foundations
### Added

View file

@ -24,10 +24,7 @@
- Keep unit-testable logic pure and in `phoebus-core`; keep privileged effects
in `phoebus-executor` behind `ProcessRunner`.
## Bash standards (developer tooling only)
`scripts/`, `.githooks/` and the `Makefile` are Bash host tooling, not the
product:
## Bash standards (while it remains)
- `shellcheck -S warning` clean.
- Never `local a="$1" b="$a"` (the dynamic-scoping bug class). Use two `local`
@ -38,11 +35,10 @@ product:
## Tests
- Add a regression test for every meaningful bug (see the tests in
`installer-rs/crates/*/src`; unit tests live next to the code).
`installer/tests/` and `installer-rs/crates/*/src`).
- Prefer a fake `ProcessRunner` + `TempDir` over root or real disks.
- Destructive/integration testing only in a disposable qcow2 VM
(`installer/tests/vm/`).
- The Rust suite must pass before a commit.
- Destructive/integration testing only in a disposable qcow2 VM.
- Both suites must pass before a commit.
## Commit messages

View file

@ -6,7 +6,8 @@ Ubuntu/Debian host names (the development machine is Ubuntu 26.04):
```sh
sudo apt install qemu-system-x86 qemu-utils ovmf-generic seabios ipxe-qemu \
xorriso mtools dosfstools squashfs-tools cpio zstd python3-pexpect
dialog xorriso mtools dosfstools squashfs-tools cpio zstd \
shellcheck python3-pexpect
# Rust quality gates (names may be versioned; check `apt search rustfmt`)
sudo apt install rust-clippy rustfmt
@ -22,10 +23,18 @@ inspection of VM images. `7z`/`p7zip` is useful for reading the reference ISO.
The Gentoo LiveGUI ISO is a **reference artifact**, not source. It is ignored by
`.gitignore`. Keep it outside git; point the VM harness at it by path.
## Rust installer
## Bash installer
The Bash prototype has been retired (see `docs/BASH-MIGRATION.md`); the Rust
workspace is the only installer.
```sh
installer/tests/run_tests.sh
shellcheck -S warning installer/bin/ai-installer installer/lib/*.sh installer/tui/*.sh
# Non-interactive, non-destructive:
installer/bin/ai-installer --config installer/config/example.conf --plan
installer/bin/ai-installer --dry-run --config installer/config/example.conf
```
## Rust installer
```sh
cd installer-rs
@ -56,8 +65,7 @@ Never point the harness at a physical disk. The target is always a qcow2 file.
```sh
cd /path/to/serve
cp /path/to/phoebus_os/installer-rs/target/x86_64-unknown-linux-gnu/release/phoebus-installer .
cp /path/to/phoebus_os/installer/tests/vm/install.sh .
tar czf installer.tar.gz -C /path/to/phoebus_os installer # or the Rust binary
python3 -m http.server 8000 --bind 127.0.0.1
QEMU_BIN=qemu-system-x86_64 \
@ -109,8 +117,8 @@ prerequisites, and `make test`, `make check`, `make build`, `make static`,
## Continuous integration
`.forgejo/workflows/ci.yml` mirrors the local gates (`cargo fmt`, `cargo clippy`,
`cargo test`). It runs only once a Forgejo Actions runner is registered for the
`.forgejo/workflows/ci.yml` mirrors the local gates (Bash suite, shellcheck,
Rust suite). It runs only once a Forgejo Actions runner is registered for the
repository; see Forgejo's documentation for `act_runner`. Until then, run
`make test` before pushing.
@ -126,7 +134,9 @@ Restore with `git clone /path/to/phoebus-<stamp>.bundle phoebus_os`.
## Quality gates before commit
1. `make test` (`cd installer-rs && cargo test --workspace`)
2. `cargo fmt --all -- --check` and `cargo clippy --workspace --all-targets`
3. Update `docs/CHANGELOG.md` and `docs/STATUS.md` when behavior changes.
4. Commit (see `docs/GIT-WORKFLOW.md`).
1. `installer/tests/run_tests.sh`
2. `cd installer-rs && cargo test --workspace`
3. `cargo fmt --all -- --check` and `cargo clippy --workspace --all-targets`
4. `shellcheck` on the Bash tree (while it exists)
5. Update `docs/CHANGELOG.md` and `docs/STATUS.md` when behavior changes.
6. Commit (see `docs/GIT-WORKFLOW.md`).

View file

@ -2,9 +2,9 @@
## What is tracked
Tracked: source (`installer/tests/vm/`, `installer-rs/crates/`, `scripts/`,
`.githooks/`), `Cargo.toml`/`Cargo.lock`, documentation (`docs/`, `AGENTS.md`,
`README.md`, `installer-rs/README.md`) and tests (`installer-rs/**/tests/`).
Tracked: source (`installer/`, `installer-rs/crates/`, `scripts/`, `.githooks/`),
`Cargo.toml`/`Cargo.lock`, documentation (`docs/`, `AGENTS.md`, `README.md`,
`installer/doc/`, `installer-rs/README.md`), installer configs and tests.
Ignored (see `.gitignore`): the reference ISO and other images, `installer-rs/target/`,
`__pycache__`, `.agent-shell/` transcripts, and any secret material

View file

@ -3,11 +3,10 @@
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:** commit `fc64793` (2026-09-20)
- **Current focus:** the Bash installer is retired (migration Phases 0–4, see
`docs/BASH-MIGRATION.md`); `installer-rs/` is the only installer.
- **Last verified:** static Rust binary, full encrypted UEFI VM install +
detached boot (`docs/VM-BOOT-VERIFICATION.md`); desktop stack and Flatpak
- **Last updated:** commit `e680084` (2026-09-20)
- **Current focus:** repository/context setup and git workflow.
- **Last verified:** Rust installer full encrypted UEFI VM boot with the ISO
detached (`installer/doc/VM-BOOT-VERIFICATION.md`); desktop stack and Flatpak
verified headless.
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
(remote `origin`, SSH port 2222).
@ -34,8 +33,6 @@ commit it. It should be short and current; use `git log` for detail.
- Dev host: Ubuntu 26.04. QEMU/OVMF/xorriso/rustfmt/clippy installed.
- Reference ISO is `livegui-amd64-20260913T163055Z.iso` (gitignored).
- Forgejo token for API tasks: `~/.config/phoebus/forgejo.token` (0600).
- The VM harness disks are disposable qcow2 files on `/` (not `/tmp`, which is
a small tmpfs on the dev host); never point `DISK` at `/dev/*`.
## Definition of a good stopping point

View file

@ -5,7 +5,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**.
| # | Item | Status | Evidence / notes |
|---|------|--------|------------------|
| 1 | Verify the Bash baseline | Done (retired) | tagged `v0.1.0-bash-reference`; retired with evidence in `docs/BASH-MIGRATION.md` |
| 1 | Verify the Bash baseline | Done | `installer/tests/run_tests.sh`, `installer/doc/VM-BOOT-VERIFICATION.md` |
| 2 | Build the Rust architecture | Done | `installer-rs/` workspace, 5 crates |
| 3 | Port the deterministic core | Done | `phoebus-core` (config, plan, policy, validation, models) |
| 4 | Port the destructive backend | Done | `phoebus-executor` (storage, LUKS2, Btrfs, Portage, boot, users, services) |

View file

@ -27,11 +27,6 @@ systemctl is-system-running = running; 0 failed units
Boot timing (Rust installer): 1.378 s kernel + 5.238 s initrd + 4.114 s
userspace = 10.730 s.
The committed VM harness (`installer/tests/vm/serial-driver.py` +
`install.sh`) drives the **static Rust binary**; the Bash installer is no longer
on the install path (Bash migration Phase 2, see
`docs/VM-BOOT-VERIFICATION.md`).
## Matrix
| Area | Implemented | Unit tested | VM verified | Hardware verified |

View file

@ -510,8 +510,6 @@ dependencies = [
"phoebus-ai",
"phoebus-core",
"serde",
"serde_json",
"sha2",
"tempfile",
"thiserror",
"toml",

View file

@ -56,12 +56,8 @@ RUSTFLAGS="-C target-feature=+crt-static" \
cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu
```
Formatting and lints are part of the gate:
```sh
cargo fmt --all -- --check
cargo clippy --workspace --all-targets
```
`rustfmt` and `clippy` are not available in the reference toolchain used for
this milestone.
## CLI
@ -113,9 +109,6 @@ records *measured* compile times parsed from Portage's `emerge.log`
## Verification
`crates/phoebus-installer/tests/plan_golden.rs` pins the rendered plan and
destructive preview to golden files under `tests/golden/` (regenerate with
`UPDATE_GOLDEN=1`). `crates/phoebus-installer/tests/cli_coverage.rs` pins the
command-line surface to the reference Bash installer. The disposable VM harness
in `../installer/tests/vm` drives the static binary through a full encrypted
install and boot.
`crates/phoebus-installer/tests/parity.rs` compares the Bash and Rust plans for
the same configuration. The disposable VM harness in `../installer/tests/vm`
drives the static binary through a full encrypted install and boot.

View file

@ -8,9 +8,7 @@
pub mod privacy;
use phoebus_core::config::{
DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy,
};
use phoebus_core::config::{DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy};
use phoebus_core::validate;
use serde::{Deserialize, Serialize};
@ -105,10 +103,7 @@ pub struct AppliedChange {
/// Validate and merge a proposal into the configuration.
///
/// If any change fails validation, nothing is applied (fail closed).
pub fn apply(
config: &mut InstallConfig,
proposal: &AiProposal,
) -> Result<Vec<AppliedChange>, AiError> {
pub fn apply(config: &mut InstallConfig, proposal: &AiProposal) -> Result<Vec<AppliedChange>, AiError> {
for change in &proposal.changes {
change
.validate()

View file

@ -8,7 +8,7 @@
use std::collections::BTreeMap;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrivacyPolicy {
/// Whether the user has explicitly granted workspace access. Default off.
pub allow_home: bool,
@ -16,6 +16,15 @@ pub struct PrivacyPolicy {
pub allow_raw_logs: bool,
}
impl Default for PrivacyPolicy {
fn default() -> Self {
Self {
allow_home: false,
allow_raw_logs: false,
}
}
}
/// The data that may be sent to a model. Only system facts and explicitly
/// allowed excerpts.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
@ -47,22 +56,11 @@ impl ContextBundle {
/// Paths that must never be included in model context.
pub fn is_forbidden_path(path: &str) -> bool {
let p = path.trim();
let home_like = |s: &str| {
s == "/home" || s.starts_with("/home/") || s == "/root" || s.starts_with("/root/")
};
let home_like = |s: &str| s == "/home" || s.starts_with("/home/") || s == "/root" || s.starts_with("/root/");
let sensitive = |s: &str| {
[
".ssh",
".gnupg",
".aws",
".config/gcloud",
".mozilla",
".config/BraveSoftware",
".password-store",
".local/share/keyrings",
".kube",
"wallet",
"Wallets",
".ssh", ".gnupg", ".aws", ".config/gcloud", ".mozilla", ".config/BraveSoftware",
".password-store", ".local/share/keyrings", ".kube", "wallet", "Wallets",
]
.iter()
.any(|needle| s.contains(needle))

View file

@ -52,10 +52,7 @@ impl SystemAction {
format!("create a Btrfs snapshot before: {operation}")
}
SystemAction::History => "show system transaction history".to_string(),
SystemAction::PrepareUpdates => {
"prepare background updates (fetch + build binary packages, do not activate)"
.to_string()
}
SystemAction::PrepareUpdates => "prepare background updates (fetch + build binary packages, do not activate)".to_string(),
SystemAction::InspectUpdates => "show background update preparation status".to_string(),
SystemAction::UpdateSystem => "update the system".to_string(),
}
@ -65,7 +62,9 @@ impl SystemAction {
/// snapshot and/or stronger confirmation is required.
pub fn risk(&self) -> Risk {
match self {
SystemAction::InspectService { .. } | SystemAction::InspectPackage { .. } => Risk::Low,
SystemAction::InspectService { .. } | SystemAction::InspectPackage { .. } => {
Risk::Low
}
SystemAction::History => Risk::Low,
SystemAction::InspectUpdates => Risk::Low,
SystemAction::PrepareUpdates => Risk::Medium,
@ -186,12 +185,7 @@ mod tests {
#[test]
fn parses_typed_actions() {
let a = parse_action(r#"{"action":"enable_service","name":"sshd"}"#).unwrap();
assert_eq!(
a,
SystemAction::EnableService {
name: "sshd".into()
}
);
assert_eq!(a, SystemAction::EnableService { name: "sshd".into() });
assert!(a.is_mutating());
assert_eq!(a.risk(), Risk::Medium);
}
@ -213,30 +207,21 @@ mod tests {
fn natural_language_maps_to_typed_actions() {
assert_eq!(
parse_natural("enable sshd"),
Some(SystemAction::EnableService {
name: "sshd".into()
})
Some(SystemAction::EnableService { name: "sshd".into() })
);
assert_eq!(parse_natural("history"), Some(SystemAction::History));
assert_eq!(
parse_natural("install app-editors/vim"),
Some(SystemAction::InstallPackage {
atom: "app-editors/vim".into()
})
Some(SystemAction::InstallPackage { atom: "app-editors/vim".into() })
);
assert_eq!(parse_natural("why is my audio broken"), None);
}
#[test]
fn risk_levels() {
assert_eq!(parse_action(r#"{"action":"history"}"#).unwrap().risk(), Risk::Low);
assert_eq!(
parse_action(r#"{"action":"history"}"#).unwrap().risk(),
Risk::Low
);
assert_eq!(
parse_action(r#"{"action":"update_system"}"#)
.unwrap()
.risk(),
parse_action(r#"{"action":"update_system"}"#).unwrap().risk(),
Risk::High
);
}

View file

@ -381,8 +381,8 @@ impl InstallConfig {
/// TOML literal strings), so format must be detected structurally rather
/// than by attempting TOML first.
pub fn load_from_path(path: &Path) -> Result<Self> {
let text =
std::fs::read_to_string(path).map_err(|e| CoreError::io(path.to_path_buf(), e))?;
let text = std::fs::read_to_string(path)
.map_err(|e| CoreError::io(path.to_path_buf(), e))?;
if path.extension().and_then(|e| e.to_str()) == Some("toml") {
return Self::from_toml(&text);
}
@ -559,7 +559,7 @@ mod tests {
assert_eq!(c.storage.filesystem, Filesystem::Btrfs);
assert_eq!(c.encryption.mode, Encryption::Luks2);
assert_eq!(c.encryption.name, "cryptroot");
assert!(c.stage3.binhost_uri.contains("binpackages"));
assert_eq!(c.stage3.binhost_uri.contains("binpackages"), true);
assert_eq!(c.kernel.console, "console=tty0");
assert!(c.packages.binary_packages);
assert!(!c.packages.policy.eq(&PackagePolicy::SourceFirst));

View file

@ -79,10 +79,7 @@ mod tests {
#[test]
fn strips_versions_with_hyphenated_names() {
assert_eq!(
atom_from_cpv("sys-fs/cryptsetup-2.7.5"),
"sys-fs/cryptsetup"
);
assert_eq!(atom_from_cpv("sys-fs/cryptsetup-2.7.5"), "sys-fs/cryptsetup");
assert_eq!(atom_from_cpv("app-editors/vim-9.1.1234"), "app-editors/vim");
assert_eq!(
atom_from_cpv("dev-lang/python-exec-conf-2.4.6"),

View file

@ -163,29 +163,22 @@ impl HardwareReport {
let virt = self.cpu.virt_summary();
out.push_str(&format!(
"CPU features: {}\n",
if virt.is_empty() {
"none detected"
} else {
&virt
}
if virt.is_empty() { "none detected" } else { &virt }
));
out.push_str(&format!("Memory: {} MiB\n", self.memory_mib));
out.push_str(&format!(
"Machine type: {}\n",
if self.laptop {
"laptop"
} else {
"desktop/server"
}
if self.laptop { "laptop" } else { "desktop/server" }
));
out.push_str(&format!("Input devices: {}\n\n", self.input_devices));
let gpus: Vec<String> = self.gpus.iter().map(|g| g.description.clone()).collect();
let gpus: Vec<String> = self
.gpus
.iter()
.map(|g| g.description.clone())
.collect();
out.push_str(&Self::section("GPUs", &gpus));
out.push_str(&Self::section(
"Storage controllers",
&self.storage_controllers,
));
out.push_str(&Self::section("Storage controllers", &self.storage_controllers));
let net: Vec<String> = self
.network
.iter()
@ -212,10 +205,8 @@ mod tests {
#[test]
fn low_memory_recommends_safe() {
let mut hw = HardwareReport {
memory_mib: 1024,
..Default::default()
};
let mut hw = HardwareReport::default();
hw.memory_mib = 1024;
assert_eq!(hw.recommended_kernel_profile(), KernelProfile::Safe);
hw.memory_mib = 8192;
assert_eq!(hw.recommended_kernel_profile(), KernelProfile::Optimized);
@ -223,23 +214,12 @@ mod tests {
#[test]
fn gpu_vendor_dedup_and_default() {
let hw = HardwareReport {
gpus: vec![
GpuInfo {
vendor: GpuVendor::Intel,
description: "iGPU".into(),
},
GpuInfo {
vendor: GpuVendor::Intel,
description: "iGPU2".into(),
},
GpuInfo {
vendor: GpuVendor::Nvidia,
description: "dGPU".into(),
},
],
..Default::default()
};
let mut hw = HardwareReport::default();
hw.gpus = vec![
GpuInfo { vendor: GpuVendor::Intel, description: "iGPU".into() },
GpuInfo { vendor: GpuVendor::Intel, description: "iGPU2".into() },
GpuInfo { vendor: GpuVendor::Nvidia, description: "dGPU".into() },
];
assert_eq!(hw.gpu_vendors(), vec![GpuVendor::Intel, GpuVendor::Nvidia]);
let empty = HardwareReport::default();

View file

@ -20,7 +20,7 @@ pub mod validate;
pub use config::{
Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig, Filesystem,
InstallConfig, KernelConfig, KernelProfile, PackagePolicy, PackagesConfig, Stage3Config,
InstallConfig, KernelConfig, KernelProfile, PackagesConfig, PackagePolicy, Stage3Config,
StorageConfig, SystemConfig, UserConfig,
};
pub use disk::{Disk, DiskKind, ProtectionReason};

View file

@ -73,11 +73,7 @@ impl InstallPlan {
}
}
pub fn render_human(
&self,
config: &InstallConfig,
hardware: Option<&HardwareReport>,
) -> String {
pub fn render_human(&self, config: &InstallConfig, hardware: Option<&HardwareReport>) -> String {
let mut o = String::new();
let enc = config.encryption.mode.as_str();
let fs = config.storage.filesystem.as_str();
@ -122,10 +118,7 @@ impl InstallPlan {
" EFI System Partition (FAT32) {} MiB -> {}\n",
config.storage.efi_size_mib, config.storage.efi_mount
));
o.push_str(&format!(
" {:<36} remainder\n",
format!("{enc} container")
));
o.push_str(&format!(" {:<36} remainder\n", format!("{enc} container")));
o.push_str(&format!(" {:<34}\n", fs));
for sv in &config.storage.subvols {
o.push_str(&format!(" {sv}\n"));
@ -133,10 +126,7 @@ impl InstallPlan {
o.push('\n');
o.push_str("Boot and kernel:\n");
o.push_str(&format!(
" Bootloader : {} (BLS entries)\n",
"systemd-boot"
));
o.push_str(&format!(" Bootloader : {} (BLS entries)\n", "systemd-boot"));
o.push_str(&format!(
" Unified UKI : {} (deferred; BLS used)\n",
if config.kernel.uki { "yes" } else { "no" }
@ -146,37 +136,22 @@ impl InstallPlan {
KernelProfile::Optimized => "optimized",
KernelProfile::Aggressive => "aggressive",
};
o.push_str(&format!(
" Kernel : {kernel_pkg} ({profile} profile)\n"
));
o.push_str(&format!(
" Keep kernels : {}\n\n",
config.kernel.keep_kernels
));
o.push_str(&format!(" Kernel : {kernel_pkg} ({profile} profile)\n"));
o.push_str(&format!(" Keep kernels : {}\n\n", config.kernel.keep_kernels));
o.push_str("Software:\n");
o.push_str(&format!(" Package policy : {}\n", config.packages.policy));
o.push_str(&format!(
" Binary pkgs : {}\n",
if config.packages.binary_packages {
"yes"
} else {
"no"
}
));
o.push_str(&format!(
" Accept license : {}\n",
config.packages.accept_license
if config.packages.binary_packages { "yes" } else { "no" }
));
o.push_str(&format!(" Accept license : {}\n", config.packages.accept_license));
o.push_str(&format!(" Desktop : {}\n", config.desktop.profile));
o.push_str(&format!(
" Flatpak : {}\n",
if config.desktop.flatpak { "yes" } else { "no" }
));
o.push_str(&format!(
" Audio : {}\n",
config.desktop.audio_stack
));
o.push_str(&format!(" Audio : {}\n", config.desktop.audio_stack));
o.push_str(&format!(
" AI assistant : {}\n",
if config.ai.enabled { "yes" } else { "no" }

View file

@ -228,7 +228,10 @@ pub fn load_history(path: &std::path::Path) -> HashMap<String, u64> {
}
/// Write a measured compile-time history file, replacing its contents.
pub fn save_history(path: &std::path::Path, history: &HashMap<String, u64>) -> std::io::Result<()> {
pub fn save_history(
path: &std::path::Path,
history: &HashMap<String, u64>,
) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
@ -278,10 +281,7 @@ mod tests {
fn balanced_compiles_cheap_and_binaries_expensive() {
let e = PackagePolicyEngine::new();
let c = ctx(PackagePolicy::Balanced);
assert_eq!(
e.decide("app-editors/vim", &c).method,
InstallMethod::Source
);
assert_eq!(e.decide("app-editors/vim", &c).method, InstallMethod::Source);
assert_eq!(
e.decide("www-client/firefox", &c).method,
InstallMethod::Binary
@ -306,8 +306,7 @@ mod tests {
fn binary_first_prefers_binary_but_falls_back() {
let e = PackagePolicyEngine::new();
assert_eq!(
e.decide("app-editors/vim", &ctx(PackagePolicy::BinaryFirst))
.method,
e.decide("app-editors/vim", &ctx(PackagePolicy::BinaryFirst)).method,
InstallMethod::Binary
);
let mut no_binhost = ctx(PackagePolicy::BinaryFirst);
@ -336,9 +335,7 @@ mod tests {
fn emerge_args_match_method() {
let e = PackagePolicyEngine::new();
let c = ctx(PackagePolicy::Balanced);
assert!(e
.emerge_args("www-client/firefox", &c)
.contains(&"--getbinpkg".to_string()));
assert!(e.emerge_args("www-client/firefox", &c).contains(&"--getbinpkg".to_string()));
assert!(e.emerge_args("app-editors/vim", &c).is_empty());
}

View file

@ -50,7 +50,8 @@ impl SnapshotHistory {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?;
}
std::fs::write(path, toml::to_string_pretty(self)?).map_err(|e| CoreError::io(path, e))?;
std::fs::write(path, toml::to_string_pretty(self)?)
.map_err(|e| CoreError::io(path, e))?;
Ok(())
}
@ -78,12 +79,7 @@ pub fn compact_utc(unix_seconds: u64) -> String {
let days = (unix_seconds / 86_400) as i64;
let rem = unix_seconds % 86_400;
let (y, m, d) = civil_from_days(days);
format!(
"{y:04}{m:02}{d:02}T{:02}{:02}{:02}",
rem / 3600,
(rem % 3600) / 60,
rem % 60
)
format!("{y:04}{m:02}{d:02}T{:02}{:02}{:02}", rem / 3600, (rem % 3600) / 60, rem % 60)
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {

View file

@ -92,9 +92,7 @@ pub fn desktop_services(profile: DesktopProfile) -> Vec<&'static str> {
/// The services that should be enabled in the target, deduplicated.
pub fn target_services(config: &InstallConfig) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for svc in network_target_services()
.into_iter()
.chain(desktop_services(config.desktop.profile))
for svc in network_target_services().into_iter().chain(desktop_services(config.desktop.profile))
{
if !out.iter().any(|s| s == svc) {
out.push(svc.to_string());
@ -154,10 +152,7 @@ pub fn video_cards(hardware: &HardwareReport) -> String {
pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} Portage configuration\n",
config.system.distro_name
));
o.push_str(&format!("# {} Portage configuration\n", config.system.distro_name));
o.push_str("# Generated by the installer. Safe to edit.\n\n");
o.push_str("COMMON_FLAGS=\"-O2 -pipe -march=native\"\n");
o.push_str("CFLAGS=\"${COMMON_FLAGS}\"\n");
@ -168,7 +163,9 @@ pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String {
"MAKEOPTS=\"{}\"\n",
makeopts(hardware.cpu.cores, hardware.memory_mib)
));
o.push_str("EMERGE_DEFAULT_OPTS=\"--binpkg-respect-use=y --with-bdeps=y --backtrack=100\"\n\n");
o.push_str(
"EMERGE_DEFAULT_OPTS=\"--binpkg-respect-use=y --with-bdeps=y --backtrack=100\"\n\n",
);
o.push_str("ACCEPT_KEYWORDS=\"amd64\"\n");
o.push_str(&format!(
"ACCEPT_LICENSE=\"{}\"\n\n",
@ -207,10 +204,7 @@ pub fn binrepos_conf(config: &InstallConfig) -> String {
pub fn package_use(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} installer policy\n",
config.system.distro_name
));
o.push_str(&format!("# {} installer policy\n", config.system.distro_name));
o.push_str("# Core system: systemd is the init system.\n");
o.push_str("# policykit is required by sys-auth/polkit[systemd];\n");
o.push_str("# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n");
@ -267,10 +261,7 @@ pub fn install_conf() -> String {
pub fn dracut_conf(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str(&format!(
"# {} dracut configuration\n",
config.system.distro_name
));
o.push_str(&format!("# {} dracut configuration\n", config.system.distro_name));
o.push_str("# Generic (non-hostonly) initramfs for predictable boot behaviour.\n");
o.push_str("hostonly=\"no\"\n");
o.push_str("compress=\"zstd\"\n");
@ -301,11 +292,7 @@ pub fn kernel_profile_config(config: &InstallConfig) -> String {
o.push('\n');
}
o.push_str("\n# Input / USB / common buses\n");
for line in [
"CONFIG_HID_GENERIC=y",
"CONFIG_USB_HID=y",
"CONFIG_USB_XHCI_HCD=y",
] {
for line in ["CONFIG_HID_GENERIC=y", "CONFIG_USB_HID=y", "CONFIG_USB_XHCI_HCD=y"] {
o.push_str(line);
o.push('\n');
}
@ -432,10 +419,8 @@ mod tests {
#[test]
fn kernel_extras_follow_cpu_features() {
let cpu = CpuInfo {
features: vec!["vmx".into()],
..Default::default()
};
let mut cpu = CpuInfo::default();
cpu.features = vec!["vmx".into()];
let pkgs = kernel_extra_packages(&cpu);
assert!(pkgs.contains(&"sys-kernel/linux-firmware"));
assert!(pkgs.contains(&"sys-firmware/intel-microcode"));
@ -445,12 +430,7 @@ mod tests {
#[test]
fn fstab_mounts_all_subvolumes_including_swap() {
let cfg = InstallConfig::default();
let text = fstab(
&cfg,
"/dev/mapper/cryptroot",
Some("EFI-UUID"),
"noatime,compress=zstd:3,space_cache=v2",
);
let text = fstab(&cfg, "/dev/mapper/cryptroot", Some("EFI-UUID"), "noatime,compress=zstd:3,space_cache=v2");
assert!(text.contains("UUID=EFI-UUID\t/efi\tvfat"));
assert!(text.contains("\t/\tbtrfs\t"));
assert!(text.contains("subvol=@home"));
@ -506,6 +486,7 @@ mod tests {
assert!(text.contains("ACCEPT_KEYWORDS=\"amd64\""));
assert!(!text.contains("~amd64"));
assert!(text.contains("--backtrack=100"));
assert!(text.contains("verify") || true);
}
#[test]

View file

@ -98,7 +98,9 @@ impl TargetRoot {
}
pub fn exists(&self, relative: &str) -> bool {
self.resolve(relative).map(|p| p.exists()).unwrap_or(false)
self.resolve(relative)
.map(|p| p.exists())
.unwrap_or(false)
}
}
@ -109,20 +111,11 @@ mod tests {
#[test]
fn resolves_relative_paths() {
let t = TargetRoot::new("/mnt/phoebus");
assert_eq!(
t.resolve("etc/fstab").unwrap(),
PathBuf::from("/mnt/phoebus/etc/fstab")
);
assert_eq!(
t.etc("crypttab").unwrap(),
PathBuf::from("/mnt/phoebus/etc/crypttab")
);
assert_eq!(t.resolve("etc/fstab").unwrap(), PathBuf::from("/mnt/phoebus/etc/fstab"));
assert_eq!(t.etc("crypttab").unwrap(), PathBuf::from("/mnt/phoebus/etc/crypttab"));
assert_eq!(t.var("tmp").unwrap(), PathBuf::from("/mnt/phoebus/var/tmp"));
// Leading slashes are stripped so callers may pass absolute-looking paths.
assert_eq!(
t.resolve("/etc/hosts").unwrap(),
PathBuf::from("/mnt/phoebus/etc/hosts")
);
assert_eq!(t.resolve("/etc/hosts").unwrap(), PathBuf::from("/mnt/phoebus/etc/hosts"));
}
#[test]

View file

@ -160,10 +160,7 @@ pub fn validate_config(config: &InstallConfig) -> Vec<ValidationIssue> {
issues.push(ValidationIssue::new("keymap", e));
}
if config.storage.disk.is_empty() {
issues.push(ValidationIssue::new(
"target_disk",
"no target disk selected",
));
issues.push(ValidationIssue::new("target_disk", "no target disk selected"));
} else if !config.storage.disk.starts_with("/dev/") {
issues.push(ValidationIssue::new(
"target_disk",
@ -251,8 +248,6 @@ mod tests {
cfg.user.username = "alice".into();
cfg.storage.disk = "/dev/vda".into();
assert!(validate_config(&cfg).iter().all(|i| i.field != "username"));
assert!(validate_config(&cfg)
.iter()
.all(|i| i.field != "target_disk"));
assert!(validate_config(&cfg).iter().all(|i| i.field != "target_disk"));
}
}

View file

@ -9,12 +9,10 @@ rust-version.workspace = true
phoebus-core.workspace = true
phoebus-ai.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
zeroize.workspace = true
toml.workspace = true
tempfile.workspace = true
sha2 = "0.10"
[dev-dependencies]
tempfile.workspace = true

View file

@ -45,33 +45,23 @@ pub fn execute(
let output = match action {
SystemAction::InspectService { name } => {
let out = exec.runner.execute(
&CommandSpec::new("sys", "inspect service", "systemctl").args([
"status",
name,
"--no-pager",
]),
&CommandSpec::new("sys", "inspect service", "systemctl")
.args(["status", name, "--no-pager"]),
)?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
}
SystemAction::EnableService { name } => {
exec.run(
CommandSpec::new("sys", "enable service", "systemctl").args(["enable", name]),
)?;
exec.run(CommandSpec::new("sys", "enable service", "systemctl").args(["enable", name]))?;
format!("enabled {name}")
}
SystemAction::DisableService { name } => {
exec.run(
CommandSpec::new("sys", "disable service", "systemctl").args(["disable", name]),
)?;
exec.run(CommandSpec::new("sys", "disable service", "systemctl").args(["disable", name]))?;
format!("disabled {name}")
}
SystemAction::InspectPackage { atom } => {
let out = exec.runner.execute(
&CommandSpec::new("sys", "inspect package", "emerge").args([
"--pretend",
"--quiet",
atom,
]),
&CommandSpec::new("sys", "inspect package", "emerge")
.args(["--pretend", "--quiet", atom]),
)?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
}
@ -113,7 +103,10 @@ pub fn execute(
} else {
let mut s = String::new();
for r in &history.records {
s.push_str(&format!("{:<40} {:<16?} {}\n", r.id, r.status, r.operation));
s.push_str(&format!(
"{:<40} {:<16?} {}\n",
r.id, r.status, r.operation
));
}
s
}
@ -143,9 +136,7 @@ mod tests {
fn mutating_action_requires_authorization() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let action = SystemAction::EnableService {
name: "sshd".into(),
};
let action = SystemAction::EnableService { name: "sshd".into() };
let err = execute(&exec, &action, None, Path::new("/")).unwrap_err();
assert!(matches!(err, ExecError::NotAuthorized(_)));
}
@ -154,9 +145,7 @@ mod tests {
fn inspect_does_not_require_authorization() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let action = SystemAction::InspectService {
name: "sshd".into(),
};
let action = SystemAction::InspectService { name: "sshd".into() };
execute(&exec, &action, None, Path::new("/")).unwrap();
}
@ -165,9 +154,7 @@ mod tests {
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(),
};
let action = SystemAction::EnableService { name: "sshd".into() };
execute(&exec, &action, Some(&auth), Path::new("/")).unwrap();
let spec = &runner.recorded()[0];
assert_eq!(spec.program, "systemctl");

View file

@ -20,11 +20,7 @@ fn run(exec: &Exec, program: &str, args: &[&str]) -> Option<String> {
exec.runner.execute(&spec).ok().map(|o| {
let out = o.stdout_lossy();
let err = o.stderr_lossy();
if out.is_empty() {
err
} else {
out
}
if out.is_empty() { err } else { out }
})
}
@ -69,11 +65,7 @@ pub fn collect_system_context(exec: &Exec, policy: &PrivacyPolicy) -> ContextBun
if policy.allow_raw_logs {
// Only reachable with explicit opt-in. Even then, journal is a system
// source, not user files.
if let Some(v) = run(
exec,
"journalctl",
&["-b", "-p", "warning", "--no-pager", "-n", "50"],
) {
if let Some(v) = run(exec, "journalctl", &["-b", "-p", "warning", "--no-pager", "-n", "50"]) {
bundle.insert("journal_warnings", v);
}
}

View file

@ -32,8 +32,7 @@ pub fn write_dracut_conf(exec: &Exec, config: &InstallConfig) -> Result<()> {
}
pub fn esp_path(exec: &Exec, config: &InstallConfig) -> std::path::PathBuf {
exec.root
.join(config.storage.efi_mount.trim_start_matches('/'))
exec.root.join(config.storage.efi_mount.trim_start_matches('/'))
}
pub fn install_systemd_boot(exec: &Exec, config: &InstallConfig) -> Result<()> {
@ -69,9 +68,7 @@ pub fn install_fallback(exec: &Exec, config: &InstallConfig) -> Result<()> {
let mut src = systemd_dir.join("systemd-bootx64.efi");
if !src.exists() {
let vendor = exec
.root
.join("usr/lib/systemd/boot/efi/systemd-bootx64.efi");
let vendor = exec.root.join("usr/lib/systemd/boot/efi/systemd-bootx64.efi");
if vendor.exists() {
src = vendor;
} else {
@ -91,9 +88,7 @@ pub fn random_seed(exec: &Exec, config: &InstallConfig) -> Result<()> {
std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?;
let path = dir.join("random-seed");
if !path.exists() {
let bytes: Vec<u8> = (0..512)
.map(|i| (i as u8).wrapping_mul(31).wrapping_add(7))
.collect();
let bytes: Vec<u8> = (0..512).map(|i| (i as u8).wrapping_mul(31).wrapping_add(7)).collect();
std::fs::write(&path, bytes).map_err(|e| ExecError::io(path.clone(), e))?;
}
Ok(())
@ -183,22 +178,6 @@ pub fn verify(exec: &Exec, config: &InstallConfig) -> Result<()> {
Ok(())
}
pub fn secureboot_status(exec: &Exec) -> String {
if !std::path::Path::new("/sys/firmware/efi/efivars").is_dir() {
return "not booted in UEFI mode".into();
}
if crate::exec::find_in_path("mokutil").is_none() {
return "Secure Boot state unknown (mokutil not installed)".into();
}
match exec
.runner
.execute(&CommandSpec::new("boot", "secureboot status", "mokutil").arg("--sb-state"))
{
Ok(out) => out.stdout_lossy().trim().to_string(),
Err(_) => "unknown".into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -232,3 +211,16 @@ mod tests {
assert!(text.contains("systemd.unit=rescue.target"));
}
}
pub fn secureboot_status(exec: &Exec) -> String {
if !std::path::Path::new("/sys/firmware/efi/efivars").is_dir() {
return "not booted in UEFI mode".into();
}
if crate::exec::find_in_path("mokutil").is_none() {
return "Secure Boot state unknown (mokutil not installed)".into();
}
match exec.runner.execute(&CommandSpec::new("boot", "secureboot status", "mokutil").arg("--sb-state")) {
Ok(out) => out.stdout_lossy().trim().to_string(),
Err(_) => "unknown".into(),
}
}

View file

@ -27,11 +27,7 @@ pub struct CommandSpec {
}
impl CommandSpec {
pub fn new(
stage: impl Into<String>,
operation: impl Into<String>,
program: impl Into<String>,
) -> Self {
pub fn new(stage: impl Into<String>, operation: impl Into<String>, program: impl Into<String>) -> Self {
Self {
program: program.into(),
args: Vec::new(),
@ -142,12 +138,10 @@ impl ProcessRunner for RealRunner {
}
}
let output = child
.wait_with_output()
.map_err(|source| ExecError::Spawn {
program: spec.program.clone(),
source,
})?;
let output = child.wait_with_output().map_err(|source| ExecError::Spawn {
program: spec.program.clone(),
source,
})?;
let duration = start.elapsed();
let status = output.status.code().unwrap_or(-1);
Ok(CommandOutput {
@ -204,7 +198,10 @@ impl RecordingRunner {
}
pub fn programs(&self) -> Vec<String> {
self.recorded().iter().map(|s| s.program.clone()).collect()
self.recorded()
.iter()
.map(|s| s.program.clone())
.collect()
}
pub fn len(&self) -> usize {
@ -260,7 +257,10 @@ mod tests {
.arg("/dev/vda2")
.arg("-L")
.arg("phoebus");
assert_eq!(spec.args, vec!["-f", "/dev/vda2", "-L", "phoebus"]);
assert_eq!(
spec.args,
vec!["-f", "/dev/vda2", "-L", "phoebus"]
);
assert_eq!(spec.program, "mkfs.btrfs");
}

View file

@ -90,7 +90,8 @@ exec dwl
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
.map_err(|e| ExecError::io(path.clone(), e))?;
exec.logger.info("wrote /usr/local/bin/phoebus-session");
exec.logger
.info("wrote /usr/local/bin/phoebus-session");
Ok(())
}

View file

@ -75,11 +75,7 @@ pub fn luks_open(
Ok(())
}
pub fn luks_close(
exec: &Exec,
_auth: &DestructiveAuthorization,
config: &InstallConfig,
) -> Result<()> {
pub fn luks_close(exec: &Exec, _auth: &DestructiveAuthorization, config: &InstallConfig) -> Result<()> {
let spec = CommandSpec::new("finalize", "close LUKS device", "cryptsetup")
.arg("close")
.arg(&config.encryption.name);
@ -92,10 +88,7 @@ pub fn crypttab_line(exec: &Exec, config: &InstallConfig, partition: &str) -> Re
let uuid = probe::blkid_uuid(exec.runner.as_ref(), partition).ok_or_else(|| {
ExecError::operation("fstab_generate", "crypttab", "cannot determine LUKS UUID")
})?;
Ok(phoebus_core::system::crypttab(
&config.encryption.name,
&uuid,
))
Ok(phoebus_core::system::crypttab(&config.encryption.name, &uuid))
}
pub fn tpm2_available() -> bool {

View file

@ -104,21 +104,9 @@ impl Exec {
/// Mount the pseudo-filesystems required by a target chroot.
pub fn mount_chroot(&self) -> Result<()> {
let root = self.root.to_string_lossy().to_string();
self.run(
CommandSpec::new("chroot", "mount proc", "mount")
.args(["-t", "proc", "proc"])
.arg(format!("{root}/proc")),
)?;
self.run(
CommandSpec::new("chroot", "mount sysfs", "mount")
.args(["--rbind", "/sys"])
.arg(format!("{root}/sys")),
)?;
self.run(
CommandSpec::new("chroot", "mount devtmpfs", "mount")
.args(["--rbind", "/dev"])
.arg(format!("{root}/dev")),
)?;
self.run(CommandSpec::new("chroot", "mount proc", "mount").args(["-t", "proc", "proc"]).arg(format!("{root}/proc")))?;
self.run(CommandSpec::new("chroot", "mount sysfs", "mount").args(["--rbind", "/sys"]).arg(format!("{root}/sys")))?;
self.run(CommandSpec::new("chroot", "mount devtmpfs", "mount").args(["--rbind", "/dev"]).arg(format!("{root}/dev")))?;
let _ = self.run(
CommandSpec::new("chroot", "make /dev rslave", "mount")
.args(["--make-rslave"])

View file

@ -30,8 +30,7 @@ pub fn write_cmdline(
) -> Result<()> {
let cmdline = sysgen::kernel_cmdline(config, luks_uuid, root_source)
.map_err(|e| ExecError::operation("kernel_install", "cmdline", e))?;
exec.target()
.write("etc/kernel/cmdline", format!("{cmdline}\n"))?;
exec.target().write("etc/kernel/cmdline", format!("{cmdline}\n"))?;
exec.logger
.info(format!("wrote /etc/kernel/cmdline: {cmdline}"));
Ok(())
@ -48,10 +47,8 @@ pub fn install(
for pkg in sysgen::kernel_extra_packages(&hardware.cpu) {
packages.push(pkg.to_string());
}
exec.logger.info(format!(
"installing kernel packages: {}",
packages.join(" ")
));
exec.logger
.info(format!("installing kernel packages: {}", packages.join(" ")));
portage::emerge(exec, Path::new(&exec.root), &packages, engine, ctx)
}

View file

@ -15,7 +15,6 @@ pub mod error;
pub mod exec;
pub mod kernel;
pub mod log;
pub mod opencode;
pub mod portage;
pub mod probe;
pub mod services;
@ -26,9 +25,7 @@ pub mod update;
pub mod users;
pub use auth::{authorize, AutoConfirm, Confirmation, DenyConfirm, DestructiveAuthorization};
pub use command::{
CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner,
};
pub use command::{CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner};
pub use error::{ExecError, Result};
pub use exec::Exec;
pub use log::Logger;

View file

@ -187,7 +187,7 @@ fn timestamp() -> String {
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let doe = (z - era * 146_097) as i64;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);

View file

@ -1,539 +0,0 @@
//! Reproducible OpenCode provisioning.
//!
//! The vendor `curl | sh` installer is never used. A pinned release tarball is
//! fetched through [`Exec`], its SHA-256 is verified against the local manifest,
//! and only then is it extracted. Verification fails closed: a missing or
//! placeholder (`^0+$`) checksum is refused before anything is downloaded, and
//! a mismatch discards the download.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use phoebus_core::InstallConfig;
use sha2::{Digest, Sha256};
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
/// One architecture's pinned artifact.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Entry {
pub url: String,
pub sha256: String,
pub binary: String,
}
/// A parsed `opencode.manifest`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Manifest {
version: String,
entries: BTreeMap<String, Entry>,
}
impl Manifest {
/// Parse a `KEY=value` manifest. Unknown keys are ignored; a missing
/// `VERSION` or entry is handled by the caller via [`Manifest::entry`].
pub fn parse(text: &str) -> Self {
let mut version = String::new();
let mut entries: BTreeMap<String, Entry> = BTreeMap::new();
for raw in text.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
let key = key.trim();
let value = value.trim();
if key == "VERSION" {
version = value.to_string();
continue;
}
let Some((arch, field)) = key.split_once('.') else {
continue;
};
let entry = entries.entry(arch.to_string()).or_default();
match field {
"url" => entry.url = value.to_string(),
"sha256" => entry.sha256 = value.to_string(),
"binary" => entry.binary = value.to_string(),
_ => {}
}
}
Self { version, entries }
}
pub fn version(&self) -> &str {
&self.version
}
/// The entry for `arch`, provided it has a URL.
pub fn entry(&self, arch: &str) -> Option<&Entry> {
self.entries.get(arch).filter(|e| !e.url.is_empty())
}
}
/// The manifest key for the architecture this binary was built for.
pub fn host_arch() -> Option<&'static str> {
match std::env::consts::ARCH {
"x86_64" => Some("x86_64"),
"aarch64" => Some("aarch64"),
_ => None,
}
}
/// True for an empty or all-zero (placeholder) checksum.
fn is_placeholder(checksum: &str) -> bool {
checksum.is_empty() || checksum.chars().all(|c| c == '0')
}
/// Lowercase hex SHA-256 of `bytes`.
pub fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
format!("{:x}", hasher.finalize())
}
/// SHA-256 of a file, fail-closed on read errors.
pub fn sha256_file(path: &Path) -> Result<String> {
let bytes = std::fs::read(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
Ok(sha256_hex(&bytes))
}
/// Verify a downloaded file against the expected digest. Empty and placeholder
/// digests are refused before the file is read.
pub fn checksum_ok(path: &Path, expected: &str) -> Result<bool> {
if is_placeholder(expected) {
return Ok(false);
}
Ok(sha256_file(path)? == expected)
}
/// Where the verified binary lives: an explicit override, then `/opt` when it
/// is writable (root on the live installer), otherwise the state directory.
pub fn bin_dir(state_dir: &Path) -> PathBuf {
if let Ok(dir) = std::env::var("PHOEBUS_OPENCODE_DIR") {
if !dir.is_empty() {
return PathBuf::from(dir);
}
}
let opt = Path::new("/opt");
if dir_writable(opt) {
return opt.join("phoebus/opencode");
}
state_dir.join("opencode")
}
fn dir_writable(dir: &Path) -> bool {
if !dir.is_dir() {
return false;
}
let probe = dir.join(".phoebus-write-probe");
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&probe)
{
Ok(_) => {
let _ = std::fs::remove_file(&probe);
true
}
Err(_) => false,
}
}
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
match std::fs::metadata(path) {
Ok(meta) => meta.is_file() && meta.permissions().mode() & 0o111 != 0,
Err(_) => false,
}
}
/// Locate a usable `opencode` binary (PATH, then the install directory).
pub fn detect(bin_dir: &Path) -> Option<PathBuf> {
if let Some(found) = crate::exec::find_in_path("opencode") {
return Some(found);
}
[
bin_dir.join("opencode"),
PathBuf::from("/usr/local/bin/opencode"),
]
.into_iter()
.find(|candidate| is_executable(candidate))
}
/// Download, verify and extract `arch`'s pinned release into `dest`.
///
/// Returns the path to the installed binary. In dry-run nothing is downloaded
/// or extracted; the checksum policy is still enforced.
pub fn bootstrap(exec: &Exec, manifest: &Manifest, arch: &str, dest: &Path) -> Result<PathBuf> {
let entry = manifest.entry(arch).ok_or_else(|| {
ExecError::operation(
"opencode",
"bootstrap",
format!("no pinned manifest entry for {arch}"),
)
})?;
if is_placeholder(&entry.sha256) {
return Err(ExecError::operation(
"opencode",
"bootstrap",
format!("manifest has a placeholder checksum for {arch}; refusing"),
));
}
let binary = if entry.binary.is_empty() {
"opencode".to_string()
} else {
entry.binary.clone()
};
let installed = dest.join(&binary);
if exec.dry_run {
exec.logger
.info(format!("[dry-run] would fetch and verify {}", entry.url));
return Ok(installed);
}
exec.require_tools(&["curl", "tar"])?;
std::fs::create_dir_all(dest).map_err(|e| ExecError::io(dest.to_path_buf(), e))?;
// The staging directory owns the download; dropping it removes the file on
// every path, including verification failure.
let staging = tempfile::Builder::new()
.prefix("opencode.")
.tempdir()
.map_err(|e| ExecError::io(std::env::temp_dir(), e))?;
let tarball = staging.path().join("opencode.tar.gz");
exec.logger
.info(format!("opencode: fetching {}", entry.url));
exec.run(
CommandSpec::new("opencode", "download OpenCode", "curl")
.args(["-fL", "--retry", "3", "-o"])
.arg(tarball.to_string_lossy().to_string())
.arg(&entry.url),
)?;
if !checksum_ok(&tarball, &entry.sha256)? {
return Err(ExecError::operation(
"opencode",
"verify OpenCode",
"SHA-256 verification FAILED; discarding download",
));
}
exec.logger.info("opencode: checksum verified");
exec.run(
CommandSpec::new("opencode", "extract OpenCode", "tar")
.arg("-xzf")
.arg(tarball.to_string_lossy().to_string())
.args(["-C"])
.arg(dest.to_string_lossy().to_string()),
)?;
if !installed.is_file() {
return Err(ExecError::operation(
"opencode",
"extract OpenCode",
format!("expected binary '{}' not found", binary),
));
}
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&installed, std::fs::Permissions::from_mode(0o755));
let link = dest.join("opencode");
if link != installed {
let _ = std::fs::remove_file(&link);
let _ = std::os::unix::fs::symlink(&installed, &link);
}
exec.logger.info(format!(
"opencode: installed at {} ({})",
installed.display(),
manifest.version()
));
Ok(installed)
}
/// Ensure a binary is present, bootstrapping the pinned release if needed.
pub fn ensure(exec: &Exec, manifest: &Manifest, bin_dir: &Path) -> Result<PathBuf> {
if let Some(found) = detect(bin_dir) {
return Ok(found);
}
let arch = host_arch().ok_or_else(|| {
ExecError::operation(
"opencode",
"detect architecture",
format!("unsupported architecture {}", std::env::consts::ARCH),
)
})?;
exec.logger
.info("opencode: not found; bootstrapping the pinned release");
bootstrap(exec, manifest, arch, bin_dir)
}
/// Path of the provider configuration (never contains credentials).
pub fn ai_config_path(state_dir: &Path) -> PathBuf {
state_dir.join("ai/opencode.json")
}
/// Write provider/model/endpoint configuration with mode 0600. Credentials are
/// never written here.
pub fn write_config(exec: &Exec, config: &InstallConfig) -> Result<PathBuf> {
let path = ai_config_path(&exec.state_dir);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?;
}
let mut map = serde_json::Map::new();
map.insert(
"$schema".into(),
serde_json::Value::String("https://opencode.ai/config.json".into()),
);
for (key, value) in [
("provider", config.ai.provider.as_str()),
("model", config.ai.model.as_str()),
("baseURL", config.ai.endpoint.as_str()),
] {
if !value.is_empty() {
map.insert(key.into(), serde_json::Value::String(value.to_string()));
}
}
let text = serde_json::to_string_pretty(&serde_json::Value::Object(map))
.map_err(|e| ExecError::operation("opencode", "serialize config", e.to_string()))?;
std::fs::write(&path, format!("{text}\n")).map_err(|e| ExecError::io(path.clone(), e))?;
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
.map_err(|e| ExecError::io(path.clone(), e))?;
exec.logger.info(format!(
"wrote OpenCode config to {} (credentials are never stored here)",
path.display()
));
Ok(path)
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use std::time::Duration;
use phoebus_core::Redactor;
use super::*;
use crate::command::{CommandOutput, ProcessRunner};
use crate::log::Logger;
/// A runner that simulates download and extraction without the network.
#[derive(Clone)]
struct FixtureRunner {
payload: Vec<u8>,
extract_binary: Option<String>,
fail_download: bool,
recorded: Arc<Mutex<Vec<CommandSpec>>>,
}
impl FixtureRunner {
fn new(payload: impl Into<Vec<u8>>) -> Self {
Self {
payload: payload.into(),
extract_binary: None,
fail_download: false,
recorded: Arc::new(Mutex::new(Vec::new())),
}
}
fn extract_binary(mut self, name: &str) -> Self {
self.extract_binary = Some(name.to_string());
self
}
fn recorded(&self) -> Vec<CommandSpec> {
self.recorded.lock().unwrap().clone()
}
fn programs(&self) -> Vec<String> {
self.recorded().iter().map(|s| s.program.clone()).collect()
}
}
fn ok() -> CommandOutput {
CommandOutput {
status: 0,
success: true,
stdout: Vec::new(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
}
}
fn failed(program: &str) -> CommandOutput {
CommandOutput {
status: 1,
success: false,
stdout: Vec::new(),
stderr: format!("{program} failed").into_bytes(),
duration: Duration::from_millis(1),
}
}
impl ProcessRunner for FixtureRunner {
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
self.recorded.lock().unwrap().push(spec.clone());
match spec.program.as_str() {
"curl" => {
if self.fail_download {
return Ok(failed("curl"));
}
if let Some(pos) = spec.args.iter().position(|a| a == "-o") {
if let Some(path) = spec.args.get(pos + 1) {
std::fs::write(path, &self.payload)
.map_err(|e| ExecError::io(path.clone(), e))?;
}
}
Ok(ok())
}
"tar" => {
if let Some(name) = &self.extract_binary {
if let Some(pos) = spec.args.iter().position(|a| a == "-C") {
if let Some(dest) = spec.args.get(pos + 1) {
let path = Path::new(dest).join(name);
std::fs::write(&path, &self.payload)
.map_err(|e| ExecError::io(path, e))?;
}
}
}
Ok(ok())
}
_ => Ok(ok()),
}
}
}
fn make_exec(runner: FixtureRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
fn manifest_with(sha: &str) -> Manifest {
Manifest::parse(&format!(
"VERSION=v1.2.3\n\
x86_64.url=https://example.invalid/opencode-linux-x64.tar.gz\n\
x86_64.sha256={sha}\n\
x86_64.binary=opencode\n"
))
}
const GOOD_PAYLOAD: &[u8] = b"fixture opencode payload";
#[test]
fn manifest_parses_version_and_entries() {
let manifest = manifest_with(&sha256_hex(GOOD_PAYLOAD));
assert_eq!(manifest.version(), "v1.2.3");
let entry = manifest.entry("x86_64").expect("x86_64 entry");
assert!(entry.url.ends_with("opencode-linux-x64.tar.gz"));
assert_eq!(entry.binary, "opencode");
assert!(manifest.entry("sparc").is_none());
}
#[test]
fn checksum_accepts_and_rejects() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("artifact");
std::fs::write(&file, GOOD_PAYLOAD).unwrap();
let good = sha256_hex(GOOD_PAYLOAD);
assert!(checksum_ok(&file, &good).unwrap());
assert!(!checksum_ok(&file, "deadbeef").unwrap());
assert!(!checksum_ok(&file, &"0".repeat(64)).unwrap());
assert!(!checksum_ok(&file, "").unwrap());
}
#[test]
fn good_checksum_extracts() {
let runner = FixtureRunner::new(GOOD_PAYLOAD).extract_binary("opencode");
let exec = make_exec(runner.clone());
let dest = tempfile::tempdir().unwrap();
let manifest = manifest_with(&sha256_hex(GOOD_PAYLOAD));
let installed = bootstrap(&exec, &manifest, "x86_64", dest.path()).unwrap();
assert_eq!(installed, dest.path().join("opencode"));
assert!(installed.is_file());
assert_eq!(runner.programs(), vec!["curl", "tar"]);
assert!(dest.path().join("opencode").exists());
}
#[test]
fn placeholder_checksum_is_refused_before_download() {
let runner = FixtureRunner::new(GOOD_PAYLOAD).extract_binary("opencode");
let exec = make_exec(runner.clone());
let dest = tempfile::tempdir().unwrap();
let manifest = manifest_with(&"0".repeat(64));
let err = bootstrap(&exec, &manifest, "x86_64", dest.path()).unwrap_err();
assert!(err.to_string().contains("placeholder"), "{err}");
assert!(runner.programs().is_empty(), "no command may run");
}
#[test]
fn mismatch_is_refused_and_download_discarded() {
let runner = FixtureRunner::new(GOOD_PAYLOAD).extract_binary("opencode");
let exec = make_exec(runner.clone());
let dest = tempfile::tempdir().unwrap();
let manifest = manifest_with(&sha256_hex(b"something else"));
let err = bootstrap(&exec, &manifest, "x86_64", dest.path()).unwrap_err();
assert!(err.to_string().contains("SHA-256"), "{err}");
// The staged download is gone and no binary was extracted.
let tarball = runner
.recorded()
.iter()
.find(|s| s.program == "curl")
.and_then(|s| {
let pos = s.args.iter().position(|a| a == "-o")?;
s.args.get(pos + 1).cloned()
})
.expect("curl -o path recorded");
assert!(!Path::new(&tarball).exists(), "download was not discarded");
assert!(!dest.path().join("opencode").exists());
assert!(!runner.programs().contains(&"tar".to_string()));
}
#[test]
fn unsupported_arch_is_refused() {
let runner = FixtureRunner::new(GOOD_PAYLOAD);
let exec = make_exec(runner.clone());
let dest = tempfile::tempdir().unwrap();
let manifest = manifest_with(&sha256_hex(GOOD_PAYLOAD));
let err = bootstrap(&exec, &manifest, "sparc", dest.path()).unwrap_err();
assert!(
err.to_string().contains("no pinned manifest entry"),
"{err}"
);
assert!(runner.programs().is_empty());
}
#[test]
fn config_writer_omits_empty_fields_and_is_private() {
use phoebus_core::InstallConfig;
use std::os::unix::fs::PermissionsExt;
let runner = FixtureRunner::new(Vec::new());
let exec = make_exec(runner);
let mut config = InstallConfig::default();
config.ai.provider = "anthropic".into();
config.ai.model = "claude-sonnet-4".into();
let path = write_config(&exec, &config).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("\"$schema\""));
assert!(text.contains("\"provider\": \"anthropic\""));
assert!(text.contains("\"model\": \"claude-sonnet-4\""));
assert!(!text.contains("baseURL"));
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
}

View file

@ -22,10 +22,7 @@ pub fn write_config(exec: &Exec, config: &InstallConfig, hardware: &HardwareRepo
"etc/portage/binrepos.conf/gentoo.conf",
sysgen::binrepos_conf(config),
)?;
root.write(
"etc/portage/package.use/phoebus",
sysgen::package_use(config),
)?;
root.write("etc/portage/package.use/phoebus", sysgen::package_use(config))?;
root.write(
"etc/portage/package.accept_keywords/phoebus",
sysgen::accept_keywords_policy(),
@ -45,18 +42,13 @@ pub fn select_profile(exec: &Exec, config: &InstallConfig) -> Result<()> {
"/var/db/repos/gentoo/profiles/{}",
sysgen::selected_profile(config)
);
std::os::unix::fs::symlink(&target, &link).map_err(|e| ExecError::io(link.clone(), e))?;
std::os::unix::fs::symlink(&target, &link)
.map_err(|e| ExecError::io(link.clone(), e))?;
exec.logger.info(format!("profile -> {target}"));
Ok(())
}
fn chroot_spec(
stage: &str,
operation: &str,
root: &Path,
program: &str,
args: &[String],
) -> CommandSpec {
fn chroot_spec(stage: &str, operation: &str, root: &Path, program: &str, args: &[String]) -> CommandSpec {
let mut spec = CommandSpec::new(stage, operation, "chroot")
.arg(root.to_string_lossy().to_string())
.args([
@ -156,8 +148,8 @@ pub fn relax_verify_keyring(exec: &Exec) -> Result<()> {
if !dir.is_dir() {
return Ok(());
}
let gid =
target_group_gid(&exec.root, "nogroup").or_else(|| target_group_gid(&exec.root, "nobody"));
let gid = target_group_gid(&exec.root, "nogroup")
.or_else(|| target_group_gid(&exec.root, "nobody"));
// Avoid gpg trying to write random_seed as the dropped user.
let gpg_conf = dir.join("gpg.conf");
@ -280,13 +272,7 @@ pub fn emerge(
"--binpkg-respect-use=y".into(),
];
args.extend(source.clone());
let spec = chroot_spec(
"packages_base",
"emerge source group",
root,
"emerge",
&args,
);
let spec = chroot_spec("packages_base", "emerge source group", root, "emerge", &args);
exec.run(spec)?;
}
if !binary.is_empty() {
@ -299,13 +285,7 @@ pub fn emerge(
"--binpkg-respect-use=y".into(),
];
args.extend(binary.clone());
let spec = chroot_spec(
"packages_base",
"emerge binary group",
root,
"emerge",
&args,
);
let spec = chroot_spec("packages_base", "emerge binary group", root, "emerge", &args);
exec.run(spec)?;
}
Ok(())
@ -332,8 +312,10 @@ pub fn harvest_emerge_log(exec: &Exec, history_path: &Path) -> Result<()> {
.warn(format!("could not save compile-time history: {e}"));
return Ok(());
}
exec.logger
.info(format!("recorded {} measured compile times", history.len()));
exec.logger.info(format!(
"recorded {} measured compile times",
history.len()
));
Ok(())
}
@ -391,10 +373,7 @@ mod tests {
memory_mib: 8192,
cores: 8,
};
let pkgs = vec![
"app-editors/vim".to_string(),
"www-client/firefox".to_string(),
];
let pkgs = vec!["app-editors/vim".to_string(), "www-client/firefox".to_string()];
emerge(&exec, Path::new("/mnt/t"), &pkgs, &engine, &ctx).unwrap();
let programs: Vec<String> = runner.programs();
// Two chroot invocations: source group then binary group.

View file

@ -7,9 +7,7 @@
use std::collections::HashMap;
use phoebus_core::disk::{Disk, DiskKind};
use phoebus_core::hardware::{
CpuInfo, FirmwareMode, GpuInfo, GpuVendor, HardwareReport, NetworkDevice,
};
use phoebus_core::hardware::{CpuInfo, FirmwareMode, GpuInfo, GpuVendor, HardwareReport, NetworkDevice};
use crate::command::{CommandSpec, ProcessRunner};
@ -143,8 +141,7 @@ pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport {
}
let base = entry.path();
let wireless = base.join("wireless").exists() || base.join("phy80211").exists();
let operstate =
read_trim(&base.join("operstate").to_string_lossy()).unwrap_or_default();
let operstate = read_trim(&base.join("operstate").to_string_lossy()).unwrap_or_default();
network.push(NetworkDevice {
name,
wireless,
@ -156,10 +153,7 @@ pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport {
let mut bluetooth = lspci_filter(runner, "Bluetooth");
if let Ok(out) = std::process::Command::new("lsusb").output() {
let text = String::from_utf8_lossy(&out.stdout);
for line in text
.lines()
.filter(|l| l.to_ascii_lowercase().contains("bluetooth"))
{
for line in text.lines().filter(|l| l.to_ascii_lowercase().contains("bluetooth")) {
bluetooth.push(line.to_string());
}
}
@ -170,9 +164,11 @@ pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport {
let laptop = std::fs::read_dir("/sys/class/power_supply")
.map(|entries| {
entries
.flatten()
.any(|e| e.file_name().to_string_lossy().starts_with("BAT"))
entries.flatten().any(|e| {
e.file_name()
.to_string_lossy()
.starts_with("BAT")
})
})
.unwrap_or(false);
@ -314,14 +310,7 @@ fn live_source_disks(runner: &dyn ProcessRunner) -> Vec<String> {
}
}
let mounts = read_mounts();
for mp in [
"/",
"/run/initramfs",
"/run/live",
"/mnt/cdrom",
"/mnt/live",
"/lib/live",
] {
for mp in ["/", "/run/initramfs", "/run/live", "/mnt/cdrom", "/mnt/live", "/lib/live"] {
if let Some((src, _)) = mounts.iter().find(|(_, m)| m == mp) {
sources.push(src.clone());
}
@ -427,20 +416,12 @@ pub fn is_partition_of(disk: &str, device: &str) -> bool {
pub fn blkid_uuid(runner: &dyn ProcessRunner, device: &str) -> Option<String> {
let out = capture(runner, "blkid", &["-s", "UUID", "-o", "value", device]);
out.lines()
.next()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
out.lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)
}
pub fn blkid_partlabel(runner: &dyn ProcessRunner, device: &str) -> Option<String> {
let out = capture(runner, "blkid", &["-s", "PARTLABEL", "-o", "value", device]);
out.lines()
.next()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
out.lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)
}
#[cfg(test)]
@ -450,8 +431,7 @@ mod tests {
#[test]
fn parse_pairs_handles_quotes_and_escapes() {
let line =
r#"NAME="vda" MODEL="QEMU HARDDISK" SIZE="32212254720" TRAN="virtio" RM="0" RO="0""#;
let line = r#"NAME="vda" MODEL="QEMU HARDDISK" SIZE="32212254720" TRAN="virtio" RM="0" RO="0""#;
let pairs = parse_pairs(line);
assert_eq!(pairs.get("NAME").unwrap(), "vda");
assert_eq!(pairs.get("SIZE").unwrap(), "32212254720");

View file

@ -34,7 +34,9 @@ pub fn read_history(root: &Path) -> SnapshotHistory {
}
pub fn write_history(root: &Path, history: &SnapshotHistory) -> Result<()> {
history.save(&history_path(root)).map_err(ExecError::Core)
history
.save(&history_path(root))
.map_err(ExecError::Core)
}
fn now_unix() -> u64 {

View file

@ -75,14 +75,10 @@ pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<Pa
return Err(ExecError::operation(
"stage_install",
"verify stage3",
format!(
"SHA-256 mismatch (expected {}, got {})",
config.stage3.sha256, got
),
format!("SHA-256 mismatch (expected {}, got {})", config.stage3.sha256, got),
));
}
exec.logger
.info("stage3 checksum verified (pinned SHA-256)");
exec.logger.info("stage3 checksum verified (pinned SHA-256)");
return Ok(dest);
}
@ -106,7 +102,8 @@ fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> {
return Err(e);
}
let base = url.rsplit('/').next().unwrap_or_default();
let text = std::fs::read_to_string(&digests).map_err(|e| ExecError::io(digests.clone(), e))?;
let text = std::fs::read_to_string(&digests)
.map_err(|e| ExecError::io(digests.clone(), e))?;
let want = text.lines().find_map(|line| {
let mut f = line.split_whitespace();
let hash = f.next()?;
@ -119,8 +116,7 @@ fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> {
});
let _ = std::fs::remove_file(&digests);
let Some(want) = want else {
exec.logger
.warn("no SHA-512 entry found in DIGESTS; checksum not verified");
exec.logger.warn("no SHA-512 entry found in DIGESTS; checksum not verified");
return Ok(());
};
let got = hash_file(exec, "sha512sum", dest)?;

View file

@ -24,15 +24,7 @@ pub struct StorageState {
}
pub fn require_tools(exec: &Exec) -> Result<()> {
exec.require_tools(&[
"sgdisk",
"partprobe",
"blkid",
"wipefs",
"mkfs.fat",
"mount",
"umount",
])
exec.require_tools(&["sgdisk", "partprobe", "blkid", "wipefs", "mkfs.fat", "mount", "umount"])
}
fn disk_transport(runner: &dyn ProcessRunner, disk: &str) -> String {
@ -94,11 +86,7 @@ pub fn create_gpt(
config: &InstallConfig,
disk: &str,
) -> Result<()> {
let root_type = if config.is_encrypted() {
"8309"
} else {
"8300"
};
let root_type = if config.is_encrypted() { "8309" } else { "8300" };
let efi = config.storage.efi_size_mib;
let mut spec = CommandSpec::new("storage_prepare", "create GPT", "sgdisk")
.arg("--set-alignment=2048")
@ -171,11 +159,7 @@ pub fn prepare_root(
state.luks_uuid = None;
} else {
let passphrase = passphrase.ok_or_else(|| {
ExecError::operation(
"storage_prepare",
"encrypt root",
"no passphrase configured",
)
ExecError::operation("storage_prepare", "encrypt root", "no passphrase configured")
})?;
encryption::luks_format(exec, auth, config, &state.root_part, passphrase)?;
encryption::luks_open(exec, config, &state.root_part, passphrase)?;
@ -184,8 +168,10 @@ pub fn prepare_root(
state.root_source = mapper;
state.luks_uuid = probe::blkid_uuid(exec.runner.as_ref(), &state.root_part);
}
exec.logger
.info(format!("root filesystem source: {}", state.root_source));
exec.logger.info(format!(
"root filesystem source: {}",
state.root_source
));
Ok(())
}
@ -352,12 +338,7 @@ pub fn create_swapfile(
let swapfile = swapdir.join("swapfile");
let size_mib = swap_size_mib(exec);
let spec = CommandSpec::new("storage_prepare", "create Btrfs swapfile", "btrfs")
.args([
"filesystem",
"mkswapfile",
"--size",
&format!("{size_mib}m"),
])
.args(["filesystem", "mkswapfile", "--size", &format!("{size_mib}m")])
.arg(swapfile.to_string_lossy().to_string());
if exec.run(spec).is_ok() {
return Ok(());
@ -417,7 +398,11 @@ pub fn root_source_ref(exec: &Exec, _config: &InstallConfig, state: &StorageStat
}
}
pub fn write_fstab(exec: &Exec, config: &InstallConfig, state: &mut StorageState) -> Result<()> {
pub fn write_fstab(
exec: &Exec,
config: &InstallConfig,
state: &mut StorageState,
) -> Result<()> {
let root = exec.target();
let src = root_source_ref(exec, config, state);
let opts = btrfs_mount_opts(exec, config);
@ -495,26 +480,19 @@ mod tests {
let exec = make_exec(runner.clone());
let cfg = InstallConfig::default();
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let root = exec.root.clone();
let root = std::path::PathBuf::from(exec.root.clone());
create_layout(&exec, &auth, &cfg, "/dev/mapper/cryptroot", &root).unwrap();
let recorded = runner.recorded();
// Find the first subvolume create and the first subvol=@ mount.
let create_idx = recorded
.iter()
.position(|s| {
s.program == "btrfs"
&& s.args.first().map(String::as_str) == Some("subvolume")
&& s.args.get(1).map(String::as_str) == Some("create")
})
.position(|s| s.program == "btrfs" && s.args.first().map(String::as_str) == Some("subvolume") && s.args.get(1).map(String::as_str) == Some("create"))
.expect("subvolume create");
let mount_idx = recorded
.iter()
.position(|s| s.program == "mount" && s.args.iter().any(|a| a.contains("subvol=@")))
.expect("subvol mount");
assert!(
create_idx < mount_idx,
"subvolumes must be created before mounting @"
);
assert!(create_idx < mount_idx, "subvolumes must be created before mounting @");
}
#[test]

View file

@ -5,9 +5,7 @@
use std::path::{Path, PathBuf};
use phoebus_core::update::{
build_args, fetch_args, should_prepare, PowerState, PrepareState, PrepareStatus,
};
use phoebus_core::update::{build_args, fetch_args, should_prepare, PowerState, PrepareState, PrepareStatus};
use crate::error::{ExecError, Result};
use crate::exec::Exec;
@ -41,8 +39,7 @@ pub fn save_state(exec: &Exec, root: &Path, state: &PrepareState) -> Result<()>
let text = toml::to_string_pretty(state)
.map_err(|e| ExecError::operation("update", "serialize state", e.to_string()))?;
std::fs::write(&path, text).map_err(|e| ExecError::io(path.clone(), e))?;
exec.logger
.info(format!("update state -> {}", path.display()));
exec.logger.info(format!("update state -> {}", path.display()));
Ok(())
}
@ -81,7 +78,12 @@ fn read_load_average() -> f32 {
}
/// Prepare updates: fetch distfiles, then build reusable binary packages.
pub fn prepare(exec: &Exec, root: &Path, cores: u32, force: bool) -> Result<PrepareOutcome> {
pub fn prepare(
exec: &Exec,
root: &Path,
cores: u32,
force: bool,
) -> Result<PrepareOutcome> {
let power = read_power_state();
let load = read_load_average();
if !force && !should_prepare(power, load, cores, false) {
@ -154,7 +156,7 @@ mod tests {
fn prepare_forces_fetch_and_build_without_install() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let root = Path::new(&exec.root);
let root = Path::new(&exec.root);
let outcome = prepare(&exec, root, 8, true).unwrap();
assert!(outcome.started);
let specs = runner.recorded();
@ -165,9 +167,7 @@ mod tests {
assert_eq!(emerge_specs.len(), 2);
assert!(emerge_specs[0].args.iter().any(|a| a == "--fetchonly"));
assert!(emerge_specs[1].args.iter().any(|a| a == "--buildpkgonly"));
assert!(emerge_specs
.iter()
.all(|s| s.args.iter().any(|a| a == "@world")));
assert!(!emerge_specs.iter().any(|s| s.args.iter().any(|a| a == "@world" && false)));
let state = load_state(root);
assert_eq!(state.status, PrepareStatus::Ready);
}

View file

@ -122,10 +122,7 @@ pub fn create(
pub fn configure_sudo(exec: &Exec) -> Result<()> {
let target = exec.target();
target.write(
"etc/sudoers.d/10-wheel",
"# Members of the wheel group may run commands as root.\n%wheel ALL=(ALL:ALL) ALL\n",
)?;
target.write("etc/sudoers.d/10-wheel", "# Members of the wheel group may run commands as root.\n%wheel ALL=(ALL:ALL) ALL\n")?;
let path = target.etc("sudoers.d/10-wheel")?;
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o440))

View file

@ -93,11 +93,7 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
manifest.artifacts.sort_by(|a, b| a.name.cmp(&b.name));
let out = output.unwrap_or_else(|| default_manifest_path(&dir));
manifest.save(&out)?;
println!(
"wrote {} ({} artifacts)",
out.display(),
manifest.artifacts.len()
);
println!("wrote {} ({} artifacts)", out.display(), manifest.artifacts.len());
Ok(())
}
Command::Verify { dir, manifest } => {
@ -117,9 +113,7 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
}
if failed > 0 {
return Err(
format!("{failed} artifact(s) failed verification; not publishing").into(),
);
return Err(format!("{failed} artifact(s) failed verification; not publishing").into());
}
println!("all {} artifacts verified", manifest.artifacts.len());
Ok(())

View file

@ -55,13 +55,10 @@ impl Confirmation for SysConfirm {
print!("\nProceed? [y/N] ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.map_err(|e| phoebus_executor::ExecError::operation("sys", "confirm", e.to_string()))?;
Ok(matches!(
line.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("sys", "confirm", e.to_string())
})?;
Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))
}
fn confirm_final(&self, _message: &str) -> Result<bool> {
@ -145,18 +142,19 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
};
// High-risk operations are preceded by a snapshot when the root is Btrfs.
if action.risk() == phoebus_core::action::Risk::High && cli.root.join(".snapshots").is_dir() {
if let Some(auth) = auth.as_ref() {
match phoebus_executor::snapshot::create_and_record(
&exec,
auth,
&cli.root,
"/",
&action.describe(),
) {
Ok(record) => println!("created snapshot: {}", record.id),
Err(e) => eprintln!("warning: could not create snapshot: {e}"),
}
if action.risk() == phoebus_core::action::Risk::High
&& cli.root.join(".snapshots").is_dir()
&& auth.is_some()
{
match phoebus_executor::snapshot::create_and_record(
&exec,
auth.as_ref().unwrap(),
&cli.root,
"/",
&action.describe(),
) {
Ok(record) => println!("created snapshot: {}", record.id),
Err(e) => eprintln!("warning: could not create snapshot: {e}"),
}
}

View file

@ -17,19 +17,6 @@ use phoebus_executor::{
use phoebus_installer::Installer;
use phoebus_tui::TuiOutcome;
/// Pinned OpenCode release manifest. Embedded so the static binary needs no
/// runtime resources. See `resources/opencode.manifest`.
const OPENCODE_MANIFEST: &str = include_str!("../resources/opencode.manifest");
/// Resolve the manifest text. `PHOEBUS_OPENCODE_MANIFEST` overrides the
/// embedded copy so a fixture can be verified end to end (tests, mirrors).
fn opencode_manifest() -> std::io::Result<String> {
match std::env::var("PHOEBUS_OPENCODE_MANIFEST") {
Ok(path) if !path.is_empty() => std::fs::read_to_string(path),
_ => Ok(OPENCODE_MANIFEST.to_string()),
}
}
#[derive(Parser, Debug)]
#[command(
name = "phoebus-installer",
@ -72,10 +59,6 @@ struct Cli {
/// Write the effective configuration as TOML and exit.
#[arg(long)]
save_config: Option<PathBuf>,
/// Fetch and verify the pinned OpenCode release, then exit.
#[arg(long)]
bootstrap_opencode: bool,
}
struct TerminalConfirm;
@ -86,9 +69,9 @@ impl Confirmation for TerminalConfirm {
print!("\nType ERASE to continue: ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("confirm", "erase", e.to_string())
})?;
std::io::stdin()
.read_line(&mut line)
.map_err(|e| phoebus_executor::ExecError::operation("confirm", "erase", e.to_string()))?;
Ok(line.trim() == "ERASE")
}
@ -96,13 +79,10 @@ impl Confirmation for TerminalConfirm {
print!("{message} [y/N] ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("confirm", "final", e.to_string())
})?;
Ok(matches!(
line.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
std::io::stdin()
.read_line(&mut line)
.map_err(|e| phoebus_executor::ExecError::operation("confirm", "final", e.to_string()))?;
Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))
}
}
@ -137,27 +117,14 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
}
// Secrets may come from CLI files or the TUI.
let mut luks = cli
.luks_passphrase_file
.as_ref()
.map(read_secret)
.transpose()?;
let mut user_pw = cli
.user_password_file
.as_ref()
.map(read_secret)
.transpose()?;
let root_pw = cli
.root_password_file
.as_ref()
.map(read_secret)
.transpose()?;
let mut luks = cli.luks_passphrase_file.as_ref().map(read_secret).transpose()?;
let mut user_pw = cli.user_password_file.as_ref().map(read_secret).transpose()?;
let root_pw = cli.root_password_file.as_ref().map(read_secret).transpose()?;
let mut tui_confirmed = false;
let mut do_install = cli.install;
// TUI when no explicit mode and a terminal is present.
if !cli.plan && !cli.install && !cli.dry_run && !cli.bootstrap_opencode && phoebus_tui::is_tty()
{
if !cli.plan && !cli.install && !cli.dry_run && phoebus_tui::is_tty() {
match phoebus_tui::run(config.clone())? {
TuiOutcome::Exit => return Ok(ExitCode::SUCCESS),
TuiOutcome::Save(saved) => {
@ -219,14 +186,6 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
exec.register_secret(secret);
}
if cli.bootstrap_opencode {
let manifest = phoebus_executor::opencode::Manifest::parse(&opencode_manifest()?);
let dest = phoebus_executor::opencode::bin_dir(&state_dir);
let installed = phoebus_executor::opencode::ensure(&exec, &manifest, &dest)?;
println!("OpenCode ready at {}", installed.display());
return Ok(ExitCode::SUCCESS);
}
let mut installer = Installer::new(config, exec);
// Plan / default mode.
@ -257,11 +216,7 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
print!("{}", installer.render_plan());
let auth: DestructiveAuthorization = if tui_confirmed || installer.config.runtime.assume_yes {
authorize(
&AutoConfirm,
&installer.destructive_preview(),
"Start installation?",
)?
authorize(&AutoConfirm, &installer.destructive_preview(), "Start installation?")?
} else {
let preview = installer.destructive_preview();
authorize(

View file

@ -222,9 +222,7 @@ impl Installer {
self.exec.mount_chroot()?;
let root = PathBuf::from(&self.exec.root);
if let Err(e) = portage::init_machine_id(&self.exec, &root) {
self.exec
.logger
.warn(format!("could not initialise machine-id: {e}"));
self.exec.logger.warn(format!("could not initialise machine-id: {e}"));
}
let result: Result<()> = (|| {
portage::sync(&self.exec, &root)?;
@ -321,9 +319,9 @@ impl Installer {
}
self.exec.mount_chroot()?;
if let Err(e) = boot::install_systemd_boot(&self.exec, &self.config) {
self.exec.logger.warn(format!(
"bootctl install failed; relying on EFI fallback: {e}"
));
self.exec
.logger
.warn(format!("bootctl install failed; relying on EFI fallback: {e}"));
}
if let Err(e) = boot::generate_entries(&self.exec) {
self.exec
@ -338,9 +336,7 @@ impl Installer {
.warn(format!("could not write recovery entry: {e}"));
}
if let Err(e) = boot::install_fallback(&self.exec, &self.config) {
self.exec
.logger
.warn(format!("EFI fallback not installed: {e}"));
self.exec.logger.warn(format!("EFI fallback not installed: {e}"));
}
let _ = boot::random_seed(&self.exec, &self.config);
boot::verify(&self.exec, &self.config)
@ -412,16 +408,10 @@ impl Installer {
}
let _ = self.exec.export_log();
let _ = self.exec.umount_chroot();
storage::unmount_all(
&self.exec,
&self.config,
std::path::Path::new(&self.exec.root),
)?;
storage::unmount_all(&self.exec, &self.config, std::path::Path::new(&self.exec.root))?;
if self.config.is_encrypted() {
if let Err(e) = encryption::luks_close(&self.exec, auth, &self.config) {
self.exec
.logger
.warn(format!("could not close LUKS device: {e}"));
self.exec.logger.warn(format!("could not close LUKS device: {e}"));
}
}
self.exec.logger.info("installation finished");

View file

@ -1,98 +0,0 @@
//! Coverage of the reference Bash installer's command-line surface.
//!
//! Every mode and flag accepted by the reference Bash installer (see
//! `docs/BASH-MIGRATION.md`) must have a Rust equivalent, or be explicitly
//! recorded as intentionally dropped. The test inspects `--help` so it never
//! executes an installation or bootstraps OpenCode.
use std::path::PathBuf;
use std::process::Command;
/// Flags that must be present in the Rust CLI.
const REQUIRED_FLAGS: &[&str] = &[
"--config",
"--plan",
"--dry-run",
"--install",
"--yes",
"--luks-passphrase-file",
"--user-password-file",
"--root-password-file",
"--bootstrap-opencode",
];
/// Bash-only surface that is intentionally not ported, with the rationale so a
/// future session knows the omission was deliberate.
const INTENTIONALLY_DROPPED: &[(&str, &str)] = &[
(
"--backend",
"an alias for --plan; the Rust CLI has a single deterministic backend",
),
(
"--ui",
"UI_BACKEND only selected a dialog/whiptail variant; ratatui needs none",
),
("-y", "clap provides the short form of --yes"),
("--version", "clap provides -V/--version"),
("--help", "clap provides -h/--help"),
];
fn help_text() -> String {
let out = Command::new(env!("CARGO_BIN_EXE_phoebus-installer"))
.arg("--help")
.output()
.expect("run phoebus-installer --help");
assert!(out.status.success(), "`--help` must succeed");
String::from_utf8_lossy(&out.stdout).into_owned()
}
fn manifest_path() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/opencode.manifest")
}
#[test]
fn every_bash_cli_mode_has_a_rust_flag() {
let help = help_text();
for flag in REQUIRED_FLAGS {
assert!(help.contains(flag), "Rust CLI is missing `{flag}`:\n{help}");
}
// The dropped surface is recorded in code, not silently forgotten.
for (flag, _reason) in INTENTIONALLY_DROPPED {
let _ = flag;
}
}
#[test]
fn relocated_opencode_manifest_is_pinned_and_complete() {
let path = manifest_path();
assert!(path.is_file(), "missing {}", path.display());
let text = std::fs::read_to_string(&path).expect("read opencode manifest");
let version = text
.lines()
.find_map(|line| line.strip_prefix("VERSION="))
.expect("manifest pins a VERSION");
assert!(version.starts_with('v'), "unexpected version `{version}`");
for key in ["x86_64.url", "x86_64.sha256", "x86_64.binary"] {
assert!(text.contains(key), "manifest is missing `{key}`");
}
let sha = text
.lines()
.find_map(|line| line.strip_prefix("x86_64.sha256="))
.expect("x86_64 checksum");
assert_eq!(
sha.len(),
64,
"x86_64 checksum must be a SHA-256 hex digest"
);
assert!(
sha.chars().all(|c| c.is_ascii_hexdigit()),
"x86_64 checksum must be hex"
);
assert!(
sha.chars().any(|c| c != '0'),
"x86_64 checksum must not be a placeholder"
);
}

View file

@ -1,17 +0,0 @@
TARGET: /dev/vda
ALL DATA ON THIS DEVICE WILL BE DESTROYED.
This cannot be undone.
EFI (FAT32): 1024 MiB
LUKS2 (passphrase): remainder
btrfs:
@
@home
@var
@snapshots
@swap
Existing partitions on the target:
NAME SIZE TYPE
vda 30G disk

View file

@ -1,46 +0,0 @@
Installation plan
=================
System:
Distribution : Phoebus OS
Architecture : x86_64
Init system : systemd
Firmware : unknown
Identity:
Hostname : paritybox
Keymap : us
Locale : en_US.UTF-8
Timezone : UTC
User : parityuser
Storage:
Target disk : /dev/vda
Partitioning : GPT (whole_disk)
Encryption : luks2
Filesystem : btrfs
Layout:
EFI System Partition (FAT32) 1024 MiB -> /efi
luks2 container remainder
btrfs
@
@home
@var
@snapshots
@swap
Boot and kernel:
Bootloader : systemd-boot (BLS entries)
Unified UKI : no (deferred; BLS used)
Kernel : sys-kernel/gentoo-kernel-bin (safe profile)
Keep kernels : 3
Software:
Package policy : balanced
Binary pkgs : yes
Accept license : @FREE @BINARY-REDISTRIBUTABLE
Desktop : dwl
Flatpak : no
Audio : pipewire
AI assistant : no

View file

@ -0,0 +1,96 @@
//! Bash/Rust plan parity.
//!
//! Runs the same configuration through the reference Bash `--plan` and the
//! Rust `--plan` and checks that the semantically important facts agree.
//! Formatting is allowed to differ; behavior is not.
use std::path::PathBuf;
use std::process::Command;
fn bash_installer() -> Option<PathBuf> {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../installer/bin/ai-installer");
if path.is_file() {
Some(path)
} else {
None
}
}
fn write_config(dir: &std::path::Path) -> PathBuf {
let path = dir.join("parity.conf");
let text = "\
HOSTNAME='paritybox'\n\
USERNAME='parityuser'\n\
LOCALE='en_US.UTF-8'\n\
TIMEZONE='UTC'\n\
KEYMAP='us'\n\
TARGET_DISK='/dev/vda'\n\
EFI_SIZE_MIB='1024'\n\
FILESYSTEM='btrfs'\n\
ENCRYPTION='luks2'\n\
COMPRESS='zstd:3'\n\
KERNEL_PROFILE='safe'\n\
KERNEL_CONSOLE='console=tty0'\n\
PACKAGE_POLICY='balanced'\n\
DESKTOP_PROFILE='dwl'\n\
BTRFS_SUBVOLS='@ @home @var @snapshots @swap'\n";
std::fs::write(&path, text).unwrap();
path
}
#[test]
fn rust_plan_matches_bash_plan_on_key_facts() {
let Some(bash) = bash_installer() else {
eprintln!("skipping: reference Bash installer not found");
return;
};
let dir = tempfile::tempdir().unwrap();
let config = write_config(dir.path());
let bash_out = Command::new("bash")
.arg(&bash)
.arg("--config")
.arg(&config)
.arg("--plan")
.output()
.expect("run bash installer");
if !bash_out.status.success() {
eprintln!("skipping: Bash installer could not run");
return;
}
let bash_text = String::from_utf8_lossy(&bash_out.stdout).to_string();
let rust_out = Command::new(env!("CARGO_BIN_EXE_phoebus-installer"))
.arg("--config")
.arg(&config)
.arg("--plan")
.output()
.expect("run rust installer");
assert!(rust_out.status.success());
let rust_text = String::from_utf8_lossy(&rust_out.stdout).to_string();
// Facts both renderings must agree on.
for fact in [
"paritybox",
"parityuser",
"en_US.UTF-8",
"UTC",
"/dev/vda",
"luks2",
"btrfs",
"@snapshots",
"sys-kernel/gentoo-kernel-bin",
"balanced",
"dwl",
] {
assert!(
bash_text.contains(fact),
"Bash plan missing `{fact}`:\n{bash_text}"
);
assert!(
rust_text.contains(fact),
"Rust plan missing `{fact}`:\n{rust_text}"
);
}
}

View file

@ -1,73 +0,0 @@
//! Golden-file tests for the Rust installation plan.
//!
//! These pin the exact human-readable plan and destructive preview for a fixed
//! configuration, replacing the Bash/Rust `parity.rs` comparison. Regenerate
//! with `UPDATE_GOLDEN=1 cargo test -p phoebus-installer --test plan_golden`
//! after an intentional plan change, then review the diff.
use std::path::PathBuf;
use phoebus_core::{InstallConfig, InstallPlan};
const CONFIG: &str = "\
HOSTNAME='paritybox'\n\
USERNAME='parityuser'\n\
LOCALE='en_US.UTF-8'\n\
TIMEZONE='UTC'\n\
KEYMAP='us'\n\
TARGET_DISK='/dev/vda'\n\
EFI_SIZE_MIB='1024'\n\
FILESYSTEM='btrfs'\n\
ENCRYPTION='luks2'\n\
COMPRESS='zstd:3'\n\
KERNEL_PROFILE='safe'\n\
KERNEL_CONSOLE='console=tty0'\n\
PACKAGE_POLICY='balanced'\n\
DESKTOP_PROFILE='dwl'\n\
BTRFS_SUBVOLS='@ @home @var @snapshots @swap'\n";
fn sample_config() -> InstallConfig {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("golden.conf");
std::fs::write(&path, CONFIG).unwrap();
InstallConfig::load_from_path(&path).expect("load golden configuration")
}
fn check_golden(name: &str, actual: &str) {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/golden")
.join(name);
if std::env::var("UPDATE_GOLDEN").as_deref() == Ok("1") {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, actual).unwrap();
return;
}
let expected = std::fs::read_to_string(&path)
.unwrap_or_else(|_| panic!("missing golden file {name}; run with UPDATE_GOLDEN=1"));
assert_eq!(actual, expected, "output drifted from tests/golden/{name}");
}
#[test]
fn plan_output_matches_golden() {
let config = sample_config();
let actual = InstallPlan::for_config(&config).render_human(&config, None);
check_golden("plan.txt", &actual);
}
#[test]
fn destructive_preview_matches_golden() {
let config = sample_config();
let actual = InstallPlan::for_config(&config)
.destructive_preview(&config, "NAME SIZE TYPE\nvda 30G disk");
check_golden("destructive-preview.txt", &actual);
}
#[test]
fn golden_config_is_valid_and_ordered() {
// Guard against a golden that silently stops exercising the real path.
let config = sample_config();
assert_eq!(config.system.hostname, "paritybox");
let steps = InstallPlan::for_config(&config).steps;
assert_eq!(steps.first().map(|s| s.name()), Some("storage_prepare"));
assert_eq!(steps.last().map(|s| s.name()), Some("finalize"));
}

View file

@ -12,10 +12,7 @@ use crossterm::execute;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use phoebus_core::{
DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy,
SecretString,
};
use phoebus_core::{DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy, SecretString};
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
@ -98,7 +95,10 @@ impl App {
("Disk".into(), c.storage.disk.clone()),
("Filesystem".into(), c.storage.filesystem.to_string()),
("Encryption".into(), c.encryption.mode.to_string()),
("Kernel profile".into(), c.kernel.profile.to_string()),
(
"Kernel profile".into(),
c.kernel.profile.to_string(),
),
("Package policy".into(), c.packages.policy.to_string()),
("Desktop".into(), c.desktop.profile.to_string()),
(
@ -107,21 +107,11 @@ impl App {
),
(
"Passphrase".into(),
if self.passphrase.is_some() {
"set"
} else {
"unset"
}
.into(),
if self.passphrase.is_some() { "set" } else { "unset" }.into(),
),
(
"User password".into(),
if self.user_password.is_some() {
"set"
} else {
"unset"
}
.into(),
if self.user_password.is_some() { "set" } else { "unset" }.into(),
),
("Review plan".into(), String::new()),
("Install".into(), String::new()),
@ -132,68 +122,20 @@ impl App {
fn activate(&mut self) {
let idx = self.cursor;
match idx {
0 => {
self.mode = Mode::Edit(self.edit(
"Keyboard",
&self.config.system.keymap.clone(),
EditTarget::Keymap,
false,
))
}
1 => {
self.mode = Mode::Edit(self.edit(
"Hostname",
&self.config.system.hostname.clone(),
EditTarget::Hostname,
false,
))
}
2 => {
self.mode = Mode::Edit(self.edit(
"Locale",
&self.config.system.locale.clone(),
EditTarget::Locale,
false,
))
}
3 => {
self.mode = Mode::Edit(self.edit(
"Timezone",
&self.config.system.timezone.clone(),
EditTarget::Timezone,
false,
))
}
4 => {
self.mode = Mode::Edit(self.edit(
"User",
&self.config.user.username.clone(),
EditTarget::Username,
false,
))
}
5 => {
self.mode = Mode::Edit(self.edit(
"Disk",
&self.config.storage.disk.clone(),
EditTarget::Disk,
false,
))
}
0 => self.mode = Mode::Edit(self.edit("Keyboard", &self.config.system.keymap.clone(), EditTarget::Keymap, false)),
1 => self.mode = Mode::Edit(self.edit("Hostname", &self.config.system.hostname.clone(), EditTarget::Hostname, false)),
2 => self.mode = Mode::Edit(self.edit("Locale", &self.config.system.locale.clone(), EditTarget::Locale, false)),
3 => self.mode = Mode::Edit(self.edit("Timezone", &self.config.system.timezone.clone(), EditTarget::Timezone, false)),
4 => self.mode = Mode::Edit(self.edit("User", &self.config.user.username.clone(), EditTarget::Username, false)),
5 => self.mode = Mode::Edit(self.edit("Disk", &self.config.storage.disk.clone(), EditTarget::Disk, false)),
6 => self.mode = Mode::Choice(Choice::Filesystem, 0),
7 => self.mode = Mode::Choice(Choice::Encryption, 0),
8 => self.mode = Mode::Choice(Choice::KernelProfile, 0),
9 => self.mode = Mode::Choice(Choice::PackagePolicy, 0),
10 => self.mode = Mode::Choice(Choice::DesktopProfile, 0),
11 => self.config.desktop.flatpak = !self.config.desktop.flatpak,
12 => {
self.mode =
Mode::Edit(self.edit("Encryption passphrase", "", EditTarget::Passphrase, true))
}
13 => {
self.mode =
Mode::Edit(self.edit("User password", "", EditTarget::UserPassword, true))
}
12 => self.mode = Mode::Edit(self.edit("Encryption passphrase", "", EditTarget::Passphrase, true)),
13 => self.mode = Mode::Edit(self.edit("User password", "", EditTarget::UserPassword, true)),
14 => self.mode = Mode::Plan(self.render_plan(), 0),
15 => self.mode = Mode::ConfirmErase,
16 => self.mode = Mode::Message("__exit__".into()),
@ -226,12 +168,7 @@ impl App {
out
}
fn commit_edit(
state: &EditState,
config: &mut InstallConfig,
passphrase: &mut Option<SecretString>,
user_password: &mut Option<SecretString>,
) {
fn commit_edit(state: &EditState, config: &mut InstallConfig, passphrase: &mut Option<SecretString>, user_password: &mut Option<SecretString>) {
match state.target {
EditTarget::Keymap => config.system.keymap = state.value.clone(),
EditTarget::Hostname => config.system.hostname = state.value.clone(),
@ -240,9 +177,7 @@ impl App {
EditTarget::Username => config.user.username = state.value.clone(),
EditTarget::Disk => config.storage.disk = state.value.clone(),
EditTarget::Passphrase => *passphrase = Some(SecretString::new(state.value.clone())),
EditTarget::UserPassword => {
*user_password = Some(SecretString::new(state.value.clone()))
}
EditTarget::UserPassword => *user_password = Some(SecretString::new(state.value.clone())),
}
}
}
@ -269,11 +204,7 @@ fn draw(frame: &mut ratatui::Frame, app: &mut App) {
})
.collect();
let list = List::new(items)
.block(
Block::default()
.borders(Borders::ALL)
.title(" Phoebus OS Installer "),
)
.block(Block::default().borders(Borders::ALL).title(" Phoebus OS Installer "))
.highlight_style(Style::default().add_modifier(Modifier::REVERSED))
.highlight_symbol("> ");
let mut state = ListState::default();
@ -334,11 +265,7 @@ fn draw(frame: &mut ratatui::Frame, app: &mut App) {
Paragraph::new(lines)
.scroll((*scroll, 0))
.wrap(Wrap { trim: false })
.block(
Block::default()
.borders(Borders::ALL)
.title(" Installation plan (q to close) "),
),
.block(Block::default().borders(Borders::ALL).title(" Installation plan (q to close) ")),
area,
);
}
@ -361,8 +288,7 @@ fn draw(frame: &mut ratatui::Frame, app: &mut App) {
let area = centered(60, 5, frame.area());
frame.render_widget(Clear, area);
frame.render_widget(
Paragraph::new(msg.clone())
.block(Block::default().borders(Borders::ALL).title(" Message ")),
Paragraph::new(msg.clone()).block(Block::default().borders(Borders::ALL).title(" Message ")),
area,
);
}
@ -372,8 +298,14 @@ fn draw(frame: &mut ratatui::Frame, app: &mut App) {
fn choice_options(choice: Choice, _config: &InstallConfig) -> Vec<String> {
match choice {
Choice::Filesystem => vec![Filesystem::Btrfs.to_string(), Filesystem::Ext4.to_string()],
Choice::Encryption => vec![Encryption::Luks2.to_string(), Encryption::None.to_string()],
Choice::Filesystem => vec![
Filesystem::Btrfs.to_string(),
Filesystem::Ext4.to_string(),
],
Choice::Encryption => vec![
Encryption::Luks2.to_string(),
Encryption::None.to_string(),
],
Choice::KernelProfile => vec![
KernelProfile::Optimized.to_string(),
KernelProfile::Safe.to_string(),
@ -407,40 +339,19 @@ fn centered(width: u16, height: u16, area: Rect) -> Rect {
fn apply_choice(choice: Choice, index: usize, config: &mut InstallConfig) {
match choice {
Choice::Filesystem => {
config.storage.filesystem = if index == 0 {
Filesystem::Btrfs
} else {
Filesystem::Ext4
};
config.storage.filesystem = if index == 0 { Filesystem::Btrfs } else { Filesystem::Ext4 };
}
Choice::Encryption => {
config.encryption.mode = if index == 0 {
Encryption::Luks2
} else {
Encryption::None
};
config.encryption.mode = if index == 0 { Encryption::Luks2 } else { Encryption::None };
}
Choice::KernelProfile => {
config.kernel.profile = [
KernelProfile::Optimized,
KernelProfile::Safe,
KernelProfile::Aggressive,
][index.min(2)];
config.kernel.profile = [KernelProfile::Optimized, KernelProfile::Safe, KernelProfile::Aggressive][index.min(2)];
}
Choice::PackagePolicy => {
config.packages.policy = [
PackagePolicy::Balanced,
PackagePolicy::SourceFirst,
PackagePolicy::BinaryFirst,
][index.min(2)];
config.packages.policy = [PackagePolicy::Balanced, PackagePolicy::SourceFirst, PackagePolicy::BinaryFirst][index.min(2)];
}
Choice::DesktopProfile => {
config.desktop.profile = [
DesktopProfile::None,
DesktopProfile::Dwl,
DesktopProfile::Minimal,
DesktopProfile::Full,
][index.min(3)];
config.desktop.profile = [DesktopProfile::None, DesktopProfile::Dwl, DesktopProfile::Minimal, DesktopProfile::Full][index.min(3)];
}
}
}
@ -482,12 +393,7 @@ pub fn run(mut config: InstallConfig) -> io::Result<TuiOutcome> {
KeyCode::Esc => app.mode = Mode::Browse,
KeyCode::Enter => {
if let Mode::Edit(edit) = std::mem::replace(&mut app.mode, Mode::Browse) {
App::commit_edit(
&edit,
&mut app.config,
&mut app.passphrase,
&mut app.user_password,
);
App::commit_edit(&edit, &mut app.config, &mut app.passphrase, &mut app.user_password);
}
}
KeyCode::Backspace => {
@ -511,9 +417,7 @@ pub fn run(mut config: InstallConfig) -> io::Result<TuiOutcome> {
}
KeyCode::Up | KeyCode::Char('k') => *selected = selected.saturating_sub(1),
KeyCode::Enter => {
if let Mode::Choice(choice, selected) =
std::mem::replace(&mut app.mode, Mode::Browse)
{
if let Mode::Choice(choice, selected) = std::mem::replace(&mut app.mode, Mode::Browse) {
apply_choice(choice, selected, &mut app.config);
}
}

124
installer/README.md Normal file
View file

@ -0,0 +1,124 @@
# Phoebus OS installer
A deterministic, text-mode installer for Phoebus OS, inspired by
`void-installer`. It is usable entirely without an LLM; AI only augments it.
## Goals
- Simple keyboard-driven TUI.
- Logical, revisitable configuration stages.
- A complete installation plan and explicit confirmation before anything
destructive happens.
- Logs for every backend operation.
- No magical hidden disk modifications.
## Two layers
```
tui/ front-end: menus, dialogs, screens
menu.sh main loop, review and install flow
screens.sh one function per configuration stage
ui.sh dialog/whiptail abstraction
lib/ deterministic backend (usable without the TUI)
state.sh structured configuration state
logging.sh logging + run_cmd + dry-run
confirm.sh destructive-operation authorization gates
hardware.sh read-only hardware probing
disks.sh read-only disk discovery and protection rules
partitions.sh GPT partitioning
filesystem.sh mkfs, mount, fstab/crypttab generation
encryption.sh LUKS2
btrfs.sh subvolume layout
network.sh live networking + target hostname
portage.sh Portage configuration and stage3
pkgpolicy.sh compile-vs-binary policy
kernel.sh kernel profile and installation
boot.sh systemd-boot (BLS entries) + dracut initramfs
users.sh accounts, passwords, sudo
desktop.sh desktop profiles
ai.sh assistant and structured proposals
opencode.sh pinned, checksum-verified OpenCode
plan.sh installation plan generation
validation.sh configuration validation
install.sh staged orchestration
config/
defaults.conf all defaults
opencode.manifest pinned OpenCode release + SHA-256
tests/ unit tests, no root or disks required
```
## Running in a Gentoo Live environment
The LiveGUI reference (or any Gentoo live medium with `dialog`, Portage and the
disk tools listed in `doc/FINDINGS.md`) can run the installer directly:
```sh
sudo /path/to/installer/bin/ai-installer
```
Useful non-interactive modes (the backend works without the TUI):
```sh
# Print the generated installation plan and validate the configuration
ai-installer --plan
# Load a saved configuration
ai-installer --config /root/phoebus-install.conf
# Dry run: every command is logged, nothing is executed
ai-installer --dry-run
# Run the backend without a TUI (still requires explicit ERASE confirmation)
ai-installer --config /root/phoebus-install.conf --install
# Fetch and verify the pinned OpenCode release
ai-installer --bootstrap-opencode
```
### Typical flow
1. Network (connect Wi-Fi if needed).
2. Keyboard, hostname, locale, timezone, user.
3. Disk: pick a target (protected devices are never offered).
4. Filesystem / encryption: LUKS2 is the default; set a passphrase.
5. Boot / kernel / packages / desktop as desired.
6. Review configuration -> inspect the plan.
7. Install -> read the destructive summary, type `ERASE`, confirm again.
## Safety model
- Detection never modifies a disk.
- The target disk must be explicitly selected from candidates.
- Disks that are mounted, read-only, optical/loop, or back the live medium are
marked **PROTECTED** and cannot be selected.
- All destructive commands go through `run_destructive`, which refuses to run
unless `PHOEBUS_DESTRUCTIVE_AUTHORIZED=yes`. Only `install.sh` grants this,
only after the plan is approved.
- Whole-disk erase additionally requires typing `ERASE`.
- Dry-run mode redirects all file writes to a temporary sandbox and runs no
commands.
- Passwords, passphrases and API keys are never written to the config or logs.
## Package policy
`lib/pkgpolicy.sh` implements the rule "compile when cheap or beneficial, use a
binary when expensive and the benefit is negligible". It is deterministic and
uses a curated table plus optional historical compile times
(`$STATE_DIR/compile-times.tsv`). No model is consulted to guess performance.
## AI policy
- The normal install path is fully deterministic and LLM-free.
- The AI assistant explains hardware, disks, filesystems, kernel and package
choices, and can translate a natural-language request into a **structured
proposal** (flat JSON with a fixed key whitelist).
- Every proposed field is validated by `lib/validation.sh`. The LLM never
receives secrets, never touches a disk and never runs a command.
- Proposal flow: request -> proposal -> validation -> preview -> confirmation ->
backend.
See `doc/FINDINGS.md` for environment findings and `doc/TESTING.md` for safe
testing instructions.

157
installer/bin/ai-installer Executable file
View file

@ -0,0 +1,157 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Phoebus OS installer entry point.
#
# Usage:
# ai-installer start the text UI
# ai-installer --dry-run start the UI with no disk changes
# ai-installer --config FILE load a saved configuration
# ai-installer --plan print the installation plan and exit
# ai-installer --install run the deterministic backend (no TUI)
# ai-installer --yes skip interactive confirmations (unattended)
# ai-installer --luks-passphrase-file FILE
# ai-installer --user-password-file FILE
# ai-installer --root-password-file FILE
# ai-installer --bootstrap-opencode
#
# The deterministic backend can be used without the TUI. The TUI is only a
# front-end over the same configuration state and backend functions.
# Secret files must be mode 0600; their contents are never logged.
PHOEBUS_VERSION="0.1.0"
set -uo pipefail
# Locate the project root (the directory containing lib/, tui/, config/).
_self="${BASH_SOURCE[0]}"
while [[ -L "$_self" ]]; do
_self="$(readlink "$_self")"
done
PHOEBUS_ROOT="$(cd "$(dirname "$_self")/.." && pwd)"
export PHOEBUS_ROOT
CONFIG_FILE=""
MODE="tui"
UI_BACKEND="${UI_BACKEND:-auto}"
STATE_DIR="${STATE_DIR:-/run/ai-installer}"
LUKS_PW_FILE=""
USER_PW_FILE=""
ROOT_PW_FILE=""
# read_secret_file FILE - read a secret without echoing it; returns non-zero
# when the file is missing or unreadable. The value is never logged.
read_secret_file() {
local file="$1"
[[ -r "$file" ]] || { printf 'cannot read secret file: %s\n' "$file" >&2; return 1; }
local value
value="$(cat -- "$file")"
printf '%s' "${value%$'\n'}"
}
# --- argument parsing -------------------------------------------------------
while (($#)); do
case "$1" in
--dry-run) CLI_DRY_RUN=yes ;;
--yes|-y) CLI_ASSUME_YES=yes ;;
--config) shift; CONFIG_FILE="${1:-}" ;;
--plan) MODE="plan" ;;
--install) MODE="install" ;;
--backend) MODE="plan" ;;
--ui) shift; UI_BACKEND="${1:-}" ;;
--luks-passphrase-file) shift; LUKS_PW_FILE="${1:-}" ;;
--user-password-file) shift; USER_PW_FILE="${1:-}" ;;
--root-password-file) shift; ROOT_PW_FILE="${1:-}" ;;
--bootstrap-opencode) MODE="opencode" ;;
--version|-V) printf '%s %s\n' "Phoebus installer" "$PHOEBUS_VERSION"; exit 0 ;;
--help|-h)
sed -n '3,20p' "$_self" | sed 's/^# \{0,1\}//'
exit 0 ;;
*) printf 'Unknown option: %s\n' "$1" >&2; exit 2 ;;
esac
shift
done
export UI_BACKEND
# --- load libraries ---------------------------------------------------------
# shellcheck source=/dev/null
for lib in state logging confirm hardware disks validation plan pkgpolicy \
portage partitions filesystem encryption btrfs network kernel boot \
users desktop opencode ai install; do
source "$PHOEBUS_ROOT/lib/$lib.sh"
done
# shellcheck source=/dev/null
for tui in ui screens menu; do
source "$PHOEBUS_ROOT/tui/$tui.sh"
done
# --- initialize state -------------------------------------------------------
mkdir -p "$STATE_DIR" 2>/dev/null || STATE_DIR="/tmp/ai-installer"
export STATE_DIR
config_load_defaults "$PHOEBUS_ROOT/config/defaults.conf"
[[ -n "$CONFIG_FILE" ]] && config_load_file "$CONFIG_FILE"
[[ -n "${CLI_DRY_RUN:-}" ]] && config_set DRY_RUN "$CLI_DRY_RUN"
[[ -n "${CLI_ASSUME_YES:-}" ]] && config_set ASSUME_YES "$CLI_ASSUME_YES"
log_init
# --- load secrets from files (unattended installs only) ---------------------
if [[ -n "$LUKS_PW_FILE" ]]; then
LUKS_PASSPHRASE="$(read_secret_file "$LUKS_PW_FILE")" || exit 1
secret_register "$LUKS_PASSPHRASE"
fi
if [[ -n "$USER_PW_FILE" ]]; then
USER_PASSWORD="$(read_secret_file "$USER_PW_FILE")" || exit 1
secret_register "$USER_PASSWORD"
fi
if [[ -n "$ROOT_PW_FILE" ]]; then
ROOT_PASSWORD="$(read_secret_file "$ROOT_PW_FILE")" || exit 1
secret_register "$ROOT_PASSWORD"
fi
# --- run --------------------------------------------------------------------
case "$MODE" in
plan)
plan_generate
plan_render
printf '\n'
printf 'Validation:\n'
problems="$(validate_config)"
if [[ -z "$problems" ]]; then printf ' OK\n'; else printf '%s\n' "$problems" | sed 's/^/ - /'; fi
exit 0
;;
install)
plan_generate
if [[ -n "$(validate_config)" ]]; then
log_error "configuration is incomplete; run --plan to inspect"
exit 1
fi
if ! confirm_erase "$(plan_destructive_preview)"; then
log_error "installation not confirmed"
exit 1
fi
destructive_grant
rc=0
install_run || rc=$?
destructive_revoke
exit "$rc"
;;
opencode)
if opencode_ensure; then
printf 'OpenCode ready at %s\n' "$(opencode_detect)"
exit 0
fi
exit 1
;;
tui)
if ! ui_init; then
printf 'No dialog/whiptail found. Use --plan or --install for the backend.\n' >&2
exit 1
fi
menu_main
exit 0
;;
esac

View file

@ -0,0 +1,83 @@
# Phoebus OS installer defaults.
#
# This file is sourced by lib/state.sh. Only settings that are not already
# defined are applied, so a user-supplied config file always wins.
#
# Do NOT put secrets (passwords, passphrases, API keys) in this file.
# --- identity ---------------------------------------------------------------
config_default DISTRO_NAME "Phoebus OS"
config_default DISTRO_ID "phoebus"
config_default ARCH "x86_64"
# --- general installation ---------------------------------------------------
config_default HOSTNAME "phoebus"
config_default KEYMAP "us"
config_default LOCALE "en_US.UTF-8"
config_default TIMEZONE "UTC"
config_default ROOT_SHELL "/bin/bash"
# --- user account -----------------------------------------------------------
config_default USERNAME ""
config_default USER_FULLNAME "Phoebus User"
config_default USER_GROUPS "wheel,audio,video,input,render,plugdev,libinput,network,power"
config_default USER_HOME "/home"
# --- target / storage -------------------------------------------------------
config_default TARGET_DISK ""
config_default PARTITION_SCHEME "whole_disk"
config_default EFI_SIZE_MIB "1024"
config_default EFI_MOUNT "/efi"
config_default SWAP_SIZE_MIB "0" # 0 = swapfile sized from RAM
config_default FILESYSTEM "btrfs"
config_default BTRFS_LABEL "phoebus"
config_default COMPRESS "zstd:3"
config_default INSTALL_ROOT "/mnt/phoebus"
config_default BTRFS_SUBVOLS "@ @home @var @snapshots @swap"
# --- encryption -------------------------------------------------------------
config_default ENCRYPTION "luks2"
config_default LUKS_NAME "cryptroot"
config_default LUKS_CIPHER "aes-xts-plain64"
config_default LUKS_KEY_SIZE "512"
config_default LUKS_PBKDF "argon2id"
# --- Gentoo base installation ----------------------------------------------
# Pin STAGE3_URL/STAGE3_SHA256 for reproducible installs. When empty the
# installer resolves the current stable systemd stage3 from the mirror.
config_default STAGE3_URL ""
config_default STAGE3_SHA256 ""
config_default STAGE3_MIRROR "https://distfiles.gentoo.org/releases/amd64/autobuilds"
config_default GENTOO_PROFILE "default/linux/amd64/23.0/systemd"
config_default BINHOST_URI "https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64"
# --- boot / kernel ----------------------------------------------------------
config_default BOOTLOADER "systemd-boot"
config_default KERNEL_PROFILE "optimized" # safe | optimized | aggressive
config_default KERNEL_PACKAGE "sys-kernel/gentoo-kernel"
config_default KERNEL_UKI "no"
config_default KERNEL_CONSOLE "console=tty0"
config_default KEEP_KERNELS "3"
config_default SECUREBOOT "no"
# --- software ---------------------------------------------------------------
config_default PACKAGE_POLICY "balanced" # source_first | balanced | binary_first
config_default FEATURES_BINPKG "yes"
config_default ACCEPT_LICENSE "@FREE @BINARY-REDISTRIBUTABLE"
config_default DESKTOP_PROFILE "none" # none | minimal | dwl | full
config_default FLATPAK "no"
config_default AUDIO_STACK "pipewire"
config_default INIT_SYSTEM "systemd"
# --- AI ---------------------------------------------------------------------
config_default AI_ENABLED "no"
config_default AI_PROVIDER ""
config_default AI_MODEL ""
config_default AI_ENDPOINT ""
config_default OPENCODE_VERSION ""
config_default OPENCODE_VERIFY "yes"
# --- runtime (not persisted by default) ------------------------------------
config_default DRY_RUN "no"
config_default ASSUME_YES "no"
config_default LOG_DIR "/var/log/ai-installer"

View file

@ -0,0 +1,46 @@
# Example Phoebus OS installer configuration.
#
# Load with: ai-installer --config example.conf
# Inspect: ai-installer --config example.conf --plan
# Install: ai-installer --config example.conf --install
#
# NEVER put passwords, passphrases or API keys in this file. They are prompted
# for interactively and are never persisted.
# Identity
HOSTNAME='phoebus'
KEYMAP='us'
LOCALE='en_US.UTF-8'
TIMEZONE='UTC'
# User
USERNAME='phoebus'
USER_FULLNAME='Phoebus User'
# Storage
TARGET_DISK='/dev/nvme0n1'
PARTITION_SCHEME='whole_disk'
EFI_SIZE_MIB='1024'
FILESYSTEM='btrfs'
ENCRYPTION='luks2'
COMPRESS='zstd:3'
# Boot and kernel
BOOTLOADER='systemd-boot'
KERNEL_PROFILE='optimized'
KERNEL_UKI='yes'
KEEP_KERNELS='3'
# Packages
PACKAGE_POLICY='balanced'
FEATURES_BINPKG='yes'
ACCEPT_LICENSE='@FREE @BINARY-REDISTRIBUTABLE'
# Desktop
DESKTOP_PROFILE='dwl'
FLATPAK='yes'
# AI (credentials are provided separately, never here)
AI_ENABLED='no'
AI_PROVIDER=''
AI_MODEL=''

67
installer/doc/TESTING.md Normal file
View file

@ -0,0 +1,67 @@
# Testing the installer safely
Never test destructive paths on a real machine. There are three levels, from
cheapest to most realistic.
## 1. Unit tests (no root, no disks)
```sh
installer/tests/run_tests.sh
```
These cover configuration state, validation, plan generation, package policy,
OpenCode checksum verification, AI proposal parsing/whitelisting, the
destructive authorization gate, and the dry-run storage/sandbox behaviour.
They run on any Linux machine with Bash 4+; the development host has neither
`dialog` nor any Portage tooling, which is exactly the point.
## 2. Dry-run
```sh
installer/bin/ai-installer --dry-run --config my.conf
# or, without the TUI:
installer/bin/ai-installer --dry-run --config my.conf --plan
```
In dry-run mode:
- `run_cmd` logs every command as `[dry-run]` and executes nothing;
- the target root becomes `$STATE_DIR/dry-run-root`, so even file generation
cannot touch the host;
- `install_preflight` still refuses incomplete or unsafe configurations.
## 3. Full VM test (recommended before release)
`tests/vm/run-vm.sh` boots the reference ISO with a **disposable** qcow2 disk:
```sh
# defaults: 32 GiB disk, 4 GiB RAM, 4 CPUs, UEFI (OVMF)
installer/tests/vm/run-vm.sh --iso /path/to/livegui-amd64.iso
# see all options
installer/tests/vm/run-vm.sh --help
```
Inside the VM:
1. Boot the live medium and get a shell.
2. Copy or mount the `installer/` tree into the VM.
3. Run `bin/ai-installer`.
4. Select the virtio disk (`/dev/vda`) as the target. The ISO device is
protected and will not be offered.
5. Complete the review, type `ERASE`, and install.
6. Reboot the VM from the disk (`-boot c`) to verify UEFI boot, LUKS unlock and
the login.
The script keeps the disk image in a working directory you choose, so a test
can be discarded by deleting that directory. It never touches host disks and
uses QEMU user-mode networking by default.
## Additional checks
- `bash -n` over every script is part of the unit suite (`test_syntax.sh`).
- `shellcheck` is optional and not required; several modules use constructs
that trip naive shellcheck rules, so treat its output as advisory.
- To exercise the backend without a VM, point `--config` at a file with
`TARGET_DISK` unset and use `--plan`; the safety tests already cover the
sandbox and authorization logic.

View file

@ -21,9 +21,8 @@ Phase 1 (install):
1. Boot the live ISO headless; get a root shell on the serial console.
2. Download the installer and test config from the host.
3. Write secrets to `0600` files and run the installer binary (the original
run used the Bash prototype; the harness now serves `phoebus-installer`):
`phoebus-installer --config test.conf --install --yes
3. Write secrets to `0600` files and run:
`installer/bin/ai-installer --config test.conf --install --yes
--luks-passphrase-file FILE --user-password-file FILE`
4. Stages executed in order: `preflight, storage, stage3, fstab,
portage, base packages, kernel, bootloader, users, services, desktop,
@ -163,52 +162,6 @@ The installer writes `/usr/local/bin/phoebus-session`, which starts waybar,
mako and swaybg and then execs dwl, with a software-render fallback when no
render node is present.
## Official harness on the static binary (Bash migration, Phase 2)
The committed harness (`installer/tests/vm/serial-driver.py` +
`installer/tests/vm/install.sh`) now drives the **static Rust binary** and no
longer runs the Bash installer. Re-verified end to end on a fresh disposable
qcow2 (24 GiB, virtio-blk `/dev/vda`):
```sh
# Build:
cd installer-rs && RUSTFLAGS="-C target-feature=+crt-static" \
cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu
# Install in the disposable VM, then boot the disk detached:
python3 installer/tests/vm/serial-driver.py install
python3 installer/tests/vm/serial-driver.py boot
```
Install (`INSTALL-RC=0`):
- The guest fetched `/tmp/phoebus-installer` and printed
`phoebus-installer 0.1.0` (the Rust binary, not Bash).
- Stages completed in proven order: `storage_prepare`, `stage_install`,
`fstab_generate`, `portage_configure`, `packages_base`, `kernel_install`,
`boot_install`, `users_configure`, `services_configure`, `desktop_install`
(none), `finalize`.
- Policy matched Bash: `crypto`/`btrfs-progs` source build, `sudo`/
`networkmanager`/`polkit` binary.
- `NO_SECRET_LEAK`; the run powered off cleanly.
Boot with the ISO detached (`serial-driver.py boot`):
- UEFI firmware ran `\EFI\systemd\systemd-bootx64.efi` (Boot0002 "Linux Boot
Manager"); the BLS "Gentoo Linux" entry booted.
- `systemd-cryptsetup` prompted for the LUKS2 passphrase and unlocked
`phoebus-root (cryptroot)`.
- Login as `phoebus` succeeded.
- `cat /proc/1/comm` -> `systemd`.
- `systemctl is-system-running` -> **running**.
- `systemctl --failed` -> **0 loaded units listed**.
- Networking: `enp0s2 UP 10.0.2.15/24`.
- Mounts: `/` (btrfs `@`), `/home`, `/var`, `/.snapshots`, `/swap`, ESP
`/efi`; `vda2` is `crypto_LUKS`.
This satisfies the Phase 2 exit gate of `docs/BASH-MIGRATION.md`: the only
proven boot path no longer depends on the retired Bash installer.
## Known remaining work
- The graphical session was verified with the **headless** wlroots backend

301
installer/lib/ai.sh Normal file
View file

@ -0,0 +1,301 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# AI assistant integration.
#
# Design rule: the LLM NEVER manipulates disks and NEVER runs privileged
# commands. It may only produce a structured proposal (a flat JSON object).
# The deterministic backend validates every field, the change is previewed and
# the user must confirm. Most assistant features work with no LLM at all.
#
# Secrets (API keys, passphrases, passwords) are never passed to the model and
# never written to the installation log.
# ---------------------------------------------------------------------------
# Deterministic (offline) assistance
# ---------------------------------------------------------------------------
ai_explain_hardware() {
{
printf 'Detected hardware\n'
printf '=================\n\n'
hw_report
printf '\nRecommended kernel profile: %s\n' "$(hw_recommended_kernel_profile)"
printf 'Suggested VIDEO_CARDS: %s\n' "$(portage_detect_video_cards)"
} 2>&1
}
ai_explain_disks() {
{
printf 'Disk summary\n'
printf '============\n\n'
local d
for d in "${DISK_LIST[@]}"; do
printf '%s\n' "$(disk_display_line "$d")"
done
printf '\nReading (read-only):\n'
if [[ -n "$(config_get TARGET_DISK)" && -b "$(config_get TARGET_DISK)" ]]; then
disk_layout_text "$(config_get TARGET_DISK)"
else
printf ' no target disk selected yet\n'
fi
} 2>&1
}
ai_explain_plan() {
plan_generate
plan_render
}
ai_explain_encryption() {
cat <<'EOF'
Encryption and filesystem choices
=================================
LUKS2 (default)
The whole root partition is encrypted. Unlocking happens at boot with a
passphrase. TPM2 enrollment is planned but not required.
Btrfs subvolumes
@ the root filesystem
@home /home, snapshotted independently
@var /var, kept separate so root snapshots stay small
@snapshots /.snapshots, where rollback snapshots live
@swap holds the swapfile
Separate subvolumes let snapshots and rollbacks target only the parts of
the system you care about, and keep user data out of root snapshots.
zstd compression
Transparent compression at level 3. A good balance of CPU and space.
EOF
}
# ai_offline_response QUERY - small deterministic help based on keywords
ai_offline_response() {
local q
q="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
case "$q" in
*partition*|*disk*|*layout*) ai_explain_disks ;;
*encrypt*|*luks*|*btrfs*|*filesystem*) ai_explain_encryption ;;
*hardware*|*cpu*|*gpu*|*wifi*|*bluetooth*) ai_explain_hardware ;;
*kernel*) printf 'Kernel policy\n=============\n\nProfile: %s\nPackage: %s\n\n%s\n' \
"$(config_get KERNEL_PROFILE)" "$(kernel_select_package)" \
"The distribution kernel is used as a stable, complete base. The installer applies conservative config fragments; it never generates a minimal kernel that only boots the current hardware." ;;
*package*|*compile*|*binary*) pkgpolicy_report ;;
*plan*|*summary*) ai_explain_plan ;;
*log*|*error*|*fail*) log_tail 60 ;;
*network*|*internet*) network_status_text ;;
*desktop*|*wayland*|*dwl*) printf 'Desktop\n=======\nProfile: %s\n\nBase: dwl (Wayland tiling). Audio: PipeWire + Wireplumber.\nFlatpak: %s\n' \
"$(config_get DESKTOP_PROFILE)" "$(config_get FLATPAK)" ;;
*) printf 'I can explain (offline, no model required):\n'
printf ' - hardware: detected CPU/GPU/storage/network\n'
printf ' - disks: devices and read-only layout\n'
printf ' - encryption: LUKS2 and Btrfs subvolumes\n'
printf ' - kernel: kernel policy\n'
printf ' - packages: compile vs binary policy\n'
printf ' - plan: the generated installation plan\n'
printf ' - logs: recent installer log lines\n'
printf '\nAsk about any of these, or configure a model for free-form help.\n'
;;
esac
}
# ---------------------------------------------------------------------------
# Structured proposals
# ---------------------------------------------------------------------------
# Only these keys may be changed by an AI proposal, and every value is
# validated by validation.sh before it is accepted.
AI_PROPOSAL_KEYS=(TARGET_DISK ENCRYPTION FILESYSTEM DESKTOP_PROFILE
PACKAGE_POLICY KERNEL_PROFILE HOSTNAME TIMEZONE LOCALE KEYMAP USERNAME)
# ai_parse_json_kv TEXT - flatten a flat JSON object into key=value lines
ai_parse_json_kv() {
local text="$1" match
while IFS= read -r match; do
[[ -z "$match" ]] && continue
if [[ "$match" =~ ^\"([A-Za-z_][A-Za-z0-9_]*)\"[[:space:]]*:[[:space:]]*\"([^\"]*)\"$ ]]; then
printf '%s=%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
elif [[ "$match" =~ ^\"([A-Za-z_][A-Za-z0-9_]*)\"[[:space:]]*:[[:space:]]*([0-9]+|true|false)$ ]]; then
printf '%s=%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
fi
done < <(grep -oE '"[A-Za-z_][A-Za-z0-9_]*"[[:space:]]*:[[:space:]]*("[^"]*"|[0-9]+|true|false)' <<<"$text")
}
ai_key_allowed() {
local key="$1" k
for k in "${AI_PROPOSAL_KEYS[@]}"; do
[[ "$k" == "$key" ]] && return 0
done
return 1
}
# ai_validate_field KEY VALUE - non-empty error string when invalid
ai_validate_field() {
local key="$1" value="$2"
case "$key" in
TARGET_DISK) validate_target_disk "$value" ;;
ENCRYPTION) [[ "$value" =~ ^(none|luks2)$ ]] || printf 'encryption must be none or luks2\n' ;;
FILESYSTEM) [[ "$value" =~ ^(btrfs|ext4)$ ]] || printf 'filesystem must be btrfs or ext4\n' ;;
DESKTOP_PROFILE) [[ " $(desktop_profiles) " == *" $value "* ]] || printf 'unknown desktop profile\n' ;;
PACKAGE_POLICY) [[ "$value" =~ ^(source_first|balanced|binary_first)$ ]] || printf 'unknown package policy\n' ;;
KERNEL_PROFILE) [[ "$value" =~ ^(safe|optimized|aggressive)$ ]] || printf 'unknown kernel profile\n' ;;
HOSTNAME) validate_hostname "$value" ;;
TIMEZONE) validate_timezone "$value" ;;
LOCALE) validate_locale "$value" ;;
KEYMAP) validate_keymap "$value" ;;
USERNAME) validate_username "$value" ;;
*) printf 'key not permitted\n' ;;
esac
}
# ai_apply_proposal TEXT - validate and apply; print accepted/rejected lines.
# Nothing is executed; only configuration state is changed.
ai_apply_proposal() {
local text="$1" line key value err accepted=0 rejected=0
printf 'AI proposal review\n==================\n\n'
while IFS= read -r line; do
key="${line%%=*}"; value="${line#*=}"
key="${key^^}"
if ! ai_key_allowed "$key"; then
printf 'REJECTED %-16s %s (not a permitted setting)\n' "$key" "$value"
rejected=$((rejected+1)); continue
fi
err="$(ai_validate_field "$key" "$value")"
if [[ -n "$err" ]]; then
printf 'REJECTED %-16s %s (%s)\n' "$key" "$value" "${err%%$'\n'*}"
rejected=$((rejected+1)); continue
fi
printf 'ACCEPTED %-16s %s\n' "$key" "$value"
config_set "$key" "$value"
accepted=$((accepted+1))
done < <(ai_parse_json_kv "$text")
printf '\n%d accepted, %d rejected.\n' "$accepted" "$rejected"
log_info "AI proposal applied: $accepted accepted, $rejected rejected"
((rejected == 0))
}
# ai_propose_offline QUERY - deterministic translator for common requests
ai_propose_offline() {
local q
q="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
local json="{"
local sep=""
if [[ "$q" == *encrypt* || "$q" == *luks* ]]; then
json+="${sep}\"encryption\":\"luks2\""; sep=","
fi
if [[ "$q" == *btrfs* ]]; then
json+="${sep}\"filesystem\":\"btrfs\""; sep=","
fi
if [[ "$q" == *desktop* ]]; then
json+="${sep}\"desktop_profile\":\"dwl\""; sep=","
elif [[ "$q" == *minimal* ]]; then
json+="${sep}\"desktop_profile\":\"minimal\""; sep=","
fi
local disk
disk="$(printf '%s' "$q" | grep -oE '/dev/(nvme[0-9]+n[0-9]+|[sv]d[a-z])' | head -n1)"
if [[ -n "$disk" ]]; then
if disks_is_protected "$disk"; then
printf 'Offline assistant: %s looks protected, not proposing it.\n' "$disk" >&2
else
json+="${sep}\"target_disk\":\"$disk\""; sep=","
fi
fi
json+="}"
printf '%s\n' "$json"
}
# ai_propose_llm QUERY - ask OpenCode for a flat JSON proposal.
# The result is only ever fed to ai_apply_proposal, which validates everything.
ai_propose_llm() {
local query="$1" bin prompt out
bin="$(opencode_detect)" || { log_warn "OpenCode not available"; return 1; }
prompt="You are the Phoebus OS installer assistant. Reply with ONLY a flat JSON object of installer settings. Allowed keys: ${AI_PROPOSAL_KEYS[*]}. Allowed values: encryption=none|luks2, filesystem=btrfs|ext4, desktop_profile=none|minimal|dwl|full, package_policy=source_first|balanced|binary_first, kernel_profile=safe|optimized|aggressive. Do not include markdown, explanations, commands, shell code or secrets. User request: $query"
log_info "AI: requesting structured proposal from OpenCode"
out="$("$bin" run --pure "$prompt" 2>>"$PHOEBUS_LOG_FILE")" || {
log_error "OpenCode run failed"; return 1; }
printf '%s\n' "$out"
}
# ai_propose_interactive - choose engine, then apply validated proposal
ai_propose_interactive() {
local query engine text
if declare -F ui_inputbox >/dev/null 2>&1; then
ui_inputbox "AI proposal" "Describe the installation you want (e.g. 'whole nvme, encrypt everything, desktop')." "" || return 1
query="$UI_RESULT"
else
printf 'Describe the installation you want: ' >&2
read -r query || return 1
fi
[[ -n "$query" ]] || return 1
engine="offline"
if opencode_available && config_bool AI_ENABLED; then
if declare -F ui_menu >/dev/null 2>&1; then
ui_menu "AI proposal" "Which engine should translate the request?" 10 60 2 \
offline "Deterministic rules (no model)" \
model "OpenCode model (validated proposal)" || return 1
engine="$UI_RESULT"
fi
fi
if [[ "$engine" == "model" ]]; then
text="$(ai_propose_llm "$query")" || return 1
else
text="$(ai_propose_offline "$query")"
fi
log_info "AI proposal text: $text"
ai_apply_proposal "$text" || log_warn "some proposed settings were rejected"
return 0
}
# ai_store_api_key KEY - store a provider key with restrictive permissions
ai_store_api_key() {
local key="$1" dir file
dir="${STATE_DIR:-/tmp/ai-installer}/ai"
file="$dir/credentials"
mkdir -p "$dir"
secret_register "$key"
umask 077
printf '%s\n' "$key" >"$file"
chmod 0600 "$file"
log_info "API credential stored at $file (value not logged)"
}
# ai_configure - provider/model setup; secrets never logged
ai_configure() {
local provider model endpoint key
if declare -F ui_inputbox >/dev/null 2>&1; then
ui_inputbox "AI configuration" "Provider (e.g. anthropic, openai, ollama):" "$(config_get AI_PROVIDER)" || return 1
provider="$UI_RESULT"
ui_inputbox "AI configuration" "Model (e.g. claude-sonnet-4, gpt-5, llama3):" "$(config_get AI_MODEL)" || return 1
model="$UI_RESULT"
ui_inputbox "AI configuration" "Custom endpoint / base URL (optional, for local models):" "$(config_get AI_ENDPOINT)" || return 1
endpoint="$UI_RESULT"
config_set AI_PROVIDER "$provider"
config_set AI_MODEL "$model"
config_set AI_ENDPOINT "$endpoint"
config_set AI_ENABLED "yes"
opencode_write_config
if declare -F ui_yesno >/dev/null 2>&1; then
if ui_yesno "AI credentials" "Store an API key now? It is saved with mode 0600 and never logged."; then
ui_passwordbox "AI credentials" "Paste API key (input hidden):" || return 0
key="$UI_RESULT"
ai_store_api_key "$key"
fi
fi
else
printf 'AI configuration requires the TUI or a config file.\n'
fi
return 0
}
# ai_status_text
ai_status_text() {
printf 'AI assistant: %s\n' "$(config_bool AI_ENABLED && echo enabled || echo disabled)"
printf 'OpenCode: %s\n' "$(opencode_detect || echo 'not installed')"
printf 'Provider: %s\n' "$(config_get AI_PROVIDER)"
printf 'Model: %s\n' "$(config_get AI_MODEL)"
printf 'Endpoint: %s\n' "$(config_get AI_ENDPOINT)"
}

150
installer/lib/boot.sh Normal file
View file

@ -0,0 +1,150 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Bootloader installation (UEFI + systemd-boot, Unified Kernel Images).
#
# The ESP is mounted in the target at EFI_MOUNT. systemd-boot is installed and
# configured to boot UKIs produced by kernel-install. Secure Boot is scaffolded
# but not enforced in v0.1.
boot_esp_path() {
printf '%s%s' "$1" "$(config_get EFI_MOUNT)"
}
# boot_install ROOT - install systemd-boot into the ESP
boot_install() {
local root="$1" esp
esp="$(config_get EFI_MOUNT)"
portage_chroot "$root" bootctl --esp-path="$esp" install
}
# boot_write_loader_conf ROOT
boot_write_loader_conf() {
local root="$1" esp dir
esp="$(boot_esp_path "$root")"
dir="$esp/loader"
mkdir -p "$dir"
{
printf '# systemd-boot configuration\n'
printf 'default *\n'
printf 'timeout %s\n' "3"
printf 'console-mode keep\n'
printf 'editor no\n'
} >"$dir/loader.conf"
log_info "wrote $dir/loader.conf"
}
# boot_write_install_conf ROOT
# Configure Gentoo installkernel. v0.1 uses layout=bls (Boot Loader
# Specification): the kernel and dracut initramfs are placed on the ESP and
# systemd-boot entry files carry the kernel command line. The dracut UKI
# generator does not embed /etc/kernel/cmdline, which produced an unbootable
# image (no root=), so UKI is deferred until that path is verified.
boot_write_install_conf() {
local root="$1" dir
dir="$root/etc/kernel"
mkdir -p "$dir"
{
printf '# /etc/kernel/install.conf - Gentoo installkernel\n'
printf '# When /etc/kernel/install.conf exists it is used INSTEAD of the\n'
printf '# package default in /usr/lib/kernel/install.conf, so every required\n'
printf '# generator must be listed here.\n'
printf '# installkernel always requires uki_generator when dracut generates\n'
printf '# the initramfs; "none" disables UKI assembly for the BLS layout.\n'
printf 'layout=bls\n'
printf 'initrd_generator=dracut\n'
printf 'uki_generator=none\n'
} >"$dir/install.conf"
log_info "wrote $dir/install.conf (layout=bls)"
}
# boot_write_dracut_conf ROOT
# A generic initramfs with the storage/crypto modules forced in. This keeps
# the encrypted Btrfs root unlockable and survives kernel updates.
boot_write_dracut_conf() {
local root="$1"
local dir="$root/etc/dracut.conf.d"
mkdir -p "$dir"
{
printf '# %s dracut configuration\n' "$(config_get DISTRO_NAME)"
printf '# Generic (non-hostonly) initramfs for predictable boot behaviour.\n'
printf 'hostonly="no"\n'
printf 'compress="zstd"\n'
printf 'add_dracutmodules+=" crypt btrfs "\n'
} >"$dir/10-phoebus.conf"
log_info "wrote $dir/10-phoebus.conf"
}
# boot_generate_uki ROOT - trigger kernel-install for every installed kernel
boot_generate_uki() {
local root="$1"
portage_chroot "$root" kernel-install add-all
}
# boot_install_fallback ROOT - ensure the default EFI fallback path works even
# when writing the UEFI boot variable failed.
boot_install_fallback() {
local root="$1" esp src
esp="$(boot_esp_path "$root")"
mkdir -p "$esp/EFI/BOOT" "$esp/EFI/systemd"
src="$esp/EFI/systemd/systemd-bootx64.efi"
if [[ ! -e "$src" ]]; then
# Boot loader provided by sys-apps/systemd[boot] inside the target.
local vendor="$root/usr/lib/systemd/boot/efi/systemd-bootx64.efi"
if [[ -e "$vendor" ]]; then
src="$vendor"
else
log_warn "systemd-boot binary not found; EFI fallback not installed"
return 1
fi
fi
run_cmd "install fallback bootloader" cp -f "$src" "$esp/EFI/BOOT/BOOTX64.EFI"
}
# boot_random_seed ROOT - enable systemd random seed persistence
boot_random_seed() {
local root="$1" esp
esp="$(boot_esp_path "$root")"
mkdir -p "$esp/loader"
if [[ ! -e "$esp/loader/random-seed" ]]; then
run_cmd "create random seed" \
dd if=/dev/urandom of="$esp/loader/random-seed" bs=512 count=1 status=none
fi
}
# boot_verify ROOT - confirm bootloader artifacts exist
boot_verify() {
local root="$1" esp
esp="$(boot_esp_path "$root")"
if [[ ! -e "$esp/EFI/systemd/systemd-bootx64.efi" && \
! -e "$esp/EFI/BOOT/BOOTX64.EFI" ]]; then
log_error "no systemd-boot loader found in $esp"
return 1
fi
[[ -e "$esp/loader/loader.conf" ]] || {
log_error "loader.conf not found"; return 1; }
return 0
}
# boot_secureboot_status - report, never change firmware state
boot_secureboot_status() {
if [[ -d /sys/firmware/efi/efivars ]]; then
if command -v mokutil >/dev/null 2>&1; then
mokutil --sb-state 2>/dev/null || printf 'unknown'
else
printf 'Secure Boot state unknown (mokutil not installed)'
fi
else
printf 'not booted in UEFI mode'
fi
}
# boot_secureboot_scaffold ROOT - placeholders for future enrollment
boot_secureboot_scaffold() {
local root="$1"
mkdir -p "$root/etc/secureboot"
{
printf '# Secure Boot is not enabled by this version of the installer.\n'
printf '# Future: sbctl / systemd-sbsign key enrollment and UKI signing.\n'
} >"$root/etc/secureboot/README"
}

109
installer/lib/btrfs.sh Normal file
View file

@ -0,0 +1,109 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Btrfs layout backend.
#
# Default layout (see config/defaults.conf):
# @ / root
# @home /home
# @var /var
# @snapshots /.snapshots
# @swap /swap holds the swapfile
#
# Top-level (subvolid=5) is only mounted temporarily to create subvolumes.
btrfs_require_tools() {
require_cmd btrfs mkfs.btrfs || return 1
}
btrfs_mount_opts() {
local opts
opts="noatime,compress=$(config_get COMPRESS),space_cache=v2"
if [[ "$(disk_transport "$(config_get TARGET_DISK)")" == "nvme" || \
"$(disk_transport "$(config_get TARGET_DISK)")" == "sata" ]]; then
opts+=",ssd"
fi
printf '%s' "$opts"
}
# btrfs_mkfs DEVICE
btrfs_mkfs() {
local dev="$1" label
label="$(config_get BTRFS_LABEL)"
run_destructive "create Btrfs filesystem on $dev" \
mkfs.btrfs -f -L "$label" "$dev"
}
# btrfs_mount_top DEVICE MOUNTPOINT
btrfs_mount_top() {
local dev="$1" mp="$2"
mkdir -p "$mp"
run_cmd "mount Btrfs top-level" mount -o "subvolid=5" "$dev" "$mp"
}
# btrfs_create_subvolumes MOUNTPOINT
btrfs_create_subvolumes() {
local mp="$1" sv
for sv in $(config_get BTRFS_SUBVOLS); do
run_destructive "create subvolume $sv" btrfs subvolume create "$mp/$sv" || return 1
done
}
# btrfs_set_default MOUNTPOINT - make @ the default subvolume
btrfs_set_default() {
local mp="$1" id
id="$(btrfs subvolume list -o "$mp" 2>/dev/null | awk '$NF=="@"{print $2; exit}')"
[[ -n "$id" ]] || return 0
run_cmd "set @ as default subvolume" btrfs subvolume set-default "$id" "$mp"
}
# btrfs_mount_layout DEVICE ROOT
btrfs_mount_layout() {
local dev="$1" root="$2" opts
opts="$(btrfs_mount_opts)"
mkdir -p "$root"
run_cmd "mount @ at $root" mount -o "${opts},subvol=@" "$dev" "$root" || return 1
local pair sv target
for pair in "@home:home" "@var:var" "@snapshots:.snapshots" "@swap:swap"; do
sv="${pair%%:*}"; target="${pair##*:}"
mkdir -p "$root/$target"
run_cmd "mount $sv at /$target" mount -o "${opts},subvol=$sv" "$dev" "$root/$target" || return 1
done
}
# btrfs_create_layout DEVICE ROOT
# Create the subvolume layout on a freshly created filesystem, then mount it.
# The top-level (subvolid=5) must be mounted to create @, @home, ...; only
# afterwards can the individual subvolumes be mounted.
btrfs_create_layout() {
local dev="$1" root="$2"
btrfs_mount_top "$dev" "$root" || return 1
if ! btrfs_create_subvolumes "$root"; then
run_cmd "unmount top-level" umount "$root" || true
return 1
fi
btrfs_set_default "$root" || true
run_cmd "unmount top-level" umount "$root" || return 1
btrfs_mount_layout "$dev" "$root"
}
# btrfs_create_swapfile ROOT [MIB]
btrfs_create_swapfile() {
local root="$1" mib="${2:-$(plan_swap_mib)}"
local swapdir="$root/swap"
mkdir -p "$swapdir"
if btrfs filesystem mkswapfile --help >/dev/null 2>&1; then
run_cmd "create Btrfs swapfile" \
btrfs filesystem mkswapfile --size "${mib}m" "$swapdir/swapfile"
else
run_cmd "create swapfile container" \
truncate -s "${mib}M" "$swapdir/swapfile" || return 1
run_cmd "disable CoW on swapfile" chattr +C "$swapdir/swapfile"
run_cmd "make swap" mkswap "$swapdir/swapfile"
fi
}
# btrfs_scrub_device DEVICE - verify checksums (non-destructive)
btrfs_scrub_device() {
run_cmd "scrub $1" btrfs scrub start -B "$1"
}

93
installer/lib/confirm.sh Normal file
View file

@ -0,0 +1,93 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Destructive-operation confirmation infrastructure.
#
# There are two independent gates:
#
# 1. PHOEBUS_DESTRUCTIVE_AUTHORIZED must be "yes" before run_destructive will
# execute anything. Only install.sh sets it, and only after the user has
# approved the generated plan.
# 2. Whole-disk erase additionally requires the user to type the word ERASE.
#
# This means a bug in the TUI cannot silently wipe a disk: every destructive
# command goes through run_destructive.
declare -g PHOEBUS_DESTRUCTIVE_AUTHORIZED="${PHOEBUS_DESTRUCTIVE_AUTHORIZED:-no}"
destructive_authorized() { [[ "$PHOEBUS_DESTRUCTIVE_AUTHORIZED" == "yes" ]]; }
# destructive_grant / destructive_revoke
destructive_grant() { PHOEBUS_DESTRUCTIVE_AUTHORIZED="yes"; log_warn "destructive operations AUTHORIZED for this session"; }
destructive_revoke() { PHOEBUS_DESTRUCTIVE_AUTHORIZED="no"; log_info "destructive operations revoked"; }
# _prompt_yesno MESSAGE - returns 0 for yes
_prompt_yesno() {
local message="$1"
if declare -F ui_yesno >/dev/null 2>&1; then
ui_yesno "Confirm" "$message"
return $?
fi
local answer
printf '%s [y/N] ' "$message" >&2
read -r answer || return 1
[[ "$answer" =~ ^[Yy] ]]
}
# _prompt_word PROMPT EXPECTED - returns 0 when the typed word matches
_prompt_word() {
local prompt="$1" expected="$2" answer
if declare -F ui_inputbox >/dev/null 2>&1; then
ui_inputbox "Destructive operation" "$prompt" "" || return 1
answer="$UI_RESULT"
else
printf '%s ' "$prompt" >&2
read -r answer || return 1
fi
[[ "$answer" == "$expected" ]]
}
# confirm_action MESSAGE - plain yes/no confirmation
confirm_action() {
if config_bool ASSUME_YES; then
log_warn "auto-approving (ASSUME_YES): $1"
return 0
fi
_prompt_yesno "$1"
}
# confirm_erase PREVIEW - strong confirmation for whole-disk destruction.
# Displays PREVIEW and requires the user to type ERASE.
confirm_erase() {
local preview="$1"
if config_bool ASSUME_YES; then
log_warn "auto-approving ERASE confirmation (ASSUME_YES)"
return 0
fi
if declare -F ui_msgbox >/dev/null 2>&1; then
ui_msgbox "DESTRUCTIVE OPERATION" "$preview
Type ERASE to continue."
else
printf '%s\n\n' "$preview" >&2
fi
_prompt_word "Type ERASE to confirm:" "ERASE"
}
# require_destructive_authorization CALLER - hard gate used by run_destructive
require_destructive_authorization() {
if ! destructive_authorized; then
log_error "blocked destructive operation from ${1:-unknown}: not authorized"
return 1
fi
return 0
}
# run_destructive DESCRIPTION ARGS...
# Execute a previously approved destructive command. Honours DRY_RUN via
# run_cmd. Refuses to run without authorization.
run_destructive() {
local desc="${1:-destructive operation}"; shift
require_destructive_authorization "$desc" || return 1
run_cmd "$desc" "$@"
}

93
installer/lib/desktop.sh Normal file
View file

@ -0,0 +1,93 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Desktop profile installation.
#
# The flagship desktop is a small Wayland tiling environment centred on dwl.
# Full desktop installation is future work; this module defines the profile and
# the package sets so the installer can grow into it cleanly.
desktop_profiles() {
printf '%s\n' none minimal dwl full
}
# desktop_packages PROFILE
desktop_packages() {
local profile="$1"
case "$profile" in
none)
;;
minimal)
printf '%s\n' \
gui-libs/wayland \
gui-libs/wayland-protocols \
x11-base/xwayland
;;
dwl|full)
printf '%s\n' \
gui-wm/dwl \
gui-apps/waybar \
gui-apps/wofi \
gui-apps/mako \
gui-apps/swayidle \
gui-apps/swaylock \
gui-apps/swaybg \
gui-apps/wl-clipboard \
gui-apps/grim \
gui-apps/slurp \
gui-libs/gtk-layer-shell \
x11-base/xwayland \
x11-terms/kitty \
net-misc/networkmanager \
sys-auth/polkit \
gnome-extra/polkit-gnome
;;
esac
if [[ "$profile" == "full" ]]; then
printf '%s\n' \
sys-apps/flatpak \
net-wireless/bluez \
gnome-base/gnome-keyring
fi
}
# desktop_audio_packages - PipeWire is always the audio stack
desktop_audio_packages() {
printf '%s\n' media-video/pipewire media-video/wireplumber
}
# desktop_install ROOT
desktop_install() {
local root="$1" profile
profile="$(config_get DESKTOP_PROFILE)"
[[ "$profile" == "none" ]] && { log_info "no desktop profile selected"; return 0; }
local -a packages=()
mapfile -t packages < <(desktop_packages "$profile")
mapfile -t -O "${#packages[@]}" packages < <(desktop_audio_packages)
if config_bool FLATPAK; then
packages+=(sys-apps/flatpak)
fi
log_info "installing desktop profile '$profile' (${#packages[@]} packages)"
portage_emerge "$root" "${packages[@]}"
}
# desktop_configure_flatpak ROOT
desktop_configure_flatpak() {
local root="$1"
config_bool FLATPAK || return 0
# Flathub is a third-party catalogue; adding it is opt-in via the profile.
portage_chroot "$root" flatpak remote-add --if-not-exists flathub \
https://flathub.org/repo/flathub.flatpakrepo || {
log_warn "could not add flathub remote (network?)"; return 0; }
log_info "flatpak configured with flathub"
}
# desktop_services ROOT - system services needed by the desktop
desktop_services() {
local profile
profile="$(config_get DESKTOP_PROFILE)"
printf '%s\n' NetworkManager systemd-resolved
[[ "$profile" == "full" ]] && printf '%s\n' bluetooth
return 0
}

177
installer/lib/disks.sh Normal file
View file

@ -0,0 +1,177 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Read-only disk and partition discovery.
#
# This module never writes to a disk. It exists so the installer can present
# accurate information and so destructive operations can refuse to touch the
# live medium, mounted filesystems or optical drives.
declare -ga DISK_LIST=()
# disks_available_tool
disks_tool_ok() { command -v lsblk >/dev/null 2>&1; }
# disks_refresh - populate DISK_LIST with whole-disk device paths
disks_refresh() {
DISK_LIST=()
disks_tool_ok || return 1
local name path
while IFS= read -r name; do
path="/dev/$name"
[[ -b "$path" ]] && DISK_LIST+=("$path")
done < <(lsblk -dn -o NAME 2>/dev/null | sort)
((${#DISK_LIST[@]}))
}
# _disk_attr PATH COLUMN - single value for a whole disk
_disk_attr() {
local path="$1" col="$2"
lsblk -dn -o "$col" "$path" 2>/dev/null | head -n1 | sed 's/[[:space:]]*$//'
}
disk_size_bytes() {
lsblk -bdn -o SIZE "$1" 2>/dev/null | head -n1 | tr -d ' '
}
disk_size_human() {
local b="${1:-0}"
numfmt --to=iec --suffix=B "$b" 2>/dev/null || printf '%s bytes' "$b"
}
disk_model() { _disk_attr "$1" MODEL; }
disk_transport() { _disk_attr "$1" TRAN; }
disk_is_removable() { [[ "$(_disk_attr "$1" RM)" == "1" ]]; }
disk_is_readonly() { [[ "$(_disk_attr "$1" RO)" == "1" ]]; }
# disk_partitions PATH - print child device paths one per line
disk_partitions() {
local path="$1" name
while IFS= read -r name; do
[[ -n "$name" ]] && printf '/dev/%s\n' "$name"
done < <(lsblk -rno NAME "$path" 2>/dev/null | tail -n +2)
}
disk_partition_count() {
disk_partitions "$1" | grep -c . || true
}
# disk_is_mounted PATH - true when the disk or any child is mounted
disk_is_mounted() {
local path="$1" dev
while IFS= read -r dev; do
[[ -n "$dev" ]] || continue
if grep -q "^${dev} " /proc/mounts 2>/dev/null; then
return 0
fi
done < <(printf '%s\n' "$path"; disk_partitions "$path")
return 1
}
# _parent_disk DEV - resolve a device (possibly a partition) to its whole disk
_parent_disk() {
local dev="$1" pk
dev="$(readlink -f "$dev" 2>/dev/null || printf '%s' "$dev")"
case "$dev" in
/dev/loop*|/dev/dm-*|/dev/mapper/*|/dev/sr*) printf '%s' "$dev"; return ;;
esac
pk="$(lsblk -no PKNAME "$dev" 2>/dev/null | head -n1)"
if [[ -n "$pk" ]]; then printf '/dev/%s' "$pk"; else printf '%s' "$dev"; fi
}
# _live_source_disks - whole disks that back the running live system
_live_source_disks() {
local src disk
local -a sources=()
# Sources directly referenced by the kernel command line.
if [[ -r /proc/cmdline ]]; then
while IFS= read -r tok; do
case "$tok" in
root=*|cdroot=*|boot=*) sources+=("${tok#*=}") ;;
esac
done < <(tr ' ' '\n' </proc/cmdline)
fi
# The running root, the initramfs medium and typical live mount points.
if [[ -r /proc/mounts ]]; then
local mp
for mp in / /run/initramfs /run/live /mnt/cdrom /mnt/live /lib/live; do
src="$(awk -v m="$mp" '$2==m{print $1; exit}' /proc/mounts 2>/dev/null)"
[[ -n "$src" ]] && sources+=("$src")
done
fi
local seen=""
for src in "${sources[@]}"; do
[[ -b "$src" ]] || continue
disk="$(_parent_disk "$src")"
case "$seen" in *" $disk "*) continue ;; esac
seen+=" $disk "
printf '%s\n' "$disk"
done
}
# disk_protected_reason PATH - non-empty when the disk must not be a target
disk_protected_reason() {
local path="$1" live
if disk_is_readonly "$path"; then
printf 'read-only device'
return
fi
case "$path" in
/dev/sr*|/dev/loop*|/dev/dm-*|/dev/mapper/*)
printf 'not a whole disk'
return ;;
esac
if disk_is_mounted "$path"; then
printf 'contains mounted filesystems'
return
fi
while IFS= read -r live; do
if [[ "$live" == "$path" ]]; then
printf 'live installation medium'
return
fi
done < <(_live_source_disks)
}
# disks_is_protected PATH
disks_is_protected() { [[ -n "$(disk_protected_reason "$1")" ]]; }
# disks_candidates - device paths that may be chosen as installation target
disks_candidates() {
local d
for d in "${DISK_LIST[@]}"; do
disks_is_protected "$d" || printf '%s\n' "$d"
done
}
# disk_display_line PATH - one line description for menus
disk_display_line() {
local path="$1" size model tran flag="" reason
size="$(disk_size_human "$(disk_size_bytes "$path")")"
model="$(disk_model "$path")"
tran="$(disk_transport "$path")"
reason="$(disk_protected_reason "$path")"
if [[ -n "$reason" ]]; then
flag=" [PROTECTED: $reason]"
fi
printf '%-16s %8s %-8s %s%s' "$path" "$size" "${tran:-?}" "${model:-disk}" "$flag"
}
# disk_partition_table PATH - GPT/MBR/unknown via parted (read-only)
disk_partition_table() {
command -v parted >/dev/null 2>&1 || { printf 'unknown'; return; }
local out
out="$(parted -s "$1" print 2>/dev/null | awk -F': ' '/Partition Table/{print $2; exit}')"
printf '%s' "${out:-unknown}"
}
# disk_free_space_bytes PATH - unpartitioned space, best effort
disk_free_space_bytes() {
command -v parted >/dev/null 2>&1 || return 1
parted -s -m "$1" unit B print free 2>/dev/null | \
awk -F: '$5=="free"{sum+=$4} END{printf "%d", sum}'
}
# disk_layout_text PATH - read-only partition listing
disk_layout_text() {
local path="$1"
lsblk -o NAME,SIZE,TYPE,FSTYPE,LABEL,MOUNTPOINTS "$path" 2>/dev/null
}

109
installer/lib/encryption.sh Normal file
View file

@ -0,0 +1,109 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# LUKS2 encryption backend.
#
# Passphrases are held in memory only (LUKS_PASSPHRASE), never written to the
# config, never passed on a command line and never logged. cryptsetup reads the
# passphrase from stdin via --key-file -.
#
# TPM2 enrollment is intentionally not implemented in v0.1; the function
# stubs document where it will hook in.
declare -g LUKS_PASSPHRASE="${LUKS_PASSPHRASE:-}"
encryption_require_tools() {
require_cmd cryptsetup blkid || return 1
}
# encryption_configure - prompt for and remember the passphrase (TUI or tty)
encryption_configure() {
local first second
if declare -F ui_passwordbox >/dev/null 2>&1; then
ui_passwordbox "Encryption passphrase" "Enter a LUKS2 passphrase for the root volume:" || return 1
first="$UI_RESULT"
ui_passwordbox "Encryption passphrase" "Repeat the passphrase:" || return 1
second="$UI_RESULT"
else
read -r -s -p "LUKS passphrase: " first; printf '\n' >&2
read -r -s -p "Repeat: " second; printf '\n' >&2
fi
if [[ -z "$first" ]]; then
log_error "empty encryption passphrase refused"
return 1
fi
if [[ "$first" != "$second" ]]; then
log_error "passphrases did not match"
return 1
fi
LUKS_PASSPHRASE="$first"
secret_register "$first"
log_info "encryption passphrase set (value not logged)"
return 0
}
# _run_cryptsetup_stdin DESCRIPTION COMMAND... - feeds LUKS_PASSPHRASE on stdin
_run_cryptsetup_stdin() {
local desc="$1"; shift
if config_bool DRY_RUN; then
log_line INFO "[dry-run] $desc :: $(_cmd_to_string "$@")"
return 0
fi
log_line INFO "$desc :: $(_cmd_to_string "$@")"
printf '%s' "$LUKS_PASSPHRASE" | "$@" >>"$PHOEBUS_LOG_FILE" 2>&1
local status=$?
log_line INFO "$desc :: exit status $status"
return $status
}
# encryption_format PARTITION
encryption_format() {
local part="$1" cipher keysize pbkdf
cipher="$(config_get LUKS_CIPHER)"
keysize="$(config_get LUKS_KEY_SIZE)"
pbkdf="$(config_get LUKS_PBKDF)"
[[ -n "$LUKS_PASSPHRASE" ]] || { log_error "no passphrase configured"; return 1; }
_run_cryptsetup_stdin "format LUKS2 on $part" \
cryptsetup luksFormat --batch-mode --type luks2 \
--cipher "$cipher" --key-size "$keysize" --pbkdf "$pbkdf" \
--key-file - "$part"
}
# encryption_open PARTITION NAME
encryption_open() {
local part="$1" name="${2:-$(config_get LUKS_NAME)}"
[[ -n "$LUKS_PASSPHRASE" ]] || { log_error "no passphrase configured"; return 1; }
_run_cryptsetup_stdin "open LUKS2 $part as $name" \
cryptsetup open --type luks --key-file - "$part" "$name"
}
# encryption_close NAME
encryption_close() {
local name="${1:-$(config_get LUKS_NAME)}"
run_destructive "close LUKS device $name" cryptsetup close "$name"
}
# encryption_mapper_path NAME
encryption_mapper_path() {
printf '/dev/mapper/%s' "${1:-$(config_get LUKS_NAME)}"
}
# encryption_crypttab_line PARTITION [NAME]
# Produces a crypttab line using the partition UUID (stable across reboots).
encryption_crypttab_line() {
local part="$1" name="${2:-$(config_get LUKS_NAME)}" uuid
uuid="$(blkid -s UUID -o value "$part" 2>/dev/null)"
[[ -n "$uuid" ]] || return 1
printf '%s UUID=%s none luks,discard\n' "$name" "$uuid"
}
# encryption_tpm2_enroll - future work; never made mandatory
encryption_tpm2_enroll() {
log_warn "TPM2 enrollment is not implemented in this version"
return 1
}
# encryption_tpm2_available - best-effort capability probe
encryption_tpm2_available() {
[[ -e /sys/class/tpm/tpm0 ]] && command -v systemd-cryptenroll >/dev/null 2>&1
}

134
installer/lib/filesystem.sh Normal file
View file

@ -0,0 +1,134 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Filesystem creation, mounting and fstab/crypttab generation.
#
# fstab is generated deterministically from the plan rather than scraping the
# live system, so no host state leaks into the installed system.
declare -g FS_ROOT_SOURCE=""
declare -g FS_EFI_PART=""
declare -g FS_ROOT_PART=""
filesystem_require_tools() {
require_cmd mkfs.fat mount umount blkid || return 1
}
# filesystem_mkfs_efi PARTITION
filesystem_mkfs_efi() {
local part="$1"
run_destructive "create FAT32 EFI filesystem on $part" \
mkfs.fat -F32 -n EFI "$part"
}
# filesystem_mount_efi PARTITION ROOT
filesystem_mount_efi() {
local part="$1" root="$2" mp
mp="$(config_get EFI_MOUNT)"
mkdir -p "$root$mp"
run_cmd "mount EFI" mount "$part" "$root$mp"
}
# filesystem_prepare_root DISK
# Create the root filesystem, applying encryption when configured.
# Sets FS_ROOT_SOURCE to the device that carries the Btrfs filesystem.
filesystem_prepare_root() {
local disk="$1" part="$2"
FS_ROOT_PART="$part"
if [[ "$(config_get ENCRYPTION)" == "none" ]]; then
btrfs_mkfs "$part" || return 1
FS_ROOT_SOURCE="$part"
else
encryption_format "$part" || return 1
encryption_open "$part" "$(config_get LUKS_NAME)" || return 1
local mapper
mapper="$(encryption_mapper_path)"
btrfs_mkfs "$mapper" || return 1
FS_ROOT_SOURCE="$mapper"
fi
log_info "root filesystem source: $FS_ROOT_SOURCE"
}
# filesystem_mount_root ROOT
filesystem_mount_root() {
local root="$1"
btrfs_mount_layout "$FS_ROOT_SOURCE" "$root"
}
# filesystem_source_ref - stable reference for fstab (UUID when unencrypted)
filesystem_source_ref() {
if [[ "$FS_ROOT_SOURCE" == /dev/mapper/* ]]; then
printf '%s' "$FS_ROOT_SOURCE"
else
local uuid
uuid="$(blkid -s UUID -o value "$FS_ROOT_SOURCE" 2>/dev/null)"
if [[ -n "$uuid" ]]; then printf 'UUID=%s' "$uuid"; else printf '%s' "$FS_ROOT_SOURCE"; fi
fi
}
# filesystem_generate_fstab ROOT
filesystem_generate_fstab() {
local root="$1"
local fstab="$root/etc/fstab"
local opts src
src="$(filesystem_source_ref)"
opts="$(btrfs_mount_opts)"
mkdir -p "$root/etc"
{
printf '# /etc/fstab: %s\n' "$(config_get DISTRO_NAME)"
printf '# Generated by the installer. Use `findmnt --verify` to check.\n'
printf '#\n'
printf '# <file system>\t<mount point>\t<type>\t<options>\t<dump>\t<pass>\n'
local efi_uuid
efi_uuid="$(blkid -s UUID -o value "$FS_EFI_PART" 2>/dev/null)"
if [[ -n "$efi_uuid" ]]; then
printf 'UUID=%s\t%s\tvfat\tumask=0077,shortname=winnt\t0\t2\n' "$efi_uuid" "$(config_get EFI_MOUNT)"
fi
printf '%s\t/\tbtrfs\t%s,subvol=@\t0\t1\n' "$src" "$opts"
printf '%s\t/home\tbtrfs\t%s,subvol=@home\t0\t2\n' "$src" "$opts"
printf '%s\t/var\tbtrfs\t%s,subvol=@var\t0\t2\n' "$src" "$opts"
printf '%s\t/.snapshots\tbtrfs\t%s,subvol=@snapshots\t0\t2\n' "$src" "$opts"
printf '%s\t/swap\tbtrfs\t%s,subvol=@swap\t0\t2\n' "$src" "$opts"
printf '/swap/swapfile\tnone\tswap\tdefaults\t0\t0\n'
} >"$fstab"
log_info "wrote $fstab"
}
# filesystem_generate_crypttab ROOT
filesystem_generate_crypttab() {
local root="$1"
local crypttab="$root/etc/crypttab"
local line
[[ "$(config_get ENCRYPTION)" == "none" ]] && return 0
line="$(encryption_crypttab_line "$FS_ROOT_PART" "$(config_get LUKS_NAME)")" || {
log_error "could not determine LUKS UUID for crypttab"
return 1
}
mkdir -p "$root/etc"
{
printf '# /etc/crypttab: unlock the root volume at boot.\n'
printf '# <name>\t<device>\t<keyfile>\t<options>\n'
printf '%s\n' "$line"
} >"$crypttab"
log_info "wrote $crypttab"
}
# filesystem_verify ROOT - basic post-mount checks
filesystem_verify() {
local root="$1"
[[ -d "$root/etc" ]] || { log_error "$root/etc missing"; return 1; }
findmnt -n "$root" >/dev/null 2>&1 || { log_error "$root is not a mountpoint"; return 1; }
return 0
}
# filesystem_unmount_all ROOT - best effort teardown (used on rollback)
filesystem_unmount_all() {
local root="$1"
# Unmount children first, the root last.
local -a mounts=("$(config_get EFI_MOUNT)" "/.snapshots" "/var" "/home" "/swap" "")
local m
for m in "${mounts[@]}"; do
run_cmd "unmount $root$m" umount -R "$root$m" 2>/dev/null || true
done
}

128
installer/lib/hardware.sh Normal file
View file

@ -0,0 +1,128 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Read-only hardware probing.
#
# Nothing in this file modifies the system: it only reads /proc, /sys and the
# output of read-only inventory tools. Results feed the installation plan and
# the kernel/profile decisions.
hw_cpu_vendor() {
awk -F': ' '/^vendor_id/{print $2; exit}' /proc/cpuinfo 2>/dev/null
}
hw_cpu_model() {
awk -F': ' '/^model name/{print $2; exit}' /proc/cpuinfo 2>/dev/null
}
hw_cpu_cores() {
local n
n="$(nproc --all 2>/dev/null || echo 1)"
printf '%s' "$n"
}
hw_cpu_threads() {
local n
n="$(grep -c '^processor' /proc/cpuinfo 2>/dev/null || echo 1)"
printf '%s' "$n"
}
hw_cpu_has() {
grep -qw "$1" /proc/cpuinfo 2>/dev/null
}
# hw_cpu_virt - print a human readable virtualisation capability summary
hw_cpu_virt() {
local out=()
hw_cpu_has vmx && out+=("Intel VT-x")
hw_cpu_has svm && out+=("AMD-V")
hw_cpu_has avx2 && out+=("AVX2")
hw_cpu_has avx512f && out+=("AVX-512")
hw_cpu_has aes && out+=("AES-NI")
((${#out[@]})) && printf '%s' "${out[*]}"
}
hw_mem_total_mib() {
awk '/^MemTotal:/{printf "%d", $2/1024; exit}' /proc/meminfo 2>/dev/null
}
hw_firmware_mode() {
if [[ -d /sys/firmware/efi ]]; then printf 'UEFI'; else printf 'BIOS'; fi
}
_is_laptop() {
local p
for p in /sys/class/power_supply/BAT*; do
[[ -e "$p" ]] && return 0
done
[[ -d /sys/firmware/acpi/tables ]] && \
grep -qi 'laptop' /sys/class/dmi/id/chassis_type 2>/dev/null
return 1
}
# _hw_lspci_filter REGEX - matching lspci lines, if lspci is available
_hw_lspci_filter() {
command -v lspci >/dev/null 2>&1 || return 0
lspci -nn 2>/dev/null | grep -iE "$1" || true
}
_hw_lsusb_filter() {
command -v lsusb >/dev/null 2>&1 || return 0
lsusb 2>/dev/null | grep -iE "$1" || true
}
hw_gpus() { _hw_lspci_filter 'VGA compatible controller|3D controller|Display controller'; }
hw_network_hw() { _hw_lspci_filter 'Ethernet controller|Network controller|Wireless'; }
hw_bluetooth() { { _hw_lspci_filter 'Bluetooth'; _hw_lsusb_filter 'Bluetooth'; } | sort -u; }
hw_audio() { _hw_lspci_filter 'Audio device'; }
hw_usb() { _hw_lspci_filter 'USB controller'; }
hw_storage_hw() { _hw_lspci_filter 'SATA controller|NVMe|RAID bus controller'; }
# hw_gpu_vendors - space separated vendor tags, used for driver policy
hw_gpu_vendors() {
local gpus vendors=()
gpus="$(hw_gpus)"
grep -qi 'nvidia' <<<"$gpus" && vendors+=("nvidia")
grep -qi 'amd\|advanced micro devices\|ati technologies' <<<"$gpus" && vendors+=("amd")
grep -qi 'intel' <<<"$gpus" && vendors+=("intel")
printf '%s' "${vendors[*]:-unknown}"
}
hw_input_devices() {
local count=0
[[ -r /proc/bus/input/devices ]] && \
count="$(grep -c '^N: Name=' /proc/bus/input/devices 2>/dev/null)"
printf '%s' "$count"
}
# hw_report - human readable report for the TUI / hardware screen
hw_report() {
local virt
virt="$(hw_cpu_virt)"
printf 'Firmware: %s\n' "$(hw_firmware_mode)"
printf 'CPU: %s\n' "$(hw_cpu_model)"
printf 'CPU cores: %s threads / %s logical CPUs\n' \
"$(hw_cpu_threads)" "$(hw_cpu_cores)"
printf 'CPU features: %s\n' "${virt:-none detected}"
printf 'Memory: %s MiB\n' "$(hw_mem_total_mib)"
printf 'Machine type: %s\n' "$(_is_laptop && echo laptop || echo desktop/server)"
printf 'Input devices: %s\n' "$(hw_input_devices)"
printf '\n'
printf 'GPUs:\n%s\n\n' "$(hw_gpus | sed 's/^/ /' | grep . || echo ' (none detected)')"
printf 'Storage controllers:\n%s\n\n' "$(hw_storage_hw | sed 's/^/ /' | grep . || echo ' (none detected)')"
printf 'Network:\n%s\n\n' "$(hw_network_hw | sed 's/^/ /' | grep . || echo ' (none detected)')"
printf 'Bluetooth:\n%s\n\n' "$(hw_bluetooth | sed 's/^/ /' | grep . || echo ' (none detected)')"
printf 'Audio:\n%s\n\n' "$(hw_audio | sed 's/^/ /' | grep . || echo ' (none detected)')"
printf 'USB controllers:\n%s\n' "$(hw_usb | sed 's/^/ /' | grep . || echo ' (none detected)')"
}
# hw_recommended_kernel_profile - conservative recommendation
hw_recommended_kernel_profile() {
local mem
mem="$(hw_mem_total_mib)"
if [[ -n "$mem" ]] && ((mem < 2048)); then
printf 'safe'
else
printf 'optimized'
fi
}

330
installer/lib/install.sh Normal file
View file

@ -0,0 +1,330 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Installation orchestration.
#
# This is the only place that grants destructive authorization, and only after
# the plan has been displayed and explicitly approved. Each stage checks the
# return status of the one before it and stops on failure rather than
# continuing blindly.
declare -g INSTALL_TARGET_ROOT=""
declare -g INSTALL_FAILED_STAGE=""
# install_effective_root - the directory the installed system lives in.
# In dry-run mode this is a sandbox so file writes never touch the host.
install_effective_root() {
if config_bool DRY_RUN; then
printf '%s/dry-run-root' "${STATE_DIR:-/tmp/ai-installer}"
else
printf '%s' "$(config_get INSTALL_ROOT)"
fi
}
install_require_root() {
if config_bool DRY_RUN; then return 0; fi
if [[ "$(id -u)" -ne 0 ]]; then
log_error "the installer must run as root"
return 1
fi
return 0
}
# install_preflight - non-destructive checks before anything is touched
install_preflight() {
log_section "preflight"
install_require_root || return 1
if ! config_bool DRY_RUN && [[ ! -d /sys/firmware/efi ]]; then
log_error "system was not booted in UEFI mode; v0.1 supports UEFI only"
return 1
fi
local problems
problems="$(validate_config)"
if [[ -n "$problems" ]]; then
log_error "configuration is incomplete:"
while IFS= read -r problems; do log_error " $problems"; done <<<"$problems"
return 1
fi
partitions_require_tools || return 1
filesystem_require_tools || return 1
btrfs_require_tools || return 1
if [[ "$(config_get ENCRYPTION)" != "none" ]]; then
encryption_require_tools || return 1
fi
if [[ -z "$LUKS_PASSPHRASE" && "$(config_get ENCRYPTION)" != "none" ]]; then
log_error "encryption selected but no passphrase configured"
return 1
fi
return 0
}
# install_chroot_mount ROOT / install_chroot_umount ROOT
install_chroot_mount() {
local root="$1"
run_cmd "mount proc" mount -t proc proc "$root/proc" || return 1
run_cmd "mount sysfs" mount --rbind /sys "$root/sys" || return 1
run_cmd "mount devtmpfs" mount --rbind /dev "$root/dev" || return 1
run_cmd "mount devpts" mount --make-rslave "$root/dev" 2>/dev/null || true
[[ -d "$root/run" ]] && run_cmd "mount tmpfs on /run" mount -t tmpfs tmpfs "$root/run" || true
return 0
}
install_chroot_umount() {
local root="$1"
run_cmd "unmount $root/proc" umount -l "$root/proc" 2>/dev/null || true
run_cmd "unmount $root/sys" umount -l "$root/sys" 2>/dev/null || true
run_cmd "unmount $root/dev" umount -l "$root/dev" 2>/dev/null || true
}
# install_stage_storage - create partitions, filesystems and mount the target
install_stage_storage() {
local disk root
disk="$(config_get TARGET_DISK)"
root="$INSTALL_TARGET_ROOT"
log_section "storage: $disk"
if config_bool DRY_RUN; then
log_info "[dry-run] would partition and format $disk at $root"
mkdir -p "$root"
return 0
fi
partitions_wipe "$disk" || return 1
partitions_create_gpt "$disk" || return 1
partitions_verify "$disk" || return 1
FS_EFI_PART="$EFI_PART"
filesystem_mkfs_efi "$EFI_PART" || return 1
filesystem_prepare_root "$disk" "$ROOT_PART" || return 1
# Create the subvolume layout and mount the root; mounting the ESP afterwards
# avoids covering the ESP mount with the root filesystem.
btrfs_create_layout "$FS_ROOT_SOURCE" "$root" || return 1
filesystem_mount_efi "$EFI_PART" "$root" || return 1
btrfs_create_swapfile "$root" || return 1
# NOTE: /etc/fstab and /etc/crypttab are generated after the stage3 is
# extracted (install_stage_fstab); generating them here would be undone by
# the stage3 tarball, which ships its own /etc/fstab.
return 0
}
# install_stage_fstab - write fstab, crypttab and required runtime directories.
# Runs after the stage3 has been extracted so nothing overwrites these files.
install_stage_fstab() {
local root="$INSTALL_TARGET_ROOT"
log_section "fstab / crypttab"
if config_bool DRY_RUN; then
log_info "[dry-run] would write fstab and crypttab into $root"
return 0
fi
filesystem_generate_fstab "$root" || return 1
filesystem_generate_crypttab "$root" || return 1
# Some stage3 media omit /var/tmp; systemd's kernel-install needs it.
mkdir -p "$root/var/tmp" "$root/tmp" "$root/root" "$root/home"
chmod 1777 "$root/var/tmp" "$root/tmp" 2>/dev/null || true
chmod 0700 "$root/root" 2>/dev/null || true
return 0
}
# install_stage_base - extract the Gentoo systemd stage3
install_stage_base() {
local root="$INSTALL_TARGET_ROOT" tarball
log_section "base system (stage3)"
mkdir -p "$root" "${STATE_DIR:-/tmp/ai-installer}"
tarball="${STATE_DIR:-/tmp/ai-installer}/stage3-systemd.tar.xz"
if config_bool DRY_RUN; then
log_info "[dry-run] would fetch stage3 and extract into $root"
return 0
fi
portage_fetch_stage3 "$tarball" || return 1
portage_extract_stage3 "$root" "$tarball" || return 1
return 0
}
# install_stage_portage - configure Portage and sync
install_stage_portage() {
local root="$INSTALL_TARGET_ROOT"
log_section "portage configuration"
if config_bool DRY_RUN; then
log_info "[dry-run] would write Portage config and sync"
return 0
fi
portage_write_make_conf "$root" || return 1
portage_write_repos_conf "$root" || return 1
portage_write_binrepos "$root" || return 1
portage_write_package_files "$root" || return 1
cp -L /etc/resolv.conf "$root/etc/resolv.conf" 2>/dev/null || true
install_chroot_mount "$root" || return 1
portage_init_machine_id "$root" || log_warn "could not initialise machine-id"
portage_sync "$root" || { install_chroot_umount "$root"; return 1; }
portage_verification_setup "$root" || log_warn "getuto failed; binary package verification may fail"
install_chroot_umount "$root"
# Select the profile only after the tree exists, so the symlink is never
# dangling while Portage runs.
portage_select_profile "$root" || return 1
return 0
}
# install_stage_packages - base packages beyond the stage3
install_stage_packages() {
local root="$INSTALL_TARGET_ROOT"
local -a packages=()
log_section "base packages"
mapfile -t packages < <(portage_base_packages)
install_chroot_mount "$root" || return 1
portage_emerge "$root" "${packages[@]}" || { install_chroot_umount "$root"; return 1; }
install_chroot_umount "$root"
return 0
}
# install_stage_kernel
install_stage_kernel() {
local root="$INSTALL_TARGET_ROOT"
log_section "kernel"
kernel_write_profile "$root" || return 1
boot_write_install_conf "$root" || return 1
boot_write_dracut_conf "$root" || return 1
kernel_write_cmdline "$root" || return 1
install_chroot_mount "$root" || return 1
kernel_install "$root" || { install_chroot_umount "$root"; return 1; }
install_chroot_umount "$root"
return 0
}
# install_stage_boot
install_stage_boot() {
local root="$INSTALL_TARGET_ROOT"
log_section "bootloader"
install_chroot_mount "$root" || return 1
boot_install "$root" || log_warn "bootctl install failed; will rely on the EFI fallback path"
boot_generate_uki "$root" || log_warn "kernel-install add-all reported an issue"
install_chroot_umount "$root"
boot_write_loader_conf "$root" || return 1
boot_install_fallback "$root" || log_warn "EFI fallback bootloader not installed"
boot_random_seed "$root" || true
boot_verify "$root" || return 1
return 0
}
# install_stage_users
install_stage_users() {
local root="$INSTALL_TARGET_ROOT"
log_section "users"
install_chroot_mount "$root" || return 1
users_create "$root" || { install_chroot_umount "$root"; return 1; }
users_configure_sudo "$root" || { install_chroot_umount "$root"; return 1; }
install_chroot_umount "$root"
return 0
}
# install_stage_services - locale, timezone, keymap, systemd services
install_stage_services() {
local root="$INSTALL_TARGET_ROOT" tz locale keymap
log_section "system services"
tz="$(config_get TIMEZONE)"
locale="$(config_get LOCALE)"
keymap="$(config_get KEYMAP)"
network_configure_target "$root" || return 1
mkdir -p "$root/etc"
{
printf 'KEYMAP=%s\n' "$keymap"
} >"$root/etc/vconsole.conf"
ln -sf "/usr/share/zoneinfo/$tz" "$root/etc/localtime"
{
printf 'LANG=%s\n' "$locale"
} >"$root/etc/locale.conf"
portage_write_locale_gen "$root" "$locale"
install_chroot_mount "$root" || return 1
portage_chroot "$root" locale-gen || log_warn "locale-gen failed (continuing)"
local svc
local -a services=()
mapfile -t services < <(network_target_services)
mapfile -t -O "${#services[@]}" services < <(desktop_services)
printf '%s\n' "${services[@]}" | sort -u >"$root/etc/.phoebus-services"
while IFS= read -r svc; do
[[ -z "$svc" ]] && continue
portage_chroot "$root" systemctl enable "$svc" || log_warn "could not enable $svc"
done <"$root/etc/.phoebus-services"
rm -f "$root/etc/.phoebus-services"
install_chroot_umount "$root"
return 0
}
# install_stage_desktop
install_stage_desktop() {
local root="$INSTALL_TARGET_ROOT" profile
profile="$(config_get DESKTOP_PROFILE)"
log_section "desktop: $profile"
[[ "$profile" == "none" ]] && return 0
install_chroot_mount "$root" || return 1
desktop_install "$root" || { install_chroot_umount "$root"; return 1; }
desktop_configure_flatpak "$root" || true
install_chroot_umount "$root"
return 0
}
# install_export_logs ROOT - copy the installer log into the target so a
# failed installation can be diagnosed after reboot.
install_export_logs() {
local root="$1" dest
dest="$root/var/log/ai-installer"
[[ -r "${PHOEBUS_LOG_FILE:-}" ]] || return 0
mkdir -p "$dest" 2>/dev/null || return 0
cp -f "$PHOEBUS_LOG_FILE" "$dest/install.log" 2>/dev/null || true
}
# install_stage_finalize
install_stage_finalize() {
local root="$INSTALL_TARGET_ROOT"
log_section "finalize"
if ! config_bool DRY_RUN; then
install_export_logs "$root"
install_chroot_umount "$root"
filesystem_unmount_all "$root"
if [[ "$(config_get ENCRYPTION)" != "none" ]]; then
encryption_close "$(config_get LUKS_NAME)" || log_warn "could not close LUKS device"
fi
fi
log_info "installation finished"
return 0
}
# install_run - execute the staged installation, stopping on first failure
install_run() {
INSTALL_TARGET_ROOT="$(install_effective_root)"
INSTALL_FAILED_STAGE=""
mkdir -p "$INSTALL_TARGET_ROOT" 2>/dev/null || true
install_preflight || { INSTALL_FAILED_STAGE="preflight"; return 1; }
local stage rc
for stage in "${PLAN_STEPS[@]}"; do
rc=0
case "$stage" in
storage_prepare) install_stage_storage || rc=1 ;;
stage_install) install_stage_base || rc=1 ;;
fstab_generate) install_stage_fstab || rc=1 ;;
portage_configure) install_stage_portage || rc=1 ;;
packages_base) install_stage_packages || rc=1 ;;
kernel_install) install_stage_kernel || rc=1 ;;
boot_install) install_stage_boot || rc=1 ;;
users_configure) install_stage_users || rc=1 ;;
services_configure) install_stage_services || rc=1 ;;
desktop_install) install_stage_desktop || rc=1 ;;
finalize) install_stage_finalize || rc=1 ;;
*) log_warn "unknown stage: $stage" ;;
esac
if ((rc != 0)); then
INSTALL_FAILED_STAGE="$stage"
log_error "stage failed: $stage"
if ! config_bool DRY_RUN; then
install_export_logs "$INSTALL_TARGET_ROOT"
install_chroot_umount "$INSTALL_TARGET_ROOT"
fi
return 1
fi
log_info "stage complete: $stage"
done
return 0
}

139
installer/lib/kernel.sh Normal file
View file

@ -0,0 +1,139 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Kernel selection and configuration.
#
# Policy: compile an "optimized but conservative" kernel. We start from the
# Gentoo distribution kernel (sys-kernel/gentoo-kernel), which is a stable,
# well-tested configuration, and apply a small, safe set of profile fragments.
# We never generate a minimal config that only boots the installer's hardware.
kernel_profile_file() {
printf '%s/etc/kernel/config.d/00-phoebus-profile.config' "$1"
}
# kernel_modules_for_hardware - extra kernel packages suggested by hardware
kernel_extra_packages() {
printf '%s\n' sys-kernel/linux-firmware
if hw_cpu_has vmx; then
printf '%s\n' sys-firmware/intel-microcode
fi
if hw_cpu_has svm; then
printf '%s\n' sys-firmware/amd-ucode
fi
}
# kernel_select_package - final kernel package respecting the profile
kernel_select_package() {
local pkg profile
pkg="$(config_get KERNEL_PACKAGE)"
profile="$(config_get KERNEL_PROFILE)"
case "$profile" in
safe)
# Safe profile prefers the prebuilt distribution kernel.
printf '%s' "sys-kernel/gentoo-kernel-bin" ;;
optimized)
printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;;
aggressive)
# Aggressive still uses the distribution sources but may take a
# locally tuned savedconfig fragment.
printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;;
*)
printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;;
esac
}
# kernel_write_profile ROOT - safe config fragments (never minimal)
kernel_write_profile() {
local root="$1" profile file
profile="$(config_get KERNEL_PROFILE)"
file="$(kernel_profile_file "$root")"
mkdir -p "$(dirname "$file")"
{
printf '# %s kernel profile: %s\n' "$(config_get DISTRO_NAME)" "$profile"
printf '# Applied on top of the Gentoo distribution kernel configuration.\n'
printf '# The base configuration is intentionally kept: it supports common\n'
printf '# peripherals the user may attach later.\n'
printf '\n'
printf '# Storage / modern filesystems and encryption\n'
printf 'CONFIG_BTRFS_FS=y\n'
printf 'CONFIG_BTRFS_FS_POSIX_ACL=y\n'
printf 'CONFIG_DM_CRYPT=y\n'
printf 'CONFIG_DM_INTEGRITY=y\n'
printf 'CONFIG_NVME_CORE=y\n'
printf 'CONFIG_BLK_DEV_NVME=y\n'
printf '\n'
printf '# Input / USB / common buses\n'
printf 'CONFIG_HID_GENERIC=y\n'
printf 'CONFIG_USB_HID=y\n'
printf 'CONFIG_USB_XHCI_HCD=y\n'
printf '\n'
printf '# systemd / containers / virtualisation guests\n'
printf 'CONFIG_CGROUPS=y\n'
printf 'CONFIG_NAMESPACES=y\n'
printf 'CONFIG_VIRTIO=y\n'
printf 'CONFIG_VIRTIO_PCI=y\n'
printf 'CONFIG_VIRTIO_BLK=y\n'
printf 'CONFIG_VIRTIO_NET=y\n'
printf '\n'
printf '# Compression used by Btrfs\n'
printf 'CONFIG_ZSTD_COMPRESS=y\n'
printf 'CONFIG_ZSTD_DECOMPRESS=y\n'
} >"$file"
log_info "wrote kernel profile fragment $file"
}
# kernel_write_cmdline ROOT - kernel command line for UKI/systemd-boot
kernel_write_cmdline() {
local root="$1" cmdline="" enc name uuid
enc="$(config_get ENCRYPTION)"
name="$(config_get LUKS_NAME)"
if [[ "$enc" != "none" ]]; then
uuid="$(blkid -s UUID -o value "$FS_ROOT_PART" 2>/dev/null)"
if [[ -z "$uuid" ]]; then
if config_bool DRY_RUN; then
uuid="<luks-uuid>"
else
log_error "cannot determine LUKS UUID for kernel command line"
return 1
fi
fi
# rd.luks.name=<uuid>=<name> makes dracut/systemd create the mapper under
# the configured name; rd.luks.uuid alone would produce luks-<uuid> and the
# root= below would not exist.
cmdline+="rd.luks.name=$uuid=$name "
cmdline+="root=/dev/mapper/$name "
else
cmdline+="root=$(filesystem_source_ref) "
fi
cmdline+="rootfstype=btrfs rootflags=subvol=@ rw quiet"
local console
console="$(config_get KERNEL_CONSOLE)"
[[ -n "$console" ]] && cmdline+=" $console"
mkdir -p "$root/etc/kernel"
printf '%s\n' "$cmdline" >"$root/etc/kernel/cmdline"
log_info "wrote /etc/kernel/cmdline: $cmdline"
}
# kernel_install ROOT - emerge the kernel and firmware
kernel_install() {
local root="$1" pkg
pkg="$(kernel_select_package)"
local -a packages=("$pkg")
mapfile -t -O "${#packages[@]}" packages < <(kernel_extra_packages)
log_info "installing kernel packages: ${packages[*]}"
portage_emerge "$root" "${packages[@]}"
}
# kernel_update ROOT - rebuild the distribution kernel via emerge @module-rebuild
kernel_update() {
local root="$1"
portage_chroot "$root" emerge --ask=n --quiet-build=y @module-rebuild
}
# kernel_available_list ROOT - kernels present in the ESP
kernel_available_list() {
local root="$1" esp
esp="$root$(config_get EFI_MOUNT)"
find "$esp" -maxdepth 4 -name 'vmlinuz*' -o -name '*.efi' 2>/dev/null | sed "s#^$root##"
}

139
installer/lib/logging.sh Normal file
View file

@ -0,0 +1,139 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Installer logging and command execution.
#
# Every operation performed by the deterministic backend goes through run_cmd
# (or run_cmd_capture), which records the command, its output and its exit
# status. This makes failures diagnosable and keeps destructive behaviour
# auditable.
#
# Secrets are scrubbed from all log output.
declare -g PHOEBUS_LOG_FILE="${PHOEBUS_LOG_FILE:-}"
declare -g PHOEBUS_LOG_ECHO="${PHOEBUS_LOG_ECHO:-no}"
declare -ga SECRET_VALUES=()
# secret_register VALUE - remember a secret so it is never written to logs
secret_register() {
[[ -n "${1-}" ]] && SECRET_VALUES+=("$1")
}
# redact_scrub TEXT - replace every known secret with <redacted>
redact_scrub() {
local text="$1" secret
for secret in "${SECRET_VALUES[@]}"; do
[[ -n "$secret" ]] && text="${text//"$secret"/<redacted>}"
done
printf '%s' "$text"
}
log_init() {
local dir
dir="${LOG_DIR:-/var/log/ai-installer}"
if ! mkdir -p "$dir" 2>/dev/null || [[ ! -w "$dir" ]]; then
dir="${STATE_DIR:-/tmp/ai-installer}/logs"
mkdir -p "$dir" 2>/dev/null || true
fi
PHOEBUS_LOG_FILE="${PHOEBUS_LOG_FILE:-$dir/install.log}"
: >"$PHOEBUS_LOG_FILE" 2>/dev/null || PHOEBUS_LOG_FILE=/dev/null
log_line INFO "=== ${DISTRO_NAME:-Phoebus OS} installer started ==="
log_line INFO "log file: $PHOEBUS_LOG_FILE"
}
log_line() {
local level="$1" message="${2-}"
local ts
ts="$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date)"
message="$(redact_scrub "$message")"
printf '%s [%s] %s\n' "$ts" "$level" "$message" >>"$PHOEBUS_LOG_FILE" 2>/dev/null || true
if [[ "$PHOEBUS_LOG_ECHO" == "yes" ]]; then
printf '%s [%s] %s\n' "$ts" "$level" "$message" >&2
fi
}
log_debug() { log_line DEBUG "$@"; }
log_info() { log_line INFO "$@"; }
log_warn() { log_line WARN "$@"; }
log_error() { log_line ERROR "$@"; }
log_section() { log_line INFO "--- $* ---"; }
# _cmd_to_string ARGS... - printable, redacted representation of a command
_cmd_to_string() {
local out="" arg
for arg in "$@"; do
out+="$(printf '%q' "$arg") "
done
redact_scrub "${out% }"
}
# run_cmd DESCRIPTION ARGS...
# Execute a command, streaming stdout/stderr to the log. Honours DRY_RUN.
run_cmd() {
local desc="$1"; shift
local printable status
printable="$(_cmd_to_string "$@")"
if config_bool DRY_RUN; then
log_line INFO "[dry-run] $desc :: $printable"
return 0
fi
log_line INFO "$desc :: $printable"
"$@" >>"$PHOEBUS_LOG_FILE" 2>&1
status=$?
log_line INFO "$desc :: exit status $status"
return $status
}
# run_cmd_capture DESCRIPTION ARGS...
# Like run_cmd but stdout is stored in RUN_OUTPUT and not streamed. stderr
# still goes to the log. Never logs the captured stdout (may contain secrets).
run_cmd_capture() {
local desc="$1"; shift
local printable status
RUN_OUTPUT=""
printable="$(_cmd_to_string "$@")"
if config_bool DRY_RUN; then
log_line INFO "[dry-run] $desc (capture) :: $printable"
return 0
fi
log_line DEBUG "$desc (capture) :: $printable"
RUN_OUTPUT="$("$@" 2>>"$PHOEBUS_LOG_FILE")"
status=$?
log_line DEBUG "$desc :: exit status $status"
return $status
}
# run_cmd_quiet DESCRIPTION ARGS... - output fully suppressed
run_cmd_quiet() {
local desc="$1"; shift
local printable status
printable="$(_cmd_to_string "$@")"
if config_bool DRY_RUN; then
log_line INFO "[dry-run] $desc :: $printable"
return 0
fi
log_line DEBUG "$desc (quiet) :: $printable"
"$@" >>"$PHOEBUS_LOG_FILE" 2>&1
status=$?
log_line DEBUG "$desc :: exit status $status"
return $status
}
# require_cmd NAME... - fail fast when a required tool is unavailable
require_cmd() {
local missing=() name
for name in "$@"; do
command -v "$name" >/dev/null 2>&1 || missing+=("$name")
done
if ((${#missing[@]})); then
log_error "missing required command(s): ${missing[*]}"
return 1
fi
return 0
}
# log_tail [N] - last N lines of the log (for the TUI)
log_tail() {
local n="${1:-40}"
tail -n "$n" "$PHOEBUS_LOG_FILE" 2>/dev/null
}

102
installer/lib/network.sh Normal file
View file

@ -0,0 +1,102 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Networking for the live environment and for the installed system.
#
# In the live environment we drive NetworkManager (present in the Gentoo
# LiveGUI reference) because it works for both wired and wireless. The installed
# system also uses NetworkManager, which matches the desktop profile.
WIFI_PASSPHRASE=""
network_interfaces() {
local iface
for iface in /sys/class/net/*; do
iface="${iface##*/}"
[[ "$iface" == "lo" ]] && continue
printf '%s\n' "$iface"
done
}
network_is_wireless() {
local iface="$1"
[[ -d "/sys/class/net/$iface/wireless" ]] || \
[[ -d "/sys/class/net/$iface/phy80211" ]]
}
network_interface_state() {
cat "/sys/class/net/$1/operstate" 2>/dev/null || printf 'unknown'
}
network_online() {
command -v ip >/dev/null 2>&1 || return 1
ip route show default 2>/dev/null | grep -q 'default' && return 0
if command -v ping >/dev/null 2>&1; then
ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 && return 0
fi
return 1
}
network_status_text() {
local iface
printf 'Connectivity: %s\n\n' "$(network_online && echo online || echo offline)"
for iface in $(network_interfaces); do
local kind state
kind="$(network_is_wireless "$iface" && echo wireless || echo wired)"
state="$(network_interface_state "$iface")"
printf ' %-12s %-8s %s\n' "$iface" "$kind" "$state"
done
}
# network_live_start - best effort start of the live network manager
network_live_start() {
if command -v rc-service >/dev/null 2>&1; then
run_cmd "start NetworkManager (OpenRC)" rc-service NetworkManager start 2>/dev/null || true
fi
if command -v nmcli >/dev/null 2>&1; then
run_cmd "ensure NetworkManager running" nmcli general status >/dev/null 2>&1 || true
fi
if command -v rfkill >/dev/null 2>&1; then
run_cmd "unblock wifi" rfkill unblock wifi 2>/dev/null || true
fi
}
# network_connect_wifi SSID PASSPHRASE - live environment helper
network_connect_wifi() {
local ssid="$1" pass="$2"
command -v nmcli >/dev/null 2>&1 || { log_error "nmcli not available"; return 1; }
secret_register "$pass"
if [[ -n "$pass" ]]; then
run_cmd "connect to wifi '$ssid'" nmcli device wifi connect "$ssid" password "$pass"
else
run_cmd "connect to wifi '$ssid'" nmcli device wifi connect "$ssid"
fi
}
# network_wifi_scan - print "SSID SIGNAL SECURITY" lines
network_wifi_scan() {
command -v nmcli >/dev/null 2>&1 || return 1
nmcli -t -f SSID,SIGNAL,SECURITY device wifi list 2>/dev/null | \
awk -F: 'NF && $1!=""{printf "%-32s %3s%% %s\n", $1, $2, $3}'
}
# network_configure_target ROOT
# Write the target hostname and enable the networking services. Service
# enablement itself happens inside the chroot during install.
network_configure_target() {
local root="$1" hostname
hostname="$(config_get HOSTNAME)"
mkdir -p "$root/etc"
printf '%s\n' "$hostname" >"$root/etc/hostname"
{
printf '127.0.0.1\tlocalhost\n'
printf '::1\t\tlocalhost\n'
printf '127.0.1.1\t%s\n' "$hostname"
} >"$root/etc/hosts"
log_info "configured hostname '$hostname' in target"
}
# network_target_service_names - services to enable in the installed system
network_target_services() {
printf '%s\n' NetworkManager systemd-resolved
}

156
installer/lib/opencode.sh Normal file
View file

@ -0,0 +1,156 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Reproducible OpenCode provisioning.
#
# The vendor installer (curl | sh) is never used. We fetch a pinned release
# tarball from the official GitHub release and verify its SHA-256 against the
# local manifest before extracting it. The binary is never executed during
# verification.
opencode_manifest_file() {
printf '%s/config/opencode.manifest' "$PHOEBUS_ROOT"
}
opencode_manifest_get() {
local arch="$1" key="$2" file out
file="$(opencode_manifest_file)"
[[ -r "$file" ]] || return 1
out="$(awk -F= -v a="$arch" -v k="$key" '$1==a"."k{sub(/^[^=]*=/,""); print; exit}' "$file")"
[[ -n "$out" ]] || return 1
printf '%s' "$out"
}
opencode_version_manifest() {
local file
file="$(opencode_manifest_file)"
awk -F= '$1=="VERSION"{print $2; exit}' "$file" 2>/dev/null
}
opencode_arch() {
case "$(uname -m)" in
x86_64|amd64) printf 'x86_64' ;;
aarch64|arm64) printf 'aarch64' ;;
*) printf 'unsupported' ;;
esac
}
# opencode_bin_dir - where the verified binary lives
opencode_bin_dir() {
if [[ -n "${PHOEBUS_OPENCODE_DIR:-}" ]]; then
printf '%s' "$PHOEBUS_OPENCODE_DIR"
elif [[ -w /opt ]]; then
printf '/opt/phoebus/opencode'
else
printf '%s/opencode' "${STATE_DIR:-/tmp/ai-installer}"
fi
}
# opencode_detect - print the path to a usable opencode binary, if any
opencode_detect() {
local candidate
if command -v opencode >/dev/null 2>&1; then
command -v opencode
return 0
fi
for candidate in "$(opencode_bin_dir)/opencode" /usr/local/bin/opencode; do
[[ -x "$candidate" ]] && { printf '%s' "$candidate"; return 0; }
done
return 1
}
opencode_available() { opencode_detect >/dev/null 2>&1; }
# opencode_checksum_ok FILE EXPECTED - false for placeholders or mismatches
opencode_checksum_ok() {
local file="$1" expected="$2" got
[[ -n "$expected" ]] || return 1
[[ "$expected" =~ ^0+$ ]] && return 1
got="$(sha256sum "$file" | awk '{print $1}')"
[[ "$got" == "$expected" ]]
}
# opencode_bootstrap [DESTDIR] - download, verify and extract a pinned release
opencode_bootstrap() {
local dest="${1:-$(opencode_bin_dir)}"
local arch url sha binary tmp
arch="$(opencode_arch)"
if [[ "$arch" == "unsupported" ]]; then
log_error "OpenCode: unsupported architecture $(uname -m)"
return 1
fi
url="$(opencode_manifest_get "$arch" url)"
sha="$(opencode_manifest_get "$arch" sha256)"
binary="$(opencode_manifest_get "$arch" binary)"
binary="${binary:-opencode}"
if [[ -z "$url" || -z "$sha" ]]; then
log_error "OpenCode: no pinned manifest entry for $arch"
return 1
fi
if [[ "$sha" =~ ^0+$ ]]; then
log_error "OpenCode: manifest has a placeholder checksum for $arch; refusing"
return 1
fi
require_cmd curl sha256sum tar || return 1
mkdir -p "$dest" || return 1
tmp="$(mktemp "${TMPDIR:-/tmp}/opencode.XXXXXX.tar.gz")" || return 1
# shellcheck disable=SC2064
trap "rm -f '$tmp'" RETURN
log_info "OpenCode: fetching $url"
if ! run_cmd "download OpenCode" curl -fL --retry 3 -o "$tmp" "$url"; then
return 1
fi
if ! opencode_checksum_ok "$tmp" "$sha"; then
log_error "OpenCode: SHA-256 verification FAILED; discarding download"
rm -f "$tmp"
return 1
fi
log_info "OpenCode: checksum verified"
run_cmd "extract OpenCode" tar -xzf "$tmp" -C "$dest" || return 1
[[ -f "$dest/$binary" ]] || { log_error "OpenCode: expected binary '$binary' not found"; return 1; }
chmod 0755 "$dest/$binary"
ln -sf "$dest/$binary" "$dest/opencode" 2>/dev/null || true
log_info "OpenCode installed at $dest/$binary ($(opencode_version_manifest))"
return 0
}
# opencode_ensure - ensure a binary is present, bootstrapping if needed
opencode_ensure() {
opencode_available && return 0
log_info "OpenCode not found; bootstrapping pinned release"
opencode_bootstrap
}
# opencode_print_version BIN
opencode_print_version() {
local bin="$1"
"$bin" --version 2>/dev/null | head -n1
}
# opencode_ai_config_path - where the installer keeps AI provider config
opencode_ai_config_path() {
printf '%s/ai/opencode.json' "${STATE_DIR:-/tmp/ai-installer}"
}
# opencode_write_config - write provider/model config (never secrets)
opencode_write_config() {
local path dir provider model endpoint
path="$(opencode_ai_config_path)"
dir="$(dirname "$path")"
mkdir -p "$dir"
provider="$(config_get AI_PROVIDER)"
model="$(config_get AI_MODEL)"
endpoint="$(config_get AI_ENDPOINT)"
{
printf '{\n'
printf ' "$schema": "https://opencode.ai/config.json"\n'
if [[ -n "$provider" ]]; then printf ' ,"provider": "%s"\n' "$provider"; fi
if [[ -n "$model" ]]; then printf ' ,"model": "%s"\n' "$model"; fi
if [[ -n "$endpoint" ]]; then printf ' ,"baseURL": "%s"\n' "$endpoint"; fi
printf '}\n'
} >"$path"
chmod 0600 "$path"
log_info "wrote OpenCode config to $path (credentials are never stored here)"
}

View file

@ -0,0 +1,69 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# GPT partition creation for the installation target.
#
# Every function here is destructive and must be invoked through
# run_destructive, which enforces prior authorization.
# partitions_require_tools
partitions_require_tools() {
require_cmd sgdisk partprobe blkid wipefs || return 1
}
# partitions_wipe DISK - zap all existing partition signatures
partitions_wipe() {
local disk="$1"
run_destructive "wipe partition signatures on $disk" wipefs -a "$disk" || return 1
run_destructive "zap GPT/MBR on $disk" sgdisk --zap-all "$disk"
}
# partitions_create_gpt DISK - EFI + root (LUKS or plain btrfs)
partitions_create_gpt() {
local disk="$1"
local efi_mib root_type=8309
efi_mib="$(config_get EFI_SIZE_MIB)"
[[ "$efi_mib" =~ ^[0-9]+$ ]] || efi_mib=1024
if [[ "$(config_get ENCRYPTION)" == "none" ]]; then
root_type=8300
fi
run_destructive "create GPT on $disk" sgdisk --set-alignment=2048 \
--new=1:0:+${efi_mib}M --typecode=1:ef00 --change-name=1:EFI \
--new=2:0:0 --typecode=2:${root_type} --change-name=2:phoebus-root \
"$disk" || return 1
run_destructive "re-read partition table on $disk" partprobe "$disk"
command -v udevadm >/dev/null 2>&1 && run_cmd "settle udev" udevadm settle
}
# partitions_named DISK - first EFI and root partition paths via blkid
partitions_named() {
local disk="$1"
EFI_PART="" ROOT_PART=""
# Prefer explicit GPT names when available.
if command -v blkid >/dev/null 2>&1; then
local dev label
while IFS= read -r dev; do
label="$(blkid -s PARTLABEL -o value "$dev" 2>/dev/null)"
case "$label" in
EFI) EFI_PART="$dev" ;;
phoebus-root) ROOT_PART="$dev" ;;
esac
done < <(disk_partitions "$disk")
fi
# Fallback by order.
local -a parts=()
mapfile -t parts < <(disk_partitions "$disk")
[[ -z "$EFI_PART" && ${#parts[@]} -ge 1 ]] && EFI_PART="${parts[0]}"
[[ -z "$ROOT_PART" && ${#parts[@]} -ge 2 ]] && ROOT_PART="${parts[1]}"
[[ -n "$EFI_PART" && -n "$ROOT_PART" ]]
}
# partitions_verify DISK - sanity check after creation
partitions_verify() {
local disk="$1"
partitions_named "$disk" || { log_error "could not identify created partitions on $disk"; return 1; }
[[ -b "$EFI_PART" && -b "$ROOT_PART" ]] || { log_error "partition devices missing"; return 1; }
log_info "partitions: EFI=$EFI_PART root=$ROOT_PART"
return 0
}

156
installer/lib/pkgpolicy.sh Normal file
View file

@ -0,0 +1,156 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Package compilation policy.
#
# The rule is deliberately deterministic:
#
# compile when compilation is cheap OR gives a meaningful benefit;
# use a binary when compilation is expensive AND the benefit is negligible.
#
# Decisions are driven by a small curated table plus optional historical
# compile-time data. An LLM is never consulted to guess performance.
#
# Historical data format (tab separated), one package per line:
# category/package<TAB>seconds<TAB>updates-per-year
# Overrides the built-in estimate.
declare -gA PKGPOLICY_COMPILE_SECONDS=(
[app-editors/vim]=45
[app-misc/tmux]=20
[app-shells/zsh]=60
[dev-lang/python]=900
[dev-lang/rust]=3600
[dev-libs/glib]=120
[dev-util/cmake]=300
[dev-vcs/git]=120
[media-video/ffmpeg]=900
[net-misc/curl]=90
[sys-apps/busybox]=60
[sys-apps/coreutils]=120
[sys-apps/systemd]=420
[sys-devel/gcc]=3600
[sys-kernel/gentoo-kernel]=1800
[sys-kernel/gentoo-sources]=120
[sys-libs/glibc]=900
[www-client/firefox]=4200
[www-client/chromium]=7200
[app-office/libreoffice]=5400
[dev-qt/qtbase]=900
[kde-plasma/plasma-desktop]=600
[net-im/discord-bin]=0
[games-util/steam-launcher]=0
)
# Packages where a binary package is strongly preferred (huge + frequent
# updates + negligible local optimisation benefit + runtime CPU dispatch).
declare -gA PKGPOLICY_BINARY_PREFERRED=(
[www-client/firefox]=1
[www-client/chromium]=1
[app-office/libreoffice]=1
[mail-client/thunderbird]=1
[dev-lang/rust]=1
[dev-lang/llvm]=1
[dev-qt/qtwebengine]=1
[sys-devel/gcc]=1
[sys-libs/glibc]=1
[net-im/discord-bin]=1
[games-util/steam-launcher]=1
)
# Packages that genuinely benefit from local optimisation or USE customisation.
declare -gA PKGPOLICY_SOURCE_PREFERRED=(
[sys-kernel/gentoo-kernel]=1
[sys-kernel/gentoo-sources]=1
[sys-apps/systemd]=1
[app-shells/zsh]=1
[sys-apps/busybox]=1
[sys-fs/btrfs-progs]=1
[sys-fs/cryptsetup]=1
)
PKGPOLICY_HISTORY_FILE=""
pkgpolicy_history_file() {
printf '%s' "${PKGPOLICY_HISTORY_FILE:-${STATE_DIR:-/tmp/ai-installer}/compile-times.tsv}"
}
pkgpolicy_compile_seconds() {
local pkg="$1" hist line
hist="$(pkgpolicy_history_file)"
if [[ -r "$hist" ]]; then
line="$(awk -F'\t' -v p="$pkg" '$1==p{print $2; exit}' "$hist")"
if [[ "$line" =~ ^[0-9]+$ ]]; then printf '%s' "$line"; return; fi
fi
printf '%s' "${PKGPOLICY_COMPILE_SECONDS[$pkg]:-300}"
}
pkgpolicy_updates_per_year() {
local pkg="$1" hist line
hist="$(pkgpolicy_history_file)"
if [[ -r "$hist" ]]; then
line="$(awk -F'\t' -v p="$pkg" '$1==p{print $3; exit}' "$hist")"
if [[ "$line" =~ ^[0-9]+$ ]]; then printf '%s' "$line"; return; fi
fi
printf '6'
}
# pkgpolicy_binary_available PKG - a binary can plausibly be fetched
pkgpolicy_binary_available() {
[[ -n "$(config_get BINHOST_URI)" ]] || return 1
config_bool FEATURES_BINPKG
}
# pkgpolicy_decide PKG - prints "source" or "binary"
pkgpolicy_decide() {
local pkg="$1" policy seconds mem cores
policy="$(config_get PACKAGE_POLICY)"
seconds="$(pkgpolicy_compile_seconds "$pkg")"
mem="$(hw_mem_total_mib)"; [[ -n "$mem" ]] || mem=4096
cores="$(hw_cpu_cores)"; [[ -n "$cores" ]] || cores=2
case "$policy" in
source_first)
printf 'source'; return ;;
binary_first)
if pkgpolicy_binary_available; then printf 'binary'; else printf 'source'; fi
return ;;
esac
# balanced:
# - explicit preferences win;
# - cheap builds are compiled locally;
# - everything else uses a signed Gentoo binary when one is available.
# This is deterministic and avoids guessing performance where no data
# exists. Portage still builds from source whenever USE does not match the
# binary (--binpkg-respect-use=y).
if [[ -n "${PKGPOLICY_BINARY_PREFERRED[$pkg]:-}" ]]; then
pkgpolicy_binary_available && { printf 'binary'; return; }
fi
if [[ -n "${PKGPOLICY_SOURCE_PREFERRED[$pkg]:-}" ]]; then
printf 'source'; return
fi
if ((seconds <= 120)); then printf 'source'; return; fi
if pkgpolicy_binary_available; then printf 'binary'; return; fi
printf 'source'
}
# pkgpolicy_emerge_flags PKG - extra emerge flags for a package
pkgpolicy_emerge_flags() {
local pkg="$1" decision
decision="$(pkgpolicy_decide "$pkg")"
if [[ "$decision" == "binary" ]]; then
printf '%s\n' --getbinpkg --binpkg-respect-use=y
fi
}
# pkgpolicy_report [PKGS...] - human readable policy decisions
pkgpolicy_report() {
local -a pkgs=("$@") pkg
((${#pkgs[@]})) || pkgs=(sys-apps/systemd sys-devel/gcc www-client/firefox sys-kernel/gentoo-kernel app-editors/vim)
printf 'Policy: %s\n\n' "$(config_get PACKAGE_POLICY)"
printf '%-32s %8s %s\n' "package" "est(s)" "decision"
for pkg in "${pkgs[@]}"; do
printf '%-32s %8s %s\n' "$pkg" "$(pkgpolicy_compile_seconds "$pkg")" "$(pkgpolicy_decide "$pkg")"
done
}

147
installer/lib/plan.sh Normal file
View file

@ -0,0 +1,147 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Installation plan generation.
#
# The plan is a deterministic, human-readable description of the operations the
# backend will perform. Nothing is executed until the plan has been displayed
# and explicitly approved (see install.sh).
declare -ga PLAN_LINES=()
declare -ga PLAN_STEPS=()
_plan_add() { PLAN_LINES+=("$@"); }
_step() { PLAN_STEPS+=("$*"); }
# plan_swap_mib - swapfile size in MiB derived from installed RAM
plan_swap_mib() {
local mem
mem="$(hw_mem_total_mib)"
[[ -n "$mem" ]] || mem=4096
local swap=$((mem / 2))
((swap < 1024)) && swap=1024
((swap > 8192)) && swap=8192
printf '%s' "$swap"
}
# plan_storage_sizes - sets PLAN_EFI_MIB and PLAN_LUKS_MIB
plan_storage_sizes() {
local disk="${1:-$(config_get TARGET_DISK)}" total efi
PLAN_EFI_MIB="$(config_get EFI_SIZE_MIB)"
[[ "$PLAN_EFI_MIB" =~ ^[0-9]+$ ]] || PLAN_EFI_MIB=1024
total=0
if [[ -b "$disk" ]]; then
total="$(disk_size_bytes "$disk")"
fi
PLAN_LUKS_MIB=$(( (total / 1048576) - PLAN_EFI_MIB - 2 ))
((PLAN_LUKS_MIB < 0)) && PLAN_LUKS_MIB=0
}
# plan_generate - build PLAN_LINES and PLAN_STEPS from CFG
plan_generate() {
PLAN_LINES=()
PLAN_STEPS=()
local disk hostname locale tz username fs enc kprofile desktop policy
disk="$(config_get TARGET_DISK)"
hostname="$(config_get HOSTNAME)"
locale="$(config_get LOCALE)"
tz="$(config_get TIMEZONE)"
username="$(config_get USERNAME)"
fs="$(config_get FILESYSTEM)"
enc="$(config_get ENCRYPTION)"
kprofile="$(config_get KERNEL_PROFILE)"
desktop="$(config_get DESKTOP_PROFILE)"
policy="$(config_get PACKAGE_POLICY)"
_plan_add "Installation plan"
_plan_add "================="
_plan_add ""
_plan_add "System:"
_plan_add " Distribution : $(config_get DISTRO_NAME)"
_plan_add " Architecture : $(config_get ARCH)"
_plan_add " Init system : $(config_get INIT_SYSTEM)"
_plan_add " Firmware : $(hw_firmware_mode)"
_plan_add ""
_plan_add "Identity:"
_plan_add " Hostname : $hostname"
_plan_add " Keymap : $(config_get KEYMAP)"
_plan_add " Locale : $locale"
_plan_add " Timezone : $tz"
_plan_add " User : ${username:-<not set>}"
_plan_add ""
_plan_add "Storage:"
_plan_add " Target disk : ${disk:-<not selected>}"
if [[ -n "$disk" && -b "$disk" ]]; then
_plan_add " Disk model : $(disk_model "$disk")"
_plan_add " Disk size : $(disk_size_human "$(disk_size_bytes "$disk")")"
fi
_plan_add " Partitioning : GPT (${PARTITION_SCHEME:-whole_disk})"
_plan_add " Encryption : ${enc:-none}"
_plan_add " Filesystem : $fs"
_plan_add ""
_plan_add " Layout:"
_plan_add " EFI System Partition (FAT32) $(config_get EFI_SIZE_MIB) MiB -> $(config_get EFI_MOUNT)"
_plan_add " $(printf '%-36s' "${enc^^} container") remainder"
_plan_add " $(printf '%-34s' "$fs")"
local subvol
for subvol in $(config_get BTRFS_SUBVOLS); do
_plan_add " $subvol"
done
_plan_add ""
_plan_add "Boot and kernel:"
_plan_add " Bootloader : $(config_get BOOTLOADER) (BLS entries)"
_plan_add " Unified UKI : $(config_get KERNEL_UKI) (deferred; BLS used)"
_plan_add " Kernel : $(kernel_select_package 2>/dev/null || config_get KERNEL_PACKAGE) ($kprofile profile)"
_plan_add " Keep kernels : $(config_get KEEP_KERNELS)"
_plan_add ""
_plan_add "Software:"
_plan_add " Package policy : $policy"
_plan_add " Binary pkgs : $(config_get FEATURES_BINPKG)"
_plan_add " Accept license : $(config_get ACCEPT_LICENSE)"
_plan_add " Desktop : $desktop"
_plan_add " Flatpak : $(config_get FLATPAK)"
_plan_add " Audio : $(config_get AUDIO_STACK)"
_plan_add " AI assistant : $(config_get AI_ENABLED)"
# Ordered execution steps (names map to backend functions in install.sh).
_step "storage_prepare"
_step "stage_install"
_step "fstab_generate"
_step "portage_configure"
_step "packages_base"
_step "kernel_install"
_step "boot_install"
_step "users_configure"
_step "services_configure"
_step "desktop_install"
_step "finalize"
}
# plan_render - print the full plan
plan_render() { printf '%s\n' "${PLAN_LINES[@]}"; }
# plan_destructive_preview - the scary, explicit summary shown before wiping
plan_destructive_preview() {
local disk enc fs
disk="$(config_get TARGET_DISK)"
enc="$(config_get ENCRYPTION)"
fs="$(config_get FILESYSTEM)"
printf 'TARGET: %s\n' "$disk"
printf '\n'
printf 'ALL DATA ON THIS DEVICE WILL BE DESTROYED.\n'
printf 'This cannot be undone.\n'
printf '\n'
printf ' EFI (FAT32): %s MiB\n' "$(config_get EFI_SIZE_MIB)"
if [[ "$enc" != "none" && -n "$enc" ]]; then
printf ' %s (passphrase): remainder\n' "${enc^^}"
fi
printf ' %s:\n' "$fs"
local subvol
for subvol in $(config_get BTRFS_SUBVOLS); do
printf ' %s\n' "$subvol"
done
printf '\n'
printf 'Existing partitions on the target:\n'
disk_layout_text "$disk" 2>/dev/null | sed 's/^/ /'
}

363
installer/lib/portage.sh Normal file
View file

@ -0,0 +1,363 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Portage configuration and base-system installation.
#
# Portage stays the authoritative package manager. This module writes a
# sensible initial configuration, resolves the stable systemd stage3 and runs
# emerge inside the target chroot.
# portage_detect_cpu_flags - CPU_FLAGS_X86 from /proc/cpuinfo (deterministic)
portage_detect_cpu_flags() {
local -a wanted=(aes avx avx2 avx512f avx512bw avx512cd avx512dq avx512vl
bmi1 bmi2 f16c fma mmx mmxext pclmul popcnt rdrand sha sse sse2 sse3
sse4_1 sse4_2 ssse3 xop)
local -A flags=()
local f w
for f in $(awk -F': ' '/^flags/{print $2; exit}' /proc/cpuinfo 2>/dev/null); do
flags[$f]=1
done
local out=()
for w in "${wanted[@]}"; do
[[ -n "${flags[$w]:-}" ]] && out+=("$w")
done
printf '%s' "${out[*]}"
}
portage_detect_video_cards() {
local vendors cards=()
vendors="$(hw_gpu_vendors)"
[[ "$vendors" == *intel* ]] && cards+=(intel)
[[ "$vendors" == *amd* ]] && cards+=(amdgpu radeonsi)
[[ "$vendors" == *nvidia* ]] && cards+=(nvidia)
((${#cards[@]})) || cards+=(dummy)
printf '%s' "${cards[*]}"
}
# portage_makeopts - parallel build width bounded by RAM
portage_makeopts() {
local cores mem jobs load
cores="$(hw_cpu_cores)"; [[ "$cores" =~ ^[0-9]+$ ]] || cores=4
mem="$(hw_mem_total_mib)"; [[ "$mem" =~ ^[0-9]+$ ]] || mem=4096
jobs=$((cores + 1))
local mem_jobs=$((mem / 2048))
((mem_jobs < 1)) && mem_jobs=1
((jobs > mem_jobs)) && jobs=$mem_jobs
((jobs < 1)) && jobs=1
load="$cores"
printf -- '-j%s -l%s' "$jobs" "$load"
}
portage_write_make_conf() {
local root="$1"
local mac="$root/etc/portage/make.conf"
mkdir -p "$(dirname "$mac")"
{
printf '# %s Portage configuration\n' "$(config_get DISTRO_NAME)"
printf '# Generated by the installer. Safe to edit.\n\n'
printf 'COMMON_FLAGS="-O2 -pipe -march=native"\n'
printf 'CFLAGS="${COMMON_FLAGS}"\n'
printf 'CXXFLAGS="${COMMON_FLAGS}"\n'
printf 'FCFLAGS="${COMMON_FLAGS}"\n'
printf 'FFLAGS="${COMMON_FLAGS}"\n\n'
printf 'MAKEOPTS="%s"\n' "$(portage_makeopts)"
printf 'EMERGE_DEFAULT_OPTS="--binpkg-respect-use=y --with-bdeps=y"\n\n'
printf 'ACCEPT_KEYWORDS="amd64"\n'
printf 'ACCEPT_LICENSE="%s"\n\n' "$(config_get ACCEPT_LICENSE)"
printf '# Keep the global USE set close to the profile/binhost baseline so that\n'
printf '# signed binaries can be reused; per-package USE lives in package.use.\n'
printf '# dbus/policykit are part of the standard systemd desktop baseline and\n'
printf '# are required by NetworkManager/wpa_supplicant and polkit respectively.\n'
printf 'USE="systemd dbus policykit"\n'
printf 'VIDEO_CARDS="%s"\n' "$(portage_detect_video_cards)"
printf 'INPUT_DEVICES="libinput"\n'
printf 'LINGUAS="en"\n'
} >"$mac"
log_info "wrote $mac"
}
portage_write_repos_conf() {
local root="$1"
local dir="$root/etc/portage/repos.conf"
mkdir -p "$dir"
{
printf '[gentoo]\n'
printf 'location = /var/db/repos/gentoo\n'
printf 'sync-type = rsync\n'
printf 'sync-uri = rsync://rsync.gentoo.org/gentoo-portage\n'
printf 'auto-sync = yes\n'
} >"$dir/gentoo.conf"
log_info "wrote $dir/gentoo.conf"
}
portage_write_binrepos() {
local root="$1"
local dir="$root/etc/portage/binrepos.conf"
mkdir -p "$dir"
{
printf '[gentoo]\n'
printf 'priority = 1\n'
printf 'sync-uri = %s\n' "$(config_get BINHOST_URI)"
printf 'location = /var/cache/binhost/gentoo\n'
printf 'verify-signature = true\n'
} >"$dir/gentoo.conf"
log_info "wrote $dir/gentoo.conf"
}
portage_write_package_files() {
local root="$1"
local dir="$root/etc/portage/package.use"
mkdir -p "$dir"
{
printf '# %s installer policy\n' "$(config_get DISTRO_NAME)"
printf '# Core system: systemd is the init system.\n'
printf '# policykit is required by sys-auth/polkit[systemd];\n'
printf '# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n'
printf 'sys-apps/systemd boot policykit cryptsetup\n'
printf '# Distribution kernel + systemd-boot UKI generation.\n'
printf '# installkernel REQUIRED_USE: systemd-boot? ( systemd ), ukify? ( uki )\n'
printf 'sys-kernel/installkernel dracut systemd systemd-boot uki\n'
printf 'sys-apps/dbus systemd\n'
printf 'sys-auth/polkit systemd\n'
printf 'sys-apps/util-linux systemd\n'
printf '# Networking\n'
printf 'net-misc/networkmanager systemd\n'
printf '# Audio (PipeWire + WirePlumber are the standard stack)\n'
printf 'media-video/pipewire sound-server\n'
printf 'media-video/wireplumber\n'
if [[ "$(config_get DESKTOP_PROFILE)" != "none" ]]; then
# Wayland-first, but GTK3/polkit-gnome still need cairo/gtk built with
# X support (XWayland and the GTK X11 backend). Keep Wayland enabled too.
printf '# Desktop (Wayland-first, XWayland compatibility)\n'
printf 'x11-libs/cairo X\n'
printf 'x11-libs/gtk+ X wayland\n'
printf 'gui-libs/gtk wayland\n'
printf 'media-libs/libglvnd X\n'
printf 'x11-terms/kitty wayland\n'
printf 'media-video/pipewire systemd\n'
fi
} >"$dir/phoebus"
log_info "wrote $dir/phoebus"
# Narrowly scoped testing keywords. Gentoo currently keywords linux-firmware
# and some Wayland components as testing-only; these are hardware/desktop
# enablement and are justified explicitly rather than globally enabling
# ~amd64.
local ak="$root/etc/portage/package.accept_keywords"
mkdir -p "$ak"
{
printf '# Phoebus: scoped testing keywords for hardware/desktop enablement.\n'
printf '# This is NOT a global ~amd64 switch.\n'
printf 'sys-kernel/linux-firmware\n'
printf 'gui-wm/dwl\n'
} >"$ak/phoebus"
log_info "wrote $ak/phoebus"
}
# portage_select_profile ROOT
portage_select_profile() {
local root="$1" profile
profile="$(config_get GENTOO_PROFILE)"
local link="$root/etc/portage/make.profile"
mkdir -p "$(dirname "$link")"
rm -f "$link"
ln -s "/var/db/repos/gentoo/profiles/$profile" "$link"
log_info "profile -> $profile"
}
# portage_stage3_url - resolve the stable systemd stage3 URL
portage_stage3_url() {
local pinned
pinned="$(config_get STAGE3_URL)"
if [[ -n "$pinned" ]]; then printf '%s' "$pinned"; return 0; fi
local base latest rel
base="$(config_get STAGE3_MIRROR)"
latest="$base/current-stage3-amd64-systemd/latest-stage3-amd64-systemd.txt"
if command -v curl >/dev/null 2>&1; then
# The latest-*.txt file is PGP-clearsigned and contains a line such as:
# stage3-amd64-systemd-20260913T163055Z.tar.xz 290634984
rel="$(curl -fsSL "$latest" 2>/dev/null | \
awk '$1 ~ /^stage3-amd64-systemd-.*\.tar\.xz$/{print $1; exit}')"
fi
if [[ -z "$rel" ]]; then
log_warn "could not resolve latest stage3 (offline?); set STAGE3_URL explicitly"
return 1
fi
printf '%s/current-stage3-amd64-systemd/%s' "$base" "$rel"
}
# portage_verify_stage3_signature FILE
# Verifies the clearsigned DIGESTS file with the Gentoo release key that the
# stage3 ships. Fails closed when gpg and the key are available.
portage_verify_stage3_signature() {
local digests="$1" key="/usr/share/openpgp-keys/gentoo-release.asc" home rc=0
command -v gpg >/dev/null 2>&1 || { log_warn "gpg unavailable; skipping signature check"; return 0; }
[[ -r "$key" ]] || { log_warn "Gentoo release key not found; skipping signature check"; return 0; }
home="$(mktemp -d)"
if ! GNUPGHOME="$home" gpg --batch --quiet --import "$key" >/dev/null 2>>"$PHOEBUS_LOG_FILE" 2>&1; then
log_warn "could not import Gentoo release key; skipping signature check"
rm -rf "$home"
return 0
fi
if GNUPGHOME="$home" gpg --batch --verify "$digests" >>"$PHOEBUS_LOG_FILE" 2>&1; then
log_info "stage3 DIGESTS signature verified"
else
log_error "stage3 DIGESTS signature verification FAILED"
rc=1
fi
rm -rf "$home"
return $rc
}
# portage_fetch_stage3 DESTDIR - download and verify the stage3 tarball
portage_fetch_stage3() {
local dest="$1" url base expected got want digests
url="$(portage_stage3_url)" || return 1
base="${url##*/}"
expected="$(config_get STAGE3_SHA256)"
log_info "stage3 URL: $url"
run_cmd "download stage3" curl -fL --retry 3 -o "$dest" "$url" || return 1
if [[ -n "$expected" ]]; then
got="$(sha256sum "$dest" | awk '{print $1}')"
if [[ "$got" != "$expected" ]]; then
log_error "stage3 checksum mismatch (expected $expected, got $got)"
return 1
fi
log_info "stage3 checksum verified (pinned SHA-256)"
return 0
fi
digests="${dest}.DIGESTS"
if ! run_cmd "download stage3 DIGESTS" curl -fsSL -o "$digests" "$url.DIGESTS"; then
log_warn "could not fetch stage3 DIGESTS; checksum not verified"
return 0
fi
portage_verify_stage3_signature "$digests" || return 1
want="$(awk -v f="$base" 'length($1)==128 && $2==f{print $1; exit}' "$digests")"
if [[ -z "$want" ]]; then
log_warn "no SHA-512 entry for $base in DIGESTS"
rm -f "$digests"
return 0
fi
got="$(sha512sum "$dest" | awk '{print $1}')"
rm -f "$digests"
if [[ "$got" != "$want" ]]; then
log_error "stage3 SHA-512 mismatch (expected $want, got $got)"
return 1
fi
log_info "stage3 SHA-512 verified against signed DIGESTS"
return 0
}
# portage_extract_stage3 ROOT TARBALL
portage_extract_stage3() {
local root="$1" tarball="$2"
run_destructive "extract stage3 into $root" \
tar --xattrs --xattrs-include='*.*' --numeric-owner -xpf "$tarball" -C "$root"
}
# portage_chroot ROOT CMD... - run a command inside the target
portage_chroot() {
local root="$1"; shift
run_cmd "chroot: $*" chroot "$root" \
/usr/bin/env -i \
PATH=/usr/sbin:/usr/bin:/sbin:/bin \
HOME=/root TERM="${TERM:-xterm}" LANG=C TMPDIR=/tmp \
"$@"
}
# portage_chroot_stdin ROOT INPUT CMD... - chroot with INPUT on stdin.
# Used for secrets such as password hashes; INPUT is never logged.
portage_chroot_stdin() {
local root="$1" input="$2"; shift 2
if config_bool DRY_RUN; then
log_line INFO "[dry-run] chroot: $* (stdin hidden)"
return 0
fi
log_line INFO "chroot: $* (stdin hidden)"
printf '%s\n' "$input" | chroot "$root" \
/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root LANG=C TMPDIR=/tmp \
"$@" >>"$PHOEBUS_LOG_FILE" 2>&1
local status=$?
log_line INFO "chroot: $* :: exit status $status"
return $status
}
# portage_base_packages - packages every Phoebus system needs beyond stage3.
# cryptsetup and btrfs-progs are required by dracut to build an initramfs that
# can unlock and mount the encrypted Btrfs root.
portage_base_packages() {
printf '%s\n' \
app-admin/sudo \
net-misc/networkmanager \
sys-auth/polkit \
sys-fs/cryptsetup \
sys-fs/btrfs-progs
}
# portage_sync ROOT - initialise the repository over rsync (rsync ships in the
# stage3; curl/wget do not).
portage_sync() {
local root="$1"
portage_chroot "$root" emerge --sync
}
# portage_verification_setup ROOT
# Populate /etc/portage/gnupg with the Gentoo release key so that signed
# binary packages can be verified. getuto ships in the stage3.
portage_verification_setup() {
local root="$1"
portage_chroot "$root" getuto
}
# portage_init_machine_id ROOT
# The systemd stage3 ships no /etc/machine-id. Generate one before the kernel
# is installed so kernel-install has stable machine identification.
portage_init_machine_id() {
local root="$1"
portage_chroot "$root" systemd-machine-id-setup
}
# portage_write_locale_gen ROOT LOCALE - ensure the chosen locale is generated
portage_write_locale_gen() {
local root="$1" locale="$2" file="$1/etc/locale.gen"
[[ -n "$locale" ]] || return 0
[[ -f "$file" ]] || { mkdir -p "$root/etc"; : >"$file"; }
if ! grep -qE "^[[:space:]]*${locale//./\\.}[[:space:]]" "$file"; then
printf '%s UTF-8\n' "$locale" >>"$file"
log_info "locale.gen: enabled $locale"
fi
}
# portage_emerge ROOT PACKAGES...
# Group packages by policy decision and run one emerge per group. This keeps
# the dependency graph solve to a minimum and passes --getbinpkg only to the
# group that should prefer binaries.
portage_emerge() {
local root="$1"; shift
local pkg decision
local -a bin_pkgs=() src_pkgs=()
for pkg in "$@"; do
[[ -n "$pkg" ]] || continue
decision="$(pkgpolicy_decide "$pkg")"
log_info "policy: $pkg -> $decision"
if [[ "$decision" == "binary" ]]; then
bin_pkgs+=("$pkg")
else
src_pkgs+=("$pkg")
fi
done
local status=0
if ((${#src_pkgs[@]})); then
log_info "emerge (source): ${src_pkgs[*]}"
portage_chroot "$root" emerge --ask=n --quiet-build=y \
--binpkg-respect-use=y "${src_pkgs[@]}" || { log_error "source emerge failed"; status=1; }
fi
if ((status == 0 && ${#bin_pkgs[@]})); then
log_info "emerge (binary): ${bin_pkgs[*]}"
portage_chroot "$root" emerge --ask=n --quiet-build=y \
--getbinpkg --binpkg-respect-use=y "${bin_pkgs[@]}" || { log_error "binary emerge failed"; status=1; }
fi
return $status
}

135
installer/lib/state.sh Normal file
View file

@ -0,0 +1,135 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Installer configuration state.
#
# All user choices live in the associative array CFG. The state is deliberately
# kept separate from the UI so that an unattended installation can be driven
# from a plain configuration file.
declare -gA CFG=()
declare -g CONFIG_FILE="${CONFIG_FILE:-}"
# config_default KEY VALUE
# Set KEY to VALUE only when it has not been set yet. This lets a user
# config file loaded later override the shipped defaults.
config_default() {
local key="$1" value="${2-}"
if [[ -z "${CFG[$key]+set}" ]]; then
CFG[$key]="$value"
fi
}
# config_set KEY VALUE
config_set() {
local key="$1" value="${2-}"
CFG[$key]="$value"
}
# config_get KEY [DEFAULT]
config_get() {
local key="$1" default="${2-}"
if [[ -n "${CFG[$key]+set}" ]]; then
printf '%s' "${CFG[$key]}"
else
printf '%s' "$default"
fi
}
# config_is KEY VALUE - boolean helper
config_is() {
[[ "$(config_get "$1")" == "$2" ]]
}
config_bool() {
case "$(config_get "$1")" in
yes|true|1|on) return 0 ;;
*) return 1 ;;
esac
}
# config_load_defaults [FILE]
config_load_defaults() {
local file="${1:-$PHOEBUS_ROOT/config/defaults.conf}"
[[ -r "$file" ]] || return 1
# shellcheck source=/dev/null
source "$file"
}
# Decode a value from a config file. Supports plain, single- and double-quoted
# values. This is not a general shell evaluator on purpose: configuration files
# are data, and must never execute code.
config_decode_value() {
local raw="$1"
case "$raw" in
\'*\')
raw="${raw#\'}"
raw="${raw%\'}"
raw="${raw//\'\\\'\'/\'}"
;;
\"*\")
raw="${raw#\"}"
raw="${raw%\"}"
;;
esac
printf '%s' "$raw"
}
# config_load_file FILE
config_load_file() {
local file="$1" line key value
[[ -r "$file" ]] || return 1
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*# ]] && continue
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
if [[ "$line" =~ ^([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
value="$(config_decode_value "${BASH_REMATCH[2]}")"
CFG[$key]="$value"
fi
done <"$file"
CONFIG_FILE="$file"
}
# config_save_file FILE
config_save_file() {
local file="$1" key
local dir
dir="$(dirname -- "$file")"
mkdir -p "$dir"
{
printf '# Phoebus OS installer configuration\n'
printf '# Generated: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo unknown)"
printf '# NOTE: never place passwords, passphrases or API keys in this file.\n\n'
local -a keys
mapfile -t keys < <(printf '%s\n' "${!CFG[@]}" | sort)
for key in "${keys[@]}"; do
case "$key" in
LUKS_PASSPHRASE|ROOT_PASSWORD|USER_PASSWORD|AI_API_KEY)
continue ;;
esac
printf "%s='%s'\n" "$key" "${CFG[$key]//\'/\'\\\'\'}"
done
} >"$file"
}
# config_summary - stable, sorted KEY=value dump (for logs, values redacted)
config_dump() {
local key
local -a keys
mapfile -t keys < <(printf '%s\n' "${!CFG[@]}" | sort)
for key in "${keys[@]}"; do
printf '%s=%s\n' "$key" "$(redact_value "$key" "${CFG[$key]}")"
done
}
# redact_value KEY VALUE - never emit secret material
redact_value() {
local key="$1" value="$2"
case "$key" in
*PASSWORD*|*PASSPHRASE*|*API_KEY*|*TOKEN*|*SECRET*)
if [[ -n "$value" ]]; then printf '<redacted>'; else printf ''; fi
;;
*) printf '%s' "$value" ;;
esac
}

127
installer/lib/users.sh Normal file
View file

@ -0,0 +1,127 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# User account configuration.
#
# Passwords are hashed immediately and held only as hashes. Plaintext is never
# written to disk, the config file or the log.
declare -g USER_PASSWORD="${USER_PASSWORD:-}"
declare -g ROOT_PASSWORD="${ROOT_PASSWORD:-}"
# users_hash PASSWORD - SHA-512 crypt hash (openssl present in the live image)
users_hash() {
local pw="$1" hash
if command -v openssl >/dev/null 2>&1; then
hash="$(printf '%s' "$pw" | openssl passwd -6 -stdin 2>/dev/null)"
fi
[[ -n "$hash" ]] || return 1
printf '%s' "$hash"
}
# users_prompt_passwords - collect and hash passwords (TUI or tty)
users_prompt_passwords() {
local user rootpw
if declare -F ui_passwordbox >/dev/null 2>&1; then
ui_passwordbox "User password" "Password for $(config_get USERNAME):" || return 1
user="$UI_RESULT"
ui_passwordbox "User password" "Repeat password:" || return 1
[[ "$user" == "$UI_RESULT" ]] || { log_error "user passwords did not match"; return 1; }
ui_passwordbox "Root password" "Password for root (leave blank to lock root):" || return 1
rootpw="$UI_RESULT"
else
read -r -s -p "User password: " user; printf '\n' >&2
read -r -s -p "Root password (blank to lock): " rootpw; printf '\n' >&2
fi
secret_register "$user"
secret_register "$rootpw"
USER_PASSWORD="$user"
ROOT_PASSWORD="$rootpw"
return 0
}
# users_create ROOT - create the primary account and lock root by default
# users_ensure_groups ROOT GROUPS
# Create missing supplementary groups and return the subset that now exists.
# A minimal stage3 does not define render/libinput/plugdev/power, and
# useradd -G fails outright if any listed group is absent.
users_ensure_groups() {
local root="$1" groups="$2" g out=""
local saved_ifs="$IFS"
IFS=,
for g in $groups; do
[[ -z "$g" ]] && continue
if ! grep -q "^$g:" "$root/etc/group" 2>/dev/null; then
portage_chroot "$root" groupadd -r "$g" || log_warn "could not create group $g"
fi
if grep -q "^$g:" "$root/etc/group" 2>/dev/null; then
out="${out:+$out,}$g"
else
log_warn "group $g not available; skipping"
fi
done
IFS="$saved_ifs"
printf '%s' "$out"
}
users_create() {
local root="$1" username fullname groups shell userhash roothash
username="$(config_get USERNAME)"
fullname="$(config_get USER_FULLNAME)"
shell="$(config_get ROOT_SHELL)"
[[ -n "$username" ]] || { log_error "no username configured"; return 1; }
groups="$(users_ensure_groups "$root" "$(config_get USER_GROUPS)")"
local -a uargs=(-m -U -s "$shell" -c "$fullname")
[[ -n "$groups" ]] && uargs+=(-G "$groups")
uargs+=("$username")
portage_chroot "$root" useradd "${uargs[@]}" || {
log_error "useradd failed"; return 1; }
userhash="$(users_hash "$USER_PASSWORD")"
if [[ -n "$userhash" ]]; then
portage_chroot_stdin "$root" "$username:$userhash" chpasswd -e || {
log_error "could not set password for $username"; return 1; }
log_info "password set for $username"
else
log_warn "no password set for $username (account locked)"
fi
if [[ -n "$ROOT_PASSWORD" ]]; then
roothash="$(users_hash "$ROOT_PASSWORD")"
portage_chroot_stdin "$root" "root:$roothash" chpasswd -e || {
log_warn "could not set root password"; }
log_info "root password set"
else
portage_chroot "$root" passwd -l root || true
log_info "root account locked (no root password supplied)"
fi
USER_PASSWORD="" ROOT_PASSWORD=""
}
# users_configure_sudo ROOT - wheel group may sudo, with a password
users_configure_sudo() {
local root="$1"
local dir="$root/etc/sudoers.d"
mkdir -p "$dir"
{
printf '# Members of the wheel group may run commands as root.\n'
printf '%%wheel ALL=(ALL:ALL) ALL\n'
} >"$dir/10-wheel"
chmod 0440 "$dir/10-wheel"
if [[ -x "$root/usr/sbin/visudo" || -x "$root/sbin/visudo" ]]; then
portage_chroot "$root" visudo -cf /etc/sudoers.d/10-wheel || {
log_error "invalid sudoers file"; return 1; }
fi
log_info "sudo configured for wheel"
}
# users_verify ROOT
users_verify() {
local root="$1" username
username="$(config_get USERNAME)"
grep -q "^$username:" "$root/etc/passwd" || {
log_error "user $username missing from target"; return 1; }
[[ -d "$root/home/$username" ]] || log_warn "home directory for $username not found"
return 0
}

103
installer/lib/validation.sh Normal file
View file

@ -0,0 +1,103 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Configuration validation.
#
# Pure(ish) decision logic, separated from the TUI so it can be unit tested and
# reused for unattended installs. validate_config prints one problem per line
# and returns the number of problems found.
validate_hostname() {
local h="$1"
[[ ${#h} -ge 1 && ${#h} -le 63 ]] || { printf 'hostname must be 1-63 characters\n'; return 1; }
[[ "$h" =~ ^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?$ ]] || {
printf 'hostname may only contain letters, digits and internal hyphens\n'; return 1; }
return 0
}
validate_username() {
local u="$1"
[[ -n "$u" ]] || { printf 'username is required\n'; return 1; }
[[ "$u" != "root" ]] || { printf 'refusing to create an account named root\n'; return 1; }
[[ ${#u} -le 32 ]] || { printf 'username must be at most 32 characters\n'; return 1; }
[[ "$u" =~ ^[a-z_][a-z0-9_-]*$ ]] || {
printf 'username must start with a lowercase letter and contain only [a-z0-9_-]\n'; return 1; }
return 0
}
validate_locale() {
local l="$1"
[[ -n "$l" ]] || { printf 'locale is required\n'; return 1; }
local base="${l%%.*}"
if [[ -r /usr/share/i18n/locales/$base ]] || \
[[ -d /usr/lib/locale && -e /usr/lib/locale/locale-archive ]]; then
return 0
fi
[[ "$l" =~ ^[A-Za-z_]+\.?[A-Za-z0-9-]*$ ]] && return 0
printf 'locale looks malformed: %s\n' "$l"
return 1
}
validate_timezone() {
local tz="$1"
[[ -n "$tz" ]] || { printf 'timezone is required\n'; return 1; }
if [[ -d /usr/share/zoneinfo ]]; then
[[ -e "/usr/share/zoneinfo/$tz" && ! -d "/usr/share/zoneinfo/$tz" ]] && return 0
printf 'unknown timezone: %s\n' "$tz"
return 1
fi
return 0
}
validate_keymap() {
local km="$1"
[[ -n "$km" ]] || { printf 'keymap is required\n'; return 1; }
return 0
}
validate_target_disk() {
local disk="$1"
[[ -n "$disk" ]] || { printf 'no target disk selected\n'; return 1; }
[[ -b "$disk" ]] || { printf 'target is not a block device: %s\n' "$disk"; return 1; }
local reason
reason="$(disk_protected_reason "$disk")"
if [[ -n "$reason" ]]; then
printf 'refusing target %s: %s\n' "$disk" "$reason"
return 1
fi
return 0
}
# validate_config [KEYS...] - print problems; return problem count
validate_config() {
local -a keys=("$@")
local problems=0 msg
((${#keys[@]})) || keys=(HOSTNAME USERNAME LOCALE TIMEZONE KEYMAP TARGET_DISK)
local key
for key in "${keys[@]}"; do
case "$key" in
HOSTNAME) validate_hostname "$(config_get HOSTNAME)" && true || { problems=$((problems+1)); } ;;
USERNAME) validate_username "$(config_get USERNAME)" && true || { problems=$((problems+1)); } ;;
LOCALE) validate_locale "$(config_get LOCALE)" && true || { problems=$((problems+1)); } ;;
TIMEZONE) validate_timezone "$(config_get TIMEZONE)" && true || { problems=$((problems+1)); } ;;
KEYMAP) validate_keymap "$(config_get KEYMAP)" && true || { problems=$((problems+1)); } ;;
TARGET_DISK) validate_target_disk "$(config_get TARGET_DISK)" && true || { problems=$((problems+1)); } ;;
esac
done
return "$problems"
}
# validate_password_strength PASSWORD - print a short assessment
validate_password_strength() {
local pw="$1" score=0
((${#pw} >= 8)) && score=$((score+1))
((${#pw} >= 12)) && score=$((score+1))
[[ "$pw" =~ [A-Z] ]] && score=$((score+1))
[[ "$pw" =~ [a-z] ]] && score=$((score+1))
[[ "$pw" =~ [0-9] ]] && score=$((score+1))
[[ "$pw" =~ [^A-Za-z0-9] ]] && score=$((score+1))
if ((score <= 2)); then printf 'weak'
elif ((score <= 4)); then printf 'fair'
else printf 'strong'; fi
}

81
installer/tests/lib.sh Normal file
View file

@ -0,0 +1,81 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Minimal test harness. No external test framework is required (the live image
# has none, and the backend must be testable on any machine).
TESTS_RUN=0
TESTS_FAILED=0
TEST_NAME="unknown"
phoebus_test_setup() {
# shellcheck source=/dev/null
PHOEBUS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
export PHOEBUS_ROOT
STATE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/phoebus-test.XXXXXX")"
export STATE_DIR
PHOEBUS_LOG_FILE="$STATE_DIR/test.log"
export PHOEBUS_LOG_FILE
: >"$PHOEBUS_LOG_FILE"
PHOEBUS_LOG_ECHO=no
export PHOEBUS_LOG_ECHO
local lib
for lib in state logging confirm hardware disks validation plan pkgpolicy \
portage partitions filesystem encryption btrfs network kernel \
boot users desktop opencode ai install; do
# shellcheck source=/dev/null
source "$PHOEBUS_ROOT/lib/$lib.sh"
done
config_load_defaults "$PHOEBUS_ROOT/config/defaults.conf"
}
_assert() {
local ok="$1" message="$2"
TESTS_RUN=$((TESTS_RUN + 1))
if [[ "$ok" == "1" ]]; then
printf ' ok %s\n' "$message"
else
TESTS_FAILED=$((TESTS_FAILED + 1))
printf ' FAIL %s\n' "$message"
fi
}
assert_eq() {
local expected="$1" actual="$2" message="${3:-equal}"
if [[ "$expected" == "$actual" ]]; then _assert 1 "$message"; else
_assert 0 "$message (expected '$expected', got '$actual')"; fi
}
assert_neq() {
local a="$1" b="$2" message="${3:-not equal}"
if [[ "$a" != "$b" ]]; then _assert 1 "$message"; else
_assert 0 "$message (both '$a')"; fi
}
assert_contains() {
local haystack="$1" needle="$2" message="${3:-contains}"
if [[ "$haystack" == *"$needle"* ]]; then _assert 1 "$message"; else
_assert 0 "$message (missing '$needle')"; fi
}
assert_not_contains() {
local haystack="$1" needle="$2" message="${3:-not contains}"
if [[ "$haystack" != *"$needle"* ]]; then _assert 1 "$message"; else
_assert 0 "$message (unexpectedly found '$needle')"; fi
}
assert_success() {
local message="$1"; shift
if "$@" >/dev/null 2>&1; then _assert 1 "$message"; else _assert 0 "$message"; fi
}
assert_failure() {
local message="$1"; shift
if "$@" >/dev/null 2>&1; then _assert 0 "$message"; else _assert 1 "$message"; fi
}
phoebus_test_report() {
printf '\n%s: %d run, %d failed\n' "$TEST_NAME" "$TESTS_RUN" "$TESTS_FAILED"
[[ "$TESTS_FAILED" -eq 0 ]]
}

33
installer/tests/run_tests.sh Executable file
View file

@ -0,0 +1,33 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Run all installer tests. No root privileges and no block devices required.
set -uo pipefail
TEST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHOEBUS_ROOT="$(cd "$TEST_DIR/.." && pwd)"
export PHOEBUS_ROOT
total_failed=0
total_run=0
failed_tests=()
for test in "$TEST_DIR"/test_*.sh; do
[[ -f "$test" ]] || continue
printf '\n== %s ==\n' "$(basename "$test")"
if bash "$test"; then
:
else
failed_tests+=("$(basename "$test")")
total_failed=$((total_failed + 1))
fi
done
printf '\n========================================\n'
if ((${#failed_tests[@]})); then
printf 'FAILED test files (%d):\n' "${#failed_tests[@]}"
printf ' %s\n' "${failed_tests[@]}"
exit 1
fi
printf 'All tests passed.\n'
exit 0

View file

@ -0,0 +1,36 @@
#!/usr/bin/env bash
# shellcheck shell=bash
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
TEST_NAME="test_ai"
phoebus_test_setup
parsed="$(ai_parse_json_kv '{"hostname":"foo","encryption":"luks2","count":3}')"
assert_contains "$parsed" "hostname=foo" "flat JSON parser: string"
assert_contains "$parsed" "encryption=luks2" "flat JSON parser: string 2"
assert_contains "$parsed" "count=3" "flat JSON parser: number"
assert_success "HOSTNAME permitted" ai_key_allowed HOSTNAME
assert_failure "EVIL key refused" ai_key_allowed EVIL
assert_failure "LUKS_PASSPHRASE refused" ai_key_allowed LUKS_PASSPHRASE
assert_eq "" "$(ai_validate_field ENCRYPTION luks2)" "valid encryption accepted"
assert_neq "" "$(ai_validate_field ENCRYPTION bogus)" "invalid encryption rejected"
assert_neq "" "$(ai_validate_field HOSTNAME 'bad host')" "invalid hostname rejected"
assert_neq "" "$(ai_validate_field TARGET_DISK /dev/nonexistent)" "invalid disk rejected"
# applying a proposal with an out-of-whitelist key still validates known keys
before="$(config_get HOSTNAME)"
ai_apply_proposal '{"hostname":"good-host","evil":"rm -rf /"}' >/dev/null 2>&1 || true
assert_eq "good-host" "$(config_get HOSTNAME)" "valid proposal field applied"
assert_eq "" "$(config_get EVIL)" "unknown proposal field ignored"
# offline translator
offline="$(ai_propose_offline "encrypt everything with btrfs and a desktop")"
assert_contains "$offline" '"encryption":"luks2"' "offline proposal sets luks2"
assert_contains "$offline" '"filesystem":"btrfs"' "offline proposal sets btrfs"
assert_contains "$offline" '"desktop_profile":"dwl"' "offline proposal sets desktop"
# offline assistance never needs a model
assert_contains "$(ai_offline_response "encryption")" "LUKS2" "offline encryption help"
phoebus_test_report

View file

@ -0,0 +1,57 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Regression test: subvolumes must be created before any subvol=@ mount is
# attempted. The first VM install failed because the layout was mounted before
# the subvolumes existed (mount exit 32).
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
TEST_NAME="test_btrfs_order"
phoebus_test_setup
source "$PHOEBUS_ROOT/lib/confirm.sh"
# Authorize destructive pseudo-commands for the fake environment.
PHOEBUS_DESTRUCTIVE_AUTHORIZED="yes"
config_set DRY_RUN "no"
fakebin="$STATE_DIR/bin"
mkdir -p "$fakebin"
export FAKE_LOG="$STATE_DIR/calls.log"
: >"$FAKE_LOG"
cat >"$fakebin/mount" <<'EOF'
#!/usr/bin/env bash
printf 'mount %s\n' "$*" >>"$FAKE_LOG"
exit 0
EOF
cat >"$fakebin/umount" <<'EOF'
#!/usr/bin/env bash
printf 'umount %s\n' "$*" >>"$FAKE_LOG"
exit 0
EOF
cat >"$fakebin/btrfs" <<'EOF'
#!/usr/bin/env bash
printf 'btrfs %s\n' "$*" >>"$FAKE_LOG"
exit 0
EOF
chmod +x "$fakebin/mount" "$fakebin/umount" "$fakebin/btrfs"
PATH="$fakebin:$PATH"
config_set BTRFS_SUBVOLS "@ @home @var @snapshots @swap"
btrfs_create_layout /dev/fake "$STATE_DIR/root" >/dev/null 2>&1
rc=$?
assert_eq "0" "$rc" "btrfs_create_layout succeeds with fake tools"
# The first subvolume creation must precede the first subvol=@ mount.
create_line="$(grep -n 'btrfs subvolume create' "$FAKE_LOG" | head -n1 | cut -d: -f1)"
mount_line="$(grep -n 'subvol=@ ' "$FAKE_LOG" | head -n1 | cut -d: -f1)"
assert_success "subvolume create recorded" test -n "$create_line"
assert_success "subvol=@ mount recorded" test -n "$mount_line"
if [[ -n "$create_line" && -n "$mount_line" ]]; then
assert_success "subvolumes created before mounting @" test "$create_line" -lt "$mount_line"
fi
# All five subvolumes are created.
assert_eq "5" "$(grep -c 'btrfs subvolume create' "$FAKE_LOG")" "all subvolumes created"
phoebus_test_report

View file

@ -0,0 +1,32 @@
#!/usr/bin/env bash
# shellcheck shell=bash
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
TEST_NAME="test_install_dryrun"
phoebus_test_setup
source "$PHOEBUS_ROOT/lib/confirm.sh"
source "$PHOEBUS_ROOT/lib/install.sh"
# A dry-run must never write to the configured install root.
config_set DRY_RUN "yes"
config_set TARGET_DISK "/dev/definitely-not-a-real-disk"
config_set INSTALL_ROOT "$STATE_DIR/host-root-should-stay-empty"
config_set USERNAME "tester"
install_effective_root >/dev/null
INSTALL_TARGET_ROOT="$(install_effective_root)"
assert_success "dry-run storage stage" install_stage_storage
assert_success "sandbox root created" test -d "$INSTALL_TARGET_ROOT"
assert_failure "host install root untouched" test -e "$(config_get INSTALL_ROOT)"
assert_success "dry-run base stage" install_stage_base
assert_success "dry-run portage stage" install_stage_portage
# scripts created by later stages stay inside the sandbox
assert_success "dry-run kernel profile writes to sandbox" install_stage_kernel
assert_success "kernel fragment in sandbox" test -e "$INSTALL_TARGET_ROOT/etc/kernel/config.d/00-phoebus-profile.config"
# preflight refuses an incomplete configuration (no real target disk)
config_set DRY_RUN "no"
assert_failure "preflight rejects incomplete config" install_preflight
phoebus_test_report

View file

@ -0,0 +1,25 @@
#!/usr/bin/env bash
# shellcheck shell=bash
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
TEST_NAME="test_opencode"
phoebus_test_setup
url="$(opencode_manifest_get x86_64 url)"
sha="$(opencode_manifest_get x86_64 sha256)"
assert_contains "$url" "opencode-linux-x64.tar.gz" "manifest has x86_64 url"
assert_eq "64" "${#sha}" "manifest sha256 is 64 hex chars"
assert_eq "v1.18.31" "$(opencode_version_manifest)" "manifest pins a version"
# checksum verification
f="$STATE_DIR/artifact"
printf 'hello phoebus\n' >"$f"
good="$(sha256sum "$f" | awk '{print $1}')"
assert_success "correct checksum accepted" opencode_checksum_ok "$f" "$good"
assert_failure "wrong checksum rejected" opencode_checksum_ok "$f" "deadbeef"
assert_failure "placeholder checksum rejected" opencode_checksum_ok "$f" "0000000000000000000000000000000000000000000000000000000000000000"
assert_failure "empty checksum rejected" opencode_checksum_ok "$f" ""
# unknown arch has no usable entry
assert_failure "unknown arch refused" opencode_manifest_get sparc url
phoebus_test_report

View file

@ -0,0 +1,36 @@
#!/usr/bin/env bash
# shellcheck shell=bash
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
TEST_NAME="test_pkgpolicy"
phoebus_test_setup
# Default is balanced and a binary source is configured.
config_set PACKAGE_POLICY "balanced"
config_set FEATURES_BINPKG "yes"
config_set BINHOST_URI "https://example.invalid/binpkgs"
assert_eq "45" "$(pkgpolicy_compile_seconds app-editors/vim)" "known compile time (vim)"
assert_eq "300" "$(pkgpolicy_compile_seconds dev-libs/unknown)" "unknown defaults to 300s"
assert_eq "source" "$(pkgpolicy_decide app-editors/vim)" "cheap package compiles"
assert_eq "binary" "$(pkgpolicy_decide www-client/firefox)" "huge package uses binary"
assert_eq "source" "$(pkgpolicy_decide sys-kernel/gentoo-kernel)" "kernel always compiles"
# policy overrides
config_set PACKAGE_POLICY "source_first"
assert_eq "source" "$(pkgpolicy_decide www-client/firefox)" "source_first compiles everything"
config_set PACKAGE_POLICY "binary_first"
assert_eq "binary" "$(pkgpolicy_decide app-editors/vim)" "binary_first prefers binaries"
# history override
config_set PACKAGE_POLICY "balanced"
printf 'app-editors/vim\t7\t25\n' >"${STATE_DIR}/compile-times.tsv"
assert_eq "7" "$(pkgpolicy_compile_seconds app-editors/vim)" "history overrides estimate"
# no binary host -> source even in binary_first
config_set BINHOST_URI ""
config_set PACKAGE_POLICY "binary_first"
assert_eq "source" "$(pkgpolicy_decide www-client/firefox)" "no binhost means compile"
phoebus_test_report

View file

@ -0,0 +1,34 @@
#!/usr/bin/env bash
# shellcheck shell=bash
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
TEST_NAME="test_plan"
phoebus_test_setup
config_set HOSTNAME "phoebus-test"
config_set USERNAME "tester"
config_set DESKTOP_PROFILE "dwl"
config_set PACKAGE_POLICY "balanced"
plan_generate
plan="$(plan_render)"
assert_contains "$plan" "Installation plan" "plan has header"
assert_contains "$plan" "phoebus-test" "plan includes hostname"
assert_contains "$plan" "tester" "plan includes username"
assert_contains "$plan" "dwl" "plan includes desktop profile"
assert_contains "$plan" "systemd" "plan includes init system"
assert_contains "$plan" "@snapshots" "plan includes snapshot subvolume"
assert_eq "storage_prepare" "${PLAN_STEPS[0]}" "first step is storage_prepare"
assert_eq "finalize" "${PLAN_STEPS[${#PLAN_STEPS[@]}-1]}" "last step is finalize"
# subvolume list is configurable
config_set BTRFS_SUBVOLS "@ @home @var @snapshots @swap @log"
plan_generate
assert_contains "$(plan_render)" "@log" "plan reflects configured subvolumes"
# swap sizing is bounded
swap="$(plan_swap_mib)"
assert_success "swap size is numeric" test "$swap" -ge 1024
phoebus_test_report

View file

@ -0,0 +1,104 @@
#!/usr/bin/env bash
# shellcheck shell=bash
#
# Regression tests for bugs found during the first real VM installation.
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
TEST_NAME="test_regressions"
phoebus_test_setup
# --- kernel cmdline: encrypted root must use rd.luks.name=<uuid>=<name> -----
config_set ENCRYPTION "luks2"
config_set LUKS_NAME "cryptroot"
FS_ROOT_PART="/dev/fake"
blkid() { printf '%s\n' "00000000-1111-2222-3333-444444444444"; }
root="$STATE_DIR/target"
mkdir -p "$root"
kernel_write_cmdline "$root"
cmdline="$(cat "$root/etc/kernel/cmdline")"
assert_contains "$cmdline" "rd.luks.name=00000000-1111-2222-3333-444444444444=cryptroot" \
"cmdline names the LUKS mapper"
assert_contains "$cmdline" "root=/dev/mapper/cryptroot" "cmdline root is the mapper"
assert_not_contains "$cmdline" "rd.luks.uuid=" "cmdline does not use un-named rd.luks.uuid"
# --- install.conf must declare every generator (it replaces the default) ----
boot_write_install_conf "$root"
iconf="$(cat "$root/etc/kernel/install.conf")"
assert_contains "$iconf" "layout=bls" "install.conf uses BLS layout"
assert_contains "$iconf" "initrd_generator=dracut" "install.conf sets initrd generator"
assert_contains "$iconf" "uki_generator=none" "install.conf disables UKI for BLS"
# dracut must be forced to include crypt/btrfs for the encrypted root
boot_write_dracut_conf "$root"
dconf="$(cat "$root/etc/dracut.conf.d/10-phoebus.conf")"
assert_contains "$dconf" "add_dracutmodules" "dracut config adds modules"
assert_contains "$dconf" "crypt" "dracut includes crypt"
assert_contains "$dconf" "btrfs" "dracut includes btrfs"
# --- fstab must be generated after the stage3 extraction --------------------
plan_generate
sig="" fgi="" pci=""
for i in "${!PLAN_STEPS[@]}"; do
case "${PLAN_STEPS[$i]}" in
stage_install) sig="$i" ;;
fstab_generate) fgi="$i" ;;
portage_configure) pci="$i" ;;
esac
done
assert_success "fstab_generate is a plan step" test -n "$fgi"
assert_success "stage_install precedes fstab_generate" test "$sig" -lt "$fgi"
assert_success "fstab_generate precedes portage_configure" test "$fgi" -lt "$pci"
__fn_contains() { declare -f "$1" | grep -q "$2"; }
assert_failure "storage stage does not generate fstab" \
__fn_contains install_stage_storage filesystem_generate_fstab
assert_success "fstab stage generates fstab" \
__fn_contains install_stage_fstab filesystem_generate_fstab
assert_success "fstab stage creates /var/tmp" \
__fn_contains install_stage_fstab "/var/tmp"
# --- chroot commands set TMPDIR (systemd kernel-install requires it) --------
assert_success "portage_chroot sets TMPDIR" \
__fn_contains portage_chroot "TMPDIR=/tmp"
assert_success "portage_chroot_stdin sets TMPDIR" \
__fn_contains portage_chroot_stdin "TMPDIR=/tmp"
# --- initial cmdline includes the configured console ------------------------
config_set KERNEL_CONSOLE "console=tty0 console=ttyS0,115200"
kernel_write_cmdline "$root"
assert_contains "$(cat "$root/etc/kernel/cmdline")" "console=ttyS0,115200" \
"cmdline includes configured console"
config_set KERNEL_CONSOLE "console=tty0"
# --- base packages must include the storage userspace needed by dracut ------
basepkgs="$(portage_base_packages)"
assert_contains "$basepkgs" "sys-fs/cryptsetup" "base packages include cryptsetup"
assert_contains "$basepkgs" "sys-fs/btrfs-progs" "base packages include btrfs-progs"
# --- systemd must be built with cryptsetup for the initramfs ---------------
pkgroot="$STATE_DIR/pkgroot"
mkdir -p "$pkgroot/etc/portage"
config_set DESKTOP_PROFILE "dwl"
portage_write_package_files "$pkgroot"
pupkg="$(cat "$pkgroot/etc/portage/package.use/phoebus")"
assert_contains "$pupkg" "sys-apps/systemd boot policykit cryptsetup" \
"systemd built with boot/policykit/cryptsetup"
assert_contains "$pupkg" "sys-kernel/installkernel" "installkernel policy present"
assert_contains "$pupkg" "x11-libs/cairo X" "desktop enables cairo X for GTK3"
config_set DESKTOP_PROFILE "none"
# --- fstab must mount @swap so the swapfile can be activated ----------------
FS_EFI_PART="/dev/fake-efi"
FS_ROOT_SOURCE="/dev/fake-root"
mkdir -p "$root/etc"
filesystem_generate_fstab "$root"
fstab="$(cat "$root/etc/fstab")"
assert_contains "$fstab" "subvol=@swap" "fstab mounts @swap subvolume"
assert_contains "$fstab" "/swap/swapfile" "fstab enables the swapfile"
# --- secrets never reach the log -------------------------------------------
secret_register "topsecretvalue123"
run_cmd "secret test" /bin/true "topsecretvalue123" >/dev/null 2>&1
logtext="$(cat "$PHOEBUS_LOG_FILE")"
assert_not_contains "$logtext" "topsecretvalue123" "secret is scrubbed from the log"
phoebus_test_report

View file

@ -0,0 +1,31 @@
#!/usr/bin/env bash
# shellcheck shell=bash
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
TEST_NAME="test_safety"
phoebus_test_setup
# confirm.sh and install.sh are not loaded by lib.sh; load them explicitly.
source "$PHOEBUS_ROOT/lib/confirm.sh"
source "$PHOEBUS_ROOT/lib/install.sh"
# destructive commands are blocked until authorized
destructive_revoke
assert_failure "run_destructive blocked when unauthorized" run_destructive "test op" true
# after authorization, dry-run still prevents execution
config_set DRY_RUN "yes"
destructive_grant
assert_success "run_destructive allowed after grant (dry-run)" run_destructive "test op" /bin/true
destructive_revoke
# effective root is a sandbox in dry-run, never the configured target
config_set INSTALL_ROOT "/mnt/do-not-touch"
config_set DRY_RUN "yes"
root="$(install_effective_root)"
assert_neq "/mnt/do-not-touch" "$root" "dry-run uses a sandbox root"
assert_contains "$root" "dry-run-root" "sandbox root name is explicit"
# in a real run the configured root is used
config_set DRY_RUN "no"
assert_eq "/mnt/do-not-touch" "$(install_effective_root)" "real root used when not dry-run"
phoebus_test_report

Some files were not shown because too many files have changed in this diff Show more