agent_control_specification_core 0.3.1-beta.0

Stateless Rust core for Agent Control Specification
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
use agent_control_specification_core::{
    AnnotatorDispatcher, AnnotatorInvocation, AnnotatorType, Decision, EnforcementMode,
    InterventionPoint, InterventionPointRequest, JsonValue, Manifest, PolicyDispatcher,
    PreparedPolicyInvocation, Runtime, RuntimeError,
};
use serde_json::{json, Value};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    path::{Path, PathBuf},
    str::FromStr,
    sync::Arc,
};

fn fixture_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
}

fn load_manifest_fixture(name: &str) -> Manifest {
    let path = fixture_root().join("manifests").join(name);
    let source = fs::read_to_string(&path)
        .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()));
    Manifest::from_yaml_str(&source)
        .unwrap_or_else(|err| panic!("{} did not load: {err}", path.display()))
}

fn load_policy_input_fixture(name: &str) -> Value {
    let path = fixture_root().join("policy-inputs").join(name);
    let source = fs::read_to_string(&path)
        .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()));
    serde_json::from_str(&source)
        .unwrap_or_else(|err| panic!("failed to parse {}: {err}", path.display()))
}

fn assert_manifest_invalid(manifest_yaml: &str) {
    let error = Manifest::from_yaml_str(manifest_yaml).expect_err("manifest should be invalid");
    assert_eq!(error.reason(), "runtime_error:manifest_invalid");
}

#[test]
fn canonical_manifest_fixtures_load_successfully() {
    let manifests_dir = fixture_root().join("manifests");
    let mut paths: Vec<_> = fs::read_dir(&manifests_dir)
        .unwrap_or_else(|err| panic!("failed to read {}: {err}", manifests_dir.display()))
        .map(|entry| entry.unwrap().path())
        .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("yaml"))
        .collect();
    paths.sort();

    let names: BTreeSet<_> = paths
        .iter()
        .map(|path| path.file_name().unwrap().to_string_lossy().to_string())
        .collect();
    assert!(names.contains("canonical-all-interventions.yaml"));
    assert!(names.contains("minimal-all-interventions.yaml"));

    let expected_intervention_points = [
        InterventionPoint::AgentStartup,
        InterventionPoint::Input,
        InterventionPoint::PreModelCall,
        InterventionPoint::PostModelCall,
        InterventionPoint::PreToolCall,
        InterventionPoint::PostToolCall,
        InterventionPoint::Output,
        InterventionPoint::AgentShutdown,
    ];

    for path in paths {
        let source = fs::read_to_string(&path)
            .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()));
        let manifest = Manifest::from_yaml_str(&source)
            .unwrap_or_else(|err| panic!("{} did not load: {err}", path.display()));
        assert!(
            !manifest.policies.is_empty(),
            "{} must use top-level policies",
            path.display()
        );
        for intervention_point in expected_intervention_points {
            assert!(
                manifest
                    .intervention_points
                    .contains_key(&intervention_point),
                "{} missing {intervention_point}",
                path.display()
            );
        }
    }

    let canonical = load_manifest_fixture("canonical-all-interventions.yaml");
    assert_eq!(canonical.extends, vec!["./base-controls.yaml"]);
    assert!(canonical
        .intervention_points
        .values()
        .all(|config| !config.annotations.is_empty()));

    let annotator_types: BTreeSet<_> = canonical
        .annotators
        .values()
        .map(|annotator| annotator.annotator_type.as_str().to_string())
        .collect();
    assert_eq!(
        annotator_types,
        BTreeSet::from([
            AnnotatorType::Classifier.as_str().to_string(),
            AnnotatorType::Llm.as_str().to_string(),
            AnnotatorType::Endpoint.as_str().to_string(),
        ])
    );
}

#[test]
fn manifest_invariants_are_frozen() {
    for intervention_point in ["agent_startup", "output", "agent_shutdown"] {
        assert_eq!(
            InterventionPoint::from_str(intervention_point)
                .unwrap()
                .as_str(),
            intervention_point
        );
    }
    for removed_or_alias in ["startup", "shutdown", "final_output", "state", "endpoint"] {
        assert!(InterventionPoint::from_str(removed_or_alias).is_err());
    }

    let valid = Manifest::from_yaml_str(
        r#"agent_control_specification_version: "0.3.1-beta"
extends:
  - ./base.yaml
policies:
  test_policy:
    type: test
intervention_points:
  input:
    policy_target: "$snap.input"
    policy_target_kind: user_input
    annotations:
      classifier:
        from: "$policy_target.text"
    policy:
      id: test_policy
annotators:
  classifier:
    type: classifier
  judge:
    type: llm
  actor_lookup:
    type: endpoint
"#,
    )
    .unwrap();
    assert_eq!(valid.extends, vec!["./base.yaml"]);
    assert!(valid.policies.contains_key("test_policy"));
    assert!(valid.intervention_points[&InterventionPoint::Input]
        .annotations
        .contains_key("classifier"));

    assert_manifest_invalid(
        r#"agent_control_specification_version: "0.3.1-beta"
extends: ./base.yaml
policies:
  test_policy:
    type: test
intervention_points:
  input:
    policy_target: "$snap.input"
    policy:
      id: test_policy
"#,
    );

    assert_manifest_invalid(
        r#"agent_control_specification_version: "0.3.1-beta"
policies:
  test_policy:
    type: test
intervention_points:
  startup:
    policy_target: "$snap.agent"
    policy:
      id: test_policy
"#,
    );

    assert_manifest_invalid(
        r#"agent_control_specification_version: "0.3.1-beta"
policies:
  test_policy:
    type: test
intervention_points:
  input:
    policy_target: "$pi.input"
    policy:
      id: test_policy
"#,
    );

    assert_manifest_invalid(
        r#"agent_control_specification_version: "0.3.1-beta"
policies:
  test_policy:
    type: test
intervention_points:
  input:
    policy:
      id: test_policy
"#,
    );

    assert_manifest_invalid(
        r#"agent_control_specification_version: "0.3.1-beta"
intervention_points:
  input:
    policy_target: "$snap.input"
    policy:
      id: test_policy
"#,
    );

    assert_manifest_invalid(
        r#"agent_control_specification_version: "0.3.1-beta"
policies:
  test_policy:
    type: test
intervention_points:
  input:
    policy_target: "$snap.input"
    policy:
      type: test
"#,
    );

    assert_manifest_invalid(
        r#"agent_control_specification_version: "0.3.1-beta"
policies:
  test_policy:
    type: test
intervention_points:
  input:
    policy_target: "$snap.input"
    policy:
      id: test_policy
annotators:
  classifier:
    type: regex
"#,
    );

    assert_manifest_invalid(
        r#"agent_control_specification_version: "0.3.1-beta"
policies:
  test_policy:
    type: test
annotations:
  classifier:
    from: "$snap.input.text"
intervention_points:
  input:
    policy_target: "$snap.input"
    policy:
      id: test_policy
annotators:
  classifier:
    type: classifier
"#,
    );
}

struct GoldenAnnotator {
    responses: BTreeMap<String, JsonValue>,
}

impl AnnotatorDispatcher for GoldenAnnotator {
    fn dispatch(
        &self,
        annotator_name: &str,
        _annotator: &AnnotatorInvocation,
        _preliminary_policy_input: &JsonValue,
    ) -> Result<JsonValue, RuntimeError> {
        Ok(self
            .responses
            .get(annotator_name)
            .cloned()
            .unwrap_or(JsonValue::Null))
    }
}

struct AllowPolicy;

impl PolicyDispatcher for AllowPolicy {
    fn evaluate(&self, _invocation: &PreparedPolicyInvocation) -> Result<JsonValue, RuntimeError> {
        Ok(json!({"decision": "allow"}))
    }
}

#[test]
fn golden_policy_input_fixtures_match_runtime_contract() {
    let mut manifest = load_manifest_fixture("canonical-all-interventions.yaml");
    // The fixture carries `extends` purely to prove the field round-trips as data
    // (see canonical_manifest_fixtures_load_successfully); it is otherwise
    // self-contained, so clear the unresolved reference before building a runtime,
    // matching what a file-based loader does after composing the bases.
    manifest.extends.clear();
    let mut responses = BTreeMap::new();
    responses.insert("actor_context".to_string(), json!({"tier": "gold"}));
    responses.insert(
        "output_safety".to_string(),
        json!({"contains_pii": false, "risk": "low"}),
    );
    responses.insert(
        "prompt_classifier".to_string(),
        json!({"categories": [], "risk": "low"}),
    );
    responses.insert(
        "startup_context".to_string(),
        json!({"deployment": "prod", "region": "us-east"}),
    );
    responses.insert(
        "shutdown_context".to_string(),
        json!({"reason_seen": "completed"}),
    );
    responses.insert(
        "tool_risk".to_string(),
        json!({"data_labels": ["public"], "risk": "low"}),
    );

    let runtime = Runtime::new(
        manifest,
        Arc::new(GoldenAnnotator { responses }),
        Arc::new(AllowPolicy),
    )
    .unwrap();

    let cases = [
        (
            InterventionPoint::AgentStartup,
            json!({
                "agent": {"id": "agent-007", "version": "1.0.0"},
                "metadata": {"deployment": "prod"}
            }),
            "agent-startup.json",
        ),
        (
            InterventionPoint::PreModelCall,
            json!({
                "conversation": {"id": "conv-123"},
                "model_request": {
                    "messages": [
                        {"content": "Be helpful.", "role": "system"},
                        {"content": "Summarize account policy.", "role": "user"}
                    ],
                    "params": {"temperature": 0},
                    "tools": [{"name": "search"}]
                }
            }),
            "pre-model-call.json",
        ),
        (
            InterventionPoint::AgentShutdown,
            json!({
                "agent": {"id": "agent-007", "version": "1.0.0"},
                "metadata": {"deployment": "prod"},
                "reason": "completed"
            }),
            "agent-shutdown.json",
        ),
        (
            InterventionPoint::PreToolCall,
            json!({
                "action": "invokeTool",
                "actor": {"id": "user-123", "type": "User"},
                "tool_call": {
                    "args": {"limit": 5, "query": "account policy"},
                    "id": "tool-call-1",
                    "name": "search"
                }
            }),
            "pre-tool-call.json",
        ),
        (
            InterventionPoint::Output,
            json!({
                "output": {
                    "citations": ["policy-doc-1"],
                    "content": "Your account policy summary is ready."
                }
            }),
            "output.json",
        ),
    ];

    for (intervention_point, snapshot, fixture_name) in cases {
        let result = runtime.evaluate_intervention_point(InterventionPointRequest {
            intervention_point,
            snapshot,
            mode: EnforcementMode::Enforce,
        });
        assert_eq!(result.verdict.decision, Decision::Allow, "{fixture_name}");
        let actual = result
            .policy_input
            .expect("policy input should be available");
        let expected = load_policy_input_fixture(fixture_name);
        assert_eq!(actual, expected, "{fixture_name}");

        let root = actual
            .as_object()
            .expect("policy input root should be an object");
        assert!(root.contains_key("annotations"));
        assert!(root.contains_key("snapshot"));
        assert!(root.contains_key("policy_target"));
        assert!(root.contains_key("tool"));
        assert!(!root.contains_key("request"));
        assert!(!root.contains_key("resource"));
        assert!(!root.contains_key("tools"));
    }
}