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