Skip to main content

aria_operator/
work_api.rs

1//! JSON-CLI protocol for the work gateway.
2//!
3//! A worker (or Aria compiling a hosted command list) sends one JSON object.
4//! The gateway never invents a `BIN.*`. Unknown ops fail closed.
5
6use serde::{Deserialize, Serialize};
7use serde_json::{json, Value};
8
9use crate::catalog;
10use crate::organize::{organize_slop, OrganizeReport};
11use crate::run::{run_binary, run_many, OperatorError, RunOpts};
12
13/// Schema tag for a compiled work response.
14pub const WORK_V1: &str = "aria-work-v1";
15
16/// JSON command the nervous-system gateway accepts.
17#[derive(Debug, Clone, Default, Deserialize)]
18pub struct WorkRequest {
19    /// Dump the hosted command list and stop.
20    #[serde(default)]
21    pub commands: bool,
22    /// One `BIN.*` (or operator name).
23    #[serde(default)]
24    pub work: Option<String>,
25    /// Many `BIN.*` / operator names. One Φ, N verticals.
26    #[serde(default)]
27    pub ops: Vec<String>,
28    /// Host payload. Required unless `commands` is true.
29    #[serde(default, rename = "in")]
30    pub payload: Option<Value>,
31    /// Embed the Aria spine. Default off.
32    #[serde(default)]
33    pub telemetry: bool,
34    /// Φ steps.
35    #[serde(default)]
36    pub steps: Option<u64>,
37    /// Seed.
38    #[serde(default)]
39    pub seed: Option<u64>,
40    /// Plan bind.
41    #[serde(default)]
42    pub plan_hash: Option<String>,
43    /// Coverage key.
44    #[serde(default)]
45    pub requirement_id: Option<String>,
46}
47
48/// Compiled results. Zero Trust: no Trust/Use/Goal keys.
49///
50/// Production contract: `results` holds **working verticals only**. A binary
51/// that cannot tag the payload is omitted — not returned as an empty
52/// skeleton. `asked` is how many identities were named; `ops` is how many
53/// came back with nodes, relationships, or properties.
54#[derive(Debug, Clone, Serialize)]
55pub struct WorkResponse {
56    /// Always [`WORK_V1`].
57    pub schema: String,
58    /// True when one transform served every op.
59    pub phi_once: bool,
60    /// How many catalog identities were named (compiled).
61    pub asked: usize,
62    /// How many working envelopes are in `results`.
63    pub ops: usize,
64    /// Tokens, listed hits, and binaries that will structure this slop.
65    pub organize: OrganizeReport,
66    /// Working verticals only. Missing data is absence, not an empty object.
67    pub results: Vec<Value>,
68}
69
70/// Filter a projection set down to envelopes a PCVC worker or Neo4j driver
71/// can consume. Dump scoring still uses the unfiltered `run_many` set.
72#[must_use]
73pub fn callback_results(envs: &[crate::OperatorEnvelope]) -> Vec<&crate::OperatorEnvelope> {
74    envs.iter().filter(|e| e.has_working_data()).collect()
75}
76
77/// Hosted command list — what Aria compiles against.
78#[must_use]
79pub fn commands_json() -> Value {
80    let mut rows: Vec<Value> = catalog()
81        .iter()
82        .map(|s| {
83            json!({
84                "binary_id": s.binary_id,
85                "operator": s.operator,
86                "package": s.package,
87                "layer": s.layer,
88                "class": s.class,
89                "resultDefinitionRef": s.result_definition_ref,
90                "verify": s.verify,
91                "cli": format!("work --binary {}", s.binary_id),
92            })
93        })
94        .collect();
95    rows.sort_by(|a, b| {
96        a["binary_id"]
97            .as_str()
98            .unwrap_or("")
99            .cmp(b["binary_id"].as_str().unwrap_or(""))
100    });
101    json!({
102        "schema": "aria-work-commands-v1",
103        "count": rows.len(),
104        "commands": rows,
105    })
106}
107
108/// Execute a JSON work request.
109pub fn execute_work(req: &WorkRequest, opts_overlay: &RunOpts) -> Result<Value, OperatorError> {
110    if req.commands {
111        return Ok(commands_json());
112    }
113
114    let mut opts = opts_overlay.clone();
115    if let Some(s) = req.steps {
116        opts.steps = s;
117    }
118    if req.seed.is_some() {
119        opts.seed = req.seed;
120    }
121    if req.plan_hash.is_some() {
122        opts.plan_hash.clone_from(&req.plan_hash);
123    }
124    if req.requirement_id.is_some() {
125        opts.requirement_id.clone_from(&req.requirement_id);
126    }
127    opts.include_telemetry = req.telemetry;
128
129    let payload = match &req.payload {
130        Some(v) => serde_json::to_vec(v)?,
131        None => {
132            return Err(OperatorError::Spec(
133                "work JSON requires 'in' payload unless commands=true".into(),
134            ));
135        }
136    };
137
138    let ids = resolve_ops(req)?;
139    let asked = ids.len();
140    let envs = if asked == 1 {
141        vec![run_binary(&ids[0], &payload, &opts)?]
142    } else {
143        run_many(&ids, &payload, &opts)?
144    };
145    let results: Vec<Value> = callback_results(&envs)
146        .into_iter()
147        .map(serde_json::to_value)
148        .collect::<Result<_, _>>()?;
149    Ok(serde_json::to_value(WorkResponse {
150        schema: WORK_V1.into(),
151        phi_once: true,
152        asked,
153        ops: results.len(),
154        organize: organize_slop(&payload),
155        results,
156    })?)
157}
158
159fn resolve_ops(req: &WorkRequest) -> Result<Vec<String>, OperatorError> {
160    let mut ids = Vec::new();
161    if let Some(w) = &req.work {
162        ids.push(resolve_one(w)?);
163    }
164    for op in &req.ops {
165        ids.push(resolve_one(op)?);
166    }
167    if ids.is_empty() {
168        return Err(OperatorError::Spec(
169            "name work or ops[] from the hosted command list".into(),
170        ));
171    }
172    Ok(ids)
173}
174
175fn resolve_one(name: &str) -> Result<String, OperatorError> {
176    if let Some(s) = crate::spec_by_id(name) {
177        return Ok(s.binary_id.clone());
178    }
179    if let Some(e) = crate::endpoint_by_operator(name) {
180        return Ok(e.binary_id);
181    }
182    if let Some(e) = crate::endpoint_by_package(name) {
183        return Ok(e.binary_id);
184    }
185    Err(OperatorError::UnknownBinary(name.to_string()))
186}
187
188/// True if a JSON value looks like a work command rather than a raw payload.
189#[must_use]
190pub fn looks_like_work_command(v: &Value) -> bool {
191    v.get("commands")
192        .and_then(Value::as_bool)
193        .unwrap_or(false)
194        || v.get("work").is_some()
195        || v.get("ops").and_then(Value::as_array).is_some_and(|a| !a.is_empty())
196}
197
198