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