Skip to main content

taskfleet_core/
reducer.rs

1//! Event → projection reducer (design.md §1.4).
2//!
3//! Each event mutates zero or more projection files. Unknown kinds are
4//! ignored for forward compatibility. The reducer expects to run under the
5//! per-run `flock`.
6//!
7//! Idempotency contract (per design.md §7.3 at-least-once delivery):
8//! `*.created` reducers short-circuit when their projection file already
9//! exists; status/resolution reducers are no-ops once the terminal state
10//! has been reached. Replaying the same event stream against existing
11//! projections is therefore a clean no-op-or-apply.
12//!
13//! This idempotence is load-bearing for the `applied_seq` watermark
14//! (append-then-apply atomicity; see [`crate::schema::Manifest::applied_seq`]
15//! and [`crate::events::append_and_apply_event`]). Of the two options the spec
16//! offered — make the reducer idempotent, OR have the writer skip events
17//! already reflected in the projection — we chose **idempotent reducer**: the
18//! existence/terminal guards already present here mean the catch-up replay can
19//! re-fold *any* tail event (one whose projection landed before a crash, or one
20//! whose projection did not) with the same no-op-or-apply outcome, so the
21//! writer needs no per-event "already applied?" probe. The watermark advances
22//! only after an event's projections are fsynced, so it can lag the projections
23//! but never lead them.
24//!
25//! ## Manifest counters are derived, not folded
26//!
27//! The reducers here deliberately do **not** touch the manifest's denormalized
28//! `node_count` counter. It is
29//! recomputed from the projection directories by
30//! [`derive_counters`](crate::projections), invoked from
31//! [`advance_applied_seq`](crate::events) at the
32//! watermark advance. An earlier design incremented/decremented them inside
33//! these reducers, but a crash between a projection write and the follow-on
34//! `manifest.json` write could permanently desync them: the replay re-folded
35//! the event, hit the `*.created`/terminal idempotency guard above, and skipped
36//! the counter mutation that never actually landed. Deriving the counts makes
37//! drift impossible — there is no delta to lose. See issue
38//! `manifest-counter-desync`. A count-affecting reducer still emits its manifest
39//! op to refresh `updated_at`; the counter fields it carries are overwritten by
40//! the derive step.
41//!
42//! Because a count-affecting event rewrites a projection file *and* the
43//! manifest counter under the same exclusive `flock`, a reader that scans both
44//! together must hold the shared `flock` (`LOCK_SH`) for the whole scan or it
45//! could see the projection change without the matching counter (or vice
46//! versa). See [`crate::projections`] and design.md §4.
47
48use std::path::{Path, PathBuf};
49
50use jiff::Timestamp;
51use serde_json::Value;
52
53mod ask;
54use ask::cancel_open_ask;
55pub use ask::{
56    valid_ask_key, valid_ask_option, valid_ask_text, MAX_ASK_ANSWER_BYTES, MAX_ASK_DEFAULT_BYTES,
57    MAX_ASK_KEY_CHARS, MAX_ASK_NOTE_BYTES, MAX_ASK_OPTIONS, MAX_ASK_OPTION_CHARS,
58    MAX_ASK_QUESTION_BYTES, MAX_ASK_TIMEOUT_SECS,
59};
60
61use crate::error::{Error, Result};
62use crate::paths::RunPaths;
63use crate::projections::{read_manifest_opt, read_node_opt, write_manifest, write_node};
64use crate::report::ReportOrigin;
65use crate::schema::{
66    CallerPiLifecycle, CallerPiSession, CallerPiState, CallerSettlementIntent, ChildRef, Event,
67    EvidenceStatus, IdValidationError, Kind, Lifecycle, Manifest, MergeTxn, Node, NodeId,
68    ResidentPolicy, RoundLanding, RoundReport, RunId, Status, TmuxIdentity, WorkerEvidence,
69    WorkerExit, STATE_SCHEMA_VERSION,
70};
71
72/// Map an id-validation failure on an event-sourced id to a [`CorruptEventLog`]
73/// error. An id that fails to parse here came off `events.jsonl` (or a forged
74/// event), so the log — not the caller — is the corrupt party.
75///
76/// [`CorruptEventLog`]: Error::CorruptEventLog
77fn corrupt_id(events_path: &Path, ev: &Event, e: &IdValidationError) -> Error {
78    Error::CorruptEventLog {
79        path: events_path.to_path_buf(),
80        reason: format!("event seq={} kind={}: {e}", ev.seq, ev.kind),
81    }
82}
83
84/// Parse an optional `RunId` from event-data field `field`: missing/null →
85/// `None`; a JSON string → validated `Some(RunId)`; a malformed id or a
86/// non-string value → [`Error::CorruptEventLog`].
87fn opt_run_id(events_path: &Path, ev: &Event, d: &Value, field: &str) -> Result<Option<RunId>> {
88    match d.get(field) {
89        None | Some(Value::Null) => Ok(None),
90        Some(Value::String(s)) => RunId::parse_str(s)
91            .map(Some)
92            .map_err(|e| corrupt_id(events_path, ev, &e)),
93        Some(_) => Err(Error::CorruptEventLog {
94            path: events_path.to_path_buf(),
95            reason: format!(
96                "event seq={} kind={} `{field}` must be a JSON string or null",
97                ev.seq, ev.kind
98            ),
99        }),
100    }
101}
102
103/// Parse an optional `NodeId` from event-data field `field`. See [`opt_run_id`].
104fn opt_node_id(events_path: &Path, ev: &Event, d: &Value, field: &str) -> Result<Option<NodeId>> {
105    match d.get(field) {
106        None | Some(Value::Null) => Ok(None),
107        Some(Value::String(s)) => NodeId::parse_str(s)
108            .map(Some)
109            .map_err(|e| corrupt_id(events_path, ev, &e)),
110        Some(_) => Err(Error::CorruptEventLog {
111            path: events_path.to_path_buf(),
112            reason: format!(
113                "event seq={} kind={} `{field}` must be a JSON string or null",
114                ev.seq, ev.kind
115            ),
116        }),
117    }
118}
119
120/// Parse a `kind` value from event `data` for a NEW append, failing closed on
121/// anything not a live, creatable kind.
122///
123/// `Kind`'s `#[serde(other)]` catch-all means every unrecognized string —
124/// a removed kind (`code`, `orchestrate`, …), a typo, or a future kind —
125/// deserializes to [`Kind::Unknown`] rather than erroring. That read-only
126/// catch-all exists so `run list` / `doctor` can decode a legacy on-disk run
127/// (ADR §D7); it must NOT let a garbage `kind` slip through the append gate as
128/// though it were valid. Mapping `Unknown` back to `None` keeps the reducer's
129/// `run.created` / `node.created` / `child.spawned` validation fail-closed, as
130/// it was before the 0.2 cut added the catch-all. (Legacy runs are never
131/// re-created through this path — their manifest/nodes already exist on disk and
132/// are read directly, not replayed from a fresh `*.created`.)
133fn data_kind(v: &Value) -> Option<Kind> {
134    match serde_json::from_value::<Kind>(v.clone()) {
135        Ok(Kind::Unknown) | Err(_) => None,
136        Ok(k) => Some(k),
137    }
138}
139
140fn data_status(v: &Value) -> Option<Status> {
141    serde_json::from_value(v.clone()).ok()
142}
143
144fn require_status(ev: &Event, path: PathBuf) -> Result<Status> {
145    data_status(ev.data.get("status").unwrap_or(&Value::Null)).ok_or_else(|| {
146        Error::CorruptEventLog {
147            path,
148            reason: format!("{} missing/invalid `status`", ev.kind),
149        }
150    })
151}
152
153fn want_str<'a>(events_path: &Path, ev: &Event, d: &'a Value, field: &str) -> Result<&'a str> {
154    d.get(field)
155        .and_then(Value::as_str)
156        .ok_or_else(|| Error::CorruptEventLog {
157            path: events_path.to_path_buf(),
158            reason: format!(
159                "event seq={} kind={} missing `{field}` string field",
160                ev.seq, ev.kind
161            ),
162        })
163}
164
165/// Read an optional boolean field with strict typing: missing/null → `None`,
166/// JSON bool → `Some(b)`, anything else → `CorruptEventLog`. Mirrors
167/// [`optional_str`] / [`optional_i32`]; prevents a non-boolean `success` /
168/// `cancelled` from being silently coerced to `false` and bypassing the
169/// success-XOR-cancelled invariant.
170fn optional_bool(events_path: &Path, ev: &Event, d: &Value, field: &str) -> Result<Option<bool>> {
171    match d.get(field) {
172        None | Some(Value::Null) => Ok(None),
173        Some(Value::Bool(b)) => Ok(Some(*b)),
174        Some(_) => Err(Error::CorruptEventLog {
175            path: events_path.to_path_buf(),
176            reason: format!(
177                "event seq={} kind={} `{field}` must be a JSON boolean or null",
178                ev.seq, ev.kind
179            ),
180        }),
181    }
182}
183
184fn optional_i32(d: &Value, field: &str, events_path: &Path, ev: &Event) -> Result<Option<i32>> {
185    match d.get(field) {
186        None | Some(Value::Null) => Ok(None),
187        Some(v) => {
188            let raw = v.as_i64().ok_or_else(|| Error::CorruptEventLog {
189                path: events_path.to_path_buf(),
190                reason: format!(
191                    "event seq={} kind={} `{field}` must be integer",
192                    ev.seq, ev.kind
193                ),
194            })?;
195            i32::try_from(raw)
196                .map(Some)
197                .map_err(|_| Error::CorruptEventLog {
198                    path: events_path.to_path_buf(),
199                    reason: format!(
200                        "event seq={} kind={} `{field}` out of i32 range: {raw}",
201                        ev.seq, ev.kind
202                    ),
203                })
204        }
205    }
206}
207
208fn optional_ts(
209    d: &Value,
210    field: &str,
211    events_path: &Path,
212    ev: &Event,
213) -> Result<Option<Timestamp>> {
214    match d.get(field) {
215        None | Some(Value::Null) => Ok(None),
216        Some(Value::String(s)) => {
217            s.parse::<Timestamp>()
218                .map(Some)
219                .map_err(|_| Error::CorruptEventLog {
220                    path: events_path.to_path_buf(),
221                    reason: format!(
222                        "event seq={} kind={} `{field}` not RFC3339",
223                        ev.seq, ev.kind
224                    ),
225                })
226        }
227        Some(_) => Err(Error::CorruptEventLog {
228            path: events_path.to_path_buf(),
229            reason: format!(
230                "event seq={} kind={} `{field}` must be RFC3339 string or null",
231                ev.seq, ev.kind
232            ),
233        }),
234    }
235}
236
237/// A projection write planned by [`reduce_event_to_ops`] and performed by
238/// [`commit_ops`].
239///
240/// Splitting the reducer into a pure *plan* phase (compute these ops from the
241/// current projection state, validating as it goes) and a *commit* phase
242/// (write them) means a single branch per kind implements both the pre-append
243/// validation gate and the post-append apply — there is no validate/apply
244/// mirror to drift out of lockstep, and the projection state is read once
245/// rather than twice.
246// Both variants are short-lived values in the locked reducer plan; boxing
247// each node would add allocation to every event for a small size difference.
248#[allow(clippy::large_enum_variant)]
249pub(crate) enum ProjectionOp {
250    /// Write the run manifest.
251    Manifest(Manifest),
252    /// Write a node projection.
253    Node(Node),
254}
255
256/// Commit a planned batch of projection writes, in order.
257///
258/// Caller must hold the run's [`crate::lock::RunLock`]. Pairs with
259/// [`reduce_event_to_ops`]: the ops were computed against the same locked
260/// state, and nothing mutates the projections between the plan and this commit
261/// (in the append path only `events.jsonl` is written in between), so the
262/// planned writes are still valid.
263pub(crate) fn commit_ops(paths: &RunPaths, ops: Vec<ProjectionOp>) -> Result<()> {
264    for op in ops {
265        match op {
266            ProjectionOp::Manifest(m) => write_manifest(paths, &m)?,
267            ProjectionOp::Node(n) => write_node(paths, &n)?,
268        }
269    }
270    Ok(())
271}
272
273/// Plan the projection writes one event implies, *without* performing them.
274///
275/// This is the single source of truth for both validation and application: it
276/// reads the current projection state, enforces every event-payload invariant
277/// (returning [`Error::CorruptEventLog`] for a malformed or cross-run event),
278/// and returns the exact [`ProjectionOp`]s to commit (empty for a no-op or an
279/// unknown `kind`). Because it never writes, it is also the transactional gate
280/// run *before* the durable append in
281/// [`crate::events::append_and_apply_unlocked`]: a reducer-rejected event is
282/// caught here and never reaches `events.jsonl`, so a later replay /
283/// `rebuild_projections` can't trip over a poison line. The state-dependent
284/// no-op guards live here too (a settled node/run/discussion swallows a late
285/// or even malformed event as a clean no-op rather than erroring).
286///
287/// Caller must hold the run's [`crate::lock::RunLock`].
288pub(crate) fn reduce_event_to_ops(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
289    // An event whose envelope `run_id` doesn't match the run we're folding it
290    // into means the log was copied/misrouted — folding it would silently
291    // cross-contaminate projections. Reject before planning anything.
292    if ev.run_id != paths.run_id {
293        return Err(Error::CorruptEventLog {
294            path: paths.events(),
295            reason: format!(
296                "event seq={} envelope run_id {:?} does not match run {:?}",
297                ev.seq,
298                ev.run_id.as_str(),
299                paths.run_id.as_str()
300            ),
301        });
302    }
303    // Each event kind is listed explicitly as documentation of the known set;
304    // `supervisor.exited` and the `_` fallthrough share a body intentionally.
305    #[allow(clippy::match_same_arms)]
306    match ev.kind.as_str() {
307        "run.created" => reduce_run_created(paths, ev),
308        "run.status" => reduce_run_status(paths, ev),
309        "node.created" => reduce_node_created(paths, ev),
310        "node.status" => reduce_node_status(paths, ev),
311        "node.report" => reduce_node_report(paths, ev),
312        "node.retry" => reduce_node_retry(paths, ev),
313        "caller.pi.session_bound" => reduce_caller_pi_session_bound(paths, ev),
314        "caller.pi.lifecycle" => reduce_caller_pi_lifecycle(paths, ev),
315        "caller.settlement_intent" => reduce_caller_settlement_intent(paths, ev),
316        "worker.exited" => reduce_worker_exited(paths, ev),
317        "worker.evidence.archived" => reduce_worker_evidence_archived(paths, ev),
318        "worker.evidence.failed" => reduce_worker_evidence_failed(paths, ev),
319        "worker.display.retained" => reduce_worker_display_retained(paths, ev),
320        "worker.display.expired" => reduce_worker_display_expired(paths, ev),
321        "worker.display.unavailable" => reduce_worker_display_unavailable(paths, ev),
322        "node.death_observed" => reduce_node_death_observed(paths, ev),
323        "node.awaiting_input" => reduce_node_awaiting_input(paths, ev),
324        "node.input_resolved" => reduce_node_input_resolved(paths, ev),
325        "node.round_reported" => reduce_node_round_reported(paths, ev),
326        "node.asked" => ask::reduce_node_asked(paths, ev),
327        "node.ask_escalated" => ask::reduce_node_ask_escalated(paths, ev),
328        "node.answered" => ask::reduce_node_answered(paths, ev),
329        "node.ask_timed_out" => ask::reduce_node_ask_timed_out(paths, ev),
330        "node.resumed" => reduce_node_resumed(paths, ev),
331        "node.round_landed" => reduce_node_round_landed(paths, ev),
332        "node.resident_dormant" => reduce_node_resident_dormant(paths, ev),
333        "node.resident_attention" => reduce_node_resident_attention(paths, ev),
334        KIND_MERGE_STARTED => reduce_merge_started(paths, ev),
335        KIND_MERGE_ABORTED => reduce_merge_aborted(paths, ev),
336        "child.spawned" => reduce_child_spawned(paths, ev),
337        "supervisor.attached" => reduce_supervisor_attached(paths, ev),
338        "supervisor.cursor_advanced" => reduce_supervisor_cursor_advanced(paths, ev),
339        "supervisor.exited" => Ok(vec![]),
340        // Append-only audit records from `/orchestrate` (decision log +
341        // pakkopysäytys). They mutate no projection — the event log is their
342        // canonical home — so they fold to a clean no-op. Listed explicitly
343        // (rather than relying on the `_` fallthrough) so the append path's
344        // transactional gate runs the same no-op plan for them and the intent
345        // is documented at the match site. They are NOT `node.report`, so the
346        // supervisor never mistakes them for a terminal signal.
347        "orchestrator.decision" | "discuss.critical" => Ok(vec![]),
348        // At-most-once marker the supervisor appends the first time a run is
349        // observed terminal, gating the `run create --notify` completion hook so
350        // a restart never re-fires it (issue `no-completion-notification-to-parent`).
351        // Mutates no projection — the event log is its only home — so it folds to
352        // a clean no-op. Listed explicitly so the append path's transactional gate
353        // runs the same no-op plan and the intent is documented here.
354        "run.notified" | "run.awaiting_input_notified" | "run.round_notified" => Ok(vec![]),
355        // Best-effort teardown audit records from the supervisor's cleanup
356        // path. Each mutates no projection — the event log is their only home —
357        // so they fold to a clean no-op. Listed explicitly so the append path's
358        // transactional gate runs the same no-op plan and the intent is
359        // documented here.
360        //   - `cleanup.window_missing`: the node's tmux window could not be
361        //     located to close it (typically a manually-resolved rebase renamed
362        //     the window — issue `worktree-merge-orphans-tmux-window`).
363        //   - `cleanup.worktree_missing`: the worktree dir was already gone at
364        //     teardown (e.g. removed manually), so nothing to `worktree remove`.
365        //   - `cleanup.branch_remove_failed`: `git branch -{d,D}` refused (e.g.
366        //     unmerged commits, or the branch is already gone); the run completes
367        //     anyway (issue `supervisor-worktree-remove-no-force`).
368        //   - `cleanup.branch_preserved`: a BLOCKED terminal report
369        //     (`success: false`, no explicit merge) intentionally left the branch
370        //     and worktree in place for the human to pick up, instead of tearing
371        //     them down (issue `blocked-report-deletes-branch`).
372        //   - `cleanup.session_killed`: the run's managed `--headless` tmux
373        //     session was torn down once its last managed window was gone, so an
374        //     empty session is not left behind (issue
375        //     `headless-tmux-session-not-torn-down`).
376        //   - `cleanup.session_retained`: the same teardown was skipped because a
377        //     human had attached to the session — never yanked out from under
378        //     them.
379        "cleanup.window_missing"
380        | "cleanup.worktree_missing"
381        | "cleanup.branch_remove_failed"
382        | "cleanup.branch_preserved"
383        | "cleanup.discard_authorized"
384        | "cleanup.session_killed"
385        | "cleanup.session_retained" => Ok(vec![]),
386        // Data-integrity audit record: the supervisor found a persisted child
387        // run id (in `supervisor.state.json`'s `spawned_children`) that fails
388        // `RunId` structural validation and quarantined it — a corrupt id that
389        // would otherwise resolve with `.ok()` and be silently skipped every
390        // tick, indistinguishable from a child that completed and was torn down
391        // (issue `wildly-glorious-food`). It mutates no projection — the event
392        // log is its only home — so it folds to a clean no-op. Listed
393        // explicitly so the append path's transactional gate runs the same
394        // no-op plan and the intent is documented here.
395        "supervisor.child_id_quarantined" => Ok(vec![]),
396        _ => Ok(vec![]),
397    }
398}
399
400/// The projection file [`commit_ops`] writes for `op`, keyed exactly as the
401/// `write_*` helpers key it internally. Shared by [`plan_projections`] (which
402/// reports the path) and conceptually by [`commit_ops`] (which writes it), so
403/// the enumerated path list can never name a different file than the one the
404/// reducer actually fsyncs.
405fn op_path(paths: &RunPaths, op: &ProjectionOp) -> PathBuf {
406    match op {
407        ProjectionOp::Manifest(_) => paths.manifest(),
408        ProjectionOp::Node(n) => paths.node(&n.node_id),
409    }
410}
411
412/// Enumerate the projection files the reducer would write for `event`, in the
413/// order `commit_ops` would write them, *without* performing any write.
414///
415/// This is the single source of truth that ends the CLI/reducer divergence the
416/// `projected-paths-into-reducer` issue describes: rather than a hand-maintained
417/// list in `taskfleet` that drifts whenever a new projection is added, both the
418/// reducer and a caller's preflight (`event create --dry-run`) read the *same*
419/// `reduce_event_to_ops` plan. This function maps that plan to file paths;
420/// `apply_event` commits it. A new projection added to a reducer arm is
421/// therefore reflected here automatically.
422///
423/// Because it runs the real reducer plan against current projection state, the
424/// result is exact, not a guess: a state-dependent no-op (a settled node, an
425/// already-created projection, a terminal-guarded transition) yields an empty
426/// list — precisely the files `apply_event` would touch, which is none. A
427/// malformed-payload event surfaces the same [`Error::CorruptEventLog`] the
428/// real apply would, so a dry-run preflight cannot report success for an event
429/// the write path would reject.
430///
431/// Caller should hold the run's [`crate::lock::RunLock`] for a snapshot
432/// consistent with a concurrent reducer; a lock-free read is best-effort.
433pub fn plan_projections(paths: &RunPaths, event: &Event) -> Result<Vec<PathBuf>> {
434    let ops = reduce_event_to_ops(paths, event)?;
435    Ok(ops.iter().map(|op| op_path(paths, op)).collect())
436}
437
438/// Apply one event to projections: plan via [`reduce_event_to_ops`], then
439/// [`commit_ops`]. No-op for unknown `kind`. Caller must hold the run's
440/// [`crate::lock::RunLock`].
441///
442/// Shares the one [`reduce_event_to_ops`] plan with [`plan_projections`]: the
443/// paths that function reports are exactly the files this one fsyncs, because
444/// both consume the same `ProjectionOp` vector (this commits it; that maps it to
445/// paths via [`op_path`]).
446///
447/// `pub(crate)`: applying an event in isolation (without the matching
448/// `events.jsonl` append) is an internal building block used by `cancel` (to
449/// re-fold a crash-stranded event) and a future `rebuild_projections_from_events`.
450/// External callers mutate state through
451/// [`crate::events::append_and_apply_event`] so the log and projections can
452/// never diverge.
453pub(crate) fn apply_event(paths: &RunPaths, ev: &Event) -> Result<()> {
454    let ops = reduce_event_to_ops(paths, ev)?;
455    commit_ops(paths, ops)
456}
457
458/// Validate one persisted event through the normal reducer plan without
459/// committing projection writes. It performs the same checks as projection
460/// application and then discards the planned writes. Migration preflight uses
461/// this under the run's exclusive lock so it never invents a second
462/// event-payload validator.
463pub fn validate_event(paths: &RunPaths, ev: &Event) -> Result<()> {
464    reduce_event_to_ops(paths, ev).map(|_| ())
465}
466
467/// The envelope `node_id` that a `node.*` event must carry, with the same
468/// `CorruptEventLog` message `apply_*` produces. Shared by validate/apply so
469/// the missing-id check can't drift between them.
470fn require_envelope_node_id(events_path: &Path, ev: &Event) -> Result<NodeId> {
471    ev.node_id.clone().ok_or_else(|| Error::CorruptEventLog {
472        path: events_path.to_path_buf(),
473        reason: format!(
474            "event seq={} kind={} missing top-level `node_id`",
475            ev.seq, ev.kind
476        ),
477    })
478}
479
480fn reduce_run_created(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
481    // Idempotent: a replayed `run.created` against an existing manifest is a
482    // no-op (but validates that `run_id` matches; otherwise the event log
483    // is being applied to the wrong run).
484    if let Some(existing) = read_manifest_opt(paths)? {
485        if existing.run_id != ev.run_id {
486            return Err(Error::CorruptEventLog {
487                path: paths.manifest(),
488                reason: format!(
489                    "run.created run_id={} conflicts with existing manifest run_id={}",
490                    ev.run_id, existing.run_id
491                ),
492            });
493        }
494        return Ok(vec![]);
495    }
496    let events_path = paths.events();
497    let d = &ev.data;
498    let kind =
499        data_kind(d.get("kind").unwrap_or(&Value::Null)).ok_or_else(|| Error::CorruptEventLog {
500            path: events_path.clone(),
501            reason: "run.created missing/invalid `kind`".into(),
502        })?;
503    let lifecycle: Lifecycle = serde_json::from_value(
504        d.get("lifecycle").cloned().unwrap_or(Value::Null),
505    )
506    .map_err(|_| Error::CorruptEventLog {
507        path: events_path.clone(),
508        reason: "run.created missing/invalid `lifecycle`".into(),
509    })?;
510    let title = want_str(&events_path, ev, d, "title")?.to_string();
511    let agent_selection: Option<crate::schema::AgentSelection> = d
512        .get("agent_selection")
513        .cloned()
514        .map(serde_json::from_value)
515        .transpose()
516        .map_err(|e| Error::CorruptEventLog {
517            path: events_path.clone(),
518            reason: format!("run.created invalid `agent_selection`: {e}"),
519        })?;
520    if let Some(selection) = &agent_selection {
521        selection
522            .validate()
523            .map_err(|reason| Error::CorruptEventLog {
524                path: events_path.clone(),
525                reason: format!("run.created invalid `agent_selection`: {reason}"),
526            })?;
527    }
528    let m = Manifest {
529        schema_version: STATE_SCHEMA_VERSION,
530        // Created at the watermark floor; the append path advances it to this
531        // event's `seq` (after the manifest is fsynced) in `advance_applied_seq`.
532        applied_seq: 0,
533        // `run_id == paths.run_id` was verified at `reduce_event_to_ops` entry.
534        run_id: paths.run_id.clone(),
535        kind,
536        lifecycle,
537        caller_settlement_intent: None,
538        agent_owner: d
539            .get("agent_owner")
540            .cloned()
541            .map(serde_json::from_value)
542            .transpose()
543            .map_err(|e| Error::CorruptEventLog {
544                path: events_path.clone(),
545                reason: format!("run.created invalid agent_owner: {e}"),
546            })?
547            .unwrap_or_default(),
548        title,
549        status: Status::Pending,
550        created_at: ev.ts,
551        updated_at: ev.ts,
552        source_repo: d
553            .get("source_repo")
554            .and_then(Value::as_str)
555            .map(str::to_string),
556        source_branch: d
557            .get("source_branch")
558            .and_then(Value::as_str)
559            .map(str::to_string),
560        worktree_root: d
561            .get("worktree_root")
562            .and_then(Value::as_str)
563            .map(str::to_string),
564        managed_tmux_session: d
565            .get("managed_tmux_session")
566            .and_then(Value::as_str)
567            .map(str::to_string),
568        tmux_retention: retention_policy_from_data(&events_path, d)?,
569        notify_cmd: d
570            .get("notify_cmd")
571            .and_then(Value::as_str)
572            .map(str::to_string),
573        harness: d.get("harness").and_then(Value::as_str).map(str::to_string),
574        agent_selection,
575        node_count: 0,
576        created_by_run_id: opt_run_id(&events_path, ev, d, "created_by_run_id")?,
577        created_by_session: serde_json::from_value(
578            d.get("created_by_session").cloned().unwrap_or(Value::Null),
579        )
580        .map_err(|e| Error::CorruptEventLog {
581            path: events_path.clone(),
582            reason: format!("run.created invalid `created_by_session`: {e}"),
583        })?,
584        parent_run_id: opt_run_id(&events_path, ev, d, "parent_run_id")?,
585        parent_node_id: opt_node_id(&events_path, ev, d, "parent_node_id")?,
586        resident: resident_policy_from_data(&events_path, ev, d)?,
587    };
588    Ok(vec![ProjectionOp::Manifest(m)])
589}
590
591fn reduce_run_status(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
592    let mut m = match read_manifest_opt(paths)? {
593        Some(m) => m,
594        None => return Ok(vec![]),
595    };
596    let new_status = require_status(ev, paths.events())?;
597    // Terminal-state guard with one narrow recovery: Failed -> Done is allowed
598    // only when this event names an authoritative merge report that was already
599    // adopted by the log-derived node fold before this event, every own node is
600    // now Done, and the supervisor attests that every linked child is Done.
601    // Cancelled (and every other terminal transition) remains immutable.
602    if m.status.is_terminal() {
603        let recovery_seq = ev
604            .data
605            .get("recovery_merge_report_seq")
606            .and_then(Value::as_u64);
607        let children_successful =
608            ev.data.get("children_successful").and_then(Value::as_bool) == Some(true);
609        let recovery_allowed = m.status == Status::Failed
610            && new_status == Status::Done
611            && children_successful
612            && recovery_seq.is_some_and(|wanted| {
613                crate::cancel::read_node_status_facts(paths, Some(ev.seq))
614                    .ok()
615                    .filter(|facts| {
616                        crate::aggregate_terminal_status(facts.iter().map(|fact| fact.status))
617                            == Some(Status::Done)
618                    })
619                    .is_some_and(|facts| {
620                        facts
621                            .iter()
622                            .any(|fact| fact.confirmed_merge_seq == Some(wanted))
623                    })
624            });
625        if !recovery_allowed {
626            trace_terminal_noop(ev, m.status, new_status);
627            return Ok(vec![]);
628        }
629    }
630    if m.status == new_status {
631        return Ok(vec![]);
632    }
633    m.status = new_status;
634    m.updated_at = ev.ts;
635    Ok(vec![ProjectionOp::Manifest(m)])
636}
637
638/// Reconstruct the fully-qualified tmux identity from `node.created` event
639/// data. Returns `Some` only when both `tmux_session` and `tmux_window_id` are
640/// present and non-empty — the minimum needed to match a window. `tmux_socket`
641/// is optional (a default-socket spawn may emit null); an empty socket is
642/// normalized to `None` so the watchdog never invokes `tmux -S ""`.
643/// `tmux_pane_id` is likewise optional (create.sh predating it emits nothing);
644/// agent-log capture falls back to the window's active pane when absent. Legacy
645/// events from a create.sh that predates the qualified fields (or that emit a
646/// partial/empty identity) yield `None`, so the node falls back to bare-name
647/// matching on `tmux_window`.
648fn retention_policy_from_data(
649    events_path: &Path,
650    data: &Value,
651) -> Result<Option<Box<crate::schema::TmuxRetentionPolicy>>> {
652    let Some(value) = data.get("tmux_retention") else {
653        return Ok(None);
654    };
655    let policy: crate::schema::TmuxRetentionPolicy = serde_json::from_value(value.clone())
656        .map_err(|e| Error::CorruptEventLog {
657            path: events_path.to_path_buf(),
658            reason: format!("run.created invalid `tmux_retention`: {e}"),
659        })?;
660    if !policy.persistent
661        || policy.completed_window_ttl_secs == 0
662        || policy.completed_window_max == 0
663    {
664        return Err(Error::CorruptEventLog {
665            path: events_path.to_path_buf(),
666            reason: "run.created tmux_retention must be persistent with positive ttl/max".into(),
667        });
668    }
669    Ok(Some(Box::new(policy)))
670}
671
672fn tmux_identity_from_data(d: &Value) -> Option<TmuxIdentity> {
673    let nonempty = |key| {
674        d.get(key)
675            .and_then(Value::as_str)
676            .map(str::trim)
677            .filter(|s| !s.is_empty())
678            .map(str::to_string)
679    };
680    let session = nonempty("tmux_session")?;
681    let window_id = nonempty("tmux_window_id")?;
682    Some(TmuxIdentity {
683        socket: nonempty("tmux_socket"),
684        session,
685        window_id,
686        // Optional: create.sh predating the field (or a failed pane query)
687        // emits no `tmux_pane_id`; capture then falls back to `window_id`.
688        pane_id: nonempty("tmux_pane_id"),
689        server_pid: d
690            .get("tmux_server_pid")
691            .and_then(Value::as_u64)
692            .and_then(|value| u32::try_from(value).ok()),
693        server_pid_start_secs: d.get("tmux_server_pid_start_secs").and_then(Value::as_u64),
694        server_pid_start_identity: nonempty("tmux_server_pid_start_identity"),
695        server_marker: nonempty("tmux_server_marker"),
696    })
697}
698
699/// The agent's kernel start identity from spawn event data. Absent, empty, or
700/// non-string values (events written before the field existed) yield `None`,
701/// which keeps the seconds-only legacy comparison for that node.
702fn start_identity_from_data(d: &Value) -> Option<String> {
703    d.get("agent_pid_start_identity")
704        .and_then(Value::as_str)
705        .filter(|s| !s.is_empty())
706        .map(str::to_string)
707}
708
709fn worker_evidence_from_spawn_data(
710    events_path: &Path,
711    ev: &Event,
712    data: &Value,
713) -> Result<Option<WorkerEvidence>> {
714    let Some(session_id) = data.get("pi_session_id") else {
715        if data.get("pi_session_path").is_some() || data.get("pi_session_cwd").is_some() {
716            return Err(Error::CorruptEventLog {
717                path: events_path.to_path_buf(),
718                reason: format!(
719                    "event seq={} Pi evidence fields must be all-or-none",
720                    ev.seq
721                ),
722            });
723        }
724        return Ok(None);
725    };
726    if session_id.is_null() {
727        if data
728            .get("pi_session_path")
729            .is_some_and(|value| !value.is_null())
730            || data
731                .get("pi_session_cwd")
732                .is_some_and(|value| !value.is_null())
733        {
734            return Err(Error::CorruptEventLog {
735                path: events_path.to_path_buf(),
736                reason: format!(
737                    "event seq={} Pi evidence fields must be all-or-none",
738                    ev.seq
739                ),
740            });
741        }
742        return Ok(None);
743    }
744    let session_id = session_id
745        .as_str()
746        .filter(|v| !v.is_empty())
747        .ok_or_else(|| Error::CorruptEventLog {
748            path: events_path.to_path_buf(),
749            reason: format!(
750                "event seq={} pi_session_id must be a non-empty string",
751                ev.seq
752            ),
753        })?;
754    if session_id.len() != 36
755        || !session_id.bytes().enumerate().all(|(index, byte)| {
756            if matches!(index, 8 | 13 | 18 | 23) {
757                byte == b'-'
758            } else {
759                byte.is_ascii_hexdigit()
760            }
761        })
762    {
763        return Err(Error::CorruptEventLog {
764            path: events_path.to_path_buf(),
765            reason: format!("event seq={} pi_session_id must be a UUID", ev.seq),
766        });
767    }
768    let original_cwd = want_str(events_path, ev, data, "pi_session_cwd")?;
769    let live_session_path = want_str(events_path, ev, data, "pi_session_path")?;
770    let expected_live_path = format!(
771        ".creating/pi-sessions/{}/pi-session-{session_id}.jsonl",
772        ev.run_id.as_str()
773    );
774    if live_session_path != expected_live_path {
775        return Err(Error::CorruptEventLog {
776            path: events_path.to_path_buf(),
777            reason: format!(
778                "event seq={} pi_session_path is not the canonical state-relative path",
779                ev.seq
780            ),
781        });
782    }
783    let attempt = match data.get("attempt") {
784        None | Some(Value::Null) => 0,
785        Some(value) => value
786            .as_u64()
787            .and_then(|raw| u32::try_from(raw).ok())
788            .ok_or_else(|| Error::CorruptEventLog {
789                path: events_path.to_path_buf(),
790                reason: format!("event seq={} attempt must be a u32", ev.seq),
791            })?,
792    };
793    Ok(Some(WorkerEvidence {
794        attempt,
795        session_id: session_id.to_string(),
796        original_cwd: original_cwd.to_string(),
797        live_session_path: live_session_path.to_string(),
798        status: EvidenceStatus::Pending,
799        transcript_path: None,
800        resume_path: None,
801        pane_path: None,
802        report_path: None,
803        transcript_sha256: None,
804        error: None,
805    }))
806}
807
808/// Parse the optional `resident` policy of `run.created` (ADR 0003).
809fn resident_policy_from_data(
810    events_path: &Path,
811    ev: &Event,
812    d: &Value,
813) -> Result<Option<ResidentPolicy>> {
814    let Some(raw) = d.get("resident").filter(|v| !v.is_null()) else {
815        return Ok(None);
816    };
817    let policy: ResidentPolicy =
818        serde_json::from_value(raw.clone()).map_err(|e| Error::CorruptEventLog {
819            path: events_path.to_path_buf(),
820            reason: format!("event seq={} run.created invalid `resident`: {e}", ev.seq),
821        })?;
822    ResidentPolicy::validate_name(&policy.name).map_err(|reason| Error::CorruptEventLog {
823        path: events_path.to_path_buf(),
824        reason: format!(
825            "event seq={} run.created invalid `resident`: {reason}",
826            ev.seq
827        ),
828    })?;
829    if policy.idle_expiry_secs == 0 {
830        return Err(Error::CorruptEventLog {
831            path: events_path.to_path_buf(),
832            reason: format!(
833                "event seq={} run.created `resident.idle_expiry_secs` must be positive",
834                ev.seq
835            ),
836        });
837    }
838    Ok(Some(policy))
839}
840
841/// Parse an optional launcher-assigned Claude session id (lowercase UUID).
842fn claude_session_from_data(events_path: &Path, ev: &Event, d: &Value) -> Result<Option<String>> {
843    let Some(raw) = d.get("claude_session_id").filter(|v| !v.is_null()) else {
844        return Ok(None);
845    };
846    let id = raw.as_str().unwrap_or("");
847    let uuid_shape = id.len() == 36
848        && id.bytes().enumerate().all(|(i, b)| {
849            if matches!(i, 8 | 13 | 18 | 23) {
850                b == b'-'
851            } else {
852                b.is_ascii_digit() || (b'a'..=b'f').contains(&b)
853            }
854        });
855    if !uuid_shape {
856        return Err(Error::CorruptEventLog {
857            path: events_path.to_path_buf(),
858            reason: format!(
859                "event seq={} claude_session_id must be a lowercase hyphenated UUID",
860                ev.seq
861            ),
862        });
863    }
864    Ok(Some(id.to_string()))
865}
866
867fn reduce_node_created(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
868    let events_path = paths.events();
869    // The envelope `node_id` is already a validated `NodeId` (parsed on read),
870    // so take it directly — no re-parse needed.
871    let node_id = require_envelope_node_id(&events_path, ev)?;
872    let is_default_node = node_id.as_str() == "n-0001";
873    // Idempotent on replay: skip if the node already exists.
874    if read_node_opt(paths, &node_id)?.is_some() {
875        return Ok(vec![]);
876    }
877    let d = &ev.data;
878    let kind =
879        data_kind(d.get("kind").unwrap_or(&Value::Null)).ok_or_else(|| Error::CorruptEventLog {
880            path: events_path.clone(),
881            reason: format!(
882                "event seq={} kind=node.created missing/invalid `kind`",
883                ev.seq
884            ),
885        })?;
886    let n = Node {
887        schema_version: STATE_SCHEMA_VERSION,
888        node_id,
889        // `run_id == paths.run_id` was verified at `reduce_event_to_ops` entry.
890        run_id: paths.run_id.clone(),
891        parent_node_id: opt_node_id(&events_path, ev, d, "parent_node_id")?,
892        kind,
893        status: Status::Pending,
894        task: d.get("task").and_then(Value::as_str).map(str::to_string),
895        worktree_path: d
896            .get("worktree_path")
897            .and_then(Value::as_str)
898            .map(str::to_string),
899        branch: d.get("branch").and_then(Value::as_str).map(str::to_string),
900        base_sha: d
901            .get("base_sha")
902            .and_then(Value::as_str)
903            .filter(|s| !s.is_empty())
904            .map(str::to_string),
905        tmux_window: d
906            .get("tmux_window")
907            .and_then(Value::as_str)
908            .map(str::to_string),
909        tmux_identity: tmux_identity_from_data(d).map(Box::new),
910        evidence: worker_evidence_from_spawn_data(&events_path, ev, d)?,
911        caller_pi_session: None,
912        caller_pi_lifecycle: None,
913        retained_display: None,
914        retention_unavailable: None,
915        agent_pid: optional_i32(d, "agent_pid", &events_path, ev)?,
916        agent_pid_start_time: optional_ts(d, "agent_pid_start_time", &events_path, ev)?,
917        agent_pid_start_identity: start_identity_from_data(d),
918        supervisor_pid: optional_i32(d, "supervisor_pid", &events_path, ev)?,
919        children: Vec::new(),
920        started_at: Some(ev.ts),
921        updated_at: ev.ts,
922        last_report: None,
923        last_processed_report_seq_by_child: serde_json::Map::default(),
924        retry_attempts: 0,
925        worker_exit: None,
926        pending_merge: None,
927        first_death_at: None,
928        awaiting_input: None,
929        open_ask: None,
930        last_ask: None,
931        claude_session_id: claude_session_from_data(&events_path, ev, d)?,
932        resident: None,
933    };
934    let mut ops = vec![ProjectionOp::Node(n)];
935    if let Some(mut m) = read_manifest_opt(paths)? {
936        // Materialization is the point at which an implicit source branch is
937        // known. Preserve an explicit run.created value; otherwise fold the
938        // source discovered by the creator into the manifest in this same
939        // locked event application.
940        if is_default_node && m.source_branch.is_none() {
941            m.source_branch = d
942                .get("source_branch")
943                .and_then(Value::as_str)
944                .filter(|branch| !branch.is_empty())
945                .map(str::to_string);
946        }
947        // `node_count` is derived from the projection directories in
948        // `advance_applied_seq`, never incremented here — see the module note
949        // and issue `manifest-counter-desync`. This op also refreshes the run's
950        // last-activity timestamp.
951        m.updated_at = ev.ts;
952        ops.push(ProjectionOp::Manifest(m));
953    }
954    Ok(ops)
955}
956
957/// Replay may encounter an already projected intent after a crash before the
958/// applied watermark advanced. Only an exact duplicate is a no-op.
959fn reduce_caller_settlement_intent(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
960    let bad = |reason: &str| Error::CorruptEventLog {
961        path: paths.events(),
962        reason: format!("event seq={} caller.settlement_intent: {reason}", ev.seq),
963    };
964    let id = require_envelope_node_id(&paths.events(), ev)?;
965    let mut manifest = read_manifest_opt(paths)?.ok_or_else(|| bad("missing run"))?;
966    let node = read_node_opt(paths, &id)?.ok_or_else(|| bad("missing node"))?;
967    let mut intent: CallerSettlementIntent =
968        serde_json::from_value(ev.data.clone()).map_err(|_| bad("invalid typed intent"))?;
969    if manifest.agent_owner != crate::schema::AgentOwner::Caller
970        || intent.run_id != ev.run_id
971        || intent.node_id != id
972        || node.run_id != ev.run_id
973        || ev.idempotency_key.as_deref() != Some(intent.key.as_str())
974        || intent.key.trim().is_empty()
975        || intent.actor.trim().is_empty()
976        || intent.writer_dev == 0
977        || intent.writer_ino == 0
978        || intent.gate_dev == 0
979        || intent.gate_ino == 0
980        || intent.seq != 0
981        || intent.generation
982            != node
983                .caller_pi_lifecycle
984                .as_ref()
985                .map_or(0, |v| v.generation)
986    {
987        return Err(bad("invalid identity, generation or audit fields"));
988    }
989    intent.seq = ev.seq;
990    if let Some(existing) = &manifest.caller_settlement_intent {
991        return if existing == &intent {
992            Ok(vec![])
993        } else {
994            Err(bad("intent already recorded"))
995        };
996    }
997    if manifest.status.is_terminal()
998        && !(manifest.status == Status::Failed
999            && node.status == Status::Failed
1000            && manifest.node_count == 1
1001            && id.as_str() == "n-0001"
1002            && matches!(
1003                intent.operation,
1004                crate::schema::SettlementOperation::Merge
1005                    | crate::schema::SettlementOperation::Discard
1006            ))
1007    {
1008        return Err(bad("terminal run"));
1009    }
1010    manifest.caller_settlement_intent = Some(intent);
1011    manifest.updated_at = ev.ts;
1012    Ok(vec![ProjectionOp::Manifest(manifest)])
1013}
1014
1015/// Binding is immutable even if the worktree later disappears. The CLI validates
1016/// the native file at admission; replay only checks the recorded identity.
1017fn reduce_caller_pi_session_bound(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1018    let bad = |reason: &str| Error::CorruptEventLog {
1019        path: paths.events(),
1020        reason: format!("event seq={} caller.pi.session_bound: {reason}", ev.seq),
1021    };
1022    let id = require_envelope_node_id(&paths.events(), ev)?;
1023    let manifest = read_manifest_opt(paths)?.ok_or_else(|| bad("missing run"))?;
1024    if manifest.agent_owner != crate::schema::AgentOwner::Caller {
1025        return Err(bad("not a caller-owned run"));
1026    }
1027    let mut node = read_node_opt(paths, &id)?.ok_or_else(|| bad("missing node"))?;
1028    let binding: CallerPiSession =
1029        serde_json::from_value(ev.data.clone()).map_err(|_| bad("invalid binding"))?;
1030    if binding.original_cwd != node.worktree_path.as_deref().unwrap_or("")
1031        || binding.original_cwd.is_empty()
1032        || binding.pi_session_id.is_empty()
1033        || binding.session_path.is_empty()
1034    {
1035        return Err(bad("binding identity does not match node"));
1036    }
1037    match &node.caller_pi_session {
1038        Some(existing) if existing == &binding => return Ok(vec![]),
1039        Some(_) => return Err(bad("binding already exists with different identity")),
1040        None => {}
1041    }
1042    if let Some(reserved) = &node.caller_pi_lifecycle {
1043        if reserved.pi_session_id != binding.pi_session_id
1044            || Some(reserved.generation) != binding.generation
1045            || reserved
1046                .session_path
1047                .as_deref()
1048                .is_some_and(|p| p != binding.session_path)
1049            || !matches!(
1050                reserved.state,
1051                CallerPiState::Reserved | CallerPiState::Started
1052            )
1053        {
1054            return Err(bad("binding does not match the current launch reservation"));
1055        }
1056    }
1057    if binding.generation.is_some() && node.caller_pi_lifecycle.is_none() {
1058        return Err(bad("binding generation has no reservation"));
1059    }
1060    if let Some(current) = &mut node.caller_pi_lifecycle {
1061        current.session_path = Some(binding.session_path.clone());
1062    }
1063    node.caller_pi_session = Some(binding);
1064    node.updated_at = ev.ts;
1065    Ok(vec![ProjectionOp::Node(node)])
1066}
1067
1068/// Fold only exact, generation-ordered caller attestations. Replaying an already
1069/// projected event must be a no-op; a conflicting event poisons neither log nor
1070/// projection because append validates with this same reducer first.
1071fn reduce_caller_pi_lifecycle(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1072    let bad = |reason: &str| Error::CorruptEventLog {
1073        path: paths.events(),
1074        reason: format!("event seq={} caller.pi.lifecycle: {reason}", ev.seq),
1075    };
1076    let id = require_envelope_node_id(&paths.events(), ev)?;
1077    let manifest = read_manifest_opt(paths)?.ok_or_else(|| bad("missing run"))?;
1078    if manifest.agent_owner != crate::schema::AgentOwner::Caller {
1079        return Err(bad("not a caller-owned run"));
1080    }
1081    let mut node = read_node_opt(paths, &id)?.ok_or_else(|| bad("missing node"))?;
1082    let fact: CallerPiLifecycle =
1083        serde_json::from_value(ev.data.clone()).map_err(|_| bad("invalid lifecycle fact"))?;
1084    let binding = node.caller_pi_session.as_ref();
1085    if fact.generation == 0
1086        || binding.is_some_and(|b| {
1087            fact.pi_session_id != b.pi_session_id
1088                || fact.session_path.as_deref() != Some(&b.session_path)
1089        })
1090        || (fact.state == CallerPiState::Reserved && fact.session_path.is_some())
1091        || (fact.state == CallerPiState::Started && fact.session_path.is_none())
1092        || (binding.is_none()
1093            && fact.state != CallerPiState::Reserved
1094            && !node
1095                .caller_pi_lifecycle
1096                .as_ref()
1097                .is_some_and(|old| old.state == CallerPiState::Reserved))
1098        || fact
1099            .reason
1100            .as_ref()
1101            .is_some_and(|r| r.trim().is_empty() || r.len() > 1024)
1102        || matches!(fact.state, CallerPiState::Started | CallerPiState::Reserved)
1103            != fact.reason.is_none()
1104    {
1105        return Err(bad("invalid generation, session identity or reason"));
1106    }
1107    if node.caller_pi_lifecycle.as_ref() == Some(&fact) {
1108        return Ok(vec![]);
1109    }
1110    if manifest.status.is_terminal() {
1111        return Err(bad("terminal run cannot accept a new Pi transition"));
1112    }
1113    match &node.caller_pi_lifecycle {
1114        None if fact.generation == 1
1115            && fact.state == CallerPiState::Started
1116            && binding.is_some() => {}
1117        None if fact.generation == 1
1118            && fact.state == CallerPiState::Reserved
1119            && binding.is_none() => {}
1120        Some(old) if *old == fact => return Ok(vec![]),
1121        Some(old)
1122            if old.generation == fact.generation
1123                && old.state == CallerPiState::Started
1124                && matches!(
1125                    fact.state,
1126                    CallerPiState::Exited | CallerPiState::ControlUncertain
1127                ) => {}
1128        Some(old)
1129            if old.generation == fact.generation
1130                && old.state == CallerPiState::Reserved
1131                && old.pi_session_id == fact.pi_session_id
1132                && (old.session_path == fact.session_path
1133                    || (old.session_path.is_none()
1134                        && fact.state == CallerPiState::Started
1135                        && binding.is_some()))
1136                && (matches!(
1137                    fact.state,
1138                    CallerPiState::LaunchFailed | CallerPiState::ControlUncertain
1139                ) || (fact.state == CallerPiState::Started && binding.is_some())) => {}
1140        Some(old)
1141            if old.generation.checked_add(1) == Some(fact.generation)
1142                && matches!(
1143                    old.state,
1144                    CallerPiState::Exited | CallerPiState::LaunchFailed
1145                )
1146                && fact.state == CallerPiState::Started => {}
1147        _ => return Err(bad("stale or conflicting generation/transition")),
1148    }
1149    node.caller_pi_lifecycle = Some(fact);
1150    node.updated_at = ev.ts;
1151    Ok(vec![ProjectionOp::Node(node)])
1152}
1153
1154/// Rewire an existing node to a freshly re-spawned agent after an empty-handed
1155/// `agent-died` bounded auto-retry (issue `autoretry-agent-died-worker`). The
1156/// supervisor tore down the dead worker's stale worktree and `create.sh`'d a
1157/// clean one at the run's source branch; this event carries the new spawn
1158/// metadata (`branch`, `base_sha`, `worktree_path`, tmux identity, `agent_pid`)
1159/// plus the audit fields (`attempt`, `reason`).
1160///
1161/// It updates the node in place: the new agent's coordinates replace the dead
1162/// one's, `status` returns to `Pending`, `started_at` is re-stamped so the
1163/// watchdog's spawn-grace window re-applies to the new agent, `last_report` is
1164/// cleared, and `retry_attempts` is incremented — the DURABLE, restart-safe
1165/// bound the watchdog checks before scheduling the next retry.
1166///
1167/// Guards, mirroring the other node reducers:
1168/// - A missing node is a no-op (a retry event whose node was never created).
1169/// - A TERMINAL node is never resurrected (a settled node is frozen): if a real
1170///   `node.report` raced in and terminalized the node, the retry is a dead event.
1171///   This keeps replay robust and preserves the terminal-state invariant.
1172fn reduce_node_retry(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1173    let events_path = paths.events();
1174    let node_id = require_envelope_node_id(&events_path, ev)?;
1175    let mut n = match read_node_opt(paths, &node_id)? {
1176        Some(n) => n,
1177        None => return Ok(vec![]),
1178    };
1179    // Terminal-state guard: a settled node is frozen. A late `node.report` that
1180    // beat this retry to the lock wins; the retry must not resurrect it.
1181    if n.status.is_terminal() {
1182        tracing::debug!(
1183            target: "taskfleet_core::reducer",
1184            seq = ev.seq, kind = %ev.kind, node_id = %node_id, current = ?n.status,
1185            "no-op: node.retry against terminal node"
1186        );
1187        return Ok(vec![]);
1188    }
1189    let d = &ev.data;
1190    // Rewire to the new agent. Each field mirrors `reduce_node_created`'s parsing
1191    // so the projection shape is identical to a fresh spawn.
1192    n.branch = d.get("branch").and_then(Value::as_str).map(str::to_string);
1193    n.base_sha = d
1194        .get("base_sha")
1195        .and_then(Value::as_str)
1196        .filter(|s| !s.is_empty())
1197        .map(str::to_string);
1198    n.worktree_path = d
1199        .get("worktree_path")
1200        .and_then(Value::as_str)
1201        .map(str::to_string);
1202    n.tmux_window = d
1203        .get("tmux_window")
1204        .and_then(Value::as_str)
1205        .map(str::to_string);
1206    n.tmux_identity = tmux_identity_from_data(d).map(Box::new);
1207    n.evidence = worker_evidence_from_spawn_data(&events_path, ev, d)?;
1208    n.claude_session_id = claude_session_from_data(&events_path, ev, d)?;
1209    n.retained_display = None;
1210    n.retention_unavailable = None;
1211    n.agent_pid = optional_i32(d, "agent_pid", &events_path, ev)?;
1212    n.agent_pid_start_time = optional_ts(d, "agent_pid_start_time", &events_path, ev)?;
1213    n.agent_pid_start_identity = start_identity_from_data(d);
1214    n.status = Status::Pending;
1215    n.started_at = Some(ev.ts);
1216    n.updated_at = ev.ts;
1217    n.last_report = None;
1218    // Drop any in-flight merge transaction from the PREVIOUS attempt: the retry
1219    // rewires the node to a new branch/worktree/agent, so a `pending_merge` that
1220    // referenced the dead attempt's branch must not carry forward — recovery would
1221    // otherwise judge the new attempt from the old worker's merge state (issue
1222    // `merge-transaction-recovery`, /llm-review finding).
1223    n.pending_merge = None;
1224    // Clear the previous attempt's told exit fact: the freshly re-spawned worker
1225    // is a NEW process, so a stale `worker_exit` must not carry over — otherwise
1226    // the supervisor's told-fact pass would instantly (mis)judge the new attempt
1227    // from the dead one's exit (issue `thin-exit-status-launcher`).
1228    n.worker_exit = None;
1229    // Clear the previous attempt's first-death anchor: the residual crash backstop
1230    // must measure the NEW attempt's own post-death grace from scratch, not inherit
1231    // the dead attempt's timestamp (which would fire the backstop with no grace on
1232    // the fresh worker's first confirmed death). Issue `typed-supervisor-outcomes`.
1233    n.first_death_at = None;
1234    // A retry is a new worker attempt. Never carry an unresolved question from
1235    // the dead attempt onto the replacement worker.
1236    n.awaiting_input = None;
1237    cancel_open_ask(&mut n, ev);
1238    // The event carries its ABSOLUTE attempt number (the supervisor set it to
1239    // `retry_attempts + 1` at emit time). Assign it directly rather than a blind
1240    // `+= 1`: this makes the projection a pure function of the event, so a
1241    // full replay from seq 0, or a (guarded-against but defensive) double-apply,
1242    // converges to the same `retry_attempts` the log declares — the audit count
1243    // and the durable bound can never disagree. A legacy/malformed event with no
1244    // parseable `attempt` falls back to the monotone increment.
1245    n.retry_attempts = d
1246        .get("attempt")
1247        .and_then(Value::as_u64)
1248        .map_or_else(|| n.retry_attempts.saturating_add(1), |a| a as u32);
1249    Ok(vec![ProjectionOp::Node(n)])
1250}
1251
1252fn reduce_node_status(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1253    let events_path = paths.events();
1254    let node_id = require_envelope_node_id(&events_path, ev)?;
1255    let mut n = match read_node_opt(paths, &node_id)? {
1256        Some(n) => n,
1257        None => return Ok(vec![]),
1258    };
1259    let new_status = require_status(ev, events_path)?;
1260    // Terminal-state guard: a settled node never transitions again. See
1261    // run-cli-read/handoff.md D5.
1262    if n.status.is_terminal() {
1263        trace_terminal_noop(ev, n.status, new_status);
1264        return Ok(vec![]);
1265    }
1266    if n.status == new_status {
1267        return Ok(vec![]);
1268    }
1269    n.status = new_status;
1270    // A terminal `node.status` (e.g. a watchdog-synthesized failure) ends the
1271    // node's lifecycle, so any in-flight merge transaction is moot — clear it so a
1272    // `pending_merge` is not stranded on a terminal node (recovery skips terminal
1273    // nodes, so an uncleared one would dangle forever). Issue
1274    // `merge-transaction-recovery` (/llm-review finding).
1275    if new_status.is_terminal() {
1276        n.pending_merge = None;
1277        n.awaiting_input = None;
1278        cancel_open_ask(&mut n, ev);
1279    }
1280    n.updated_at = ev.ts;
1281    Ok(vec![ProjectionOp::Node(n)])
1282}
1283
1284fn reduce_node_report(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1285    let events_path = paths.events();
1286    let node_id = require_envelope_node_id(&events_path, ev)?;
1287    let mut n = match read_node_opt(paths, &node_id)? {
1288        Some(n) => n,
1289        None => return Ok(vec![]),
1290    };
1291    // Terminal-state guard *before* payload validation: a node that already
1292    // reached a terminal state is settled, so a late-arriving report (e.g. an
1293    // agent success racing a `run cancel`) is a dead event — it must not
1294    // resurrect the node, and must not even decorate the projection, so
1295    // `last_report` is left untouched. Guarding first also keeps replay
1296    // robust: a malformed dead report against a settled node is a clean
1297    // no-op rather than a `CorruptEventLog` that would brick rebuild of a
1298    // log `append_and_apply_event` already committed. See run-cli-read/handoff.md
1299    // D5. (3/4 of /llm-review preferred guard-before-validate over the
1300    // reverse the issue spec sketched; the required CorruptEventLog cases
1301    // all target live nodes, so validation still runs for them.)
1302    if n.status.is_terminal() {
1303        // ONE exception to the dead-event rule: a late, CONFIRMED explicit-merge
1304        // report is adopted even against a terminal node (issue
1305        // `reducer-adopt-explicit-merge`). A watchdog `agent-died` false positive
1306        // on a long-lived interactive run can terminalize a node BEFORE the user's
1307        // `run merge` report arrives; an explicit user merge carries strictly
1308        // higher-fidelity ground truth (the branch demonstrably landed in source)
1309        // than a watchdog timeout, so it wins. Overwriting `last_report` here is
1310        // what lets `any_node_merged_explicitly` see the merge and the SUPERVISOR
1311        // — invariant #5's canonical teardown actor — warrant teardown, instead of
1312        // the CLI compensating inline (issues `merge-skips-teardown`,
1313        // `agent-died-merge-no-teardown-interactive`).
1314        //
1315        // Scoped tightly, on BOTH sides:
1316        //   - incoming: a CONFIRMED SUCCESSFUL explicit merge
1317        //     (`via == "explicit-merge"`, `success == true`, not `cancelled`) —
1318        //     matches exactly the force-`-D` teardown gate (`node_branch_merged`),
1319        //     so a failed/cancelled or non-merge late report never resurrects a
1320        //     settled node and unmerged-work preservation is untouched.
1321        //   - prior: only a `Failed` or `Done` node (positive whitelist). A
1322        //     `Cancelled` terminal is a DELIBERATE `run cancel` teardown, not a
1323        //     watchdog false positive, so a later merge does not override it (it
1324        //     stays cancelled — matching the existing "late success report keeps the
1325        //     cancel" reducer contract). The whitelist (rather than `!= Cancelled`)
1326        //     is future-safe: a new deliberate-teardown terminal added later is not
1327        //     silently resurrected to Done.
1328        // Idempotent: if this exact report is already the node's `last_report`,
1329        // re-folding it on replay is a clean no-op (never churns `updated_at`).
1330        //
1331        // The node reducer does not directly project run status: the supervisor
1332        // owns cross-node/child topology. Once that topology is wholly successful,
1333        // it emits the narrowly-authorized Failed -> Done recovery `run.status`,
1334        // whose reducer independently verifies this adopted merge evidence.
1335        if ReportOrigin::permits_terminal_merge_recovery(n.status, &ev.data) {
1336            if n.last_report.as_ref() == Some(&ev.data) && n.status == Status::Done {
1337                return Ok(vec![]);
1338            }
1339            tracing::info!(
1340                target: "taskfleet_core::reducer",
1341                seq = ev.seq, kind = %ev.kind, node_id = %node_id, prior = ?n.status,
1342                "adopting late explicit-merge report against terminal node (invariant #5 teardown)"
1343            );
1344            n.last_report = Some(ev.data.clone());
1345            // A confirmed merge is a terminal SUCCESS: the work landed in source.
1346            // (A false watchdog `Failed` is corrected to `Done`; a genuine `Done`
1347            // stays `Done` with the merge marker adopted so teardown is warranted.)
1348            n.status = Status::Done;
1349            // The merge completed, so any in-flight merge transaction is resolved:
1350            // clear it so recovery does not later re-examine a settled node
1351            // (issue `merge-transaction-recovery`).
1352            n.pending_merge = None;
1353            n.awaiting_input = None;
1354            cancel_open_ask(&mut n, ev);
1355            n.updated_at = ev.ts;
1356            return Ok(vec![ProjectionOp::Node(n)]);
1357        }
1358        tracing::debug!(
1359            target: "taskfleet_core::reducer",
1360            seq = ev.seq, kind = %ev.kind, node_id = %node_id, current = ?n.status,
1361            "no-op: node.report against terminal node"
1362        );
1363        return Ok(vec![]);
1364    }
1365    // Live node: validate the report's terminal outcome. A `node.report`
1366    // must express exactly one terminal outcome — success/failure XOR
1367    // cancellation. Anything else (a bare `{}` with neither, or the
1368    // contradiction `success: true` + `cancelled: true`) is a corrupt event:
1369    // the reducer is the canonical gate, so reject it rather than silently
1370    // leaving the node in a dangling state. See design.md §7.7 and
1371    // node-cli-read/handoff.md D4.
1372    let new_status = report_terminal_status(&events_path, ev)?;
1373    n.last_report = Some(ev.data.clone());
1374    n.status = new_status;
1375    // A terminal report settles any open human-decision request. A blocked
1376    // report still preserves the discussion in `last_report`, while avoiding a
1377    // stale non-terminal awaiting-input flag on the settled node.
1378    n.awaiting_input = None;
1379    cancel_open_ask(&mut n, ev);
1380    // Any terminal outcome resolves an in-flight merge transaction: a successful
1381    // `explicit-merge` report completes it here (the normal, no-crash path), and
1382    // any other terminal report ends the node's lifecycle so no merge recovery
1383    // should later fire (issue `merge-transaction-recovery`).
1384    n.pending_merge = None;
1385    n.updated_at = ev.ts;
1386    Ok(vec![ProjectionOp::Node(n)])
1387}
1388
1389/// Fold a `worker.exited` event onto the node's `worker_exit` field (design.md
1390/// §2.1 / A1). This records the launcher shim's **told** exit status as a
1391/// durable fact; it deliberately does NOT transition `status`. Terminalization
1392/// is the supervisor's decision via the typed outcome table (§2.6) — a non-zero
1393/// or signalled exit becomes `failed`, while a clean exit without a merge stays
1394/// non-terminal (attention-required). Keeping the status transition out of the
1395/// reducer is what lets the clean-but-unmerged worker remain a visible, resumable
1396/// state instead of an auto-failed one.
1397///
1398/// Payload contract: at least one of `exit_code` (JSON integer) or `signal`
1399/// (JSON integer) must be present; a payload carrying neither is a corrupt event
1400/// (the reducer is the canonical gate). The fold is idempotent and **first-write-
1401/// wins**: once `worker_exit` is set, a replay or a spurious duplicate is a clean
1402/// no-op, so a full replay from seq 0 converges to the same recorded fact.
1403fn reduce_worker_exited(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1404    let events_path = paths.events();
1405    let node_id = require_envelope_node_id(&events_path, ev)?;
1406    let attempt = match ev.data.get("attempt") {
1407        None | Some(Value::Null) => 0,
1408        Some(_) => evidence_attempt(&events_path, ev)?,
1409    };
1410    let code = optional_i32(&ev.data, "exit_code", &events_path, ev)?;
1411    let signal = optional_i32(&ev.data, "signal", &events_path, ev)?;
1412    // A worker exit is EXACTLY one of a normal return (code) or a signal death
1413    // (signal). Neither is meaningless; both is contradictory (a process cannot
1414    // both return a code and be killed) — reject either rather than record an
1415    // ambiguous fact the outcome classifier would then have to disambiguate.
1416    match (code, signal) {
1417        (Some(_), None) | (None, Some(_)) => {}
1418        _ => {
1419            return Err(Error::CorruptEventLog {
1420                path: events_path,
1421                reason: format!(
1422                    "event seq={} kind=worker.exited must carry EXACTLY one of `exit_code` or `signal`",
1423                    ev.seq
1424                ),
1425            });
1426        }
1427    }
1428    let mut n = match read_node_opt(paths, &node_id)? {
1429        Some(n) => n,
1430        // No projection to decorate. A `worker.exited` for a node that does not
1431        // exist folds to nothing — consistent with the other node reducers
1432        // (`node.report` / `node.status`). In practice the shim validates the node
1433        // exists before it can record an exit, and normal append ordering always
1434        // places `node.created` first, so this is only hit for a genuinely orphan
1435        // event.
1436        None => return Ok(vec![]),
1437    };
1438    // First-write-wins: the shim fires exactly once per worker, so an existing
1439    // record is a replay/duplicate. Leaving it untouched keeps the fold a pure
1440    // function of the first exit event and never churns `updated_at`.
1441    if attempt != n.retry_attempts || n.worker_exit.is_some() {
1442        return Ok(vec![]);
1443    }
1444    n.worker_exit = Some(WorkerExit {
1445        code,
1446        signal,
1447        at: ev.ts,
1448    });
1449    // A departed worker cannot proceed on its recommended default. Clear its
1450    // open request so clean-exit attention and crash/stall handling remain the
1451    // actionable read-surface verdicts.
1452    n.awaiting_input = None;
1453    cancel_open_ask(&mut n, ev);
1454    n.updated_at = ev.ts;
1455    Ok(vec![ProjectionOp::Node(n)])
1456}
1457
1458fn evidence_attempt(events_path: &Path, ev: &Event) -> Result<u32> {
1459    ev.data
1460        .get("attempt")
1461        .and_then(Value::as_u64)
1462        .and_then(|raw| u32::try_from(raw).ok())
1463        .ok_or_else(|| Error::CorruptEventLog {
1464            path: events_path.to_path_buf(),
1465            reason: format!("event seq={} attempt must be a u32", ev.seq),
1466        })
1467}
1468
1469fn reduce_worker_evidence_archived(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1470    let events_path = paths.events();
1471    let node_id = require_envelope_node_id(&events_path, ev)?;
1472    let attempt = evidence_attempt(&events_path, ev)?;
1473    let session_id = want_str(&events_path, ev, &ev.data, "session_id")?.to_string();
1474    let mut values = Vec::new();
1475    for field in [
1476        "transcript_path",
1477        "resume_path",
1478        "pane_path",
1479        "report_path",
1480        "transcript_sha256",
1481    ] {
1482        values.push(want_str(&events_path, ev, &ev.data, field)?.to_string());
1483    }
1484    let expected_prefix = format!("evidence/{}/", node_id.as_str());
1485    for (index, suffix) in [
1486        "pi-session.original.jsonl",
1487        "pi-session.resume.jsonl",
1488        "final-pane.log",
1489        "terminal-report.json",
1490    ]
1491    .iter()
1492    .enumerate()
1493    {
1494        if values[index] != format!("{expected_prefix}{suffix}") {
1495            return Err(Error::CorruptEventLog {
1496                path: events_path,
1497                reason: format!(
1498                    "event seq={} evidence artifact path is not canonical",
1499                    ev.seq
1500                ),
1501            });
1502        }
1503    }
1504    if values[4].len() != 64
1505        || !values[4]
1506            .bytes()
1507            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1508    {
1509        return Err(Error::CorruptEventLog {
1510            path: events_path,
1511            reason: format!(
1512                "event seq={} transcript_sha256 is not lowercase SHA-256",
1513                ev.seq
1514            ),
1515        });
1516    }
1517    let mut node = match read_node_opt(paths, &node_id)? {
1518        Some(node) => node,
1519        None => return Ok(vec![]),
1520    };
1521    let Some(evidence) = node.evidence.as_mut() else {
1522        return Err(Error::CorruptEventLog {
1523            path: events_path,
1524            reason: format!(
1525                "event seq={} evidence archive has no recorded Pi session",
1526                ev.seq
1527            ),
1528        });
1529    };
1530    if evidence.attempt != attempt || evidence.session_id != session_id {
1531        return Ok(vec![]);
1532    }
1533    if evidence.status == EvidenceStatus::Complete {
1534        return Ok(vec![]);
1535    }
1536    evidence.transcript_path = Some(values.remove(0));
1537    evidence.resume_path = Some(values.remove(0));
1538    evidence.pane_path = Some(values.remove(0));
1539    evidence.report_path = Some(values.remove(0));
1540    evidence.transcript_sha256 = Some(values.remove(0));
1541    evidence.status = EvidenceStatus::Complete;
1542    evidence.error = None;
1543    node.updated_at = ev.ts;
1544    Ok(vec![ProjectionOp::Node(node)])
1545}
1546
1547fn reduce_worker_display_retained(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1548    let events_path = paths.events();
1549    let node_id = require_envelope_node_id(&events_path, ev)?;
1550    let display: crate::schema::RetainedDisplay =
1551        serde_json::from_value(ev.data.clone()).map_err(|e| Error::CorruptEventLog {
1552            path: events_path.clone(),
1553            reason: format!("event seq={} invalid retained display: {e}", ev.seq),
1554        })?;
1555    let mut node = match read_node_opt(paths, &node_id)? {
1556        Some(node) => node,
1557        None => return Ok(vec![]),
1558    };
1559    if display.attempt != node.retry_attempts || display.ownership_marker.is_empty() {
1560        return Ok(vec![]);
1561    }
1562    if node.retained_display.is_some() {
1563        return Ok(vec![]);
1564    }
1565    node.retained_display = Some(Box::new(display));
1566    node.updated_at = ev.ts;
1567    Ok(vec![ProjectionOp::Node(node)])
1568}
1569
1570fn reduce_worker_display_expired(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1571    let events_path = paths.events();
1572    let node_id = require_envelope_node_id(&events_path, ev)?;
1573    let marker = want_str(&events_path, ev, &ev.data, "ownership_marker")?;
1574    let attempt = evidence_attempt(&events_path, ev)?;
1575    let mut node = match read_node_opt(paths, &node_id)? {
1576        Some(node) => node,
1577        None => return Ok(vec![]),
1578    };
1579    let Some(display) = node.retained_display.as_mut() else {
1580        return Ok(vec![]);
1581    };
1582    if display.attempt != attempt
1583        || display.ownership_marker != marker
1584        || display.expired_at.is_some()
1585    {
1586        return Ok(vec![]);
1587    }
1588    display.expired_at = Some(ev.ts);
1589    node.updated_at = ev.ts;
1590    Ok(vec![ProjectionOp::Node(node)])
1591}
1592
1593fn reduce_worker_display_unavailable(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1594    let events_path = paths.events();
1595    let node_id = require_envelope_node_id(&events_path, ev)?;
1596    let attempt = evidence_attempt(&events_path, ev)?;
1597    let reason = want_str(&events_path, ev, &ev.data, "reason")?;
1598    let mut node = match read_node_opt(paths, &node_id)? {
1599        Some(node) => node,
1600        None => return Ok(vec![]),
1601    };
1602    if attempt != node.retry_attempts || node.retained_display.is_some() {
1603        return Ok(vec![]);
1604    }
1605    if node.retention_unavailable.is_none() {
1606        node.retention_unavailable = Some(reason.to_string());
1607        node.updated_at = ev.ts;
1608    }
1609    Ok(vec![ProjectionOp::Node(node)])
1610}
1611
1612fn reduce_worker_evidence_failed(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1613    let events_path = paths.events();
1614    let node_id = require_envelope_node_id(&events_path, ev)?;
1615    let attempt = evidence_attempt(&events_path, ev)?;
1616    let session_id = want_str(&events_path, ev, &ev.data, "session_id")?.to_string();
1617    let detail = want_str(&events_path, ev, &ev.data, "error")?.to_string();
1618    let mut node = match read_node_opt(paths, &node_id)? {
1619        Some(node) => node,
1620        None => return Ok(vec![]),
1621    };
1622    let Some(evidence) = node.evidence.as_mut() else {
1623        return Err(Error::CorruptEventLog {
1624            path: events_path,
1625            reason: format!(
1626                "event seq={} evidence failure has no recorded Pi session",
1627                ev.seq
1628            ),
1629        });
1630    };
1631    if evidence.attempt != attempt || evidence.session_id != session_id {
1632        return Ok(vec![]);
1633    }
1634    if evidence.status == EvidenceStatus::Complete {
1635        return Ok(vec![]);
1636    }
1637    evidence.status = EvidenceStatus::Failed;
1638    evidence.error = Some(detail);
1639    node.updated_at = ev.ts;
1640    Ok(vec![ProjectionOp::Node(node)])
1641}
1642
1643/// Fold a `node.death_observed` event onto [`Node::first_death_at`], recording
1644/// the FIRST tick on which the supervisor saw this node's worker confirmed-dead
1645/// with no told `worker.exited` and no merge — the durable anchor for the
1646/// residual crash backstop's fixed post-death grace (design.md §2.1a, issue
1647/// `typed-supervisor-outcomes`).
1648///
1649/// The anchor is the event's own timestamp (`ev.ts`) — no payload field needed.
1650/// The fold is **first-write-wins**: the anchor is monotonic, so a later
1651/// re-observation (a supervisor restart still seeing the dead pid) never resets
1652/// the clock, and a full replay from seq 0 converges to the first observation. A
1653/// `node.death_observed` for a missing or already terminal node folds to nothing
1654/// (the backstop is moot once the node settles).
1655fn reduce_node_death_observed(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1656    let events_path = paths.events();
1657    let node_id = require_envelope_node_id(&events_path, ev)?;
1658    let mut n = match read_node_opt(paths, &node_id)? {
1659        Some(n) => n,
1660        None => return Ok(vec![]),
1661    };
1662    // First-write-wins (monotonic anchor). No-op once the backstop is moot or a
1663    // higher-fidelity fact exists — a terminal node, a told `worker.exited`, a
1664    // landed report, or an in-flight merge transaction. The supervisor's emitter
1665    // already gates on all of these under the exclusive lock; mirroring them here
1666    // keeps a from-scratch replay convergent regardless of caller.
1667    if n.first_death_at.is_some()
1668        || n.status.is_terminal()
1669        || n.worker_exit.is_some()
1670        || n.last_report.is_some()
1671        || n.pending_merge.is_some()
1672    {
1673        return Ok(vec![]);
1674    }
1675    n.first_death_at = Some(ev.ts);
1676    n.updated_at = ev.ts;
1677    Ok(vec![ProjectionOp::Node(n)])
1678}
1679
1680/// Fold an agent's explicit request for a human decision onto the node without
1681/// changing its status. This is deliberately non-terminal: the worker may still
1682/// resolve the fork itself or proceed with its stated default.
1683///
1684/// The first open signal wins until a matching `node.input_resolved` clears it,
1685/// so retries or duplicate writes cannot move the grace clock forward. The
1686/// event timestamp, not a caller-supplied payload timestamp, is the durable
1687/// restart-safe anchor.
1688fn reduce_node_awaiting_input(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1689    const MAX_ITEMS: usize = 8;
1690    const MAX_TOPIC_CHARS: usize = 512;
1691    const MAX_OPTIONS: usize = 16;
1692    const MAX_OPTION_CHARS: usize = 256;
1693
1694    let events_path = paths.events();
1695    let node_id = require_envelope_node_id(&events_path, ev)?;
1696    // Validate before every state-dependent no-op. An ignored duplicate or late
1697    // event must still be structurally valid before it enters the durable log.
1698    let items = ev
1699        .data
1700        .get("discussion_items")
1701        .and_then(Value::as_array)
1702        .filter(|items| !items.is_empty() && items.len() <= MAX_ITEMS)
1703        .ok_or_else(|| Error::CorruptEventLog {
1704            path: events_path.clone(),
1705            reason: format!(
1706                "event seq={} kind=node.awaiting_input requires 1..={MAX_ITEMS} `discussion_items`",
1707                ev.seq
1708            ),
1709        })?;
1710    for (index, item) in items.iter().enumerate() {
1711        let obj = item.as_object().ok_or_else(|| Error::CorruptEventLog {
1712            path: events_path.clone(),
1713            reason: format!(
1714                "event seq={} discussion_items[{index}] must be an object",
1715                ev.seq
1716            ),
1717        })?;
1718        let topic = obj.get("topic").and_then(Value::as_str).unwrap_or("");
1719        let default = obj
1720            .get("recommended_default")
1721            .and_then(Value::as_str)
1722            .unwrap_or("");
1723        let options = obj.get("options").and_then(Value::as_array);
1724        let options_valid = options.is_some_and(|values| {
1725            !values.is_empty()
1726                && values.len() <= MAX_OPTIONS
1727                && values.iter().all(|v| {
1728                    v.as_str().is_some_and(|s| {
1729                        !s.trim().is_empty() && s.chars().count() <= MAX_OPTION_CHARS
1730                    })
1731                })
1732                && values.iter().any(|v| v.as_str() == Some(default))
1733        });
1734        if topic.trim().is_empty()
1735            || topic.chars().count() > MAX_TOPIC_CHARS
1736            || default.trim().is_empty()
1737            || !options_valid
1738        {
1739            return Err(Error::CorruptEventLog {
1740                path: events_path.clone(),
1741                reason: format!(
1742                    "event seq={} discussion_items[{index}] requires bounded non-empty `topic`, 1..={MAX_OPTIONS} bounded string `options`, and a `recommended_default` present in options",
1743                    ev.seq
1744                ),
1745            });
1746        }
1747    }
1748
1749    let mut n = match read_node_opt(paths, &node_id)? {
1750        Some(n) => n,
1751        None => return Ok(vec![]),
1752    };
1753    if n.status.is_terminal() || n.worker_exit.is_some() {
1754        return Ok(vec![]);
1755    }
1756    if let Some(open) = n.awaiting_input.as_mut() {
1757        // A later fork joins the current open generation without moving its
1758        // restart-safe clock or notification key. Bound the aggregate too.
1759        if open.discussion_items.len() + items.len() > MAX_ITEMS {
1760            return Err(Error::CorruptEventLog {
1761                path: events_path,
1762                reason: format!(
1763                    "event seq={} would exceed {MAX_ITEMS} open discussion items",
1764                    ev.seq
1765                ),
1766            });
1767        }
1768        open.discussion_items.extend(items.iter().cloned());
1769    } else {
1770        n.awaiting_input = Some(Box::new(crate::schema::AwaitingInput {
1771            opened_at: ev.ts,
1772            event_seq: ev.seq,
1773            discussion_items: items.clone(),
1774        }));
1775    }
1776    n.updated_at = ev.ts;
1777    Ok(vec![ProjectionOp::Node(n)])
1778}
1779
1780/// Clear the current open decision request. `event_seq` is mandatory and
1781/// fences the resolve to the generation the worker observed, so a delayed
1782/// timeout cannot clear a newer question opened after the old one resolved.
1783fn reduce_node_input_resolved(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1784    let events_path = paths.events();
1785    let node_id = require_envelope_node_id(&events_path, ev)?;
1786    // Validate before the no-open no-op so malformed events never enter the log
1787    // merely because their projection happens to be absent today.
1788    let seq = ev
1789        .data
1790        .get("event_seq")
1791        .and_then(Value::as_u64)
1792        .ok_or_else(|| Error::CorruptEventLog {
1793            path: events_path.clone(),
1794            reason: format!(
1795                "event seq={} kind=node.input_resolved requires unsigned `event_seq`",
1796                ev.seq
1797            ),
1798        })?;
1799    let mut n = match read_node_opt(paths, &node_id)? {
1800        Some(n) => n,
1801        None => return Ok(vec![]),
1802    };
1803    let Some(open) = n.awaiting_input.as_ref() else {
1804        return Ok(vec![]);
1805    };
1806    if seq != open.event_seq {
1807        return Ok(vec![]);
1808    }
1809    n.awaiting_input = None;
1810    n.updated_at = ev.ts;
1811    Ok(vec![ProjectionOp::Node(n)])
1812}
1813
1814/// The event kind `run merge` appends BEFORE mutating git to record the
1815/// in-flight merge transaction (design.md §2.1b / A2). Its `data` payload is a
1816/// serialized [`MergeTxn`]; the reducer folds it onto [`Node::pending_merge`].
1817pub const KIND_MERGE_STARTED: &str = "merge.started";
1818
1819/// The event kind recovery appends when it resolves a pending merge transaction
1820/// by REJECTING it — the recorded source ref never moved (the git mutation never
1821/// landed), so the worker's branch + work are preserved and the transaction is
1822/// cleared. Its `data` carries `op_id` (which transaction) and `reason`.
1823pub const KIND_MERGE_ABORTED: &str = "merge.aborted";
1824
1825/// Fold a `merge.started` event onto [`Node::pending_merge`], recording the
1826/// in-flight `run merge` transaction BEFORE the git mutation so a crash between
1827/// the git merge and the terminal `explicit-merge` report can be resolved
1828/// deterministically by OID (design.md §2.1b / A2, issue
1829/// `merge-transaction-recovery`). The reducer deliberately does NOT transition
1830/// `status`: recording a transaction is not a terminal outcome.
1831///
1832/// Payload contract: the `data` is a serialized [`MergeTxn`]; a payload missing
1833/// required fields is a corrupt event (the reducer is the canonical gate, so the
1834/// append is rejected before any byte is written). The fold is idempotent —
1835/// re-folding the same `op_id` on replay is a clean no-op — and last-write-wins
1836/// across a fresh attempt's larger `op_id` (each `run merge` re-reads
1837/// `expected_source_oid`, so the newest record is authoritative).
1838fn reduce_merge_started(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1839    let events_path = paths.events();
1840    let node_id = require_envelope_node_id(&events_path, ev)?;
1841    let txn: MergeTxn =
1842        serde_json::from_value(ev.data.clone()).map_err(|e| Error::CorruptEventLog {
1843            path: events_path.clone(),
1844            reason: format!(
1845                "event seq={} kind=merge.started has an invalid MergeTxn payload: {e}",
1846                ev.seq
1847            ),
1848        })?;
1849    let manifest = read_manifest_opt(paths)?.ok_or_else(|| Error::CorruptEventLog {
1850        path: events_path.clone(),
1851        reason: "merge.started without a run".into(),
1852    })?;
1853    let bad_link = || Error::CorruptEventLog {
1854        path: events_path.clone(),
1855        reason: format!(
1856            "event seq={} merge.started caller authority does not match intent",
1857            ev.seq
1858        ),
1859    };
1860    match manifest.agent_owner {
1861        crate::schema::AgentOwner::Caller => {
1862            let intent = manifest
1863                .caller_settlement_intent
1864                .as_ref()
1865                .ok_or_else(bad_link)?;
1866            let link = txn.caller_authority.as_ref().ok_or_else(bad_link)?;
1867            if intent.operation != crate::schema::SettlementOperation::Merge
1868                || intent.run_id != ev.run_id
1869                || intent.node_id != node_id
1870                || link.intent_seq != intent.seq
1871                || link.intent_key != intent.key
1872                || (link.writer_dev, link.writer_ino) != (intent.writer_dev, intent.writer_ino)
1873                || txn.source_branch != manifest.source_branch.as_deref().unwrap_or("")
1874            {
1875                return Err(bad_link());
1876            }
1877        }
1878        crate::schema::AgentOwner::Taskfleet if txn.caller_authority.is_some() => {
1879            return Err(bad_link())
1880        }
1881        crate::schema::AgentOwner::Taskfleet => {}
1882    }
1883    let mut n = match read_node_opt(paths, &node_id)? {
1884        Some(n) => n,
1885        None => return Ok(vec![]),
1886    };
1887    if manifest.agent_owner == crate::schema::AgentOwner::Caller
1888        && (n.branch.as_deref() != Some(&txn.worker_branch)
1889            || n.caller_pi_lifecycle.as_ref().map_or(0, |p| p.generation)
1890                != manifest
1891                    .caller_settlement_intent
1892                    .as_ref()
1893                    .unwrap()
1894                    .generation)
1895    {
1896        return Err(bad_link());
1897    }
1898    // A terminal node has no in-flight merge to track — `run merge` is refused on
1899    // a terminal run at the CLI, so this is a dead/duplicate event. Ignore it
1900    // (never resurrect the projection).
1901    if n.status.is_terminal()
1902        && !(manifest.agent_owner == crate::schema::AgentOwner::Caller
1903            && n.status == Status::Failed
1904            && manifest.status == Status::Failed
1905            && manifest.node_count == 1
1906            && manifest.caller_settlement_intent.as_ref().is_some_and(|i| {
1907                i.operation == crate::schema::SettlementOperation::Merge && i.node_id == node_id
1908            }))
1909    {
1910        return Ok(vec![]);
1911    }
1912    // Idempotent: re-folding the SAME transaction on replay must not churn
1913    // `updated_at`.
1914    if n.pending_merge.as_ref().map(|t| t.op_id.as_str()) == Some(txn.op_id.as_str()) {
1915        return Ok(vec![]);
1916    }
1917    n.pending_merge = Some(Box::new(txn));
1918    n.updated_at = ev.ts;
1919    Ok(vec![ProjectionOp::Node(n)])
1920}
1921
1922/// Fold a `merge.aborted` event, clearing [`Node::pending_merge`] iff it names
1923/// the transaction being aborted (`op_id` match). Recovery appends this when it
1924/// determines a pending merge's git mutation never landed (the source ref is
1925/// still at `expected_source_oid`) or moved unexpectedly — the transaction is
1926/// rejected, the worker's branch + work are preserved, and the node stays
1927/// whatever non-terminal status it was (a retry may re-attempt the merge).
1928///
1929/// The `op_id` guard is what keeps this from clobbering a *newer* transaction: a
1930/// stale `merge.aborted` for a superseded attempt (a different `op_id`) is a
1931/// clean no-op. Deliberately
1932/// does NOT transition `status`.
1933fn reduce_merge_aborted(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
1934    let events_path = paths.events();
1935    let node_id = require_envelope_node_id(&events_path, ev)?;
1936    let op_id = ev
1937        .data
1938        .get("op_id")
1939        .and_then(Value::as_str)
1940        .ok_or_else(|| Error::CorruptEventLog {
1941            path: events_path.clone(),
1942            reason: format!(
1943                "event seq={} kind=merge.aborted is missing string `op_id`",
1944                ev.seq
1945            ),
1946        })?;
1947    let mut n = match read_node_opt(paths, &node_id)? {
1948        Some(n) => n,
1949        None => return Ok(vec![]),
1950    };
1951    // Clear only the transaction this event names. A mismatch (already resolved,
1952    // or a newer attempt is pending) is a clean no-op.
1953    match n.pending_merge.as_ref() {
1954        Some(t) if t.op_id == op_id => {}
1955        _ => return Ok(vec![]),
1956    }
1957    n.pending_merge = None;
1958    n.updated_at = ev.ts;
1959    Ok(vec![ProjectionOp::Node(n)])
1960}
1961
1962/// Emit an observability trace for a status event dropped by the terminal
1963/// guard. Re-applying the *same* terminal status is routine idempotent replay
1964/// (`debug`); an event carrying a *different* status is a real conflict that
1965/// should not occur on a well-formed log (`warn`) — e.g. a `done` node being
1966/// told to go `cancelled`. The guard no-ops either way; the level is the only
1967/// difference, so a genuine corruption signal is visible without flooding
1968/// logs on every replay.
1969fn trace_terminal_noop(ev: &Event, current: Status, incoming: Status) {
1970    if current == incoming {
1971        tracing::debug!(
1972            target: "taskfleet_core::reducer",
1973            seq = ev.seq, kind = %ev.kind, status = ?current,
1974            "no-op: status re-applied to terminal target"
1975        );
1976    } else {
1977        tracing::warn!(
1978            target: "taskfleet_core::reducer",
1979            seq = ev.seq, kind = %ev.kind, current = ?current, incoming = ?incoming,
1980            "no-op: ignored conflicting transition from terminal target"
1981        );
1982    }
1983}
1984
1985/// Derive the terminal status a `node.report` event asserts, enforcing the
1986/// success-XOR-cancelled invariant with strict boolean typing.
1987///
1988/// `cancelled: true` (with `success: false` or absent) → [`Status::Cancelled`].
1989/// Otherwise `success` must be present: `true` → [`Status::Done`], `false` →
1990/// [`Status::Failed`]. Neither field (bare `{}`), the contradiction
1991/// `success: true` + `cancelled: true`, or a non-boolean `success` /
1992/// `cancelled` is a [`Error::CorruptEventLog`].
1993fn report_terminal_status(events_path: &Path, ev: &Event) -> Result<Status> {
1994    let corrupt = |reason: String| Error::CorruptEventLog {
1995        path: events_path.to_path_buf(),
1996        reason,
1997    };
1998    let cancelled = optional_bool(events_path, ev, &ev.data, "cancelled")?.unwrap_or(false);
1999    let success = optional_bool(events_path, ev, &ev.data, "success")?;
2000    if cancelled {
2001        if success == Some(true) {
2002            return Err(corrupt(format!(
2003                "event seq={} kind=node.report has contradictory `success: true` with `cancelled: true`",
2004                ev.seq
2005            )));
2006        }
2007        Ok(Status::Cancelled)
2008    } else {
2009        match success {
2010            Some(true) => Ok(Status::Done),
2011            Some(false) => Ok(Status::Failed),
2012            None => Err(corrupt(format!(
2013                "event seq={} kind=node.report must set boolean `success` or `cancelled: true`",
2014                ev.seq
2015            ))),
2016        }
2017    }
2018}
2019
2020fn reduce_child_spawned(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2021    // `child.spawned` is written to the PARENT run's events; the parent
2022    // spawning node is `ev.node_id`, the child run/node lives in `data`.
2023    let events_path = paths.events();
2024    let parent_node_id = ev.node_id.clone().ok_or_else(|| Error::CorruptEventLog {
2025        path: events_path.clone(),
2026        reason: format!(
2027            "event seq={} kind=child.spawned missing parent `node_id`",
2028            ev.seq
2029        ),
2030    })?;
2031    let child_run_id = RunId::parse_str(want_str(&events_path, ev, &ev.data, "child_run_id")?)
2032        .map_err(|e| corrupt_id(&events_path, ev, &e))?;
2033    let child_node_id = NodeId::parse_str(
2034        ev.data
2035            .get("child_node_id")
2036            .and_then(Value::as_str)
2037            .unwrap_or("n-0001"),
2038    )
2039    .map_err(|e| corrupt_id(&events_path, ev, &e))?;
2040    let mut n = match read_node_opt(paths, &parent_node_id)? {
2041        Some(n) => n,
2042        None => return Ok(vec![]),
2043    };
2044    let new_ref = ChildRef {
2045        run_id: child_run_id,
2046        node_id: child_node_id,
2047    };
2048    if n.children.iter().any(|c| c == &new_ref) {
2049        // Already recorded — pure no-op so replayed events don't churn
2050        // `updated_at` or the projection file.
2051        return Ok(vec![]);
2052    }
2053    n.children.push(new_ref);
2054    n.updated_at = ev.ts;
2055    Ok(vec![ProjectionOp::Node(n)])
2056}
2057
2058/// `supervisor.attached` records the supervisor PID watching the envelope
2059/// node onto `Node.supervisor_pid`. Event-sourced replacement for the
2060/// supervisor's former direct `write_node` (issue
2061/// `supervisor-state-not-event-sourced`), so a from-scratch projection
2062/// rebuild reproduces the field.
2063///
2064/// Latest-wins: a later attach (a supervisor restart binds a fresh PID)
2065/// overrides the recorded value. Re-applying an event that carries the
2066/// already-recorded PID is a pure no-op, so replay never churns the
2067/// projection file's `updated_at`.
2068fn reduce_supervisor_attached(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2069    let events_path = paths.events();
2070    let node_id = require_envelope_node_id(&events_path, ev)?;
2071    let raw = ev
2072        .data
2073        .get("pid")
2074        .and_then(Value::as_i64)
2075        .ok_or_else(|| Error::CorruptEventLog {
2076            path: events_path.clone(),
2077            reason: format!(
2078                "event seq={} kind=supervisor.attached missing/invalid `pid`",
2079                ev.seq
2080            ),
2081        })?;
2082    let pid = i32::try_from(raw).map_err(|_| Error::CorruptEventLog {
2083        path: events_path.clone(),
2084        reason: format!(
2085            "event seq={} kind=supervisor.attached `pid` out of i32 range: {raw}",
2086            ev.seq
2087        ),
2088    })?;
2089    let mut n = match read_node_opt(paths, &node_id)? {
2090        Some(n) => n,
2091        None => return Ok(vec![]),
2092    };
2093    if n.supervisor_pid == Some(pid) {
2094        return Ok(vec![]);
2095    }
2096    n.supervisor_pid = Some(pid);
2097    n.updated_at = ev.ts;
2098    Ok(vec![ProjectionOp::Node(n)])
2099}
2100
2101/// `supervisor.cursor_advanced` mirrors the supervisor's per-child report
2102/// cursor onto the envelope (parent) node's `last_processed_report_seq_by_child`
2103/// map. Event-sourced replacement for the supervisor's former direct
2104/// `write_node` of that map (issue `supervisor-state-not-event-sourced`).
2105///
2106/// The cursor is monotonic: a `report_seq` at or below the recorded
2107/// high-water mark for this child is a no-op, so replaying the same event —
2108/// or an older out-of-order one — never moves the cursor backward or churns
2109/// the projection. This is the §7.3 idempotency guarantee at the reducer
2110/// boundary.
2111fn reduce_supervisor_cursor_advanced(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2112    let events_path = paths.events();
2113    let node_id = require_envelope_node_id(&events_path, ev)?;
2114    let child_run_id = want_str(&events_path, ev, &ev.data, "child_run_id")?;
2115    // Validate the child id even though it only becomes a map key — a forged
2116    // event must not smuggle a path-shaped or malformed run id into the
2117    // projection.
2118    RunId::parse_str(child_run_id).map_err(|e| corrupt_id(&events_path, ev, &e))?;
2119    let report_seq = ev
2120        .data
2121        .get("report_seq")
2122        .and_then(Value::as_u64)
2123        .ok_or_else(|| Error::CorruptEventLog {
2124            path: events_path.clone(),
2125            reason: format!(
2126                "event seq={} kind=supervisor.cursor_advanced missing/invalid `report_seq`",
2127                ev.seq
2128            ),
2129        })?;
2130    let mut n = match read_node_opt(paths, &node_id)? {
2131        Some(n) => n,
2132        None => return Ok(vec![]),
2133    };
2134    if let Some(prev) = n
2135        .last_processed_report_seq_by_child
2136        .get(child_run_id)
2137        .and_then(Value::as_u64)
2138    {
2139        if report_seq <= prev {
2140            return Ok(vec![]);
2141        }
2142    }
2143    n.last_processed_report_seq_by_child
2144        .insert(child_run_id.to_string(), Value::from(report_seq));
2145    n.updated_at = ev.ts;
2146    Ok(vec![ProjectionOp::Node(n)])
2147}
2148
2149/// Longest accepted round-report summary, in bytes.
2150pub const MAX_ROUND_SUMMARY_BYTES: usize = 16 * 1024;
2151
2152fn corrupt(events_path: &Path, ev: &Event, what: &str) -> Error {
2153    Error::CorruptEventLog {
2154        path: events_path.to_path_buf(),
2155        reason: format!("event seq={} kind={} {what}", ev.seq, ev.kind),
2156    }
2157}
2158
2159/// Read the run's resident policy, requiring one: a resident event against an
2160/// ordinary run is a corrupt event (the CLI refuses it before appending).
2161fn require_resident(paths: &RunPaths, events_path: &Path, ev: &Event) -> Result<ResidentPolicy> {
2162    read_manifest_opt(paths)?
2163        .and_then(|m| m.resident)
2164        .ok_or_else(|| corrupt(events_path, ev, "requires a resident run"))
2165}
2166
2167/// Fold `node.round_reported` (ADR 0003): the worker's told end of a round.
2168///
2169/// Payload: `attempt` (the reporting worker attempt, which must be the node's
2170/// current one), a bounded non-blank `summary`, and an optional boolean
2171/// `interrupted` (`run interrupt`: the parent ended the round). A second
2172/// report from the same attempt amends the open round (same number) rather
2173/// than opening a new one; an interrupt never amends a round the worker
2174/// already reported, and a worker report never clears an interrupt. A settled
2175/// node, or a report from a superseded attempt, is a no-op.
2176fn reduce_node_round_reported(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2177    let events_path = paths.events();
2178    let node_id = require_envelope_node_id(&events_path, ev)?;
2179    let summary = ev
2180        .data
2181        .get("summary")
2182        .and_then(Value::as_str)
2183        .filter(|s| !s.trim().is_empty() && s.len() <= MAX_ROUND_SUMMARY_BYTES && !s.contains('\0'))
2184        .ok_or_else(|| {
2185            corrupt(
2186                &events_path,
2187                ev,
2188                &format!(
2189                    "requires a non-blank `summary` of at most {MAX_ROUND_SUMMARY_BYTES} bytes"
2190                ),
2191            )
2192        })?
2193        .to_string();
2194    let attempt = evidence_attempt(&events_path, ev)?;
2195    let interrupted = match ev.data.get("interrupted") {
2196        None => false,
2197        Some(Value::Bool(b)) => *b,
2198        Some(_) => return Err(corrupt(&events_path, ev, "`interrupted` must be a boolean")),
2199    };
2200    require_resident(paths, &events_path, ev)?;
2201    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2202        return Ok(vec![]);
2203    };
2204    if n.status.is_terminal() || attempt != n.retry_attempts {
2205        return Ok(vec![]);
2206    }
2207    let state = n.resident.get_or_insert_with(Box::default);
2208    match state.last_round.as_mut() {
2209        // The worker already ended this round; the interrupt has nothing to do.
2210        Some(open) if open.closed_at.is_none() && open.attempt == attempt && interrupted => {
2211            return Ok(vec![]);
2212        }
2213        Some(open) if open.closed_at.is_none() && open.attempt == attempt => {
2214            open.summary = summary;
2215            open.reported_at = ev.ts;
2216            open.event_seq = ev.seq;
2217        }
2218        _ => {
2219            state.rounds_reported = state.rounds_reported.saturating_add(1);
2220            state.last_round = Some(RoundReport {
2221                round: state.rounds_reported,
2222                attempt,
2223                reported_at: ev.ts,
2224                event_seq: ev.seq,
2225                summary,
2226                interrupted,
2227                closed_at: None,
2228                closed_by: None,
2229            });
2230            state.expiry_attention_at = None;
2231        }
2232    }
2233    // The round report answers any open question of this attempt.
2234    n.awaiting_input = None;
2235    cancel_open_ask(&mut n, ev);
2236    n.updated_at = ev.ts;
2237    Ok(vec![ProjectionOp::Node(n)])
2238}
2239
2240/// Fold `node.resumed` (ADR 0003): a message started the next worker attempt
2241/// from the same native session in the same worktree.
2242///
2243/// Rewires the node to the new attempt exactly like `node.retry` does for the
2244/// agent identity, but keeps the branch, the worktree path and the session,
2245/// closes the open round with `message_id`, and clears dormancy/attention. The
2246/// event carries its absolute `attempt`, which must advance the current one.
2247fn reduce_node_resumed(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2248    let events_path = paths.events();
2249    let node_id = require_envelope_node_id(&events_path, ev)?;
2250    let d = &ev.data;
2251    let attempt = evidence_attempt(&events_path, ev)?;
2252    let message_id = want_str(&events_path, ev, d, "message_id")?.to_string();
2253    let evidence = worker_evidence_from_spawn_data(&events_path, ev, d)?;
2254    let claude_session_id = claude_session_from_data(&events_path, ev, d)?;
2255    require_resident(paths, &events_path, ev)?;
2256    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2257        return Ok(vec![]);
2258    };
2259    if n.status.is_terminal() || attempt <= n.retry_attempts {
2260        return Ok(vec![]);
2261    }
2262    if let Some(sha) = d
2263        .get("base_sha")
2264        .and_then(Value::as_str)
2265        .filter(|s| !s.is_empty())
2266    {
2267        n.base_sha = Some(sha.to_string());
2268    }
2269    n.tmux_window = d
2270        .get("tmux_window")
2271        .and_then(Value::as_str)
2272        .map(str::to_string)
2273        .or(n.tmux_window);
2274    if let Some(identity) = tmux_identity_from_data(d) {
2275        n.tmux_identity = Some(Box::new(identity));
2276    }
2277    n.evidence = evidence;
2278    n.claude_session_id = claude_session_id;
2279    n.agent_pid = optional_i32(d, "agent_pid", &events_path, ev)?;
2280    n.agent_pid_start_time = optional_ts(d, "agent_pid_start_time", &events_path, ev)?;
2281    n.agent_pid_start_identity = start_identity_from_data(d);
2282    n.status = Status::Pending;
2283    n.started_at = Some(ev.ts);
2284    n.updated_at = ev.ts;
2285    n.worker_exit = None;
2286    n.first_death_at = None;
2287    n.awaiting_input = None;
2288    cancel_open_ask(&mut n, ev);
2289    n.pending_merge = None;
2290    n.retained_display = None;
2291    n.retention_unavailable = None;
2292    n.retry_attempts = attempt;
2293    let state = n.resident.get_or_insert_with(Box::default);
2294    if let Some(round) = state.last_round.as_mut().filter(|r| r.closed_at.is_none()) {
2295        round.closed_at = Some(ev.ts);
2296        round.closed_by = Some(message_id);
2297    }
2298    state.dormant_since = None;
2299    state.expiry_attention_at = None;
2300    Ok(vec![ProjectionOp::Node(n)])
2301}
2302
2303/// Fold `node.round_landed` (ADR 0003): `run land` (or recovery of a crashed
2304/// land) fast-forwarded the source branch to the rebased worker tip. Never a
2305/// status transition. Clears the matching landing transaction and moves the
2306/// node's fork point to the integrated tip.
2307fn reduce_node_round_landed(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2308    let events_path = paths.events();
2309    let node_id = require_envelope_node_id(&events_path, ev)?;
2310    let d = &ev.data;
2311    let op_id = want_str(&events_path, ev, d, "op_id")?.to_string();
2312    let source_branch = want_str(&events_path, ev, d, "source_branch")?.to_string();
2313    let integrated_oid = want_str(&events_path, ev, d, "integrated_oid")?.to_string();
2314    if integrated_oid.len() < 40 || !integrated_oid.bytes().all(|b| b.is_ascii_hexdigit()) {
2315        return Err(corrupt(
2316            &events_path,
2317            ev,
2318            "requires a full hex `integrated_oid`",
2319        ));
2320    }
2321    require_resident(paths, &events_path, ev)?;
2322    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2323        return Ok(vec![]);
2324    };
2325    if n.status.is_terminal() {
2326        return Ok(vec![]);
2327    }
2328    if n.pending_merge
2329        .as_ref()
2330        .is_some_and(|txn| txn.landing && txn.op_id == op_id)
2331    {
2332        n.pending_merge = None;
2333    }
2334    n.base_sha = Some(integrated_oid.clone());
2335    let state = n.resident.get_or_insert_with(Box::default);
2336    let round = state.last_round.as_ref().map_or(0, |r| r.round);
2337    state.last_landing = Some(RoundLanding {
2338        at: ev.ts,
2339        source_branch,
2340        integrated_oid,
2341        round,
2342    });
2343    // Landing the work answers an unlanded-work expiry for this round.
2344    state.expiry_attention_at = None;
2345    n.updated_at = ev.ts;
2346    Ok(vec![ProjectionOp::Node(n)])
2347}
2348
2349/// Fold `node.resident_dormant` (ADR 0003): idle expiry removed the worktree
2350/// (and integrated branch) of a wholly landed round. The worktree path, branch
2351/// name and native session stay recorded so the next message can revive it.
2352fn reduce_node_resident_dormant(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2353    let events_path = paths.events();
2354    let node_id = require_envelope_node_id(&events_path, ev)?;
2355    require_resident(paths, &events_path, ev)?;
2356    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2357        return Ok(vec![]);
2358    };
2359    if n.status.is_terminal() {
2360        return Ok(vec![]);
2361    }
2362    let state = n.resident.get_or_insert_with(Box::default);
2363    if state.open_round().is_none() || state.dormant_since.is_some() {
2364        return Ok(vec![]);
2365    }
2366    state.dormant_since = Some(ev.ts);
2367    state.expiry_attention_at = None;
2368    n.updated_at = ev.ts;
2369    Ok(vec![ProjectionOp::Node(n)])
2370}
2371
2372/// Fold `node.resident_attention` (ADR 0003): idle expiry found unlanded or
2373/// unverifiable work and preserved everything. Raised once per open round.
2374fn reduce_node_resident_attention(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2375    let events_path = paths.events();
2376    let node_id = require_envelope_node_id(&events_path, ev)?;
2377    want_str(&events_path, ev, &ev.data, "reason")?;
2378    require_resident(paths, &events_path, ev)?;
2379    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2380        return Ok(vec![]);
2381    };
2382    if n.status.is_terminal() {
2383        return Ok(vec![]);
2384    }
2385    let state = n.resident.get_or_insert_with(Box::default);
2386    if state.open_round().is_none() || state.expiry_attention_at.is_some() {
2387        return Ok(vec![]);
2388    }
2389    state.expiry_attention_at = Some(ev.ts);
2390    n.updated_at = ev.ts;
2391    Ok(vec![ProjectionOp::Node(n)])
2392}
2393
2394#[cfg(test)]
2395mod tests {
2396    use super::*;
2397    use crate::schema::Event;
2398    use jiff::Timestamp;
2399    use tempfile::TempDir;
2400
2401    fn event(run_id: &str) -> Event {
2402        Event {
2403            ts: Timestamp::now(),
2404            seq: 1,
2405            kind: "run.status".into(),
2406            run_id: RunId::parse_str(run_id).unwrap(),
2407            node_id: None,
2408            idempotency_key: None,
2409            data: serde_json::json!({ "status": "running" }),
2410        }
2411    }
2412
2413    #[test]
2414    fn orchestrator_decision_and_discuss_critical_reduce_to_noop() {
2415        // The /orchestrate audit kinds are append-only: the reducer must plan
2416        // ZERO projection ops for them regardless of payload, so the event log
2417        // is their sole home and no projection is created or mutated.
2418        let tmp = TempDir::new().unwrap();
2419        let run_id = "01jxsnap000000000000000000";
2420        let rid = RunId::parse_str(run_id).unwrap();
2421        let dir = crate::run_dir(tmp.path(), &rid);
2422        std::fs::create_dir_all(&dir).unwrap();
2423        let paths = RunPaths::new(dir, run_id).unwrap();
2424
2425        // Bootstrap a manifest so we can prove the audit events leave it
2426        // byte-for-byte untouched (no counter churn, no status drift).
2427        let mut created = event(run_id);
2428        created.kind = "run.created".into();
2429        created.data = serde_json::json!({
2430            "kind": "spinoff", "lifecycle": "autonomous", "title": "t"
2431        });
2432        apply_event(&paths, &created).expect("run.created applies");
2433        let manifest_before = std::fs::read(paths.manifest()).unwrap();
2434
2435        for (seq, kind) in [(10u64, "orchestrator.decision"), (11, "discuss.critical")] {
2436            let mut ev = event(run_id);
2437            ev.seq = seq;
2438            ev.kind = kind.into();
2439            // A non-trivial payload to prove the reducer ignores it wholesale.
2440            ev.data = serde_json::json!({ "summary": "x", "arbitrary": [1, 2, 3] });
2441            let ops = reduce_event_to_ops(&paths, &ev).expect("audit kind reduces cleanly");
2442            assert!(ops.is_empty(), "{kind} must plan no projection ops");
2443            // apply_event is the plan+commit path; it must also be a clean no-op.
2444            apply_event(&paths, &ev).expect("audit kind applies as no-op");
2445        }
2446
2447        // The manifest is unchanged and no stray projection dirs appeared.
2448        assert_eq!(
2449            std::fs::read(paths.manifest()).unwrap(),
2450            manifest_before,
2451            "audit events must not mutate the manifest"
2452        );
2453        assert!(!paths.nodes_dir().exists(), "no node projection created");
2454    }
2455
2456    #[test]
2457    fn run_created_folds_harness_when_present_and_defaults_none() {
2458        let tmp = TempDir::new().unwrap();
2459
2460        // A `run.created` carrying `harness` folds it onto the manifest.
2461        let run_id = "01jxhrnsaa0000000000000001";
2462        let rid = RunId::parse_str(run_id).unwrap();
2463        let dir = crate::run_dir(tmp.path(), &rid);
2464        std::fs::create_dir_all(&dir).unwrap();
2465        let paths = RunPaths::new(dir, run_id).unwrap();
2466        let mut created = event(run_id);
2467        created.kind = "run.created".into();
2468        created.data = serde_json::json!({
2469            "kind": "spinoff", "lifecycle": "autonomous", "title": "t",
2470            "harness": "pi", "harness_source": "flag",
2471        });
2472        apply_event(&paths, &created).expect("run.created applies");
2473        let m = read_manifest_opt(&paths).unwrap().unwrap();
2474        assert_eq!(m.harness.as_deref(), Some("pi"));
2475
2476        // A `run.created` WITHOUT `harness` (legacy / claude) leaves it `None`.
2477        let run_id2 = "01jxhrnsaa0000000000000002";
2478        let rid2 = RunId::parse_str(run_id2).unwrap();
2479        let dir2 = crate::run_dir(tmp.path(), &rid2);
2480        std::fs::create_dir_all(&dir2).unwrap();
2481        let paths2 = RunPaths::new(dir2, run_id2).unwrap();
2482        let mut created2 = event(run_id2);
2483        created2.kind = "run.created".into();
2484        created2.data =
2485            serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" });
2486        apply_event(&paths2, &created2).expect("run.created applies");
2487        let m2 = read_manifest_opt(&paths2).unwrap().unwrap();
2488        assert_eq!(m2.harness, None);
2489    }
2490
2491    /// Bootstrap a run manifest + one live `n-0001` spinoff node, returning its
2492    /// paths. Used by the `node.retry` reducer tests.
2493    fn bootstrap_retry_node(tmp: &TempDir, run_id: &str) -> RunPaths {
2494        let rid = RunId::parse_str(run_id).unwrap();
2495        let dir = crate::run_dir(tmp.path(), &rid);
2496        std::fs::create_dir_all(&dir).unwrap();
2497        let paths = RunPaths::new(dir, run_id).unwrap();
2498        let mut created = event(run_id);
2499        created.kind = "run.created".into();
2500        created.data =
2501            serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" });
2502        apply_event(&paths, &created).expect("run.created applies");
2503        let mut node = event(run_id);
2504        node.seq = 2;
2505        node.kind = "node.created".into();
2506        node.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2507        node.data = serde_json::json!({
2508            "kind": "spinoff",
2509            "branch": "wt/foo",
2510            "worktree_path": "/tmp/old-wt",
2511            "agent_pid": 111,
2512        });
2513        apply_event(&paths, &node).expect("node.created applies");
2514        paths
2515    }
2516
2517    /// `node.retry` rewires the node to the freshly re-spawned agent, returns it to
2518    /// `Pending`, re-stamps `started_at`, and increments the durable
2519    /// `retry_attempts` bound (issue `autoretry-agent-died-worker`).
2520    #[test]
2521    fn node_retry_rewires_node_and_increments_attempts() {
2522        let tmp = TempDir::new().unwrap();
2523        let run_id = "01jxsnap000000000000000000";
2524        let paths = bootstrap_retry_node(&tmp, run_id);
2525
2526        let mut retry = event(run_id);
2527        retry.seq = 3;
2528        retry.kind = "node.retry".into();
2529        retry.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2530        retry.data = serde_json::json!({
2531            "attempt": 1,
2532            "reason": "agent-died",
2533            "branch": "wt/foo-r1",
2534            "base_sha": "a".repeat(40),
2535            "worktree_path": "/tmp/new-wt",
2536            "agent_pid": 222,
2537            "tmux_session": "s",
2538            "tmux_window_id": "@9",
2539        });
2540        apply_event(&paths, &retry).expect("node.retry applies");
2541
2542        let n = read_n0001(&paths);
2543        assert_eq!(n.retry_attempts, 1, "attempt bound incremented");
2544        assert_eq!(
2545            n.branch.as_deref(),
2546            Some("wt/foo-r1"),
2547            "rewired to new branch"
2548        );
2549        assert_eq!(n.worktree_path.as_deref(), Some("/tmp/new-wt"));
2550        assert_eq!(n.agent_pid, Some(222), "rewired to new agent pid");
2551        assert_eq!(n.status, Status::Pending, "node returns to pending");
2552        assert!(n.last_report.is_none());
2553        assert_eq!(
2554            n.tmux_identity.as_ref().map(|t| t.window_id.as_str()),
2555            Some("@9"),
2556            "rewired tmux identity"
2557        );
2558
2559        // A second retry increments again — the bound is monotone.
2560        let mut retry2 = event(run_id);
2561        retry2.seq = 4;
2562        retry2.kind = "node.retry".into();
2563        retry2.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2564        retry2.data = serde_json::json!({
2565            "attempt": 2, "reason": "agent-died", "branch": "wt/foo-r2",
2566            "worktree_path": "/tmp/new-wt-2", "agent_pid": 333,
2567        });
2568        apply_event(&paths, &retry2).expect("node.retry applies");
2569        assert_eq!(read_n0001(&paths).retry_attempts, 2);
2570    }
2571
2572    #[test]
2573    fn stale_worker_evidence_and_exit_do_not_cross_retry_generation() {
2574        let tmp = TempDir::new().unwrap();
2575        let run_id = "01jxsnap000000000000000000";
2576        let paths = bootstrap_retry_node(&tmp, run_id);
2577        let nid = NodeId::parse_str("n-0001").unwrap();
2578        let current_session = "018f5f64-b137-7d44-b2b4-4f02c3f646e8";
2579
2580        let mut retry = event(run_id);
2581        retry.seq = 3;
2582        retry.kind = "node.retry".into();
2583        retry.node_id = Some(nid.clone());
2584        retry.data = serde_json::json!({
2585            "attempt": 1, "reason": "agent-died", "branch": "wt/foo-r1",
2586            "worktree_path": "/tmp/new-wt", "agent_pid": 222,
2587            "pi_session_id": current_session,
2588            "pi_session_path": format!(".creating/pi-sessions/{run_id}/pi-session-{current_session}.jsonl"),
2589            "pi_session_cwd": "/tmp/new-wt"
2590        });
2591        apply_event(&paths, &retry).unwrap();
2592
2593        let mut stale_failure = event(run_id);
2594        stale_failure.seq = 4;
2595        stale_failure.kind = "worker.evidence.failed".into();
2596        stale_failure.node_id = Some(nid.clone());
2597        stale_failure.data = serde_json::json!({
2598            "attempt": 0,
2599            "session_id": "118f5f64-b137-7d44-b2b4-4f02c3f646e8",
2600            "error": "old attempt"
2601        });
2602        apply_event(&paths, &stale_failure).unwrap();
2603        assert_eq!(
2604            read_n0001(&paths).evidence.unwrap().status,
2605            EvidenceStatus::Pending
2606        );
2607
2608        let mut stale_exit = event(run_id);
2609        stale_exit.seq = 5;
2610        stale_exit.kind = "worker.exited".into();
2611        stale_exit.node_id = Some(nid.clone());
2612        stale_exit.data = serde_json::json!({"attempt":0,"exit_code":9});
2613        apply_event(&paths, &stale_exit).unwrap();
2614        assert!(read_n0001(&paths).worker_exit.is_none());
2615
2616        let mut archived = event(run_id);
2617        archived.seq = 6;
2618        archived.kind = "worker.evidence.archived".into();
2619        archived.node_id = Some(nid);
2620        archived.data = serde_json::json!({
2621            "attempt":1, "session_id":current_session,
2622            "transcript_path":"evidence/n-0001/pi-session.original.jsonl",
2623            "resume_path":"evidence/n-0001/pi-session.resume.jsonl",
2624            "pane_path":"evidence/n-0001/final-pane.log",
2625            "report_path":"evidence/n-0001/terminal-report.json",
2626            "transcript_sha256":"0".repeat(64)
2627        });
2628        apply_event(&paths, &archived).unwrap();
2629        assert_eq!(
2630            read_n0001(&paths).evidence.unwrap().status,
2631            EvidenceStatus::Complete
2632        );
2633    }
2634
2635    /// A `node.retry` against an already-terminal node is a dead event: the
2636    /// terminal-state invariant holds, so a late retry never resurrects a settled
2637    /// node (a real report that raced in wins).
2638    #[test]
2639    fn node_retry_against_terminal_node_is_noop() {
2640        let tmp = TempDir::new().unwrap();
2641        let run_id = "01jxsnap000000000000000000";
2642        let paths = bootstrap_retry_node(&tmp, run_id);
2643
2644        // Terminalize the node via a success report.
2645        let mut report = event(run_id);
2646        report.seq = 3;
2647        report.kind = "node.report".into();
2648        report.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2649        report.data = serde_json::json!({ "success": true });
2650        apply_event(&paths, &report).expect("node.report applies");
2651        assert_eq!(read_n0001(&paths).status, Status::Done);
2652
2653        let mut retry = event(run_id);
2654        retry.seq = 4;
2655        retry.kind = "node.retry".into();
2656        retry.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2657        retry.data = serde_json::json!({
2658            "attempt": 1, "reason": "agent-died", "branch": "wt/foo-r1",
2659            "worktree_path": "/tmp/new-wt", "agent_pid": 222,
2660        });
2661        apply_event(&paths, &retry).expect("node.retry applies as no-op");
2662
2663        let n = read_n0001(&paths);
2664        assert_eq!(n.status, Status::Done, "terminal node not resurrected");
2665        assert_eq!(n.retry_attempts, 0, "no increment against terminal node");
2666        assert_eq!(n.agent_pid, Some(111), "not rewired");
2667    }
2668
2669    #[test]
2670    fn apply_event_rejects_event_from_a_different_run() {
2671        let tmp = TempDir::new().unwrap();
2672        let run_id = "01jxsnap000000000000000000";
2673        let rid = RunId::parse_str(run_id).unwrap();
2674        let dir = crate::run_dir(tmp.path(), &rid);
2675        std::fs::create_dir_all(&dir).unwrap();
2676        let paths = RunPaths::new(dir, run_id).unwrap();
2677
2678        // An event whose envelope names a different run must not be folded.
2679        let foreign = event("02jxsnap000000000000000000");
2680        let err = apply_event(&paths, &foreign).expect_err("cross-run event must be rejected");
2681        assert!(matches!(err, Error::CorruptEventLog { .. }), "got {err:?}");
2682
2683        // The matching run_id is accepted (no projection exists yet, so
2684        // `run.status` is a clean no-op rather than an error).
2685        let mine = event(run_id);
2686        apply_event(&paths, &mine).expect("matching run_id must be accepted");
2687    }
2688
2689    #[test]
2690    fn tmux_identity_from_data_reads_qualified_fields() {
2691        let d = serde_json::json!({
2692            "tmux_socket": "/private/tmp/tmux-501/default",
2693            "tmux_session": "taskfleet",
2694            "tmux_window_id": "@42",
2695        });
2696        let id = tmux_identity_from_data(&d).expect("qualified identity");
2697        assert_eq!(id.socket.as_deref(), Some("/private/tmp/tmux-501/default"));
2698        assert_eq!(id.session, "taskfleet");
2699        assert_eq!(id.window_id, "@42");
2700        // No pane_id in this event → None (back-compat / older create.sh).
2701        assert_eq!(id.pane_id, None);
2702
2703        // Null socket is tolerated — session + window_id are the minimum.
2704        let d2 = serde_json::json!({
2705            "tmux_socket": null,
2706            "tmux_session": "taskfleet",
2707            "tmux_window_id": "@7",
2708        });
2709        let id2 = tmux_identity_from_data(&d2).expect("identity without socket");
2710        assert_eq!(id2.socket, None);
2711        assert_eq!(id2.window_id, "@7");
2712
2713        // A create.sh that emits `tmux_pane_id` is folded into the identity.
2714        let d3 = serde_json::json!({
2715            "tmux_session": "taskfleet",
2716            "tmux_window_id": "@42",
2717            "tmux_pane_id": "%7",
2718        });
2719        let id3 = tmux_identity_from_data(&d3).expect("identity with pane");
2720        assert_eq!(id3.pane_id.as_deref(), Some("%7"));
2721        assert_eq!(id3.capture_target(), "%7");
2722
2723        // Explicit `tmux_pane_id: null` (create.sh emits null when its pane
2724        // query failed) must fold to None — never `Some("null")`.
2725        let d4 = serde_json::json!({
2726            "tmux_session": "taskfleet",
2727            "tmux_window_id": "@42",
2728            "tmux_pane_id": null,
2729        });
2730        let id4 = tmux_identity_from_data(&d4).expect("identity with null pane");
2731        assert_eq!(id4.pane_id, None);
2732        assert_eq!(id4.capture_target(), "@42");
2733    }
2734
2735    #[test]
2736    fn tmux_identity_from_data_back_compat_is_none() {
2737        // Legacy create.sh: no qualified fields at all.
2738        let legacy = serde_json::json!({ "tmux_window": "🚀 wt/x" });
2739        assert!(tmux_identity_from_data(&legacy).is_none());
2740        // Partial (window_id without session) is also insufficient → None.
2741        let partial = serde_json::json!({ "tmux_window_id": "@42" });
2742        assert!(tmux_identity_from_data(&partial).is_none());
2743    }
2744
2745    /// End-to-end: a `node.created` event carrying the qualified fields folds
2746    /// them into `Node.tmux_identity`; one without them leaves it `None`.
2747    #[test]
2748    fn node_created_populates_tmux_identity() {
2749        let tmp = TempDir::new().unwrap();
2750        let run_id = "01jxsnap000000000000000000";
2751        let rid = RunId::parse_str(run_id).unwrap();
2752        let dir = crate::run_dir(tmp.path(), &rid);
2753        std::fs::create_dir_all(&dir).unwrap();
2754        let paths = RunPaths::new(dir, run_id).unwrap();
2755
2756        let mut ev = event(run_id);
2757        ev.seq = 2;
2758        ev.kind = "node.created".into();
2759        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2760        ev.data = serde_json::json!({
2761            "kind": "spinoff",
2762            "tmux_window": "🚀 wt/x",
2763            "tmux_socket": "/private/tmp/tmux-501/default",
2764            "tmux_session": "taskfleet",
2765            "tmux_window_id": "@42",
2766        });
2767        apply_event(&paths, &ev).expect("node.created applies");
2768        let n = read_node_opt(&paths, &NodeId::parse_str("n-0001").unwrap())
2769            .unwrap()
2770            .unwrap();
2771        let id = n.tmux_identity.expect("qualified identity recorded");
2772        assert_eq!(id.session, "taskfleet");
2773        assert_eq!(id.window_id, "@42");
2774        assert_eq!(n.tmux_window.as_deref(), Some("🚀 wt/x"));
2775
2776        // A second run with a legacy event leaves tmux_identity None.
2777        let run2 = "02jxsnap000000000000000000";
2778        let rid2 = RunId::parse_str(run2).unwrap();
2779        let dir2 = crate::run_dir(tmp.path(), &rid2);
2780        std::fs::create_dir_all(&dir2).unwrap();
2781        let paths2 = RunPaths::new(dir2, run2).unwrap();
2782        let mut ev2 = event(run2);
2783        ev2.seq = 2;
2784        ev2.kind = "node.created".into();
2785        ev2.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2786        ev2.data = serde_json::json!({ "kind": "spinoff", "tmux_window": "🚀 wt/y" });
2787        apply_event(&paths2, &ev2).expect("legacy node.created applies");
2788        let n2 = read_node_opt(&paths2, &NodeId::parse_str("n-0001").unwrap())
2789            .unwrap()
2790            .unwrap();
2791        assert!(n2.tmux_identity.is_none());
2792        assert_eq!(n2.tmux_window.as_deref(), Some("🚀 wt/y"));
2793    }
2794
2795    #[test]
2796    fn node_materialization_populates_missing_manifest_source_branch() {
2797        let tmp = TempDir::new().unwrap();
2798        let run_id = "01jxsnap000000000000000001";
2799        let rid = RunId::parse_str(run_id).unwrap();
2800        let dir = crate::run_dir(tmp.path(), &rid);
2801        std::fs::create_dir_all(&dir).unwrap();
2802        let paths = RunPaths::new(dir, run_id).unwrap();
2803
2804        let mut created = event(run_id);
2805        created.kind = "run.created".into();
2806        created.data = serde_json::json!({
2807            "kind": "spinoff", "lifecycle": "autonomous", "title": "t"
2808        });
2809        apply_event(&paths, &created).unwrap();
2810        assert!(read_manifest_opt(&paths)
2811            .unwrap()
2812            .unwrap()
2813            .source_branch
2814            .is_none());
2815
2816        let mut node = event(run_id);
2817        node.seq = 2;
2818        node.kind = "node.created".into();
2819        node.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2820        node.data = serde_json::json!({
2821            "kind": "spinoff",
2822            "source_branch": "main",
2823            "worktree_path": "/tmp/wt/pending"
2824        });
2825        apply_event(&paths, &node).unwrap();
2826
2827        let manifest = read_manifest_opt(&paths).unwrap().unwrap();
2828        assert_eq!(manifest.status, Status::Pending);
2829        assert_eq!(manifest.source_branch.as_deref(), Some("main"));
2830        let node = read_n0001(&paths);
2831        assert_eq!(node.worktree_path.as_deref(), Some("/tmp/wt/pending"));
2832    }
2833
2834    #[test]
2835    fn node_materialization_preserves_explicit_manifest_source_branch() {
2836        let tmp = TempDir::new().unwrap();
2837        let run_id = "01jxsnap000000000000000002";
2838        let rid = RunId::parse_str(run_id).unwrap();
2839        let dir = crate::run_dir(tmp.path(), &rid);
2840        std::fs::create_dir_all(&dir).unwrap();
2841        let paths = RunPaths::new(dir, run_id).unwrap();
2842
2843        let mut created = event(run_id);
2844        created.kind = "run.created".into();
2845        created.data = serde_json::json!({
2846            "kind": "spinoff", "lifecycle": "autonomous", "title": "t",
2847            "source_branch": "release"
2848        });
2849        apply_event(&paths, &created).unwrap();
2850
2851        let mut node = event(run_id);
2852        node.seq = 2;
2853        node.kind = "node.created".into();
2854        node.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2855        node.data = serde_json::json!({
2856            "kind": "spinoff", "source_branch": "main"
2857        });
2858        apply_event(&paths, &node).unwrap();
2859
2860        assert_eq!(
2861            read_manifest_opt(&paths)
2862                .unwrap()
2863                .unwrap()
2864                .source_branch
2865                .as_deref(),
2866            Some("release")
2867        );
2868    }
2869
2870    /// Bootstrap a run with a single `n-0001` node via the event-sourced path,
2871    /// returning its paths. Shared by the supervisor-state replay tests below.
2872    fn seed_run_with_node(tmp: &TempDir, run_id: &str) -> RunPaths {
2873        let rid = RunId::parse_str(run_id).unwrap();
2874        let dir = crate::run_dir(tmp.path(), &rid);
2875        std::fs::create_dir_all(&dir).unwrap();
2876        let paths = RunPaths::new(dir, run_id).unwrap();
2877
2878        let mut created = event(run_id);
2879        created.kind = "run.created".into();
2880        created.data = serde_json::json!({
2881            "kind": "spinoff", "lifecycle": "autonomous", "title": "t"
2882        });
2883        apply_event(&paths, &created).expect("run.created applies");
2884
2885        let mut node = event(run_id);
2886        node.seq = 2;
2887        node.kind = "node.created".into();
2888        node.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2889        node.data = serde_json::json!({ "kind": "spinoff" });
2890        apply_event(&paths, &node).expect("node.created applies");
2891        paths
2892    }
2893
2894    fn read_n0001(paths: &RunPaths) -> Node {
2895        read_node_opt(paths, &NodeId::parse_str("n-0001").unwrap())
2896            .unwrap()
2897            .unwrap()
2898    }
2899
2900    #[test]
2901    fn awaiting_input_clock_is_durable_first_write_wins_and_resolve_is_fenced() {
2902        let tmp = TempDir::new().unwrap();
2903        let run_id = "01jxwd0000000000000000000w";
2904        let paths = seed_run_with_node(&tmp, run_id);
2905        let nid = Some(NodeId::parse_str("n-0001").unwrap());
2906        let opened_at: jiff::Timestamp = "2026-08-16T12:00:00Z".parse().unwrap();
2907        let mut open = event(run_id);
2908        open.seq = 3;
2909        open.ts = opened_at;
2910        open.kind = "node.awaiting_input".into();
2911        open.node_id = nid.clone();
2912        open.data = serde_json::json!({ "discussion_items": [{
2913            "topic": "Which scope?",
2914            "options": ["small", "large"],
2915            "recommended_default": "small"
2916        }] });
2917        apply_event(&paths, &open).unwrap();
2918        let first = read_n0001(&paths).awaiting_input.unwrap();
2919        assert_eq!(first.opened_at, opened_at);
2920        assert_eq!(first.event_seq, 3);
2921
2922        // A duplicate/restarted supervisor observation cannot restart the clock.
2923        let mut duplicate = open.clone();
2924        duplicate.seq = 4;
2925        duplicate.ts = opened_at + jiff::SignedDuration::from_hours(1);
2926        apply_event(&paths, &duplicate).unwrap();
2927        let still_first = read_n0001(&paths).awaiting_input.unwrap();
2928        assert_eq!(still_first.opened_at, opened_at);
2929        assert_eq!(still_first.event_seq, 3);
2930
2931        // A stale timeout for another generation cannot clear this request.
2932        let mut stale = event(run_id);
2933        stale.seq = 5;
2934        stale.kind = "node.input_resolved".into();
2935        stale.node_id = nid.clone();
2936        stale.data = serde_json::json!({ "event_seq": 2 });
2937        apply_event(&paths, &stale).unwrap();
2938        assert!(read_n0001(&paths).awaiting_input.is_some());
2939
2940        let mut resolved = stale;
2941        resolved.seq = 6;
2942        resolved.data = serde_json::json!({ "event_seq": 3 });
2943        apply_event(&paths, &resolved).unwrap();
2944        assert!(read_n0001(&paths).awaiting_input.is_none());
2945    }
2946
2947    #[test]
2948    fn awaiting_input_rejects_missing_default_without_mutating_projection() {
2949        let tmp = TempDir::new().unwrap();
2950        let run_id = "01jxwd0000000000000000000x";
2951        let paths = seed_run_with_node(&tmp, run_id);
2952        let mut open = event(run_id);
2953        open.seq = 3;
2954        open.kind = "node.awaiting_input".into();
2955        open.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2956        open.data = serde_json::json!({ "discussion_items": [{
2957            "topic": "Which scope?", "options": ["small", "large"]
2958        }] });
2959        assert!(reduce_event_to_ops(&paths, &open).is_err());
2960        assert!(read_n0001(&paths).awaiting_input.is_none());
2961    }
2962
2963    #[test]
2964    fn awaiting_input_validation_is_state_independent_and_worker_exit_clears_it() {
2965        let tmp = TempDir::new().unwrap();
2966        let run_id = "01jxwd0000000000000000000y";
2967        let paths = seed_run_with_node(&tmp, run_id);
2968        let nid = Some(NodeId::parse_str("n-0001").unwrap());
2969
2970        let mut open = event(run_id);
2971        open.seq = 3;
2972        open.kind = "node.awaiting_input".into();
2973        open.node_id = nid.clone();
2974        open.data = serde_json::json!({ "discussion_items": [{
2975            "topic": "Which scope?", "options": ["small", "large"],
2976            "recommended_default": "small"
2977        }] });
2978        apply_event(&paths, &open).unwrap();
2979
2980        let mut malformed_duplicate = open.clone();
2981        malformed_duplicate.seq = 4;
2982        malformed_duplicate.data = serde_json::json!({ "discussion_items": [] });
2983        assert!(reduce_event_to_ops(&paths, &malformed_duplicate).is_err());
2984
2985        let mut exited = event(run_id);
2986        exited.seq = 5;
2987        exited.kind = "worker.exited".into();
2988        exited.node_id = nid;
2989        exited.data = serde_json::json!({ "exit_code": 0 });
2990        apply_event(&paths, &exited).unwrap();
2991        let node = read_n0001(&paths);
2992        assert!(node.awaiting_input.is_none());
2993        assert!(node.worker_exit.is_some());
2994
2995        let mut delayed_open = open;
2996        delayed_open.seq = 6;
2997        assert!(reduce_event_to_ops(&paths, &delayed_open)
2998            .unwrap()
2999            .is_empty());
3000    }
3001
3002    #[test]
3003    fn input_resolved_requires_generation_even_when_nothing_is_open() {
3004        let tmp = TempDir::new().unwrap();
3005        let run_id = "01jxwd0000000000000000000z";
3006        let paths = seed_run_with_node(&tmp, run_id);
3007        let mut resolved = event(run_id);
3008        resolved.seq = 3;
3009        resolved.kind = "node.input_resolved".into();
3010        resolved.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3011        resolved.data = serde_json::json!({});
3012        assert!(reduce_event_to_ops(&paths, &resolved).is_err());
3013    }
3014
3015    #[test]
3016    fn awaiting_input_default_must_be_one_of_options() {
3017        let tmp = TempDir::new().unwrap();
3018        let run_id = "01jxwd00000000000000000010";
3019        let paths = seed_run_with_node(&tmp, run_id);
3020        let mut open = event(run_id);
3021        open.seq = 3;
3022        open.kind = "node.awaiting_input".into();
3023        open.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3024        open.data = serde_json::json!({ "discussion_items": [{
3025            "topic": "Which scope?", "options": ["small", "large"],
3026            "recommended_default": "other"
3027        }] });
3028        assert!(reduce_event_to_ops(&paths, &open).is_err());
3029    }
3030
3031    fn merge_started_event(run_id: &str, seq: u64, op_id: &str, expected: &str) -> Event {
3032        let mut ev = event(run_id);
3033        ev.seq = seq;
3034        ev.kind = KIND_MERGE_STARTED.into();
3035        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3036        ev.data = serde_json::json!({
3037            "op_id": op_id,
3038            "source_branch": "main",
3039            "worker_branch": "wt/worker",
3040            "expected_source_oid": expected,
3041            "worker_oid": "cafebabecafebabecafebabecafebabecafebabe",
3042            "base_sha": null,
3043            "driver_pid": 4242,
3044            "driver_pid_start_secs": null,
3045            "started_at": "2026-08-15T00:00:00Z",
3046        });
3047        ev
3048    }
3049
3050    /// `merge.started` records the in-flight transaction on `pending_merge`
3051    /// without transitioning the node's status.
3052    #[test]
3053    fn merge_started_records_pending_transaction() {
3054        let tmp = TempDir::new().unwrap();
3055        let run_id = "01jxsnap000000000000000000";
3056        let paths = seed_run_with_node(&tmp, run_id);
3057
3058        apply_event(&paths, &merge_started_event(run_id, 3, "op-1", "aaa")).unwrap();
3059        let n = read_n0001(&paths);
3060        assert_eq!(
3061            n.status,
3062            Status::Pending,
3063            "recording a merge is not terminal"
3064        );
3065        let txn = n.pending_merge.expect("transaction recorded");
3066        assert_eq!(txn.op_id, "op-1");
3067        assert_eq!(txn.expected_source_oid, "aaa");
3068    }
3069
3070    /// `merge.aborted` clears the pending transaction it names, leaving the node
3071    /// live; a stale abort for a different `op_id` is a clean no-op.
3072    #[test]
3073    fn merge_aborted_clears_matching_transaction_only() {
3074        let tmp = TempDir::new().unwrap();
3075        let run_id = "01jxsnap000000000000000000";
3076        let paths = seed_run_with_node(&tmp, run_id);
3077        apply_event(&paths, &merge_started_event(run_id, 3, "op-1", "aaa")).unwrap();
3078
3079        // A stale abort for a different op_id does nothing.
3080        let mut stale = event(run_id);
3081        stale.seq = 4;
3082        stale.kind = KIND_MERGE_ABORTED.into();
3083        stale.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3084        stale.data = serde_json::json!({ "op_id": "op-OTHER", "reason": "x" });
3085        apply_event(&paths, &stale).unwrap();
3086        assert!(
3087            read_n0001(&paths).pending_merge.is_some(),
3088            "stale abort is a no-op"
3089        );
3090
3091        // The matching abort clears it; the node stays live.
3092        let mut abort = event(run_id);
3093        abort.seq = 5;
3094        abort.kind = KIND_MERGE_ABORTED.into();
3095        abort.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3096        abort.data = serde_json::json!({ "op_id": "op-1", "reason": "no mutation" });
3097        apply_event(&paths, &abort).unwrap();
3098        let n = read_n0001(&paths);
3099        assert!(
3100            n.pending_merge.is_none(),
3101            "matching abort clears the transaction"
3102        );
3103        assert_eq!(n.status, Status::Pending, "abort does not terminalize");
3104    }
3105
3106    /// A terminal `node.report` (the normal, no-crash completion) clears any
3107    /// pending merge transaction.
3108    #[test]
3109    fn terminal_report_clears_pending_merge() {
3110        let tmp = TempDir::new().unwrap();
3111        let run_id = "01jxsnap000000000000000000";
3112        let paths = seed_run_with_node(&tmp, run_id);
3113        apply_event(&paths, &merge_started_event(run_id, 3, "op-1", "aaa")).unwrap();
3114
3115        let mut report = event(run_id);
3116        report.seq = 4;
3117        report.kind = "node.report".into();
3118        report.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3119        report.data = serde_json::json!({ "success": true, "via": "explicit-merge" });
3120        apply_event(&paths, &report).unwrap();
3121        let n = read_n0001(&paths);
3122        assert_eq!(n.status, Status::Done);
3123        assert!(
3124            n.pending_merge.is_none(),
3125            "completed merge clears the transaction"
3126        );
3127    }
3128
3129    /// Regression (issue `retire-via-string`): the terminal-node adoption
3130    /// exception now keys on the typed `RunMerge` origin, NOT a forgeable `via`
3131    /// string. A late report against a `Failed` node that carries an `Agent`
3132    /// origin (as every `node report` self-submission does) plus a forged
3133    /// `via: "explicit-merge"` must NOT be adopted — the node stays `Failed`. A
3134    /// present-but-malformed origin is likewise not adopted. Only a genuine
3135    /// `RunMerge`-origin report (or a legacy report with NO origin field) is
3136    /// adopted and corrects the node to `Done`.
3137    #[test]
3138    fn late_merge_adoption_requires_run_merge_origin_not_forged_via() {
3139        let tmp = TempDir::new().unwrap();
3140
3141        // Helper: seed a fresh run (distinct id), drive n-0001 to Failed, apply a
3142        // late report, and return the resulting node status.
3143        let drive = |run_id: &str, report_data: Value| -> Status {
3144            let paths = seed_run_with_node(&tmp, run_id);
3145            // Terminalize the node as Failed (a watchdog-synthesized failure).
3146            let mut fail = event(run_id);
3147            fail.seq = 3;
3148            fail.kind = "node.status".into();
3149            fail.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3150            fail.data = serde_json::json!({ "status": "failed" });
3151            apply_event(&paths, &fail).unwrap();
3152            assert_eq!(read_n0001(&paths).status, Status::Failed);
3153            // The late report under test.
3154            let mut report = event(run_id);
3155            report.seq = 4;
3156            report.kind = "node.report".into();
3157            report.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3158            report.data = report_data;
3159            apply_event(&paths, &report).unwrap();
3160            read_n0001(&paths).status
3161        };
3162
3163        // Forged: Agent origin + a hand-set `via` — NOT adopted, stays Failed.
3164        let mut agent_forged = serde_json::json!({ "success": true, "via": "explicit-merge" });
3165        crate::ReportOrigin::Agent.stamp(&mut agent_forged);
3166        assert_eq!(
3167            drive("01jxsnap000000000000000001", agent_forged),
3168            Status::Failed,
3169            "an Agent-origin report with a forged via must not be adopted"
3170        );
3171
3172        // Present-but-malformed origin + forged via — NOT adopted, stays Failed.
3173        let malformed = serde_json::json!({
3174            "success": true, "via": "explicit-merge", "origin": "garbage-not-an-object"
3175        });
3176        assert_eq!(
3177            drive("01jxsnap000000000000000002", malformed),
3178            Status::Failed,
3179            "a malformed origin must not re-unlock the legacy via adoption path"
3180        );
3181
3182        // Genuine RunMerge origin (no `via` at all) — adopted, corrected to Done.
3183        let mut run_merge = serde_json::json!({ "success": true });
3184        crate::ReportOrigin::RunMerge {
3185            op_id: Some("op-1".into()),
3186            worker_oid: Some("cafebabe".into()),
3187            integrated_oid: None,
3188        }
3189        .stamp(&mut run_merge);
3190        assert_eq!(
3191            drive("01jxsnap000000000000000003", run_merge),
3192            Status::Done,
3193            "a genuine RunMerge-origin report is adopted and corrects Failed→Done"
3194        );
3195
3196        // Legacy report (no origin field) with `via` — still adopted (backward
3197        // compat with pre-typed-origin on-disk runs).
3198        let legacy = serde_json::json!({ "success": true, "via": "explicit-merge" });
3199        assert_eq!(
3200            drive("01jxsnap000000000000000004", legacy),
3201            Status::Done,
3202            "a legacy via-only report (no origin field) is still adopted"
3203        );
3204    }
3205
3206    /// A terminal `node.status` (e.g. a watchdog-synthesized failure) clears any
3207    /// in-flight merge transaction, so `pending_merge` is never stranded on a
3208    /// terminal node where recovery would refuse to look (/llm-review finding).
3209    #[test]
3210    fn terminal_node_status_clears_pending_merge() {
3211        let tmp = TempDir::new().unwrap();
3212        let run_id = "01jxsnap000000000000000000";
3213        let paths = seed_run_with_node(&tmp, run_id);
3214        apply_event(&paths, &merge_started_event(run_id, 3, "op-1", "aaa")).unwrap();
3215        assert!(read_n0001(&paths).pending_merge.is_some());
3216
3217        let mut status = event(run_id);
3218        status.seq = 4;
3219        status.kind = "node.status".into();
3220        status.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3221        status.data = serde_json::json!({ "status": "failed" });
3222        apply_event(&paths, &status).unwrap();
3223        let n = read_n0001(&paths);
3224        assert_eq!(n.status, Status::Failed);
3225        assert!(
3226            n.pending_merge.is_none(),
3227            "terminal status clears the transaction"
3228        );
3229    }
3230
3231    /// Replaying `supervisor.attached` from scratch reproduces
3232    /// `Node.supervisor_pid` — the field is now event-sourced, not a
3233    /// projection-only write (issue `supervisor-state-not-event-sourced`).
3234    #[test]
3235    fn supervisor_attached_sets_supervisor_pid() {
3236        let tmp = TempDir::new().unwrap();
3237        let run_id = "01jxsnap000000000000000000";
3238        let paths = seed_run_with_node(&tmp, run_id);
3239        assert_eq!(read_n0001(&paths).supervisor_pid, None);
3240
3241        let mut ev = event(run_id);
3242        ev.seq = 3;
3243        ev.kind = "supervisor.attached".into();
3244        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3245        ev.data = serde_json::json!({ "pid": 47820 });
3246        apply_event(&paths, &ev).expect("supervisor.attached applies");
3247        assert_eq!(read_n0001(&paths).supervisor_pid, Some(47820));
3248    }
3249
3250    /// A second attach with a different pid overrides (latest-wins); a replay
3251    /// of the *same* pid is a pure no-op that does not churn `updated_at`.
3252    #[test]
3253    fn supervisor_attached_latest_wins_and_idempotent_on_replay() {
3254        let tmp = TempDir::new().unwrap();
3255        let run_id = "01jxsnap000000000000000000";
3256        let paths = seed_run_with_node(&tmp, run_id);
3257
3258        let mut ev = event(run_id);
3259        ev.kind = "supervisor.attached".into();
3260        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3261
3262        ev.seq = 3;
3263        ev.data = serde_json::json!({ "pid": 100 });
3264        apply_event(&paths, &ev).expect("first attach applies");
3265        assert_eq!(read_n0001(&paths).supervisor_pid, Some(100));
3266
3267        // A restart binds a fresh pid: latest-wins.
3268        ev.seq = 4;
3269        ev.data = serde_json::json!({ "pid": 200 });
3270        apply_event(&paths, &ev).expect("second attach applies");
3271        let after_second = read_n0001(&paths);
3272        assert_eq!(after_second.supervisor_pid, Some(200));
3273
3274        // Replaying the latest event again is a no-op: the planned ops are
3275        // empty and the projection bytes (including `updated_at`) are unchanged.
3276        let ops = reduce_event_to_ops(&paths, &ev).expect("replay reduces cleanly");
3277        assert!(ops.is_empty(), "re-applying same pid must plan no ops");
3278        apply_event(&paths, &ev).expect("replay applies as no-op");
3279        assert_eq!(read_n0001(&paths).updated_at, after_second.updated_at);
3280    }
3281
3282    /// Replaying `supervisor.cursor_advanced` from scratch reproduces
3283    /// `Node.last_processed_report_seq_by_child`.
3284    #[test]
3285    fn supervisor_cursor_advanced_sets_report_cursor() {
3286        let tmp = TempDir::new().unwrap();
3287        let run_id = "01jxsnap000000000000000000";
3288        let paths = seed_run_with_node(&tmp, run_id);
3289        let child = "02jxsnap000000000000000000";
3290
3291        let mut ev = event(run_id);
3292        ev.seq = 3;
3293        ev.kind = "supervisor.cursor_advanced".into();
3294        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3295        ev.data = serde_json::json!({ "child_run_id": child, "report_seq": 7 });
3296        apply_event(&paths, &ev).expect("cursor_advanced applies");
3297
3298        let n = read_n0001(&paths);
3299        assert_eq!(
3300            n.last_processed_report_seq_by_child.get(child),
3301            Some(&Value::from(7u64))
3302        );
3303    }
3304
3305    /// The cursor is monotonic and idempotent: re-applying the same
3306    /// `(child_run_id, report_seq)` is a no-op, an older seq never moves the
3307    /// cursor backward, and a higher seq advances it. A second distinct child
3308    /// gets its own independent entry.
3309    #[test]
3310    fn supervisor_cursor_advanced_is_monotonic_and_idempotent() {
3311        let tmp = TempDir::new().unwrap();
3312        let run_id = "01jxsnap000000000000000000";
3313        let paths = seed_run_with_node(&tmp, run_id);
3314        let child_a = "02jxsnap000000000000000000";
3315        let child_b = "03jxsnap000000000000000000";
3316
3317        let mut ev = event(run_id);
3318        ev.kind = "supervisor.cursor_advanced".into();
3319        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3320
3321        ev.seq = 3;
3322        ev.data = serde_json::json!({ "child_run_id": child_a, "report_seq": 5 });
3323        apply_event(&paths, &ev).expect("seq 5 applies");
3324
3325        // Replay the exact same event — no-op, plans zero ops.
3326        let ops = reduce_event_to_ops(&paths, &ev).expect("replay reduces cleanly");
3327        assert!(ops.is_empty(), "re-applying same cursor must plan no ops");
3328
3329        // An older seq must not move the cursor backward.
3330        ev.seq = 4;
3331        ev.data = serde_json::json!({ "child_run_id": child_a, "report_seq": 3 });
3332        let ops = reduce_event_to_ops(&paths, &ev).expect("older seq reduces cleanly");
3333        assert!(ops.is_empty(), "older seq must plan no ops");
3334        apply_event(&paths, &ev).expect("older seq applies as no-op");
3335        assert_eq!(
3336            read_n0001(&paths)
3337                .last_processed_report_seq_by_child
3338                .get(child_a),
3339            Some(&Value::from(5u64))
3340        );
3341
3342        // A higher seq advances; an independent child gets its own entry.
3343        ev.seq = 5;
3344        ev.data = serde_json::json!({ "child_run_id": child_a, "report_seq": 9 });
3345        apply_event(&paths, &ev).expect("higher seq applies");
3346        ev.seq = 6;
3347        ev.data = serde_json::json!({ "child_run_id": child_b, "report_seq": 1 });
3348        apply_event(&paths, &ev).expect("second child applies");
3349
3350        let n = read_n0001(&paths);
3351        assert_eq!(
3352            n.last_processed_report_seq_by_child.get(child_a),
3353            Some(&Value::from(9u64))
3354        );
3355        assert_eq!(
3356            n.last_processed_report_seq_by_child.get(child_b),
3357            Some(&Value::from(1u64))
3358        );
3359    }
3360
3361    /// Both new kinds reject a malformed payload at the reducer boundary so a
3362    /// forged event can never write a corrupt projection.
3363    #[test]
3364    fn supervisor_state_events_reject_malformed_payloads() {
3365        let tmp = TempDir::new().unwrap();
3366        let run_id = "01jxsnap000000000000000000";
3367        let paths = seed_run_with_node(&tmp, run_id);
3368        let nid = Some(NodeId::parse_str("n-0001").unwrap());
3369
3370        // Missing pid.
3371        let mut ev = event(run_id);
3372        ev.seq = 3;
3373        ev.kind = "supervisor.attached".into();
3374        ev.node_id = nid.clone();
3375        ev.data = serde_json::json!({});
3376        assert!(matches!(
3377            reduce_event_to_ops(&paths, &ev),
3378            Err(Error::CorruptEventLog { .. })
3379        ));
3380
3381        // Missing envelope node_id.
3382        ev.node_id = None;
3383        ev.data = serde_json::json!({ "pid": 1 });
3384        assert!(matches!(
3385            reduce_event_to_ops(&paths, &ev),
3386            Err(Error::CorruptEventLog { .. })
3387        ));
3388
3389        // cursor_advanced: malformed child_run_id.
3390        let mut ev2 = event(run_id);
3391        ev2.seq = 4;
3392        ev2.kind = "supervisor.cursor_advanced".into();
3393        ev2.node_id = nid.clone();
3394        ev2.data = serde_json::json!({ "child_run_id": "../etc", "report_seq": 1 });
3395        assert!(matches!(
3396            reduce_event_to_ops(&paths, &ev2),
3397            Err(Error::CorruptEventLog { .. })
3398        ));
3399
3400        // cursor_advanced: missing report_seq.
3401        ev2.data = serde_json::json!({ "child_run_id": "02jxsnap000000000000000000" });
3402        assert!(matches!(
3403            reduce_event_to_ops(&paths, &ev2),
3404            Err(Error::CorruptEventLog { .. })
3405        ));
3406    }
3407
3408    /// The append gate stays fail-closed after the 0.2 cut added
3409    /// `Kind`'s `#[serde(other)]` catch-all: a `run.created` / `node.created`
3410    /// whose `kind` is a removed kind (`code`, …) or plain garbage must still be
3411    /// rejected as `CorruptEventLog`, NOT silently accepted as `Kind::Unknown`.
3412    /// (Legacy runs are never re-created through the reducer — their manifest is
3413    /// read directly from disk via the permissive `Kind::Unknown` decode.)
3414    #[test]
3415    fn removed_or_garbage_kind_in_created_events_is_rejected() {
3416        let tmp = TempDir::new().unwrap();
3417        let run_id = "01jxsnap000000000000000000";
3418        let rid = RunId::parse_str(run_id).unwrap();
3419        let dir = crate::run_dir(tmp.path(), &rid);
3420        std::fs::create_dir_all(&dir).unwrap();
3421        let paths = RunPaths::new(dir, run_id).unwrap();
3422
3423        for bad in ["code", "orchestrate", "bugfix", "make-skill", "garbage"] {
3424            let mut ev = event(run_id);
3425            ev.kind = "run.created".into();
3426            ev.node_id = None;
3427            ev.data = serde_json::json!({ "kind": bad, "lifecycle": "autonomous", "title": "t" });
3428            assert!(
3429                matches!(
3430                    reduce_event_to_ops(&paths, &ev),
3431                    Err(Error::CorruptEventLog { .. })
3432                ),
3433                "run.created with kind {bad:?} must be rejected, not folded to Unknown"
3434            );
3435        }
3436
3437        // A surviving creatable kind still folds cleanly (guards against a
3438        // false positive that rejects everything).
3439        let mut ok = event(run_id);
3440        ok.kind = "run.created".into();
3441        ok.node_id = None;
3442        ok.data = serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" });
3443        assert!(reduce_event_to_ops(&paths, &ok).is_ok());
3444    }
3445
3446    /// Snapshot every projection file under `paths` to a `path → inode` map.
3447    ///
3448    /// An atomic projection write is temp-file + rename, so a rewritten file
3449    /// always lands a *fresh inode* — even when its bytes are byte-for-byte
3450    /// identical (e.g. a manifest op that refreshes `updated_at` to the same
3451    /// timestamp). Comparing inodes therefore detects every write the reducer
3452    /// makes, with no false negatives a content diff would suffer. `events.jsonl`
3453    /// and `.lock` are excluded: `apply_event` never touches them.
3454    #[cfg(unix)]
3455    fn projection_inodes(paths: &RunPaths) -> std::collections::BTreeMap<PathBuf, u64> {
3456        use std::os::unix::fs::MetadataExt;
3457        let mut consider = vec![paths.manifest()];
3458        for dir in [paths.nodes_dir()] {
3459            if let Ok(rd) = std::fs::read_dir(&dir) {
3460                for ent in rd.flatten() {
3461                    let p = ent.path();
3462                    if p.extension().and_then(|s| s.to_str()) == Some("json") {
3463                        consider.push(p);
3464                    }
3465                }
3466            }
3467        }
3468        let mut map = std::collections::BTreeMap::new();
3469        for p in consider {
3470            if let Ok(md) = std::fs::symlink_metadata(&p) {
3471                if md.file_type().is_file() {
3472                    map.insert(p, md.ino());
3473                }
3474            }
3475        }
3476        map
3477    }
3478
3479    /// The exhaustive parity guarantee `projected-paths-into-reducer` requires:
3480    /// for an event applied against a given state, the paths
3481    /// [`plan_projections`] reports MUST equal the files [`apply_event`]
3482    /// actually writes. Plan first (against pre-apply state), apply, then diff
3483    /// the projection inodes — a file is "written" iff it is newly present or
3484    /// its inode changed. `expect_writes` guards the test itself: when set, the
3485    /// touched set must be non-empty, so a kind that silently stopped writing
3486    /// can't pass by matching an empty plan against an empty diff.
3487    #[cfg(unix)]
3488    fn assert_plan_matches_apply(paths: &RunPaths, ev: &Event, expect_writes: bool) {
3489        use std::collections::BTreeSet;
3490        let before = projection_inodes(paths);
3491        let planned: BTreeSet<PathBuf> = plan_projections(paths, ev)
3492            .unwrap_or_else(|e| panic!("plan_projections({}) errored: {e:?}", ev.kind))
3493            .into_iter()
3494            .collect();
3495        apply_event(paths, ev)
3496            .unwrap_or_else(|e| panic!("apply_event({}) errored: {e:?}", ev.kind));
3497        let after = projection_inodes(paths);
3498        let touched: BTreeSet<PathBuf> = after
3499            .iter()
3500            .filter(|(p, ino)| before.get(*p) != Some(*ino))
3501            .map(|(p, _)| p.clone())
3502            .collect();
3503        assert_eq!(
3504            planned, touched,
3505            "kind={}: plan_projections must name exactly the files apply_event writes",
3506            ev.kind
3507        );
3508        if expect_writes {
3509            assert!(
3510                !touched.is_empty(),
3511                "kind={}: expected this event to write at least one projection",
3512                ev.kind
3513            );
3514        }
3515    }
3516
3517    /// Drive every event kind through a dependency-ordered lifecycle on real
3518    /// runs, asserting plan/apply parity at each step. Covers the writing kinds
3519    /// (run/node/supervisor/child) in states where they
3520    /// project, plus the no-op kinds (audit records, `supervisor.exited`,
3521    /// terminal-guarded transitions) where both the plan and the apply touch
3522    /// nothing.
3523    #[cfg(unix)]
3524    #[test]
3525    fn plan_projections_matches_apply_for_every_kind() {
3526        let tmp = TempDir::new().unwrap();
3527        let run_id = "01jxsnap000000000000000000";
3528        let rid = RunId::parse_str(run_id).unwrap();
3529        let dir = crate::run_dir(tmp.path(), &rid);
3530        std::fs::create_dir_all(&dir).unwrap();
3531        let paths = RunPaths::new(dir, run_id).unwrap();
3532        let nid = || Some(NodeId::parse_str("n-0001").unwrap());
3533        let child = "02jxsnap000000000000000000";
3534
3535        // Helper to build a fresh envelope at a monotonic seq.
3536        let mut next_seq = 0u64;
3537        let mut at = |kind: &str, node_id, data| {
3538            next_seq += 1;
3539            Event {
3540                ts: Timestamp::now(),
3541                seq: next_seq,
3542                kind: kind.into(),
3543                run_id: rid.clone(),
3544                node_id,
3545                idempotency_key: None,
3546                data,
3547            }
3548        };
3549
3550        // run.created → manifest.json
3551        assert_plan_matches_apply(
3552            &paths,
3553            &at(
3554                "run.created",
3555                None,
3556                serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" }),
3557            ),
3558            true,
3559        );
3560        // run.status (pending → running) → manifest.json
3561        assert_plan_matches_apply(
3562            &paths,
3563            &at(
3564                "run.status",
3565                None,
3566                serde_json::json!({ "status": "running" }),
3567            ),
3568            true,
3569        );
3570        // node.created → nodes/n-0001.json + manifest.json
3571        assert_plan_matches_apply(
3572            &paths,
3573            &at(
3574                "node.created",
3575                nid(),
3576                serde_json::json!({ "kind": "spinoff" }),
3577            ),
3578            true,
3579        );
3580        // node.status (pending → running) → nodes/n-0001.json
3581        assert_plan_matches_apply(
3582            &paths,
3583            &at(
3584                "node.status",
3585                nid(),
3586                serde_json::json!({ "status": "running" }),
3587            ),
3588            true,
3589        );
3590        // supervisor.attached → nodes/n-0001.json (still non-terminal)
3591        assert_plan_matches_apply(
3592            &paths,
3593            &at(
3594                "supervisor.attached",
3595                nid(),
3596                serde_json::json!({ "pid": 4242 }),
3597            ),
3598            true,
3599        );
3600        // supervisor.cursor_advanced → nodes/n-0001.json
3601        assert_plan_matches_apply(
3602            &paths,
3603            &at(
3604                "supervisor.cursor_advanced",
3605                nid(),
3606                serde_json::json!({ "child_run_id": child, "report_seq": 3 }),
3607            ),
3608            true,
3609        );
3610        // child.spawned → nodes/n-0001.json (parent node)
3611        assert_plan_matches_apply(
3612            &paths,
3613            &at(
3614                "child.spawned",
3615                nid(),
3616                serde_json::json!({ "child_run_id": child, "child_node_id": "n-0001" }),
3617            ),
3618            true,
3619        );
3620        // node.report success → nodes/n-0001.json (now terminal)
3621        assert_plan_matches_apply(
3622            &paths,
3623            &at("node.report", nid(), serde_json::json!({ "success": true })),
3624            true,
3625        );
3626        // Terminal-guarded no-ops: a settled node swallows further transitions,
3627        // so both the plan and the apply touch nothing.
3628        assert_plan_matches_apply(
3629            &paths,
3630            &at(
3631                "node.status",
3632                nid(),
3633                serde_json::json!({ "status": "failed" }),
3634            ),
3635            false,
3636        );
3637        // No-op audit / lifecycle kinds: zero projections by design.
3638        for kind in [
3639            "supervisor.exited",
3640            "orchestrator.decision",
3641            "discuss.critical",
3642            "cleanup.window_missing",
3643        ] {
3644            assert_plan_matches_apply(&paths, &at(kind, None, serde_json::json!({})), false);
3645        }
3646    }
3647
3648    /// A `worker.exited` carrying a clean `exit_code: 0` folds onto the node's
3649    /// `worker_exit` field as a clean exit — and does NOT transition `status`
3650    /// (terminalization is the supervisor's decision via the typed table).
3651    #[test]
3652    fn worker_exited_records_clean_exit_without_transitioning_status() {
3653        let tmp = TempDir::new().unwrap();
3654        let run_id = "01jxsnap000000000000000000";
3655        let paths = bootstrap_retry_node(&tmp, run_id);
3656
3657        let mut ev = event(run_id);
3658        ev.seq = 3;
3659        ev.kind = "worker.exited".into();
3660        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3661        ev.data = serde_json::json!({ "exit_code": 0 });
3662        apply_event(&paths, &ev).expect("worker.exited applies");
3663
3664        let n = read_node_opt(&paths, &NodeId::parse_str("n-0001").unwrap())
3665            .unwrap()
3666            .unwrap();
3667        let exit = n.worker_exit.expect("worker_exit recorded");
3668        assert_eq!(exit.code, Some(0));
3669        assert_eq!(exit.signal, None);
3670        assert!(exit.is_clean());
3671        assert_eq!(
3672            n.status,
3673            Status::Pending,
3674            "the exit fact never transitions status"
3675        );
3676    }
3677
3678    /// A `worker.exited` carrying a `signal` records it as a failure; and the fold
3679    /// is first-write-wins — a replayed/duplicate exit event never overwrites the
3680    /// first recorded fact (replay-safety for the `applied_seq` watermark).
3681    #[test]
3682    fn worker_exited_records_signal_and_is_first_write_wins() {
3683        let tmp = TempDir::new().unwrap();
3684        let run_id = "01jxsnap000000000000000000";
3685        let paths = bootstrap_retry_node(&tmp, run_id);
3686        let nid = NodeId::parse_str("n-0001").unwrap();
3687
3688        let mut ev = event(run_id);
3689        ev.seq = 3;
3690        ev.kind = "worker.exited".into();
3691        ev.node_id = Some(nid.clone());
3692        ev.data = serde_json::json!({ "signal": 9 });
3693        apply_event(&paths, &ev).expect("worker.exited applies");
3694
3695        let n = read_node_opt(&paths, &nid).unwrap().unwrap();
3696        let exit = n.worker_exit.expect("worker_exit recorded");
3697        assert_eq!(exit.signal, Some(9));
3698        assert!(exit.is_failure());
3699
3700        // A later, conflicting exit event (e.g. a replay of a different value) is a
3701        // clean no-op: the first fact stands.
3702        let mut dup = event(run_id);
3703        dup.seq = 4;
3704        dup.kind = "worker.exited".into();
3705        dup.node_id = Some(nid.clone());
3706        dup.data = serde_json::json!({ "exit_code": 0 });
3707        apply_event(&paths, &dup).expect("duplicate worker.exited applies as no-op");
3708        let n2 = read_node_opt(&paths, &nid).unwrap().unwrap();
3709        assert_eq!(
3710            n2.worker_exit.unwrap().signal,
3711            Some(9),
3712            "first-write-wins: the replayed exit must not overwrite the recorded fact"
3713        );
3714    }
3715
3716    /// A `worker.exited` carrying neither `exit_code` nor `signal` is malformed —
3717    /// the reducer is the canonical gate and rejects it as `CorruptEventLog` rather
3718    /// than record an empty fact.
3719    #[test]
3720    fn worker_exited_without_code_or_signal_is_corrupt() {
3721        let tmp = TempDir::new().unwrap();
3722        let run_id = "01jxsnap000000000000000000";
3723        let paths = bootstrap_retry_node(&tmp, run_id);
3724
3725        let mut ev = event(run_id);
3726        ev.seq = 3;
3727        ev.kind = "worker.exited".into();
3728        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3729        ev.data = serde_json::json!({});
3730        match reduce_event_to_ops(&paths, &ev) {
3731            Err(Error::CorruptEventLog { .. }) => {}
3732            Ok(_) => panic!("an empty worker.exited payload must be rejected, not applied"),
3733            Err(other) => panic!("expected CorruptEventLog, got {other:?}"),
3734        }
3735
3736        // Carrying BOTH is contradictory (a process cannot both return a code and
3737        // be killed) — also rejected.
3738        ev.data = serde_json::json!({ "exit_code": 0, "signal": 9 });
3739        match reduce_event_to_ops(&paths, &ev) {
3740            Err(Error::CorruptEventLog { .. }) => {}
3741            Ok(_) => panic!("a worker.exited with both fields must be rejected"),
3742            Err(other) => panic!("expected CorruptEventLog, got {other:?}"),
3743        }
3744    }
3745
3746    /// `node.death_observed` records the residual crash backstop's first-death
3747    /// anchor (`first_death_at`) as `ev.ts`, is **first-write-wins** (a later
3748    /// re-observation never resets the monotonic anchor), and is a no-op against a
3749    /// terminal node (the backstop is moot once settled). Issue
3750    /// `typed-supervisor-outcomes`.
3751    #[test]
3752    fn node_death_observed_records_first_death_first_write_wins() {
3753        let tmp = TempDir::new().unwrap();
3754        let run_id = "01jxsnap000000000000000000";
3755        let paths = bootstrap_retry_node(&tmp, run_id);
3756        let nid = NodeId::parse_str("n-0001").unwrap();
3757
3758        let mut ev = event(run_id);
3759        ev.seq = 3;
3760        ev.kind = "node.death_observed".into();
3761        ev.node_id = Some(nid.clone());
3762        ev.data = serde_json::json!({});
3763        apply_event(&paths, &ev).expect("node.death_observed applies");
3764        let first = read_node_opt(&paths, &nid)
3765            .unwrap()
3766            .unwrap()
3767            .first_death_at
3768            .expect("first_death_at recorded");
3769        assert_eq!(first, ev.ts, "the anchor is the event's own timestamp");
3770
3771        // A later re-observation is first-write-wins: the monotonic anchor holds.
3772        let mut later = event(run_id);
3773        later.seq = 4;
3774        later.kind = "node.death_observed".into();
3775        later.node_id = Some(nid.clone());
3776        later.ts = ev.ts + jiff::SignedDuration::from_secs(30);
3777        later.data = serde_json::json!({});
3778        apply_event(&paths, &later).expect("re-observation applies as no-op");
3779        assert_eq!(
3780            read_node_opt(&paths, &nid).unwrap().unwrap().first_death_at,
3781            Some(first),
3782            "first-write-wins: a re-observation must not reset the anchor"
3783        );
3784    }
3785
3786    /// `node.death_observed` is a no-op once a higher-fidelity fact exists — here a
3787    /// told `worker.exited` — so a from-scratch replay converges to the same state
3788    /// the supervisor's lock-guarded emitter would produce (the backstop is moot
3789    /// once the shim recorded a real exit). Issue `typed-supervisor-outcomes`.
3790    #[test]
3791    fn node_death_observed_noop_when_worker_exit_present() {
3792        let tmp = TempDir::new().unwrap();
3793        let run_id = "01jxsnap000000000000000000";
3794        let paths = bootstrap_retry_node(&tmp, run_id);
3795        let nid = NodeId::parse_str("n-0001").unwrap();
3796
3797        // A told exit lands first.
3798        let mut exit = event(run_id);
3799        exit.seq = 3;
3800        exit.kind = "worker.exited".into();
3801        exit.node_id = Some(nid.clone());
3802        exit.data = serde_json::json!({ "exit_code": 0 });
3803        apply_event(&paths, &exit).unwrap();
3804
3805        // A death observation for the same node folds to nothing.
3806        let mut death = event(run_id);
3807        death.seq = 4;
3808        death.kind = "node.death_observed".into();
3809        death.node_id = Some(nid.clone());
3810        death.data = serde_json::json!({});
3811        apply_event(&paths, &death).expect("applies as no-op");
3812        assert_eq!(
3813            read_node_opt(&paths, &nid).unwrap().unwrap().first_death_at,
3814            None,
3815            "a told worker.exited makes the crash backstop moot; no anchor recorded"
3816        );
3817    }
3818
3819    /// `node.retry` clears the previous attempt's told exit fact: the re-spawned
3820    /// worker is a NEW process, so a stale `worker_exit` must not carry over (it
3821    /// would make the supervisor mis-judge the fresh attempt from the dead one's
3822    /// exit). Issue `thin-exit-status-launcher`.
3823    #[test]
3824    fn node_retry_clears_worker_exit() {
3825        let tmp = TempDir::new().unwrap();
3826        let run_id = "01jxsnap000000000000000000";
3827        let paths = bootstrap_retry_node(&tmp, run_id);
3828        let nid = NodeId::parse_str("n-0001").unwrap();
3829
3830        // Record a failing exit on the first attempt.
3831        let mut exit = event(run_id);
3832        exit.seq = 3;
3833        exit.kind = "worker.exited".into();
3834        exit.node_id = Some(nid.clone());
3835        exit.data = serde_json::json!({ "exit_code": 7 });
3836        apply_event(&paths, &exit).unwrap();
3837        assert!(read_node_opt(&paths, &nid)
3838            .unwrap()
3839            .unwrap()
3840            .worker_exit
3841            .is_some());
3842
3843        // Retry re-spawns the node — the stale exit fact must be gone.
3844        let mut retry = event(run_id);
3845        retry.seq = 4;
3846        retry.kind = "node.retry".into();
3847        retry.node_id = Some(nid.clone());
3848        retry.data = serde_json::json!({
3849            "attempt": 1,
3850            "reason": "agent-died",
3851            "branch": "wt/foo",
3852            "worktree_path": "/tmp/new-wt",
3853            "agent_pid": 222,
3854        });
3855        apply_event(&paths, &retry).unwrap();
3856
3857        let n = read_node_opt(&paths, &nid).unwrap().unwrap();
3858        assert!(
3859            n.worker_exit.is_none(),
3860            "node.retry must clear the previous attempt's worker_exit"
3861        );
3862        assert_eq!(
3863            n.status,
3864            Status::Pending,
3865            "retry returns the node to Pending"
3866        );
3867    }
3868}