Skip to main content

rusty_agent_runtime/
agents.rs

1//! Agent Fabric contracts (R0.7): durable agent identity, the
2//! versioned capability manifest, the state-scope taxonomy, the
3//! supervision vocabulary (wave 2), and the typed coordination
4//! patterns (wave 3).
5//!
6//! This module freezes the wire shapes the agent fabric builds on — the
7//! server's agent registry and activation leases, the agent hosts (a later
8//! wave), and the SDKs must agree on them byte-for-byte, exactly the rule
9//! [`crate::durable`] set for the R0.6 queue before it. Nothing here
10//! performs I/O, scheduling, or supervision; these are pure data contracts
11//! plus the addressing grammar both sides of a mailbox must share.
12//!
13//! The three pillars:
14//!
15//! - [`AgentId`] — stable, tenant-namespaced agent identity. Identity is
16//!   names and records, not processes: it survives redeploys and crashes
17//!   because the registry record, the thread, and the mailbox all derive
18//!   from the one id. [`AgentId::mailbox_recipient`] is the addressing
19//!   discipline the R0.6 queue carries mailbox traffic under.
20//! - [`CapabilityManifest`] — the versioned declaration of what an agent
21//!   runs, which message kinds its mailbox accepts, which [`StateScope`]s
22//!   it may touch, and its budget ceiling. The exact-match
23//!   `manifest_version` pin is the agent-level form of R0.6's worker
24//!   version pinning: a team started against one manifest never has its
25//!   semantics changed mid-flight by a redeploy.
26//! - [`StateScope`] — the closed taxonomy of state an agent may read and
27//!   write, mapped onto stores that already exist (the agent's checkpoint
28//!   log, a shared team thread, the server KV namespaces).
29//! - [`SupervisionPolicy`] — the declared restart semantics
30//!   ([`RestartPolicy`], OTP's vocabulary) plus the intensity/period
31//!   budget and supervisor address; [`EscalationNotice`] is the message
32//!   shape an exhausted budget submits to the supervisor's mailbox.
33//!   Escalation is a message, not an exit, because Rusty agents are data
34//!   and runs, not processes.
35//! - [`CoordinationContract`] — the four typed patterns (delegate, fan-out,
36//!   race, quorum) a delegator submits as one declaration (wave 3). The
37//!   contracts are pure data; the runtime guarantees (bounded fan-out, the
38//!   race effect gate, quorum thresholds, journaled dispositions) are
39//!   enforced by the server against these shapes.
40//!
41//! Golden-file tests under `tests/golden/` pin the serialized shapes; any
42//! accidental contract drift fails CI. To bless an intentional change,
43//! re-run with `UPDATE_GOLDEN=1` and review the diff.
44
45use std::collections::BTreeMap;
46
47use chrono::{DateTime, Utc};
48use serde::{Deserialize, Serialize};
49use serde_json::Value;
50use thiserror::Error;
51
52use crate::durable::{ArtifactContract, ErrorClass};
53use crate::llm::Usage;
54use crate::record::{Effect, PayloadRef};
55
56/// The address prefix distinguishing mailbox recipients from worker pools
57/// on the task queue: a `recipient` of `agent:{agent_id}` is mailbox
58/// traffic, drained one message at a time by the agent's activation; any
59/// other recipient is ordinary queue work. Server-side, recipient-addressed
60/// tasks are excluded from the pool claim path — a pool worker must never
61/// steal a mailbox message out from under the turn-serialization
62/// discipline.
63pub const AGENT_RECIPIENT_PREFIX: &str = "agent:";
64
65/// A stable agent identity (R0.7).
66///
67/// Tenant-namespaced like every other server id (`{tenant}/researcher-7`
68/// inherits the v0.5 isolation model unchanged — a cross-tenant agent
69/// resolves to nothing). Transparent over `String`: the wire shape is the
70/// id itself. The newtype — not convention — is what keeps agent ids
71/// distinct from run ids, task ids, and pool names at every construction
72/// site, the same discipline [`crate::record::PolicyVersion`] applies to
73/// policy pins.
74///
75/// The constructor does not validate: the server's route layer enforces the
76/// id grammar (non-empty, bounded, no path separators) at the boundary,
77/// the same division of labor every other server id follows.
78#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
79#[serde(transparent)]
80pub struct AgentId(pub String);
81
82impl AgentId {
83    /// Wrap an id string.
84    pub fn new(id: impl Into<String>) -> Self {
85        Self(id.into())
86    }
87
88    /// The id string.
89    pub fn as_str(&self) -> &str {
90        &self.0
91    }
92
93    /// The queue recipient addressing this agent's mailbox:
94    /// `agent:{agent_id}`. A mailbox is an addressing discipline on the
95    /// existing task queue — not a new queue — so mailbox messages inherit
96    /// the R0.6 durability, retry, dead-letter, and cancellation machinery
97    /// unchanged.
98    pub fn mailbox_recipient(&self) -> String {
99        format!("{AGENT_RECIPIENT_PREFIX}{}", self.0)
100    }
101
102    /// The thread holding this agent's private state: `agent:{agent_id}` —
103    /// a naming convention over the existing checkpointer, not a new store,
104    /// so checkpoints, time travel, and fork-on-replay work on agent state
105    /// unmodified. The checkpoint log *is* the private state; restart is
106    /// re-driving it.
107    pub fn thread_id(&self) -> String {
108        format!("{AGENT_RECIPIENT_PREFIX}{}", self.0)
109    }
110}
111
112impl std::fmt::Display for AgentId {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.write_str(&self.0)
115    }
116}
117
118/// Strip the mailbox prefix from a recipient string: `Some(agent_id)` when
119/// `recipient` is mailbox traffic (`agent:{agent_id}`), `None` for ordinary
120/// pool/pinned-worker recipients. The server uses this to keep mailbox
121/// messages off the pool claim path.
122pub fn agent_id_from_recipient(recipient: &str) -> Option<&str> {
123    recipient.strip_prefix(AGENT_RECIPIENT_PREFIX)
124}
125
126/// A state scope an agent may read and write (R0.7): the closed taxonomy
127/// naming where agent state lives, declared per agent in its
128/// [`CapabilityManifest::scopes`].
129///
130/// Each scope maps onto a store that already exists — the contract is the
131/// name and the declaration, not a new mechanism. Access is checked against
132/// the manifest's declaration: an undeclared access fails fast before any
133/// I/O, the same shape as a write to an undeclared channel failing at the
134/// barrier.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[serde(rename_all = "snake_case")]
137pub enum StateScope {
138    /// The agent's own thread (`agent:{agent_id}`). The checkpoint log is
139    /// the private state: per-turn writes land in channels, the boundary
140    /// checkpoint persists them, restart restores them.
141    Private,
142
143    /// A thread shared by a team's members (`team:{team_id}`), written only
144    /// through mailbox-driven turns so every mutation has a journaled
145    /// author. Shared mutable team state outside the turn discipline is not
146    /// offered — that is the shared-state bug class the channel/reducer
147    /// model was built to kill.
148    Team,
149
150    /// The server KV store under a `user:{user_id}` namespace (inside the
151    /// tenant's `{tenant}/` isolation prefix).
152    User,
153
154    /// The server KV store's tenant namespace itself — configuration and
155    /// reference data shared by every agent and run in the tenant.
156    Tenant,
157}
158
159/// An agent-level budget ceiling (R0.7): the whole-activity bound across
160/// turns, the way [`crate::durable::TaskBudget`] bounds one task across its
161/// attempts.
162///
163/// Every field is optional and omitted from the wire when unset, so a
164/// manifest carrying no budget — or a partial one — produces no shape
165/// change for older readers. `None` means unbounded within the tenant's
166/// own quotas, never an invented default.
167#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
168pub struct AgentBudget {
169    /// Token ceiling across all of the agent's turns.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub max_tokens: Option<u64>,
172
173    /// Cost ceiling in USD across all turns. Evidence-grade `f64`, matching
174    /// [`crate::record::RunEvent::cost_usd`]: the ledger aggregates
175    /// elsewhere.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub max_cost_usd: Option<f64>,
178
179    /// Wall-clock deadline for the whole agent activity, across turns.
180    /// Expiry is cancellation by clock one level up from
181    /// [`crate::durable::TaskEnvelope::deadline`]: the server stamps it
182    /// onto the agent's mailbox messages (the earlier bound wins), and its
183    /// breach is a supervision signal — the turn's outstanding work is
184    /// cancelled, journaled, and the declared [`SupervisionPolicy`]
185    /// decides restart vs escalate (R0.7 wave 2).
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub deadline: Option<DateTime<Utc>>,
188}
189
190/// The message kind carrying a supervision escalation (R0.7 wave 2).
191///
192/// Escalation is a *message*, not an exit: when a supervised agent exhausts
193/// its restart budget, the runtime submits an [`EscalationNotice`] under
194/// this kind to the supervisor's mailbox — durable, journaled,
195/// retry-policy-bearing like any other mailbox traffic. A supervisor's
196/// manifest must declare this kind in [`CapabilityManifest::accepts`] for
197/// the escalation to be delivered; when it cannot be delivered (no
198/// supervisor declared, unknown supervisor, or the kind not accepted) the
199/// notice dead-letters with the full evidence attached — the design's
200/// "root escalations dead-letter" rule, honoring the chosen default of
201/// open question 2 (DLQ + operator, no runtime-level root policy).
202pub const ESCALATION_MESSAGE_KIND: &str = "escalated";
203
204/// A restart policy (R0.7 wave 2): how a supervised agent is restarted
205/// after a failed turn, in Erlang/OTP's vocabulary because that vocabulary
206/// is the reference implementation of operational restart semantics.
207///
208/// "Restart" here means what the design doc defines it to mean: a new run
209/// on the agent's thread, restoring the latest checkpoint — the mailbox is
210/// untouched, so the crashed turn's message returns to visibility at its
211/// own lease expiry and is re-delivered under its idempotency key. State
212/// loss is bounded and explicit (the in-flight turn re-executes from its
213/// start; everything checkpointed survives), unlike OTP's process restart,
214/// because the state is the checkpoint log, not the process.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
216#[serde(rename_all = "snake_case")]
217pub enum RestartPolicy {
218    /// Always restarted after a failed turn (within the declared
219    /// intensity/period budget).
220    Permanent,
221    /// Restarted only after an *abnormal* termination. A turn cancelled by
222    /// clock (deadline) or by the cancellation tree is control flow, not a
223    /// crash — OTP's transient rule applied to the R0.6
224    /// [`ErrorClass::Cancelled`] semantics.
225    Transient,
226    /// Never restarted after a failure: the first failed turn escalates.
227    Temporary,
228}
229
230/// What triggered a supervision decision (R0.7 wave 2), recorded on every
231/// [`SupervisionAttempt`] so the escalation's attempt history reads as
232/// evidence, not just as a counter.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
234#[serde(rename_all = "snake_case")]
235pub enum SupervisionTrigger {
236    /// A mailbox turn settled as failed (the worker running the turn
237    /// classified the error into the shared [`ErrorClass`] taxonomy).
238    TurnFailed,
239    /// The agent's whole-activity deadline
240    /// ([`AgentBudget::deadline`]) passed: cancellation by clock one level
241    /// up from the task deadline.
242    DeadlineBreached,
243    /// An operator restarted the agent deliberately
244    /// (`POST /agents/{id}/restart`). Manual restarts carry no failure
245    /// class and do not consume the restart budget.
246    ManualRestart,
247}
248
249/// One entry in a supervised agent's attempt history (R0.7 wave 2): the
250/// failure (or operator action) a supervision decision was made about.
251///
252/// The history is the evidence an escalation carries — the design's
253/// "escalation with its attempt history intact" — so every entry records
254/// the trigger, the classification, and the turn task it came from, not
255/// merely a count.
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257pub struct SupervisionAttempt {
258    /// 1-based position in the agent's full supervision history. When the
259    /// decision was a restart, this is the restart ordinal the journaled
260    /// `SupervisionEvent` names.
261    pub ordinal: u32,
262    /// What the runtime observed.
263    pub trigger: SupervisionTrigger,
264    /// The failed turn's classification (core's closed [`ErrorClass`]
265    /// taxonomy). `None` for [`SupervisionTrigger::ManualRestart`] — an
266    /// operator action has no failure class.
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub error_class: Option<ErrorClass>,
269    /// The human-readable failure message (or the operator's reason).
270    pub message: String,
271    /// The mailbox turn task this attempt came from, when there is one.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub task_id: Option<String>,
274    /// When the attempt was recorded.
275    pub at: DateTime<Utc>,
276}
277
278/// The supervision policy declared per agent in its
279/// [`CapabilityManifest`] (R0.7 wave 2): the restart vocabulary plus the
280/// intensity/period budget bounding how much failure the runtime tolerates
281/// before escalating to the supervisor.
282///
283/// Policy is static and declared — no learned supervision in R0.7; the
284/// journaled decisions are the R0.10 policy plane's training data.
285#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
286pub struct SupervisionPolicy {
287    /// When the agent is restarted after a failed turn.
288    pub restart: RestartPolicy,
289    /// The maximum restarts tolerated within `period_ms` before the
290    /// runtime stops restarting and escalates (OTP's restart intensity).
291    pub intensity: u32,
292    /// The sliding window `intensity` is counted over, in milliseconds
293    /// (OTP's restart period). A quiet gap longer than this resets the
294    /// count.
295    pub period_ms: u64,
296    /// The supervisor's agent id (external, same tenant) whose mailbox
297    /// receives the [`EscalationNotice`] when the budget is exhausted.
298    /// `None` — a root agent — dead-letters its escalations for an
299    /// operator, per open question 2's chosen default.
300    #[serde(default, skip_serializing_if = "Option::is_none")]
301    pub supervisor: Option<String>,
302}
303
304impl SupervisionPolicy {
305    /// A policy with no supervisor (a root agent): set the optional field
306    /// directly; it is public.
307    pub fn new(restart: RestartPolicy, intensity: u32, period_ms: u64) -> Self {
308        Self {
309            restart,
310            intensity,
311            period_ms,
312            supervisor: None,
313        }
314    }
315
316    /// Whether a turn ending with `error_class` (`None` = the agent's
317    /// deadline breached, cancellation by clock) may be restarted under
318    /// this policy — OTP's restart semantics mapped onto the shared
319    /// [`ErrorClass`] taxonomy: `permanent` restarts on any termination,
320    /// `transient` only on abnormal ones (a cancellation — operator or
321    /// clock — is control flow, not a crash), `temporary` never.
322    pub fn allows_restart_after(&self, error_class: Option<ErrorClass>) -> bool {
323        match self.restart {
324            RestartPolicy::Permanent => true,
325            RestartPolicy::Transient => {
326                matches!(error_class, Some(class) if class != ErrorClass::Cancelled)
327            }
328            RestartPolicy::Temporary => false,
329        }
330    }
331}
332
333/// The escalation message submitted to a supervisor's mailbox (or the
334/// dead-letter queue) when an agent exhausts its restart budget (R0.7 wave
335/// 2). This is the payload of every mailbox message of kind
336/// [`ESCALATION_MESSAGE_KIND`].
337///
338/// Escalation-as-message is the structural change from OTP: Rusty agents
339/// are data and runs, not processes, so there is no exit signal to trap —
340/// the exhausted supervision budget submits this notice instead, durable
341/// and journaled like any other mailbox traffic, naming the failed agent,
342/// the policy that gave out, and the full attempt history as evidence.
343#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
344pub struct EscalationNotice {
345    /// The failed agent (external id within the tenant).
346    pub agent_id: String,
347    /// The policy that exhausted, verbatim — the supervisor (or the
348    /// operator reading the DLQ) sees exactly what was declared, not a
349    /// paraphrase.
350    pub policy: SupervisionPolicy,
351    /// The full attempt history at escalation time, oldest first.
352    pub attempts: Vec<SupervisionAttempt>,
353    /// When the runtime escalated.
354    pub escalated_at: DateTime<Utc>,
355}
356
357/// The versioned capability manifest of an agent (R0.7 wave 1): what the
358/// agent runs, what its mailbox accepts, which state scopes it may touch,
359/// and its budget ceiling.
360///
361/// Registration pins the manifest in the server's agent registry; a team
362/// started against `researcher/1.4.0` pins its mailbox traffic to that
363/// manifest, so a mid-team redeploy never changes semantics under an
364/// in-flight coordination. `manifest_version` is an *exact* version string,
365/// deliberately: semver ranges make a team's behavior depend on the version
366/// grammar's rules rather than on what the team actually recorded — the
367/// same reason R0.6's worker version pin is exact match only.
368///
369/// Every field past `agent_kind` / `manifest_version` is additive and
370/// omitted from the wire when empty, so manifests written against later
371/// waves keep deserializing here and a minimal manifest stays minimal on
372/// the wire. The supervision policy (R0.7 wave 2) landed the same additive
373/// way.
374#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
375pub struct CapabilityManifest {
376    /// What the agent runs: a graph/assistant identity (a graph plus
377    /// config, as the server's assistant registry already models it).
378    pub agent_kind: String,
379
380    /// The exact manifest version string (e.g. `researcher/1.4.0`). Exact
381    /// match, surviving retries and redeploys — see the type docs.
382    pub manifest_version: String,
383
384    /// The message kinds the mailbox accepts: message kind → the
385    /// [`ArtifactContract`] its payload must satisfy. A send naming a kind
386    /// outside this map fails fast at submission
387    /// ([`crate::durable::ErrorClass::InvalidInput`] semantics — never
388    /// retried) instead of dead-lettering after the attempt budget.
389    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
390    pub accepts: BTreeMap<String, ArtifactContract>,
391
392    /// The declared [`StateScope`]s the agent may read and write. Journaled
393    /// with the spawn event ([`crate::record::RunEventKind::AgentSpawn`]),
394    /// checked at every access.
395    #[serde(default, skip_serializing_if = "Vec::is_empty")]
396    pub scopes: Vec<StateScope>,
397
398    /// The agent-level budget ceiling. `None` (the default) means no
399    /// agent-level bound; tenant quotas still apply.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub budget: Option<AgentBudget>,
402
403    /// The declared supervision policy (R0.7 wave 2): restart semantics,
404    /// the intensity/period budget, and the supervisor escalation is
405    /// addressed to. `None` (the default) means unmanaged — failures stand
406    /// on their own, no restarts and no escalations; the runtime only
407    /// supervises agents that declare a policy.
408    #[serde(default, skip_serializing_if = "Option::is_none")]
409    pub supervision: Option<SupervisionPolicy>,
410}
411
412impl CapabilityManifest {
413    /// A minimal manifest: the agent kind and its exact version, accepting
414    /// no message kinds and declaring no scopes. Set the optional fields
415    /// directly; they are public.
416    pub fn new(agent_kind: impl Into<String>, manifest_version: impl Into<String>) -> Self {
417        Self {
418            agent_kind: agent_kind.into(),
419            manifest_version: manifest_version.into(),
420            accepts: BTreeMap::new(),
421            scopes: Vec::new(),
422            budget: None,
423            supervision: None,
424        }
425    }
426
427    /// The contract the manifest declares for message `kind`, or `None`
428    /// when the mailbox refuses that kind outright.
429    pub fn accepts_kind(&self, kind: &str) -> Option<&ArtifactContract> {
430        self.accepts.get(kind)
431    }
432}
433
434// ---------------------------------------------------------------------------
435// Coordination patterns (R0.7 wave 3)
436// ---------------------------------------------------------------------------
437
438/// The reserved message kind a coordination's outcome is delivered to the
439/// delegator's mailbox under (R0.7 wave 3). Reserved the way
440/// [`ESCALATION_MESSAGE_KIND`] is: an agent that wants to submit a pattern
441/// must declare this kind in its manifest, otherwise the submission is
442/// rejected at the door — a delegator that cannot receive the outcome would
443/// strand every pattern it starts.
444pub const COORDINATION_RESULT_KIND: &str = "coordination_result";
445
446/// Returns `true` when `kind` is the reserved coordination outcome kind.
447pub fn is_coordination_result(kind: &str) -> bool {
448    kind == COORDINATION_RESULT_KIND
449}
450
451/// The four typed coordination patterns (R0.7 wave 3). The variant name is
452/// the wire tag of [`CoordinationContract`] and the `pattern` field of every
453/// artifact the runtime produces for the pattern.
454#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
455#[serde(rename_all = "snake_case")]
456pub enum CoordinationKind {
457    /// Hand one task to one member; the member's result is the outcome.
458    Delegate,
459    /// Run members under a bounded in-flight window and merge the results.
460    FanOut,
461    /// First completed member wins; losers are cancel-signalled.
462    Race,
463    /// Accept the first `k` completions and resolve them into one outcome.
464    Quorum,
465}
466
467/// What a fan-out does when one member fails terminally (R0.7 wave 3).
468/// There is no third option on purpose: "retry the member" is the queue's
469/// retry taxonomy, already expressed on the member task itself.
470#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
471#[serde(rename_all = "snake_case")]
472pub enum MemberFailurePolicy {
473    /// Any terminal member failure fails the whole pattern; the remaining
474    /// members are cancel-signalled.
475    FailFast,
476    /// Completed members' results are merged; missing members are journaled
477    /// in the outcome's dispositions. The pattern still completes.
478    Partial,
479}
480
481/// The terminal settlement of one member, as observed by the pattern from
482/// the member's durable task record (R0.7 wave 3). This is the evidence
483/// vocabulary of [`CoordinationOutcome::members`] — a member that crashed
484/// mid-pattern surfaces as `Failed` (retry budget exhausted) or `Dead`
485/// (lease expired past its deadline), never as silence.
486#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
487#[serde(rename_all = "snake_case")]
488pub enum MemberSettlement {
489    /// The member task settled `completed` with a result.
490    Completed,
491    /// The member task settled `failed` (terminal, retry budget exhausted or
492    /// explicitly non-retryable).
493    Failed,
494    /// The member task settled `cancelled` (cancel-signalled by the pattern,
495    /// by the delegator, or by its deadline).
496    Cancelled,
497    /// The member task landed in the dead-letter queue.
498    Dead,
499}
500
501/// The settled status of a whole coordination (R0.7 wave 3). Outcome-only:
502/// a pattern in flight has no `CoordinationOutcome` yet, so there is no
503/// `Open` variant to drift out of sync with reality.
504#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
505#[serde(rename_all = "snake_case")]
506pub enum CoordinationStatus {
507    /// The pattern produced its result (a member result, a merge, a winner,
508    /// or a resolver decision).
509    Completed,
510    /// The pattern failed: the delegate failed, a fail-fast fan-out member
511    /// failed, or every race candidate failed.
512    Failed,
513    /// The pattern was cancelled before it could settle.
514    Cancelled,
515    /// Quorum only: fewer than `k` members can possibly complete, so the
516    /// threshold is unreachable. The threshold is never silently downgraded
517    /// — `k` in the journaled contract is the `k` that was enforced.
518    Unreachable,
519}
520
521/// A narrow slice of context handed to a member alongside its input (R0.7
522/// wave 3). Grants only ever **narrow** what the target agent already
523/// declared in its manifest — a delegation must never become a privilege
524/// escalation path. The server rejects a widening grant at submission.
525#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
526pub struct ContextGrant {
527    /// The state scopes the member may touch for this delegation; each must
528    /// be a subset of the target manifest's declared scopes.
529    #[serde(default, skip_serializing_if = "Vec::is_empty")]
530    pub scopes: Vec<StateScope>,
531    /// Named context channels (team thread ids, KV prefixes) the member may
532    /// read. Free-form strings: channels are addressing, not taxonomy.
533    #[serde(default, skip_serializing_if = "Vec::is_empty")]
534    pub channels: Vec<String>,
535}
536
537impl ContextGrant {
538    /// `true` when every granted scope is declared by the target manifest —
539    /// the only direction a grant may point. Checked at submission; a
540    /// widening grant is a 400, not a runtime surprise.
541    pub fn narrows(&self, declared: &[StateScope]) -> bool {
542        self.scopes.iter().all(|scope| declared.contains(scope))
543    }
544}
545
546fn default_effect_non_idempotent() -> Effect {
547    Effect::NonIdempotent
548}
549
550/// Sparse-wire helper for `bool` fields whose meaningful value is `true`:
551/// `false` is the default and is never serialized.
552fn is_false(value: &bool) -> bool {
553    !*value
554}
555
556/// One member assignment inside a pattern (R0.7 wave 3): which agent, pinned
557/// to which exact manifest version, running which declared message kind,
558/// over which input. There is deliberately **no caller-supplied idempotency
559/// key** — the runtime derives `coordination:{coordination_id}:{member}` so
560/// a retried submission converges on the same member task instead of
561/// forking duplicates.
562#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
563pub struct Delegation {
564    /// The member's name inside this pattern. Labels dispositions, member
565    /// task ids, and trace nodes; unique within one contract.
566    pub member: String,
567    /// The target agent's id (external form; the server namespaces it per
568    /// tenant like every other id).
569    pub agent_id: String,
570    /// The exact manifest version the delegation is pinned to. The server
571    /// refuses anything but an exact match against the registered record —
572    /// the agent-level form of R0.6's worker version pinning.
573    pub manifest_version: String,
574    /// The message kind submitted to the member's mailbox; must be declared
575    /// in the pinned manifest's `accepts`.
576    pub kind: String,
577    /// The member's input, inline or referenced per the journal's payload
578    /// discipline.
579    pub input: PayloadRef,
580    /// The declared effect class of the work. Defaults to
581    /// [`Effect::NonIdempotent`] — the safe assumption, and the one that
582    /// makes the race gate fail closed: an undeclared effect is never
583    /// eligible to race.
584    #[serde(default = "default_effect_non_idempotent")]
585    pub effect: Effect,
586    /// An optional member deadline. Composed with the target agent's budget
587    /// deadline at submission (the earlier wins), exactly like direct
588    /// mailbox sends.
589    #[serde(default, skip_serializing_if = "Option::is_none")]
590    pub deadline: Option<DateTime<Utc>>,
591}
592
593/// `delegate` — hand one task to one member (R0.7 wave 3). The member's
594/// settlement is the pattern's settlement; with `handoff`, the journaled
595/// outcome doubles as the delegator's handoff record.
596#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
597pub struct DelegateContract {
598    /// The single member assignment.
599    pub delegate: Delegation,
600    /// The context granted to the member. May only narrow the target's
601    /// declared scopes ([`ContextGrant::narrows`]).
602    #[serde(default, skip_serializing_if = "Option::is_none")]
603    pub context: Option<ContextGrant>,
604    /// The contract the member's result must satisfy. Carried on the wire in
605    /// wave 3; contract enforcement on the result lands with schema
606    /// validation in a later wave.
607    #[serde(default, skip_serializing_if = "Option::is_none")]
608    pub result_contract: Option<ArtifactContract>,
609    /// When `true`, the outcome is journaled as the delegator's handoff
610    /// record — the delegate's result stands in for the delegator's own
611    /// next step. Sparse wire: absent means `false`.
612    #[serde(default, skip_serializing_if = "is_false")]
613    pub handoff: bool,
614}
615
616/// `fan_out` — run members under a bounded in-flight window and merge the
617/// completed results in deterministic order (R0.7 wave 3).
618#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
619pub struct FanOutContract {
620    /// The member assignments. Member names must be unique.
621    pub members: Vec<Delegation>,
622    /// The in-flight window: at most this many member tasks are
623    /// unsubmitted-or-running at once. Must be ≥ 1 — the window is the
624    /// backpressure guarantee, and a zero window would deadlock the pattern.
625    pub max_in_flight: u32,
626    /// What one terminal member failure does to the whole pattern.
627    pub on_member_failure: MemberFailurePolicy,
628}
629
630/// `race` — first completed candidate wins; losers are cancel-signalled
631/// (R0.7 wave 3). Every candidate must declare a freely-repeatable effect:
632/// a loser may be cancelled at any point, so any candidate that is not safe
633/// to abandon makes the whole pattern unsafe. That is a submission-time
634/// gate, not a runtime check — see [`RaceContract::validate`].
635#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
636pub struct RaceContract {
637    /// The candidates. Member names must be unique; every candidate's
638    /// `effect` must satisfy [`Effect::is_freely_repeatable`].
639    pub candidates: Vec<Delegation>,
640}
641
642/// How a quorum resolves its first `k` accepted results into one outcome
643/// (R0.7 wave 3).
644#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
645#[serde(tag = "resolver", rename_all = "snake_case")]
646pub enum QuorumResolver {
647    /// Strict majority over byte-identical outputs: one output must collect
648    /// more than half of the accepted votes, else the outcome is
649    /// no-majority (decided = `false`).
650    MajorityEqual,
651    /// The accepted outputs as an array, in deterministic (member task-id)
652    /// order — the caller's own policy consumes the k-tuple.
653    FirstK,
654    /// A named custom resolver. The wire shape is pinned for a later
655    /// resolver registry; wave 3 rejects it at submission — shipping the
656    /// shape without the mechanism keeps the contract stable without
657    /// promising semantics the runtime cannot yet honor.
658    Custom {
659        /// The registry name of the resolver.
660        name: String,
661    },
662}
663
664/// `quorum` — accept the first `k` completions and resolve them into one
665/// outcome (R0.7 wave 3). The threshold is a hard floor: if fewer than `k`
666/// members can still complete, the pattern settles
667/// [`CoordinationStatus::Unreachable`] — it fails open with the evidence
668/// journaled, and never silently downgrades `k`.
669#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
670pub struct QuorumContract {
671    /// The member assignments. Member names must be unique.
672    pub members: Vec<Delegation>,
673    /// The acceptance threshold: the pattern settles as soon as this many
674    /// members have completed. Must be within `1..=members.len()`.
675    pub threshold: u32,
676    /// How the accepted results become the outcome.
677    pub resolver: QuorumResolver,
678}
679
680/// A rejection of a coordination contract at validation time (R0.7 wave 3).
681/// Every variant maps to a 400 at submission: these are contract violations,
682/// not runtime failures, and they must be caught before a single member
683/// task exists.
684#[derive(Debug, Clone, PartialEq, Eq, Error)]
685pub enum CoordinationViolation {
686    /// A race candidate declared an effect that is not freely repeatable.
687    #[error(
688        "race candidate '{member}' declares effect '{effect}', which is not freely \
689         repeatable: a race loser may be cancelled at any point, so every candidate \
690         must be safe to abandon"
691    )]
692    RaceEffectNotFreelyRepeatable {
693        /// The offending member name.
694        member: String,
695        /// The declared effect's wire name.
696        effect: String,
697    },
698    /// A pattern was declared with no members.
699    #[error("{pattern} declares no members")]
700    EmptyMembers {
701        /// The pattern's wire name.
702        pattern: String,
703    },
704    /// Two members share a name inside one contract.
705    #[error(
706        "{pattern} declares member '{member}' twice; member names label task ids \
707             and dispositions and must be unique within a pattern"
708    )]
709    DuplicateMember {
710        /// The pattern's wire name.
711        pattern: String,
712        /// The duplicated member name.
713        member: String,
714    },
715    /// A fan-out window of zero.
716    #[error(
717        "fan-out max_in_flight must be at least 1: the window is the backpressure \
718             guarantee, and a zero window can never make progress"
719    )]
720    MaxInFlightZero,
721    /// A quorum threshold outside `1..=members.len()`.
722    #[error(
723        "quorum threshold {threshold} is out of range 1..={members}: the threshold \
724             is a hard floor and is never silently clamped"
725    )]
726    QuorumThresholdOutOfRange {
727        /// The declared threshold.
728        threshold: u32,
729        /// The number of declared members.
730        members: usize,
731    },
732    /// A custom quorum resolver, which wave 3 does not honor.
733    #[error(
734        "custom quorum resolver '{name}' is not supported in wave 3: resolvers are \
735             majority_equal and first_k; the custom wire shape is pinned for a later \
736             resolver registry"
737    )]
738    CustomResolverUnsupported {
739        /// The rejected registry name.
740        name: String,
741    },
742}
743
744fn effect_wire_name(effect: Effect) -> &'static str {
745    match effect {
746        Effect::Pure => "pure",
747        Effect::ReadOnly => "read_only",
748        Effect::Idempotent => "idempotent",
749        Effect::Compensatable => "compensatable",
750        Effect::NonIdempotent => "non_idempotent",
751    }
752}
753
754/// Returns `true` when `members` contains a duplicate `member` name. Used by
755/// every multi-member validator — member names key dispositions and
756/// deterministic task ids, so a duplicate would make the evidence
757/// ambiguous.
758fn duplicate_member(members: &[Delegation]) -> Option<&str> {
759    for (i, m) in members.iter().enumerate() {
760        if members[..i]
761            .iter()
762            .any(|earlier| earlier.member == m.member)
763        {
764            return Some(m.member.as_str());
765        }
766    }
767    None
768}
769
770impl RaceContract {
771    /// The race effect gate, enforced at submission: every candidate must be
772    /// freely repeatable. This is the pattern's whole safety argument — a
773    /// loser is cancel-signalled at an arbitrary point, so a candidate that
774    /// cannot be safely abandoned (a `NonIdempotent` charge, a
775    /// `Compensatable` write) must never enter a race.
776    pub fn validate(&self) -> Result<(), CoordinationViolation> {
777        if self.candidates.is_empty() {
778            return Err(CoordinationViolation::EmptyMembers {
779                pattern: "race".to_string(),
780            });
781        }
782        if let Some(member) = duplicate_member(&self.candidates) {
783            return Err(CoordinationViolation::DuplicateMember {
784                pattern: "race".to_string(),
785                member: member.to_string(),
786            });
787        }
788        for candidate in &self.candidates {
789            if !candidate.effect.is_freely_repeatable() {
790                return Err(CoordinationViolation::RaceEffectNotFreelyRepeatable {
791                    member: candidate.member.clone(),
792                    effect: effect_wire_name(candidate.effect).to_string(),
793                });
794            }
795        }
796        Ok(())
797    }
798}
799
800impl FanOutContract {
801    /// Structural validation enforced at submission: a non-empty member set
802    /// with unique names and a window of at least one.
803    pub fn validate(&self) -> Result<(), CoordinationViolation> {
804        if self.members.is_empty() {
805            return Err(CoordinationViolation::EmptyMembers {
806                pattern: "fan_out".to_string(),
807            });
808        }
809        if let Some(member) = duplicate_member(&self.members) {
810            return Err(CoordinationViolation::DuplicateMember {
811                pattern: "fan_out".to_string(),
812                member: member.to_string(),
813            });
814        }
815        if self.max_in_flight == 0 {
816            return Err(CoordinationViolation::MaxInFlightZero);
817        }
818        Ok(())
819    }
820}
821
822impl QuorumContract {
823    /// Structural validation enforced at submission: a non-empty member set
824    /// with unique names, a threshold inside `1..=members.len()`, and a
825    /// resolver wave 3 can honor. The threshold is checked exactly and never
826    /// clamped — a silent clamp would change the pattern's semantics without
827    /// a journaled decision.
828    pub fn validate(&self) -> Result<(), CoordinationViolation> {
829        if self.members.is_empty() {
830            return Err(CoordinationViolation::EmptyMembers {
831                pattern: "quorum".to_string(),
832            });
833        }
834        if let Some(member) = duplicate_member(&self.members) {
835            return Err(CoordinationViolation::DuplicateMember {
836                pattern: "quorum".to_string(),
837                member: member.to_string(),
838            });
839        }
840        if self.threshold == 0 || self.threshold as usize > self.members.len() {
841            return Err(CoordinationViolation::QuorumThresholdOutOfRange {
842                threshold: self.threshold,
843                members: self.members.len(),
844            });
845        }
846        if let QuorumResolver::Custom { name } = &self.resolver {
847            return Err(CoordinationViolation::CustomResolverUnsupported { name: name.clone() });
848        }
849        Ok(())
850    }
851}
852
853/// One vote group in a majority tally: an output and how many accepted
854/// members produced it byte-identically (R0.7 wave 3).
855#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
856pub struct QuorumTally {
857    /// The output the group agrees on.
858    pub output: Value,
859    /// How many of the accepted members produced it.
860    pub votes: u32,
861}
862
863/// The result of resolving a quorum's accepted outputs (R0.7 wave 3).
864/// Returned by [`resolve_quorum`]; the server converts it into the
865/// journaled [`QuorumResolverRecord`].
866#[derive(Debug, Clone, PartialEq)]
867pub enum QuorumOutcome {
868    /// Majority resolved: one output collected a strict majority.
869    Decided {
870        /// The winning output.
871        output: Value,
872    },
873    /// First-K resolution: the accepted outputs in deterministic order.
874    FirstK {
875        /// The k accepted outputs, ordered by member task id.
876        outputs: Vec<Value>,
877    },
878    /// No output reached a strict majority. The pattern still completes —
879    /// the no-majority evidence is the outcome.
880    NoMajority {
881        /// The full tally, sorted by votes (desc) then output bytes (asc).
882        tallies: Vec<QuorumTally>,
883    },
884}
885
886/// Resolve a quorum's accepted outputs into an outcome (R0.7 wave 3).
887///
888/// `accepted` is `(member task id, output)` pairs; the function sorts them
889/// by task id first, so the result is deterministic regardless of the order
890/// the caller observed completions in — replaying the same journal always
891/// reproduces the same resolution. Pure: no I/O, no clock, no randomness.
892pub fn resolve_quorum(
893    resolver: &QuorumResolver,
894    accepted: &[(String, Value)],
895) -> Result<QuorumOutcome, CoordinationViolation> {
896    let mut accepted: Vec<&(String, Value)> = accepted.iter().collect();
897    accepted.sort_by(|a, b| a.0.cmp(&b.0));
898    match resolver {
899        QuorumResolver::FirstK => Ok(QuorumOutcome::FirstK {
900            outputs: accepted
901                .iter()
902                .map(|(_, output)| (*output).clone())
903                .collect(),
904        }),
905        QuorumResolver::MajorityEqual => {
906            // Group by byte-identical output. serde_json::Value equality is
907            // structural (object key order is irrelevant), which is exactly
908            // the "same answer" a voter means.
909            let mut tallies: Vec<QuorumTally> = Vec::new();
910            for (_, output) in &accepted {
911                match tallies.iter_mut().find(|t| t.output == *output) {
912                    Some(tally) => tally.votes += 1,
913                    None => tallies.push(QuorumTally {
914                        output: (*output).clone(),
915                        votes: 1,
916                    }),
917                }
918            }
919            // Deterministic evidence order: most votes first, ties broken by
920            // the output's serialized bytes.
921            tallies.sort_by(|a, b| {
922                b.votes
923                    .cmp(&a.votes)
924                    .then_with(|| a.output.to_string().cmp(&b.output.to_string()))
925            });
926            let total = accepted.len() as u32;
927            match tallies.first() {
928                Some(winner) if winner.votes * 2 > total => Ok(QuorumOutcome::Decided {
929                    output: winner.output.clone(),
930                }),
931                _ => Ok(QuorumOutcome::NoMajority { tallies }),
932            }
933        }
934        QuorumResolver::Custom { name } => {
935            Err(CoordinationViolation::CustomResolverUnsupported { name: name.clone() })
936        }
937    }
938}
939
940/// Merge a fan-out's completed member results into the pattern result (R0.7
941/// wave 3). `results` is `(member task id, output)` pairs for the
942/// **completed** members; the merge orders them by task id, so the merged
943/// array is byte-deterministic no matter which order members finished in.
944/// Missing members are not in the array at all — they are journaled in the
945/// outcome's dispositions instead, which is where partial failure evidence
946/// belongs.
947pub fn merge_fan_out(results: &[(String, Value)]) -> Vec<Value> {
948    let mut sorted: Vec<&(String, Value)> = results.iter().collect();
949    sorted.sort_by(|a, b| a.0.cmp(&b.0));
950    sorted
951        .into_iter()
952        .map(|(_, output)| output.clone())
953        .collect()
954}
955
956/// One member's terminal evidence inside a settled coordination (R0.7 wave
957/// 3). Derived from the member's durable task record — never from an
958/// in-memory observation — so a server restart recomputes the same
959/// disposition from the same store.
960#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
961pub struct MemberDisposition {
962    /// The member name from the contract.
963    pub member: String,
964    /// The member's deterministic task id — the correlation key into the
965    /// task queue's own evidence (and the DLQ, when `Dead`).
966    pub task_id: String,
967    /// How the member settled.
968    pub settlement: MemberSettlement,
969    /// The member's result, when it completed.
970    #[serde(default, skip_serializing_if = "Option::is_none")]
971    pub result: Option<PayloadRef>,
972    /// The failure's error class, when it failed or died.
973    #[serde(default, skip_serializing_if = "Option::is_none")]
974    pub error_class: Option<ErrorClass>,
975    /// The failure's message, when it failed or died.
976    #[serde(default, skip_serializing_if = "Option::is_none")]
977    pub error: Option<String>,
978    /// The token usage the member reported on settlement, when any.
979    #[serde(default, skip_serializing_if = "Option::is_none")]
980    pub tokens: Option<Usage>,
981    /// The cost the member reported on settlement, when any.
982    #[serde(default, skip_serializing_if = "Option::is_none")]
983    pub cost_usd: Option<f64>,
984}
985
986/// The journaled record of how a quorum was resolved (R0.7 wave 3): the
987/// resolver, the exact inputs it saw, and what it decided. Carried on
988/// [`CoordinationOutcome::resolver`] so the decision is auditable without
989/// re-running the resolution.
990#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
991pub struct QuorumResolverRecord {
992    /// The resolver that ran.
993    pub resolver: QuorumResolver,
994    /// The accepted outputs, in the deterministic order the resolver saw
995    /// them (member task-id order).
996    #[serde(default, skip_serializing_if = "Vec::is_empty")]
997    pub inputs: Vec<Value>,
998    /// The resolved output. `None` under no-majority: the inputs and the
999    /// `decided` flag are the evidence.
1000    #[serde(default, skip_serializing_if = "Option::is_none")]
1001    pub output: Option<Value>,
1002    /// Whether the resolver reached a decision (`false` = no-majority).
1003    pub decided: bool,
1004}
1005
1006/// The settled outcome of a coordination (R0.7 wave 3) — the payload of the
1007/// `CoordinationEnd` journal event and of the `coordination_result` message
1008/// delivered to the delegator's mailbox. One shape for all four patterns:
1009/// the delegator consumes one contract no matter which pattern it started.
1010#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1011pub struct CoordinationOutcome {
1012    /// The pattern's id (external form).
1013    pub coordination_id: String,
1014    /// Which pattern ran.
1015    pub pattern: CoordinationKind,
1016    /// How the pattern settled.
1017    pub status: CoordinationStatus,
1018    /// The pattern's result: the delegate's result, the fan-out merge, the
1019    /// race winner's result, or the quorum resolution. Absent when the
1020    /// pattern failed, was cancelled, or reached no decision.
1021    #[serde(default, skip_serializing_if = "Option::is_none")]
1022    pub result: Option<PayloadRef>,
1023    /// Every member's terminal evidence, in contract declaration order —
1024    /// including members that never produced a result, which is the point:
1025    /// missing members are journaled, never silent.
1026    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1027    pub members: Vec<MemberDisposition>,
1028    /// Total tokens spent on work the pattern discarded (race losers,
1029    /// cancelled members), when the members reported usage. The pattern's
1030    /// waste accounting is part of the outcome, not a side channel.
1031    #[serde(default, skip_serializing_if = "Option::is_none")]
1032    pub wasted_tokens: Option<u64>,
1033    /// Total reported cost of discarded work, when reported.
1034    #[serde(default, skip_serializing_if = "Option::is_none")]
1035    pub wasted_cost_usd: Option<f64>,
1036    /// The quorum resolution record, present only for the quorum pattern.
1037    #[serde(default, skip_serializing_if = "Option::is_none")]
1038    pub resolver: Option<QuorumResolverRecord>,
1039}
1040
1041/// The typed pattern declaration a delegator submits (R0.7 wave 3). The
1042/// `pattern` tag is the wire discriminator; each variant carries exactly
1043/// the contract of one pattern. The delegate variant is boxed: its contract
1044/// embeds a [`Delegation`] with an optional [`ContextGrant`], which would
1045/// otherwise make every variant pay the largest variant's size.
1046#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1047#[serde(tag = "pattern", rename_all = "snake_case")]
1048pub enum CoordinationContract {
1049    /// See [`DelegateContract`].
1050    Delegate(Box<DelegateContract>),
1051    /// See [`FanOutContract`].
1052    FanOut(FanOutContract),
1053    /// See [`RaceContract`].
1054    Race(RaceContract),
1055    /// See [`QuorumContract`].
1056    Quorum(QuorumContract),
1057}
1058
1059impl CoordinationContract {
1060    /// Which pattern this contract declares.
1061    pub fn kind(&self) -> CoordinationKind {
1062        match self {
1063            Self::Delegate(_) => CoordinationKind::Delegate,
1064            Self::FanOut(_) => CoordinationKind::FanOut,
1065            Self::Race(_) => CoordinationKind::Race,
1066            Self::Quorum(_) => CoordinationKind::Quorum,
1067        }
1068    }
1069
1070    /// Every member assignment in declaration order — one for delegate, all
1071    /// for the multi-member patterns.
1072    pub fn members(&self) -> Vec<&Delegation> {
1073        match self {
1074            Self::Delegate(c) => vec![&c.delegate],
1075            Self::FanOut(c) => c.members.iter().collect(),
1076            Self::Race(c) => c.candidates.iter().collect(),
1077            Self::Quorum(c) => c.members.iter().collect(),
1078        }
1079    }
1080
1081    /// The structural validation every pattern runs at submission. Dispatch
1082    /// lives here so the server has exactly one gate to call.
1083    pub fn validate(&self) -> Result<(), CoordinationViolation> {
1084        match self {
1085            Self::Delegate(_) => Ok(()),
1086            Self::FanOut(c) => c.validate(),
1087            Self::Race(c) => c.validate(),
1088            Self::Quorum(c) => c.validate(),
1089        }
1090    }
1091}
1092
1093/// The payload of a member task the pattern submits (R0.7 wave 3). This is
1094/// the detection gate for the settle hooks: when any task settles, the
1095/// server parses its payload as a `CoordinationMessage` and, only if a
1096/// scoped coordination record matches, drives the pattern forward. Ordinary
1097/// queue tasks never parse — the pattern field and member field together
1098/// make a false positive a deliberate act, not an accident.
1099#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1100pub struct CoordinationMessage {
1101    /// The pattern this task belongs to (external id form).
1102    pub coordination_id: String,
1103    /// The member name this task executes.
1104    pub member: String,
1105    /// Which pattern is driving, denormalized onto the message so a reader
1106    /// of the task queue can classify member work without a record lookup.
1107    pub pattern: CoordinationKind,
1108    /// The member's input, from the contract.
1109    pub input: PayloadRef,
1110    /// The context grant handed to the member, when the pattern declares one.
1111    #[serde(default, skip_serializing_if = "Option::is_none")]
1112    pub context: Option<ContextGrant>,
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117    use super::*;
1118    use serde_json::json;
1119
1120    fn sample_manifest() -> CapabilityManifest {
1121        let mut manifest = CapabilityManifest::new("researcher", "researcher/1.4.0");
1122        manifest.accepts.insert(
1123            "summarize".into(),
1124            ArtifactContract {
1125                kind: "application/json".into(),
1126                max_bytes: Some(65_536),
1127                schema: Some(json!({
1128                    "$schema": "https://json-schema.org/draft/2020-12/schema",
1129                    "type": "object",
1130                    "properties": {"topic": {"type": "string"}},
1131                    "required": ["topic"],
1132                })),
1133            },
1134        );
1135        manifest.scopes = vec![StateScope::Private, StateScope::Team];
1136        manifest.budget = Some(AgentBudget {
1137            max_tokens: Some(250_000),
1138            max_cost_usd: Some(1.50),
1139            deadline: DateTime::<Utc>::from_timestamp_millis(1_800_000_000_000),
1140        });
1141        manifest
1142    }
1143
1144    #[test]
1145    fn agent_id_derives_mailbox_and_thread_addresses() {
1146        let id = AgentId::new("acme/researcher-7");
1147        assert_eq!(id.as_str(), "acme/researcher-7");
1148        assert_eq!(id.mailbox_recipient(), "agent:acme/researcher-7");
1149        // The thread convention mirrors the mailbox address — one name, two
1150        // views (queue addressing, checkpoint log).
1151        assert_eq!(id.thread_id(), "agent:acme/researcher-7");
1152        // Transparent wire shape: the bare string, no wrapper object.
1153        assert_eq!(
1154            serde_json::to_value(&id).unwrap(),
1155            json!("acme/researcher-7")
1156        );
1157        assert_eq!(id.to_string(), "acme/researcher-7");
1158    }
1159
1160    #[test]
1161    fn recipient_parsing_strips_only_the_agent_prefix() {
1162        assert_eq!(
1163            agent_id_from_recipient("agent:researcher-7"),
1164            Some("researcher-7")
1165        );
1166        assert_eq!(agent_id_from_recipient("pool-default"), None);
1167        assert_eq!(agent_id_from_recipient("agent:"), Some(""));
1168        // A prefix alone is not a mailbox address ("agents:x" is not one).
1169        assert_eq!(agent_id_from_recipient("agents:researcher-7"), None);
1170    }
1171
1172    #[test]
1173    fn state_scope_serde_names_are_snake_case() {
1174        for (scope, name) in [
1175            (StateScope::Private, "private"),
1176            (StateScope::Team, "team"),
1177            (StateScope::User, "user"),
1178            (StateScope::Tenant, "tenant"),
1179        ] {
1180            assert_eq!(serde_json::to_value(scope).unwrap(), json!(name));
1181            assert_eq!(
1182                serde_json::from_value::<StateScope>(json!(name)).unwrap(),
1183                scope
1184            );
1185        }
1186        assert!(serde_json::from_value::<StateScope>(json!("global")).is_err());
1187    }
1188
1189    #[test]
1190    fn manifest_serde_roundtrip_and_sparse_wire_shape() {
1191        let manifest = sample_manifest();
1192        let back: CapabilityManifest =
1193            serde_json::from_str(&serde_json::to_string(&manifest).unwrap()).unwrap();
1194        assert_eq!(manifest, back);
1195
1196        // A minimal manifest stays minimal on the wire: only the two
1197        // required keys, nothing null or empty — pre-R0.7-shaped readers see
1198        // no new keys at all.
1199        let minimal = CapabilityManifest::new("researcher", "researcher/1.4.0");
1200        let value = serde_json::to_value(&minimal).unwrap();
1201        assert_eq!(
1202            value,
1203            json!({"agent_kind": "researcher", "manifest_version": "researcher/1.4.0"})
1204        );
1205
1206        // And the minimal shape — what the smallest client writes — loads
1207        // with honest defaults: nothing accepted, no scopes, no budget.
1208        let back: CapabilityManifest = serde_json::from_value(value).unwrap();
1209        assert_eq!(back, minimal);
1210        assert!(back.accepts_kind("summarize").is_none());
1211    }
1212
1213    #[test]
1214    fn manifest_lookup_finds_only_declared_kinds() {
1215        let manifest = sample_manifest();
1216        let contract = manifest.accepts_kind("summarize").expect("declared kind");
1217        assert_eq!(contract.kind, "application/json");
1218        assert!(contract.schema.is_some());
1219        assert!(manifest.accepts_kind("delete_everything").is_none());
1220    }
1221
1222    #[test]
1223    fn artifact_contract_schema_field_is_additive() {
1224        // A pre-R0.7 contract — exactly the shape the R0.6 golden pins —
1225        // deserializes with the schema unset.
1226        let r06_shape = json!({"kind": "application/json", "max_bytes": 65536});
1227        let contract: ArtifactContract = serde_json::from_value(r06_shape).unwrap();
1228        assert_eq!(contract.schema, None);
1229        // Unset: absent from the wire, so R0.6 readers see no shape change.
1230        assert_eq!(
1231            serde_json::to_value(&contract).unwrap(),
1232            json!({"kind": "application/json", "max_bytes": 65536})
1233        );
1234
1235        // Set: carried as the schema document itself, surviving the
1236        // round-trip.
1237        let with_schema = ArtifactContract {
1238            kind: "application/json".into(),
1239            max_bytes: None,
1240            schema: Some(json!({"type": "object"})),
1241        };
1242        let back: ArtifactContract =
1243            serde_json::from_str(&serde_json::to_string(&with_schema).unwrap()).unwrap();
1244        assert_eq!(with_schema, back);
1245    }
1246
1247    #[test]
1248    fn agent_event_kinds_stay_additive_to_the_closed_enum() {
1249        use crate::record::RunEventKind;
1250        // The R0.7 variants serialize snake_case like every event kind
1251        // before them, and pre-R0.7 kinds deserialize unchanged — old
1252        // journals keep loading (the rule R0.6's EffectReceipt followed).
1253        for (kind, name) in [
1254            (RunEventKind::AgentSpawn, "agent_spawn"),
1255            (RunEventKind::AgentExit, "agent_exit"),
1256            (RunEventKind::MailboxSend, "mailbox_send"),
1257            (RunEventKind::MailboxReceive, "mailbox_receive"),
1258            (RunEventKind::SupervisionEvent, "supervision_event"),
1259            (RunEventKind::CoordinationStart, "coordination_start"),
1260            (RunEventKind::CoordinationEnd, "coordination_end"),
1261        ] {
1262            assert_eq!(serde_json::to_value(kind).unwrap(), json!(name));
1263            assert_eq!(
1264                serde_json::from_value::<RunEventKind>(json!(name)).unwrap(),
1265                kind
1266            );
1267        }
1268        assert_eq!(
1269            serde_json::from_value::<RunEventKind>(json!("model_call")).unwrap(),
1270            RunEventKind::ModelCall
1271        );
1272        assert!(serde_json::from_value::<RunEventKind>(json!("agent_magic")).is_err());
1273    }
1274
1275    #[test]
1276    fn restart_policy_and_trigger_serde_names_are_snake_case() {
1277        for (policy, name) in [
1278            (RestartPolicy::Permanent, "permanent"),
1279            (RestartPolicy::Transient, "transient"),
1280            (RestartPolicy::Temporary, "temporary"),
1281        ] {
1282            assert_eq!(serde_json::to_value(policy).unwrap(), json!(name));
1283            assert_eq!(
1284                serde_json::from_value::<RestartPolicy>(json!(name)).unwrap(),
1285                policy
1286            );
1287        }
1288        for (trigger, name) in [
1289            (SupervisionTrigger::TurnFailed, "turn_failed"),
1290            (SupervisionTrigger::DeadlineBreached, "deadline_breached"),
1291            (SupervisionTrigger::ManualRestart, "manual_restart"),
1292        ] {
1293            assert_eq!(serde_json::to_value(trigger).unwrap(), json!(name));
1294            assert_eq!(
1295                serde_json::from_value::<SupervisionTrigger>(json!(name)).unwrap(),
1296                trigger
1297            );
1298        }
1299        assert!(serde_json::from_value::<RestartPolicy>(json!("always")).is_err());
1300    }
1301
1302    #[test]
1303    fn allows_restart_after_maps_the_otp_vocabulary_onto_error_class() {
1304        let permanent = SupervisionPolicy::new(RestartPolicy::Permanent, 3, 60_000);
1305        let transient = SupervisionPolicy::new(RestartPolicy::Transient, 3, 60_000);
1306        let temporary = SupervisionPolicy::new(RestartPolicy::Temporary, 3, 60_000);
1307
1308        // Permanent restarts on any termination, including cancellation.
1309        assert!(permanent.allows_restart_after(Some(ErrorClass::Transient)));
1310        assert!(permanent.allows_restart_after(Some(ErrorClass::Cancelled)));
1311        assert!(permanent.allows_restart_after(None));
1312        // Transient restarts only on abnormal termination: cancellation
1313        // (operator or deadline clock) is control flow, not a crash.
1314        assert!(transient.allows_restart_after(Some(ErrorClass::Timeout)));
1315        assert!(!transient.allows_restart_after(Some(ErrorClass::Cancelled)));
1316        assert!(!transient.allows_restart_after(None));
1317        // Temporary never restarts after a failure.
1318        assert!(!temporary.allows_restart_after(Some(ErrorClass::Unknown)));
1319        assert!(!temporary.allows_restart_after(None));
1320    }
1321
1322    #[test]
1323    fn supervision_policy_wire_shape_is_sparse_and_additive() {
1324        // Root policy: no supervisor key on the wire at all.
1325        let root = SupervisionPolicy::new(RestartPolicy::Permanent, 3, 60_000);
1326        assert_eq!(
1327            serde_json::to_value(&root).unwrap(),
1328            json!({"restart": "permanent", "intensity": 3, "period_ms": 60000})
1329        );
1330        let back: SupervisionPolicy =
1331            serde_json::from_str(&serde_json::to_string(&root).unwrap()).unwrap();
1332        assert_eq!(root, back);
1333
1334        let with_supervisor = SupervisionPolicy {
1335            supervisor: Some("boss".into()),
1336            ..root.clone()
1337        };
1338        assert_eq!(
1339            serde_json::to_value(&with_supervisor).unwrap(),
1340            json!({
1341                "restart": "permanent",
1342                "intensity": 3,
1343                "period_ms": 60000,
1344                "supervisor": "boss",
1345            })
1346        );
1347
1348        // A minimal manifest — the pre-wave-2 shape — keeps deserializing
1349        // with the policy unset, and stays minimal on the wire.
1350        let minimal = CapabilityManifest::new("researcher", "researcher/1.4.0");
1351        assert_eq!(minimal.supervision, None);
1352        assert_eq!(
1353            serde_json::to_value(&minimal).unwrap(),
1354            json!({"agent_kind": "researcher", "manifest_version": "researcher/1.4.0"})
1355        );
1356    }
1357
1358    #[test]
1359    fn attempt_history_and_escalation_notice_round_trip() {
1360        let t0 = DateTime::<Utc>::from_timestamp_millis(1_800_000_000_000).unwrap();
1361        let attempts = vec![
1362            SupervisionAttempt {
1363                ordinal: 1,
1364                trigger: SupervisionTrigger::TurnFailed,
1365                error_class: Some(ErrorClass::Transient),
1366                message: "model timed out".into(),
1367                task_id: Some("task-1".into()),
1368                at: t0,
1369            },
1370            // A manual restart carries no failure class and no task —
1371            // both keys vanish from the wire.
1372            SupervisionAttempt {
1373                ordinal: 2,
1374                trigger: SupervisionTrigger::ManualRestart,
1375                error_class: None,
1376                message: "operator reset".into(),
1377                task_id: None,
1378                at: t0 + chrono::Duration::seconds(5),
1379            },
1380        ];
1381        let manual = serde_json::to_value(&attempts[1]).unwrap();
1382        // Sparse wire: unset fields are absent, not null.
1383        assert!(manual.get("error_class").is_none());
1384        assert!(manual.get("task_id").is_none());
1385
1386        let notice = EscalationNotice {
1387            agent_id: "looper".into(),
1388            policy: SupervisionPolicy {
1389                supervisor: Some("boss".into()),
1390                ..SupervisionPolicy::new(RestartPolicy::Permanent, 2, 60_000)
1391            },
1392            attempts,
1393            escalated_at: t0 + chrono::Duration::seconds(9),
1394        };
1395        let back: EscalationNotice =
1396            serde_json::from_str(&serde_json::to_string(&notice).unwrap()).unwrap();
1397        assert_eq!(notice, back);
1398        // The attempt history survives the round-trip intact — ordinals,
1399        // classes, task ids: the escalation's evidence is the point.
1400        assert_eq!(back.attempts.len(), 2);
1401        assert_eq!(back.attempts[0].ordinal, 1);
1402        assert_eq!(back.attempts[0].error_class, Some(ErrorClass::Transient));
1403        assert_eq!(back.attempts[0].task_id.as_deref(), Some("task-1"));
1404    }
1405
1406    // ---------------------------------------------------------------------
1407    // Coordination patterns (wave 3)
1408    // ---------------------------------------------------------------------
1409
1410    fn delegation(member: &str, effect: Effect) -> Delegation {
1411        Delegation {
1412            member: member.into(),
1413            agent_id: format!("agent-{member}"),
1414            manifest_version: "researcher/1.4.0".into(),
1415            kind: "summarize".into(),
1416            input: PayloadRef::inline(json!({"topic": member})),
1417            effect,
1418            deadline: None,
1419        }
1420    }
1421
1422    #[test]
1423    fn race_effect_gate_fails_closed() {
1424        // Freely-repeatable candidates pass: pure, read_only, idempotent.
1425        for effect in [Effect::Pure, Effect::ReadOnly, Effect::Idempotent] {
1426            let contract = RaceContract {
1427                candidates: vec![delegation("a", effect), delegation("b", Effect::Pure)],
1428            };
1429            assert!(contract.validate().is_ok(), "{effect:?} must be raceable");
1430        }
1431        // NonIdempotent and Compensatable are rejected, naming the member
1432        // and the effect — and the *default* (undeclared) effect is
1433        // NonIdempotent, so an undeclared candidate is rejected too.
1434        let undeclared: Delegation = serde_json::from_value(json!({
1435            "member": "a",
1436            "agent_id": "agent-a",
1437            "manifest_version": "researcher/1.4.0",
1438            "kind": "summarize",
1439            "input": {"kind": "inline", "value": {"topic": "a"}},
1440        }))
1441        .unwrap();
1442        assert_eq!(undeclared.effect, Effect::NonIdempotent);
1443        let contract = RaceContract {
1444            candidates: vec![undeclared, delegation("b", Effect::Pure)],
1445        };
1446        assert_eq!(
1447            contract.validate(),
1448            Err(CoordinationViolation::RaceEffectNotFreelyRepeatable {
1449                member: "a".into(),
1450                effect: "non_idempotent".into(),
1451            })
1452        );
1453        let contract = RaceContract {
1454            candidates: vec![delegation("a", Effect::Compensatable)],
1455        };
1456        assert!(matches!(
1457            contract.validate(),
1458            Err(CoordinationViolation::RaceEffectNotFreelyRepeatable { .. })
1459        ));
1460    }
1461
1462    #[test]
1463    fn pattern_contracts_validate_structure() {
1464        // Empty member sets are rejected for every multi-member pattern.
1465        let race = RaceContract { candidates: vec![] };
1466        assert_eq!(
1467            race.validate(),
1468            Err(CoordinationViolation::EmptyMembers {
1469                pattern: "race".into()
1470            })
1471        );
1472        // Duplicate member names make dispositions ambiguous — rejected.
1473        let fan_out = FanOutContract {
1474            members: vec![delegation("a", Effect::Pure), delegation("a", Effect::Pure)],
1475            max_in_flight: 1,
1476            on_member_failure: MemberFailurePolicy::Partial,
1477        };
1478        assert_eq!(
1479            fan_out.validate(),
1480            Err(CoordinationViolation::DuplicateMember {
1481                pattern: "fan_out".into(),
1482                member: "a".into(),
1483            })
1484        );
1485        // A zero window can never make progress.
1486        let fan_out = FanOutContract {
1487            members: vec![delegation("a", Effect::Pure)],
1488            max_in_flight: 0,
1489            on_member_failure: MemberFailurePolicy::FailFast,
1490        };
1491        assert_eq!(
1492            fan_out.validate(),
1493            Err(CoordinationViolation::MaxInFlightZero)
1494        );
1495        // Quorum thresholds are exact: 0 and > members are both out of
1496        // range, never clamped.
1497        let quorum = QuorumContract {
1498            members: vec![delegation("a", Effect::Pure)],
1499            threshold: 0,
1500            resolver: QuorumResolver::MajorityEqual,
1501        };
1502        assert_eq!(
1503            quorum.validate(),
1504            Err(CoordinationViolation::QuorumThresholdOutOfRange {
1505                threshold: 0,
1506                members: 1,
1507            })
1508        );
1509        let quorum = QuorumContract {
1510            threshold: 2,
1511            ..quorum
1512        };
1513        assert!(matches!(
1514            quorum.validate(),
1515            Err(CoordinationViolation::QuorumThresholdOutOfRange { .. })
1516        ));
1517        // Custom resolvers are a pinned wire shape, not a wave-3 mechanism.
1518        let quorum = QuorumContract {
1519            members: vec![delegation("a", Effect::Pure)],
1520            threshold: 1,
1521            resolver: QuorumResolver::Custom {
1522                name: "semantic_vote".into(),
1523            },
1524        };
1525        assert_eq!(
1526            quorum.validate(),
1527            Err(CoordinationViolation::CustomResolverUnsupported {
1528                name: "semantic_vote".into(),
1529            })
1530        );
1531    }
1532
1533    #[test]
1534    fn context_grant_only_narrows() {
1535        let declared = vec![StateScope::Private, StateScope::Team];
1536        let grant = ContextGrant {
1537            scopes: vec![StateScope::Team],
1538            channels: vec!["thread:team".into()],
1539        };
1540        assert!(grant.narrows(&declared));
1541        let widening = ContextGrant {
1542            scopes: vec![StateScope::Tenant],
1543            channels: vec![],
1544        };
1545        assert!(!widening.narrows(&declared));
1546        // An empty grant narrows trivially — it grants nothing.
1547        assert!(ContextGrant::default().narrows(&[]));
1548    }
1549
1550    #[test]
1551    fn merge_fan_out_orders_by_task_id_not_completion_order() {
1552        let results = vec![
1553            ("t--c--b".to_string(), json!("B")),
1554            ("t--c--d".to_string(), json!("D")),
1555            ("t--c--a".to_string(), json!("A")),
1556        ];
1557        assert_eq!(
1558            merge_fan_out(&results),
1559            vec![json!("A"), json!("B"), json!("D")]
1560        );
1561        // Input permutation cannot change the merge.
1562        let mut reversed = results.clone();
1563        reversed.reverse();
1564        assert_eq!(merge_fan_out(&reversed), merge_fan_out(&results));
1565    }
1566
1567    #[test]
1568    fn resolve_quorum_majority_decides_and_tallies_ties() {
1569        let accepted = vec![
1570            ("t--c--a".to_string(), json!("X")),
1571            ("t--c--b".to_string(), json!("Y")),
1572            ("t--c--c".to_string(), json!("X")),
1573        ];
1574        let outcome = resolve_quorum(&QuorumResolver::MajorityEqual, &accepted).unwrap();
1575        assert_eq!(outcome, QuorumOutcome::Decided { output: json!("X") });
1576
1577        // Two-two split: no strict majority, and the tallies are
1578        // deterministic (votes desc, then output bytes).
1579        let tied = vec![
1580            ("t--c--a".to_string(), json!("X")),
1581            ("t--c--b".to_string(), json!("Y")),
1582            ("t--c--c".to_string(), json!("Y")),
1583            ("t--c--d".to_string(), json!("X")),
1584        ];
1585        let outcome = resolve_quorum(&QuorumResolver::MajorityEqual, &tied).unwrap();
1586        assert_eq!(
1587            outcome,
1588            QuorumOutcome::NoMajority {
1589                tallies: vec![
1590                    QuorumTally {
1591                        output: json!("X"),
1592                        votes: 2,
1593                    },
1594                    QuorumTally {
1595                        output: json!("Y"),
1596                        votes: 2,
1597                    },
1598                ]
1599            }
1600        );
1601
1602        // Object equality is structural: key order does not split a vote.
1603        let objects = vec![
1604            ("t--c--a".to_string(), json!({"p": 1, "q": 2})),
1605            ("t--c--b".to_string(), json!({"q": 2, "p": 1})),
1606            ("t--c--c".to_string(), json!({"p": 9})),
1607        ];
1608        let outcome = resolve_quorum(&QuorumResolver::MajorityEqual, &objects).unwrap();
1609        assert_eq!(
1610            outcome,
1611            QuorumOutcome::Decided {
1612                output: json!({"p": 1, "q": 2})
1613            }
1614        );
1615    }
1616
1617    #[test]
1618    fn resolve_quorum_first_k_is_task_id_ordered_and_deterministic() {
1619        let accepted = vec![
1620            ("t--c--b".to_string(), json!(2)),
1621            ("t--c--a".to_string(), json!(1)),
1622            ("t--c--c".to_string(), json!(3)),
1623        ];
1624        let outcome = resolve_quorum(&QuorumResolver::FirstK, &accepted).unwrap();
1625        assert_eq!(
1626            outcome,
1627            QuorumOutcome::FirstK {
1628                outputs: vec![json!(1), json!(2), json!(3)]
1629            }
1630        );
1631        // Permuted input, identical outcome — replay determinism.
1632        let mut permuted = accepted.clone();
1633        permuted.reverse();
1634        assert_eq!(
1635            resolve_quorum(&QuorumResolver::FirstK, &permuted).unwrap(),
1636            outcome
1637        );
1638        // Custom resolvers are rejected here too — defense in depth behind
1639        // the submission gate.
1640        assert!(matches!(
1641            resolve_quorum(&QuorumResolver::Custom { name: "x".into() }, &accepted),
1642            Err(CoordinationViolation::CustomResolverUnsupported { .. })
1643        ));
1644    }
1645
1646    #[test]
1647    fn coordination_contract_dispatch_and_sparse_wire() {
1648        let contract = CoordinationContract::Delegate(Box::new(DelegateContract {
1649            delegate: delegation("only", Effect::Pure),
1650            context: None,
1651            result_contract: None,
1652            handoff: false,
1653        }));
1654        assert_eq!(contract.kind(), CoordinationKind::Delegate);
1655        assert_eq!(contract.members().len(), 1);
1656        assert!(contract.validate().is_ok());
1657
1658        // Sparse wire: unset optional fields and false handoff vanish;
1659        // the pattern tag is the discriminator.
1660        let wire = serde_json::to_value(&contract).unwrap();
1661        assert_eq!(wire["pattern"], json!("delegate"));
1662        assert!(wire["delegate"].get("context").is_none());
1663        assert!(wire["delegate"].get("result_contract").is_none());
1664        assert!(wire["delegate"].get("handoff").is_none());
1665        // The effect is explicit on the wire even when defaulted in.
1666        assert_eq!(wire["delegate"]["effect"], json!("pure"));
1667        let back: CoordinationContract =
1668            serde_json::from_str(&serde_json::to_string(&contract).unwrap()).unwrap();
1669        assert_eq!(contract, back);
1670    }
1671
1672    #[test]
1673    fn coordination_message_and_outcome_round_trip() {
1674        let message = CoordinationMessage {
1675            coordination_id: "c1".into(),
1676            member: "a".into(),
1677            pattern: CoordinationKind::FanOut,
1678            input: PayloadRef::inline(json!({"topic": "a"})),
1679            context: None,
1680        };
1681        let back: CoordinationMessage =
1682            serde_json::from_str(&serde_json::to_string(&message).unwrap()).unwrap();
1683        assert_eq!(message, back);
1684        assert!(is_coordination_result(COORDINATION_RESULT_KIND));
1685        assert!(!is_coordination_result("summarize"));
1686
1687        let outcome = CoordinationOutcome {
1688            coordination_id: "c1".into(),
1689            pattern: CoordinationKind::FanOut,
1690            status: CoordinationStatus::Completed,
1691            result: Some(PayloadRef::inline(json!(["A"]))),
1692            members: vec![MemberDisposition {
1693                member: "a".into(),
1694                task_id: "t--c1--a".into(),
1695                settlement: MemberSettlement::Completed,
1696                result: Some(PayloadRef::inline(json!("A"))),
1697                error_class: None,
1698                error: None,
1699                tokens: None,
1700                cost_usd: None,
1701            }],
1702            wasted_tokens: None,
1703            wasted_cost_usd: None,
1704            resolver: None,
1705        };
1706        let wire = serde_json::to_value(&outcome).unwrap();
1707        // Sparse: no waste fields, no resolver record on a fan-out.
1708        assert!(wire.get("wasted_tokens").is_none());
1709        assert!(wire.get("wasted_cost_usd").is_none());
1710        assert!(wire.get("resolver").is_none());
1711        let back: CoordinationOutcome =
1712            serde_json::from_str(&serde_json::to_string(&outcome).unwrap()).unwrap();
1713        assert_eq!(outcome, back);
1714    }
1715}