Skip to main content

aria_operator/
lib.rs

1//! Closed operator JSON over the Aria telemetry transform.
2//!
3//! Each catalog binary is a distinct crate that includes its own `spec.json`
4//! and calls [`run_spec`]. AriA is the underlying transformer in every
5//! binary: Φ is not copied, it is linked.
6
7#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]
8
9mod dispatch;
10mod envelope;
11mod harness;
12mod index;
13mod organize;
14mod run;
15#[cfg(feature = "cli")]
16mod serve;
17mod typecast;
18mod work_api;
19#[cfg(feature = "cli")]
20mod work_cli;
21
22pub use harness::{
23    dispatch_json, execute_harness, harness_lane, HarnessError, HarnessRequest, HarnessResult,
24    DEFAULT_OUTPUT_LIMIT, HARNESS_CAPABILITY, HARNESS_REQUEST_V1, HARNESS_RESULT_V1,
25};
26#[cfg(feature = "cli")]
27pub use serve::{serve, serve_background};
28
29pub use dispatch::{
30    endpoint_by_binary_id, endpoint_by_operator, endpoint_by_package, WorkerEndpoint,
31};
32pub use envelope::{
33    OperatorEnvelope, OperatorGraph, OperatorNode, OperatorRel, OperatorSpec, ENVELOPE_KEYS,
34};
35pub use run::{run_binary, run_many, run_spec, OperatorError, RunOpts};
36pub use organize::{organize_slop, OrganizeReport};
37pub use typecast::{cast_lexicon, cast_tags, tag_phrase, uncast_fields};
38pub use work_api::{
39    callback_results, commands_json, execute_work, looks_like_work_command, WorkRequest,
40    WorkResponse, WORK_V1,
41};
42#[cfg(feature = "cli")]
43pub use work_cli::work_main;
44
45#[cfg(feature = "cli")]
46use clap::Parser;
47#[cfg(feature = "cli")]
48use std::io::{self, Read, Write};
49#[cfg(feature = "cli")]
50use std::path::PathBuf;
51#[cfg(feature = "cli")]
52use std::process::ExitCode;
53use std::sync::OnceLock;
54
55/// Schema tag for the operator envelope (Binary Repository v1 / sheet 09).
56pub const OPERATOR_ENVELOPE_V1: &str = "aria-operator-envelope-v1";
57/// Closed envelope semver carried on every operator document.
58pub const OPERATOR_SCHEMA_VERSION: &str = "1.0.0";
59/// Frozen catalog shipped with this crate (560 rows: 535 research/host + 25 map mixers).
60pub const CATALOG_JSON: &str = include_str!("../catalog/operators.json");
61/// Slim PCVC spawn table (M7 / E9): 560 rows, no graph block.
62pub const DISPATCH_JSON: &str = include_str!("../catalog/dispatch.json");
63
64static CATALOG: OnceLock<Vec<OperatorSpec>> = OnceLock::new();
65
66/// Frozen catalog (560 rows). Parsed once per process.
67#[must_use]
68pub fn catalog() -> &'static [OperatorSpec] {
69    CATALOG
70        .get_or_init(|| {
71            serde_json::from_str(CATALOG_JSON)
72                .expect("catalog/operators.json is generated valid JSON")
73        })
74        .as_slice()
75}
76
77/// Look up one catalog row by `BIN.*` (interned, O(1)).
78#[must_use]
79pub fn spec_by_id(binary_id: &str) -> Option<&'static OperatorSpec> {
80    intern_maps()
81        .by_id
82        .get(binary_id)
83        .copied()
84}
85
86/// Look up one catalog row by operator name (`PEOPLE`, `TAG.PERSON_FOUNDER`, …).
87#[must_use]
88pub fn spec_by_operator(operator: &str) -> Option<&'static OperatorSpec> {
89    intern_maps()
90        .by_operator
91        .get(operator)
92        .copied()
93}
94
95/// Look up one catalog row by cargo package.
96#[must_use]
97pub fn spec_by_package(package: &str) -> Option<&'static OperatorSpec> {
98    intern_maps()
99        .by_package
100        .get(package)
101        .copied()
102}
103
104/// Residual + DEEP_TAG specs whose `parent` is this family operator (E10).
105#[must_use]
106pub fn family_residuals(parent: &str) -> &'static [&'static OperatorSpec] {
107    intern_maps()
108        .family
109        .get(parent)
110        .map_or(&[], Vec::as_slice)
111}
112
113/// Research binaries that declare this exact anchor tag.
114#[must_use]
115pub fn specs_for_tag(tag: &str) -> &'static [&'static OperatorSpec] {
116    intern_maps()
117        .by_anchor
118        .get(tag)
119        .map_or(&[], Vec::as_slice)
120}
121
122struct InternMaps {
123    by_id: std::collections::HashMap<&'static str, &'static OperatorSpec>,
124    by_operator: std::collections::HashMap<&'static str, &'static OperatorSpec>,
125    by_package: std::collections::HashMap<&'static str, &'static OperatorSpec>,
126    family: std::collections::HashMap<&'static str, Vec<&'static OperatorSpec>>,
127    by_anchor: std::collections::HashMap<&'static str, Vec<&'static OperatorSpec>>,
128}
129
130fn intern_maps() -> &'static InternMaps {
131    static M: OnceLock<InternMaps> = OnceLock::new();
132    M.get_or_init(|| {
133        let cat = catalog();
134        let mut by_id = std::collections::HashMap::with_capacity(cat.len());
135        let mut by_operator = std::collections::HashMap::with_capacity(cat.len());
136        let mut by_package = std::collections::HashMap::with_capacity(cat.len());
137        let mut family: std::collections::HashMap<&str, Vec<&OperatorSpec>> =
138            std::collections::HashMap::new();
139        let mut by_anchor: std::collections::HashMap<&str, Vec<&OperatorSpec>> =
140            std::collections::HashMap::new();
141        for s in cat {
142            by_id.insert(s.binary_id.as_str(), s);
143            by_operator.entry(s.operator.as_str()).or_insert(s);
144            by_package.entry(s.package.as_str()).or_insert(s);
145            if !s.parent.is_empty()
146                && (s.layer.eq_ignore_ascii_case("RESIDUAL")
147                    || s.layer.eq_ignore_ascii_case("DEEP_TAG"))
148            {
149                family.entry(s.parent.as_str()).or_default().push(s);
150            }
151            if !s.layer.eq_ignore_ascii_case("HOST") {
152                for t in &s.anchor_tags {
153                    by_anchor.entry(t.as_str()).or_default().push(s);
154                }
155            }
156        }
157        InternMaps {
158            by_id,
159            by_operator,
160            by_package,
161            family,
162            by_anchor,
163        }
164    })
165}
166
167/// Wave ladder height (sheet 12 `wave` column): A→1, B→2, C→3, D→4.
168#[must_use]
169pub fn wave_height(wave: Option<&str>) -> u8 {
170    match wave.unwrap_or("") {
171        "A" => 1,
172        "B" => 2,
173        "C" => 3,
174        "D" => 4,
175        _ => 0,
176    }
177}
178
179/// Token → (category weight, max wave height) over the frozen catalog.
180/// Weight = # of research binaries declaring the token in 02/03/04 terms
181/// (anchor_tags, node/rel types, property keys); HOST declarations weigh
182/// nothing (B6). Parsed once per process; fully deterministic.
183fn token_stats() -> &'static std::collections::BTreeMap<String, (u32, u8)> {
184    use std::collections::BTreeMap;
185    static STATS: OnceLock<BTreeMap<String, (u32, u8)>> = OnceLock::new();
186    STATS.get_or_init(|| {
187        let mut m: BTreeMap<String, (u32, u8)> = BTreeMap::new();
188        for s in catalog().iter().filter(|s| s.layer != "HOST") {
189            let h = wave_height(s.wave.as_deref());
190            let mut bump = |t: &str| {
191                let e = m.entry(t.to_ascii_lowercase()).or_insert((0, 0));
192                e.0 += 1;
193                e.1 = e.1.max(h);
194            };
195            for t in s
196                .anchor_tags
197                .iter()
198                .chain(s.node_types.iter())
199                .chain(s.relationship_types.iter())
200            {
201                bump(t);
202            }
203            if let Some(k) = s.property_key.as_deref() {
204                bump(k);
205            }
206        }
207        m
208    })
209}
210
211/// (weight, height) of one grammar token: kind, rel type, tag, property key.
212#[must_use]
213pub fn token_stat(token: &str) -> (u32, u8) {
214    token_stats()
215        .get(&token.to_ascii_lowercase())
216        .copied()
217        .unwrap_or((0, 0))
218}
219
220#[cfg(feature = "cli")]
221#[derive(Parser, Debug)]
222#[command(
223    name = "aria-operator",
224    about = "Run one catalog operator: Aria transform + closed operator JSON"
225)]
226struct Cli {
227    /// Payload JSON. `-` or omitted reads stdin.
228    #[arg(long)]
229    r#in: Option<PathBuf>,
230    /// Write the operator envelope here (stdout when omitted).
231    #[arg(short, long)]
232    out: Option<PathBuf>,
233    /// Φ steps.
234    #[arg(long, default_value_t = 32)]
235    steps: u64,
236    /// Seed. Equal payload + spec + seed ⇒ equal bytes.
237    #[arg(long)]
238    seed: Option<u64>,
239    /// Bind this Observation Plan hash (hex). Unbound runs hash the payload.
240    #[arg(long)]
241    plan_hash: Option<String>,
242    /// Coverage key from the sealed plan.
243    #[arg(long)]
244    requirement_id: Option<String>,
245    /// Embed the Aria telemetry spine (sheet 09: optional). Off by default.
246    #[arg(long)]
247    telemetry: bool,
248}
249
250/// CLI entry used by every generated `[[bin]]`. Returns a process exit code.
251#[cfg(feature = "cli")]
252#[must_use]
253pub fn bin_main(spec_json: &str) -> i32 {
254    match bin_main_inner(spec_json) {
255        Ok(()) => 0,
256        Err(code) => code,
257    }
258}
259
260#[cfg(feature = "cli")]
261fn bin_main_inner(spec_json: &str) -> Result<(), i32> {
262    let cli = Cli::parse();
263    let payload = read_payload(cli.r#in.as_deref()).map_err(|e| {
264        eprintln!("aria-operator: {e}");
265        3
266    })?;
267    let opts = RunOpts {
268        steps: cli.steps,
269        seed: cli.seed,
270        plan_hash: cli.plan_hash,
271        requirement_id: cli.requirement_id,
272        include_telemetry: cli.telemetry,
273        ..RunOpts::default()
274    };
275
276    let envelope = run_spec(spec_json, &payload, &opts).map_err(|e| {
277        eprintln!("aria-operator: {e}");
278        e.exit_code()
279    })?;
280    let bytes = serde_json::to_vec(&envelope).map_err(|e| {
281        eprintln!("aria-operator: serialize: {e}");
282        2
283    })?;
284    write_sink(cli.out.as_deref(), &bytes).map_err(|e| {
285        eprintln!("aria-operator: {e}");
286        3
287    })?;
288    Ok(())
289}
290
291#[cfg(feature = "cli")]
292fn read_payload(path: Option<&std::path::Path>) -> io::Result<Vec<u8>> {
293    match path {
294        None => {
295            let mut buf = Vec::new();
296            io::stdin().read_to_end(&mut buf)?;
297            Ok(buf)
298        }
299        Some(p) if p.as_os_str() == "-" => {
300            let mut buf = Vec::new();
301            io::stdin().read_to_end(&mut buf)?;
302            Ok(buf)
303        }
304        Some(p) => std::fs::read(p),
305    }
306}
307
308#[cfg(feature = "cli")]
309fn write_sink(path: Option<&std::path::Path>, bytes: &[u8]) -> io::Result<()> {
310    match path {
311        None => {
312            io::stdout().write_all(bytes)?;
313            Ok(())
314        }
315        Some(p) => {
316            std::fs::write(p, bytes)?;
317            Ok(())
318        }
319    }
320}
321
322/// `ExitCode` wrapper for callers that prefer the std type.
323#[cfg(feature = "cli")]
324#[must_use]
325pub fn bin_exit(spec_json: &str) -> ExitCode {
326    ExitCode::from(u8::try_from(bin_main(spec_json)).unwrap_or(2))
327}