feat(sys): review third-party package sources before AI installs
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-10-03 12:08:47 -07:00
parent a224bb72e8
commit c1aee13d3e
11 changed files with 570 additions and 21 deletions

View file

@ -5,6 +5,21 @@ this file is the curated, human-readable summary.
## Unreleased — Fast defaults with user-controlled source builds
- **Third-party package source review (2026-10-03).** AI installation now
requires `inspect_candidate` evidence for the exact third-party backend and
package ID before recommending it. The inspection reports source,
verification evidence, reported version, isolation and explicit freshness
limits. Flatpak installation refuses a remote without HTTPS or GPG
verification, binds the selected `flathub` URL and version to the review,
and rechecks them before execution. The install plan displays these
findings and never treats catalog metadata or a checksum as proof that a
publisher is uncompromised. General assistant plans cannot bypass this
workflow with direct package install actions. Rust format, strict clippy,
workspace tests, `make check`, and dynamic/static release builds pass. The
running VM's read-only inspection of `org.mozilla.firefox` returned a
Flathub HTTPS source with GPG enabled and `review_required` status; no
package was installed.
- **Bounded Assistant searches (2026-10-03).** A general search reply with more
than six typed read-only checks now runs the first six and tells the model
which checks were skipped, so it can continue on the next turn. The full

View file

@ -3,6 +3,24 @@
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.
- **Third-party source health review (2026-10-03):** AI installation now must
inspect the exact candidate for third-party lanes before making a proposal.
The read-only report separates backend evidence from publisher trust and
unknown release age. Flatpak plans require the app to resolve from the
configured `flathub` remote with HTTPS and GPG enabled; the broker checks
again just before execution and aborts on version, remote, or verification
drift. Direct installs in general AI plans are rejected in favor of the
dedicated `sys install` workflow. Rust format, strict clippy, workspace
tests, `make check`, and dynamic/static release builds pass. The running VM
showed a read-only `org.mozilla.firefox` inspection with Flathub HTTPS,
GPG enabled, version `157.0`, and `review_required` status
(`/var/tmp/phoebus-vm/source-health-inspect2.png`). The updated static `sys`
was installed at `~/.local/bin/sys` (SHA-256
`3cbbe7aaf25bf4659abc1d5dc3e2772e738ffffc6a324e4a666ef0c5752dd941`)
and the Assistant was restarted connected. No package was installed. An
actual reviewed Flatpak install remains unverified in the VM; a fresh ISO
remains gated by `make doctor` reporting 8 GiB free versus 20 GiB required.
- **General Assistant search cap (2026-10-03):** The exact VM question `can you
find a package for balena etcher for me` previously failed with `too many
investigation requests in one turn (max 6)`. The general loop now validates

View file

@ -48,6 +48,28 @@ disposable VM; `serial-driver.py recovery` now automates the same check.
## Matrix
Third-party source health review (2026-10-03): `inspect_candidate` now returns
structured `health` evidence. AI install proposals from Portage vendor, Nix,
Flatpak, Snap, AppImage and custom ebuild lanes require that exact inspection;
the deterministic resolver still confirms candidates. Flatpak plans check the
selected `flathub` remote's HTTPS URL and GPG setting, show the source health
limits, and revalidate the remote, version and verification status before
execution. A disabled GPG setting aborts both planning and execution. General
assistant plans refuse direct package install actions that would bypass the
dedicated workflow. Rust format, strict clippy, workspace tests, `make check`,
and dynamic/static release builds pass. The running VM's read-only inspection
of `org.mozilla.firefox` reported `flathub` at
`https://dl.flathub.org/repo/`, version `157.0`, and `review_required`
(`/var/tmp/phoebus-vm/source-health-inspect2.png`). The static binary was
installed in the VM user's `~/.local/bin/sys` (SHA-256
`3cbbe7aaf25bf4659abc1d5dc3e2772e738ffffc6a324e4a666ef0c5752dd941`)
and the Assistant was restarted connected. No package was installed; an
actual Flatpak install under this review has not yet been VM verified. A new
ISO remains gated by `make doctor` finding 8 GiB free versus 20 GiB required.
Upstream compromise and release age cannot be established from local package
metadata alone.
General Assistant search bounds (2026-10-03): an oversized model investigation
is validated in full and only its first six read-only requests are executed;
the model receives the evidence and a clear note about the skipped checks.

View file

@ -120,6 +120,23 @@ identify -> evidence -> AI investigation -> proposed selection
specified backend, ensuring the model evaluates and explains candidates for
that source while preserving the full investigation, explanation, and
approval cycle.
- **Third-party source review** requires the model to inspect the exact
candidate before recommending a Portage vendor, Nix, Flatpak, Snap,
AppImage, or custom ebuild source. `inspect_candidate` returns a structured
health report: source, integrity evidence, reported version and freshness
limits, isolation, and a `hold` or `review_required` status. The model must
explain uncertainty rather than declare a package safe or current. For
Flatpak, `sys` checks that the resolved app comes from its configured
`flathub` install remote, that the remote uses HTTPS, and that GPG
verification is enabled. It refuses an unverified remote and repeats the
check before execution; a changed version, remote, or verification state
invalidates approval. The plan shows these source health findings. A hash or
catalog entry alone does not authenticate an AppImage publisher, and this
review cannot prove that an upstream release is uncompromised.
- **General assistant plans** cannot use direct package install actions to
skip this source review. Package installs use the dedicated `sys install`
workflow. Typed administrator actions remain available through the audited
`--legacy` entry point.
- **Explicit backend flags with `--legacy`** bypass the model entirely, are
mutually exclusive, and never fall back to another lane. If the lane cannot
satisfy the request, the reason and alternatives are shown and nothing is

View file

@ -106,10 +106,17 @@ installation status or availability.
Rules: prefer inspection before mutation. Where an action takes a `kind`, it is \
exactly one of base-system, desktop-app, developer-tool, cli-tool, unclassified; a \
GUI application is kind desktop-app plus a separate `gui` boolean. \
For third-party software, request inspect_candidate for the exact backend and id \
before recommending an install. Describe the source verification, reported \
version, isolation and remaining uncertainty; do not claim a package is safe or \
current from a catalog listing, checksum or model knowledge alone. Use the \
dedicated sys install workflow for package installation; direct install_package, \
flatpak_install, snap_install, nix_install, appimage_import, appimage_acquire and custom_ebuild_install actions \
are not accepted in a general assistant plan. \
Do not choose a software lane by \
category alone: use choose_package to compare the available lanes against the \
machine (architecture, memory, storage, GPU, Wayland) and the user's \
preferences, or install_package for an explicit Portage request. Base system \
preferences. Base system \
components (kernel, drivers, systemd, the host graphics and audio stack, boot \
tooling) stay under Portage. A custom ebuild is untrusted, executable content: \
stage it with custom_ebuild_prepare so a human reviews the artifact and its \

View file

@ -212,6 +212,11 @@ Portage owns the kernel, drivers, systemd, the host graphics/audio stack and boo
Prefer an existing installation and the user's saved preference; never migrate or duplicate \
silently. If the user asked for a specific backend, investigate only that lane and honour it. \
AppImage catalog leads are discovery links and cannot be proposed as verified install candidates. \
Before proposing a candidate from a source outside Gentoo's source tree or signed binhost, \
request inspect_candidate for that exact backend and id. Read its health report: check \
source identity, integrity, version/freshness, isolation and the stated limits. A reported \
version is not proof of the latest upstream release; a hash is not proof of publisher identity. \
If the inspection is unavailable or on hold, do not claim the package is healthy. \
Request at most six read-only actions per turn. When you have enough evidence, propose.";
/// Build the first request of the investigation.
@ -376,6 +381,7 @@ pub fn investigate_install(
let mut turns = 0usize;
let mut malformed_replies = 0usize;
let mut discovered_candidates = false;
let mut inspected = std::collections::BTreeSet::new();
while turns < limits.max_turns {
turns += 1;
@ -483,6 +489,21 @@ pub fn investigate_install(
continue;
}
let evidence = session.investigate(&requests);
for (request, item) in requests.iter().zip(&evidence) {
if let SystemAction::InspectCandidate { backend, id } = request {
if let Ok(detail) = serde_json::from_str::<serde_json::Value>(&item.output)
{
if detail.get("backend") == Some(&serde_json::json!(backend))
&& detail.get("id").and_then(|v| v.as_str()) == Some(id.as_str())
&& detail.get("available").and_then(|v| v.as_bool()) == Some(true)
&& detail.pointer("/health/status").and_then(|v| v.as_str())
== Some("review_required")
{
inspected.insert((*backend, id.clone()));
}
}
}
}
discovered_candidates |= requests
.iter()
.any(|request| matches!(request, SystemAction::DiscoverCandidates { .. }));
@ -507,6 +528,26 @@ pub fn investigate_install(
}
InstallStep::Propose { proposal, .. } => {
proposal.validate_structural().map_err(AiError::Rejected)?;
if proposal.backend.requires_source_review()
&& !inspected.contains(&(proposal.backend, proposal.candidate.clone()))
{
chat.messages.push(ChatMessage {
role: "assistant".into(),
content: content.clone(),
});
chat.messages.push(ChatMessage {
role: "user".into(),
content: format!(
"Before recommending {} from {}, request inspect_candidate for \
that exact backend and id. Its read-only health report must resolve \
the candidate and state what remains unknown. Do not call a package \
healthy on the basis of a catalog listing or a hash alone.",
proposal.candidate,
proposal.backend.as_str()
),
});
continue;
}
match validate(&proposal) {
Ok(()) => return Ok(proposal),
Err(findings) => {
@ -568,7 +609,11 @@ mod tests {
.iter()
.map(|r| Evidence {
request: r.describe(),
output: "[{\"backend\":\"flatpak\",\"id\":\"org.mozilla.firefox\"}]".into(),
output: if matches!(r, SystemAction::InspectCandidate { .. }) {
r#"{"backend":"flatpak","id":"org.mozilla.firefox","available":true,"health":{"status":"review_required"}}"#.into()
} else {
"[{\"backend\":\"flatpak\",\"id\":\"org.mozilla.firefox\"}]".into()
},
})
.collect()
}
@ -581,6 +626,10 @@ mod tests {
r#"{"version":2,"kind":"propose","proposal":{"application":"firefox","backend":"flatpak","candidate":"org.mozilla.firefox","reason":"sandboxed, native Wayland","evidence":["org.mozilla.firefox"]}}"#
}
fn inspection_step() -> &'static str {
r#"{"version":2,"kind":"investigate","requests":[{"action":"inspect_candidate","backend":"flatpak","id":"org.mozilla.firefox"}]}"#
}
#[test]
fn parse_accepts_the_four_step_kinds() {
let ask = parse_step(r#"{"version":2,"kind":"ask","question":"Do you need dev tools?"}"#)
@ -634,6 +683,7 @@ mod tests {
chat_response(
r#"{"version":2,"kind":"investigate","requests":[{"action":"discover_candidates","query":"firefox"}]}"#,
),
chat_response(inspection_step()),
chat_response(ok_proposal()),
]);
let session = Sessions {
@ -653,13 +703,46 @@ mod tests {
)
.unwrap();
assert_eq!(proposal.candidate, "org.mozilla.firefox");
assert_eq!(session.evidence.borrow().len(), 1);
assert_eq!(session.evidence.borrow().len(), 2);
let requests = transport.requests();
assert_eq!(requests.len(), 2);
assert_eq!(requests.len(), 3);
// The second request must carry the evidence back to the model.
assert!(requests[1].contains("org.mozilla.firefox"));
}
#[test]
fn third_party_proposal_requires_a_real_candidate_inspection() {
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response(ok_proposal()),
chat_response(inspection_step()),
chat_response(ok_proposal()),
]);
let session = Sessions {
evidence: std::cell::RefCell::new(Vec::new()),
answer: None,
};
let validations = std::cell::Cell::new(0);
let proposal = investigate_install(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"install firefox",
&transport,
&session,
&|_| {
validations.set(validations.get() + 1);
Ok(())
},
&Limits::default(),
)
.unwrap();
assert_eq!(proposal.candidate, "org.mozilla.firefox");
assert_eq!(validations.get(), 1);
assert!(transport.requests()[1].contains("request inspect_candidate"));
assert_eq!(session.evidence.borrow().len(), 1);
}
#[test]
fn unavailable_requires_candidate_discovery_and_stops_without_a_proposal() {
let unavailable =
@ -708,6 +791,7 @@ mod tests {
#[test]
fn a_rejected_proposal_is_revised_with_findings() {
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response(inspection_step()),
chat_response(ok_proposal()),
chat_response(ok_proposal()),
]);
@ -739,7 +823,7 @@ mod tests {
assert_eq!(proposal.application, "firefox");
assert_eq!(attempts.get(), 2);
let requests = transport.requests();
assert!(requests[1].contains("rejected"));
assert!(requests[2].contains("rejected"));
}
#[test]
@ -788,6 +872,7 @@ mod tests {
chat_response(
r#"{"version":2,"kind":"investigate","requests":[{"action":"check_backend","backend":"appimage"}]}"#,
),
chat_response(inspection_step()),
chat_response(ok_proposal()),
]);
let session = Sessions {
@ -807,7 +892,7 @@ mod tests {
)
.unwrap();
assert_eq!(proposal.candidate, "org.mozilla.firefox");
assert_eq!(session.evidence.borrow().len(), 1);
assert_eq!(session.evidence.borrow().len(), 2);
assert_eq!(session.evidence.borrow()[0].len(), 1);
assert!(transport.requests()[1].contains("None were run"));
}
@ -816,6 +901,7 @@ mod tests {
fn ask_feeds_the_answer_back_and_none_is_explicit() {
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response(r#"{"version":2,"kind":"ask","question":"Do you need dev tools?"}"#),
chat_response(inspection_step()),
chat_response(ok_proposal()),
]);
let session = Sessions {
@ -863,6 +949,7 @@ mod tests {
fn malformed_model_json_gets_one_bounded_retry() {
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response("Here is a plan: {broken"),
chat_response(inspection_step()),
chat_response(ok_proposal()),
]);
let session = Sessions {
@ -883,7 +970,7 @@ mod tests {
.unwrap();
assert_eq!(proposal.candidate, "org.mozilla.firefox");
let requests = transport.requests();
assert_eq!(requests.len(), 2);
assert_eq!(requests.len(), 3);
assert!(requests[1].contains("Your last reply was invalid"));
}
@ -892,6 +979,7 @@ mod tests {
let invalid = r#"{"version":2,"kind":"investigate","requests":[{"query":"etcher"}]}"#;
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response(invalid),
chat_response(inspection_step()),
chat_response(ok_proposal()),
]);
let session = Sessions {
@ -911,7 +999,7 @@ mod tests {
)
.unwrap();
assert_eq!(proposal.candidate, "org.mozilla.firefox");
assert!(session.evidence.borrow().is_empty());
assert_eq!(session.evidence.borrow().len(), 1);
assert!(transport.requests()[1].contains("typed action objects"));
}
@ -952,6 +1040,7 @@ mod tests {
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response(invalid_action),
chat_response(invalid_name),
chat_response(inspection_step()),
chat_response(ok_proposal()),
]);
let session = Sessions {
@ -971,7 +1060,7 @@ mod tests {
)
.unwrap();
assert_eq!(proposal.application, "firefox");
assert_eq!(transport.requests().len(), 3);
assert_eq!(transport.requests().len(), 4);
assert!(transport.requests()[2].contains("canonical name without spaces"));
}

View file

@ -105,6 +105,20 @@ impl Backend {
matches!(self, Backend::Flatpak | Backend::Snap)
}
/// Sources outside Gentoo's ordinary source tree and signed binhost need
/// an explicit inspection before an AI installation recommendation.
pub fn requires_source_review(self) -> bool {
matches!(
self,
Backend::PortageVendor
| Backend::Nix
| Backend::Flatpak
| Backend::Snap
| Backend::AppImage
| Backend::CustomEbuild
)
}
pub fn all() -> &'static [Backend] {
&[
Backend::PortageSource,

View file

@ -587,6 +587,9 @@ pub fn infer_kind(_name: &str) -> PackageKind {
pub struct CandidateDetail {
#[serde(flatten)]
pub candidate: Candidate,
/// A bounded pre-install assessment. It reports evidence and uncertainty;
/// it is not a malware or upstream-compromise certificate.
pub health: CandidateHealth,
/// The transitive merge/dependency set, when the backend can report it.
pub dependencies: Vec<String>,
/// Snap confinement (`strict`/`partial`/`none`), when applicable.
@ -597,6 +600,139 @@ pub struct CandidateDetail {
pub channel: Option<String>,
}
/// What sys can establish before downloading or executing a candidate.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct CandidateHealth {
pub status: &'static str,
pub source: String,
pub integrity: String,
pub freshness: String,
pub isolation: String,
pub limitation: &'static str,
}
pub fn candidate_health(candidate: &Candidate) -> CandidateHealth {
let status = if !candidate.available || !candidate.verified {
"hold"
} else {
"review_required"
};
let integrity = match candidate.backend {
Backend::AppImage => "A managed SHA-256 records the bytes, but a hash alone does not authenticate the publisher".into(),
Backend::CustomEbuild => "The staged ebuild is untrusted executable build code; its digest only detects changes after review".into(),
Backend::Flatpak if candidate.verified => "The selected HTTPS Flatpak remote has GPG verification enabled; the artifact itself is verified during installation".into(),
_ if candidate.verified => "The configured package backend reports this candidate; this inspection has not independently verified the artifact".into(),
_ => "No cryptographic publisher or artifact verification is established".into(),
};
let freshness = match candidate.version.as_deref() {
Some(version) if !version.trim().is_empty() => format!(
"Configured source reports version {version}; upstream release age and security advisories were not independently checked"
),
_ => "The source did not report a version; upstream release age and security advisories are unknown".into(),
};
let isolation = match candidate.sandbox {
SandboxLevel::Strong => {
"Backend reports application isolation; review requested permissions".into()
}
SandboxLevel::Partial => "Only partial application isolation is available".into(),
SandboxLevel::None => "No application sandbox is provided by this lane".into(),
};
CandidateHealth {
status,
source: if candidate.available {
format!("Candidate resolved from {}", candidate.provenance)
} else {
format!("Candidate was not resolved from {}", candidate.provenance)
},
integrity,
freshness,
isolation,
limitation: "Metadata, hashes, and signatures cannot prove that an upstream publisher or release has not been compromised",
}
}
fn inspect_flatpak_remote(exec: &Exec, root: &Path, candidate: &mut Candidate) {
let search = exec.runner.execute(&rooted(
root,
"sys",
"inspect Flatpak source",
"flatpak",
&[
"search",
"--system",
"--columns=application,version,remotes",
"--",
&candidate.id,
],
));
let Some((version, remote)) = search.ok().filter(|o| o.success).and_then(|o| {
o.stdout_lossy().lines().find_map(|line| {
let mut columns = line.split('\t');
if columns.next()? != candidate.id {
return None;
}
Some((
columns.next()?.trim().to_string(),
columns.next()?.trim().to_string(),
))
})
}) else {
candidate.verified = false;
candidate
.notes
.push("the Flatpak source and version could not be identified".into());
return;
};
if !version.is_empty() {
candidate.version = Some(version);
}
if remote.is_empty() || remote.contains(',') || remote != "flathub" {
candidate.verified = false;
candidate.notes.push(
"the Flatpak search did not identify the configured flathub install remote".into(),
);
return;
}
candidate.provenance = remote.clone();
let remotes = exec.runner.execute(&rooted(
root,
"sys",
"inspect Flatpak verification",
"flatpak",
&["remotes", "--system", "--columns=name,url,options"],
));
let Some((url, options)) = remotes.ok().filter(|o| o.success).and_then(|o| {
o.stdout_lossy().lines().find_map(|line| {
let mut columns = line.split('\t');
if columns.next()? != remote {
return None;
}
Some((
columns.next()?.trim().to_string(),
columns.next().unwrap_or("").to_string(),
))
})
}) else {
candidate.verified = false;
candidate
.notes
.push("the selected Flatpak remote could not be inspected".into());
return;
};
candidate.provenance = format!("{remote} ({url})");
if !url.starts_with("https://")
|| options
.split(|c: char| c.is_whitespace() || c == ',')
.any(|o| o == "no-gpg-verify")
{
candidate.verified = false;
candidate
.notes
.push("the Flatpak remote lacks HTTPS or has GPG verification disabled".into());
}
}
/// Whether a lane is installed and ready on the intended system.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct BackendStatus {
@ -700,7 +836,7 @@ pub fn candidate_detail(exec: &Exec, root: &Path, backend: Backend, id: &str) ->
Backend::Flatpak | Backend::Nix | Backend::AppImage | Backend::CustomEbuild => {}
}
let candidate = candidate.unwrap_or_else(|| {
let mut candidate = candidate.unwrap_or_else(|| {
let mut c = Candidate::new(backend, id, "(unresolved)");
c.available = false;
c.notes
@ -708,8 +844,14 @@ pub fn candidate_detail(exec: &Exec, root: &Path, backend: Backend, id: &str) ->
c
});
if backend == Backend::Flatpak && candidate.available {
inspect_flatpak_remote(exec, root, &mut candidate);
}
let health = candidate_health(&candidate);
CandidateDetail {
candidate,
health,
dependencies,
confinement,
channel,
@ -1248,6 +1390,23 @@ mod tests {
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn health_report_distinguishes_source_metadata_from_upstream_safety() {
let mut flatpak = Candidate::new(Backend::Flatpak, "org.example.App", "flathub");
flatpak.verified = true;
flatpak.version = Some("2.3".into());
let report = candidate_health(&flatpak);
assert_eq!(report.status, "review_required");
assert!(report.freshness.contains("version 2.3"));
assert!(report.freshness.contains("not independently checked"));
assert!(report.limitation.contains("cannot prove"));
let staged = Candidate::new(Backend::CustomEbuild, "app-misc/example", "Phoebus overlay");
let report = candidate_health(&staged);
assert_eq!(report.status, "hold");
assert!(report.integrity.contains("untrusted executable build code"));
}
fn ok(stdout: &str) -> CommandOutput {
CommandOutput {
status: 0,

View file

@ -133,7 +133,7 @@ impl ResolvedInstall {
out.push_str(&format!(
" integrity: {}\n",
if c.verified {
"verified (signature/hash)"
"backend reports candidate; artifact not yet verified"
} else {
"UNVERIFIED — provenance not cryptographic"
}
@ -308,6 +308,10 @@ pub fn approval_digest_for(
hasher.update(b"\0");
hasher.update(candidate.version.as_deref().unwrap_or("").as_bytes());
hasher.update(b"\0");
hasher.update(candidate.provenance.as_bytes());
hasher.update(b"\0");
hasher.update([u8::from(candidate.verified)]);
hasher.update(b"\0");
hasher.update(serde_json::to_string(action).unwrap_or_default().as_bytes());
hasher.update(b"\0");
if effects.established {
@ -345,6 +349,20 @@ pub fn revalidate(exec: &Exec, root: &Path, resolved: &ResolvedInstall) -> Resul
"the reviewed candidate is no longer available from real metadata",
)
})?;
let checked;
let current = if backend == Backend::Flatpak {
checked = chooser::candidate_detail(exec, root, backend, &current.id);
if checked.health.status == "hold" {
return Err(ExecError::operation(
"install",
"revalidate",
"the Flatpak source no longer passes the HTTPS and GPG checks",
));
}
&checked.candidate
} else {
current
};
if current.version != resolved.candidate.version {
return Err(ExecError::operation(
"install",
@ -356,6 +374,15 @@ pub fn revalidate(exec: &Exec, root: &Path, resolved: &ResolvedInstall) -> Resul
),
));
}
if current.provenance != resolved.candidate.provenance
|| current.verified != resolved.candidate.verified
{
return Err(ExecError::operation(
"install",
"revalidate",
"the candidate source or verification status changed since review",
));
}
let action = action_for(exec, root, current)?;
if action != resolved.action {
return Err(ExecError::operation(
@ -570,8 +597,46 @@ fn finalize(
source: InstallSource,
allow_duplicate: bool,
) -> Result<ResolvedInstall> {
let candidate = if candidate.backend == Backend::Flatpak {
let detail = chooser::candidate_detail(exec, root, candidate.backend, &candidate.id);
if detail.health.status == "hold" {
return Err(ExecError::operation(
"install",
"source health review",
format!(
"{} cannot be installed from an unverified Flatpak remote: {}",
candidate.id,
detail.candidate.notes.join("; ")
),
));
}
detail.candidate
} else {
candidate
};
let inspection = chooser::installed_copies(exec, root, &request.application);
let mut warnings = Vec::new();
if candidate.backend.requires_source_review() {
let health = chooser::candidate_health(&candidate);
if source == InstallSource::AiRecommendation && health.status == "hold" {
return Err(ExecError::operation(
"install",
"source health review",
format!(
"{} cannot be recommended from {}: {}. Use a source with verifiable \
provenance or inspect and select an explicit legacy source yourself",
candidate.id,
candidate.backend.as_str(),
health.integrity
),
));
}
warnings.push(format!(
"Source health: {}. {}",
health.integrity, health.freshness
));
warnings.push(health.limitation.into());
}
let candidate_is_portage = candidate.backend.is_portage();
if !inspection.copies.is_empty() {
let summary = inspection
@ -1041,14 +1106,20 @@ mod tests {
version: std::sync::Arc<std::sync::atomic::AtomicU32>,
/// Whether `flatpak list` reports the app as installed.
installed: bool,
remote_verified: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl ArgRunner {
fn new(version: std::sync::Arc<std::sync::atomic::AtomicU32>, installed: bool) -> Self {
fn new(
version: std::sync::Arc<std::sync::atomic::AtomicU32>,
installed: bool,
remote_verified: std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> Self {
Self {
recorded: std::sync::Mutex::new(Vec::new()),
version,
installed,
remote_verified,
}
}
}
@ -1074,7 +1145,27 @@ mod tests {
let is_flatpak = spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak");
let is_emerge = spec.program == "emerge" || spec.args.iter().any(|a| a == "emerge");
if is_flatpak && spec.args.iter().any(|a| a == "search") {
if spec
.args
.iter()
.any(|a| a == "--columns=application,version,remotes")
{
Ok(ok(format!("org.mozilla.firefox\t{version}\tflathub\n")))
} else {
Ok(ok(format!("org.mozilla.firefox {version}\n")))
}
} else if is_flatpak && spec.args.iter().any(|a| a == "remotes") {
let options = if self
.remote_verified
.load(std::sync::atomic::Ordering::SeqCst)
{
""
} else {
"no-gpg-verify"
};
Ok(ok(format!(
"flathub\thttps://dl.flathub.org/repo/\t{options}\n"
)))
} else if is_flatpak && spec.args.iter().any(|a| a == "list") {
Ok(ok(if self.installed {
format!("org.mozilla.firefox {version}\n")
@ -1090,6 +1181,18 @@ mod tests {
}
fn arg_exec(version: std::sync::Arc<std::sync::atomic::AtomicU32>, installed: bool) -> Exec {
arg_exec_with_remote(
version,
installed,
std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
)
}
fn arg_exec_with_remote(
version: std::sync::Arc<std::sync::atomic::AtomicU32>,
installed: bool,
remote_verified: std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> Exec {
use std::os::unix::fs::PermissionsExt;
let path = tempfile::tempdir().unwrap().keep();
// A Flatpak must be present in the *target* for the lane to resolve.
@ -1100,7 +1203,7 @@ mod tests {
std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(
Box::new(ArgRunner::new(version, installed)),
Box::new(ArgRunner::new(version, installed, remote_verified)),
logger,
false,
path.join("root"),
@ -1124,7 +1227,17 @@ mod tests {
.iter()
.map(|r| Evidence {
request: r.describe(),
output: "[]".into(),
output: if let SystemAction::InspectCandidate { backend, id } = r {
serde_json::json!({
"backend": backend,
"id": id,
"available": true,
"health": {"status": "review_required"}
})
.to_string()
} else {
"[]".into()
},
})
.collect()
}
@ -1149,14 +1262,22 @@ mod tests {
))
}
fn inspection(candidate: &str) -> String {
phoebus_ai::provider::chat_response(&format!(
r#"{{"version":2,"kind":"investigate","requests":[{{"action":"inspect_candidate","backend":"flatpak","id":"{candidate}"}}]}}"#
))
}
#[test]
fn ai_unqualified_install_is_confirmed_by_the_resolver() {
let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128));
let exec = arg_exec(version, false);
let root = Path::new(&exec.root);
let request = InstallRequest::new("firefox");
let transport =
phoebus_ai::provider::ScriptedTransport::new(vec![proposal("org.mozilla.firefox")]);
let transport = phoebus_ai::provider::ScriptedTransport::new(vec![
inspection("org.mozilla.firefox"),
proposal("org.mozilla.firefox"),
]);
let resolved =
resolve_with_ai(&exec, root, &request, &NoAsk, &ai(&transport), &facts()).unwrap();
assert_eq!(resolved.candidate.id, "org.mozilla.firefox");
@ -1174,8 +1295,10 @@ mod tests {
let root = Path::new(&exec.root);
let mut request = InstallRequest::new("firefox");
request.backend = Some(Backend::Flatpak);
let transport =
phoebus_ai::provider::ScriptedTransport::new(vec![proposal("org.mozilla.firefox")]);
let transport = phoebus_ai::provider::ScriptedTransport::new(vec![
inspection("org.mozilla.firefox"),
proposal("org.mozilla.firefox"),
]);
resolve_with_ai(&exec, root, &request, &NoAsk, &ai(&transport), &facts()).unwrap();
assert!(transport.requests()[0].contains("only use the flatpak backend"));
}
@ -1201,14 +1324,16 @@ mod tests {
let root = Path::new(&exec.root);
let request = InstallRequest::new("firefox");
let transport = phoebus_ai::provider::ScriptedTransport::new(vec![
inspection("org.evil.Firefox"),
proposal("org.evil.Firefox"),
inspection("org.mozilla.firefox"),
proposal("org.mozilla.firefox"),
]);
let resolved =
resolve_with_ai(&exec, root, &request, &NoAsk, &ai(&transport), &facts()).unwrap();
assert_eq!(resolved.candidate.id, "org.mozilla.firefox");
// The second request carries the resolver's finding.
assert!(transport.requests()[1].contains("no available"));
assert!(transport.requests()[2].contains("no available"));
}
#[test]
@ -1231,6 +1356,36 @@ mod tests {
assert!(err.to_string().contains("version changed"), "{err}");
}
#[test]
fn flatpak_remote_without_gpg_is_refused_and_rechecked() {
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
let verified = std::sync::Arc::new(AtomicBool::new(false));
let exec = arg_exec_with_remote(
std::sync::Arc::new(AtomicU32::new(128)),
false,
verified.clone(),
);
let root = Path::new(&exec.root);
let mut request = InstallRequest::new("org.mozilla.firefox");
request.backend = Some(Backend::Flatpak);
let err = resolve_explicit(&exec, root, &request).unwrap_err();
assert!(
err.to_string().contains("unverified Flatpak remote"),
"{err}"
);
verified.store(true, Ordering::SeqCst);
let resolved = resolve_explicit(&exec, root, &request).unwrap();
assert!(resolved.candidate.provenance.contains("https://"));
assert!(resolved.render().contains("Source health:"));
verified.store(false, Ordering::SeqCst);
let err = revalidate(&exec, root, &resolved).unwrap_err();
assert!(err.to_string().contains("HTTPS and GPG"), "{err}");
}
#[test]
fn an_already_installed_app_in_the_same_lane_is_not_reinstalled() {
let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128));

View file

@ -815,6 +815,28 @@ pub fn plan_general(
None => assistant_plan.actions.clone(),
};
// Direct package actions from a general AI plan would bypass the install
// workflow's candidate inspection, source checks and execution-time
// revalidation. Keep those actions on the dedicated install path.
if actions_list.iter().any(|action| {
matches!(
action,
SystemAction::InstallPackage { .. }
| SystemAction::FlatpakInstall { .. }
| SystemAction::SnapInstall { .. }
| SystemAction::NixInstall { .. }
| SystemAction::AppImageImport { .. }
| SystemAction::AppImageAcquire { .. }
| SystemAction::CustomEbuildInstall { .. }
)
}) {
return Err(ExecError::operation(
"service",
"source health review",
"package installation requires the dedicated `sys install` workflow; request an install by application name and source so sys can inspect it before approval",
));
}
let mut combined_effects = ResolvedPlan {
established: true,
..Default::default()

View file

@ -476,7 +476,17 @@ impl phoebus_executor::command::ProcessRunner for FlatpakRunner {
let installed = self.installed.load(std::sync::atomic::Ordering::SeqCst);
let is_flatpak = spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak");
if is_flatpak && spec.args.iter().any(|a| a == "search") {
if spec
.args
.iter()
.any(|a| a == "--columns=application,version,remotes")
{
Ok(ok("org.mozilla.firefox\t128\tflathub\n".into()))
} else {
Ok(ok("org.mozilla.firefox 128\n".into()))
}
} else if is_flatpak && spec.args.iter().any(|a| a == "remotes") {
Ok(ok("flathub\thttps://dl.flathub.org/repo/\t\n".into()))
} else if is_flatpak && spec.args.iter().any(|a| a == "list") {
if !installed {
return Ok(ok(String::new()));
@ -1997,6 +2007,27 @@ fn plan_general_refuses_a_foreign_lane_under_a_constraint() {
assert!(err.to_string().contains("constrained"), "{err}");
}
#[test]
fn plan_general_refuses_direct_third_party_install_actions() {
use phoebus_ai::provider::{chat_response, ScriptedTransport};
let transport = ScriptedTransport::new(vec![chat_response(
r#"{"version":1,"summary":"install it","actions":[{"action":"flatpak_install","app_id":"org.mozilla.firefox"}],"rationale":[{"action":"flatpak_install","reason":"requested"}]}"#,
)]);
let exec = make_test_exec(Path::new("/"));
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let err = plan_general(
&store,
&exec,
Path::new("/"),
"install Firefox",
&SystemFacts::default(),
&general_ai(&transport),
None,
)
.unwrap_err();
assert!(err.to_string().contains("dedicated `sys install`"), "{err}");
}
#[test]
fn plan_general_rewrites_a_laneless_query_to_the_constraint() {
use phoebus_ai::provider::{chat_response, ScriptedTransport};