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