aion-package 0.30.0

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
//! The canonical identity encoding of the contract surface.
//!
//! Everything here answers one question: what bytes does a
//! [`PackageContract`] contribute to the package hash, under which identity
//! domain, and how does the verifier reproduce what a prior release minted.
//! The shapes being encoded live in the sibling `surface` module.

use std::time::Duration;

use serde_json::Value;

use super::surface::{
    ActionBodyContract, ActionContract, ChildContract, CommandBodyCapture, PackageContract,
    RetryContract, ToleranceContract, WorkerContract, WorkloopContract,
};

/// 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,
    },
}

impl PackageContract {
    /// Returns the deterministic binary encoding committed by the current
    /// identity domain.
    ///
    /// 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> {
        self.canonical_bytes_in(
            ContractDomain::V6,
            &crate::declared_command::PriorCommandIdentities::new(),
        )
    }

    /// The superseded `.v5` encoding, exactly as every released cut from
    /// v0.19 through v0.24 computed it: no per-action agent byte, no
    /// workloop block.
    ///
    /// 🔴 VERIFICATION-ONLY MIGRATION SURFACE. This exists so the verifier
    /// in [`crate::hash`] can re-attest archives those releases minted —
    /// a store restarted under the current build must not strand its own
    /// recorded deployments. Nothing ever MINTS a `.v5` identity again;
    /// calling this anywhere except a verifier is a defect.
    #[must_use]
    pub fn legacy_v5_canonical_bytes(&self) -> Vec<u8> {
        self.canonical_bytes_in(
            ContractDomain::LegacyV5,
            &crate::declared_command::PriorCommandIdentities::new(),
        )
    }

    /// The current-domain encoding with each prior-form declared command's
    /// identity record substituted from `prior` — the bytes the minting
    /// release actually hashed.
    ///
    /// 🔴 VERIFICATION-ONLY MIGRATION SURFACE, one level deeper than
    /// [`Self::legacy_v5_canonical_bytes`]: the v0.27.0 command reshape moved
    /// no identity domain, so a prior-form archive's stored hash was computed
    /// under the SAME domain constants over the PRIOR command encoding. The
    /// verifier reads that encoding back from the raw archive bytes (see
    /// [`crate::declared_command::prior_command_identities`]) and substitutes
    /// it here, wholesale, at the one site a command encodes. With `prior`
    /// empty this is exactly [`Self::canonical_bytes`]. Nothing ever MINTS
    /// prior bytes; calling this anywhere except a verifier is a defect.
    pub(crate) fn canonical_bytes_with_prior_commands(
        &self,
        prior: &crate::declared_command::PriorCommandIdentities,
    ) -> Vec<u8> {
        self.canonical_bytes_in(ContractDomain::V6, prior)
    }

    /// The `.v5`-domain encoding with prior-form command substitution — see
    /// [`Self::canonical_bytes_with_prior_commands`]. Declared commands
    /// postdate every `.v5` mint, so a genuine `.v5` archive always reaches
    /// this with `prior` empty; the substitution seam is threaded uniformly
    /// so the two domains cannot disagree about what a command's identity is.
    pub(crate) fn legacy_v5_canonical_bytes_with_prior_commands(
        &self,
        prior: &crate::declared_command::PriorCommandIdentities,
    ) -> Vec<u8> {
        self.canonical_bytes_in(ContractDomain::LegacyV5, prior)
    }

    fn canonical_bytes_in(
        &self,
        domain: ContractDomain,
        prior: &crate::declared_command::PriorCommandIdentities,
    ) -> 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(|worker| worker.canonical_bytes_in(domain, prior.get(&worker.task_queue)))
            .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. The `.v5` domain
        // predates the field entirely, so its encoding stops here — and the
        // verifier refuses to attest a workloop under `.v5` for the same
        // reason this block encodes under `.v6`.
        if domain == ContractDomain::V6 {
            match &self.workloop {
                None => bytes.push(0),
                Some(workloop) => {
                    bytes.push(1);
                    update_record(&mut bytes, &workloop.canonical_bytes());
                }
            }
        }
        bytes
    }
}

/// Which identity domain a canonical encoding targets.
///
/// `LegacyV5` exists ONLY for the verifier's migration accommodation
/// ([`crate::hash`]); it is never a minting target.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ContractDomain {
    /// The superseded released domain (v0.19–v0.24): no per-action agent
    /// byte, no workloop block.
    LegacyV5,
    /// The current domain.
    V6,
}

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
    }
}

impl WorkerContract {
    fn canonical_bytes_in(
        &self,
        domain: ContractDomain,
        prior: Option<&std::collections::BTreeMap<String, Vec<u8>>>,
    ) -> Vec<u8> {
        let mut bytes = Vec::new();
        encode_text(&mut bytes, &self.task_queue);
        let mut actions = self
            .actions
            .iter()
            .map(|action| {
                action.canonical_bytes_in(
                    domain,
                    prior
                        .and_then(|actions| actions.get(&action.name))
                        .map(Vec::as_slice),
                )
            })
            .collect::<Vec<_>>();
        actions.sort();
        encode_len(&mut bytes, actions.len());
        for action in actions {
            update_record(&mut bytes, &action);
        }
        bytes
    }
}

impl CommandBodyCapture {
    /// The byte this capture contributes to a canonical identity record.
    const fn identity_byte(self) -> u8 {
        match self {
            Self::Text => 0,
            Self::Json => 1,
        }
    }
}

impl ActionContract {
    fn canonical_bytes_in(&self, domain: ContractDomain, prior_command: Option<&[u8]>) -> 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, and no body discriminant is ever
        // `ADVISORY_MARKER`. Stated as the rule rather than as a list of the
        // discriminants that exist today, because the list grows.
        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);
            }
            // A DECLARED command body encodes its whole emitted form, not a
            // name: the body's lines, their argv slots, the environment and
            // the working directory are each executable authority, and a
            // package whose identity named only `say_hello` could have its
            // argument list rewritten in storage without changing what the
            // deployment claims to be. (A per-command timeout was authority
            // here too, until the surface that declared one was deleted; the
            // encoding no longer carries a bound because no command declares
            // one.) The discriminant continues the same positional block, so
            // no optional tail is added and the domain does not move again.
            Some(ActionBodyContract::Command { capture, command }) => {
                bytes.push(2);
                bytes.push(capture.identity_byte());
                // The verification-only prior-form substitution seam: when
                // the archive minted this command under the prior encoding,
                // its identity IS that prior record — read back from the raw
                // archive bytes, never re-derived from the translated shape —
                // so the recompute reproduces exactly what the minting
                // release hashed. Every freshly minted contract takes the
                // current encoder.
                match prior_command {
                    Some(prior) => bytes.extend_from_slice(prior),
                    None => crate::declared_command::encode_identity(&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. Under the
        // `.v5` migration accommodation the byte is absent because that is
        // what every released cut computed: a re-attested `.v5` archive's
        // agent flags travel AS STORED, un-vouched, at exactly the trust
        // level those releases gave them — redeploying mints the `.v6`
        // identity that binds them.
        if domain == ContractDomain::V6 {
            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;

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
    }
}

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());
}