Skip to main content

gunnar_server/
narrate.rs

1//! **The app's half of the boot narration: stages, ticks and fault codes.**
2//!
3//! # The measurement this exists for
4//!
5//! 2026-09-23, the live estate. The twin was installed with the narration
6//! channel ON (`korp.log_udp=10.13.2.127:5140`) and it delivered **66
7//! datagrams**: three application lines and sixty-three kernel records.
8//! Network up at 6.34 s, xfs recovered, `end of hand-off` at 6.35 s — and then
9//! silence, for ever. The twin then read its config, bound its listeners, took
10//! its role, held its certificate, started following its primary, and panicked
11//! (`Cannot drop a runtime in a context where blocking is not allowed`). gunnar
12//! is PID 1, so the kernel panicked with it and the box stopped.
13//!
14//! **Everything that mattered happened after the last datagram.** The rung
15//! waiting on that box timed out at 600 s with an empty status, and the only
16//! account anybody got was a VNC screenshot taken by hand.
17//!
18//! `boot::ship_boot_narration` was never meant to be the whole story: it is the
19//! hand-off, the moment the DHCP lease makes the wire usable, and it says so —
20//! `end of hand-off`. Nothing said anything after it. This module is what
21//! speaks from there on.
22//!
23//! # What it does
24//!
25//! * **[`at`]** — one line at every boundary the app crosses, with a monotonic
26//!   stamp: config read, every listener BOUND with its address, the role, a
27//!   twin's primary and certificate, serving.
28//! * **[`tick`](Narrator::tick)** — one short line a minute with uptime and the
29//!   current stage, so silence means dead rather than idle, and the ear can say
30//!   "last tick N s ago" instead of "nothing has ever arrived" (which cannot
31//!   tell "never started" from "died at minute 12").
32//! * **[`fault`]** — a short STABLE code, the stage, one line of reason and the
33//!   crash-record path; re-sent because this is UDP; acknowledged by the ear;
34//!   then a CLEAN POWER-OFF. No kernel panic, no reboot loop. The rung refuses
35//!   by that code.
36//!
37//! # Three readers, one story
38//!
39//! Every line goes to the console, to `BOOTLOG.TXT` on the ESP (which
40//! `korp-start` left mounted read-only at `/boot`, flipped read-write for one
41//! append at a time — the same flip the rollback floor makes) and to
42//! `/data/log/boot.log`. A fault also writes `/data/crash/fault.txt`. A box
43//! that dies before its DHCP lease has said nothing on the wire and everything
44//! on the other two.
45//!
46//! # The off switch
47//!
48//! `korp.log_udp=` on the kernel command line, and nothing else. Unset ⇒
49//! [`armed`] is false, no socket is bound, no tick thread exists and not one
50//! datagram is sent; the ESP and `/data` lines cost nothing anybody can hear
51//! and are kept, because a box that powers itself off has to leave the reason
52//! somewhere. The estate's steady state ships media with no `log_udp` param, so
53//! a box that narrates for ever cannot be produced by forgetting to turn
54//! something off — only by asking for it.
55//!
56//! # One vocabulary, three spellings
57//!
58//! `korp-installer::narrate` (korp-start), this module and the ear
59//! (`private-gunnar-ops/xtask/src/bootnarr.rs`) each spell these constants.
60//! There is no dependency edge between the three repositories, which is the
61//! same arrangement the secret-class door already lives under and for the same
62//! reason. What keeps them honest is that the wire format is a TOKEN and not
63//! prose: a spelling that drifts stops matching, and the ear says so loudly
64//! rather than quietly judging something else.
65
66use std::path::{Path, PathBuf};
67use std::sync::atomic::{AtomicU8, Ordering};
68use std::sync::{Mutex, OnceLock};
69use std::time::{Duration, Instant};
70
71// ── the vocabulary ───────────────────────────────────────────────────────────
72
73/// A boundary in the boot, named. The first eight are `korp-start`'s, before
74/// the exec; this process emits the last eight. One enum because it is one
75/// story on one wire.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
77pub enum Stage {
78    /// PID 1's first instruction.
79    Entered,
80    /// `devtmpfs` is on `/dev`.
81    Devtmpfs,
82    /// fds 0-2 take a byte.
83    Console,
84    /// The kernel command line, as parsed.
85    Cmdline,
86    /// The disks seen, and which was chosen.
87    Disks,
88    /// The data filesystem is mounted.
89    DataFs,
90    /// The app archive is open and its digest is known.
91    Archive,
92    /// The exec: which binary, which version, which args.
93    Exec,
94    /// This process read its configuration.
95    Config,
96    /// The network link is up.
97    Network,
98    /// A DHCP lease, with the address. The first stage the wire can carry live.
99    Lease,
100    /// The narration sink is resolved and the backlog has been flushed.
101    Sink,
102    /// One listener is BOUND, with its address. Once per listener.
103    Listener,
104    /// The role this box took.
105    Role,
106    /// A twin: the primary it follows and the certificate it holds.
107    Follow,
108    /// Serving. The end of the boot story and the beginning of the ticks.
109    Serving,
110}
111
112impl Stage {
113    /// The wire token: one lower-case word, matched rather than read.
114    pub const fn token(self) -> &'static str {
115        match self {
116            Stage::Entered => "entered",
117            Stage::Devtmpfs => "devtmpfs",
118            Stage::Console => "console",
119            Stage::Cmdline => "cmdline",
120            Stage::Disks => "disks",
121            Stage::DataFs => "datafs",
122            Stage::Archive => "archive",
123            Stage::Exec => "exec",
124            Stage::Config => "config",
125            Stage::Network => "network",
126            Stage::Lease => "lease",
127            Stage::Sink => "sink",
128            Stage::Listener => "listener",
129            Stage::Role => "role",
130            Stage::Follow => "follow",
131            Stage::Serving => "serving",
132        }
133    }
134}
135
136/// Every stage, in the order a healthy boot crosses them. Index = discriminant,
137/// which is what lets the tick thread carry the stage in one atomic byte.
138pub const ORDER: [Stage; 16] = [
139    Stage::Entered,
140    Stage::Devtmpfs,
141    Stage::Console,
142    Stage::Cmdline,
143    Stage::Disks,
144    Stage::DataFs,
145    Stage::Archive,
146    Stage::Exec,
147    Stage::Config,
148    Stage::Network,
149    Stage::Lease,
150    Stage::Sink,
151    Stage::Listener,
152    Stage::Role,
153    Stage::Follow,
154    Stage::Serving,
155];
156
157/// The marker a stage line begins with.
158pub const STAGE_MARKER: &str = "STAGE";
159/// The marker a tick line begins with.
160pub const TICK_MARKER: &str = "TICK";
161/// The marker a fault line begins with.
162pub const FAULT_MARKER: &str = "FAULT";
163/// What the ear sends back.
164pub const ACK_MARKER: &str = "ACK";
165
166/// One line a minute. Short on purpose: it is sent for the life of the box.
167pub const TICK_EVERY: Duration = Duration::from_secs(60);
168
169/// How many times a fault datagram is sent. One is a coin flip on UDP from a
170/// box that is about to power itself off.
171pub const FAULT_RESENDS: usize = 3;
172/// The gap between the re-sends.
173pub const FAULT_RESEND_EVERY: Duration = Duration::from_millis(400);
174
175/// **How long a faulting box waits to be heard, and no longer: five seconds.**
176///
177/// Chosen and stated. Long enough for three datagrams and a reply to cross a
178/// utility network (sub-millisecond) with four orders of magnitude of slack;
179/// short enough that a box with no ear waits about as long as a human blinks
180/// before it powers off. Unheard is NOT a reason to stay up — the whole point
181/// is that the box stops rather than loops.
182pub const ACK_BUDGET: Duration = Duration::from_secs(5);
183
184/// The stable fault codes this process can emit. `KS-*` are `korp-start`'s and
185/// live in `korp_installer::narrate`; these are the app's. Add codes, never
186/// renumber one — a rung refuses BY the code.
187pub const CODES: [(&str, &str); 6] = [
188    ("GN-01", "the app could not read its configuration"),
189    ("GN-02", "a declared listener could not be bound"),
190    ("GN-03", "the role this box was given is not one it can take"),
191    ("GN-04", "a twin could not follow its primary"),
192    ("GN-05", "the app stopped serving with an error"),
193    ("GN-99", "the app panicked"),
194];
195
196/// **The code an ordinary `Err` out of the serve path carries**, read off the
197/// last boundary the narrator crossed.
198///
199/// Until 2026-09-23 only the panic hook sent a code (`GN-99`). An `Err` out of
200/// `serve` went `std::process::exit(1)`, and as PID 1 that is the kernel's
201/// `Attempted to kill init!` — no code, no power-off, the tick simply stops.
202/// `GN-01..04` were declared and never called. This is what calls them: the
203/// stage names the boundary that WAS crossed, so the failure lies in the step
204/// after it.
205///
206/// * nothing past `exec` — the configuration was never read: `GN-01`;
207/// * `config`, `network`, `lease`, `sink` — the next boundary is a bound
208///   listener, so this is the bind: `GN-02`;
209/// * `listener` — the next boundary is the role: `GN-03`;
210/// * `role`, `follow` — a twin that could not follow (a primary crosses from
211///   `role` straight to `serving` with nothing fallible between): `GN-04`;
212/// * `serving` — the box was up and its serve loop returned an error: `GN-05`.
213pub fn code_after(stage: Stage) -> &'static str {
214    match stage {
215        Stage::Entered
216        | Stage::Devtmpfs
217        | Stage::Console
218        | Stage::Cmdline
219        | Stage::Disks
220        | Stage::DataFs
221        | Stage::Archive
222        | Stage::Exec => "GN-01",
223        Stage::Config | Stage::Network | Stage::Lease | Stage::Sink => "GN-02",
224        Stage::Listener => "GN-03",
225        Stage::Role | Stage::Follow => "GN-04",
226        Stage::Serving => "GN-05",
227    }
228}
229
230/// What a code means, in one clause.
231pub fn code_meaning(code: &str) -> Option<&'static str> {
232    CODES.iter().find(|(c, _)| *c == code).map(|(_, m)| *m)
233}
234
235/// The acknowledgement for `code`.
236pub fn ack_line(code: &str) -> String {
237    format!("{ACK_MARKER} {code}")
238}
239
240/// Does this datagram acknowledge `code`? Tolerant of an ear that says more
241/// after the code; strict about the code itself.
242pub fn ack_matches(datagram: &[u8], code: &str) -> bool {
243    let text = String::from_utf8_lossy(datagram);
244    let mut parts = text.split_whitespace();
245    parts.next() == Some(ACK_MARKER) && parts.next() == Some(code)
246}
247
248/// `STAGE <token> +<ms>ms <detail>`.
249pub fn stage_line(stage: Stage, monotonic_ms: u128, detail: &str) -> String {
250    let detail = detail.trim();
251    if detail.is_empty() {
252        format!("{STAGE_MARKER} {} +{monotonic_ms}ms", stage.token())
253    } else {
254        format!("{STAGE_MARKER} {} +{monotonic_ms}ms {detail}", stage.token())
255    }
256}
257
258/// `TICK stage=<token> up=<s>s`.
259pub fn tick_line(stage: Stage, uptime_s: u64) -> String {
260    format!("{TICK_MARKER} stage={} up={uptime_s}s", stage.token())
261}
262
263/// `FAULT <code> stage=<token> +<ms>ms reason=<one line> crash=<path>`.
264///
265/// The reason is flattened to one line: a newline would forge a second line at
266/// every reader here, and all three are line-oriented.
267pub fn fault_line(
268    code: &str,
269    stage: Stage,
270    monotonic_ms: u128,
271    reason: &str,
272    crash: Option<&Path>,
273) -> String {
274    let reason = reason.replace(['\r', '\n'], " ");
275    let reason = reason.trim();
276    let crash = crash.map(|p| p.display().to_string()).unwrap_or_else(|| "-".to_string());
277    format!(
278        "{FAULT_MARKER} {code} stage={} +{monotonic_ms}ms reason={reason} crash={crash}",
279        stage.token()
280    )
281}
282
283/// Where the fault record goes on the data disk. `crate::slow::CRASH_DIR` is
284/// the same directory; this is the fixed file inside it, one per boot, so a
285/// reboot loop cannot fill `/data` with a file per attempt.
286pub const CRASH_RECORD: &str = "fault.txt";
287
288// ── the narrator ─────────────────────────────────────────────────────────────
289
290/// The file `korp-start` appends this boot's narration to on the ESP.
291const ESP_LOG: &str = "/boot/BOOTLOG.TXT";
292/// The mountpoint that file lives on, flipped read-write for one append.
293const ESP_MOUNT: &str = "/boot";
294/// The durable log `korp-start` opened on the data home, which this process
295/// continues rather than starting a second one beside.
296const DATA_LOG: &str = "log/boot.log";
297
298/// The one narrator, installed once by [`install`].
299static NARRATOR: OnceLock<Narrator> = OnceLock::new();
300
301/// **The app's narrator.** One per process, installed at the top of the serve
302/// path and read from everywhere afterwards — including the panic hook, which
303/// takes no arguments and is why this is a process global rather than a value
304/// threaded through the call graph.
305pub struct Narrator {
306    /// The boot's monotonic zero for this process. The kernel's uptime is the
307    /// number on the tick; this is the number on the stage lines, so they are
308    /// stamped from the exec rather than from the power-on.
309    t0: Instant,
310    /// The last boundary crossed. An atomic because the tick thread reads it.
311    stage: AtomicU8,
312    /// The data home, when there is one — where the crash record goes.
313    data: Mutex<Option<PathBuf>>,
314    /// Everything narrated so far, for the crash record. A boot narrates a few
315    /// KiB; unbounded is fine and bounded would lose the beginning, which is
316    /// the part a fault at minute twelve needs.
317    memory: Mutex<Vec<u8>>,
318}
319
320/// **Install the narrator.** Since 2026-09-24 there is no CLEAR-TEXT UDP wire:
321/// the boot narration over `korp.log_udp` is RETIRED, because the installer
322/// collects each VM's whole boot log over its own mutual TLS
323/// (`crate::installer_listener`). Every line goes to the console, the ESP's
324/// `BOOTLOG.TXT`, `/data`'s boot log and the log the installer reads — and on a
325/// DEV build (feature `dev-narrate`, 2026-09-30) that same log also leaves
326/// SEALED to the installer's key over udp/51822 from the moment the NIC has an
327/// address, before the installer's link exists (`crate::dev_narrate`).
328///
329/// Idempotent: the first caller wins.
330pub fn install() {
331    let _ = NARRATOR.set(Narrator {
332        t0: Instant::now(),
333        // The exec happened, so this process starts where korp-start stopped.
334        stage: AtomicU8::new(Stage::Exec as u8),
335        data: Mutex::new(None),
336        memory: Mutex::new(Vec::new()),
337    });
338}
339
340/// The installed narrator, if there is one. Everything here is a no-op before
341/// [`install`] — a unit test, `gunnar-solo` on a laptop, `serve --check`.
342pub fn narrator() -> Option<&'static Narrator> {
343    NARRATOR.get()
344}
345
346/// **Everything narrated so far** (empty before [`install`]): what a panic's
347/// crash record holds under its fault line (`boot::install_panic_fault` names
348/// it to edda's `fault::narration_from`).
349pub fn memory() -> Vec<u8> {
350    NARRATOR.get().map(Narrator::memory).unwrap_or_default()
351}
352
353/// **Cross a boundary, and say so on every reader.** The free function every
354/// call site uses; a no-op before [`install`].
355pub fn at(stage: Stage, detail: &str) {
356    if let Some(n) = NARRATOR.get() {
357        n.at(stage, detail);
358    }
359}
360
361/// Tell the narrator where the data home is, so a fault can leave a crash
362/// record on it. Called once the stores are open.
363pub fn data_home(root: &Path) {
364    if let Some(n) = NARRATOR.get() {
365        *n.data.lock().expect("the narrator's data home") = Some(root.to_path_buf());
366    }
367}
368
369impl Narrator {
370    /// Milliseconds since this process started narrating.
371    pub fn monotonic_ms(&self) -> u128 {
372        self.t0.elapsed().as_millis()
373    }
374
375    /// Everything this narrator said so far, as rendered (`gunnar: …\r\n`).
376    pub fn memory(&self) -> Vec<u8> {
377        self.memory.lock().map(|m| m.clone()).unwrap_or_default()
378    }
379
380    /// The last boundary crossed.
381    pub fn stage(&self) -> Stage {
382        let raw = self.stage.load(Ordering::Relaxed) as usize;
383        ORDER.get(raw).copied().unwrap_or(Stage::Exec)
384    }
385
386    /// Cross a boundary: remember it, then say it on all three readers.
387    pub fn at(&self, stage: Stage, detail: &str) {
388        self.stage.store(stage as u8, Ordering::Relaxed);
389        // And to edda's PID 1, which a panic (`GN-99`, `boot::install_panic_fault`)
390        // reads its stage and its restart-or-power-off off.
391        if stage == Stage::Serving {
392            appliance_pid1::fault::serving_now();
393        } else {
394            appliance_pid1::fault::reached(stage.token());
395        }
396        let line = stage_line(stage, self.monotonic_ms(), detail);
397        self.say(&line);
398    }
399
400    /// **One line, on every reader.** The console (which on the appliance is
401    /// the serial line teed with the VGA screen), the wire, `BOOTLOG.TXT` on
402    /// the ESP and `/data`'s boot log. Every failure is swallowed: this is
403    /// diagnostics, and a narration that could refuse a boot would be worse
404    /// than no narration.
405    pub fn say(&self, line: &str) {
406        let rendered = format!("gunnar: {line}\r\n");
407        if let Ok(mut m) = self.memory.lock() {
408            m.extend_from_slice(rendered.as_bytes());
409        }
410        // The console first: it is the reader that needs nothing to exist.
411        appliance_pid1::console::mirror_to_gfx_console(&rendered);
412        eprint!("{rendered}");
413        gunnar_common::logqueue::tap_line(rendered.trim_end());
414        append_to_esp(rendered.as_bytes());
415        if let Some(root) = self.data.lock().ok().and_then(|d| d.clone()) {
416            append_file(&root.join(DATA_LOG), rendered.as_bytes());
417        }
418    }
419}
420
421/// **A fatal fault: the code, the record, the ear's word, then a clean stop.**
422///
423/// In this order, and the order is the point:
424///
425/// 1. the crash record on `/data/crash/fault.txt`, holding the whole narration
426///    so far under the fault line — so the fault line can NAME it;
427/// 2. the fault line on every reader, including the two that need no network;
428/// 3. [`FAULT_RESENDS`] datagrams, spaced, because this is UDP;
429/// 4. a bounded wait for `ACK <code>` ([`ACK_BUDGET`], five seconds);
430/// 5. `sync` and power off — or, for a box that was serving, restart ([`end_after`]).
431///
432/// **Not a panic, and a reboot only once it serves.** gunnar is PID 1: a panic is
433/// the kernel's `Attempted to kill init!`, which names an exit code and nothing
434/// else, and a reboot into the same fault is a loop, which is how a fault
435/// becomes a mystery — so a fault during the boot powers off. A SERVING box
436/// restarts unless its last fault was recent ([`end_after`]). With the narration off it still writes the code to the two file
437/// readers and still powers off cleanly.
438///
439/// Never returns.
440pub fn fault(code: &'static str, stage: Stage, reason: &str) -> ! {
441    let Some(n) = NARRATOR.get() else {
442        // Nothing was installed: a unit test, or a fault before the serve path
443        // began. Say it where a process without a narrator can say it, and
444        // stop — but by exiting, not by powering off a developer's laptop.
445        eprintln!("gunnar: {}", fault_line(code, stage, 0, reason, None));
446        std::process::exit(1);
447    };
448    n.stage.store(stage as u8, Ordering::Relaxed);
449    let ms = n.monotonic_ms();
450    let root = n.data.lock().ok().and_then(|d| d.clone());
451    // The previous fault's age, read BEFORE this one overwrites its record.
452    let since_last = root
453        .as_ref()
454        .and_then(|r| std::fs::metadata(r.join(crate::slow::CRASH_DIR).join(CRASH_RECORD)).ok())
455        .and_then(|m| m.modified().ok())
456        .and_then(|t| t.elapsed().ok());
457    let crash = root.and_then(|root| write_crash_record(&root, code, stage, ms, reason, n));
458    let line = fault_line(code, stage, ms, reason, crash.as_deref());
459    n.say(&line);
460    if let Some(meaning) = code_meaning(code) {
461        n.say(&format!("{code}: {meaning}"));
462    }
463    match end_after(stage, since_last) {
464        End::Restart => {
465            n.say(&format!("{code}: the box was SERVING and its last fault is older than {} min — restarting, not powering off", RESTART_LOOP_WINDOW.as_secs() / 60));
466            restart_now()
467        }
468        End::PowerOff => power_off_now(),
469    }
470}
471
472/// How recent the previous fault must be for a fault on a SERVING box to count
473/// as a loop (and power off instead of restarting).
474pub const RESTART_LOOP_WINDOW: Duration = Duration::from_secs(30 * 60);
475
476/// How a fault ends the box.
477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
478pub enum End {
479    /// `sync` and reboot: the box comes back by itself.
480    Restart,
481    /// `sync` and power off: a person decides (see [`fault`]).
482    PowerOff,
483}
484
485/// **How a fault at `stage` ends, given how long ago the previous one was.**
486///
487/// During the boot a reboot is a reboot into the same fault — a loop that turns
488/// a fault into a mystery — so it powers off, as it always did. Once the box
489/// SERVES, a fault is one request task's panic or one listener's error, and
490/// powering off leaves the forge down until a person starts it, with nothing
491/// alerting anybody (finalization 2026-09-28, row h-panic-poweroff; UpCloud
492/// leaves a powered-off server stopped). So a serving box restarts — unless its
493/// previous fault was within [`RESTART_LOOP_WINDOW`], which is a loop again.
494/// `since_last_fault` is read off the crash record's mtime on `/data` (it
495/// survives the restart); `None` = no earlier record.
496pub fn end_after(stage: Stage, since_last_fault: Option<Duration>) -> End {
497    match (stage, since_last_fault) {
498        (Stage::Serving, None) => End::Restart,
499        (Stage::Serving, Some(d)) if d >= RESTART_LOOP_WINDOW => End::Restart,
500        _ => End::PowerOff,
501    }
502}
503
504/// `sync(2)` then `reboot(RB_AUTOBOOT)`, and park if the kernel refuses.
505pub fn restart_now() -> ! {
506    #[cfg(target_os = "linux")]
507    {
508        rustix::fs::sync();
509        let _ = rustix::system::reboot(rustix::system::RebootCommand::Restart);
510    }
511    loop {
512        std::thread::sleep(Duration::from_secs(3600));
513    }
514}
515
516/// `sync(2)` then `reboot(RB_POWER_OFF)`, and park if the kernel refuses.
517///
518/// A PID 1 that returns from `main` is `Attempted to kill init!` all over
519/// again, so the park is the last resort rather than the plan.
520pub fn power_off_now() -> ! {
521    #[cfg(target_os = "linux")]
522    {
523        // `sync(2)` first: the crash record and the two log appends above were
524        // fsync'd by their writers, but the box is about to lose power and
525        // anything else in flight has one chance.
526        rustix::fs::sync();
527        let _ = rustix::system::reboot(rustix::system::RebootCommand::PowerOff);
528    }
529    loop {
530        std::thread::sleep(Duration::from_secs(3600));
531    }
532}
533
534/// `sync(2)` then `reboot(RB_AUTOBOOT)`, and park if the kernel refuses — the
535/// restart a box restored from its twin owes (`twin::restart_after_restore`).
536pub fn reboot_now() -> ! {
537    #[cfg(target_os = "linux")]
538    {
539        rustix::fs::sync();
540        let _ = rustix::system::reboot(rustix::system::RebootCommand::Restart);
541    }
542    loop {
543        std::thread::sleep(Duration::from_secs(3600));
544    }
545}
546
547/// Write `<data>/crash/fault.txt`: the fault line, what the code means, and the
548/// narration that led to it. Best effort — the caller is on its way to a
549/// power-off and a failed write must not change that.
550fn write_crash_record(
551    root: &Path,
552    code: &str,
553    stage: Stage,
554    ms: u128,
555    reason: &str,
556    n: &Narrator,
557) -> Option<PathBuf> {
558    use std::io::Write as _;
559    let path = root.join(crate::slow::CRASH_DIR).join(CRASH_RECORD);
560    std::fs::create_dir_all(path.parent()?).ok()?;
561    let mut f = std::fs::File::create(&path).ok()?;
562    writeln!(f, "---- {} ----", fault_line(code, stage, ms, reason, None)).ok()?;
563    if let Some(meaning) = code_meaning(code) {
564        writeln!(f, "{code}: {meaning}").ok()?;
565    }
566    writeln!(f, "---- the boot narration up to this fault ----").ok()?;
567    if let Ok(m) = n.memory.lock() {
568        f.write_all(&m).ok()?;
569    }
570    f.sync_all().ok()?;
571    Some(path)
572}
573
574/// Append to `BOOTLOG.TXT` on the ESP, flipping `/boot` read-write for exactly
575/// one append and straight back — the same flip `korp-start` and the rollback
576/// floor make, and for the same reason: nothing may hold a writer open across
577/// a remount to read-only, which answers `EBUSY`.
578///
579/// Every failure is swallowed. A box with no ESP mounted (a container, a
580/// laptop, `gunnar-solo`) simply has no such reader.
581fn append_to_esp(bytes: &[u8]) {
582    if !Path::new(ESP_LOG).exists() {
583        return;
584    }
585    let flipped = remount(ESP_MOUNT, false).is_ok();
586    append_file(Path::new(ESP_LOG), bytes);
587    if flipped {
588        let _ = remount(ESP_MOUNT, true);
589    }
590}
591
592/// **Write one small file on the ESP** (a marker), `/boot` flipped read-write
593/// for exactly that write, the way [`append_to_esp`] flips it. `false` when it
594/// could not be written — the caller decides what that means.
595pub fn write_esp_file(path: &Path, bytes: &[u8]) -> bool {
596    use std::io::Write as _;
597    let flipped = remount(ESP_MOUNT, false).is_ok();
598    let written = std::fs::File::create(path).and_then(|mut f| f.write_all(bytes).and_then(|_| f.sync_all())).is_ok();
599    if flipped {
600        let _ = remount(ESP_MOUNT, true);
601    }
602    written
603}
604
605/// **Remove one small file from the ESP**, `/boot` flipped read-write for exactly that
606/// removal (the next boot's cleanup of a record [`write_esp_file`] left).
607pub fn remove_esp_file(path: &Path) -> bool {
608    let flipped = remount(ESP_MOUNT, false).is_ok();
609    let removed = std::fs::remove_file(path).is_ok();
610    if flipped {
611        let _ = remount(ESP_MOUNT, true);
612    }
613    removed
614}
615
616/// Open-append-fsync-close. No descriptor is held between lines, so the mount
617/// under it can go back to read-only immediately.
618fn append_file(path: &Path, bytes: &[u8]) {
619    use std::io::Write as _;
620    if let Ok(mut f) = std::fs::OpenOptions::new().append(true).create(true).open(path) {
621        let _ = f.write_all(bytes);
622        let _ = f.sync_all();
623    }
624}
625
626/// Flip a mountpoint between read-only and read-write in place.
627#[cfg(target_os = "linux")]
628fn remount(mountpoint: &str, readonly: bool) -> std::io::Result<()> {
629    use rustix::mount::{mount_remount, MountFlags};
630    let mut flags = MountFlags::NOSUID | MountFlags::NODEV | MountFlags::NOEXEC;
631    if readonly {
632        flags |= MountFlags::RDONLY;
633    }
634    mount_remount(mountpoint, flags, "").map_err(std::io::Error::from)
635}
636
637#[cfg(not(target_os = "linux"))]
638fn remount(_mountpoint: &str, _readonly: bool) -> std::io::Result<()> {
639    Ok(())
640}
641
642/// Seconds since the kernel started — the one clock `korp-start` and this
643/// process share, so their ticks and stamps sit on the same number line.
644pub fn uptime_s() -> u64 {
645    std::fs::read_to_string("/proc/uptime")
646        .ok()
647        .and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok())
648        .map(|f| f as u64)
649        .unwrap_or_default()
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655
656    /// ★ **A panic's crash record holds Gunnar's narration again** (lane L10,
657    /// appliance-pid1 0.1.5): edda's panic hook wrote `crash/fault.txt` with an
658    /// empty narration; `boot::install_panic_fault` now names the narrator's
659    /// memory to `fault::narration_from`, so the record carries every line the
660    /// narrator said, under the fault line, as `narrate::fault`'s own record does.
661    #[test]
662    fn a_panics_crash_record_holds_the_narrators_memory() {
663        static N: OnceLock<Narrator> = OnceLock::new();
664        let n = N.get_or_init(|| Narrator { t0: Instant::now(), stage: AtomicU8::new(Stage::Exec as u8), data: Mutex::new(None), memory: Mutex::new(Vec::new()) });
665        n.say("STAGE serving +812ms l10-crash-narration");
666        assert_eq!(n.memory(), b"gunnar: STAGE serving +812ms l10-crash-narration\r\n");
667        // Not installed in a test process: the global is empty, never a panic.
668        if NARRATOR.get().is_none() {
669            assert!(memory().is_empty());
670        }
671        // Gunnar's wiring: the hook's installer names `narrate::memory` …
672        let boot = include_str!("boot.rs");
673        let hook = &boot[boot.find("pub fn install_panic_fault").unwrap()..];
674        let hook = &hook[..hook.find("\n}\n").unwrap()];
675        assert!(hook.contains("appliance_pid1::fault::narration_from(crate::narrate::memory)"), "{hook}");
676        // … and what such a source answers is what the panic's record holds.
677        appliance_pid1::fault::narration_from(|| N.get().map(Narrator::memory).unwrap_or_default());
678        let d = tempfile::tempdir().unwrap();
679        let p = appliance_pid1::fault::PanicFault { code: "GN-99", meaning: "the app panicked", data: Some(d.path().to_path_buf()) };
680        appliance_pid1::fault::panic_ending(&p, "panicked at src/x.rs:1: boom", ("serving", true), 9);
681        let text = std::fs::read_to_string(d.path().join(appliance_pid1::fault::CRASH_DIR).join(appliance_pid1::fault::CRASH_RECORD)).unwrap();
682        assert!(text.contains("gunnar: STAGE serving +812ms l10-crash-narration"), "{text}");
683        assert!(text.contains("GN-99: the app panicked"), "{text}");
684        appliance_pid1::fault::narration_from(memory);
685    }
686
687    /// **A serving box that faults comes back by itself; a loop still stops.**
688    /// (finalization 2026-09-28, row h-panic-poweroff.) Until now every fault
689    /// powered the box off — right during the boot, where a reboot is a loop,
690    /// and wrong once it SERVES: one panic in one request task left the forge
691    /// down until a person started it, and nothing alerted. A second fault
692    /// within [`RESTART_LOOP_WINDOW`] of the last one is a loop and powers off,
693    /// exactly as before.
694    #[test]
695    fn a_serving_fault_restarts_the_box_unless_it_is_a_loop() {
696        assert_eq!(end_after(Stage::Serving, None), End::Restart, "the first fault of a serving box: back by itself");
697        assert_eq!(end_after(Stage::Serving, Some(RESTART_LOOP_WINDOW)), End::Restart, "the last fault is old: not a loop");
698        assert_eq!(end_after(Stage::Serving, Some(Duration::from_secs(60))), End::PowerOff, "a fault a minute after the last: a loop, stop");
699        for s in ORDER.iter().copied().filter(|s| *s != Stage::Serving) {
700            assert_eq!(end_after(s, None), End::PowerOff, "{s:?}: a fault during the boot reboots into the same fault — power off");
701        }
702    }
703
704    /// The tokens are a closed set, unique, and one word each — the ear
705    /// matches on them, so a token with a space in it is a token that splits.
706    #[test]
707    fn the_stage_tokens_are_unique_single_words() {
708        let mut seen: Vec<&str> = Vec::new();
709        for (i, s) in ORDER.iter().enumerate() {
710            assert_eq!(*s as usize, i, "the discriminant IS the index: the tick carries it as one byte");
711            assert!(!s.token().contains(' '), "{:?}", s.token());
712            assert!(!seen.contains(&s.token()), "two stages spell {}", s.token());
713            seen.push(s.token());
714        }
715    }
716
717    /// **The vocabulary parity check.** These spellings exist three times, in
718    /// three repositories with no dependency edge between them. If one drifts,
719    /// the ear stops matching and says nothing useful — which is the failure
720    /// this whole module exists to end. So the exact wire shapes are asserted
721    /// here, as literals, rather than built from the constants that would drift
722    /// with them.
723    #[test]
724    fn the_wire_shapes_are_exactly_what_the_ear_matches() {
725        assert_eq!(stage_line(Stage::Lease, 6_340, "eth1 10.13.9.24/22"), "STAGE lease +6340ms eth1 10.13.9.24/22");
726        assert_eq!(tick_line(Stage::Serving, 720), "TICK stage=serving up=720s");
727        assert_eq!(
728            fault_line("GN-04", Stage::Follow, 12_345, "the primary refused", Some(Path::new("/data/crash/fault.txt"))),
729            "FAULT GN-04 stage=follow +12345ms reason=the primary refused crash=/data/crash/fault.txt"
730        );
731        assert_eq!(ack_line("GN-99"), "ACK GN-99");
732    }
733
734    /// A fault is ONE line whatever the reason was — the twin's panic message
735    /// has three lines in it, and a fault that forged two more lines at every
736    /// reader would be a fault the ear judged as something else.
737    #[test]
738    fn a_fault_is_one_line_even_when_the_reason_is_not() {
739        let l = fault_line(
740            "GN-99",
741            Stage::Follow,
742            1,
743            "panicked at\nsrc/runtime/shutdown.rs:51:\nCannot drop a runtime",
744            None,
745        );
746        assert_eq!(l.lines().count(), 1, "{l}");
747        assert!(l.contains("Cannot drop a runtime"), "{l}");
748        // The field is stated as absent rather than omitted: a field that
749        // sometimes disappears is a field the ear has to guess at.
750        assert!(l.ends_with(" crash=-"), "{l}");
751    }
752
753    /// **Every death path has a code.** An `Err` at any stage maps to one of
754    /// the declared codes — never `GN-99`, which is the panic's and would make
755    /// a refused configuration read as a crash — and the four boot codes are
756    /// each reachable from the boundary they sit behind.
757    #[test]
758    fn an_err_at_every_stage_carries_a_declared_code_that_is_not_the_panics() {
759        for s in ORDER {
760            let code = code_after(s);
761            assert!(code_meaning(code).is_some(), "{code} for {:?} is not declared", s);
762            assert_ne!(code, "GN-99", "an ordinary Err at {:?} is not a panic", s);
763        }
764        assert_eq!(code_after(Stage::Exec), "GN-01", "nothing read yet: the configuration");
765        assert_eq!(code_after(Stage::Config), "GN-02", "config read; the next boundary is a bound listener");
766        assert_eq!(code_after(Stage::Sink), "GN-02");
767        assert_eq!(code_after(Stage::Listener), "GN-03", "bound; the next boundary is the role");
768        assert_eq!(code_after(Stage::Role), "GN-04", "role taken; a twin follows next");
769        assert_eq!(code_after(Stage::Follow), "GN-04");
770        assert_eq!(code_after(Stage::Serving), "GN-05", "up, and the serve loop returned an error");
771        assert_eq!(
772            [code_after(Stage::Exec), code_after(Stage::Config), code_after(Stage::Listener), code_after(Stage::Role)],
773            ["GN-01", "GN-02", "GN-03", "GN-04"],
774            "the four boot codes are all reachable"
775        );
776    }
777
778    /// The acknowledgement matches its own code and nothing else's.
779    #[test]
780    fn an_ack_matches_its_code_and_only_its_code() {
781        assert!(ack_matches(b"ACK GN-99", "GN-99"));
782        assert!(ack_matches(b"ACK GN-99 heard\n", "GN-99"), "an ear may say more");
783        assert!(!ack_matches(b"ACK GN-01", "GN-99"));
784        assert!(!ack_matches(b"GN-99", "GN-99"), "a bare code is not an ack");
785        assert!(!ack_matches(b"NACK GN-99", "GN-99"));
786    }
787
788    /// Every code is unique, shaped the way a matcher expects, and means
789    /// something. A rung refuses BY these, so they are a contract.
790    #[test]
791    fn the_fault_codes_are_unique_and_stable_shaped() {
792        let mut seen: Vec<&str> = Vec::new();
793        for (c, meaning) in CODES {
794            assert!(c.len() == 5 && c.as_bytes()[2] == b'-', "a code is XX-NN: {c}");
795            assert!(!seen.contains(&c), "two faults spell {c}");
796            assert!(!meaning.is_empty());
797            assert_eq!(code_meaning(c), Some(meaning));
798            seen.push(c);
799        }
800        assert_eq!(code_meaning("ZZ-99"), None);
801    }
802}