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