runx-runtime 0.6.19

Native Rust runtime for local runx execution, adapters, harness replay, receipts, and sandboxing.
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
// rust-style-allow: large-file because harness fixture parsing, typed diagnostics,
// and expectation normalization stay together for the cutover review surface.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use runx_contracts::{ClosureDisposition, JsonObject, ReceiptSchema};
use serde::Deserialize;
use thiserror::Error;

const RETIRED_RECEIPT_FIELDS: &[&str] =
    &["kind", "skill_name", "source_type", "graph_name", "owner"];

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HarnessFixtureCase {
    pub name: &'static str,
    pub fixture_path: &'static str,
    pub root_oracle_path: &'static str,
    pub step_oracles: &'static [HarnessFixtureStepOracle],
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HarnessFixtureStepOracle {
    pub step_id: &'static str,
    pub oracle_path: &'static str,
}

const HARNESS_FIXTURE_CASES: &[HarnessFixtureCase] = &[
    HarnessFixtureCase {
        name: "echo-skill",
        fixture_path: "fixtures/harness/echo-skill.yaml",
        root_oracle_path: "fixtures/harness/oracle/echo-skill.receipt.json",
        step_oracles: &[],
    },
    HarnessFixtureCase {
        name: "sequential-graph",
        fixture_path: "fixtures/harness/sequential-graph.yaml",
        root_oracle_path: "fixtures/harness/oracle/sequential-graph.receipt.json",
        step_oracles: &[
            HarnessFixtureStepOracle {
                step_id: "first",
                oracle_path: "fixtures/harness/oracle/sequential-graph.first.json",
            },
            HarnessFixtureStepOracle {
                step_id: "second",
                oracle_path: "fixtures/harness/oracle/sequential-graph.second.json",
            },
        ],
    },
];

#[must_use]
pub fn list_cases() -> &'static [HarnessFixtureCase] {
    HARNESS_FIXTURE_CASES
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessFixtureKind {
    Skill,
    Graph,
    Mcp,
    A2a,
    Agent,
    #[serde(rename = "agent_task")]
    AgentStep,
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessExpectedStatus {
    Sealed,
    Failure,
    NeedsAgent,
    PolicyDenied,
    Escalated,
}

#[derive(Clone, Debug, PartialEq)]
pub struct HarnessFixture {
    pub name: String,
    pub kind: HarnessFixtureKind,
    pub target: String,
    pub runner: Option<String>,
    pub inputs: JsonObject,
    pub env: BTreeMap<String, String>,
    pub caller: JsonObject,
    pub expect: HarnessExpectation,
    pub metadata: JsonObject,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct HarnessExpectation {
    pub status: Option<HarnessExpectedStatus>,
    pub receipt: Option<ReceiptExpectation>,
    pub steps: Vec<String>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ReceiptExpectation {
    pub schema: ReceiptSchema,
    pub body_digest: Option<String>,
    pub receipt_id: Option<String>,
    pub receipt_digest: Option<String>,
    pub harness_id: Option<String>,
    pub state: Option<String>,
    pub disposition: Option<ClosureDisposition>,
    pub reason_code: Option<String>,
    pub act_ids: Vec<String>,
    pub decision_ids: Vec<String>,
    pub child_receipt_refs: Vec<String>,
    pub verification_refs: Vec<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawHarnessFixture {
    name: String,
    kind: HarnessFixtureKind,
    #[serde(default)]
    target: Option<String>,
    runner: Option<String>,
    #[serde(default)]
    inputs: JsonObject,
    #[serde(default)]
    env: BTreeMap<String, String>,
    #[serde(default)]
    caller: JsonObject,
    #[serde(default)]
    expect: RawHarnessExpectation,
    #[serde(default)]
    metadata: JsonObject,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawHarnessExpectation {
    status: Option<HarnessExpectedStatus>,
    receipt: Option<RawReceiptExpectation>,
    #[serde(default)]
    steps: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct RawReceiptExpectation {
    #[serde(default = "default_receipt_schema")]
    schema: ReceiptSchema,
    body_digest: Option<String>,
    receipt_id: Option<String>,
    receipt_digest: Option<String>,
    harness_id: Option<String>,
    state: Option<String>,
    disposition: Option<ClosureDisposition>,
    reason_code: Option<String>,
    #[serde(default)]
    act_ids: Vec<String>,
    #[serde(default)]
    decision_ids: Vec<String>,
    #[serde(default)]
    child_receipt_refs: Vec<String>,
    #[serde(default)]
    verification_refs: Vec<String>,
    #[serde(flatten)]
    extra: BTreeMap<String, serde::de::IgnoredAny>,
}

#[derive(Debug, Error)]
pub enum HarnessFixtureError {
    #[error("failed to read harness fixture {path}: {source}")]
    Read {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("failed to parse harness fixture YAML: {0}")]
    Parse(#[from] serde_norway::Error),
    #[error("harness fixture {field} is required")]
    Required { field: String },
    #[error("harness fixture {field} must not be empty")]
    Empty { field: &'static str },
    #[error("retired receipt expectation field {field_path}")]
    RetiredReceiptField { field_path: String },
    #[error("unknown receipt expectation field {field_path}")]
    UnknownReceiptField { field_path: String },
    #[error("harness fixture mode {mode} at {field_path} is not yet supported by the Rust harness")]
    UnsupportedFixtureMode { mode: String, field_path: String },
}

pub fn load_harness_fixture(path: impl AsRef<Path>) -> Result<HarnessFixture, HarnessFixtureError> {
    let path = path.as_ref();
    let contents = fs::read_to_string(path).map_err(|source| HarnessFixtureError::Read {
        path: path.to_path_buf(),
        source,
    })?;
    parse_harness_fixture(&contents)
}

pub fn parse_harness_fixture(contents: &str) -> Result<HarnessFixture, HarnessFixtureError> {
    let fixture = serde_norway::from_str::<RawHarnessFixture>(contents)?;
    validate_fixture(fixture)
}

fn validate_fixture(fixture: RawHarnessFixture) -> Result<HarnessFixture, HarnessFixtureError> {
    require_non_empty(&fixture.name, "name")?;
    validate_supported_fixture_kind(&fixture.kind, "kind")?;
    let target = fixture.target.unwrap_or_default();
    if !matches!(fixture.kind, HarnessFixtureKind::AgentStep) {
        require_non_empty(&target, "target")?;
    }
    if let Some(runner) = &fixture.runner {
        require_non_empty(runner, "runner")?;
    }
    Ok(HarnessFixture {
        name: fixture.name,
        kind: fixture.kind,
        target,
        runner: fixture.runner,
        inputs: fixture.inputs,
        env: fixture.env,
        caller: fixture.caller,
        expect: validate_expectation(fixture.expect)?,
        metadata: fixture.metadata,
    })
}

fn validate_expectation(
    expectation: RawHarnessExpectation,
) -> Result<HarnessExpectation, HarnessFixtureError> {
    Ok(HarnessExpectation {
        status: expectation.status,
        receipt: expectation
            .receipt
            .map(validate_receipt_expectation)
            .transpose()?,
        steps: expectation.steps,
    })
}

fn validate_receipt_expectation(
    receipt: RawReceiptExpectation,
) -> Result<ReceiptExpectation, HarnessFixtureError> {
    if let Some(field) = receipt.extra.keys().next() {
        let field_path = format!("expect.receipt.{field}");
        if is_retired_receipt_field(field) {
            return Err(HarnessFixtureError::RetiredReceiptField { field_path });
        }
        return Err(HarnessFixtureError::UnknownReceiptField { field_path });
    }
    Ok(ReceiptExpectation {
        schema: receipt.schema,
        body_digest: receipt.body_digest,
        receipt_id: receipt.receipt_id,
        receipt_digest: receipt.receipt_digest,
        harness_id: receipt.harness_id,
        state: receipt.state,
        disposition: receipt.disposition,
        reason_code: receipt.reason_code,
        act_ids: receipt.act_ids,
        decision_ids: receipt.decision_ids,
        child_receipt_refs: receipt.child_receipt_refs,
        verification_refs: receipt.verification_refs,
    })
}

fn is_retired_receipt_field(field: &str) -> bool {
    RETIRED_RECEIPT_FIELDS.contains(&field)
        || field == retired_execution_receipt_field("skill")
        || field == retired_execution_receipt_field("graph")
}

fn retired_execution_receipt_field(prefix: &str) -> String {
    format!("{prefix}_{}", "execution")
}

fn validate_supported_fixture_kind(
    kind: &HarnessFixtureKind,
    field_path: &'static str,
) -> Result<(), HarnessFixtureError> {
    match kind {
        HarnessFixtureKind::Skill
        | HarnessFixtureKind::Graph
        | HarnessFixtureKind::A2a
        | HarnessFixtureKind::Agent
        | HarnessFixtureKind::AgentStep => Ok(()),
        HarnessFixtureKind::Mcp => Err(HarnessFixtureError::UnsupportedFixtureMode {
            mode: fixture_kind_name(kind).to_owned(),
            field_path: field_path.to_owned(),
        }),
    }
}

pub(crate) fn fixture_kind_name(kind: &HarnessFixtureKind) -> &'static str {
    match kind {
        HarnessFixtureKind::Skill => "skill",
        HarnessFixtureKind::Graph => "graph",
        HarnessFixtureKind::Mcp => "mcp",
        HarnessFixtureKind::A2a => "a2a",
        HarnessFixtureKind::Agent => "agent",
        HarnessFixtureKind::AgentStep => "agent_task",
    }
}

fn require_non_empty(value: &str, field: &'static str) -> Result<(), HarnessFixtureError> {
    if value.is_empty() {
        Err(HarnessFixtureError::Empty { field })
    } else {
        Ok(())
    }
}

fn default_receipt_schema() -> ReceiptSchema {
    ReceiptSchema::V1
}

#[cfg(test)]
mod tests {
    use super::{
        HarnessFixtureError, HarnessFixtureKind, ReceiptSchema, parse_harness_fixture,
        retired_execution_receipt_field,
    };

    #[test]
    fn parses_post_cutover_receipt_expectation() -> Result<(), HarnessFixtureError> {
        let fixture = parse_harness_fixture(
            r#"
name: echo-skill
kind: skill
target: ../skills/echo
inputs:
  message: hello
expect:
  status: sealed
  receipt:
    schema: runx.receipt.v1
    body_digest: sha256:test
    harness_id: echo-skill
    state: sealed
    disposition: closed
    reason_code: harness_replay_passed
    act_ids:
      - echo
"#,
        )?;

        assert_eq!(fixture.kind, HarnessFixtureKind::Skill);
        let receipt = fixture
            .expect
            .receipt
            .ok_or(HarnessFixtureError::Required {
                field: "expect.receipt".to_owned(),
            })?;
        assert_eq!(receipt.schema, ReceiptSchema::V1);
        assert_eq!(receipt.state.as_deref(), Some("sealed"));
        assert_eq!(receipt.act_ids, vec!["echo"]);
        Ok(())
    }

    #[test]
    fn rejects_retired_receipt_expectation_fields() {
        for field in [
            "kind".to_owned(),
            retired_execution_receipt_field("skill"),
            retired_execution_receipt_field("graph"),
        ] {
            let result = parse_harness_fixture(&format!(
                r#"
name: old
kind: skill
target: ../skills/echo
expect:
  receipt:
    {field}: value
"#,
            ));

            assert!(matches!(
                result,
                Err(HarnessFixtureError::RetiredReceiptField { field_path })
                    if field_path == format!("expect.receipt.{field}")
            ));
        }
    }

    #[test]
    fn rejects_unsupported_fixture_modes_with_stable_diagnostic() {
        let result = parse_harness_fixture(
            r#"
name: old
kind: mcp
target: ../skills/echo
expect:
  status: sealed
"#,
        );

        assert!(matches!(
            result,
            Err(HarnessFixtureError::UnsupportedFixtureMode { mode, field_path })
                if mode == "mcp" && field_path == "kind"
        ));
    }

    #[test]
    fn rejects_unknown_receipt_expectation_fields() {
        let result = parse_harness_fixture(
            r#"
name: old
kind: skill
target: ../skills/echo
expect:
  receipt:
    unexpected: value
"#,
        );

        assert!(matches!(
            result,
            Err(HarnessFixtureError::UnknownReceiptField { field_path })
                if field_path == "expect.receipt.unexpected"
        ));
    }
}