Skip to main content

taskfleet_core/
reducer.rs

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