aion-package 0.25.1

Archive validation, content hashing, and namespacing for Aion workflow packages.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! Durable worker-contract records and their canonical identity encoding.

use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::Manifest;

/// Refusal returned when a stored package predates contract-bound identity.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ContractIdentityError {
    /// The package is integrity-valid but its identity commits to no contract.
    #[error(
        "package identity `{stored_version}` predates `.v4` worker-contract commitment; re-deploy this package under `.v4`"
    )]
    RedeployRequired {
        /// Stored pre-`.v4` package identity.
        stored_version: String,
    },
}

/// The complete contract surface committed into a package's `.v4` identity.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PackageContract {
    /// Primary workflow input schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub input_schema: Value,
    /// Primary workflow output schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub output_schema: Value,
    /// Queue-scoped activity declarations.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub workers: Vec<WorkerContract>,
    /// Declared child workflow callables.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<ChildContract>,
    /// Declared signal payloads.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub signals: Vec<SignalContract>,
    /// Additional workflow entry schemas in this package.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub additional_workflows: Vec<AdditionalWorkflowContract>,
    /// Activity names retained by legacy project manifests that cannot declare a
    /// queue or typed activity surface. They remain identity-bound but do not
    /// create a queue declaration.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unscoped_activities: Vec<String>,
    /// The workloop declaration surface, when the package's entry document is
    /// a `workloop`. This is what the ENGINE reads at start time to arm the
    /// cadence, seed generation 1's carries and evaluate tolerances, so it
    /// must travel with the deployed archive rather than only with the
    /// in-process compile output — a server restart must not forget what a
    /// deployed loop's tolerances were.
    ///
    /// IDENTITY-BOUND, and that is not a formality: a tolerance rewritten in
    /// storage changes WHEN a loop alarms, and a retention window rewritten in
    /// storage changes WHAT is destroyed. Both are executable authority, so
    /// two packages that differ in them must not be one version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workloop: Option<WorkloopContract>,
}

/// The workloop declaration surface, as compiled from a `workloop` document
/// (workloop design brief R2/R8/R13): everything the engine needs to arm
/// the loop, seed the first generation's carries from the declared
/// defaults, and evaluate tolerances without re-reading AWL source.
///
/// Carried on the COMPILE OUTPUT (`aion_awl::CompiledWorkflow::workloop`) and
/// on the deployed archive's [`PackageContract`], where it is bound into
/// package identity: the engine reads it at START time to arm the cadence,
/// seed generation 1's carries and evaluate tolerances, so it must survive a
/// server restart and must not be rewritable in storage without changing the
/// package's version.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkloopContract {
    /// The `every` cadence in seconds, when declared.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cadence_seconds: Option<u64>,
    /// The `on <signal>` arming signal names, in declaration order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub arms: Vec<String>,
    /// The carries: name, value schema, and the declared default the engine
    /// seeds the FIRST generation with (later generations carry the values
    /// `route start` minted).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub carries: Vec<CarryContract>,
    /// The invariants, with their declared tolerances and confirming routes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub invariants: Vec<InvariantContract>,
    /// The declared `retention` window in seconds (R8.1 — required, no
    /// default).
    pub retention_seconds: u64,
    /// The `detached` hatch-target contracts: name and start schema.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub detached: Vec<DetachedContract>,
    /// The report tiles: name and value schema.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reports: Vec<ReportContract>,
    /// Whether the document declares a `retire` block, and therefore whether
    /// the deployed module exports `retire/1`.
    ///
    /// 🔴 A DECLARATION, NOT A CALLER PREFERENCE. Retirement has two engine
    /// verbs — one that invokes the declared cleanup and one for a loop that
    /// declares none — and which applies is decided by the DOCUMENT. If an
    /// operator could choose, a declared cleanup could be skipped by passing
    /// an argument, which is how a lease is lost. If the engine guessed, it
    /// could not tell a module compiled before the entry existed from a loop
    /// that declared no cleanup, which is the same failure wearing a
    /// different hat. So the answer travels with the package, bound into its
    /// identity like every other executable authority here.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub has_retire_body: bool,
}

/// One `carry` declaration: name, schema, and the folded default seed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarryContract {
    /// Carry name (an input-record field of every generation).
    pub name: String,
    /// The carry's value schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub schema: Value,
    /// The declared default, folded to a JSON literal.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub default: Value,
}

/// One declared tolerance form (R2.3 — no default; both may stand).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "form", rename_all = "snake_case")]
pub enum ToleranceContract {
    /// `tolerance <N> windows` — N consecutive unhealthy samples.
    Windows {
        /// The declared window count.
        count: u64,
    },
    /// `tolerance unconfirmed for <duration>` — the only form evaluable
    /// with zero samples (R2.4a).
    UnconfirmedFor {
        /// The declared window in seconds.
        seconds: u64,
    },
}

/// One `invariant` declaration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvariantContract {
    /// Invariant name.
    pub name: String,
    /// The DECLARED type name of the current-state record (`invariant serving:
    /// type Board` → `"Board"`).
    ///
    /// Carried beside the schema, not derived from it: the engine stamps this
    /// on every durable invariant current-state record as provenance, so a
    /// reader can tell which declaration a stored value was written under. A
    /// schema is structural and two different declarations can share one.
    pub record_type: String,
    /// The current-state record schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub schema: Value,
    /// The declared tolerance forms, in declaration order (never empty for
    /// a checked document — C3).
    pub tolerances: Vec<ToleranceContract>,
    /// The route whose firing confirms the invariant, when declared.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirms: Option<String>,
}

/// One `detached` hatch-target contract.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DetachedContract {
    /// The detached workflow's logical name (the hatch dedupe scope is
    /// namespace + this name + the site's key).
    pub name: String,
    /// Start-contract schema over the declared parameters.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub input_schema: Value,
}

/// One `report` tile contract.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReportContract {
    /// Report name (registered through the answer surface).
    pub name: String,
    /// The tile's value schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub schema: Value,
}

impl PackageContract {
    /// Produces the most precise contract available from a legacy manifest.
    ///
    /// This never invents a queue or schemas for bare activity names. Such names
    /// are committed as unscoped records and therefore cannot satisfy a
    /// structural queue-service check.
    #[must_use]
    pub fn from_manifest(manifest: &Manifest) -> Self {
        Self {
            input_schema: manifest.input_schema.clone(),
            output_schema: manifest.output_schema.clone(),
            workers: Vec::new(),
            children: Vec::new(),
            signals: Vec::new(),
            additional_workflows: manifest
                .additional_workflows
                .iter()
                .map(|entry| AdditionalWorkflowContract {
                    workflow_type: entry.workflow_type.clone(),
                    input_schema: entry.input_schema.clone(),
                    output_schema: entry.output_schema.clone(),
                })
                .collect(),
            unscoped_activities: manifest
                .activities
                .iter()
                .map(|activity| activity.activity_type.clone())
                .collect(),
            // A legacy manifest declares no workloop surface: the header a
            // loop needs did not exist when it was built, and inventing one
            // would arm a cadence nobody wrote.
            workloop: None,
        }
    }

    /// Returns the deterministic binary encoding committed by the `.v4` hash.
    ///
    /// Declaration vectors and JSON object keys are sorted before encoding.
    /// JSON whitespace and source map insertion order therefore cannot affect
    /// package identity.
    #[must_use]
    pub fn canonical_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        encode_json(&mut bytes, None, &self.input_schema);
        encode_json(&mut bytes, None, &self.output_schema);

        let mut workers = self
            .workers
            .iter()
            .map(WorkerContract::canonical_bytes)
            .collect::<Vec<_>>();
        workers.sort();
        encode_len(&mut bytes, workers.len());
        for worker in workers {
            update_record(&mut bytes, &worker);
        }

        let mut children = self
            .children
            .iter()
            .map(ChildContract::canonical_bytes)
            .collect::<Vec<_>>();
        children.sort();
        encode_len(&mut bytes, children.len());
        for child in children {
            update_record(&mut bytes, &child);
        }

        let mut signals = self.signals.iter().collect::<Vec<_>>();
        signals.sort_by(|left, right| left.name.cmp(&right.name));
        encode_len(&mut bytes, signals.len());
        for signal in signals {
            encode_text(&mut bytes, &signal.name);
            encode_json(&mut bytes, None, &signal.input_schema);
        }

        let mut additional = self.additional_workflows.iter().collect::<Vec<_>>();
        additional.sort_by(|left, right| left.workflow_type.cmp(&right.workflow_type));
        encode_len(&mut bytes, additional.len());
        for workflow in additional {
            encode_text(&mut bytes, &workflow.workflow_type);
            encode_json(&mut bytes, None, &workflow.input_schema);
            encode_json(&mut bytes, None, &workflow.output_schema);
        }

        let mut unscoped = self.unscoped_activities.iter().collect::<Vec<_>>();
        unscoped.sort();
        encode_len(&mut bytes, unscoped.len());
        for activity in unscoped {
            encode_text(&mut bytes, activity);
        }

        // The WORKLOOP block, encoded UNCONDITIONALLY (a presence
        // discriminant, then the whole surface) under the `.v6` domain. Every
        // value here is executable authority the engine acts on: the cadence
        // decides when the loop fires, the tolerances decide when it alarms,
        // the retention window decides what is destroyed, and the carry
        // defaults decide what generation 1 starts from.
        match &self.workloop {
            None => bytes.push(0),
            Some(workloop) => {
                bytes.push(1);
                update_record(&mut bytes, &workloop.canonical_bytes());
            }
        }
        bytes
    }
}

impl WorkloopContract {
    fn canonical_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        match self.cadence_seconds {
            None => bytes.push(0),
            Some(seconds) => {
                bytes.push(1);
                bytes.extend_from_slice(&seconds.to_be_bytes());
            }
        }
        // Arming signals, carries, invariants, detached targets and reports
        // are all encoded in DECLARATION order rather than sorted: unlike a
        // worker's action set, these are ordered declarations in the document
        // and reordering them is a source change the author made.
        encode_len(&mut bytes, self.arms.len());
        for arm in &self.arms {
            encode_text(&mut bytes, arm);
        }
        encode_len(&mut bytes, self.carries.len());
        for carry in &self.carries {
            encode_text(&mut bytes, &carry.name);
            encode_json(&mut bytes, None, &carry.schema);
            encode_json(&mut bytes, None, &carry.default);
        }
        encode_len(&mut bytes, self.invariants.len());
        for invariant in &self.invariants {
            encode_text(&mut bytes, &invariant.name);
            encode_text(&mut bytes, &invariant.record_type);
            encode_json(&mut bytes, None, &invariant.schema);
            encode_len(&mut bytes, invariant.tolerances.len());
            for tolerance in &invariant.tolerances {
                match tolerance {
                    ToleranceContract::Windows { count } => {
                        bytes.push(1);
                        bytes.extend_from_slice(&count.to_be_bytes());
                    }
                    ToleranceContract::UnconfirmedFor { seconds } => {
                        bytes.push(2);
                        bytes.extend_from_slice(&seconds.to_be_bytes());
                    }
                }
            }
            encode_optional_text(&mut bytes, invariant.confirms.as_deref());
        }
        bytes.extend_from_slice(&self.retention_seconds.to_be_bytes());
        encode_len(&mut bytes, self.detached.len());
        for detached in &self.detached {
            encode_text(&mut bytes, &detached.name);
            encode_json(&mut bytes, None, &detached.input_schema);
        }
        encode_len(&mut bytes, self.reports.len());
        for report in &self.reports {
            encode_text(&mut bytes, &report.name);
            encode_json(&mut bytes, None, &report.schema);
        }
        bytes.push(u8::from(self.has_retire_body));
        bytes
    }
}

/// The actions a worker queue must serve.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkerContract {
    /// Declared task queue.
    pub task_queue: String,
    /// Typed activities on the queue.
    pub actions: Vec<ActionContract>,
}

impl WorkerContract {
    fn canonical_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        encode_text(&mut bytes, &self.task_queue);
        let mut actions = self
            .actions
            .iter()
            .map(ActionContract::canonical_bytes)
            .collect::<Vec<_>>();
        actions.sort();
        encode_len(&mut bytes, actions.len());
        for action in actions {
            update_record(&mut bytes, &action);
        }
        bytes
    }
}

/// Typed activity surface advertised by a concrete worker build.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActivityDescriptor {
    /// Activity type.
    pub name: String,
    /// Schema accepted by the worker.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub input_schema: Value,
    /// Schema produced by the worker.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub output_schema: Value,
}

/// One typed activity declaration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionContract {
    /// Activity type.
    pub name: String,
    /// Object schema over the activity parameters.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub input_schema: Value,
    /// Activity result schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub output_schema: Value,
    /// Declared node selector.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node: Option<String>,
    /// Declared schedule-to-close timeout.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout: Option<Duration>,
    /// Declaration-owned retry envelope.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry: Option<RetryContract>,
    /// Whether the declaration classes this activity as ADVISORY: a side
    /// channel whose failure warns on the run and never faults the calling
    /// step (RUNTIME-OPERATIONS.md R5). Identity-bound — flipping it changes
    /// what the package promises a caller.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub advisory: bool,
    /// Whether the declaration classes this activity as an AGENT seam: its one
    /// `String` parameter carries a prompt and its `String` result carries the
    /// reply, so a worker hands the call to an agent harness rather than to a
    /// typed handler. The checker enforces that shape, so a worker reading this
    /// flag may rely on it.
    ///
    /// Identity-bound for the same reason `advisory` is — an action that
    /// becomes an agent seam promises a caller something different — and
    /// skipped when false, so a document with no agent action hashes exactly as
    /// it did before the marker existed.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub agent: bool,
    /// The declarative body the action carries, when it declares one.
    ///
    /// `None` is a requirement on an out-of-band worker: the action's name
    /// and schemas are the whole promise, and something must connect to
    /// serve it. `Some` means the package itself says what the action DOES,
    /// so the host can execute it with no worker connected.
    ///
    /// Identity-bound deliberately: the body is executable authority, and an
    /// authority that did not participate in the package hash could be
    /// rewritten in storage without changing what the deployment claims to
    /// be. A body edit is a new package, always.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<ActionBodyContract>,
}

/// A declarative action body committed into package identity.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ActionBodyContract {
    /// One command line, executed directly with argv-element parameter
    /// substitution — never through a shell. The text is the authored form
    /// with `$` interpolation intact; the executor parses it and substitutes
    /// each referenced parameter as one whole argument.
    Run {
        /// The authored command text.
        command: String,
    },
}

impl ActionContract {
    /// Whether serving this action is a WORKER's job.
    ///
    /// `true` when the action carries no declared body: the declaration is a
    /// requirement on an out-of-band worker, and nothing runs until one
    /// connects and advertises the action. `false` when the action carries a
    /// declared body: the package itself says what the action does, the host
    /// executes it, and no worker is needed or admitted for it.
    ///
    /// This is the one place the body-exemption rule lives. Every surface
    /// that splits a queue's actions into worker-owed and server-run —
    /// admission diffs, availability, scaffolding, codegen — must call this
    /// rather than restate `body.is_none()`.
    #[must_use]
    pub fn worker_owed(&self) -> bool {
        self.body.is_none()
    }

    fn canonical_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        encode_text(&mut bytes, &self.name);
        encode_json(&mut bytes, None, &self.input_schema);
        encode_json(&mut bytes, None, &self.output_schema);
        encode_optional_text(&mut bytes, self.node.as_deref());
        encode_optional_duration(&mut bytes, self.timeout);
        match &self.retry {
            None => bytes.push(0),
            Some(RetryContract::Every { count, every }) => {
                bytes.push(1);
                bytes.extend_from_slice(&count.to_be_bytes());
                encode_duration(&mut bytes, *every);
            }
            Some(RetryContract::Backoff { count, min, max }) => {
                bytes.push(2);
                bytes.extend_from_slice(&count.to_be_bytes());
                encode_duration(&mut bytes, *min);
                encode_duration(&mut bytes, *max);
            }
        }
        // ADVISORY is encoded ONLY when true: a single marker byte appended
        // after the retry block, and nothing at all when false. It is
        // injective because absence and the marker cannot be confused at the
        // end of a positional record — the block that FOLLOWS it always
        // begins with a body discriminant (`0`/`1`), never `ADVISORY_MARKER`.
        if self.advisory {
            bytes.push(ADVISORY_MARKER);
        }
        // The BODY block always encodes — a discriminant byte, then the
        // command text for `Run`. Adding it consumed the record's optional
        // tail (the advisory marker was the one tail-append the previous
        // domain could injectively absorb), which is why this encoding lives
        // under the bumped `.v5` identity domain rather than as a second
        // conditional suffix: two optional tails are not injective, and a
        // contract identity that two different declarations can share is a
        // spoofable deployment.
        //
        // LAW for the next field: encode it UNCONDITIONALLY after this
        // block and bump the identity domain again. Never append another
        // optional tail.
        match &self.body {
            None => bytes.push(0),
            Some(ActionBodyContract::Run { command }) => {
                bytes.push(1);
                encode_text(&mut bytes, command);
            }
        }
        // 🔴 THE AGENT MARKER (aion#158). Its own doc comment above says it is
        // identity-bound "for the same reason `advisory` is" — and it was
        // referenced ZERO times in this encoder, so the claim was false and two
        // declarations that differ only in whether an action is an agent seam
        // hashed identically. An action that becomes an agent seam promises a
        // caller something different: its `String` parameter is a prompt and
        // its `String` result is a reply, and a worker may rely on that shape.
        //
        // Encoded UNCONDITIONALLY, exactly as the law above prescribes, under
        // the bumped `.v6` domain — never as a second optional tail, which
        // would not be injective alongside the advisory marker.
        bytes.push(u8::from(self.agent));
        bytes
    }
}

/// The marker byte appended to an advisory action's canonical record.
///
/// Distinct from every retry-kind discriminant (`0`/`1`/`2`) it can follow,
/// so a reader of the trailing bytes is never ambiguous.
const ADVISORY_MARKER: u8 = 0xA0;

/// A declaration-owned retry envelope.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RetryContract {
    /// Constant delay between attempts.
    Every {
        /// Number of further attempts after the first.
        count: u64,
        /// Delay between attempts.
        every: Duration,
    },
    /// Bounded backoff between attempts.
    Backoff {
        /// Number of further attempts after the first.
        count: u64,
        /// Minimum delay.
        min: Duration,
        /// Maximum delay.
        max: Duration,
    },
}

/// One declared child workflow callable.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChildContract {
    /// Child workflow type.
    pub name: String,
    /// Object schema over child parameters.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub input_schema: Value,
    /// Child result schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub output_schema: Value,
}

impl ChildContract {
    fn canonical_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        encode_text(&mut bytes, &self.name);
        encode_json(&mut bytes, None, &self.input_schema);
        encode_json(&mut bytes, None, &self.output_schema);
        bytes
    }
}

/// One declared signal payload.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignalContract {
    /// Signal name.
    pub name: String,
    /// Signal payload schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub input_schema: Value,
}

/// Typed shape of an additional entry in the same package.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdditionalWorkflowContract {
    /// Routing workflow type.
    pub workflow_type: String,
    /// Entry input schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub input_schema: Value,
    /// Entry output schema.
    #[serde(serialize_with = "crate::canonical::serialize_value")]
    pub output_schema: Value,
}

fn encode_json(bytes: &mut Vec<u8>, parent_key: Option<&str>, value: &Value) {
    match value {
        Value::Null => bytes.push(0),
        Value::Bool(value) => bytes.extend_from_slice(&[1, u8::from(*value)]),
        Value::Number(value) => {
            bytes.push(2);
            encode_text(bytes, &value.to_string());
        }
        Value::String(value) => {
            bytes.push(3);
            encode_text(bytes, value);
        }
        Value::Array(values) => {
            bytes.push(4);
            let mut values = values.iter().collect::<Vec<_>>();
            if matches!(parent_key, Some("required" | "enum")) {
                values.sort_by_key(ToString::to_string);
            }
            encode_len(bytes, values.len());
            for value in values {
                encode_json(bytes, None, value);
            }
        }
        Value::Object(values) => {
            bytes.push(5);
            let mut entries = values.iter().collect::<Vec<_>>();
            entries.sort_by_key(|(left, _)| *left);
            encode_len(bytes, entries.len());
            for (key, value) in entries {
                encode_text(bytes, key);
                encode_json(bytes, Some(key), value);
            }
        }
    }
}

fn encode_len(bytes: &mut Vec<u8>, len: usize) {
    bytes.extend_from_slice(&(len as u64).to_be_bytes());
}

fn encode_text(bytes: &mut Vec<u8>, value: &str) {
    encode_len(bytes, value.len());
    bytes.extend_from_slice(value.as_bytes());
}

fn update_record(bytes: &mut Vec<u8>, record: &[u8]) {
    encode_len(bytes, record.len());
    bytes.extend_from_slice(record);
}

fn encode_optional_text(bytes: &mut Vec<u8>, value: Option<&str>) {
    match value {
        Some(value) => {
            bytes.push(1);
            encode_text(bytes, value);
        }
        None => bytes.push(0),
    }
}

fn encode_optional_duration(bytes: &mut Vec<u8>, value: Option<Duration>) {
    match value {
        Some(value) => {
            bytes.push(1);
            encode_duration(bytes, value);
        }
        None => bytes.push(0),
    }
}

fn encode_duration(bytes: &mut Vec<u8>, value: Duration) {
    bytes.extend_from_slice(&value.as_secs().to_be_bytes());
    bytes.extend_from_slice(&value.subsec_nanos().to_be_bytes());
}

#[cfg(test)]
#[path = "contract_tests.rs"]
mod tests;