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