Explain daemon failures in human terms

This commit is contained in:
Archipelago 2026-11-18 13:23:43 +00:00
parent 194f97e508
commit 7b04b89cef
3 changed files with 183 additions and 18 deletions

View file

@ -1,5 +1,25 @@
# archipelagod implementation checkpoint
## 2026-11-18 checkpoint: human CLI errors and complete help
Installed-host failures are rendered from the typed public error (`code`,
`phase`, `retryable`, `diagnostic_id`) rather than from a JSON string. The CLI
fetches the authorized operation log on a terminal failure and extracts one
control-free cause line; the full journal remains behind
`archipelago transaction log ID`. Internal engine phrases and the old fallback
sentence are not shown to users. `--json` keeps one structured document and
`--debug` keeps technical output on stderr.
`archipelago --help`, `help COMMAND` and `COMMAND --help` cover every implemented
command family and option, including installed-host globals (`--json`, `--debug`,
`--interactive`, `--non-interactive`, `--offline`, `--request-id`), command
options (`--plan`, `--file`, `--reason`, `--purpose`, `--erase`, `--full`) and
kernel-argument edits. Build/install-only `--verbose` and the lab-only overlay
fixture are marked as such instead of being presented as global features.
The no-direct-write invariant is unchanged: mutating installed-host commands fail
when `archipelagod` is unavailable; only the user-facing wording changed.
## 2026-11-16 checkpoint: native libostree kernel arguments
`system/src/service/kargs.rs` no longer runs `python3 adapters/kernel-arguments.py`.

View file

@ -88,7 +88,20 @@ impl Client {
}
match snapshot["State"].as_str() {
Some("succeeded") => return Ok(snapshot["Result"].clone()),
Some("failed" | "cancelled" | "interrupted") => return Err(snapshot["Error"].to_string()),
Some("failed" | "cancelled" | "interrupted") => {
let mut detail = snapshot["Error"].clone();
// The public error is deliberately short. The authorized
// operation log contains the engine's last diagnostic line;
// include one sanitized cause so the CLI can explain it.
if !self.output.borrow().debug {
if let Ok(logs) = self.logs(id) {
if let Some(cause) = diagnostic_cause(&logs) {
detail["cause"] = json!(cause);
}
}
}
return Err(detail.to_string());
}
_ => (),
}
if Instant::now() >= deadline { return Err(format!("Stopped waiting; operation {id} continues. Use archipelago transaction wait {id}")); }
@ -299,11 +312,38 @@ impl Client {
}
self.stage(self.operation(true,"PrepareChange",&(changes,context,self.options()))?)
}
_ => Err("Unsupported installed-host command; no direct writer fallback is permitted".into()),
_ => Err(if super::client_output::russian() {
"Неизвестная команда для установленной системы. Справка: archipelago --help"
} else {
"Unknown installed-host command. See: archipelago --help"
}.into()),
}
}
}
/// Extract the most useful error line from a paginated operation log. The
/// daemon's log is already authorized for this caller; we only surface a short,
/// control-free line and keep the full record behind `transaction log`.
fn diagnostic_cause(logs: &Value) -> Option<String> {
let lines = logs["lines"].as_array()?;
let mut fallback = None;
for line in lines.iter().rev().filter_map(Value::as_str) {
let line = line.trim();
let line = line.strip_prefix("stdout: ").or_else(|| line.strip_prefix("stderr: ")).unwrap_or(line);
let lower = line.to_ascii_lowercase();
let cleaned: String = line.chars().filter(|c| !c.is_control()).take(240).collect();
if cleaned.is_empty() || cleaned.starts_with("/usr/bin/") { continue; }
if lower.contains("no space left") || lower.contains("error:") ||
lower.contains("signature") || lower.contains("not found") {
return Some(cleaned);
}
if fallback.is_none() && (lower.contains("failed") || lower.contains("failure") || lower.contains("could not") || lower.contains("cannot")) {
fallback = Some(cleaned);
}
}
fallback
}
/// Split `extension add` arguments into repository names and local archives.
///
/// A local archive is unambiguous when it is written as a path (`./x`, `../x`,
@ -426,7 +466,12 @@ pub fn dispatch(args: &[String]) -> Result<(),String> {
}
}
if !archipelago_contracts::system_bus::request_id(&request) { return Err("Expected a UUID retry token".into()); }
let client = Client { connection:Connection::system().map_err(error)?,interactive,offline,request_id:request,output };
let connection = Connection::system().map_err(|e| if super::client_output::russian() {
format!("Служба управления недоступна. Изменения не применены. Проверьте `systemctl status archipelagod`. ({e})")
} else {
format!("The management service is unavailable. No changes were applied. Check `systemctl status archipelagod`. ({e})")
})?;
let client = Client { connection,interactive,offline,request_id:request,output };
client.output.borrow_mut().record("command", &json!({"arguments":args,"request_id":client.request_id}));
let result = match client.dispatch(&positional) {
Ok(result) => result,
@ -455,12 +500,32 @@ pub fn command(args: &[String]) -> Option<&str> {
pub fn report_error(args: &[String], message: &str) {
let detail: Value = serde_json::from_str(message).unwrap_or_else(|_| json!({"message":message}));
if args.iter().any(|a| a == "--json") { println!("{}", json!({"error":detail})); }
else if args.iter().any(|a| a == "--debug") { eprintln!("{}", json!({"error":detail})); }
else {
let ru = super::client_output::russian();
eprintln!("✗ {}", super::client_output::failure(detail["message"].as_str().unwrap_or(message), ru));
if let Some(path) = detail["log"].as_str() { eprintln!("{}: {path}", if ru {"Подробности"} else {"Details"}); }
if args.iter().any(|a| a == "--json") {
println!("{}", json!({"error":detail}));
if args.iter().any(|a| a == "--debug") { eprintln!("{}", json!({"error":detail})); }
return;
}
if args.iter().any(|a| a == "--debug") {
eprintln!("{}", json!({"error":detail}));
return;
}
let ru = super::client_output::russian();
eprintln!("✗ {}", super::client_output::failure_detail(&detail, ru));
if let Some(id) = detail["diagnostic_id"].as_str().filter(|value| !value.is_empty()) {
eprintln!("{}: {id}", if ru { "Операция" } else { "Operation" });
eprintln!("{}: archipelago transaction log {id}", if ru { "Журнал" } else { "Log" });
}
if let Some(active) = detail["active_operation_id"].as_str().filter(|value| !value.is_empty()) {
eprintln!("{}: {active}", if ru { "Активная операция" } else { "Active operation" });
}
if let Some(path) = detail["log"].as_str() { eprintln!("{}: {path}", if ru { "Лог CLI" } else { "CLI log" }); }
let raw = detail["message"].as_str().unwrap_or("");
let invalid = detail["code"].as_str() == Some("InvalidArgument") ||
raw.starts_with("Unknown installed-host command") || raw.starts_with("Unknown command");
if invalid {
if let Some(command) = args.iter().find(|arg| !arg.starts_with('-')) {
eprintln!("{}: archipelago help {command}", if ru { "Справка" } else { "Help" });
}
}
}
@ -504,6 +569,17 @@ mod interface_tests {
assert!(karg_edits(&args).is_err());
}
}
#[test]
fn operation_log_cause_prefers_the_real_error_line() {
let logs = json!({"lines":[
"stdout: loading packages...",
"stdout: error: '/inputs/pkg.tar.zst': package missing required signature",
"stdout: Required package action/finalization failed"]});
assert_eq!(diagnostic_cause(&logs).as_deref(),
Some("error: '/inputs/pkg.tar.zst': package missing required signature"));
assert!(diagnostic_cause(&json!({"lines":["stdout: done"]})).is_none());
}
#[test]
fn global_flags_preserve_host_command_routing() {
let args = ["--json", "--request-id", "12345678-1234-1234-1234-123456789abc", "--offline", "extension", "status"].map(str::to_owned);

View file

@ -59,7 +59,7 @@ impl Output {
}
impl Drop for Output { fn drop(&mut self) { self.clear(); let _ = self.log.sync_all(); } }
fn phase_label(phase: &str, ru: bool) -> String {
pub fn phase_label(phase: &str, ru: bool) -> String {
let pair = match phase {
"metadata" => ("Проверка доступных пакетов и обновлений", "Checking available packages and updates"),
"details" => ("Подготовка списка изменений", "Reading changes"),
@ -160,15 +160,73 @@ fn field_label(key: &str, ru: bool) -> String {
if ru { pair.0.into() } else { pair.1.into() }
}
pub fn failure(message: &str, ru: bool) -> String {
if message.contains("Explicitly enable Host Extensions") {
return if ru { "Сначала включите Host Extensions: archipelago extension enable" } else { "Enable Host Extensions first: archipelago extension enable" }.into();
fn generic_message(message: &str) -> bool {
matches!(message,
"Engine command failed; inspect the authorized operation log" |
"Unsupported installed-host command; no direct writer fallback is permitted" |
"Operation failed" | "Failed")
}
/// Render one public daemon error. The daemon contract carries a stable code,
/// phase, diagnostic ID and retryability; internal command text is not shown
/// unless it actually adds information.
pub fn failure_detail(detail: &Value, ru: bool) -> String {
let t = |a: &str, b: &str| if ru { a.to_string() } else { b.to_string() };
let code = detail["code"].as_str().unwrap_or("");
let phase = detail["phase"].as_str().unwrap_or("");
let raw = detail["message"].as_str().unwrap_or("");
let cause = detail["cause"].as_str().filter(|value| !value.trim().is_empty());
if code.is_empty() {
return if raw.is_empty() { t("Операция не выполнена.", "The operation failed.") } else { raw.to_owned() };
}
if message.contains("Administrator authorization required") {
return if ru { "Нужно подтверждение администратора. Повторите с --interactive в сеансе с агентом авторизации или через sudo." }
else { "Administrator authorization is required. Retry with --interactive in a session with an authorization agent, or use sudo." }.into();
let mut text = match code {
"InvalidArgument" => t("Неверные аргументы команды.", "Invalid command arguments."),
"Unsupported" => t("Операция не поддерживается этой версией системы.",
"This operation is not supported by this system version."),
"NotAuthorized" | "AuthenticationRequired" =>
t("Нужно подтверждение администратора. Повторите в авторизованном сеансе или через sudo.",
"Administrator authorization is required. Retry in an authorized session or with sudo."),
"Busy" => t("Другая операция уже выполняется. Дождитесь её завершения и повторите.",
"Another operation is already running. Wait for it to finish and retry."),
"PlanStale" => t("Состояние системы изменилось после подготовки плана. Создайте новый план.",
"The system changed after the plan was prepared. Create a new plan."),
"NoTrack" => t("Не настроен источник обновлений или каталог слоёв.",
"The update track or layer catalog is not configured."),
"NoNetwork" => t("Нет доступа к сети или репозиторию. Проверьте подключение и повторите.",
"The network or repository is unavailable. Check connectivity and retry."),
"Timeout" => t("Операция превысила отведённое время. Текущая система не изменена.",
"The operation exceeded its deadline. The current system is unchanged."),
"TrustFailed" => t("Проверка подписи или доверия не пройдена. Изменения не применены.",
"Signature or trust verification failed. No changes were applied."),
"NoSpace" => t("Недостаточно свободного места для операции. Текущая система не изменена.",
"There is not enough free space for the operation. The current system is unchanged."),
"TooLate" => t("Операция больше не актуальна. Обновите состояние и повторите.",
"The operation is no longer applicable. Refresh the state and retry."),
"NotFound" => t("Запрошенный объект не найден.", "The requested object was not found."),
"Interrupted" => t("Операция прервана или требует сверки. Проверьте состояние системы перед повтором.",
"The operation was interrupted or needs reconciliation. Check the system state before retrying."),
"Conflict" => t("Состояние системы не позволяет выполнить операцию. Обновите данные и повторите.",
"The current system state does not permit this operation. Refresh and retry."),
"ExecutionFailed" if matches!(phase, "validating" | "staging") && cause.is_some() =>
t("Проверка или установка пакетов не завершена; новый deployment не подготовлен.",
"Package validation or installation did not complete; no new deployment was prepared."),
"ExecutionFailed" => t("Операция не выполнена. Изменения не применены.",
"The operation failed. No changes were applied."),
_ => t("Операция не выполнена.", "The operation failed."),
};
if !phase.is_empty() && phase != "unknown" {
text.push_str(&format!("\n{}: {}", t("Этап", "Phase"), phase_label(phase, ru)));
}
message.into()
if let Some(cause) = cause {
text.push_str(&format!("\n{}: {cause}", t("Причина", "Cause")));
} else if !raw.is_empty() && !generic_message(raw) {
text.push_str(&format!("\n{}: {raw}", t("Причина", "Cause")));
}
if detail["retryable"] == true {
text.push_str(&format!("\n{}", t("Операцию можно повторить после устранения причины.",
"The operation may be retried after the cause is resolved.")));
}
text
}
#[cfg(test)]
@ -180,6 +238,17 @@ mod tests {
let text = human(&["extension","add","nano"], &value, true);
assert!(text.contains("перезагрузки"));
assert!(!text.contains("secret-id") && !text.contains("retry-token") && !text.contains('{'));
assert!(failure("Explicitly enable Host Extensions before changing requests", true).contains("archipelago extension enable"));
}
#[test]
fn daemon_failure_is_explained_without_internal_phrases() {
let detail = json!({"code":"ExecutionFailed","phase":"validating",
"message":"Engine command failed; inspect the authorized operation log",
"cause":"error: package missing required signature","retryable":false});
let text = failure_detail(&detail, true);
assert!(text.contains("deployment"));
assert!(text.contains("Причина: error: package missing required signature"));
assert!(!text.contains("Engine command failed"));
assert!(failure_detail(&json!({"code":"PlanStale"}), false).contains("Create a new plan"));
}
}