aion-package 0.27.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
//! The contract surface: every record committed into a package's `.v4`+
//! identity — workflow schemas, worker action declarations, children,
//! signals, additional entries, and the workloop block.
//!
//! The types here are shape and meaning only. HOW they become identity
//! bytes — the canonical encoding, its domains, and the prior-form
//! substitution seam — lives in the sibling `identity` module, so that the
//! surface a reader studies and the encoding an auditor studies are each
//! one page.

use std::time::Duration;

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

use crate::Manifest;

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

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

/// 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,
    },
    /// One DECLARED command (`runs command <name>`), carried in its emitted
    /// typed form: body lines of templated argv slots, declared environment
    /// bindings, and the working directory.
    ///
    /// The difference from [`ActionBodyContract::Run`] is not spelling. A
    /// `Run` body is a command LINE that the executor still has to split; a
    /// `Command` body was split by the AWL emitter at compile time and travels
    /// as an argument list, so nothing downstream ever holds a string that
    /// could be re-split.
    Command {
        /// What the action's result is taken from.
        capture: CommandBodyCapture,
        /// The emitted command.
        command: Box<crate::declared_command::DeclaredCommandContract>,
    },
}

/// What a `runs command` body's result is, and therefore what the action's
/// declared return type has to be.
///
/// Two forms, not three: a declared command's caller is asking for the
/// command's OUTPUT, and the outcome record that a bare `run "…"` body yields
/// is the shape the string form has for historical reasons. An action that
/// wants an exit code takes it from a `run` body.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandBodyCapture {
    /// Trimmed stdout becomes a JSON string. A non-zero exit is a retryable
    /// failure carrying stderr.
    Text,
    /// Trimmed stdout is parsed as JSON and becomes the result. A non-zero
    /// exit is a retryable failure carrying stderr; stdout that is not valid
    /// JSON is a terminal one.
    Json,
}

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

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

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