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) and a bounded non-blank `summary`. A second report from the
2149/// same attempt amends the open round (same number) rather than opening a new
2150/// one. A settled node, or a report from a superseded attempt, is a no-op.
2151fn reduce_node_round_reported(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2152    let events_path = paths.events();
2153    let node_id = require_envelope_node_id(&events_path, ev)?;
2154    let summary = ev
2155        .data
2156        .get("summary")
2157        .and_then(Value::as_str)
2158        .filter(|s| !s.trim().is_empty() && s.len() <= MAX_ROUND_SUMMARY_BYTES && !s.contains('\0'))
2159        .ok_or_else(|| {
2160            corrupt(
2161                &events_path,
2162                ev,
2163                &format!(
2164                    "requires a non-blank `summary` of at most {MAX_ROUND_SUMMARY_BYTES} bytes"
2165                ),
2166            )
2167        })?
2168        .to_string();
2169    let attempt = evidence_attempt(&events_path, ev)?;
2170    require_resident(paths, &events_path, ev)?;
2171    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2172        return Ok(vec![]);
2173    };
2174    if n.status.is_terminal() || attempt != n.retry_attempts {
2175        return Ok(vec![]);
2176    }
2177    let state = n.resident.get_or_insert_with(Box::default);
2178    match state.last_round.as_mut() {
2179        Some(open) if open.closed_at.is_none() && open.attempt == attempt => {
2180            open.summary = summary;
2181            open.reported_at = ev.ts;
2182            open.event_seq = ev.seq;
2183        }
2184        _ => {
2185            state.rounds_reported = state.rounds_reported.saturating_add(1);
2186            state.last_round = Some(RoundReport {
2187                round: state.rounds_reported,
2188                attempt,
2189                reported_at: ev.ts,
2190                event_seq: ev.seq,
2191                summary,
2192                closed_at: None,
2193                closed_by: None,
2194            });
2195            state.expiry_attention_at = None;
2196        }
2197    }
2198    // The round report answers any open question of this attempt.
2199    n.awaiting_input = None;
2200    n.updated_at = ev.ts;
2201    Ok(vec![ProjectionOp::Node(n)])
2202}
2203
2204/// Fold `node.resumed` (ADR 0003): a message started the next worker attempt
2205/// from the same native session in the same worktree.
2206///
2207/// Rewires the node to the new attempt exactly like `node.retry` does for the
2208/// agent identity, but keeps the branch, the worktree path and the session,
2209/// closes the open round with `message_id`, and clears dormancy/attention. The
2210/// event carries its absolute `attempt`, which must advance the current one.
2211fn reduce_node_resumed(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2212    let events_path = paths.events();
2213    let node_id = require_envelope_node_id(&events_path, ev)?;
2214    let d = &ev.data;
2215    let attempt = evidence_attempt(&events_path, ev)?;
2216    let message_id = want_str(&events_path, ev, d, "message_id")?.to_string();
2217    let evidence = worker_evidence_from_spawn_data(&events_path, ev, d)?;
2218    let claude_session_id = claude_session_from_data(&events_path, ev, d)?;
2219    require_resident(paths, &events_path, ev)?;
2220    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2221        return Ok(vec![]);
2222    };
2223    if n.status.is_terminal() || attempt <= n.retry_attempts {
2224        return Ok(vec![]);
2225    }
2226    if let Some(sha) = d
2227        .get("base_sha")
2228        .and_then(Value::as_str)
2229        .filter(|s| !s.is_empty())
2230    {
2231        n.base_sha = Some(sha.to_string());
2232    }
2233    n.tmux_window = d
2234        .get("tmux_window")
2235        .and_then(Value::as_str)
2236        .map(str::to_string)
2237        .or(n.tmux_window);
2238    if let Some(identity) = tmux_identity_from_data(d) {
2239        n.tmux_identity = Some(Box::new(identity));
2240    }
2241    n.evidence = evidence;
2242    n.claude_session_id = claude_session_id;
2243    n.agent_pid = optional_i32(d, "agent_pid", &events_path, ev)?;
2244    n.agent_pid_start_time = optional_ts(d, "agent_pid_start_time", &events_path, ev)?;
2245    n.agent_pid_start_identity = start_identity_from_data(d);
2246    n.status = Status::Pending;
2247    n.started_at = Some(ev.ts);
2248    n.updated_at = ev.ts;
2249    n.worker_exit = None;
2250    n.first_death_at = None;
2251    n.awaiting_input = None;
2252    n.pending_merge = None;
2253    n.retained_display = None;
2254    n.retention_unavailable = None;
2255    n.retry_attempts = attempt;
2256    let state = n.resident.get_or_insert_with(Box::default);
2257    if let Some(round) = state.last_round.as_mut().filter(|r| r.closed_at.is_none()) {
2258        round.closed_at = Some(ev.ts);
2259        round.closed_by = Some(message_id);
2260    }
2261    state.dormant_since = None;
2262    state.expiry_attention_at = None;
2263    Ok(vec![ProjectionOp::Node(n)])
2264}
2265
2266/// Fold `node.round_landed` (ADR 0003): `run land` (or recovery of a crashed
2267/// land) fast-forwarded the source branch to the rebased worker tip. Never a
2268/// status transition. Clears the matching landing transaction and moves the
2269/// node's fork point to the integrated tip.
2270fn reduce_node_round_landed(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2271    let events_path = paths.events();
2272    let node_id = require_envelope_node_id(&events_path, ev)?;
2273    let d = &ev.data;
2274    let op_id = want_str(&events_path, ev, d, "op_id")?.to_string();
2275    let source_branch = want_str(&events_path, ev, d, "source_branch")?.to_string();
2276    let integrated_oid = want_str(&events_path, ev, d, "integrated_oid")?.to_string();
2277    if integrated_oid.len() < 40 || !integrated_oid.bytes().all(|b| b.is_ascii_hexdigit()) {
2278        return Err(corrupt(
2279            &events_path,
2280            ev,
2281            "requires a full hex `integrated_oid`",
2282        ));
2283    }
2284    require_resident(paths, &events_path, ev)?;
2285    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2286        return Ok(vec![]);
2287    };
2288    if n.status.is_terminal() {
2289        return Ok(vec![]);
2290    }
2291    if n.pending_merge
2292        .as_ref()
2293        .is_some_and(|txn| txn.landing && txn.op_id == op_id)
2294    {
2295        n.pending_merge = None;
2296    }
2297    n.base_sha = Some(integrated_oid.clone());
2298    let state = n.resident.get_or_insert_with(Box::default);
2299    let round = state.last_round.as_ref().map_or(0, |r| r.round);
2300    state.last_landing = Some(RoundLanding {
2301        at: ev.ts,
2302        source_branch,
2303        integrated_oid,
2304        round,
2305    });
2306    // Landing the work answers an unlanded-work expiry for this round.
2307    state.expiry_attention_at = None;
2308    n.updated_at = ev.ts;
2309    Ok(vec![ProjectionOp::Node(n)])
2310}
2311
2312/// Fold `node.resident_dormant` (ADR 0003): idle expiry removed the worktree
2313/// (and integrated branch) of a wholly landed round. The worktree path, branch
2314/// name and native session stay recorded so the next message can revive it.
2315fn reduce_node_resident_dormant(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2316    let events_path = paths.events();
2317    let node_id = require_envelope_node_id(&events_path, ev)?;
2318    require_resident(paths, &events_path, ev)?;
2319    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2320        return Ok(vec![]);
2321    };
2322    if n.status.is_terminal() {
2323        return Ok(vec![]);
2324    }
2325    let state = n.resident.get_or_insert_with(Box::default);
2326    if state.open_round().is_none() || state.dormant_since.is_some() {
2327        return Ok(vec![]);
2328    }
2329    state.dormant_since = Some(ev.ts);
2330    state.expiry_attention_at = None;
2331    n.updated_at = ev.ts;
2332    Ok(vec![ProjectionOp::Node(n)])
2333}
2334
2335/// Fold `node.resident_attention` (ADR 0003): idle expiry found unlanded or
2336/// unverifiable work and preserved everything. Raised once per open round.
2337fn reduce_node_resident_attention(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
2338    let events_path = paths.events();
2339    let node_id = require_envelope_node_id(&events_path, ev)?;
2340    want_str(&events_path, ev, &ev.data, "reason")?;
2341    require_resident(paths, &events_path, ev)?;
2342    let Some(mut n) = read_node_opt(paths, &node_id)? else {
2343        return Ok(vec![]);
2344    };
2345    if n.status.is_terminal() {
2346        return Ok(vec![]);
2347    }
2348    let state = n.resident.get_or_insert_with(Box::default);
2349    if state.open_round().is_none() || state.expiry_attention_at.is_some() {
2350        return Ok(vec![]);
2351    }
2352    state.expiry_attention_at = Some(ev.ts);
2353    n.updated_at = ev.ts;
2354    Ok(vec![ProjectionOp::Node(n)])
2355}
2356
2357#[cfg(test)]
2358mod tests {
2359    use super::*;
2360    use crate::schema::Event;
2361    use chrono::Utc;
2362    use tempfile::TempDir;
2363
2364    fn event(run_id: &str) -> Event {
2365        Event {
2366            ts: Utc::now(),
2367            seq: 1,
2368            kind: "run.status".into(),
2369            run_id: RunId::parse_str(run_id).unwrap(),
2370            node_id: None,
2371            idempotency_key: None,
2372            data: serde_json::json!({ "status": "running" }),
2373        }
2374    }
2375
2376    #[test]
2377    fn orchestrator_decision_and_discuss_critical_reduce_to_noop() {
2378        // The /orchestrate audit kinds are append-only: the reducer must plan
2379        // ZERO projection ops for them regardless of payload, so the event log
2380        // is their sole home and no projection is created or mutated.
2381        let tmp = TempDir::new().unwrap();
2382        let run_id = "01jxsnap000000000000000000";
2383        let rid = RunId::parse_str(run_id).unwrap();
2384        let dir = crate::run_dir(tmp.path(), &rid);
2385        std::fs::create_dir_all(&dir).unwrap();
2386        let paths = RunPaths::new(dir, run_id).unwrap();
2387
2388        // Bootstrap a manifest so we can prove the audit events leave it
2389        // byte-for-byte untouched (no counter churn, no status drift).
2390        let mut created = event(run_id);
2391        created.kind = "run.created".into();
2392        created.data = serde_json::json!({
2393            "kind": "spinoff", "lifecycle": "autonomous", "title": "t"
2394        });
2395        apply_event(&paths, &created).expect("run.created applies");
2396        let manifest_before = std::fs::read(paths.manifest()).unwrap();
2397
2398        for (seq, kind) in [(10u64, "orchestrator.decision"), (11, "discuss.critical")] {
2399            let mut ev = event(run_id);
2400            ev.seq = seq;
2401            ev.kind = kind.into();
2402            // A non-trivial payload to prove the reducer ignores it wholesale.
2403            ev.data = serde_json::json!({ "summary": "x", "arbitrary": [1, 2, 3] });
2404            let ops = reduce_event_to_ops(&paths, &ev).expect("audit kind reduces cleanly");
2405            assert!(ops.is_empty(), "{kind} must plan no projection ops");
2406            // apply_event is the plan+commit path; it must also be a clean no-op.
2407            apply_event(&paths, &ev).expect("audit kind applies as no-op");
2408        }
2409
2410        // The manifest is unchanged and no stray projection dirs appeared.
2411        assert_eq!(
2412            std::fs::read(paths.manifest()).unwrap(),
2413            manifest_before,
2414            "audit events must not mutate the manifest"
2415        );
2416        assert!(!paths.nodes_dir().exists(), "no node projection created");
2417    }
2418
2419    #[test]
2420    fn run_created_folds_harness_when_present_and_defaults_none() {
2421        let tmp = TempDir::new().unwrap();
2422
2423        // A `run.created` carrying `harness` folds it onto the manifest.
2424        let run_id = "01jxhrnsaa0000000000000001";
2425        let rid = RunId::parse_str(run_id).unwrap();
2426        let dir = crate::run_dir(tmp.path(), &rid);
2427        std::fs::create_dir_all(&dir).unwrap();
2428        let paths = RunPaths::new(dir, run_id).unwrap();
2429        let mut created = event(run_id);
2430        created.kind = "run.created".into();
2431        created.data = serde_json::json!({
2432            "kind": "spinoff", "lifecycle": "autonomous", "title": "t",
2433            "harness": "pi", "harness_source": "flag",
2434        });
2435        apply_event(&paths, &created).expect("run.created applies");
2436        let m = read_manifest_opt(&paths).unwrap().unwrap();
2437        assert_eq!(m.harness.as_deref(), Some("pi"));
2438
2439        // A `run.created` WITHOUT `harness` (legacy / claude) leaves it `None`.
2440        let run_id2 = "01jxhrnsaa0000000000000002";
2441        let rid2 = RunId::parse_str(run_id2).unwrap();
2442        let dir2 = crate::run_dir(tmp.path(), &rid2);
2443        std::fs::create_dir_all(&dir2).unwrap();
2444        let paths2 = RunPaths::new(dir2, run_id2).unwrap();
2445        let mut created2 = event(run_id2);
2446        created2.kind = "run.created".into();
2447        created2.data =
2448            serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" });
2449        apply_event(&paths2, &created2).expect("run.created applies");
2450        let m2 = read_manifest_opt(&paths2).unwrap().unwrap();
2451        assert_eq!(m2.harness, None);
2452    }
2453
2454    /// Bootstrap a run manifest + one live `n-0001` spinoff node, returning its
2455    /// paths. Used by the `node.retry` reducer tests.
2456    fn bootstrap_retry_node(tmp: &TempDir, run_id: &str) -> RunPaths {
2457        let rid = RunId::parse_str(run_id).unwrap();
2458        let dir = crate::run_dir(tmp.path(), &rid);
2459        std::fs::create_dir_all(&dir).unwrap();
2460        let paths = RunPaths::new(dir, run_id).unwrap();
2461        let mut created = event(run_id);
2462        created.kind = "run.created".into();
2463        created.data =
2464            serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" });
2465        apply_event(&paths, &created).expect("run.created applies");
2466        let mut node = event(run_id);
2467        node.seq = 2;
2468        node.kind = "node.created".into();
2469        node.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2470        node.data = serde_json::json!({
2471            "kind": "spinoff",
2472            "branch": "wt/foo",
2473            "worktree_path": "/tmp/old-wt",
2474            "agent_pid": 111,
2475        });
2476        apply_event(&paths, &node).expect("node.created applies");
2477        paths
2478    }
2479
2480    /// `node.retry` rewires the node to the freshly re-spawned agent, returns it to
2481    /// `Pending`, re-stamps `started_at`, and increments the durable
2482    /// `retry_attempts` bound (issue `autoretry-agent-died-worker`).
2483    #[test]
2484    fn node_retry_rewires_node_and_increments_attempts() {
2485        let tmp = TempDir::new().unwrap();
2486        let run_id = "01jxsnap000000000000000000";
2487        let paths = bootstrap_retry_node(&tmp, run_id);
2488
2489        let mut retry = event(run_id);
2490        retry.seq = 3;
2491        retry.kind = "node.retry".into();
2492        retry.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2493        retry.data = serde_json::json!({
2494            "attempt": 1,
2495            "reason": "agent-died",
2496            "branch": "wt/foo-r1",
2497            "base_sha": "a".repeat(40),
2498            "worktree_path": "/tmp/new-wt",
2499            "agent_pid": 222,
2500            "tmux_session": "s",
2501            "tmux_window_id": "@9",
2502        });
2503        apply_event(&paths, &retry).expect("node.retry applies");
2504
2505        let n = read_n0001(&paths);
2506        assert_eq!(n.retry_attempts, 1, "attempt bound incremented");
2507        assert_eq!(
2508            n.branch.as_deref(),
2509            Some("wt/foo-r1"),
2510            "rewired to new branch"
2511        );
2512        assert_eq!(n.worktree_path.as_deref(), Some("/tmp/new-wt"));
2513        assert_eq!(n.agent_pid, Some(222), "rewired to new agent pid");
2514        assert_eq!(n.status, Status::Pending, "node returns to pending");
2515        assert!(n.last_report.is_none());
2516        assert_eq!(
2517            n.tmux_identity.as_ref().map(|t| t.window_id.as_str()),
2518            Some("@9"),
2519            "rewired tmux identity"
2520        );
2521
2522        // A second retry increments again — the bound is monotone.
2523        let mut retry2 = event(run_id);
2524        retry2.seq = 4;
2525        retry2.kind = "node.retry".into();
2526        retry2.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2527        retry2.data = serde_json::json!({
2528            "attempt": 2, "reason": "agent-died", "branch": "wt/foo-r2",
2529            "worktree_path": "/tmp/new-wt-2", "agent_pid": 333,
2530        });
2531        apply_event(&paths, &retry2).expect("node.retry applies");
2532        assert_eq!(read_n0001(&paths).retry_attempts, 2);
2533    }
2534
2535    #[test]
2536    fn stale_worker_evidence_and_exit_do_not_cross_retry_generation() {
2537        let tmp = TempDir::new().unwrap();
2538        let run_id = "01jxsnap000000000000000000";
2539        let paths = bootstrap_retry_node(&tmp, run_id);
2540        let nid = NodeId::parse_str("n-0001").unwrap();
2541        let current_session = "018f5f64-b137-7d44-b2b4-4f02c3f646e8";
2542
2543        let mut retry = event(run_id);
2544        retry.seq = 3;
2545        retry.kind = "node.retry".into();
2546        retry.node_id = Some(nid.clone());
2547        retry.data = serde_json::json!({
2548            "attempt": 1, "reason": "agent-died", "branch": "wt/foo-r1",
2549            "worktree_path": "/tmp/new-wt", "agent_pid": 222,
2550            "pi_session_id": current_session,
2551            "pi_session_path": format!(".creating/pi-sessions/{run_id}/pi-session-{current_session}.jsonl"),
2552            "pi_session_cwd": "/tmp/new-wt"
2553        });
2554        apply_event(&paths, &retry).unwrap();
2555
2556        let mut stale_failure = event(run_id);
2557        stale_failure.seq = 4;
2558        stale_failure.kind = "worker.evidence.failed".into();
2559        stale_failure.node_id = Some(nid.clone());
2560        stale_failure.data = serde_json::json!({
2561            "attempt": 0,
2562            "session_id": "118f5f64-b137-7d44-b2b4-4f02c3f646e8",
2563            "error": "old attempt"
2564        });
2565        apply_event(&paths, &stale_failure).unwrap();
2566        assert_eq!(
2567            read_n0001(&paths).evidence.unwrap().status,
2568            EvidenceStatus::Pending
2569        );
2570
2571        let mut stale_exit = event(run_id);
2572        stale_exit.seq = 5;
2573        stale_exit.kind = "worker.exited".into();
2574        stale_exit.node_id = Some(nid.clone());
2575        stale_exit.data = serde_json::json!({"attempt":0,"exit_code":9});
2576        apply_event(&paths, &stale_exit).unwrap();
2577        assert!(read_n0001(&paths).worker_exit.is_none());
2578
2579        let mut archived = event(run_id);
2580        archived.seq = 6;
2581        archived.kind = "worker.evidence.archived".into();
2582        archived.node_id = Some(nid);
2583        archived.data = serde_json::json!({
2584            "attempt":1, "session_id":current_session,
2585            "transcript_path":"evidence/n-0001/pi-session.original.jsonl",
2586            "resume_path":"evidence/n-0001/pi-session.resume.jsonl",
2587            "pane_path":"evidence/n-0001/final-pane.log",
2588            "report_path":"evidence/n-0001/terminal-report.json",
2589            "transcript_sha256":"0".repeat(64)
2590        });
2591        apply_event(&paths, &archived).unwrap();
2592        assert_eq!(
2593            read_n0001(&paths).evidence.unwrap().status,
2594            EvidenceStatus::Complete
2595        );
2596    }
2597
2598    /// A `node.retry` against an already-terminal node is a dead event: the
2599    /// terminal-state invariant holds, so a late retry never resurrects a settled
2600    /// node (a real report that raced in wins).
2601    #[test]
2602    fn node_retry_against_terminal_node_is_noop() {
2603        let tmp = TempDir::new().unwrap();
2604        let run_id = "01jxsnap000000000000000000";
2605        let paths = bootstrap_retry_node(&tmp, run_id);
2606
2607        // Terminalize the node via a success report.
2608        let mut report = event(run_id);
2609        report.seq = 3;
2610        report.kind = "node.report".into();
2611        report.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2612        report.data = serde_json::json!({ "success": true });
2613        apply_event(&paths, &report).expect("node.report applies");
2614        assert_eq!(read_n0001(&paths).status, Status::Done);
2615
2616        let mut retry = event(run_id);
2617        retry.seq = 4;
2618        retry.kind = "node.retry".into();
2619        retry.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2620        retry.data = serde_json::json!({
2621            "attempt": 1, "reason": "agent-died", "branch": "wt/foo-r1",
2622            "worktree_path": "/tmp/new-wt", "agent_pid": 222,
2623        });
2624        apply_event(&paths, &retry).expect("node.retry applies as no-op");
2625
2626        let n = read_n0001(&paths);
2627        assert_eq!(n.status, Status::Done, "terminal node not resurrected");
2628        assert_eq!(n.retry_attempts, 0, "no increment against terminal node");
2629        assert_eq!(n.agent_pid, Some(111), "not rewired");
2630    }
2631
2632    #[test]
2633    fn apply_event_rejects_event_from_a_different_run() {
2634        let tmp = TempDir::new().unwrap();
2635        let run_id = "01jxsnap000000000000000000";
2636        let rid = RunId::parse_str(run_id).unwrap();
2637        let dir = crate::run_dir(tmp.path(), &rid);
2638        std::fs::create_dir_all(&dir).unwrap();
2639        let paths = RunPaths::new(dir, run_id).unwrap();
2640
2641        // An event whose envelope names a different run must not be folded.
2642        let foreign = event("02jxsnap000000000000000000");
2643        let err = apply_event(&paths, &foreign).expect_err("cross-run event must be rejected");
2644        assert!(matches!(err, Error::CorruptEventLog { .. }), "got {err:?}");
2645
2646        // The matching run_id is accepted (no projection exists yet, so
2647        // `run.status` is a clean no-op rather than an error).
2648        let mine = event(run_id);
2649        apply_event(&paths, &mine).expect("matching run_id must be accepted");
2650    }
2651
2652    #[test]
2653    fn tmux_identity_from_data_reads_qualified_fields() {
2654        let d = serde_json::json!({
2655            "tmux_socket": "/private/tmp/tmux-501/default",
2656            "tmux_session": "taskfleet",
2657            "tmux_window_id": "@42",
2658        });
2659        let id = tmux_identity_from_data(&d).expect("qualified identity");
2660        assert_eq!(id.socket.as_deref(), Some("/private/tmp/tmux-501/default"));
2661        assert_eq!(id.session, "taskfleet");
2662        assert_eq!(id.window_id, "@42");
2663        // No pane_id in this event → None (back-compat / older create.sh).
2664        assert_eq!(id.pane_id, None);
2665
2666        // Null socket is tolerated — session + window_id are the minimum.
2667        let d2 = serde_json::json!({
2668            "tmux_socket": null,
2669            "tmux_session": "taskfleet",
2670            "tmux_window_id": "@7",
2671        });
2672        let id2 = tmux_identity_from_data(&d2).expect("identity without socket");
2673        assert_eq!(id2.socket, None);
2674        assert_eq!(id2.window_id, "@7");
2675
2676        // A create.sh that emits `tmux_pane_id` is folded into the identity.
2677        let d3 = serde_json::json!({
2678            "tmux_session": "taskfleet",
2679            "tmux_window_id": "@42",
2680            "tmux_pane_id": "%7",
2681        });
2682        let id3 = tmux_identity_from_data(&d3).expect("identity with pane");
2683        assert_eq!(id3.pane_id.as_deref(), Some("%7"));
2684        assert_eq!(id3.capture_target(), "%7");
2685
2686        // Explicit `tmux_pane_id: null` (create.sh emits null when its pane
2687        // query failed) must fold to None — never `Some("null")`.
2688        let d4 = serde_json::json!({
2689            "tmux_session": "taskfleet",
2690            "tmux_window_id": "@42",
2691            "tmux_pane_id": null,
2692        });
2693        let id4 = tmux_identity_from_data(&d4).expect("identity with null pane");
2694        assert_eq!(id4.pane_id, None);
2695        assert_eq!(id4.capture_target(), "@42");
2696    }
2697
2698    #[test]
2699    fn tmux_identity_from_data_back_compat_is_none() {
2700        // Legacy create.sh: no qualified fields at all.
2701        let legacy = serde_json::json!({ "tmux_window": "🚀 wt/x" });
2702        assert!(tmux_identity_from_data(&legacy).is_none());
2703        // Partial (window_id without session) is also insufficient → None.
2704        let partial = serde_json::json!({ "tmux_window_id": "@42" });
2705        assert!(tmux_identity_from_data(&partial).is_none());
2706    }
2707
2708    /// End-to-end: a `node.created` event carrying the qualified fields folds
2709    /// them into `Node.tmux_identity`; one without them leaves it `None`.
2710    #[test]
2711    fn node_created_populates_tmux_identity() {
2712        let tmp = TempDir::new().unwrap();
2713        let run_id = "01jxsnap000000000000000000";
2714        let rid = RunId::parse_str(run_id).unwrap();
2715        let dir = crate::run_dir(tmp.path(), &rid);
2716        std::fs::create_dir_all(&dir).unwrap();
2717        let paths = RunPaths::new(dir, run_id).unwrap();
2718
2719        let mut ev = event(run_id);
2720        ev.seq = 2;
2721        ev.kind = "node.created".into();
2722        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2723        ev.data = serde_json::json!({
2724            "kind": "spinoff",
2725            "tmux_window": "🚀 wt/x",
2726            "tmux_socket": "/private/tmp/tmux-501/default",
2727            "tmux_session": "taskfleet",
2728            "tmux_window_id": "@42",
2729        });
2730        apply_event(&paths, &ev).expect("node.created applies");
2731        let n = read_node_opt(&paths, &NodeId::parse_str("n-0001").unwrap())
2732            .unwrap()
2733            .unwrap();
2734        let id = n.tmux_identity.expect("qualified identity recorded");
2735        assert_eq!(id.session, "taskfleet");
2736        assert_eq!(id.window_id, "@42");
2737        assert_eq!(n.tmux_window.as_deref(), Some("🚀 wt/x"));
2738
2739        // A second run with a legacy event leaves tmux_identity None.
2740        let run2 = "02jxsnap000000000000000000";
2741        let rid2 = RunId::parse_str(run2).unwrap();
2742        let dir2 = crate::run_dir(tmp.path(), &rid2);
2743        std::fs::create_dir_all(&dir2).unwrap();
2744        let paths2 = RunPaths::new(dir2, run2).unwrap();
2745        let mut ev2 = event(run2);
2746        ev2.seq = 2;
2747        ev2.kind = "node.created".into();
2748        ev2.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2749        ev2.data = serde_json::json!({ "kind": "spinoff", "tmux_window": "🚀 wt/y" });
2750        apply_event(&paths2, &ev2).expect("legacy node.created applies");
2751        let n2 = read_node_opt(&paths2, &NodeId::parse_str("n-0001").unwrap())
2752            .unwrap()
2753            .unwrap();
2754        assert!(n2.tmux_identity.is_none());
2755        assert_eq!(n2.tmux_window.as_deref(), Some("🚀 wt/y"));
2756    }
2757
2758    #[test]
2759    fn node_materialization_populates_missing_manifest_source_branch() {
2760        let tmp = TempDir::new().unwrap();
2761        let run_id = "01jxsnap000000000000000001";
2762        let rid = RunId::parse_str(run_id).unwrap();
2763        let dir = crate::run_dir(tmp.path(), &rid);
2764        std::fs::create_dir_all(&dir).unwrap();
2765        let paths = RunPaths::new(dir, run_id).unwrap();
2766
2767        let mut created = event(run_id);
2768        created.kind = "run.created".into();
2769        created.data = serde_json::json!({
2770            "kind": "spinoff", "lifecycle": "autonomous", "title": "t"
2771        });
2772        apply_event(&paths, &created).unwrap();
2773        assert!(read_manifest_opt(&paths)
2774            .unwrap()
2775            .unwrap()
2776            .source_branch
2777            .is_none());
2778
2779        let mut node = event(run_id);
2780        node.seq = 2;
2781        node.kind = "node.created".into();
2782        node.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2783        node.data = serde_json::json!({
2784            "kind": "spinoff",
2785            "source_branch": "main",
2786            "worktree_path": "/tmp/wt/pending"
2787        });
2788        apply_event(&paths, &node).unwrap();
2789
2790        let manifest = read_manifest_opt(&paths).unwrap().unwrap();
2791        assert_eq!(manifest.status, Status::Pending);
2792        assert_eq!(manifest.source_branch.as_deref(), Some("main"));
2793        let node = read_n0001(&paths);
2794        assert_eq!(node.worktree_path.as_deref(), Some("/tmp/wt/pending"));
2795    }
2796
2797    #[test]
2798    fn node_materialization_preserves_explicit_manifest_source_branch() {
2799        let tmp = TempDir::new().unwrap();
2800        let run_id = "01jxsnap000000000000000002";
2801        let rid = RunId::parse_str(run_id).unwrap();
2802        let dir = crate::run_dir(tmp.path(), &rid);
2803        std::fs::create_dir_all(&dir).unwrap();
2804        let paths = RunPaths::new(dir, run_id).unwrap();
2805
2806        let mut created = event(run_id);
2807        created.kind = "run.created".into();
2808        created.data = serde_json::json!({
2809            "kind": "spinoff", "lifecycle": "autonomous", "title": "t",
2810            "source_branch": "release"
2811        });
2812        apply_event(&paths, &created).unwrap();
2813
2814        let mut node = event(run_id);
2815        node.seq = 2;
2816        node.kind = "node.created".into();
2817        node.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2818        node.data = serde_json::json!({
2819            "kind": "spinoff", "source_branch": "main"
2820        });
2821        apply_event(&paths, &node).unwrap();
2822
2823        assert_eq!(
2824            read_manifest_opt(&paths)
2825                .unwrap()
2826                .unwrap()
2827                .source_branch
2828                .as_deref(),
2829            Some("release")
2830        );
2831    }
2832
2833    /// Bootstrap a run with a single `n-0001` node via the event-sourced path,
2834    /// returning its paths. Shared by the supervisor-state replay tests below.
2835    fn seed_run_with_node(tmp: &TempDir, run_id: &str) -> RunPaths {
2836        let rid = RunId::parse_str(run_id).unwrap();
2837        let dir = crate::run_dir(tmp.path(), &rid);
2838        std::fs::create_dir_all(&dir).unwrap();
2839        let paths = RunPaths::new(dir, run_id).unwrap();
2840
2841        let mut created = event(run_id);
2842        created.kind = "run.created".into();
2843        created.data = serde_json::json!({
2844            "kind": "spinoff", "lifecycle": "autonomous", "title": "t"
2845        });
2846        apply_event(&paths, &created).expect("run.created applies");
2847
2848        let mut node = event(run_id);
2849        node.seq = 2;
2850        node.kind = "node.created".into();
2851        node.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2852        node.data = serde_json::json!({ "kind": "spinoff" });
2853        apply_event(&paths, &node).expect("node.created applies");
2854        paths
2855    }
2856
2857    fn read_n0001(paths: &RunPaths) -> Node {
2858        read_node_opt(paths, &NodeId::parse_str("n-0001").unwrap())
2859            .unwrap()
2860            .unwrap()
2861    }
2862
2863    #[test]
2864    fn awaiting_input_clock_is_durable_first_write_wins_and_resolve_is_fenced() {
2865        let tmp = TempDir::new().unwrap();
2866        let run_id = "01jxwd0000000000000000000w";
2867        let paths = seed_run_with_node(&tmp, run_id);
2868        let nid = Some(NodeId::parse_str("n-0001").unwrap());
2869        let opened_at: chrono::DateTime<Utc> = "2026-08-16T12:00:00Z".parse().unwrap();
2870        let mut open = event(run_id);
2871        open.seq = 3;
2872        open.ts = opened_at;
2873        open.kind = "node.awaiting_input".into();
2874        open.node_id = nid.clone();
2875        open.data = serde_json::json!({ "discussion_items": [{
2876            "topic": "Which scope?",
2877            "options": ["small", "large"],
2878            "recommended_default": "small"
2879        }] });
2880        apply_event(&paths, &open).unwrap();
2881        let first = read_n0001(&paths).awaiting_input.unwrap();
2882        assert_eq!(first.opened_at, opened_at);
2883        assert_eq!(first.event_seq, 3);
2884
2885        // A duplicate/restarted supervisor observation cannot restart the clock.
2886        let mut duplicate = open.clone();
2887        duplicate.seq = 4;
2888        duplicate.ts = opened_at + chrono::Duration::hours(1);
2889        apply_event(&paths, &duplicate).unwrap();
2890        let still_first = read_n0001(&paths).awaiting_input.unwrap();
2891        assert_eq!(still_first.opened_at, opened_at);
2892        assert_eq!(still_first.event_seq, 3);
2893
2894        // A stale timeout for another generation cannot clear this request.
2895        let mut stale = event(run_id);
2896        stale.seq = 5;
2897        stale.kind = "node.input_resolved".into();
2898        stale.node_id = nid.clone();
2899        stale.data = serde_json::json!({ "event_seq": 2 });
2900        apply_event(&paths, &stale).unwrap();
2901        assert!(read_n0001(&paths).awaiting_input.is_some());
2902
2903        let mut resolved = stale;
2904        resolved.seq = 6;
2905        resolved.data = serde_json::json!({ "event_seq": 3 });
2906        apply_event(&paths, &resolved).unwrap();
2907        assert!(read_n0001(&paths).awaiting_input.is_none());
2908    }
2909
2910    #[test]
2911    fn awaiting_input_rejects_missing_default_without_mutating_projection() {
2912        let tmp = TempDir::new().unwrap();
2913        let run_id = "01jxwd0000000000000000000x";
2914        let paths = seed_run_with_node(&tmp, run_id);
2915        let mut open = event(run_id);
2916        open.seq = 3;
2917        open.kind = "node.awaiting_input".into();
2918        open.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2919        open.data = serde_json::json!({ "discussion_items": [{
2920            "topic": "Which scope?", "options": ["small", "large"]
2921        }] });
2922        assert!(reduce_event_to_ops(&paths, &open).is_err());
2923        assert!(read_n0001(&paths).awaiting_input.is_none());
2924    }
2925
2926    #[test]
2927    fn awaiting_input_validation_is_state_independent_and_worker_exit_clears_it() {
2928        let tmp = TempDir::new().unwrap();
2929        let run_id = "01jxwd0000000000000000000y";
2930        let paths = seed_run_with_node(&tmp, run_id);
2931        let nid = Some(NodeId::parse_str("n-0001").unwrap());
2932
2933        let mut open = event(run_id);
2934        open.seq = 3;
2935        open.kind = "node.awaiting_input".into();
2936        open.node_id = nid.clone();
2937        open.data = serde_json::json!({ "discussion_items": [{
2938            "topic": "Which scope?", "options": ["small", "large"],
2939            "recommended_default": "small"
2940        }] });
2941        apply_event(&paths, &open).unwrap();
2942
2943        let mut malformed_duplicate = open.clone();
2944        malformed_duplicate.seq = 4;
2945        malformed_duplicate.data = serde_json::json!({ "discussion_items": [] });
2946        assert!(reduce_event_to_ops(&paths, &malformed_duplicate).is_err());
2947
2948        let mut exited = event(run_id);
2949        exited.seq = 5;
2950        exited.kind = "worker.exited".into();
2951        exited.node_id = nid;
2952        exited.data = serde_json::json!({ "exit_code": 0 });
2953        apply_event(&paths, &exited).unwrap();
2954        let node = read_n0001(&paths);
2955        assert!(node.awaiting_input.is_none());
2956        assert!(node.worker_exit.is_some());
2957
2958        let mut delayed_open = open;
2959        delayed_open.seq = 6;
2960        assert!(reduce_event_to_ops(&paths, &delayed_open)
2961            .unwrap()
2962            .is_empty());
2963    }
2964
2965    #[test]
2966    fn input_resolved_requires_generation_even_when_nothing_is_open() {
2967        let tmp = TempDir::new().unwrap();
2968        let run_id = "01jxwd0000000000000000000z";
2969        let paths = seed_run_with_node(&tmp, run_id);
2970        let mut resolved = event(run_id);
2971        resolved.seq = 3;
2972        resolved.kind = "node.input_resolved".into();
2973        resolved.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2974        resolved.data = serde_json::json!({});
2975        assert!(reduce_event_to_ops(&paths, &resolved).is_err());
2976    }
2977
2978    #[test]
2979    fn awaiting_input_default_must_be_one_of_options() {
2980        let tmp = TempDir::new().unwrap();
2981        let run_id = "01jxwd00000000000000000010";
2982        let paths = seed_run_with_node(&tmp, run_id);
2983        let mut open = event(run_id);
2984        open.seq = 3;
2985        open.kind = "node.awaiting_input".into();
2986        open.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2987        open.data = serde_json::json!({ "discussion_items": [{
2988            "topic": "Which scope?", "options": ["small", "large"],
2989            "recommended_default": "other"
2990        }] });
2991        assert!(reduce_event_to_ops(&paths, &open).is_err());
2992    }
2993
2994    fn merge_started_event(run_id: &str, seq: u64, op_id: &str, expected: &str) -> Event {
2995        let mut ev = event(run_id);
2996        ev.seq = seq;
2997        ev.kind = KIND_MERGE_STARTED.into();
2998        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
2999        ev.data = serde_json::json!({
3000            "op_id": op_id,
3001            "source_branch": "main",
3002            "worker_branch": "wt/worker",
3003            "expected_source_oid": expected,
3004            "worker_oid": "cafebabecafebabecafebabecafebabecafebabe",
3005            "base_sha": null,
3006            "driver_pid": 4242,
3007            "driver_pid_start_secs": null,
3008            "started_at": "2026-08-15T00:00:00Z",
3009        });
3010        ev
3011    }
3012
3013    /// `merge.started` records the in-flight transaction on `pending_merge`
3014    /// without transitioning the node's status.
3015    #[test]
3016    fn merge_started_records_pending_transaction() {
3017        let tmp = TempDir::new().unwrap();
3018        let run_id = "01jxsnap000000000000000000";
3019        let paths = seed_run_with_node(&tmp, run_id);
3020
3021        apply_event(&paths, &merge_started_event(run_id, 3, "op-1", "aaa")).unwrap();
3022        let n = read_n0001(&paths);
3023        assert_eq!(
3024            n.status,
3025            Status::Pending,
3026            "recording a merge is not terminal"
3027        );
3028        let txn = n.pending_merge.expect("transaction recorded");
3029        assert_eq!(txn.op_id, "op-1");
3030        assert_eq!(txn.expected_source_oid, "aaa");
3031    }
3032
3033    /// `merge.aborted` clears the pending transaction it names, leaving the node
3034    /// live; a stale abort for a different `op_id` is a clean no-op.
3035    #[test]
3036    fn merge_aborted_clears_matching_transaction_only() {
3037        let tmp = TempDir::new().unwrap();
3038        let run_id = "01jxsnap000000000000000000";
3039        let paths = seed_run_with_node(&tmp, run_id);
3040        apply_event(&paths, &merge_started_event(run_id, 3, "op-1", "aaa")).unwrap();
3041
3042        // A stale abort for a different op_id does nothing.
3043        let mut stale = event(run_id);
3044        stale.seq = 4;
3045        stale.kind = KIND_MERGE_ABORTED.into();
3046        stale.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3047        stale.data = serde_json::json!({ "op_id": "op-OTHER", "reason": "x" });
3048        apply_event(&paths, &stale).unwrap();
3049        assert!(
3050            read_n0001(&paths).pending_merge.is_some(),
3051            "stale abort is a no-op"
3052        );
3053
3054        // The matching abort clears it; the node stays live.
3055        let mut abort = event(run_id);
3056        abort.seq = 5;
3057        abort.kind = KIND_MERGE_ABORTED.into();
3058        abort.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3059        abort.data = serde_json::json!({ "op_id": "op-1", "reason": "no mutation" });
3060        apply_event(&paths, &abort).unwrap();
3061        let n = read_n0001(&paths);
3062        assert!(
3063            n.pending_merge.is_none(),
3064            "matching abort clears the transaction"
3065        );
3066        assert_eq!(n.status, Status::Pending, "abort does not terminalize");
3067    }
3068
3069    /// A terminal `node.report` (the normal, no-crash completion) clears any
3070    /// pending merge transaction.
3071    #[test]
3072    fn terminal_report_clears_pending_merge() {
3073        let tmp = TempDir::new().unwrap();
3074        let run_id = "01jxsnap000000000000000000";
3075        let paths = seed_run_with_node(&tmp, run_id);
3076        apply_event(&paths, &merge_started_event(run_id, 3, "op-1", "aaa")).unwrap();
3077
3078        let mut report = event(run_id);
3079        report.seq = 4;
3080        report.kind = "node.report".into();
3081        report.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3082        report.data = serde_json::json!({ "success": true, "via": "explicit-merge" });
3083        apply_event(&paths, &report).unwrap();
3084        let n = read_n0001(&paths);
3085        assert_eq!(n.status, Status::Done);
3086        assert!(
3087            n.pending_merge.is_none(),
3088            "completed merge clears the transaction"
3089        );
3090    }
3091
3092    /// Regression (issue `retire-via-string`): the terminal-node adoption
3093    /// exception now keys on the typed `RunMerge` origin, NOT a forgeable `via`
3094    /// string. A late report against a `Failed` node that carries an `Agent`
3095    /// origin (as every `node report` self-submission does) plus a forged
3096    /// `via: "explicit-merge"` must NOT be adopted — the node stays `Failed`. A
3097    /// present-but-malformed origin is likewise not adopted. Only a genuine
3098    /// `RunMerge`-origin report (or a legacy report with NO origin field) is
3099    /// adopted and corrects the node to `Done`.
3100    #[test]
3101    fn late_merge_adoption_requires_run_merge_origin_not_forged_via() {
3102        let tmp = TempDir::new().unwrap();
3103
3104        // Helper: seed a fresh run (distinct id), drive n-0001 to Failed, apply a
3105        // late report, and return the resulting node status.
3106        let drive = |run_id: &str, report_data: Value| -> Status {
3107            let paths = seed_run_with_node(&tmp, run_id);
3108            // Terminalize the node as Failed (a watchdog-synthesized failure).
3109            let mut fail = event(run_id);
3110            fail.seq = 3;
3111            fail.kind = "node.status".into();
3112            fail.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3113            fail.data = serde_json::json!({ "status": "failed" });
3114            apply_event(&paths, &fail).unwrap();
3115            assert_eq!(read_n0001(&paths).status, Status::Failed);
3116            // The late report under test.
3117            let mut report = event(run_id);
3118            report.seq = 4;
3119            report.kind = "node.report".into();
3120            report.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3121            report.data = report_data;
3122            apply_event(&paths, &report).unwrap();
3123            read_n0001(&paths).status
3124        };
3125
3126        // Forged: Agent origin + a hand-set `via` — NOT adopted, stays Failed.
3127        let mut agent_forged = serde_json::json!({ "success": true, "via": "explicit-merge" });
3128        crate::ReportOrigin::Agent.stamp(&mut agent_forged);
3129        assert_eq!(
3130            drive("01jxsnap000000000000000001", agent_forged),
3131            Status::Failed,
3132            "an Agent-origin report with a forged via must not be adopted"
3133        );
3134
3135        // Present-but-malformed origin + forged via — NOT adopted, stays Failed.
3136        let malformed = serde_json::json!({
3137            "success": true, "via": "explicit-merge", "origin": "garbage-not-an-object"
3138        });
3139        assert_eq!(
3140            drive("01jxsnap000000000000000002", malformed),
3141            Status::Failed,
3142            "a malformed origin must not re-unlock the legacy via adoption path"
3143        );
3144
3145        // Genuine RunMerge origin (no `via` at all) — adopted, corrected to Done.
3146        let mut run_merge = serde_json::json!({ "success": true });
3147        crate::ReportOrigin::RunMerge {
3148            op_id: Some("op-1".into()),
3149            worker_oid: Some("cafebabe".into()),
3150            integrated_oid: None,
3151        }
3152        .stamp(&mut run_merge);
3153        assert_eq!(
3154            drive("01jxsnap000000000000000003", run_merge),
3155            Status::Done,
3156            "a genuine RunMerge-origin report is adopted and corrects Failed→Done"
3157        );
3158
3159        // Legacy report (no origin field) with `via` — still adopted (backward
3160        // compat with pre-typed-origin on-disk runs).
3161        let legacy = serde_json::json!({ "success": true, "via": "explicit-merge" });
3162        assert_eq!(
3163            drive("01jxsnap000000000000000004", legacy),
3164            Status::Done,
3165            "a legacy via-only report (no origin field) is still adopted"
3166        );
3167    }
3168
3169    /// A terminal `node.status` (e.g. a watchdog-synthesized failure) clears any
3170    /// in-flight merge transaction, so `pending_merge` is never stranded on a
3171    /// terminal node where recovery would refuse to look (/llm-review finding).
3172    #[test]
3173    fn terminal_node_status_clears_pending_merge() {
3174        let tmp = TempDir::new().unwrap();
3175        let run_id = "01jxsnap000000000000000000";
3176        let paths = seed_run_with_node(&tmp, run_id);
3177        apply_event(&paths, &merge_started_event(run_id, 3, "op-1", "aaa")).unwrap();
3178        assert!(read_n0001(&paths).pending_merge.is_some());
3179
3180        let mut status = event(run_id);
3181        status.seq = 4;
3182        status.kind = "node.status".into();
3183        status.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3184        status.data = serde_json::json!({ "status": "failed" });
3185        apply_event(&paths, &status).unwrap();
3186        let n = read_n0001(&paths);
3187        assert_eq!(n.status, Status::Failed);
3188        assert!(
3189            n.pending_merge.is_none(),
3190            "terminal status clears the transaction"
3191        );
3192    }
3193
3194    /// Replaying `supervisor.attached` from scratch reproduces
3195    /// `Node.supervisor_pid` — the field is now event-sourced, not a
3196    /// projection-only write (issue `supervisor-state-not-event-sourced`).
3197    #[test]
3198    fn supervisor_attached_sets_supervisor_pid() {
3199        let tmp = TempDir::new().unwrap();
3200        let run_id = "01jxsnap000000000000000000";
3201        let paths = seed_run_with_node(&tmp, run_id);
3202        assert_eq!(read_n0001(&paths).supervisor_pid, None);
3203
3204        let mut ev = event(run_id);
3205        ev.seq = 3;
3206        ev.kind = "supervisor.attached".into();
3207        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3208        ev.data = serde_json::json!({ "pid": 47820 });
3209        apply_event(&paths, &ev).expect("supervisor.attached applies");
3210        assert_eq!(read_n0001(&paths).supervisor_pid, Some(47820));
3211    }
3212
3213    /// A second attach with a different pid overrides (latest-wins); a replay
3214    /// of the *same* pid is a pure no-op that does not churn `updated_at`.
3215    #[test]
3216    fn supervisor_attached_latest_wins_and_idempotent_on_replay() {
3217        let tmp = TempDir::new().unwrap();
3218        let run_id = "01jxsnap000000000000000000";
3219        let paths = seed_run_with_node(&tmp, run_id);
3220
3221        let mut ev = event(run_id);
3222        ev.kind = "supervisor.attached".into();
3223        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3224
3225        ev.seq = 3;
3226        ev.data = serde_json::json!({ "pid": 100 });
3227        apply_event(&paths, &ev).expect("first attach applies");
3228        assert_eq!(read_n0001(&paths).supervisor_pid, Some(100));
3229
3230        // A restart binds a fresh pid: latest-wins.
3231        ev.seq = 4;
3232        ev.data = serde_json::json!({ "pid": 200 });
3233        apply_event(&paths, &ev).expect("second attach applies");
3234        let after_second = read_n0001(&paths);
3235        assert_eq!(after_second.supervisor_pid, Some(200));
3236
3237        // Replaying the latest event again is a no-op: the planned ops are
3238        // empty and the projection bytes (including `updated_at`) are unchanged.
3239        let ops = reduce_event_to_ops(&paths, &ev).expect("replay reduces cleanly");
3240        assert!(ops.is_empty(), "re-applying same pid must plan no ops");
3241        apply_event(&paths, &ev).expect("replay applies as no-op");
3242        assert_eq!(read_n0001(&paths).updated_at, after_second.updated_at);
3243    }
3244
3245    /// Replaying `supervisor.cursor_advanced` from scratch reproduces
3246    /// `Node.last_processed_report_seq_by_child`.
3247    #[test]
3248    fn supervisor_cursor_advanced_sets_report_cursor() {
3249        let tmp = TempDir::new().unwrap();
3250        let run_id = "01jxsnap000000000000000000";
3251        let paths = seed_run_with_node(&tmp, run_id);
3252        let child = "02jxsnap000000000000000000";
3253
3254        let mut ev = event(run_id);
3255        ev.seq = 3;
3256        ev.kind = "supervisor.cursor_advanced".into();
3257        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3258        ev.data = serde_json::json!({ "child_run_id": child, "report_seq": 7 });
3259        apply_event(&paths, &ev).expect("cursor_advanced applies");
3260
3261        let n = read_n0001(&paths);
3262        assert_eq!(
3263            n.last_processed_report_seq_by_child.get(child),
3264            Some(&Value::from(7u64))
3265        );
3266    }
3267
3268    /// The cursor is monotonic and idempotent: re-applying the same
3269    /// `(child_run_id, report_seq)` is a no-op, an older seq never moves the
3270    /// cursor backward, and a higher seq advances it. A second distinct child
3271    /// gets its own independent entry.
3272    #[test]
3273    fn supervisor_cursor_advanced_is_monotonic_and_idempotent() {
3274        let tmp = TempDir::new().unwrap();
3275        let run_id = "01jxsnap000000000000000000";
3276        let paths = seed_run_with_node(&tmp, run_id);
3277        let child_a = "02jxsnap000000000000000000";
3278        let child_b = "03jxsnap000000000000000000";
3279
3280        let mut ev = event(run_id);
3281        ev.kind = "supervisor.cursor_advanced".into();
3282        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3283
3284        ev.seq = 3;
3285        ev.data = serde_json::json!({ "child_run_id": child_a, "report_seq": 5 });
3286        apply_event(&paths, &ev).expect("seq 5 applies");
3287
3288        // Replay the exact same event — no-op, plans zero ops.
3289        let ops = reduce_event_to_ops(&paths, &ev).expect("replay reduces cleanly");
3290        assert!(ops.is_empty(), "re-applying same cursor must plan no ops");
3291
3292        // An older seq must not move the cursor backward.
3293        ev.seq = 4;
3294        ev.data = serde_json::json!({ "child_run_id": child_a, "report_seq": 3 });
3295        let ops = reduce_event_to_ops(&paths, &ev).expect("older seq reduces cleanly");
3296        assert!(ops.is_empty(), "older seq must plan no ops");
3297        apply_event(&paths, &ev).expect("older seq applies as no-op");
3298        assert_eq!(
3299            read_n0001(&paths)
3300                .last_processed_report_seq_by_child
3301                .get(child_a),
3302            Some(&Value::from(5u64))
3303        );
3304
3305        // A higher seq advances; an independent child gets its own entry.
3306        ev.seq = 5;
3307        ev.data = serde_json::json!({ "child_run_id": child_a, "report_seq": 9 });
3308        apply_event(&paths, &ev).expect("higher seq applies");
3309        ev.seq = 6;
3310        ev.data = serde_json::json!({ "child_run_id": child_b, "report_seq": 1 });
3311        apply_event(&paths, &ev).expect("second child applies");
3312
3313        let n = read_n0001(&paths);
3314        assert_eq!(
3315            n.last_processed_report_seq_by_child.get(child_a),
3316            Some(&Value::from(9u64))
3317        );
3318        assert_eq!(
3319            n.last_processed_report_seq_by_child.get(child_b),
3320            Some(&Value::from(1u64))
3321        );
3322    }
3323
3324    /// Both new kinds reject a malformed payload at the reducer boundary so a
3325    /// forged event can never write a corrupt projection.
3326    #[test]
3327    fn supervisor_state_events_reject_malformed_payloads() {
3328        let tmp = TempDir::new().unwrap();
3329        let run_id = "01jxsnap000000000000000000";
3330        let paths = seed_run_with_node(&tmp, run_id);
3331        let nid = Some(NodeId::parse_str("n-0001").unwrap());
3332
3333        // Missing pid.
3334        let mut ev = event(run_id);
3335        ev.seq = 3;
3336        ev.kind = "supervisor.attached".into();
3337        ev.node_id = nid.clone();
3338        ev.data = serde_json::json!({});
3339        assert!(matches!(
3340            reduce_event_to_ops(&paths, &ev),
3341            Err(Error::CorruptEventLog { .. })
3342        ));
3343
3344        // Missing envelope node_id.
3345        ev.node_id = None;
3346        ev.data = serde_json::json!({ "pid": 1 });
3347        assert!(matches!(
3348            reduce_event_to_ops(&paths, &ev),
3349            Err(Error::CorruptEventLog { .. })
3350        ));
3351
3352        // cursor_advanced: malformed child_run_id.
3353        let mut ev2 = event(run_id);
3354        ev2.seq = 4;
3355        ev2.kind = "supervisor.cursor_advanced".into();
3356        ev2.node_id = nid.clone();
3357        ev2.data = serde_json::json!({ "child_run_id": "../etc", "report_seq": 1 });
3358        assert!(matches!(
3359            reduce_event_to_ops(&paths, &ev2),
3360            Err(Error::CorruptEventLog { .. })
3361        ));
3362
3363        // cursor_advanced: missing report_seq.
3364        ev2.data = serde_json::json!({ "child_run_id": "02jxsnap000000000000000000" });
3365        assert!(matches!(
3366            reduce_event_to_ops(&paths, &ev2),
3367            Err(Error::CorruptEventLog { .. })
3368        ));
3369    }
3370
3371    /// The append gate stays fail-closed after the 0.2 cut added
3372    /// `Kind`'s `#[serde(other)]` catch-all: a `run.created` / `node.created`
3373    /// whose `kind` is a removed kind (`code`, …) or plain garbage must still be
3374    /// rejected as `CorruptEventLog`, NOT silently accepted as `Kind::Unknown`.
3375    /// (Legacy runs are never re-created through the reducer — their manifest is
3376    /// read directly from disk via the permissive `Kind::Unknown` decode.)
3377    #[test]
3378    fn removed_or_garbage_kind_in_created_events_is_rejected() {
3379        let tmp = TempDir::new().unwrap();
3380        let run_id = "01jxsnap000000000000000000";
3381        let rid = RunId::parse_str(run_id).unwrap();
3382        let dir = crate::run_dir(tmp.path(), &rid);
3383        std::fs::create_dir_all(&dir).unwrap();
3384        let paths = RunPaths::new(dir, run_id).unwrap();
3385
3386        for bad in ["code", "orchestrate", "bugfix", "make-skill", "garbage"] {
3387            let mut ev = event(run_id);
3388            ev.kind = "run.created".into();
3389            ev.node_id = None;
3390            ev.data = serde_json::json!({ "kind": bad, "lifecycle": "autonomous", "title": "t" });
3391            assert!(
3392                matches!(
3393                    reduce_event_to_ops(&paths, &ev),
3394                    Err(Error::CorruptEventLog { .. })
3395                ),
3396                "run.created with kind {bad:?} must be rejected, not folded to Unknown"
3397            );
3398        }
3399
3400        // A surviving creatable kind still folds cleanly (guards against a
3401        // false positive that rejects everything).
3402        let mut ok = event(run_id);
3403        ok.kind = "run.created".into();
3404        ok.node_id = None;
3405        ok.data = serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" });
3406        assert!(reduce_event_to_ops(&paths, &ok).is_ok());
3407    }
3408
3409    /// Snapshot every projection file under `paths` to a `path → inode` map.
3410    ///
3411    /// An atomic projection write is temp-file + rename, so a rewritten file
3412    /// always lands a *fresh inode* — even when its bytes are byte-for-byte
3413    /// identical (e.g. a manifest op that refreshes `updated_at` to the same
3414    /// timestamp). Comparing inodes therefore detects every write the reducer
3415    /// makes, with no false negatives a content diff would suffer. `events.jsonl`
3416    /// and `.lock` are excluded: `apply_event` never touches them.
3417    #[cfg(unix)]
3418    fn projection_inodes(paths: &RunPaths) -> std::collections::BTreeMap<PathBuf, u64> {
3419        use std::os::unix::fs::MetadataExt;
3420        let mut consider = vec![paths.manifest()];
3421        for dir in [paths.nodes_dir()] {
3422            if let Ok(rd) = std::fs::read_dir(&dir) {
3423                for ent in rd.flatten() {
3424                    let p = ent.path();
3425                    if p.extension().and_then(|s| s.to_str()) == Some("json") {
3426                        consider.push(p);
3427                    }
3428                }
3429            }
3430        }
3431        let mut map = std::collections::BTreeMap::new();
3432        for p in consider {
3433            if let Ok(md) = std::fs::symlink_metadata(&p) {
3434                if md.file_type().is_file() {
3435                    map.insert(p, md.ino());
3436                }
3437            }
3438        }
3439        map
3440    }
3441
3442    /// The exhaustive parity guarantee `projected-paths-into-reducer` requires:
3443    /// for an event applied against a given state, the paths
3444    /// [`plan_projections`] reports MUST equal the files [`apply_event`]
3445    /// actually writes. Plan first (against pre-apply state), apply, then diff
3446    /// the projection inodes — a file is "written" iff it is newly present or
3447    /// its inode changed. `expect_writes` guards the test itself: when set, the
3448    /// touched set must be non-empty, so a kind that silently stopped writing
3449    /// can't pass by matching an empty plan against an empty diff.
3450    #[cfg(unix)]
3451    fn assert_plan_matches_apply(paths: &RunPaths, ev: &Event, expect_writes: bool) {
3452        use std::collections::BTreeSet;
3453        let before = projection_inodes(paths);
3454        let planned: BTreeSet<PathBuf> = plan_projections(paths, ev)
3455            .unwrap_or_else(|e| panic!("plan_projections({}) errored: {e:?}", ev.kind))
3456            .into_iter()
3457            .collect();
3458        apply_event(paths, ev)
3459            .unwrap_or_else(|e| panic!("apply_event({}) errored: {e:?}", ev.kind));
3460        let after = projection_inodes(paths);
3461        let touched: BTreeSet<PathBuf> = after
3462            .iter()
3463            .filter(|(p, ino)| before.get(*p) != Some(*ino))
3464            .map(|(p, _)| p.clone())
3465            .collect();
3466        assert_eq!(
3467            planned, touched,
3468            "kind={}: plan_projections must name exactly the files apply_event writes",
3469            ev.kind
3470        );
3471        if expect_writes {
3472            assert!(
3473                !touched.is_empty(),
3474                "kind={}: expected this event to write at least one projection",
3475                ev.kind
3476            );
3477        }
3478    }
3479
3480    /// Drive every event kind through a dependency-ordered lifecycle on real
3481    /// runs, asserting plan/apply parity at each step. Covers the writing kinds
3482    /// (run/node/supervisor/child) in states where they
3483    /// project, plus the no-op kinds (audit records, `supervisor.exited`,
3484    /// terminal-guarded transitions) where both the plan and the apply touch
3485    /// nothing.
3486    #[cfg(unix)]
3487    #[test]
3488    fn plan_projections_matches_apply_for_every_kind() {
3489        let tmp = TempDir::new().unwrap();
3490        let run_id = "01jxsnap000000000000000000";
3491        let rid = RunId::parse_str(run_id).unwrap();
3492        let dir = crate::run_dir(tmp.path(), &rid);
3493        std::fs::create_dir_all(&dir).unwrap();
3494        let paths = RunPaths::new(dir, run_id).unwrap();
3495        let nid = || Some(NodeId::parse_str("n-0001").unwrap());
3496        let child = "02jxsnap000000000000000000";
3497
3498        // Helper to build a fresh envelope at a monotonic seq.
3499        let mut next_seq = 0u64;
3500        let mut at = |kind: &str, node_id, data| {
3501            next_seq += 1;
3502            Event {
3503                ts: Utc::now(),
3504                seq: next_seq,
3505                kind: kind.into(),
3506                run_id: rid.clone(),
3507                node_id,
3508                idempotency_key: None,
3509                data,
3510            }
3511        };
3512
3513        // run.created → manifest.json
3514        assert_plan_matches_apply(
3515            &paths,
3516            &at(
3517                "run.created",
3518                None,
3519                serde_json::json!({ "kind": "spinoff", "lifecycle": "autonomous", "title": "t" }),
3520            ),
3521            true,
3522        );
3523        // run.status (pending → running) → manifest.json
3524        assert_plan_matches_apply(
3525            &paths,
3526            &at(
3527                "run.status",
3528                None,
3529                serde_json::json!({ "status": "running" }),
3530            ),
3531            true,
3532        );
3533        // node.created → nodes/n-0001.json + manifest.json
3534        assert_plan_matches_apply(
3535            &paths,
3536            &at(
3537                "node.created",
3538                nid(),
3539                serde_json::json!({ "kind": "spinoff" }),
3540            ),
3541            true,
3542        );
3543        // node.status (pending → running) → nodes/n-0001.json
3544        assert_plan_matches_apply(
3545            &paths,
3546            &at(
3547                "node.status",
3548                nid(),
3549                serde_json::json!({ "status": "running" }),
3550            ),
3551            true,
3552        );
3553        // supervisor.attached → nodes/n-0001.json (still non-terminal)
3554        assert_plan_matches_apply(
3555            &paths,
3556            &at(
3557                "supervisor.attached",
3558                nid(),
3559                serde_json::json!({ "pid": 4242 }),
3560            ),
3561            true,
3562        );
3563        // supervisor.cursor_advanced → nodes/n-0001.json
3564        assert_plan_matches_apply(
3565            &paths,
3566            &at(
3567                "supervisor.cursor_advanced",
3568                nid(),
3569                serde_json::json!({ "child_run_id": child, "report_seq": 3 }),
3570            ),
3571            true,
3572        );
3573        // child.spawned → nodes/n-0001.json (parent node)
3574        assert_plan_matches_apply(
3575            &paths,
3576            &at(
3577                "child.spawned",
3578                nid(),
3579                serde_json::json!({ "child_run_id": child, "child_node_id": "n-0001" }),
3580            ),
3581            true,
3582        );
3583        // node.report success → nodes/n-0001.json (now terminal)
3584        assert_plan_matches_apply(
3585            &paths,
3586            &at("node.report", nid(), serde_json::json!({ "success": true })),
3587            true,
3588        );
3589        // Terminal-guarded no-ops: a settled node swallows further transitions,
3590        // so both the plan and the apply touch nothing.
3591        assert_plan_matches_apply(
3592            &paths,
3593            &at(
3594                "node.status",
3595                nid(),
3596                serde_json::json!({ "status": "failed" }),
3597            ),
3598            false,
3599        );
3600        // No-op audit / lifecycle kinds: zero projections by design.
3601        for kind in [
3602            "supervisor.exited",
3603            "orchestrator.decision",
3604            "discuss.critical",
3605            "cleanup.window_missing",
3606        ] {
3607            assert_plan_matches_apply(&paths, &at(kind, None, serde_json::json!({})), false);
3608        }
3609    }
3610
3611    /// A `worker.exited` carrying a clean `exit_code: 0` folds onto the node's
3612    /// `worker_exit` field as a clean exit — and does NOT transition `status`
3613    /// (terminalization is the supervisor's decision via the typed table).
3614    #[test]
3615    fn worker_exited_records_clean_exit_without_transitioning_status() {
3616        let tmp = TempDir::new().unwrap();
3617        let run_id = "01jxsnap000000000000000000";
3618        let paths = bootstrap_retry_node(&tmp, run_id);
3619
3620        let mut ev = event(run_id);
3621        ev.seq = 3;
3622        ev.kind = "worker.exited".into();
3623        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3624        ev.data = serde_json::json!({ "exit_code": 0 });
3625        apply_event(&paths, &ev).expect("worker.exited applies");
3626
3627        let n = read_node_opt(&paths, &NodeId::parse_str("n-0001").unwrap())
3628            .unwrap()
3629            .unwrap();
3630        let exit = n.worker_exit.expect("worker_exit recorded");
3631        assert_eq!(exit.code, Some(0));
3632        assert_eq!(exit.signal, None);
3633        assert!(exit.is_clean());
3634        assert_eq!(
3635            n.status,
3636            Status::Pending,
3637            "the exit fact never transitions status"
3638        );
3639    }
3640
3641    /// A `worker.exited` carrying a `signal` records it as a failure; and the fold
3642    /// is first-write-wins — a replayed/duplicate exit event never overwrites the
3643    /// first recorded fact (replay-safety for the `applied_seq` watermark).
3644    #[test]
3645    fn worker_exited_records_signal_and_is_first_write_wins() {
3646        let tmp = TempDir::new().unwrap();
3647        let run_id = "01jxsnap000000000000000000";
3648        let paths = bootstrap_retry_node(&tmp, run_id);
3649        let nid = NodeId::parse_str("n-0001").unwrap();
3650
3651        let mut ev = event(run_id);
3652        ev.seq = 3;
3653        ev.kind = "worker.exited".into();
3654        ev.node_id = Some(nid.clone());
3655        ev.data = serde_json::json!({ "signal": 9 });
3656        apply_event(&paths, &ev).expect("worker.exited applies");
3657
3658        let n = read_node_opt(&paths, &nid).unwrap().unwrap();
3659        let exit = n.worker_exit.expect("worker_exit recorded");
3660        assert_eq!(exit.signal, Some(9));
3661        assert!(exit.is_failure());
3662
3663        // A later, conflicting exit event (e.g. a replay of a different value) is a
3664        // clean no-op: the first fact stands.
3665        let mut dup = event(run_id);
3666        dup.seq = 4;
3667        dup.kind = "worker.exited".into();
3668        dup.node_id = Some(nid.clone());
3669        dup.data = serde_json::json!({ "exit_code": 0 });
3670        apply_event(&paths, &dup).expect("duplicate worker.exited applies as no-op");
3671        let n2 = read_node_opt(&paths, &nid).unwrap().unwrap();
3672        assert_eq!(
3673            n2.worker_exit.unwrap().signal,
3674            Some(9),
3675            "first-write-wins: the replayed exit must not overwrite the recorded fact"
3676        );
3677    }
3678
3679    /// A `worker.exited` carrying neither `exit_code` nor `signal` is malformed —
3680    /// the reducer is the canonical gate and rejects it as `CorruptEventLog` rather
3681    /// than record an empty fact.
3682    #[test]
3683    fn worker_exited_without_code_or_signal_is_corrupt() {
3684        let tmp = TempDir::new().unwrap();
3685        let run_id = "01jxsnap000000000000000000";
3686        let paths = bootstrap_retry_node(&tmp, run_id);
3687
3688        let mut ev = event(run_id);
3689        ev.seq = 3;
3690        ev.kind = "worker.exited".into();
3691        ev.node_id = Some(NodeId::parse_str("n-0001").unwrap());
3692        ev.data = serde_json::json!({});
3693        match reduce_event_to_ops(&paths, &ev) {
3694            Err(Error::CorruptEventLog { .. }) => {}
3695            Ok(_) => panic!("an empty worker.exited payload must be rejected, not applied"),
3696            Err(other) => panic!("expected CorruptEventLog, got {other:?}"),
3697        }
3698
3699        // Carrying BOTH is contradictory (a process cannot both return a code and
3700        // be killed) — also rejected.
3701        ev.data = serde_json::json!({ "exit_code": 0, "signal": 9 });
3702        match reduce_event_to_ops(&paths, &ev) {
3703            Err(Error::CorruptEventLog { .. }) => {}
3704            Ok(_) => panic!("a worker.exited with both fields must be rejected"),
3705            Err(other) => panic!("expected CorruptEventLog, got {other:?}"),
3706        }
3707    }
3708
3709    /// `node.death_observed` records the residual crash backstop's first-death
3710    /// anchor (`first_death_at`) as `ev.ts`, is **first-write-wins** (a later
3711    /// re-observation never resets the monotonic anchor), and is a no-op against a
3712    /// terminal node (the backstop is moot once settled). Issue
3713    /// `typed-supervisor-outcomes`.
3714    #[test]
3715    fn node_death_observed_records_first_death_first_write_wins() {
3716        let tmp = TempDir::new().unwrap();
3717        let run_id = "01jxsnap000000000000000000";
3718        let paths = bootstrap_retry_node(&tmp, run_id);
3719        let nid = NodeId::parse_str("n-0001").unwrap();
3720
3721        let mut ev = event(run_id);
3722        ev.seq = 3;
3723        ev.kind = "node.death_observed".into();
3724        ev.node_id = Some(nid.clone());
3725        ev.data = serde_json::json!({});
3726        apply_event(&paths, &ev).expect("node.death_observed applies");
3727        let first = read_node_opt(&paths, &nid)
3728            .unwrap()
3729            .unwrap()
3730            .first_death_at
3731            .expect("first_death_at recorded");
3732        assert_eq!(first, ev.ts, "the anchor is the event's own timestamp");
3733
3734        // A later re-observation is first-write-wins: the monotonic anchor holds.
3735        let mut later = event(run_id);
3736        later.seq = 4;
3737        later.kind = "node.death_observed".into();
3738        later.node_id = Some(nid.clone());
3739        later.ts = ev.ts + chrono::Duration::seconds(30);
3740        later.data = serde_json::json!({});
3741        apply_event(&paths, &later).expect("re-observation applies as no-op");
3742        assert_eq!(
3743            read_node_opt(&paths, &nid).unwrap().unwrap().first_death_at,
3744            Some(first),
3745            "first-write-wins: a re-observation must not reset the anchor"
3746        );
3747    }
3748
3749    /// `node.death_observed` is a no-op once a higher-fidelity fact exists — here a
3750    /// told `worker.exited` — so a from-scratch replay converges to the same state
3751    /// the supervisor's lock-guarded emitter would produce (the backstop is moot
3752    /// once the shim recorded a real exit). Issue `typed-supervisor-outcomes`.
3753    #[test]
3754    fn node_death_observed_noop_when_worker_exit_present() {
3755        let tmp = TempDir::new().unwrap();
3756        let run_id = "01jxsnap000000000000000000";
3757        let paths = bootstrap_retry_node(&tmp, run_id);
3758        let nid = NodeId::parse_str("n-0001").unwrap();
3759
3760        // A told exit lands first.
3761        let mut exit = event(run_id);
3762        exit.seq = 3;
3763        exit.kind = "worker.exited".into();
3764        exit.node_id = Some(nid.clone());
3765        exit.data = serde_json::json!({ "exit_code": 0 });
3766        apply_event(&paths, &exit).unwrap();
3767
3768        // A death observation for the same node folds to nothing.
3769        let mut death = event(run_id);
3770        death.seq = 4;
3771        death.kind = "node.death_observed".into();
3772        death.node_id = Some(nid.clone());
3773        death.data = serde_json::json!({});
3774        apply_event(&paths, &death).expect("applies as no-op");
3775        assert_eq!(
3776            read_node_opt(&paths, &nid).unwrap().unwrap().first_death_at,
3777            None,
3778            "a told worker.exited makes the crash backstop moot; no anchor recorded"
3779        );
3780    }
3781
3782    /// `node.retry` clears the previous attempt's told exit fact: the re-spawned
3783    /// worker is a NEW process, so a stale `worker_exit` must not carry over (it
3784    /// would make the supervisor mis-judge the fresh attempt from the dead one's
3785    /// exit). Issue `thin-exit-status-launcher`.
3786    #[test]
3787    fn node_retry_clears_worker_exit() {
3788        let tmp = TempDir::new().unwrap();
3789        let run_id = "01jxsnap000000000000000000";
3790        let paths = bootstrap_retry_node(&tmp, run_id);
3791        let nid = NodeId::parse_str("n-0001").unwrap();
3792
3793        // Record a failing exit on the first attempt.
3794        let mut exit = event(run_id);
3795        exit.seq = 3;
3796        exit.kind = "worker.exited".into();
3797        exit.node_id = Some(nid.clone());
3798        exit.data = serde_json::json!({ "exit_code": 7 });
3799        apply_event(&paths, &exit).unwrap();
3800        assert!(read_node_opt(&paths, &nid)
3801            .unwrap()
3802            .unwrap()
3803            .worker_exit
3804            .is_some());
3805
3806        // Retry re-spawns the node — the stale exit fact must be gone.
3807        let mut retry = event(run_id);
3808        retry.seq = 4;
3809        retry.kind = "node.retry".into();
3810        retry.node_id = Some(nid.clone());
3811        retry.data = serde_json::json!({
3812            "attempt": 1,
3813            "reason": "agent-died",
3814            "branch": "wt/foo",
3815            "worktree_path": "/tmp/new-wt",
3816            "agent_pid": 222,
3817        });
3818        apply_event(&paths, &retry).unwrap();
3819
3820        let n = read_node_opt(&paths, &nid).unwrap().unwrap();
3821        assert!(
3822            n.worker_exit.is_none(),
3823            "node.retry must clear the previous attempt's worker_exit"
3824        );
3825        assert_eq!(
3826            n.status,
3827            Status::Pending,
3828            "retry returns the node to Pending"
3829        );
3830    }
3831}