aion-cli 0.31.0

The `aion` command line: operate Aion durable workflows over gRPC and run the Aion server.
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! Tests for the agent worker's derived surface and its configuration contract.
//!
//! Every fixture is written to a path carrying this process's id, so concurrent
//! tests in this binary never read each other's document.

use std::collections::BTreeSet;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde_json::{Value, json};

use super::args::{self, AgentArgs};
use super::surface;
use crate::settings::Environment;
use crate::worker_surface::{self, ServingSource};

type TestResult = Result<(), Box<dyn Error>>;

/// A document declaring one queue with one bodyless agent action. The narration
/// lines before the `workflow` header are required by the checker.
const DOCUMENT: &str = r"//! reviewer: the document an agent worker derives its advertised surface from.
workflow review_flow
  input brief: String

  outcome reviewed: type Review, route success

/// What the agent reported back.
type Review {
  verdict: String,
  detail: String,
}

/// The queue an agent worker serves.
worker reviewers
  action review(brief: String) -> Review

step do_review
  brief |> review |> route reviewed
";

/// Writes `source` to a uniquely named document so concurrent tests never read
/// each other's fixture.
fn write_document(label: &str, source: &str) -> Result<PathBuf, Box<dyn Error>> {
    let directory =
        std::env::temp_dir().join(format!("aion-agent-worker-{}-{label}", std::process::id()));
    std::fs::create_dir_all(&directory)?;
    let path = directory.join("document.awl");
    std::fs::write(&path, source)?;
    Ok(path)
}

/// Arguments with only the document set — the shape `--check` is invoked with.
fn args_for(document: &Path) -> AgentArgs {
    AgentArgs {
        awl: Some(document.to_path_buf()),
        liminal_addresses: Vec::new(),
        task_queue: None,
        identity: None,
        node: None,
        check: false,
    }
}

/// THE REGRESSION THAT MATTERS. A worker advertising an empty action surface is
/// refused by contract admission on every queue carrying a deployed contract — and
/// AWL emits a contract for every `worker` block, so that is every queue this verb
/// exists to serve. The surface must be non-empty and must carry the DOCUMENT's own
/// schemas, not a permissive stand-in.
#[test]
fn the_advertised_surface_is_the_documents_and_is_not_empty() -> TestResult {
    let document = write_document("advertises", DOCUMENT)?;
    let surface = surface::derive(&document, None)?;

    assert_eq!(surface.task_queue, "reviewers");
    assert_eq!(
        surface.descriptors.len(),
        1,
        "the queue's one bodyless action must be advertised, got {:?}",
        surface.descriptors
    );
    assert_eq!(surface.descriptors[0].name, "review");
    // The document's own types: `review` takes a named `brief` parameter and
    // returns a declared record, advertised in the `$ref` + `$defs` form the
    // server's subset check resolves.
    assert_eq!(
        surface.descriptors[0].input_schema["properties"]["brief"]["type"],
        json!("string")
    );
    assert_eq!(
        surface.descriptors[0].output_schema["$ref"],
        json!("#/$defs/Review")
    );
    assert_eq!(
        surface.descriptors[0].output_schema["$defs"]["Review"]["properties"]["verdict"]["type"],
        json!("string")
    );
    Ok(())
}

/// A document declaring exactly one `worker` block leaves nothing to choose, so the
/// queue is DERIVED — that is unambiguous derivation, not an assumed default.
#[test]
fn a_single_worker_block_derives_the_queue_without_a_flag() -> TestResult {
    let document = write_document("derived", DOCUMENT)?;
    assert_eq!(surface::derive(&document, None)?.task_queue, "reviewers");
    // An explicit selection of the same queue agrees with the derivation.
    assert_eq!(
        surface::derive(&document, Some("reviewers"))?.task_queue,
        "reviewers"
    );
    Ok(())
}

/// Two worker blocks make the queue genuinely ambiguous. Guessing one would serve
/// the wrong queue silently, so the verb refuses and names every choice.
#[test]
fn a_multi_worker_document_refuses_and_names_every_choice() -> TestResult {
    let document = write_document("ambiguous", &two_worker_document())?;
    let Err(error) = surface::derive(&document, None) else {
        return Err("a document declaring two queues must not pick one".into());
    };
    let error = error.to_string();
    assert!(
        error.contains("reviewers") && error.contains("summarisers"),
        "the refusal must name every choice, got: {error}"
    );
    assert!(
        error.contains("--task-queue"),
        "the refusal must name the flag that selects one, got: {error}"
    );

    // And the flag resolves it, in either direction.
    assert_eq!(
        surface::derive(&document, Some("summarisers"))?.task_queue,
        "summarisers"
    );
    assert_eq!(
        surface::derive(&document, Some("reviewers"))?.task_queue,
        "reviewers"
    );
    Ok(())
}

/// A selected queue the document does not declare is refused naming both the
/// selection and what the document actually declares.
#[test]
fn a_queue_the_document_does_not_declare_is_refused() -> TestResult {
    let document = write_document("wrongqueue", DOCUMENT)?;
    let Err(error) = surface::derive(&document, Some("nobody")) else {
        return Err("a queue absent from the document must be refused".into());
    };
    let error = error.to_string();
    assert!(
        error.contains("nobody") && error.contains("reviewers"),
        "the refusal must name the selection and the declaration, got: {error}"
    );
    Ok(())
}

/// An action whose body the document carries is executed by the SERVER from the
/// deployed contract. It is not this worker's to run, so it must not appear in the
/// advertisement either — a worker claiming it would shadow the declared body.
#[test]
fn a_body_carrying_action_is_excluded_from_the_surface() -> TestResult {
    let document = write_document("mixed", MIXED_BODY_DOCUMENT)?;
    let surface = surface::derive(&document, None)?;

    assert_eq!(
        surface.names(),
        BTreeSet::from([String::from("review")]),
        "only the bodyless action is the worker's to serve"
    );
    Ok(())
}

/// A queue whose EVERY action carries a declared body leaves an agent worker with
/// nothing to advertise, and an empty advertisement is refused by every
/// contract-bearing queue. Refuse here, where the reason is readable, rather than
/// remotely.
#[test]
fn a_queue_of_only_bodied_actions_is_refused_by_name() -> TestResult {
    let document = write_document("allbodied", ALL_BODIED_DOCUMENT)?;
    let Err(error) = surface::derive(&document, None) else {
        return Err("a queue with nothing for a worker to serve must be refused".into());
    };
    let error = error.to_string();
    assert!(
        error.contains("declared body") && error.contains("run"),
        "the refusal must name the rule and the action, got: {error}"
    );
    Ok(())
}

/// Serving is all-or-nothing across a queue: a worker admitted on some of a queue's
/// actions is then dispatched one it never declared. The agent worker derives its
/// served set from the document and runs it through this shared rule, so the rule is
/// pinned here on a deliberately narrowed set.
#[test]
fn a_partially_served_queue_is_refused_by_name() -> TestResult {
    let document = write_document("partial", &two_action_document())?;
    let contract = worker_surface::compile_contract(&document)?;
    let worker = worker_surface::select_worker(&document, &contract, None, "--task-queue")?;
    // The whole queue reconciles.
    let whole = worker_surface::serviceable_action_names(worker);
    assert_eq!(
        whole,
        BTreeSet::from([String::from("review"), String::from("summarise")])
    );
    assert_eq!(
        worker_surface::reconcile(&document, worker, &whole, AGENT_SOURCE)?.len(),
        2
    );

    // Dropping one is refused, by name, with the rule stated.
    let partial = BTreeSet::from([String::from("review")]);
    let Err(error) = worker_surface::reconcile(&document, worker, &partial, AGENT_SOURCE) else {
        return Err("a queue must be served whole or not at all".into());
    };
    let error = error.to_string();
    assert!(
        error.contains("summarise") && error.contains("whole queue or none"),
        "the refusal must name the unserved action and the rule, got: {error}"
    );
    Ok(())
}

/// The wording the agent worker's refusals use, mirroring the verb's own source.
const AGENT_SOURCE: ServingSource = ServingSource {
    subject: "the agent worker",
    serves: "serves",
    omits: "does not serve",
};

/// A document that does not compile has no surface to derive, and saying so beats
/// advertising nothing and being refused remotely.
#[test]
fn a_document_that_does_not_compile_is_refused_with_its_diagnostics() -> TestResult {
    let document = write_document("broken", "//! broken\nworkflow \n")?;
    let Err(error) = surface::derive(&document, None) else {
        return Err("an uncompilable document must be refused".into());
    };
    assert!(
        error.to_string().contains("does not compile"),
        "the refusal must say the document does not compile, got: {error}"
    );
    Ok(())
}

/// Every connection setting must be supplied. A worker started from a shell should
/// need ONE correction, not two — so every missing setting is named at once, by both
/// the flag and the variable that could supply it.
///
/// The set is deliberately SHORT now: concurrency and the three reconnect settings are
/// declared in the document's `harness` section and are no longer flags, so a missing
/// one is refused by `aion awl check` with the field named, long before a worker is
/// started. What is left is what genuinely belongs to this process on this box.
#[test]
fn missing_settings_are_reported_by_name_and_all_at_once() -> TestResult {
    let document = write_document("missing", DOCUMENT)?;
    let Err(error) = args::resolve(&args_for(&document), &Environment::default()) else {
        return Err("resolution with nothing supplied must be refused".into());
    };
    let report = error.to_string();
    for expected in [
        "--liminal-address or $AION_WORKER_LIMINAL_ADDRESSES",
        "--identity or $AION_WORKER_IDENTITY",
    ] {
        assert!(
            report.contains(expected),
            "the report must name `{expected}`, got:\n{report}"
        );
    }
    for deleted in ["--concurrency", "--reconnect-"] {
        assert!(
            !report.contains(deleted),
            "`{deleted}` is declared in the document now, so the connection report must \
             not ask for it: {report}"
        );
    }
    Ok(())
}

/// The environment supplies a setting the flag omits, and the flag WINS when both
/// are present. Nothing is defaulted except `node`, which falls through to the
/// worker SDK's own documented hostname default.
#[test]
fn the_environment_supplies_settings_and_the_flag_wins() -> TestResult {
    let document = write_document("environment", DOCUMENT)?;
    let environment = Environment::from_pairs([
        (
            "AION_WORKER_LIMINAL_ADDRESSES",
            "127.0.0.1:50061, 127.0.0.1:50062",
        ),
        ("AION_WORKER_IDENTITY", "from-environment"),
        ("AION_TASK_QUEUE", "reviewers"),
    ]);

    let resolved = args::resolve(&args_for(&document), &environment)?;
    assert_eq!(
        resolved.addresses,
        vec![
            String::from("127.0.0.1:50061"),
            String::from("127.0.0.1:50062")
        ],
        "a comma-separated list keeps its order and drops blank entries"
    );
    assert_eq!(resolved.identity, "from-environment");
    assert_eq!(resolved.node, None, "node is the SDK's default, not ours");

    let mut arguments = args_for(&document);
    arguments.identity = Some(String::from("from-flag"));
    arguments.liminal_addresses = vec![String::from("127.0.0.1:50099")];
    arguments.task_queue = Some(String::from("from-flag-queue"));
    let resolved = args::resolve(&arguments, &environment)?;
    assert_eq!(resolved.identity, "from-flag");
    assert_eq!(resolved.addresses, vec![String::from("127.0.0.1:50099")]);
    assert_eq!(
        arguments.requested_queue(&environment).as_deref(),
        Some("from-flag-queue")
    );
    Ok(())
}

/// An exported-but-blank variable is a deployment mistake, not a setting: it must be
/// reported missing rather than silently becoming an empty identity or no address.
#[test]
fn a_blank_environment_value_counts_as_missing() -> TestResult {
    let document = write_document("blank", DOCUMENT)?;
    let environment = Environment::from_pairs([
        ("AION_WORKER_LIMINAL_ADDRESSES", "  ,  "),
        ("AION_WORKER_IDENTITY", "   "),
    ]);
    let Err(error) = args::resolve(&args_for(&document), &environment) else {
        return Err("blank values must be refused as missing".into());
    };
    let report = error.to_string();
    assert!(report.contains("--liminal-address"));
    assert!(report.contains("--identity"));
    Ok(())
}

/// The LAUNCH comes from the document and from nowhere else.
///
/// The four settings that moved — concurrency and the reconnect trio — are read off a
/// compiled `harness` section here. The pin is that the values reaching the worker are
/// the DOCUMENT's, so a future edit that reintroduced an environment fallback for any of
/// them would be caught even though the flags are gone.
#[test]
fn the_launch_settings_come_from_the_documents_harness_section() -> TestResult {
    let document = write_document("launch", &harness_document())?;
    let Some(launch) = crate::worker_surface::compile_harness(&document, "reviewers")? else {
        return Err("the document declares a harness section".into());
    };
    assert_eq!(launch.concurrency, 7);
    assert_eq!(launch.reconnect_initial_backoff, Duration::from_secs(5));
    assert_eq!(launch.reconnect_max_backoff, Duration::from_secs(120));
    assert_eq!(launch.reconnect_max_attempts, 42);
    assert_eq!(
        launch.env_pass,
        vec![String::from("PATH"), String::from("HOME")],
        "the pass-through list is the agent child's WHOLE environment"
    );
    Ok(())
}

/// A document with no `harness` section declares no launch, and that is a first-class
/// answer rather than an error: a queue served by a worker SDK build or by declared
/// bodies has no agent to start.
#[test]
fn a_document_without_a_harness_section_declares_no_launch() -> TestResult {
    let document = write_document("nolaunch", DOCUMENT)?;
    let launch = crate::worker_surface::compile_harness(&document, "reviewers")?;
    assert!(
        launch.is_none(),
        "no section means no launch, not an empty one"
    );
    Ok(())
}

/// MIGRATION RIDER: a document that declares a queue but no launch is refused LOUDLY,
/// naming where the settings live now.
///
/// This is the refusal an operator meets after the flags were deleted, so it carries the
/// whole shape rather than one missing field: they have almost certainly arrived with
/// the old flags in their fingers.
#[test]
fn serving_a_document_with_no_harness_section_refuses_naming_the_section() -> TestResult {
    let document = write_document("refusal", DOCUMENT)?;
    let surface = surface::derive(&document, None)?;
    let error = super::serve::no_harness_section(&surface, &document);
    let message = error.to_string();
    for expected in [
        "declares no `harness` section",
        "There is no flag for any of it",
        "aion awl check",
        "reviewers",
    ] {
        assert!(
            message.contains(expected),
            "the refusal must name `{expected}`, got:\n{message}"
        );
    }
    Ok(())
}

/// A document in the exact shape aion#88 is about: one queue, one BODILESS
/// `agent`-marked action, and no `harness` section.
///
/// It is the shape of `crates/aion-awl/tests/fixtures/rev2/harness-section/valid/
/// harness_absent_control.awl` — a fixture the checker holds as PASSING — so the
/// test below measures the real case rather than one that happens to resemble it.
const AGENT_SEAM_WITHOUT_A_HARNESS: &str = r"//! An agent seam with no launch: valid as a document, unservable by this verb.
workflow ask_flow
  input question: String

  outcome answered: type Answer, route success

/// What the flow routes on.
type Answer { reply: String }

/// The canonical agent-outcome record.
type Reply {
  text: String,
  final_message: String,
  stop_reason: String,
  session_id: String,
}

/// The queue an agent worker would serve.
worker reviewers
  action review(brief: String) -> Reply
    agent

step do_review
  review(brief: question) -> reply
  route answered(reply: reply.text)
";

/// aion#88: the refusal must not send the operator to a check that answers `ok`.
///
/// The two assertions are one claim in two halves, and the first is what stops this
/// becoming a string test that outlives the behaviour it describes:
///
/// 1. `aion awl check` REALLY DOES pass this document — asserted by running the
///    checker itself, not by trusting the wording. If a later change makes the
///    checker refuse an agent seam with no harness, this half goes red and the
///    refusal's explanation has to be revisited, which is exactly the moment it
///    should be.
/// 2. Given that, the refusal must lead its remedy with the `kind` line (the one
///    setting nothing can infer, and the one that gives the checker a required set
///    to scope to) and must say outright that the check reports the document valid
///    until the section exists.
///
/// The old wording failed the second half: it printed a paste-ready
/// `aion awl check <path>` whose answer on that same document was `ok`, exit 0.
#[test]
fn the_refusal_does_not_point_at_a_check_that_answers_ok() -> TestResult {
    let document = write_document("agent-seam-no-harness", AGENT_SEAM_WITHOUT_A_HARNESS)?;

    // Half one: the checker's ACTUAL verdict on this document, taken from the checker.
    let parsed = aion_awl::parse(AGENT_SEAM_WITHOUT_A_HARNESS)?;
    let findings = aion_awl::check(&parsed);
    assert!(
        findings.is_empty(),
        "the premise of aion#88 is that `aion awl check` PASSES an agent seam carrying no \
         harness section; it now reports {findings:?} — the refusal's explanation must be \
         revisited before this assertion is relaxed"
    );

    // Half two: the refusal earns the check it recommends.
    let surface = surface::derive(&document, None)?;
    let message = super::serve::no_harness_section(&surface, &document).to_string();
    for expected in [
        "kind acp",
        "kind norn",
        "reports the document valid",
        "is a legitimate document",
    ] {
        assert!(
            message.contains(expected),
            "the remedy must carry `{expected}` so the recommended check is not read as a \
             contradiction, got:\n{message}"
        );
    }
    Ok(())
}

/// `--check` prints the exact surface — every action, both schemas — plus the harness
/// that would drive it, and connects to nothing. It is written to an injected writer
/// here, which is the same call the verb makes against stdout.
///
/// Driven over EVERY harness this build carries, plus the no-harness report, because the
/// report is what an operator reads instead of a remote refusal: the harness name and
/// the capability set beside it are what the server routes operator commands on.
#[test]
fn check_prints_the_surface_without_connecting() -> TestResult {
    let document = write_document("check", DOCUMENT)?;
    let surface = surface::derive(&document, None)?;
    let mut rendered = Vec::new();
    surface::print(&mut rendered, &surface, None)?;

    let report: Value = serde_json::from_slice(&rendered)?;
    assert_eq!(report["task_queue"], json!("reviewers"));
    let Some(actions) = report["actions"].as_array() else {
        return Err("the report must carry an actions array".into());
    };
    assert_eq!(actions.len(), 1);
    assert_eq!(actions[0]["name"], json!("review"));
    assert_eq!(
        actions[0]["input_schema"]["properties"]["brief"]["type"],
        json!("string")
    );
    assert_eq!(
        actions[0]["output_schema"]["$defs"]["Review"]["properties"]["detail"]["type"],
        json!("string")
    );
    // With no harness resolved the report says so rather than naming one: that is the
    // `--no-default-features` build, and it must be visible BEFORE a dial.
    assert_eq!(report["harness"], Value::Null);
    assert_eq!(
        report["intervention_capabilities"]["supported"],
        json!([]),
        "a build with no harness advertises no controls"
    );

    // And once a harness is resolved, the report names it and carries the ADAPTER's own
    // published registration set — not an empty set, which would leave the ops console
    // offering no controls at all for a live agent.
    for harness in crate::harness::catalogue::compiled() {
        let mut rendered = Vec::new();
        surface::print(&mut rendered, &surface, Some(harness))?;
        let report: Value = serde_json::from_slice(&rendered)?;
        assert_eq!(report["harness"], json!(harness.name()));
        assert_eq!(
            report["intervention_capabilities"],
            serde_json::to_value(crate::harness::registration_capabilities(Some(harness)))?
        );
        let Some(supported) = report["intervention_capabilities"]["supported"].as_array() else {
            return Err("the capability set must carry a supported array".into());
        };
        assert!(
            !supported.is_empty(),
            "`{}` must advertise the controls its adapter can honour",
            harness.name()
        );
    }
    Ok(())
}

/// The ACP harness's `--check` report names `cancel` and nothing else — the one
/// intervention primitive ACP v1 can actually deliver. This is the operator-visible end
/// of the adapter's published ceiling.
#[cfg(feature = "acp")]
#[test]
fn the_acp_check_report_advertises_exactly_cancel() -> TestResult {
    let document = write_document("acpcheck", DOCUMENT)?;
    let surface = surface::derive(&document, None)?;
    let mut rendered = Vec::new();
    surface::print(
        &mut rendered,
        &surface,
        Some(crate::harness::HarnessKind::Acp),
    )?;
    let report: Value = serde_json::from_slice(&rendered)?;
    assert_eq!(report["harness"], json!("acp"));
    assert_eq!(
        report["intervention_capabilities"]["supported"],
        json!([{ "primitive": "Cancel" }]),
        "ACP can deliver exactly one primitive, so exactly one is advertised"
    );
    Ok(())
}

/// The composed harness's ADVERTISED set — the union `AgentHarnessConfig` computes
/// from its activity types and its descriptor names — must be exactly the document's
/// serviceable actions. A divergence would register a worker for a type it will not
/// route, or route one it never announced.
#[cfg(all(any(feature = "norn", feature = "acp"), feature = "liminal-transport"))]
#[test]
fn the_composed_config_advertises_exactly_the_documents_surface() -> TestResult {
    let document = write_document("composed", &two_action_document())?;
    let surface = surface::derive(&document, None)?;
    let advertised = surface.names();
    let Some(harness) = crate::harness::catalogue::compiled().first().copied() else {
        return Err("a build with liminal transport and a harness feature must carry one".into());
    };
    let config = harness.test_config();
    let agent = aion_worker::AgentHarnessConfig::new(
        crate::harness::compose::build(&config),
        advertised.iter().cloned(),
        crate::harness::registration_capabilities(Some(harness)),
    )
    .with_activity_descriptors(surface.descriptors.clone());

    assert_eq!(agent.agent_activity_types(), &advertised);
    assert_eq!(
        agent
            .activity_descriptors()
            .iter()
            .map(|descriptor| descriptor.name.clone())
            .collect::<BTreeSet<_>>(),
        advertised,
        "a descriptor must exist for every advertised action"
    );
    assert!(
        !agent.activity_descriptors().is_empty(),
        "an empty descriptor set is refused by every contract-bearing queue"
    );
    Ok(())
}

/// A document declaring two queues, so queue selection is genuinely ambiguous.
fn two_worker_document() -> String {
    DOCUMENT.replace(
        "step do_review",
        "/// A second queue, so the choice is the operator's.\nworker summarisers\n  \
         action summarise(brief: String) -> Review\n\nstep do_review",
    )
}

/// A document whose one queue declares two bodyless actions.
fn two_action_document() -> String {
    DOCUMENT.replace(
        "  action review(brief: String) -> Review",
        "  action review(brief: String) -> Review\n  action summarise(brief: String) -> Review",
    )
}

/// One queue carrying one bodyless action and one the document implements itself. A
/// `run` body's outcome members are fixed by the language to `exit_code`, `stdout`,
/// and `stderr`, so the bodied action returns that shape.
const MIXED_BODY_DOCUMENT: &str = r#"//! mixed: one action for a worker, one the server runs from the contract.
workflow mixed_flow
  input brief: String

  outcome reviewed: type Review, route success

/// What the agent reported back.
type Review {
  verdict: String,
  detail: String,
}

/// What a declared command reported.
type RunOutcome { exit_code: Int, stdout: String, stderr: String }

/// One action a worker serves, one the server runs.
worker reviewers
  action review(brief: String) -> Review
  action stamp(brief: String) -> RunOutcome
    run "printf %s {{brief}}"

step do_review
  brief |> review |> route reviewed
"#;

/// A queue whose every action carries a declared body, leaving a worker nothing.
const ALL_BODIED_DOCUMENT: &str = r#"//! bodied: every action on the queue is the server's to run.
workflow bodied_flow
  input brief: String

  outcome stamped: type RunOutcome, route success

/// What a declared command reported.
type RunOutcome { exit_code: Int, stdout: String, stderr: String }

/// The server runs every action here; no worker serves any of them.
worker reviewers
  action stamp(brief: String) -> RunOutcome
    run "printf %s {{brief}}"

step do_stamp
  brief |> stamp |> route stamped
"#;

/// The queue document with a complete `norn` launch declared on it.
fn harness_document() -> String {
    DOCUMENT.replace(
        "worker reviewers\n",
        "worker reviewers\n  harness\n    kind norn\n    concurrency 7\n    \
         reconnect_initial_backoff 5s\n    reconnect_max_backoff 2m\n    \
         reconnect_max_attempts 42\n    env_pass \"PATH\", \"HOME\"\n    cwd \
         \"/srv/agents\"\n",
    )
}