aion-server 0.31.0

Aion workflow server library: HTTP, gRPC, WebSocket, and worker endpoints. Run it with the `aion` binary from the aion-cli crate.
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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
use std::io;
use std::path::{Component, Path};

use aion_awl::{Span, TypeBody, parse, print, semantic, utf16_range_for_span};
use serde::{Deserialize, Serialize};

use crate::filesystem::ConfinedDir;

#[derive(Debug, Deserialize)]
pub struct CheckRequest {
    pub source: String,
    pub path: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct CheckResponse {
    pub ok: bool,
    pub deploys_green: bool,
    pub steps: Option<usize>,
    pub diagnostics: Vec<Diagnostic>,
    pub semantic: Option<SemanticIndex>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Diagnostic {
    pub class: DiagnosticClass,
    pub message: String,
    pub line: usize,
    pub column: usize,
    /// The diagnostic's full extent as a UTF-16 range (ruled: the wire carries
    /// the editors' index space, converted server-side — never byte offsets).
    pub range: DiagnosticRange,
}

/// A half-open UTF-16 range on the wire: `start` inclusive, `end` exclusive,
/// both zero-based, `character` in UTF-16 code units — the index space
/// `CodeMirror` and the LSP protocol share, so no client re-derives it.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DiagnosticRange {
    pub start: DiagnosticPosition,
    pub end: DiagnosticPosition,
}

/// One zero-based UTF-16 position inside a [`DiagnosticRange`].
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DiagnosticPosition {
    pub line: u32,
    pub character: u32,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticClass {
    Error,
}

#[derive(Debug, Deserialize)]
pub struct FormatRequest {
    pub source: String,
}

#[derive(Debug, Serialize)]
pub struct FormatResponse {
    pub formatted: String,
}

#[derive(Debug, Serialize)]
pub struct SemanticIndex {
    pub entries: Vec<SemanticEntry>,
    pub graph: super::projection::GraphProjection,
    pub studio: super::studio_projection::StudioProjection,
}

#[derive(Debug, Serialize)]
pub struct SemanticEntry {
    pub span: SourceSpan,
    #[serde(rename = "type")]
    pub type_text: Option<String>,
    pub declaration: Option<SemanticDeclaration>,
}

#[derive(Debug, Serialize)]
pub struct SemanticDeclaration {
    pub name: String,
    pub kind: String,
    pub documentation: Option<String>,
    pub span: SourceSpan,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct SourceSpan {
    pub start: usize,
    pub end: usize,
    pub line: usize,
    pub column: usize,
}

pub fn check_source(request: &CheckRequest) -> CheckResponse {
    check_source_at(request, None)
}

/// Checks `source` with schema imports resolved against `root`, carrying no
/// workspace document path.
///
/// The deployed-AWL read surface uses this: its schemas come out of the
/// deployed archive and are staged into a directory of their own, so there is
/// a root but deliberately no workspace path — a deployed document is not a
/// workspace document and must never be resolved as one.
pub(crate) fn check_source_at_root(source: &str, root: Option<&Path>) -> CheckResponse {
    check_source_at(
        &CheckRequest {
            source: source.to_owned(),
            path: None,
        },
        root,
    )
}

fn check_source_at(request: &CheckRequest, root: Option<&Path>) -> CheckResponse {
    let document = match parse(&request.source) {
        Ok(document) => document,
        Err(error) => {
            return CheckResponse {
                ok: false,
                deploys_green: false,
                steps: None,
                diagnostics: vec![diagnostic(
                    &request.source,
                    DiagnosticClass::Error,
                    error.message,
                    error.span,
                )],
                semantic: None,
            };
        }
    };
    let analysis = root.map_or_else(
        || semantic::analyze(&document),
        |root| semantic::analyze_in(&document, root),
    );
    let diagnostics: Vec<_> = analysis
        .diagnostics()
        .iter()
        .map(|error| {
            diagnostic(
                &request.source,
                DiagnosticClass::Error,
                error.message.clone(),
                error.span,
            )
        })
        .collect();
    if !diagnostics.is_empty() {
        return CheckResponse {
            ok: false,
            deploys_green: false,
            steps: None,
            diagnostics,
            semantic: None,
        };
    }
    let graph = super::projection::build(&document, analysis.step_kinds());
    let studio = super::studio_projection::build(&document);
    let semantic = SemanticIndex {
        entries: analysis
            .iter()
            .map(|info| SemanticEntry {
                span: info.span.into(),
                type_text: info.ty.clone(),
                declaration: info
                    .declaration
                    .as_ref()
                    .map(|declaration| SemanticDeclaration {
                        name: declaration.name.clone(),
                        kind: declaration.kind.as_str().to_owned(),
                        documentation: declaration.documentation.clone(),
                        span: declaration.span.into(),
                    }),
            })
            .collect(),
        graph,
        studio,
    };
    CheckResponse {
        ok: true,
        deploys_green: diagnostics.is_empty(),
        steps: Some(document.steps.len()),
        diagnostics,
        semantic: Some(semantic),
    }
}

pub async fn check_source_in_workspace(
    workspace_root: &Path,
    request: &CheckRequest,
) -> Result<CheckResponse, super::documents::DocumentError> {
    let Some(requested_path) = request.path.as_deref() else {
        return Ok(check_source(request));
    };
    let workspace_root = workspace_root.to_owned();
    let source = request.source.clone();
    let requested_path = requested_path.to_owned();
    tokio::task::spawn_blocking(move || {
        let Ok(_) = parse(&source) else {
            return Ok(check_source(&CheckRequest {
                source,
                path: Some(requested_path),
            }));
        };
        let (_staging, staged_root) =
            stage_schema_imports(&workspace_root, &requested_path, &source)?;
        Ok(check_source_at(
            &CheckRequest {
                source,
                path: Some(requested_path),
            },
            Some(&staged_root),
        ))
    })
    .await
    .map_err(|error| {
        super::documents::DocumentError::Io(io::Error::other(format!(
            "AWL check task failed: {error}"
        )))
    })?
}

/// Derive the documentation model of a WORKSPACE document.
///
/// The same model `aion awl doc` prints and `GET /awl/deployed/{type}/{hash}/doc`
/// serves — one model, three callers. It is a separate entry point from
/// `/awl/check` because it answers a different question: check reports
/// diagnostics, this reports the document's own documentation, and folding
/// the second into the first would make every keystroke pay for a page
/// nobody had opened.
///
/// Schema imports resolve against the OPERATOR'S WORKSPACE here, which is
/// correct for a workspace document and is exactly what makes this a
/// different call from the deployed one: a deployed revision resolves
/// against the schemas its own archive carries.
///
/// # Errors
///
/// Returns the staging failures of [`stage_schema_imports`]; a document that
/// does not parse, or whose committed schema set cannot be derived, is a
/// [`DocResponse::Refused`] rather than a transport error.
pub async fn doc_source_in_workspace(
    workspace_root: &Path,
    request: &CheckRequest,
) -> Result<DocResponse, super::documents::DocumentError> {
    let workspace_root = workspace_root.to_owned();
    let source = request.source.clone();
    let requested_path = request.path.clone();
    tokio::task::spawn_blocking(move || {
        let Some(requested_path) = requested_path else {
            // With no path there is no directory to resolve imports against,
            // and a document that imports one gets that failure by name
            // rather than a schema silently resolving to nothing.
            return Ok(derived(aion_awl::doc::derive(
                &source,
                &std::collections::BTreeMap::new(),
            )));
        };
        // A buffer that does not parse is the ORDINARY case on this surface
        // (an author halfway through an edit), and the derivation's own
        // refusal names the fault; staging its imports first would answer
        // with a document error instead of that reason.
        if parse(&source).is_err() {
            return Ok(derived(aion_awl::doc::derive(
                &source,
                &std::collections::BTreeMap::new(),
            )));
        }
        let (_staging, staged_root) =
            stage_schema_imports(&workspace_root, &requested_path, &source)?;
        Ok(derived(aion_awl::doc::derive_in(&source, &staged_root)))
    })
    .await
    .map_err(|error| {
        super::documents::DocumentError::Io(io::Error::other(format!(
            "AWL doc task failed: {error}"
        )))
    })?
}

/// The documentation model, or the reason there is none.
///
/// A document that does not parse is a NORMAL state on this surface — an
/// author asking for the definition of a buffer they are halfway through
/// editing — so it is an answer with a reason, not a transport failure.
#[derive(Debug, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum DocResponse {
    /// The model was derived.
    Derived {
        /// The documentation model. Boxed: a whole document's model dwarfs
        /// the refusal string, and the enum is as large as its largest arm.
        doc: Box<aion_awl::doc::DocumentDoc>,
    },
    /// The model could not be derived, and this is why.
    Refused {
        /// The derivation failure, verbatim.
        reason: String,
    },
}

fn derived(result: Result<aion_awl::doc::DocumentDoc, aion_awl::doc::DocError>) -> DocResponse {
    match result {
        Ok(doc) => DocResponse::Derived { doc: Box::new(doc) },
        Err(error) => DocResponse::Refused {
            reason: error.to_string(),
        },
    }
}

pub(crate) fn stage_schema_imports(
    workspace_root: &Path,
    requested_path: &str,
    source: &str,
) -> Result<(tempfile::TempDir, std::path::PathBuf), super::documents::DocumentError> {
    let document_path = super::documents::document_path(requested_path)?;
    let document = parse(source)
        .map_err(|error| super::documents::DocumentError::Unparseable(error.message))?;
    // A workspace directory that does not exist yet is a NORMAL state on a
    // fresh server — the default workspace is materialized on first write.
    // No directory means no schema files can exist to import, so the check
    // proceeds against an empty staged root instead of failing with a raw
    // errno (mirrors `documents::list` on the same absence).
    let workspace = match ConfinedDir::open(workspace_root) {
        Ok(workspace) => Some(workspace),
        Err(error) if error.kind() == io::ErrorKind::NotFound => None,
        Err(error) => return Err(super::documents::DocumentError::Io(error)),
    };
    let staging = tempfile::Builder::new().prefix("aion-schema-").tempdir()?;
    let document_parent = document_path.parent().unwrap_or_else(|| Path::new(""));
    let analysis_root = staging.path().join(document_parent);
    std::fs::create_dir_all(&analysis_root)?;
    let Some(workspace) = workspace else {
        return Ok((staging, analysis_root));
    };
    for declaration in &document.types {
        let TypeBody::SchemaImport { path, .. } = &declaration.body else {
            continue;
        };
        let import = Path::new(path);
        if path.is_empty()
            || import
                .components()
                .any(|component| !matches!(component, Component::Normal(_)))
        {
            continue;
        }
        let bytes = match workspace.read(&document_parent.join(import)) {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
            Err(error)
                if matches!(
                    error.kind(),
                    io::ErrorKind::InvalidInput | io::ErrorKind::NotADirectory
                ) || error.raw_os_error() == Some(rustix::io::Errno::LOOP.raw_os_error()) =>
            {
                return Err(super::documents::DocumentError::InvalidPath(format!(
                    "schema import `{path}` contains a link: {error}"
                )));
            }
            Err(error) => return Err(super::documents::DocumentError::Io(error)),
        };
        let staged = analysis_root.join(import);
        if let Some(parent) = staged.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(staged, bytes)?;
    }
    Ok((staging, analysis_root))
}

pub fn format_source(request: &FormatRequest) -> Result<FormatResponse, Diagnostic> {
    parse(&request.source)
        .map(|document| FormatResponse {
            formatted: print(&document),
        })
        .map_err(|error| {
            diagnostic(
                &request.source,
                DiagnosticClass::Error,
                error.message,
                error.span,
            )
        })
}

fn diagnostic(source: &str, class: DiagnosticClass, message: String, span: Span) -> Diagnostic {
    let range = utf16_range_for_span(source, span);
    Diagnostic {
        class,
        message,
        line: span.line,
        column: span.column,
        range: DiagnosticRange {
            start: DiagnosticPosition {
                line: range.start.line,
                character: range.start.character,
            },
            end: DiagnosticPosition {
                line: range.end.line,
                character: range.end.character,
            },
        },
    }
}

impl From<Span> for SourceSpan {
    fn from(span: Span) -> Self {
        Self {
            start: span.start,
            end: span.end,
            line: span.line,
            column: span.column,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const HAPPY: &str =
        include_str!("../../../aion-awl/tests/fixtures/rev2/dag-fork/valid/after_single.awl");
    const INVALID: &str = include_str!(
        "../../../aion-awl/tests/fixtures/rev2/dag-fork/invalid/unknown_after_target.awl"
    );
    const EMIT_REFUSED: &str = "//! Emitter refusal probe.\nworkflow emit_refused\n  outcome done: type Result, route success\n\ntype Result { value: String }\n\nworker work\n  action make() -> Result\n\nstep finish\n  make() -> result\n  route done(value: result.value)\n  on failure\n    route done(value: \"failed\")\n";

    #[test]
    fn check_happy_path_returns_steps_and_semantics() {
        let response = check_source(&CheckRequest {
            source: HAPPY.to_owned(),
            path: None,
        });
        assert!(response.ok);
        assert!(response.deploys_green);
        assert_eq!(response.steps, Some(2));
        assert!(response.diagnostics.is_empty());
        assert!(
            response
                .semantic
                .is_some_and(|semantic| !semantic.entries.is_empty())
        );
    }

    #[test]
    fn checker_message_surfaces_verbatim() -> Result<(), Box<dyn std::error::Error>> {
        let document = parse(INVALID)?;
        let expected = aion_awl::check(&document)
            .first()
            .ok_or("fixture unexpectedly checks cleanly")?
            .message
            .clone();
        let response = check_source(&CheckRequest {
            source: INVALID.to_owned(),
            path: None,
        });
        assert!(!response.ok);
        assert_eq!(response.diagnostics[0].message, expected);
        assert!(matches!(
            response.diagnostics[0].class,
            DiagnosticClass::Error
        ));
        Ok(())
    }

    /// The wire diagnostic carries the checker span's FULL extent as a UTF-16
    /// range — the fidelity this surface lost when `diagnostic()` dropped
    /// `span.start`/`span.end` and clients underlined one code point.
    #[test]
    fn checker_diagnostics_carry_their_span_as_a_utf16_range()
    -> Result<(), Box<dyn std::error::Error>> {
        let document = parse(INVALID)?;
        let span = aion_awl::check(&document)
            .first()
            .ok_or("fixture unexpectedly checks cleanly")?
            .span;
        let expected = utf16_range_for_span(INVALID, span);
        assert!(
            span.end > span.start,
            "the fixture's checker span must have extent for this pin to bite"
        );
        let response = check_source(&CheckRequest {
            source: INVALID.to_owned(),
            path: None,
        });
        let wire = serde_json::to_value(&response.diagnostics)?;
        assert_eq!(
            wire[0]["range"]["start"]["line"],
            u64::from(expected.start.line)
        );
        assert_eq!(
            wire[0]["range"]["start"]["character"],
            u64::from(expected.start.character)
        );
        assert_eq!(
            wire[0]["range"]["end"]["line"],
            u64::from(expected.end.line)
        );
        assert_eq!(
            wire[0]["range"]["end"]["character"],
            u64::from(expected.end.character)
        );
        assert!(
            wire[0].get("span").is_none() && wire[0].get("start").is_none(),
            "ruled: the wire gains a UTF-16 range ONLY — no byte-span field"
        );
        Ok(())
    }

    /// A diagnostic AFTER a multibyte character on its own line is positioned
    /// in UTF-16 code units, not bytes — the drift class the editor seam
    /// documents (2026-07-12). The prefix guard makes the pin non-vacuous: if
    /// the flagged token ever moves before the emoji, byte and UTF-16 columns
    /// coincide and this test refuses to certify anything.
    #[test]
    fn a_diagnostic_after_a_multibyte_character_ranges_in_utf16_units()
    -> Result<(), Box<dyn std::error::Error>> {
        let source = "//! Range probe.\nworkflow probe\n  outcome done: type Result, route success\n\ntype Result { value: String }\n\nworker work\n  action make(name: String, tag: String) -> Result\n\nstep finish\n  make(name: \"🧭 café\", tag: missing_binding) -> result\n  route done(value: result.value)\n";
        let span = match parse(source) {
            Err(error) => error.span,
            Ok(document) => {
                aion_awl::check(&document)
                    .first()
                    .ok_or("the multibyte probe must produce a diagnostic")?
                    .span
            }
        };
        let line_start = source[..span.start].rfind('\n').map_or(0, |at| at + 1);
        let prefix = &source[line_start..span.start];
        assert_ne!(
            prefix.encode_utf16().count(),
            prefix.len(),
            "the flagged token must sit AFTER the multibyte text on its line, \
             or byte and UTF-16 columns coincide and the pin is vacuous"
        );
        let expected_line =
            u64::try_from(source[..span.start].matches('\n').count()).unwrap_or(u64::MAX);
        let expected_character = u64::try_from(prefix.encode_utf16().count()).unwrap_or(u64::MAX);
        // The END position, by the same independent arithmetic: the extent
        // after multibyte text must land in UTF-16 units too, or a client
        // underlines the right start with the wrong width.
        assert!(span.end > span.start, "the probe span must have extent");
        let end_line_start = source[..span.end].rfind('\n').map_or(0, |at| at + 1);
        let end_prefix = &source[end_line_start..span.end];
        let expected_end_line =
            u64::try_from(source[..span.end].matches('\n').count()).unwrap_or(u64::MAX);
        let expected_end_character =
            u64::try_from(end_prefix.encode_utf16().count()).unwrap_or(u64::MAX);
        let response = check_source(&CheckRequest {
            source: source.to_owned(),
            path: None,
        });
        assert!(!response.ok);
        let wire = serde_json::to_value(&response.diagnostics)?;
        assert_eq!(wire[0]["range"]["start"]["line"], expected_line);
        assert_eq!(wire[0]["range"]["start"]["character"], expected_character);
        assert_eq!(wire[0]["range"]["end"]["line"], expected_end_line);
        assert_eq!(wire[0]["range"]["end"]["character"], expected_end_character);
        Ok(())
    }

    #[test]
    fn checker_only_check_does_not_consult_the_legacy_emitter() {
        let response = check_source(&CheckRequest {
            source: EMIT_REFUSED.to_owned(),
            path: None,
        });
        assert!(response.ok, "diagnostics: {:?}", response.diagnostics);
        assert!(response.deploys_green);
        assert!(response.diagnostics.is_empty());
    }

    /// A fresh server's default workspace directory does not exist until the
    /// first write materializes it. A check that names a `path` must still
    /// succeed against that absence — no directory means no schema files to
    /// import, not a raw errno.
    #[tokio::test]
    async fn a_pathed_check_succeeds_when_the_workspace_does_not_exist_yet()
    -> Result<(), Box<dyn std::error::Error>> {
        let parent = crate::test_support::private_tempdir()?;
        let workspace = parent.path().join("never-created");
        assert!(!workspace.exists());
        let response = check_source_in_workspace(
            &workspace,
            &CheckRequest {
                source: HAPPY.to_owned(),
                path: Some("drafts/after_single.awl".to_owned()),
            },
        )
        .await?;
        assert!(response.ok, "diagnostics: {:?}", response.diagnostics);
        assert!(response.deploys_green);
        assert!(
            !workspace.exists(),
            "a check must not materialize the workspace"
        );
        Ok(())
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn http_check_confines_document_paths_and_schema_imports()
    -> Result<(), Box<dyn std::error::Error>> {
        use std::os::unix::fs::symlink;

        let workspace = crate::test_support::private_tempdir()?;
        let fixture_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../aion-awl/tests/fixtures/rev2/schema-doors/valid");
        let source = std::fs::read_to_string(fixture_dir.join("mixed_doors.awl"))?;
        let schema = std::fs::read(fixture_dir.join("intake.schema.json"))?;
        std::fs::create_dir(workspace.path().join("nested"))?;
        std::fs::write(workspace.path().join("nested/intake.schema.json"), &schema)?;
        std::fs::write(workspace.path().join("intake.schema.json"), &schema)?;

        let valid = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.clone(),
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await?;
        assert!(valid.ok, "confined import failed: {:?}", valid.diagnostics);

        let missing_name = "missing-intake.schema.json";
        std::fs::write(workspace.path().join(missing_name), &schema)?;
        let missing = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.replace("intake.schema.json", missing_name),
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await?;
        let missing_reason = missing
            .diagnostics
            .iter()
            .map(|diagnostic| diagnostic.message.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(!missing.ok);
        assert!(missing_reason.contains(missing_name));
        assert!(!missing_reason.contains("AWL workspace I/O failed"));

        let outside = workspace.path().parent().ok_or("workspace had no parent")?;
        let absolute_source = source.replace(
            "intake.schema.json",
            &outside.join("outside.schema.json").to_string_lossy(),
        );
        let absolute = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: absolute_source,
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await?;
        assert!(!absolute.ok);
        assert!(absolute.diagnostics[0].message.contains("relative path"));

        let traversal = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.replace("intake.schema.json", "../outside.schema.json"),
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await?;
        assert!(!traversal.ok);
        assert!(traversal.diagnostics[0].message.contains("no `..`"));

        let absolute_document = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.clone(),
                path: Some("/tmp/mixed_doors.awl".to_owned()),
            },
        )
        .await;
        assert!(matches!(
            absolute_document,
            Err(super::super::documents::DocumentError::InvalidPath(_))
        ));

        let external_schema = outside.join("external.schema.json");
        std::fs::write(&external_schema, b"{\"type\":\"object\"}")?;
        symlink(
            &external_schema,
            workspace.path().join("nested/linked.schema.json"),
        )?;
        let linked = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.replace("intake.schema.json", "linked.schema.json"),
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await;
        let Err(error) = linked else {
            return Err("schema symlink was followed".into());
        };
        assert!(matches!(
            error,
            super::super::documents::DocumentError::InvalidPath(reason)
                if reason.contains("contains a link")
        ));
        Ok(())
    }

    /// A source that does not parse is refused as ITS OWN class: not a bad
    /// path (the path is fine), and on the doc surface as the derivation's own
    /// stated reason rather than a document error at all.
    #[tokio::test]
    async fn a_document_that_does_not_parse_is_refused_as_unparseable_not_as_a_bad_path()
    -> Result<(), Box<dyn std::error::Error>> {
        let workspace = tempfile::tempdir()?;
        let staged = stage_schema_imports(workspace.path(), "broken.awl", "workflow");
        assert!(
            matches!(
                staged,
                Err(super::super::documents::DocumentError::Unparseable(_))
            ),
            "{staged:?}"
        );

        let doc = doc_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: "workflow".to_owned(),
                path: Some("broken.awl".to_owned()),
            },
        )
        .await?;
        assert!(matches!(doc, DocResponse::Refused { .. }), "{doc:?}");
        Ok(())
    }

    #[test]
    fn format_is_canonical_and_idempotent() -> Result<(), Diagnostic> {
        let once = format_source(&FormatRequest {
            source: HAPPY.replace("type Summary  {", "type Summary {"),
        })?;
        let twice = format_source(&FormatRequest {
            source: once.formatted.clone(),
        })?;
        assert_eq!(once.formatted, twice.formatted);
        assert_eq!(once.formatted, HAPPY);
        Ok(())
    }

    #[test]
    fn every_valid_fixture_projects_without_mutating_source()
    -> Result<(), Box<dyn std::error::Error>> {
        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("../aion-awl/tests/fixtures");
        let mut paths = Vec::new();
        collect_valid_fixtures(&fixtures, &mut paths)?;
        assert!(!paths.is_empty());
        for path in paths {
            let source = std::fs::read_to_string(&path)?;
            let original = source.clone();
            let document = parse(&source)
                .map_err(|error| format!("{} did not parse: {}", path.display(), error.message))?;
            let canonical = print(&document);
            assert_eq!(print(&parse(&canonical)?), canonical, "{}", path.display());
            let response = check_source_at(
                &CheckRequest {
                    source: source.clone(),
                    path: Some(path.to_string_lossy().into_owned()),
                },
                path.parent(),
            );
            assert_eq!(source, original, "projection mutated {}", path.display());
            assert!(
                response.ok,
                "{}: {:?}",
                path.display(),
                response.diagnostics
            );
            let graph = response
                .semantic
                .ok_or("valid fixture had no semantics")?
                .graph;
            assert_eq!(
                graph.steps.len(),
                document.steps.len(),
                "{}",
                path.display()
            );
        }
        Ok(())
    }

    fn collect_valid_fixtures(
        directory: &Path,
        found: &mut Vec<std::path::PathBuf>,
    ) -> std::io::Result<()> {
        for entry in std::fs::read_dir(directory)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                collect_valid_fixtures(&path, found)?;
            } else if path.extension().is_some_and(|extension| extension == "awl")
                && path
                    .components()
                    .any(|component| component.as_os_str() == "valid")
            {
                found.push(path);
            }
        }
        Ok(())
    }
}