taskfleet_core/schema.rs
1//! On-disk state schema types per `design.md` §1.
2
3use jiff::Timestamp;
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value};
6
7/// The current state-on-disk schema version this crate writes.
8pub const STATE_SCHEMA_VERSION: u32 = 1;
9
10/// All state-schema versions this crate can read.
11pub const SUPPORTED_STATE_SCHEMAS: &[u32] = &[1];
12
13/// Crockford base32 alphabet in lowercase (excludes `i`, `l`, `o`, `u`). The
14/// charset for the bare ULID of a [`RunId`].
15const CROCKFORD_LOWER: &[u8] = b"0123456789abcdefghjkmnpqrstvwxyz";
16
17/// True iff every byte of `s` is a lowercase Crockford base32 character.
18fn all_crockford_lower(s: &str) -> bool {
19 s.bytes().all(|b| CROCKFORD_LOWER.contains(&b))
20}
21
22/// True iff `s` is a syntactically valid (possibly partial) prefix of a
23/// [`RunId`]: non-empty, no longer than a full ULID, every character a lowercase
24/// Crockford base32 digit, and a first character within ULID's `0..=7`
25/// timestamp bound. Used by the CLI to resolve an unambiguous run-id prefix
26/// (like `git`) — a value failing this is a malformed argument (`invalid_run_id`),
27/// not a legitimate-but-unknown prefix. The first-char bound is enforced because
28/// no valid `RunId` can begin outside `0..=7`, so an `8…`/`9…` prefix is
29/// impossible rather than merely absent — reporting it as malformed keeps the
30/// error class honest and consistent with how [`RunId::parse_str`] rejects a
31/// full-length id with the same leading digit.
32pub fn is_run_id_prefix(s: &str) -> bool {
33 !s.is_empty()
34 && s.len() <= RunId::LEN
35 && all_crockford_lower(s)
36 && matches!(s.as_bytes().first(), Some(b'0'..=b'7'))
37}
38
39/// Error returned when a typed identifier fails parse-time validation.
40///
41/// Every [`RunId`] and [`NodeId`] is
42/// constructed only through its `parse_str` constructor (or the equivalent
43/// validating `Deserialize`), so any value that reaches a path helper has
44/// already been checked for prefix, charset, and length. This is the
45/// path-traversal guard: a raw id containing `/`, `..`, or a leading dot can
46/// never be turned into one of these newtypes, so it can never name a file
47/// outside the run directory.
48#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
49pub enum IdValidationError {
50 /// The value carried the right prefix (or needs none) but its body had the
51 /// wrong length or used characters outside the permitted charset.
52 #[error("invalid {kind} id {value:?}: expected {expected}")]
53 InvalidFormat {
54 /// Which id type rejected the value (`run`, `node`).
55 kind: &'static str,
56 /// The offending raw value.
57 value: String,
58 /// Human-readable description of the accepted shape (e.g. `n-NNNN`).
59 expected: &'static str,
60 },
61 /// The value did not start with the id type's required prefix (`n-`).
62 #[error("invalid {kind} id: wrong prefix, expected {expected}")]
63 WrongPrefix {
64 /// Which id type rejected the value.
65 kind: &'static str,
66 /// Human-readable description of the accepted shape.
67 expected: &'static str,
68 },
69}
70
71impl IdValidationError {
72 /// The id type that rejected the value (`run`, `node`).
73 pub fn kind(&self) -> &'static str {
74 match self {
75 Self::InvalidFormat { kind, .. } | Self::WrongPrefix { kind, .. } => kind,
76 }
77 }
78
79 /// The accepted-shape hint, suitable for the `expected` field of a CLI
80 /// error envelope.
81 pub fn expected(&self) -> &'static str {
82 match self {
83 Self::InvalidFormat { expected, .. } | Self::WrongPrefix { expected, .. } => expected,
84 }
85 }
86}
87
88/// Generate the shared trait surface for a validated id newtype: `as_str`,
89/// `FromStr`, `Display`, `Debug`, `Ord` / `PartialOrd` (lexicographic over the
90/// inner string), `Serialize` (as the bare string), and a validating
91/// `Deserialize` (delegates to `parse_str`, so reading an old file with a
92/// malformed id fails loudly rather than silently widening the type). Each
93/// newtype supplies its own `parse_str` in a separate `impl` block.
94///
95/// `Ord` / `PartialOrd` are derived, so they forward to the inner `String`'s
96/// ordering — i.e. plain `&str` byte comparison. For the fixed-width ULID form
97/// ([`RunId`]) this preserves the natural time ordering ULIDs encode in their
98/// lexical sort.
99///
100/// CAVEAT — this ordering is lexical, *not* numeric or semantic: [`NodeId`] is
101/// `n-` + a variable-width number, so once the counter grows a digit the byte
102/// order diverges from the numeric order: `n-10000 < n-9999`. Do not sort
103/// `NodeId`s expecting ascending node number; parse the body if you need that.
104///
105/// The trait is provided for `BTreeMap`/`BTreeSet` keys and stable sorts.
106macro_rules! id_newtype {
107 ($(#[$m:meta])* $name:ident) => {
108 $(#[$m])*
109 #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
110 pub struct $name(String);
111
112 impl $name {
113 /// The validated id as a string slice. There is no mutable or
114 /// owned-`String` accessor by design: the inner value can never be
115 /// mutated into an unvalidated state after construction.
116 pub fn as_str(&self) -> &str {
117 &self.0
118 }
119 }
120
121 impl std::str::FromStr for $name {
122 type Err = IdValidationError;
123
124 /// Parse via the newtype's own `parse_str`; lets callers use the
125 /// `str::parse` / `FromStr` ecosystem (`s.parse::<RunId>()?`).
126 fn from_str(s: &str) -> Result<Self, Self::Err> {
127 Self::parse_str(s)
128 }
129 }
130
131 impl std::fmt::Display for $name {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 f.write_str(&self.0)
134 }
135 }
136
137 impl std::fmt::Debug for $name {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 write!(f, "{}({:?})", stringify!($name), self.0)
140 }
141 }
142
143 impl serde::Serialize for $name {
144 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
145 s.serialize_str(&self.0)
146 }
147 }
148
149 impl<'de> serde::Deserialize<'de> for $name {
150 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
151 let s = String::deserialize(d)?;
152 Self::parse_str(&s).map_err(serde::de::Error::custom)
153 }
154 }
155 };
156}
157
158id_newtype! {
159 /// A validated run identifier: a lowercase ULID (26 Crockford base32
160 /// characters whose first character keeps the encoded timestamp within
161 /// ULID's 48-bit range). Mirrors what [`crate::new_run_id`] emits.
162 RunId
163}
164
165impl RunId {
166 /// Accepted-shape hint shared by every rejection.
167 const EXPECTED: &'static str = "26-char lowercase Crockford base32 ULID";
168 /// Canonical length of a ULID in Crockford base32. Public so CLI-side prefix
169 /// resolution can branch on "full id vs. prefix" without mirroring the
170 /// constant (which would silently drift if the id shape ever changed).
171 pub const LEN: usize = 26;
172
173 /// Parse and validate a `run_id`. Accepts only the 26-character lowercase
174 /// ULID shape; rejects wrong length, non-Crockford characters, and a first
175 /// character outside `0..=7` (which would overflow ULID's 48-bit timestamp).
176 pub fn parse_str(s: &str) -> Result<Self, IdValidationError> {
177 let reject = || IdValidationError::InvalidFormat {
178 kind: "run",
179 value: s.to_string(),
180 expected: Self::EXPECTED,
181 };
182 if s.len() != Self::LEN || !all_crockford_lower(s) {
183 return Err(reject());
184 }
185 // The first base32 char carries the top 5 bits of the 128-bit ULID;
186 // the 48-bit timestamp cannot overflow only if it is in `0..=7`.
187 if !(b'0'..=b'7').contains(&s.as_bytes()[0]) {
188 return Err(reject());
189 }
190 Ok(Self(s.to_string()))
191 }
192}
193
194id_newtype! {
195 /// A validated node identifier: `n-` followed by 4 or more ASCII digits
196 /// (e.g. `n-0001`). Mirrors what [`crate::format_node_id`] emits.
197 NodeId
198}
199
200impl NodeId {
201 /// Accepted-shape hint shared by every rejection.
202 const EXPECTED: &'static str = "n-NNNN (n- followed by 4-10 ASCII digits)";
203
204 /// Parse and validate a `node_id`. Requires the `n-` prefix followed by
205 /// 4 to 10 ASCII digits; rejects anything else (wrong prefix, too few or
206 /// too many digits, non-digit body). The 10-digit ceiling covers the full
207 /// `u32` counter range [`crate::format_node_id`] draws from while bounding
208 /// the filename length (a defense against `ENAMETOOLONG` from a forged id).
209 pub fn parse_str(s: &str) -> Result<Self, IdValidationError> {
210 let body = s.strip_prefix("n-").ok_or(IdValidationError::WrongPrefix {
211 kind: "node",
212 expected: Self::EXPECTED,
213 })?;
214 if (4..=10).contains(&body.len()) && body.bytes().all(|b| b.is_ascii_digit()) {
215 Ok(Self(s.to_string()))
216 } else {
217 Err(IdValidationError::InvalidFormat {
218 kind: "node",
219 value: s.to_string(),
220 expected: Self::EXPECTED,
221 })
222 }
223 }
224}
225
226/// The run/node kind enum (design.md §1.2).
227///
228/// The 0.2 subtractive cut removed the `code`, `orchestrate`, `orchestrated`,
229/// `bugfix`, and `make-skill` kinds (the interactive + DAG-driver topologies and
230/// the two phantom variants that were behaviourally `Spinoff`). The surviving
231/// kinds are all autonomous. [`Kind::Unknown`] is a read-only catch-all so a
232/// legacy on-disk run recorded under a since-removed kind still deserializes —
233/// `doctor` / `run list` report it, never delete it (ADR §D7).
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
235#[serde(rename_all = "kebab-case")]
236pub enum Kind {
237 /// Autonomous fire-and-forget task that merges itself back (`/worktree-spinoff`).
238 Spinoff,
239 /// Autonomous multi-source research worktree (`/worktree-research`).
240 Research,
241 /// Drives one architectural decision to an ADR (`/worktree-technical-decision`).
242 TechnicalDecision,
243 /// Parallel fan-out of many identical units (`/fan-out`).
244 FanOut,
245 /// A kind this build no longer models — a legacy run recorded on disk under a
246 /// kind removed in the 0.2 cut (`code` / `orchestrate` / `orchestrated` /
247 /// `bugfix` / `make-skill`), or any future/unknown wire value. Read-only:
248 /// `#[serde(other)]` maps every unrecognized kind here so `doctor` / `run
249 /// list` can still surface such a run rather than faulting on it (ADR §D7).
250 /// It is NEVER a creatable kind — it is absent from [`Kind::WIRE_NAMES`], so
251 /// no CLI surface or report validator accepts it as input.
252 #[serde(other)]
253 Unknown,
254}
255
256impl Kind {
257 /// The kebab-case wire name for this kind — the same string serde
258 /// (de)serializes via `rename_all = "kebab-case"`.
259 ///
260 /// The exhaustive `match` is deliberate: adding a `Kind` variant fails
261 /// to compile until its wire name is listed here, so [`Kind::WIRE_NAMES`]
262 /// and any caller that advertises the accepted kinds (e.g. the report
263 /// validator's `expected` hint) cannot silently drift from the enum.
264 #[must_use]
265 pub const fn wire_name(self) -> &'static str {
266 match self {
267 Kind::Spinoff => "spinoff",
268 Kind::Research => "research",
269 Kind::TechnicalDecision => "technical-decision",
270 Kind::FanOut => "fan-out",
271 Kind::Unknown => "unknown",
272 }
273 }
274
275 /// Every *creatable* kind's kebab-case wire name, in declaration order.
276 /// Single source of truth for "the set of accepted kinds" — see
277 /// [`Kind::wire_name`]. Excludes [`Kind::Unknown`], which is a read-only
278 /// catch-all, never a valid input.
279 pub const WIRE_NAMES: &'static [&'static str] = &[
280 Kind::Spinoff.wire_name(),
281 Kind::Research.wire_name(),
282 Kind::TechnicalDecision.wire_name(),
283 Kind::FanOut.wire_name(),
284 ];
285
286 /// Default how-run [`Lifecycle`] for a kind — the value a run gets when
287 /// created WITHOUT `--interactive`. Every kind defaults to autonomous; the 0.2
288 /// cut removed the `code` kind that used to imply interactivity, so
289 /// interactivity is no longer kind-derived — it is the explicit `--interactive`
290 /// flag ([`Lifecycle`] docs, design.md §2/§6). This method only seeds the
291 /// default; it must NOT be read as "this kind is (non-)interactive".
292 /// [`Kind::Unknown`] (a legacy on-disk run) reads as autonomous too; it is
293 /// never freshly supervised, so the value only ever feeds read-only display.
294 pub fn lifecycle(self) -> Lifecycle {
295 match self {
296 Kind::Spinoff
297 | Kind::Research
298 | Kind::TechnicalDecision
299 | Kind::FanOut
300 | Kind::Unknown => Lifecycle::Autonomous,
301 }
302 }
303
304 /// Whether this kind is a **top-level, single-node, autonomous worker** —
305 /// one detached agent that materializes its own worktree and self-merges,
306 /// with no children and no parent DAG driving it. These are exactly the
307 /// kinds eligible for the supervisor's bounded auto-retry on an empty-handed
308 /// `agent-died` (issue `autoretry-agent-died-worker`).
309 ///
310 /// Excludes `FanOut` (a multi-unit driver — its driver node has no agent of
311 /// its own) and [`Kind::Unknown`] (a legacy on-disk run, never freshly
312 /// supervised).
313 ///
314 /// The exhaustive `match` fails to compile when a new `Kind` is added, forcing
315 /// a deliberate eligibility decision rather than a silent default.
316 #[must_use]
317 pub fn is_autonomous_single_node_worker(self) -> bool {
318 match self {
319 Kind::Spinoff | Kind::Research | Kind::TechnicalDecision => true,
320 Kind::FanOut | Kind::Unknown => false,
321 }
322 }
323}
324
325/// How a run is driven — its **how-run** state (design.md §2, §6).
326///
327/// This is an **explicit told fact**, set once at `run create` from the
328/// `--interactive` flag and never transitioned. It is deliberately NOT derived
329/// from [`Kind`]: the 0.2 cut removed the `code` kind that used to carry
330/// interactivity accidentally, and interactivity is now orthogonal to topology —
331/// *any* run can be marked interactive (`told, not guessed`, `target-state-0.2.md
332/// §2`/§4). Do not reintroduce a `Kind`-derived inference; `Kind::lifecycle`
333/// exists only to seed the default for a run created without the flag.
334///
335/// `Lifecycle` is a *category*, not a progress signal — an agent tracking
336/// completion polls `manifest.status` (`Pending | Running | Done | Failed |
337/// Cancelled`), NEVER `lifecycle`, whose value never changes (state-integrity
338/// invariant 4).
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
340#[serde(rename_all = "kebab-case")]
341pub enum Lifecycle {
342 /// Agent runs to completion unattended; the supervisor adjudicates exit
343 /// (the told `worker.exited` fact, then the residual crash backstop).
344 Autonomous,
345 /// Human-driven: the supervisor **never** auto-terminalizes or auto-tears-down
346 /// from a dead pid or a worker exit — it waits for an explicit `run merge`
347 /// (→ teardown) or `run cancel`. The human owns the whole lifecycle
348 /// (design.md §6).
349 Interactive,
350}
351
352impl Lifecycle {
353 /// True for [`Lifecycle::Interactive`] — the human-driven, supervisor-hands-off
354 /// how-run state. The single predicate the supervisor consults to suppress its
355 /// automatic terminalization/teardown machinery (design.md §6).
356 #[must_use]
357 pub fn is_interactive(self) -> bool {
358 matches!(self, Lifecycle::Interactive)
359 }
360}
361
362/// Who launches and owns the agent. This is independent of lifecycle: an
363/// interactive Taskfleet worker is still a Taskfleet-owned worker.
364#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
365#[serde(rename_all = "kebab-case")]
366pub enum AgentOwner {
367 #[default]
368 /// Taskfleet launches and supervises its own worker.
369 Taskfleet,
370 /// An external process owns the agent; Taskfleet owns only the Git run.
371 Caller,
372}
373
374impl AgentOwner {
375 /// Keep the historical projection shape byte-compatible for normal runs.
376 /// Serde's `skip_serializing_if` passes a reference even for `Copy` types.
377 #[allow(clippy::trivially_copy_pass_by_ref)]
378 pub fn is_taskfleet(&self) -> bool {
379 *self == Self::Taskfleet
380 }
381}
382
383/// Run/node status (design.md §1.2).
384///
385/// `Done`, `Failed`, and `Cancelled` are **terminal**: once a run or node
386/// reaches one of them its `status` must never change again. The reducer
387/// enforces this — `apply_run_status`, `apply_node_status`, and
388/// `apply_node_report` are all no-ops once [`Status::is_terminal`] holds — so
389/// a late-arriving event (e.g. an agent success report racing a `run cancel`)
390/// cannot resurrect a settled state. Only the `status` field is frozen;
391/// other projection fields may still be mutated by non-status events.
392#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
393#[serde(rename_all = "kebab-case")]
394pub enum Status {
395 /// Created but not yet started.
396 Pending,
397 /// Actively executing.
398 Running,
399 /// Stalled awaiting input (e.g. an open discussion).
400 Blocked,
401 /// Completed successfully (terminal).
402 Done,
403 /// Completed with failure (terminal).
404 Failed,
405 /// Terminated before completion by an operator or parent (terminal).
406 Cancelled,
407}
408
409impl Status {
410 /// True for the terminal states `Done | Failed | Cancelled`. A run or
411 /// node in a terminal state is settled: the reducer treats any further
412 /// *status* transition as a no-op. "Settled" applies to `status` only —
413 /// non-status projection fields (e.g. `Node::children` via
414 /// `child.spawned`, or manifest counters) can still change.
415 pub fn is_terminal(self) -> bool {
416 matches!(self, Status::Done | Status::Failed | Status::Cancelled)
417 }
418}
419
420/// Aggregate a set of node statuses into the run's rolled-up terminal status,
421/// or `None` when the run is not yet complete.
422///
423/// The single, shared roll-up rule — used both by the supervisor's per-tick
424/// `rollup_status` and by [`cancel_node`](crate::cancel_node)'s in-lock
425/// self-roll-up (so the two can never diverge). A **three-way** classification
426/// (design §2.5, "rollup terminalizes the run cancelled/done/failed once every
427/// node is terminal"):
428///
429/// - `None` if the set is empty (a freshly-created run must not vacuously
430/// complete) or if ANY node is still live (`Pending`/`Running`/`Blocked`);
431/// - `Some(Status::Failed)` if any node genuinely `Failed` (a real failure
432/// dominates the batch outcome);
433/// - `Some(Status::Cancelled)` if no node failed but at least one was
434/// `Cancelled` (a deliberate per-node/whole-run cancel — nothing failed, but
435/// the batch did not fully complete; branch-preserving work is untouched);
436/// - `Some(Status::Done)` when every node is `Done`.
437pub fn aggregate_terminal_status<I>(statuses: I) -> Option<Status>
438where
439 I: IntoIterator<Item = Status>,
440{
441 let mut any = false;
442 let mut any_failed = false;
443 let mut any_cancelled = false;
444 for s in statuses {
445 any = true;
446 match s {
447 Status::Done => {}
448 Status::Failed => any_failed = true,
449 Status::Cancelled => any_cancelled = true,
450 // Any live node means the run is not done yet.
451 Status::Pending | Status::Running | Status::Blocked => return None,
452 }
453 }
454 if !any {
455 return None;
456 }
457 Some(if any_failed {
458 Status::Failed
459 } else if any_cancelled {
460 Status::Cancelled
461 } else {
462 Status::Done
463 })
464}
465
466/// Compact profile resolution recorded at create time.
467#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
468pub struct AgentSelection {
469 /// Compact selection schema version (currently 1).
470 pub schema_version: u32,
471 /// Requested and selected user profile name.
472 pub profile: String,
473 /// Precedence layer that supplied the request.
474 pub selection_source: String,
475 /// Explicit create-time interaction mode.
476 pub interaction: String,
477 /// Declared profile capability tier.
478 pub capability: String,
479 /// Declared profile residency class.
480 pub residency: String,
481 /// Legacy harness alias requested at the winning layer, when applicable.
482 #[serde(default, skip_serializing_if = "Option::is_none")]
483 pub requested_harness: Option<String>,
484 /// First statically eligible candidate.
485 pub selected: SelectedAgentCandidate,
486 /// Earlier candidates and their single deterministic skip reasons.
487 #[serde(default)]
488 pub fallback: Vec<SkippedAgentCandidate>,
489}
490
491/// Exact selected candidate pinned for launch and retry.
492#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
493pub struct SelectedAgentCandidate {
494 /// Zero-based position in the profile's ordered candidate list.
495 pub candidate_index: u8,
496 /// Selected harness (`pi` or `claude`).
497 pub harness: String,
498 /// Exact user-owned argv; never a shell string.
499 pub command: Vec<String>,
500 /// Declared telemetry adapter protocol, when configured.
501 #[serde(default, skip_serializing_if = "Option::is_none")]
502 pub telemetry: Option<String>,
503}
504
505impl SelectedAgentCandidate {
506 /// Whether recorded policy configures the public worker telemetry v1
507 /// adapter. This is configuration support, not runtime attestation or a
508 /// claim that any sample has arrived.
509 #[must_use]
510 pub fn supports_worker_telemetry_v1(&self) -> bool {
511 self.harness == "pi" && self.telemetry.as_deref() == Some("worker-v1")
512 }
513}
514
515/// One rejected candidate and its first applicable reason.
516#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
517pub struct SkippedAgentCandidate {
518 /// Zero-based position in the profile's ordered candidate list.
519 pub candidate_index: u8,
520 /// Candidate harness.
521 pub harness: String,
522 /// Stable skip reason code.
523 pub reason: String,
524}
525
526impl AgentSelection {
527 /// Validate semantic bounds and closed vocabularies at the durable event
528 /// boundary, independently of the user-config parser that constructed it.
529 pub fn validate(&self) -> Result<(), String> {
530 if self.schema_version != 1 {
531 return Err(format!(
532 "unsupported selection schema_version {}",
533 self.schema_version
534 ));
535 }
536 let name = self.profile.as_bytes();
537 if name.is_empty()
538 || name.len() > 63
539 || !name[0].is_ascii_lowercase()
540 || !name
541 .iter()
542 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
543 || self.profile.ends_with('-')
544 || self.profile.contains("--")
545 {
546 return Err("invalid profile name".into());
547 }
548 if !matches!(
549 self.selection_source.as_str(),
550 "cli"
551 | "environment"
552 | "repository-per-kind"
553 | "user-per-kind"
554 | "repository-default"
555 | "user-default"
556 | "builtin-harness"
557 ) {
558 return Err("invalid selection_source".into());
559 }
560 if !matches!(
561 self.interaction.as_str(),
562 "autonomous" | "explicit-interactive"
563 ) || !matches!(
564 self.capability.as_str(),
565 "fast" | "capable" | "ultra-capable"
566 ) || !matches!(self.residency.as_str(), "local" | "remote")
567 {
568 return Err("invalid interaction, capability, or residency".into());
569 }
570 validate_selected_candidate(&self.selected)?;
571 if self.interaction == "autonomous"
572 && !((self.selected.harness == "pi"
573 && self.selected.telemetry.as_deref() == Some("worker-v1"))
574 || (self.selected.harness == "claude" && self.selected.telemetry.is_none()))
575 {
576 return Err(
577 "autonomous selection requires pi/worker-v1 or claude without telemetry".into(),
578 );
579 }
580 if self.selected.candidate_index >= 8
581 || self.fallback.len() != usize::from(self.selected.candidate_index)
582 {
583 return Err("candidate index/count exceeds profile bound".into());
584 }
585 let mut prior = None;
586 for (expected_index, skipped) in self.fallback.iter().enumerate() {
587 if usize::from(skipped.candidate_index) != expected_index
588 || prior.is_some_and(|value| skipped.candidate_index <= value)
589 || !matches!(skipped.harness.as_str(), "pi" | "claude")
590 || !matches!(
591 skipped.reason.as_str(),
592 "executable_missing"
593 | "autonomous_harness_unsupported"
594 | "telemetry_unsupported"
595 )
596 {
597 return Err("invalid fallback candidate index, harness, or reason".into());
598 }
599 if skipped.reason == "autonomous_harness_unsupported"
600 && (self.interaction != "autonomous" || skipped.harness == "pi")
601 {
602 return Err("inconsistent autonomous harness skip reason".into());
603 }
604 if skipped.reason == "telemetry_unsupported"
605 && (self.interaction != "autonomous" || skipped.harness != "pi")
606 {
607 return Err("inconsistent telemetry skip reason".into());
608 }
609 prior = Some(skipped.candidate_index);
610 }
611 Ok(())
612 }
613}
614
615fn validate_selected_candidate(candidate: &SelectedAgentCandidate) -> Result<(), String> {
616 if !matches!(candidate.harness.as_str(), "pi" | "claude")
617 || candidate.command.is_empty()
618 || candidate.command.len() > 32
619 || candidate
620 .command
621 .iter()
622 .any(|arg| arg.is_empty() || arg.len() > 4096 || arg.contains('\0'))
623 || candidate.command.iter().map(String::len).sum::<usize>() > 16_384
624 {
625 return Err("invalid selected harness or command".into());
626 }
627 match (candidate.harness.as_str(), candidate.telemetry.as_deref()) {
628 (_, None) | ("pi", Some("worker-v1")) => Ok(()),
629 _ => Err("invalid selected telemetry declaration".into()),
630 }
631}
632
633/// `manifest.json` (design.md §1.2).
634#[derive(Debug, Clone, Serialize, Deserialize)]
635pub struct Manifest {
636 /// State-schema version this file was written with.
637 pub schema_version: u32,
638 /// Watermark: the highest event `seq` whose projection fold is durably
639 /// committed. Events in `events.jsonl` with `seq > applied_seq` are
640 /// *unapplied tail* events — replayed into the projections on the next
641 /// lock acquisition before any new append (see
642 /// [`crate::events::append_and_apply_event`]). This is what makes
643 /// append-then-apply atomic across a reducer crash: the event log can run
644 /// ahead of the projections, but the gap is always healed before the next
645 /// writer observes stale state.
646 ///
647 /// `#[serde(default)]` so a legacy `manifest.json` written before this
648 /// field existed deserializes with `applied_seq = 0`. Such a manifest
649 /// self-migrates on its next write: the catch-up replay re-folds the whole
650 /// log — every event a no-op, because legacy state was already projected
651 /// synchronously under the old append-then-apply path — and advances the
652 /// watermark to `last_seq`. No separate migration pass or schema bump is
653 /// required (the field is purely additive to a derived-cache file).
654 #[serde(default)]
655 pub applied_seq: u64,
656 /// Unique run identifier (ULID). Validated on read.
657 pub run_id: RunId,
658 /// Kind of work this run performs.
659 pub kind: Kind,
660 /// How-run state (autonomous vs interactive), set once at `run create` from
661 /// the explicit `--interactive` flag — never transitioned. See [`Lifecycle`].
662 pub lifecycle: Lifecycle,
663 /// Absent on historic projections, which always launched Taskfleet workers.
664 #[serde(default, skip_serializing_if = "AgentOwner::is_taskfleet")]
665 pub agent_owner: AgentOwner,
666 /// Caller settlement admission fence; absent for historic/ordinary runs.
667 #[serde(default, skip_serializing_if = "Option::is_none")]
668 pub caller_settlement_intent: Option<CallerSettlementIntent>,
669 /// Human-readable run title.
670 pub title: String,
671 /// Current aggregate run status.
672 pub status: Status,
673 /// When the run was created.
674 pub created_at: Timestamp,
675 /// When the manifest was last modified.
676 pub updated_at: Timestamp,
677 /// Source repository the run operates on, if any.
678 pub source_repo: Option<String>,
679 /// Branch the run was started from, if any.
680 pub source_branch: Option<String>,
681 /// Root directory under which this run's worktrees live, if any.
682 pub worktree_root: Option<String>,
683 /// tmux session taskfleet created to host this run's headless windows
684 /// (`--headless` / `--tmux-session <name>`), if any. `None` for a foreground
685 /// run whose window lives in the user's own session — that session is never
686 /// a teardown target. When set, the supervisor kills this session once its
687 /// last taskfleet-owned window is torn down and only the synthetic
688 /// bootstrap shell window remains, so an empty headless session is not left
689 /// behind (issue `headless-tmux-session-not-torn-down`). `#[serde(default)]`
690 /// keeps a manifest written before this field existed readable.
691 #[serde(default)]
692 pub managed_tmux_session: Option<String>,
693 /// Create-time terminal-window retention policy. `None` preserves the
694 /// historical immediate-window/session cleanup behavior. The policy is
695 /// recorded so supervisors and timer maintenance never reinterpret a run
696 /// through later config drift.
697 #[serde(default, skip_serializing_if = "Option::is_none")]
698 pub tmux_retention: Option<Box<TmuxRetentionPolicy>>,
699 /// Completion-notification command registered at `run create --notify`,
700 /// if any. When the run reaches a terminal state (`done | failed |
701 /// cancelled`) the supervisor runs this command (at-least-once, deduped on a
702 /// durable `run.notified` marker event — the healthy path fires once, a
703 /// crash between firing and recording may re-fire) with `TASKFLEET_RUN_ID` /
704 /// `TASKFLEET_STATUS` / `TASKFLEET_SUMMARY` (and `TASKFLEET_RUN_KIND` / `TASKFLEET_RUN_TITLE`)
705 /// in its environment, BEFORE teardown removes the worktree/window. This is
706 /// how a spawning session learns of completion without polling (issue
707 /// `no-completion-notification-to-parent`). `None` for a run created without
708 /// `--notify`; `#[serde(default)]` keeps a manifest written before this
709 /// field existed readable.
710 #[serde(default)]
711 pub notify_cmd: Option<String>,
712 /// The agent runtime selected for this run's worker
713 /// (`claude` | `pi`), resolved at `run create`
714 /// via the flag > env > config > default precedence and recorded here as
715 /// provenance. This is the *selected* harness — recorded before the worker is
716 /// spawned, so it reflects intent even if the spawn later fails. `None` for a
717 /// manifest written before this field existed
718 /// (`#[serde(default)]`) — such legacy runs predate harness selection and
719 /// were all `claude`. Surfaced on `run show` / `run list --json`.
720 #[serde(default)]
721 pub harness: Option<String>,
722 /// Compact create-time profile resolution. `None` keeps manifests written
723 /// before profile selection readable without inventing requested/selected
724 /// history. Retry and read paths consume this recorded value; they never
725 /// re-resolve current configuration.
726 #[serde(default)]
727 pub agent_selection: Option<AgentSelection>,
728 /// Number of nodes created in this run (denormalized counter).
729 pub node_count: u32,
730 /// Exact owner of the worktree from which this run was created, if any.
731 /// Attribution only: unlike `parent_run_id`, this does not join the
732 /// fan-out DAG or delegate supervision. Absent on older manifests.
733 #[serde(default)]
734 pub created_by_run_id: Option<RunId>,
735 /// Optional immutable native-session display association. Absent on old runs.
736 #[serde(default)]
737 pub created_by_session: Option<CreatorSession>,
738 /// Run that spawned this run, if it is itself a child.
739 pub parent_run_id: Option<RunId>,
740 /// Node in the parent run that spawned this run, if any.
741 pub parent_node_id: Option<NodeId>,
742 /// Named resident policy (`run create --resident --name`, ADR 0003). A
743 /// told create-time fact, never transitioned; absent for ordinary runs.
744 #[serde(default, skip_serializing_if = "Option::is_none")]
745 pub resident: Option<ResidentPolicy>,
746 /// `run create --no-parent`: the creator declared that no parent agent or
747 /// person answers this run's questions or pushes its landing. A told
748 /// create-time fact, never inferred from absent parent or creator ids (a
749 /// conductor that answers may record none of them). Advisory: losing it
750 /// only makes `node ask` wait out its timeout again.
751 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
752 pub no_parent: bool,
753}
754
755/// Create-time policy of a named resident run (ADR 0003): a worker that works
756/// in told rounds and is resumed from its native session by the next message.
757#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
758pub struct ResidentPolicy {
759 /// Name scoped by repository and creator session (`created_by_session`);
760 /// resolves only among live runs of the same repository, the caller's own
761 /// session first. Starts with a lowercase letter, so it is never a run-id
762 /// prefix.
763 pub name: String,
764 /// Seconds after the open round report (worker exited) before idle expiry.
765 pub idle_expiry_secs: u64,
766}
767
768impl ResidentPolicy {
769 /// Longest accepted resident name.
770 pub const MAX_NAME_LEN: usize = 48;
771
772 /// Validate a resident name: `[a-z][a-z0-9-]*`, at most
773 /// [`Self::MAX_NAME_LEN`] bytes, no trailing or doubled hyphen. The leading
774 /// letter keeps names disjoint from run-id prefixes (which start `0`-`7`).
775 pub fn validate_name(name: &str) -> Result<(), String> {
776 let b = name.as_bytes();
777 if b.is_empty()
778 || b.len() > Self::MAX_NAME_LEN
779 || !b[0].is_ascii_lowercase()
780 || !b
781 .iter()
782 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
783 || name.ends_with('-')
784 || name.contains("--")
785 {
786 return Err(format!(
787 "resident name must match [a-z][a-z0-9-]* (at most {} bytes, no trailing or doubled hyphen)",
788 Self::MAX_NAME_LEN
789 ));
790 }
791 Ok(())
792 }
793}
794
795/// One told round report of a resident worker (`node.round_reported`).
796#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
797pub struct RoundReport {
798 /// 1-based round number.
799 pub round: u32,
800 /// Worker attempt that reported it.
801 pub attempt: u32,
802 /// Envelope timestamp of the report (the idle-expiry anchor).
803 pub reported_at: Timestamp,
804 /// Event sequence of the report.
805 pub event_seq: u64,
806 /// Worker-written summary of the round (bounded). For an interrupted round
807 /// it is Taskfleet's note until the worker's own report amends it.
808 pub summary: String,
809 /// The parent stopped this round with `run interrupt` (the worker did not
810 /// end it itself). Sticky for the round: a worker report that races the
811 /// interrupt amends the summary, but the round stays interrupted.
812 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
813 pub interrupted: bool,
814 /// Set when the next message resumed the worker.
815 #[serde(default, skip_serializing_if = "Option::is_none")]
816 pub closed_at: Option<Timestamp>,
817 /// Message id that closed the round.
818 #[serde(default, skip_serializing_if = "Option::is_none")]
819 pub closed_by: Option<String>,
820}
821
822/// A round landed into the source branch by `run land` (`node.round_landed`).
823#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
824pub struct RoundLanding {
825 /// When the landing was recorded.
826 pub at: Timestamp,
827 /// Source branch that was fast-forwarded.
828 pub source_branch: String,
829 /// The integrated tip now at the source branch.
830 pub integrated_oid: String,
831 /// Round number open (or last reported) when the land happened.
832 pub round: u32,
833}
834
835/// Durable round state of a resident worker node (ADR 0003). Folded only from
836/// told events; the read surfaces derive `working | waiting | dormant` from it.
837#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
838pub struct ResidentState {
839 /// Rounds reported so far.
840 pub rounds_reported: u32,
841 /// The latest round report, open until a message resumes the worker.
842 #[serde(default, skip_serializing_if = "Option::is_none")]
843 pub last_round: Option<RoundReport>,
844 /// The latest landing.
845 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub last_landing: Option<RoundLanding>,
847 /// Set when idle expiry removed the worktree of a wholly landed round.
848 #[serde(default, skip_serializing_if = "Option::is_none")]
849 pub dormant_since: Option<Timestamp>,
850 /// Set when idle expiry found unlanded work and raised attention.
851 #[serde(default, skip_serializing_if = "Option::is_none")]
852 pub expiry_attention_at: Option<Timestamp>,
853}
854
855impl ResidentState {
856 /// The open round report, if the worker is between rounds.
857 #[must_use]
858 pub fn open_round(&self) -> Option<&RoundReport> {
859 self.last_round.as_ref().filter(|r| r.closed_at.is_none())
860 }
861}
862
863/// Immutable same-user display attribution, never ownership or authorization.
864/// Currently only Pi sessions with canonical lowercase hyphenated UUIDs are accepted.
865#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
866#[serde(try_from = "CreatorSessionInput")]
867pub struct CreatorSession {
868 /// Native harness name (`pi`).
869 pub harness: String,
870 /// Canonical lowercase hyphenated UUID, preserved without normalization.
871 pub session_id: String,
872}
873
874#[derive(Deserialize)]
875#[serde(deny_unknown_fields)]
876struct CreatorSessionInput {
877 harness: String,
878 session_id: String,
879}
880
881impl CreatorSession {
882 /// Parse the public `pi:<session-uuid>` attribution input strictly.
883 /// No whitespace trimming, case folding, or alternate UUID spellings.
884 pub fn parse_str(value: &str) -> Result<Self, String> {
885 let (harness, session_id) = value
886 .split_once(':')
887 .ok_or_else(|| "expected pi:<lowercase hyphenated session UUID>".to_string())?;
888 Self::try_from(CreatorSessionInput {
889 harness: harness.into(),
890 session_id: session_id.into(),
891 })
892 }
893}
894
895impl TryFrom<CreatorSessionInput> for CreatorSession {
896 type Error = String;
897
898 fn try_from(input: CreatorSessionInput) -> Result<Self, Self::Error> {
899 let id = &input.session_id;
900 let uuid_shape = id.len() == 36
901 && id.bytes().enumerate().all(|(i, b)| {
902 if matches!(i, 8 | 13 | 18 | 23) {
903 b == b'-'
904 } else {
905 b.is_ascii_digit() || matches!(b, b'a'..=b'f')
906 }
907 });
908 if input.harness != "pi" || !uuid_shape {
909 return Err("expected pi:<lowercase hyphenated session UUID>".into());
910 }
911 Ok(Self {
912 harness: input.harness,
913 session_id: input.session_id,
914 })
915 }
916}
917
918/// `(child_run_id, child_node_id)` pointer recorded in `Node::children`.
919#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
920pub struct ChildRef {
921 /// Run id of the spawned child. Validated on read.
922 pub run_id: RunId,
923 /// Node id within the child run. Validated on read.
924 pub node_id: NodeId,
925}
926
927/// State of durable native worker evidence capture.
928#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
929#[serde(rename_all = "snake_case")]
930pub enum EvidenceStatus {
931 /// Capture has not completed yet.
932 Pending,
933 /// The latest capture attempt failed and cleanup remains vetoed.
934 Failed,
935 /// Every durable artifact was synced and recorded.
936 Complete,
937}
938
939impl std::fmt::Display for EvidenceStatus {
940 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
941 f.write_str(match self {
942 Self::Pending => "pending",
943 Self::Failed => "failed",
944 Self::Complete => "complete",
945 })
946 }
947}
948
949/// Durable native Pi session and terminal evidence for one worker attempt.
950///
951/// This is folded onto the node projection from append-only events. The live
952/// source is state-root-relative; completed artifact paths are run-relative.
953#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
954pub struct WorkerEvidence {
955 /// Worker attempt this evidence belongs to.
956 pub attempt: u32,
957 /// Exact Pi session identifier assigned before the candidate starts.
958 pub session_id: String,
959 /// Original cwd stored in the native transcript header.
960 pub original_cwd: String,
961 /// State-root-relative live native transcript path.
962 pub live_session_path: String,
963 /// Typed capture state.
964 pub status: EvidenceStatus,
965 /// Run-relative byte-identical archived transcript, once complete.
966 #[serde(default, skip_serializing_if = "Option::is_none")]
967 pub transcript_path: Option<String>,
968 /// Run-relative resume copy whose header names a surviving cwd.
969 #[serde(default, skip_serializing_if = "Option::is_none")]
970 pub resume_path: Option<String>,
971 /// Run-relative final tmux pane snapshot.
972 #[serde(default, skip_serializing_if = "Option::is_none")]
973 pub pane_path: Option<String>,
974 /// Run-relative exact terminal report JSON.
975 #[serde(default, skip_serializing_if = "Option::is_none")]
976 pub report_path: Option<String>,
977 /// SHA-256 of the archived original transcript.
978 #[serde(default, skip_serializing_if = "Option::is_none")]
979 pub transcript_sha256: Option<String>,
980 /// Explicit capture failure detail. Never present on complete evidence.
981 #[serde(default, skip_serializing_if = "Option::is_none")]
982 pub error: Option<String>,
983}
984
985/// Opt-in policy recorded on a run placed in a persistent tmux session.
986#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
987pub struct TmuxRetentionPolicy {
988 /// Keep the selected session after the last worker completes.
989 pub persistent: bool,
990 /// Maximum age of a completed inert display.
991 pub completed_window_ttl_secs: u64,
992 /// Maximum completed inert displays retained in this session.
993 pub completed_window_max: u32,
994}
995
996/// Durable identity of one inert completed-worker display.
997#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
998pub struct RetainedDisplay {
999 /// Worker attempt represented by this display.
1000 pub attempt: u32,
1001 /// Exact socket path observed at worker spawn.
1002 pub socket: String,
1003 /// Exact session name observed at worker spawn.
1004 pub session: String,
1005 /// Window created for the inert display.
1006 pub window_id: String,
1007 /// Its sole dead pane.
1008 pub pane_id: String,
1009 /// tmux server PID observed at worker spawn and retention creation.
1010 pub server_pid: u32,
1011 /// Unix-second start time of `server_pid`. It drifts with wall-clock steps
1012 /// on Linux, so it guards PID/socket reuse only for a display recorded
1013 /// without `server_pid_start_identity`.
1014 pub server_pid_start_secs: u64,
1015 /// Kernel start identity of `server_pid` (`linux:<starttime ticks>` or
1016 /// `macos:<sec>:<usec>`), compared exactly to guard PID/socket reuse.
1017 #[serde(default, skip_serializing_if = "Option::is_none")]
1018 pub server_pid_start_identity: Option<String>,
1019 /// Runtime-owned server marker observed at spawn (empty when unset).
1020 pub server_marker: String,
1021 /// Exact Taskfleet ownership marker stored as a tmux window option.
1022 pub ownership_marker: String,
1023 /// Time the terminal display became durable.
1024 pub retained_at: Timestamp,
1025 /// Policy-derived expiry time.
1026 pub expires_at: Timestamp,
1027 /// Set after maintenance removed the exact owned display. Durable archives
1028 /// and run events are intentionally untouched.
1029 #[serde(default, skip_serializing_if = "Option::is_none")]
1030 pub expired_at: Option<Timestamp>,
1031}
1032
1033/// Immutable caller-owned native Pi session identity. This is an association,
1034/// not evidence of writer quiescence, history retention, or settlement authority.
1035#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1036pub struct CallerPiSession {
1037 /// Native Pi UUID.
1038 pub pi_session_id: String,
1039 /// Absolute native session JSONL path (a locator, not a history guarantee).
1040 pub session_path: String,
1041 /// Checkout recorded when binding, immutable after teardown.
1042 pub original_cwd: String,
1043 /// Native file device at registration; catches path replacement on retry.
1044 pub file_dev: u64,
1045 /// Native file inode at registration; append growth is permitted.
1046 pub file_ino: u64,
1047 /// Reserved launch generation, absent for legacy direct bindings.
1048 #[serde(default, skip_serializing_if = "Option::is_none")]
1049 pub generation: Option<u64>,
1050}
1051
1052/// A caller attests a Pi lifecycle transition. This is not a worker exit or
1053/// proof of quiescence: only an external writer-fence protocol can authorize
1054/// settlement. The event log retains every distinct transition.
1055#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1056#[serde(rename_all = "kebab-case")]
1057pub enum CallerPiState {
1058 /// Durable launch attempt, before Pi creates any native file. Never liveness proof.
1059 Reserved,
1060 /// Caller confirmed Start returned successfully; not continuing liveness proof.
1061 Started,
1062 /// Pi launch failed before a writer existed.
1063 LaunchFailed,
1064 /// Caller reaped or otherwise proved the exact Pi stopped.
1065 Exited,
1066 /// Caller cannot prove whether it still controls the writer.
1067 ControlUncertain,
1068}
1069
1070impl CallerPiState {
1071 /// A told nonterminal condition requiring intervention.
1072 pub fn needs_attention(&self) -> bool {
1073 !matches!(self, Self::Reserved | Self::Started)
1074 }
1075}
1076
1077/// Current generation projection of append-only caller Pi lifecycle history.
1078#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1079pub struct CallerPiLifecycle {
1080 /// Monotonically increasing launch-attempt number.
1081 pub generation: u64,
1082 /// Verified bound native Pi UUID.
1083 pub pi_session_id: String,
1084 /// Native history path, unknown until Pi creates and the caller binds it.
1085 #[serde(default, skip_serializing_if = "Option::is_none")]
1086 pub session_path: Option<String>,
1087 /// Last attested state, not a writer fence.
1088 pub state: CallerPiState,
1089 /// Explicit attestation, not an inferred exit status.
1090 pub reason: Option<String>,
1091}
1092
1093/// Sticky caller-owned settlement operation. An intent is not a terminal report.
1094#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1095#[serde(rename_all = "kebab-case")]
1096pub enum SettlementOperation {
1097 /// Integrate branch into source.
1098 Merge,
1099 /// Terminalize without discarding work.
1100 Cancel,
1101 /// Explicitly discard retained work.
1102 Discard,
1103}
1104
1105/// One durable, single-run settlement fence. Never cleared by failed attempts.
1106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1107pub struct CallerSettlementIntent {
1108 /// Exact full run identity.
1109 pub run_id: RunId,
1110 /// Exact node identity.
1111 pub node_id: NodeId,
1112 /// Caller-supplied stable retry key.
1113 pub key: String,
1114 /// Requested action (not permission to perform it).
1115 pub operation: SettlementOperation,
1116 /// Audited initiator.
1117 pub actor: String,
1118 /// Required for discard and cancel; optional for merge.
1119 pub reason: Option<String>,
1120 /// Inode pair of the lifetime writer lock.
1121 pub writer_dev: u64,
1122 /// Writer inode.
1123 pub writer_ino: u64,
1124 /// Inode pair of the launch gate.
1125 pub gate_dev: u64,
1126 /// Gate inode.
1127 pub gate_ino: u64,
1128 /// Current reservation generation; zero means no reservation yet.
1129 pub generation: u64,
1130 /// Event sequence, filled by the reducer.
1131 pub seq: u64,
1132}
1133
1134/// Durable `nodes/<node-id>.json` projection (design.md §1.3).
1135#[derive(Debug, Clone, Serialize, Deserialize)]
1136pub struct Node {
1137 /// State-schema version this file was written with.
1138 pub schema_version: u32,
1139 /// Unique node identifier within its run (e.g. `n-0001`). Validated on
1140 /// read; this is the projection's filename key, so it can never name a
1141 /// path outside `nodes/`.
1142 pub node_id: NodeId,
1143 /// Run this node belongs to. Validated on read.
1144 pub run_id: RunId,
1145 /// Parent node within the same run, if this is a sub-node.
1146 pub parent_node_id: Option<NodeId>,
1147 /// Kind of work this node performs.
1148 pub kind: Kind,
1149 /// Current node status.
1150 pub status: Status,
1151 /// Task description / prompt driving the node, if recorded.
1152 pub task: Option<String>,
1153 /// Filesystem path of the node's git worktree, if created.
1154 pub worktree_path: Option<String>,
1155 /// Git branch the node works on, if any.
1156 pub branch: Option<String>,
1157 /// The commit SHA the node's branch/worktree was forked from at spawn
1158 /// (the branch tip the moment `create.sh` materialized the worktree). It
1159 /// is the fixed reference point that lets the supervisor tell "this branch
1160 /// produced work that merged into source" from "this branch never diverged
1161 /// from its fork point": a branch still at `base_sha` is trivially an
1162 /// ancestor of its source branch but has merged nothing, so it must NOT be
1163 /// reconciled to success or torn down (that would drop a live agent's
1164 /// uncommitted work). Only a branch whose tip has moved past `base_sha`
1165 /// *and* is now an ancestor of the run's `source_branch` is a confirmed
1166 /// merge (issues `false-failed-after-merge` /
1167 /// `supervisor-stuck-pending-after-self-merge`). `#[serde(default)]` keeps a
1168 /// node written before this field existed readable (`None` → the
1169 /// git-reconcile fallback simply does not fire for it).
1170 #[serde(default)]
1171 pub base_sha: Option<String>,
1172 /// tmux window hosting the node's agent, if interactive. This is the
1173 /// human-readable window *name* — not unique across sessions and blind to
1174 /// non-default sockets. Kept for display and as the legacy liveness key;
1175 /// prefer [`Node::tmux_identity`] when present.
1176 pub tmux_window: Option<String>,
1177 /// Fully-qualified tmux identity (`session:window_id` + socket path)
1178 /// captured at spawn time. `None` for nodes registered before create.sh
1179 /// emitted the qualified fields — those fall back to bare-name matching on
1180 /// [`Node::tmux_window`]. New spawns always populate this when create.sh
1181 /// returns it.
1182 #[serde(default)]
1183 pub tmux_identity: Option<Box<TmuxIdentity>>,
1184 /// Native worker evidence, when this attempt uses Pi. Initialized before
1185 /// publication and advanced only by locked evidence events.
1186 #[serde(default, skip_serializing_if = "Option::is_none")]
1187 pub evidence: Option<WorkerEvidence>,
1188 /// Separate from Taskfleet-launched worker evidence; survives checkout removal.
1189 #[serde(default, skip_serializing_if = "Option::is_none")]
1190 pub caller_pi_session: Option<CallerPiSession>,
1191 #[serde(default, skip_serializing_if = "Option::is_none")]
1192 /// Current caller Pi lifecycle projection; absent for ordinary workers.
1193 pub caller_pi_lifecycle: Option<CallerPiLifecycle>,
1194 /// Inert completed-window identity, when this run opted into retention.
1195 #[serde(default, skip_serializing_if = "Option::is_none")]
1196 pub retained_display: Option<Box<RetainedDisplay>>,
1197 /// Permanent reason why a configured terminal display could not exist
1198 /// (for example the recorded tmux server generation was lost).
1199 #[serde(default, skip_serializing_if = "Option::is_none")]
1200 pub retention_unavailable: Option<String>,
1201 /// PID of the running agent process, if live.
1202 pub agent_pid: Option<i32>,
1203 /// Start time of the agent process (wall-clock seconds). Detects PID reuse
1204 /// only for a node recorded without `agent_pid_start_identity`.
1205 pub agent_pid_start_time: Option<Timestamp>,
1206 /// Kernel start identity of the agent process (`linux:<starttime ticks>`
1207 /// or `macos:<sec>:<usec>`), compared exactly to detect PID reuse. Unlike
1208 /// the seconds value it does not move when the wall clock is stepped.
1209 #[serde(default, skip_serializing_if = "Option::is_none")]
1210 pub agent_pid_start_identity: Option<String>,
1211 /// PID of the supervisor watching this node, if live.
1212 pub supervisor_pid: Option<i32>,
1213 /// Children this node has spawned.
1214 #[serde(default)]
1215 pub children: Vec<ChildRef>,
1216 /// When the node started executing, if it has.
1217 pub started_at: Option<Timestamp>,
1218 /// When the node file was last modified.
1219 pub updated_at: Timestamp,
1220 /// The `node.report` payload that drove this node to its terminal status.
1221 /// Set only by the report that actually transitions the node (Done /
1222 /// Failed / Cancelled). Once the node is terminal it is frozen: a late
1223 /// report against an already-settled node is dropped without overwriting
1224 /// this field (see `reducer::apply_node_report`). So for a node cancelled
1225 /// by `run cancel`, this holds the synthesized cancel report, not a
1226 /// later-arriving agent report — that payload remains only in
1227 /// `events.jsonl`.
1228 pub last_report: Option<Value>,
1229 /// Highest report `seq` consumed per child run id, for idempotent
1230 /// report processing across supervisor restarts.
1231 #[serde(default)]
1232 pub last_processed_report_seq_by_child: Map<String, Value>,
1233 /// Number of times the supervisor has auto-retried this node after an
1234 /// empty-handed `agent-died` (issue `autoretry-agent-died-worker`). The
1235 /// DURABLE, restart-safe bound on the bounded-retry loop: each `node.retry`
1236 /// event increments it, and the watchdog terminalizes the run `failed` once
1237 /// it reaches `RETRY_MAX_ATTEMPTS`. `#[serde(default)]` keeps a node written
1238 /// before this field existed readable (`0` — never retried).
1239 #[serde(default)]
1240 pub retry_attempts: u32,
1241 /// The **told** exit status of the node's worker process, recorded durably by
1242 /// the `run-worker` launcher shim (`crates/taskfleet/src/run_worker.rs`) when
1243 /// it `wait()`s on the agent it wrapped. This is a *fact*, not an inference:
1244 /// the supervisor consumes it via the typed outcome table instead of guessing
1245 /// completion from pid/pane/activity proxies (design.md §2.1, issue
1246 /// `thin-exit-status-launcher`). A non-zero code or a terminating signal is a
1247 /// `failed` worker; `code == 0` with no `explicit-merge` transition is the
1248 /// *finished-but-unmerged* case that must stay non-terminal (attention-
1249 /// required), NOT be auto-failed. `None` until the shim records an exit — or
1250 /// forever, for a worker never launched through the shim (the crash backstop
1251 /// still covers that path). `#[serde(default)]` keeps a node written before
1252 /// this field existed readable.
1253 #[serde(default)]
1254 pub worker_exit: Option<WorkerExit>,
1255 /// The in-flight `run merge` transaction for this node, if one has been
1256 /// STARTED but not yet completed. `run merge` records a `merge.started`
1257 /// event (setting this field) BEFORE it mutates git, because the merge spans
1258 /// two durability domains — git refs and the event log — and is not atomic
1259 /// across them (design.md §2.1b / A2, issue `merge-transaction-recovery`). A
1260 /// crash after the git merge but before the terminal `explicit-merge`
1261 /// `node.report` would otherwise strand the work *merged in source* with *no
1262 /// merge event* → a false `failed`.
1263 ///
1264 /// This field is the durable op-log record that lets recovery finish or
1265 /// reject that ONE known transaction deterministically, by OID — never a
1266 /// general branch-content heuristic. It is set by [`crate::MergeTxn`]-carrying
1267 /// `merge.started`, and cleared when the transaction resolves: a terminal
1268 /// `node.report` (the merge completed) or a `merge.aborted` (recovery found
1269 /// the git mutation never landed). `#[serde(default)]` keeps a node written
1270 /// before this field existed readable (`None` — no in-flight merge).
1271 ///
1272 /// Boxed so the (rare) in-flight transaction does not inflate every `Node` /
1273 /// `ProjectionOp` by the full [`MergeTxn`] footprint.
1274 #[serde(default)]
1275 pub pending_merge: Option<Box<MergeTxn>>,
1276 /// The durable, monotonic timestamp of the FIRST tick on which the supervisor
1277 /// observed this node's worker process confirmed-dead with no told
1278 /// `worker.exited` and no merge — the anchor for the residual crash
1279 /// backstop's fixed post-death grace (design.md §2.1a, issue
1280 /// `typed-supervisor-outcomes`).
1281 ///
1282 /// The backstop is the ONLY place pid liveness still governs an outcome
1283 /// (pid liveness is a pure crash backstop now, never a primary signal). When
1284 /// the launcher shim's exit fact is lost — a hard kill of the shim, host
1285 /// death — the supervisor never sees a `worker.exited` event, so it falls
1286 /// back to "process confirmed gone → `failed`". The grace exists only to let
1287 /// an in-flight `worker.exited` / merge append land before that fires: on the
1288 /// first confirmed death the supervisor records this timestamp (via a
1289 /// `node.death_observed` event) and DEFERS; it terminalizes `failed` only on a
1290 /// later tick once a fixed short window has elapsed AND an exclusive-lock
1291 /// re-read confirms no exit/merge landed in the race window.
1292 ///
1293 /// Persisted (not in-memory) so the grace survives a supervisor restart in the
1294 /// window — a restart re-reads it rather than restarting the clock. First-write
1295 /// -wins in the reducer, so the anchor is monotonic. `None` until the first
1296 /// confirmed-death observation, or forever for a worker that exits cleanly
1297 /// (the shim records `worker.exited` and the backstop never engages).
1298 /// `#[serde(default)]` keeps a node written before this field existed readable.
1299 #[serde(default)]
1300 pub first_death_at: Option<Timestamp>,
1301 /// An open, agent-authored request for a human decision. The worker records
1302 /// this through `node.awaiting_input` instead of blocking on interactive
1303 /// stdin. It remains non-terminal and is cleared by `node.input_resolved`, a
1304 /// terminal `node.report`, or `node.retry`.
1305 ///
1306 /// `opened_at` is stamped from the event envelope and is therefore a durable,
1307 /// monotonic grace-window anchor that survives supervisor restarts. The
1308 /// original discussion objects are retained verbatim so read surfaces and
1309 /// notification hooks can carry the question, options, and recommended
1310 /// default without inventing a second advisory schema.
1311 #[serde(default)]
1312 pub awaiting_input: Option<Box<AwaitingInput>>,
1313 /// The worker's open blocking question to its parent (`node.asked`), if
1314 /// any. At most one per node. Closed by the first of `node.answered`,
1315 /// `node.ask_timed_out`, or the node ending (terminal status or report,
1316 /// retry, told worker exit, round report), which moves it to
1317 /// [`Self::last_ask`]. Deliberately separate from [`Self::awaiting_input`]:
1318 /// that field means a prompt answered at the worker itself.
1319 #[serde(default, skip_serializing_if = "Option::is_none")]
1320 pub open_ask: Option<Box<OpenAsk>>,
1321 /// How the most recent question ended. Absent before the first one closes.
1322 #[serde(default, skip_serializing_if = "Option::is_none")]
1323 pub last_ask: Option<Box<ClosedAsk>>,
1324 /// Claude session id the launcher assigned (`--session-id`), recorded so a
1325 /// resident round can `--resume` exactly that session. Absent for Pi and
1326 /// for runs created before the field existed.
1327 #[serde(default, skip_serializing_if = "Option::is_none")]
1328 pub claude_session_id: Option<String>,
1329 /// Round state of a resident worker (ADR 0003); absent for ordinary runs
1330 /// and before the first round report.
1331 #[serde(default, skip_serializing_if = "Option::is_none")]
1332 pub resident: Option<Box<ResidentState>>,
1333}
1334
1335/// A worker's open blocking question to its parent, projected from
1336/// `node.asked`. The id is the `seq` of that event, so an answer addressed to an
1337/// older question can never close a newer one.
1338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1339pub struct OpenAsk {
1340 /// `seq` of the `node.asked` event.
1341 pub ask_id: u64,
1342 /// Worker attempt that asked.
1343 pub attempt: u32,
1344 /// The question, as the worker wrote it.
1345 pub question: String,
1346 /// Optional named choices; an answer may pick one with `--choice`.
1347 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1348 pub options: Vec<String>,
1349 /// What the worker does when nobody answers before `expires_at`.
1350 pub default: String,
1351 /// The worker's idempotency key; re-asking with it re-attaches.
1352 pub idempotency_key: String,
1353 /// Envelope timestamp of `node.asked`.
1354 pub asked_at: Timestamp,
1355 /// Deadline, fixed from `asked_at` + the requested timeout and moved only
1356 /// later, by `node.ask_escalated`.
1357 pub expires_at: Timestamp,
1358 /// Set when the parent passed the question on to a person
1359 /// (`node.ask_escalated`). An escalated question no longer settles the
1360 /// parent's `run wait`.
1361 #[serde(default, skip_serializing_if = "Option::is_none")]
1362 pub escalated_at: Option<Timestamp>,
1363 /// The parent's latest escalation note, if it gave one.
1364 #[serde(default, skip_serializing_if = "Option::is_none")]
1365 pub escalation_note: Option<String>,
1366}
1367
1368/// How a question ended.
1369#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1370#[serde(rename_all = "snake_case")]
1371pub enum AskOutcome {
1372 /// The parent answered before the deadline.
1373 Answered,
1374 /// The deadline passed; the worker took its default.
1375 TimedOut,
1376 /// The node or its worker attempt ended while the question was open.
1377 Cancelled,
1378}
1379
1380impl AskOutcome {
1381 /// Stable wire name.
1382 #[must_use]
1383 pub const fn wire(self) -> &'static str {
1384 match self {
1385 Self::Answered => "answered",
1386 Self::TimedOut => "timed_out",
1387 Self::Cancelled => "cancelled",
1388 }
1389 }
1390}
1391
1392/// A closed question with its outcome (`Node::last_ask`).
1393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1394pub struct ClosedAsk {
1395 /// The question as it was open when it closed.
1396 pub ask: OpenAsk,
1397 /// How it ended.
1398 pub outcome: AskOutcome,
1399 /// Envelope timestamp of the closing event.
1400 pub closed_at: Timestamp,
1401 /// `seq` of the event that closed it.
1402 pub closed_seq: u64,
1403 /// Free-text answer (`answered` only).
1404 #[serde(default, skip_serializing_if = "Option::is_none")]
1405 pub answer: Option<String>,
1406 /// Chosen option (`answered` only).
1407 #[serde(default, skip_serializing_if = "Option::is_none")]
1408 pub choice: Option<String>,
1409 /// `agent` or `person`, as the answering session stated it (`answered`
1410 /// only). Unverified; it grants nothing.
1411 #[serde(default, skip_serializing_if = "Option::is_none")]
1412 pub decided_by: Option<String>,
1413 /// Why a `cancelled` question ended (the closing event kind).
1414 #[serde(default, skip_serializing_if = "Option::is_none")]
1415 pub cancel_reason: Option<String>,
1416}
1417
1418/// Durable open-discussion state projected from `node.awaiting_input`.
1419#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1420pub struct AwaitingInput {
1421 /// Timestamp of the first open signal in the current unresolved generation.
1422 pub opened_at: Timestamp,
1423 /// Event sequence that opened this generation, used to deduplicate its
1424 /// delayed parent notification independently from later generations.
1425 pub event_seq: u64,
1426 /// Validated report-shaped discussion objects. Each carries `topic`,
1427 /// `options`, and `recommended_default`.
1428 pub discussion_items: Vec<Value>,
1429}
1430
1431/// A durable, in-flight `run merge` transaction recorded by `merge.started`
1432/// BEFORE the git mutation, and the sole input to deterministic merge-crash
1433/// recovery (design.md §2.1b / A2, issue `merge-transaction-recovery`).
1434///
1435/// `run merge` spans git refs and the event log and is not atomic across them.
1436/// Recording the transaction — the exact source ref it will move, the OID it
1437/// expects that ref to be at (`expected_source_oid`, the compare half of the
1438/// compare-and-swap), and the worker's tip — lets the supervisor (or a retried
1439/// `run merge`) resolve the ONE recorded transaction by OID after a crash:
1440///
1441/// - source ref still at `expected_source_oid` → the mutation never landed →
1442/// REJECT (`merge.aborted`), preserving the worker's branch + work.
1443/// - source ref moved off `expected_source_oid` AND the worker's content is
1444/// integrated (rebase-robust content verification) → COMPLETE (append the
1445/// `explicit-merge` `node.report` the crash prevented).
1446/// - source ref moved unexpectedly but the worker's content is not integrated →
1447/// fail closed (REJECT), preserving the work.
1448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1449pub struct MergeTxn {
1450 /// Opaque unique id for this merge attempt. A fresh id per `run merge`
1451 /// invocation (each attempt re-reads `expected_source_oid`), so recovery can
1452 /// name exactly which transaction it resolved in the `merge.aborted` audit.
1453 pub op_id: String,
1454 /// The source/target ref this merge moves — `manifest.source_branch`
1455 /// (`main`, or an integration branch). Recovery reads this ref's current OID
1456 /// to decide the transaction's fate.
1457 pub source_branch: String,
1458 /// The worker branch whose commits are being merged (`node.branch`). Its
1459 /// content is what recovery verifies is integrated into `source_branch`.
1460 pub worker_branch: String,
1461 /// The OID `source_branch` was at when the transaction was recorded — the
1462 /// compare half of the compare-and-swap. If the ref is still here at recovery
1463 /// time, the git mutation never landed.
1464 pub expected_source_oid: String,
1465 /// The worker branch tip at record time. Retained for the audit trail and as
1466 /// a secondary landing signal; the authoritative completion check is
1467 /// content-based (rebase-robust) against `source_branch`.
1468 pub worker_oid: String,
1469 /// The worker branch's fork point (`node.base_sha`), used to bound the
1470 /// content check to the worker's own commits. `None` when unrecorded.
1471 #[serde(default)]
1472 pub base_sha: Option<String>,
1473 /// PID of the `run merge` process driving the transaction, so recovery can
1474 /// tell a still-in-progress merge (driver alive — leave it) from a crashed
1475 /// one (driver gone — resolve it), never racing a live merge. `None` when
1476 /// unrecorded.
1477 #[serde(default)]
1478 pub driver_pid: Option<i32>,
1479 /// Start time of `driver_pid` in Unix seconds (the same representation the
1480 /// pid-file liveness check records), guarding against PID reuse the way the
1481 /// agent/supervisor liveness checks do — a recycled PID must not look alive.
1482 /// `None` when the platform could not read it. Decides PID reuse only when
1483 /// `driver_pid_start_identity` is absent.
1484 #[serde(default)]
1485 pub driver_pid_start_secs: Option<u64>,
1486 /// Kernel start identity of `driver_pid` (the same token the agent and
1487 /// supervisor identity checks compare exactly). Unlike the seconds value it
1488 /// does not move when the wall clock is stepped. Absent on transactions
1489 /// recorded before the field existed.
1490 #[serde(default, skip_serializing_if = "Option::is_none")]
1491 pub driver_pid_start_identity: Option<String>,
1492 /// Caller-only provenance tying the transaction to the sticky intent and
1493 /// the exact writer inode held by the merge driver. Absent on normal merges.
1494 #[serde(default, skip_serializing_if = "Option::is_none")]
1495 pub caller_authority: Option<CallerMergeLink>,
1496 /// A resident `run land` transaction (ADR 0003): its completion is a
1497 /// non-terminal `node.round_landed`, never an `explicit-merge` report.
1498 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1499 pub landing: bool,
1500 /// When the transaction was recorded.
1501 pub started_at: Timestamp,
1502}
1503
1504/// Immutable provenance for a caller-owned merge. Checked against the intent
1505/// projection when the transaction is folded, not inferred from Git ancestry.
1506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1507pub struct CallerMergeLink {
1508 /// Durable sequence of `caller.settlement_intent`.
1509 pub intent_seq: u64,
1510 /// Stable operation key recorded by that intent.
1511 pub intent_key: String,
1512 /// Recorded writer device.
1513 pub writer_dev: u64,
1514 /// Recorded writer inode.
1515 pub writer_ino: u64,
1516}
1517
1518/// The observed exit status of a node's worker process, recorded by the
1519/// `run-worker` launcher shim under the run lock (design.md §2.1 / A1).
1520///
1521/// Exactly one of `code` / `signal` is meaningful: a worker that returned
1522/// normally carries `code = Some(n)` (and `signal = None`); a worker killed by a
1523/// signal carries `signal = Some(s)` (and, on Unix, `code = None`). A recorded
1524/// exit is a durable *told fact* — the supervisor reads it rather than inferring
1525/// completion from liveness proxies.
1526#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1527pub struct WorkerExit {
1528 /// Normal-exit status code, if the worker was not killed by a signal.
1529 #[serde(default)]
1530 pub code: Option<i32>,
1531 /// Terminating signal number, if the worker was killed by a signal.
1532 #[serde(default)]
1533 pub signal: Option<i32>,
1534 /// When the shim observed the worker's exit.
1535 pub at: Timestamp,
1536}
1537
1538impl WorkerExit {
1539 /// A clean exit: not signalled, and a zero return code. This is the *only*
1540 /// success-shaped worker exit — but a clean exit alone is NOT a completed
1541 /// unit (the worker may have finished-but-skipped `run merge`); merge is the
1542 /// only success truth (design.md §2.6). Callers pair this with a merge check.
1543 pub fn is_clean(self) -> bool {
1544 self.signal.is_none() && self.code == Some(0)
1545 }
1546
1547 /// A failed worker: killed by a signal, or a non-zero return code. Mutually
1548 /// exclusive with [`WorkerExit::is_clean`].
1549 pub fn is_failure(self) -> bool {
1550 !self.is_clean()
1551 }
1552}
1553
1554/// A fully-qualified tmux window identity recorded at spawn time.
1555///
1556/// `tmux_window` (the human name) is not unique across sessions, and a bare
1557/// `tmux list-windows -a` cannot see windows on a non-default socket. This
1558/// triple pins the exact window the agent runs in — `session:window_id` is
1559/// unique per server, `window_id` (the `@NNNN` form) survives renames, and
1560/// `socket` disambiguates multiple tmux servers. The watchdog matches on this
1561/// when present (design.md §8.1).
1562///
1563/// `pane_id` (the `%NN` form) pins the agent's *specific* pane within that
1564/// window, recorded at spawn. Window-owning operations (`kill-window` teardown —
1565/// the supervisor owns the whole window per the cleanup invariants) key off
1566/// `window_id`; only per-pane operations that must not follow the window's
1567/// *active* pane — chiefly `pipe-pane` agent-log capture — use `pane_id`. It is
1568/// `None` for a run spawned before create.sh emitted the field; capture then
1569/// falls back to `window_id` (issue `capture-agent-pane-by-pane-id`).
1570///
1571/// The watchdog's liveness probe still keys off `window_id` (correct for the
1572/// single-pane autonomous path). A pane-aware liveness probe — needed so a split
1573/// interactive window whose agent pane dies while a user shell pane survives is
1574/// still seen as dead — is a follow-up (`watchdog-pane-aware-liveness`), not this
1575/// change.
1576#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1577pub struct TmuxIdentity {
1578 /// Server socket path (`#{socket_path}`). `None` if create.sh could not
1579 /// read it; the watchdog then queries tmux on its default socket.
1580 #[serde(default)]
1581 pub socket: Option<String>,
1582 /// Session that owns the window (`#{session_name}`).
1583 pub session: String,
1584 /// Stable window id in `@NNNN` form (`#{window_id}`). Survives renames and
1585 /// is unique within the server.
1586 pub window_id: String,
1587 /// Stable pane id in `%NN` form (`#{pane_id}`), recorded at spawn — the
1588 /// agent's own pane. `None` for a run whose create.sh predates the field
1589 /// (back-compat: old state deserializes with `pane_id: None`). Prefer
1590 /// [`TmuxIdentity::capture_target`] over reading this directly.
1591 #[serde(default)]
1592 pub pane_id: Option<String>,
1593 /// tmux server PID and its OS start identity at spawn. New persistent
1594 /// sessions require both; legacy nodes deserialize them as absent.
1595 #[serde(default)]
1596 pub server_pid: Option<u32>,
1597 /// Unix-second start time of the recorded tmux server PID. It drifts with
1598 /// wall-clock steps on Linux, so it decides server identity only for a
1599 /// node recorded without `server_pid_start_identity`.
1600 #[serde(default)]
1601 pub server_pid_start_secs: Option<u64>,
1602 /// Kernel start identity of the recorded tmux server PID, compared exactly.
1603 #[serde(default, skip_serializing_if = "Option::is_none")]
1604 pub server_pid_start_identity: Option<String>,
1605 /// Runtime-owned server marker (for example Homebase's owner marker).
1606 #[serde(default)]
1607 pub server_marker: Option<String>,
1608}
1609
1610impl TmuxIdentity {
1611 /// The tmux target for a per-pane operation that must hit the agent's own
1612 /// pane, not the window's *active* pane: the recorded `pane_id` when
1613 /// present, else the `window_id` (which resolves to the active pane).
1614 ///
1615 /// Used by agent-log capture (`pipe-pane`). Window-level operations
1616 /// (`kill-window`, liveness) must NOT use this — they key off `window_id`
1617 /// directly so they act on the whole window.
1618 ///
1619 /// A recorded `pane_id` is preferred only when non-empty; an empty string
1620 /// (a directly-deserialized/corrupt state that the reducer/spawn normalizers
1621 /// never produce) is treated as absent so capture never targets `-t ""`.
1622 pub fn capture_target(&self) -> &str {
1623 self.pane_id
1624 .as_deref()
1625 .filter(|id| !id.is_empty())
1626 .unwrap_or(&self.window_id)
1627 }
1628}
1629
1630/// One event-log line (design.md §1.4).
1631///
1632/// `run_id` / `node_id` are the typed id newtypes, so deserializing an
1633/// `events.jsonl` line validates the whole envelope on read: a malformed
1634/// `run_id` or `node_id` fails the `serde` parse at the read boundary (the
1635/// id newtypes' validating `Deserialize`) rather than being carried as an
1636/// unvalidated `String` until some later path helper. The parse failure
1637/// surfaces as whatever error the reader maps a bad line to — e.g. a
1638/// newline-terminated bad line is [`Error::CorruptEventLog`] from both
1639/// [`read_all_events`] and [`find_prior_with_key`], which share one physical
1640/// reader and torn-tail policy. The reducer still performs its own per-event
1641/// checks (envelope `run_id` matches the run it is folded into; `data`-borne
1642/// ids parse), but the envelope ids can no longer be the unvalidated party.
1643///
1644/// [`read_all_events`]: crate::events::read_all_events
1645/// [`find_prior_with_key`]: crate::events
1646/// [`Error::CorruptEventLog`]: crate::Error::CorruptEventLog
1647#[derive(Debug, Clone, Serialize, Deserialize)]
1648pub struct Event {
1649 /// Wall-clock timestamp the event was appended.
1650 pub ts: Timestamp,
1651 /// Monotonic per-run sequence number (recovered on append).
1652 pub seq: u64,
1653 /// Event kind discriminator (e.g. `node.created`, `discussion.opened`).
1654 pub kind: String,
1655 /// Run the event belongs to. Validated on read.
1656 pub run_id: RunId,
1657 /// Node the event concerns, when applicable. Validated on read.
1658 #[serde(skip_serializing_if = "Option::is_none", default)]
1659 pub node_id: Option<NodeId>,
1660 /// Caller-supplied key used to dedupe retried appends.
1661 #[serde(skip_serializing_if = "Option::is_none", default)]
1662 pub idempotency_key: Option<String>,
1663 /// Kind-specific payload applied by the reducer.
1664 #[serde(default)]
1665 pub data: Value,
1666}
1667
1668#[cfg(test)]
1669mod tests {
1670 use super::*;
1671
1672 #[test]
1673 fn aggregate_terminal_status_is_the_three_way_rule() {
1674 use Status::{Blocked, Cancelled, Done, Failed, Pending, Running};
1675 // Empty set → not complete.
1676 assert_eq!(aggregate_terminal_status([]), None);
1677 // Any live node → not complete.
1678 for live in [Pending, Running, Blocked] {
1679 assert_eq!(aggregate_terminal_status([Done, live]), None);
1680 }
1681 // All done → Done.
1682 assert_eq!(aggregate_terminal_status([Done, Done]), Some(Done));
1683 // Any failure dominates.
1684 assert_eq!(aggregate_terminal_status([Done, Failed]), Some(Failed));
1685 assert_eq!(aggregate_terminal_status([Failed, Cancelled]), Some(Failed));
1686 // Cancelled (no failure) — pure or mixed with done.
1687 assert_eq!(
1688 aggregate_terminal_status([Cancelled, Cancelled]),
1689 Some(Cancelled)
1690 );
1691 assert_eq!(
1692 aggregate_terminal_status([Done, Cancelled]),
1693 Some(Cancelled)
1694 );
1695 }
1696
1697 /// `Kind::wire_name` (and thus `Kind::WIRE_NAMES`) must stay identical
1698 /// to what serde actually (de)serializes. If the `rename_all` routing
1699 /// or a variant name ever diverges from `wire_name`, this fails — which
1700 /// is what keeps the report validator's `expected` hint honest.
1701 #[test]
1702 fn wire_names_match_serde_round_trip() {
1703 for &name in Kind::WIRE_NAMES {
1704 let kind: Kind = serde_json::from_value(Value::String(name.to_string()))
1705 .unwrap_or_else(|_| panic!("WIRE_NAMES entry {name:?} is not a valid Kind"));
1706 assert_eq!(
1707 serde_json::to_value(kind).unwrap(),
1708 Value::String(name.to_string()),
1709 "serde round-trip diverged from wire_name for {name:?}",
1710 );
1711 }
1712 }
1713
1714 /// The bounded auto-retry eligibility gate (issue `autoretry-agent-died-worker`)
1715 /// must include exactly the autonomous single-node worker kinds and exclude
1716 /// the fan-out driver (and the read-only `Unknown` catch-all).
1717 #[test]
1718 fn autonomous_single_node_worker_set_is_exact() {
1719 for k in [Kind::Spinoff, Kind::Research, Kind::TechnicalDecision] {
1720 assert!(
1721 k.is_autonomous_single_node_worker(),
1722 "{k:?} should be retry-eligible"
1723 );
1724 assert_eq!(k.lifecycle(), Lifecycle::Autonomous);
1725 }
1726 for k in [
1727 Kind::FanOut, // multi-unit driver
1728 Kind::Unknown, // legacy on-disk run — never freshly supervised
1729 ] {
1730 assert!(
1731 !k.is_autonomous_single_node_worker(),
1732 "{k:?} must NOT be retry-eligible"
1733 );
1734 }
1735 }
1736
1737 /// A legacy run recorded under a since-removed kind must still deserialize
1738 /// to the read-only [`Kind::Unknown`] catch-all rather than faulting the
1739 /// read — the ADR §D7 "report, never delete" contract for the on-disk
1740 /// evidence corpus. Every creatable kind still round-trips to itself.
1741 #[test]
1742 fn removed_kinds_deserialize_to_unknown() {
1743 for removed in [
1744 "code",
1745 "orchestrate",
1746 "orchestrated",
1747 "bugfix",
1748 "make-skill",
1749 ] {
1750 let kind: Kind = serde_json::from_value(Value::String(removed.to_string()))
1751 .expect("a removed kind must still deserialize, not fault");
1752 assert_eq!(kind, Kind::Unknown, "{removed:?} should map to Unknown");
1753 }
1754 // A wholly unknown value maps there too (forward-compat).
1755 assert_eq!(
1756 serde_json::from_value::<Kind>(Value::String("future-kind".into())).unwrap(),
1757 Kind::Unknown
1758 );
1759 // The surviving kinds are unaffected.
1760 for &name in Kind::WIRE_NAMES {
1761 let kind: Kind = serde_json::from_value(Value::String(name.to_string())).unwrap();
1762 assert_ne!(kind, Kind::Unknown, "{name:?} must not fold to Unknown");
1763 }
1764 }
1765
1766 /// Back-compat acceptance criterion (issue `capture-agent-pane-by-pane-id`):
1767 /// a `TmuxIdentity` persisted before `pane_id` existed — with the field
1768 /// entirely absent, or written as an explicit `null` — must still
1769 /// deserialize, yielding `pane_id: None` and a `window_id` capture target.
1770 #[test]
1771 fn tmux_identity_deserializes_legacy_state_without_pane_id() {
1772 // Field entirely absent (a state file written by an older binary).
1773 let absent: TmuxIdentity = serde_json::from_value(serde_json::json!({
1774 "socket": null,
1775 "session": "taskfleet",
1776 "window_id": "@42",
1777 }))
1778 .expect("legacy identity without pane_id must deserialize");
1779 assert_eq!(absent.pane_id, None);
1780 assert_eq!(absent.capture_target(), "@42");
1781
1782 // Field present but explicitly null.
1783 let null: TmuxIdentity = serde_json::from_value(serde_json::json!({
1784 "socket": null,
1785 "session": "taskfleet",
1786 "window_id": "@42",
1787 "pane_id": null,
1788 }))
1789 .expect("identity with explicit null pane_id must deserialize");
1790 assert_eq!(null.pane_id, None);
1791 assert_eq!(null.capture_target(), "@42");
1792 }
1793
1794 /// `capture_target` prefers a recorded `pane_id` (`%NN`) over the window id,
1795 /// but treats an empty `pane_id` as absent (never targets `-t ""`).
1796 #[test]
1797 fn capture_target_prefers_nonempty_pane_id() {
1798 let with_pane = TmuxIdentity {
1799 socket: None,
1800 session: "taskfleet".into(),
1801 window_id: "@42".into(),
1802 pane_id: Some("%7".into()),
1803 server_pid: None,
1804 server_pid_start_secs: None,
1805 server_pid_start_identity: None,
1806 server_marker: None,
1807 };
1808 assert_eq!(with_pane.capture_target(), "%7");
1809
1810 let empty_pane = TmuxIdentity {
1811 pane_id: Some(String::new()),
1812 ..with_pane.clone()
1813 };
1814 assert_eq!(empty_pane.capture_target(), "@42");
1815 }
1816}
1817
1818#[cfg(test)]
1819mod id_tests {
1820 use super::*;
1821
1822 /// Inputs every id type must reject — the path-traversal vectors plus the
1823 /// generic malformed cases called out in the issue's success criteria.
1824 const TRAVERSAL_VECTORS: &[&str] = &[
1825 "..",
1826 "../etc",
1827 "a/b",
1828 "a/../b",
1829 ".hidden",
1830 "./x",
1831 "foo/bar.json",
1832 "n-0001/../../etc",
1833 "",
1834 ];
1835
1836 #[test]
1837 fn run_id_accepts_generator_output_and_rejects_malformed() {
1838 let id = crate::new_run_id();
1839 assert!(
1840 RunId::parse_str(&id).is_ok(),
1841 "generator must validate: {id}"
1842 );
1843 for bad in [
1844 "tooshort",
1845 "01jxsnap0000000000000000000", // 27 chars
1846 "01JXSNAP000000000000000000", // uppercase
1847 "01jxiiiiiiiiiiiiiiiiiiiiii", // `i` not in Crockford
1848 "80000000000000000000000000", // first char exceeds ULID range
1849 "n-0001", // wrong shape entirely
1850 ] {
1851 assert!(RunId::parse_str(bad).is_err(), "expected reject: {bad:?}");
1852 }
1853 for bad in TRAVERSAL_VECTORS {
1854 assert!(
1855 RunId::parse_str(bad).is_err(),
1856 "traversal not rejected: {bad:?}"
1857 );
1858 }
1859 }
1860
1861 #[test]
1862 fn node_id_accepts_canonical_and_rejects_malformed() {
1863 for ok in ["n-0001", "n-0010", "n-123456"] {
1864 assert!(NodeId::parse_str(ok).is_ok(), "expected accept: {ok}");
1865 }
1866 // Wrong prefix is its own error variant.
1867 assert!(matches!(
1868 NodeId::parse_str("d-0001"),
1869 Err(IdValidationError::WrongPrefix { .. })
1870 ));
1871 assert!(matches!(
1872 NodeId::parse_str("0001"),
1873 Err(IdValidationError::WrongPrefix { .. })
1874 ));
1875 for bad in [
1876 "n-1", // too few digits
1877 "n-abcd", // non-digit body
1878 "n-", // empty body
1879 "n-00a1", // mixed
1880 "n-00000000000", // 11 digits — over the 10-digit ceiling
1881 ] {
1882 assert!(
1883 matches!(
1884 NodeId::parse_str(bad),
1885 Err(IdValidationError::InvalidFormat { .. })
1886 ),
1887 "expected InvalidFormat: {bad:?}",
1888 );
1889 }
1890 for bad in TRAVERSAL_VECTORS {
1891 assert!(
1892 NodeId::parse_str(bad).is_err(),
1893 "traversal not rejected: {bad:?}"
1894 );
1895 }
1896 }
1897
1898 #[test]
1899 fn deserialize_rejects_malformed_ids() {
1900 // The validating Deserialize impl is the on-read guard: a tampered
1901 // projection file whose key no longer validates must fail to parse.
1902 assert!(serde_json::from_str::<NodeId>("\"n-0001\"").is_ok());
1903 assert!(serde_json::from_str::<NodeId>("\"../../etc\"").is_err());
1904 assert!(serde_json::from_str::<NodeId>("\"n-../escape\"").is_err());
1905 }
1906
1907 #[test]
1908 fn serialize_round_trips_as_bare_string() {
1909 let nid = NodeId::parse_str("n-0042").unwrap();
1910 let json = serde_json::to_string(&nid).unwrap();
1911 assert_eq!(json, "\"n-0042\"");
1912 let back: NodeId = serde_json::from_str(&json).unwrap();
1913 assert_eq!(back, nid);
1914 assert_eq!(nid.as_str(), "n-0042");
1915 assert_eq!(nid.to_string(), "n-0042");
1916 }
1917
1918 #[test]
1919 fn error_exposes_kind_and_expected() {
1920 let err = NodeId::parse_str("n-x").unwrap_err();
1921 assert_eq!(err.kind(), "node");
1922 assert_eq!(err.expected(), "n-NNNN (n- followed by 4-10 ASCII digits)");
1923 }
1924
1925 #[test]
1926 fn event_deserialize_validates_envelope_ids() {
1927 // The whole `events.jsonl` envelope is now validated on read: the
1928 // typed `run_id` / `node_id` fields parse through the id newtypes, so
1929 // a malformed envelope id fails the deserialize rather than being
1930 // carried downstream as an unchecked string.
1931 let ok = r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"node.created","run_id":"01jxsnap000000000000000000","node_id":"n-0001","data":{}}"#;
1932 assert!(serde_json::from_str::<Event>(ok).is_ok());
1933
1934 // Invalid `run_id` (not a 26-char ULID) fails the parse.
1935 let bad_run = r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"run.status","run_id":"not-a-ulid","data":{}}"#;
1936 assert!(serde_json::from_str::<Event>(bad_run).is_err());
1937
1938 // Invalid top-level `node_id` (too few digits) also fails the parse.
1939 let bad_node = r#"{"ts":"2026-06-12T00:00:00Z","seq":1,"kind":"node.status","run_id":"01jxsnap000000000000000000","node_id":"n-1","data":{}}"#;
1940 assert!(serde_json::from_str::<Event>(bad_node).is_err());
1941 }
1942
1943 #[test]
1944 fn from_str_and_ord_delegate_to_inner() {
1945 use std::str::FromStr;
1946 // `FromStr` mirrors `parse_str`, so the `str::parse` ecosystem works.
1947 assert!(RunId::from_str("01jxsnap000000000000000000").is_ok());
1948 assert!("n-0001".parse::<NodeId>().is_ok());
1949 assert!("n-x".parse::<NodeId>().is_err());
1950
1951 // `Ord` is lexicographic over the inner string; for ULIDs that is the
1952 // natural time-encoded order.
1953 let a = RunId::parse_str("01jxsnap000000000000000000").unwrap();
1954 let b = RunId::parse_str("02jxsnap000000000000000000").unwrap();
1955 assert!(a < b);
1956 let mut v = vec![b.clone(), a.clone()];
1957 v.sort();
1958 assert_eq!(v, vec![a, b]);
1959 }
1960}
1961
1962#[cfg(test)]
1963mod agent_selection_validation_tests {
1964 use super::*;
1965
1966 fn valid() -> AgentSelection {
1967 AgentSelection {
1968 schema_version: 1,
1969 profile: "capable".into(),
1970 selection_source: "cli".into(),
1971 interaction: "autonomous".into(),
1972 capability: "capable".into(),
1973 residency: "remote".into(),
1974 requested_harness: None,
1975 selected: SelectedAgentCandidate {
1976 candidate_index: 1,
1977 harness: "pi".into(),
1978 command: vec!["pi".into()],
1979 telemetry: Some("worker-v1".into()),
1980 },
1981 fallback: vec![SkippedAgentCandidate {
1982 candidate_index: 0,
1983 harness: "claude".into(),
1984 reason: "autonomous_harness_unsupported".into(),
1985 }],
1986 }
1987 }
1988
1989 #[test]
1990 fn durable_selection_rejects_impossible_state() {
1991 assert!(valid().validate().is_ok());
1992 let mut invalid = valid();
1993 invalid.selected.candidate_index = 200;
1994 assert!(invalid.validate().is_err());
1995 let mut invalid = valid();
1996 invalid.fallback[0].reason = "made_up".into();
1997 assert!(invalid.validate().is_err());
1998 let mut invalid = valid();
1999 invalid.selected.harness = "claude".into();
2000 assert!(invalid.validate().is_err());
2001 }
2002}