diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d1d9c3..2d60c03 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,6 +52,11 @@ jobs: - name: Build workspace run: cargo build --locked --workspace + - name: Gate claimed MedUI conformance against the pinned corpus + env: + MEDUI_CONFORMANCE_DIR: ${{ github.workspace }}/.medui-conformance + run: cargo test --locked -p trustsc-ui-dsl-authoring --test shared_conformance -- --nocapture + - name: Run test suite env: MEDUI_CONFORMANCE_DIR: ${{ github.workspace }}/.medui-conformance diff --git a/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs index 53f63fc..f2d4bc7 100644 --- a/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs +++ b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs @@ -56,13 +56,25 @@ impl Diagnostic { /// so a raise site reads as the condition it detects. /// /// A code's meaning never changes and a retired number is never reused (`MEDUI-DEC-005`), so -/// these constants are append-only. Codes the contract registers but this implementation never -/// raises — `MEDUI-E004` (source is not UTF-8), `MEDUI-E017` (hardcoded product string), -/// `MEDUI-E053` (dynamic text escapes its charset) — are deliberately absent rather than -/// declared and unused. +/// these constants are append-only. This is an implementation subset of the `0.3.0-rc.1` registry, +/// not a declaration that every registered diagnostic is implemented. Missing here are: +/// +/// - E000/E001/E002: recipe diagnostics (this crate has no recipe reader). +/// - E017: hardcoded product string; the legacy parser instead reports E010. +/// - E033/E034/E035: semantic kind, closed-set member and resource identity; older local +/// diagnostic mappings remain instead of these dedicated identities. +/// - E053: dynamic text escaping its charset. +/// - E054: positioned node without fixed dimensions; the legacy parser reports E051. +/// - E070: a safety-critical annotation without a requirement. In particular, an annotated +/// Button or TextInput with no requirement is currently accepted; this is a behavioral gap, +/// not simply an unnamed error. Semantics, layout and safety remain unclaimed by the harness. +/// +/// See `docs/dsl/conformance.md` for the coverage limits at the pinned contract. pub mod code { /// `MEDUI-E003` — the `.medui` source could not be read. pub const SOURCE_UNREADABLE: &str = "MEDUI-E003"; + /// `MEDUI-E004` — the source bytes are not valid UTF-8. + pub const SOURCE_NOT_UTF8: &str = "MEDUI-E004"; /// `MEDUI-E010` — the source does not parse. pub const UNEXPECTED_TOKEN: &str = "MEDUI-E010"; /// `MEDUI-E011` — the component name is not in the closed dictionary. @@ -92,14 +104,11 @@ pub mod code { /// `MEDUI-E071` — a CV check is not one the contract defines for this node. pub const UNKNOWN_CV_CHECK: &str = "MEDUI-E071"; - /// A condition the pinned registry has no code for, reported as `MEDUI-E010` until one - /// exists. + /// Legacy fallback for conditions without a dedicated raise-site identity in this crate. /// - /// `spec/component-model.md` makes unknown image IDs, templates, charsets, clock formats, - /// system events, and layout kinds fatal, but registers a code only for colour tokens - /// (`MEDUI-E030`) and CV checks (`MEDUI-E071`). Marking these sites explicitly keeps them - /// greppable as registry gaps to raise upstream, instead of letting them fall through a - /// catch-all unnoticed. + /// Some now have registered identities in the pinned contract (notably E034 for clock/event + /// members and E035 for image/template IDs); others still lack one. This name records a + /// local implementation gap, not a claim that the shared registry has no matching code. pub const UNREGISTERED: &str = UNEXPECTED_TOKEN; } diff --git a/crates/trustsc-ui-dsl-authoring/src/lib.rs b/crates/trustsc-ui-dsl-authoring/src/lib.rs index 47fca0c..6a7ff79 100644 --- a/crates/trustsc-ui-dsl-authoring/src/lib.rs +++ b/crates/trustsc-ui-dsl-authoring/src/lib.rs @@ -1,6 +1,7 @@ #![forbid(unsafe_code)] use std::{ + collections::BTreeSet, fmt::Write as _, fs, path::Path, @@ -143,14 +144,15 @@ pub fn compile_medui_file_to_rust_module( ) -> TrustScResult<()> { let input_path = input_path.as_ref(); let output_path = output_path.as_ref(); - let source = fs::read_to_string(input_path).map_err(|error| { + let bytes = fs::read(input_path).map_err(|error| { coded(code::SOURCE_UNREADABLE, format!( "failed to read MedUI source {}: {error}", input_path.display() )) })?; + let source = decode_medui_source(&bytes)?; let generated = - compile_medui_source_to_rust(&source, options, text_packages, image_packages)?; + compile_medui_source_to_rust(source, options, text_packages, image_packages)?; if let Some(parent) = output_path.parent() { fs::create_dir_all(parent).map_err(|error| { @@ -201,6 +203,29 @@ pub fn compile_medui_source_to_rust( Ok(emit_rust_module(&compiled, options.crate_path)) } +/// Parses source bytes, reporting invalid UTF-8 as `MEDUI-E004` before parsing. +/// Diagnostic positions retain the parser's line-only precision, including decoding failures. +/// File-based callers should use this entry point so encoding failures are distinct from I/O. +pub fn parse_medui_bytes(source: &[u8]) -> Result> { + let source = decode_medui_source(source) + .map_err(|error| vec![Diagnostic::from_validation_error(&error)])?; + parse_medui_source(source) +} + +fn decode_medui_source(source: &[u8]) -> TrustScResult<&str> { + std::str::from_utf8(source).map_err(|error| { + let line = 1 + source[..error.valid_up_to()] + .iter() + .filter(|&&byte| byte == b'\n') + .count(); + coded_at( + line, + code::SOURCE_NOT_UTF8, + "MedUI source is not valid UTF-8", + ) + }) +} + /// Parses `.medui` source into its AST without compiling it — the entry point a GUI (MedUI /// Studio, ADR-022) uses to load a screen for editing. The parser is fail-fast (one error stops /// parsing), so the returned `Vec` currently always has length 1; it is `Vec` rather than a @@ -260,6 +285,7 @@ fn parse_screen(source: &str) -> TrustScResult { let (layout_line, layout_header) = &lines[1]; let layout = parse_layout(*layout_line, layout_header)?; let mut items = Vec::new(); + let mut node_ids = Vec::new(); let mut pending_safety: Option = None; let mut cursor = 2usize; @@ -299,7 +325,7 @@ fn parse_screen(source: &str) -> TrustScResult { "@safety_critical cannot annotate a Row container at line {line_number}" ))); } - let (row, next_cursor) = parse_row(&lines, cursor)?; + let (row, next_cursor) = parse_row(&lines, cursor, &mut node_ids)?; items.push(ScreenItem::Row(row)); cursor = next_cursor; continue; @@ -324,6 +350,7 @@ fn parse_screen(source: &str) -> TrustScResult { component_kind, pending_safety.take(), &properties, + &mut node_ids, )?; items.push(ScreenItem::Component(node)); } @@ -336,6 +363,7 @@ fn parse_screen(source: &str) -> TrustScResult { )); } + validate_authored_node_ids(&mut node_ids)?; Ok(ScreenDefinition { id: screen_id, layout, @@ -351,6 +379,7 @@ fn parse_screen(source: &str) -> TrustScResult { fn parse_row( lines: &[(usize, String)], start: usize, + node_ids: &mut Vec<(usize, String)>, ) -> TrustScResult<(RowDefinition, usize)> { let (row_line_number, _) = &lines[start]; let row_line_number = *row_line_number; @@ -406,6 +435,7 @@ fn parse_row( component_kind, pending_safety.take(), &properties, + node_ids, )?; children.push(node); continue; @@ -419,7 +449,9 @@ fn parse_row( )) })?; match key.trim() { - "id" => id = Some(parse_identifier(*line_number, "Row id", value.trim())?), + "id" => { + id = Some((*line_number, parse_identifier(*line_number, "Row id", value.trim())?)); + } "height" => height = Some(parse_dimension(*line_number, "height", value.trim())?), "spacing" => { spacing = Some(parse_px_allowing_zero(*line_number, "spacing", value.trim())?) @@ -442,7 +474,7 @@ fn parse_row( ))); } - let id = id.ok_or_else(|| { + let (id_line, id) = id.ok_or_else(|| { coded_at(row_line_number, code::MISSING_FIELD, format!("Row at line {row_line_number} must declare `id`")) })?; let height = height.ok_or_else(|| { @@ -454,6 +486,7 @@ fn parse_row( ))); } + node_ids.push((id_line, id.clone())); Ok(( RowDefinition { id, @@ -615,6 +648,7 @@ fn parse_component_properties( component_kind: ComponentKind, safety_critical: Option, properties: &[(usize, String)], + node_ids: &mut Vec<(usize, String)>, ) -> TrustScResult { let mut id = None; let mut width = None; @@ -644,7 +678,12 @@ fn parse_component_properties( let key = key.trim(); let value = value.trim(); match key { - "id" => id = Some(parse_identifier(*property_line_number, "component id", value)?), + "id" => { + id = Some(( + *property_line_number, + parse_identifier(*property_line_number, "component id", value)?, + )); + } "width" => width = Some(parse_dimension(*property_line_number, "width", value)?), "height" => height = Some(parse_dimension(*property_line_number, "height", value)?), "requirement" => { @@ -685,7 +724,7 @@ fn parse_component_properties( } } - let id = id.ok_or_else(|| { + let (id_line, id) = id.ok_or_else(|| { coded_at(line_number, code::MISSING_FIELD, format!("component at line {line_number} must declare `id`")) })?; let width = width.ok_or_else(|| { @@ -855,6 +894,7 @@ fn parse_component_properties( } }; + node_ids.push((id_line, id.clone())); Ok(NodeDefinition { id, width, @@ -865,6 +905,25 @@ fn parse_component_properties( }) } +/// Check only the final ID of each authored node, in declaration order. Repeated `id:` +/// properties retain the parser's last-value-wins behavior; overwritten values reserve nothing. +/// Rows finish parsing after their children, so sort by the effective declaration's source line. +/// The compiled-node check still covers synthetic panels and caller-edited ASTs. +fn validate_authored_node_ids(node_ids: &mut [(usize, String)]) -> TrustScResult<()> { + node_ids.sort_by_key(|(line, _)| *line); + let mut seen = BTreeSet::new(); + for (line, id) in node_ids.iter() { + if !seen.insert(id.as_str()) { + return Err(coded_at( + *line, + code::DUPLICATE_NODE_ID, + format!("duplicate node id {id}"), + )); + } + } + Ok(()) +} + fn parse_identifier(line_number: usize, field_name: &str, raw: &str) -> TrustScResult { let value = raw.trim(); if value.is_empty() { @@ -3442,6 +3501,121 @@ Screen InteractivePanel { "/../../examples/class_c_monitor/neurosense.medui" )); + #[test] + fn source_bytes_distinguish_encoding_failures_and_preserve_line_precision() { + assert_eq!( + parse_medui_bytes(HELLO_WORLD_MEDUI.as_bytes()), + parse_medui_source(HELLO_WORLD_MEDUI) + ); + for source in [ + b"\xff".as_slice(), + b"// valid UTF-8: \xc3\xa9\r\n\n\xe2\x82".as_slice(), + ] { + let diagnostics = + parse_medui_bytes(source).expect_err("invalid UTF-8 must fail before parsing"); + assert_eq!(diagnostics[0].code, code::SOURCE_NOT_UTF8); + assert_eq!( + diagnostics[0].line, + Some(if source[0] == 0xff { 1 } else { 3 }) + ); + assert_eq!(diagnostics[0].column, None); + } + } + + #[test] + fn authored_ids_are_unique_across_rows_and_root_components_at_parse_time() { + let leaf = |id| { + format!( + "Label {{\nid: {id};\nwidth: 10px;\nheight: 10px;\ntext: t(\"STR-X\");\ncolor: Theme.Colors.Title;\n}}\n" + ) + }; + let row = |id, child| format!("Row {{\nid: {id};\nheight: 10px;\n{} }}\n", leaf(child)); + for body in [ + format!("{}{}", row("row-a", "shared"), row("row-b", "shared")), + format!("{}{}", leaf("shared"), row("row", "shared")), + format!("{}{}", row("shared", "child-a"), row("shared", "child-b")), + ] { + let source = screen_with(&body); + let error = parse_medui_source(&source) + .expect_err("duplicate authored id must fail during parsing"); + let second = source + .lines() + .enumerate() + .filter(|(_, line)| line.trim() == "id: shared;") + .nth(1) + .unwrap() + .0 + + 1; + assert_eq!(error[0].code, code::DUPLICATE_NODE_ID); + assert_eq!(error[0].line, Some(second as u32)); + assert_eq!(error[0].column, None); + } + } + + #[test] + fn overwritten_id_properties_do_not_reserve_authored_names() { + let leaf = |id| { + format!( + "Label {{\nid: {id};\nwidth: 10px;\nheight: 10px;\ntext: t(\"STR-X\");\ncolor: Theme.Colors.Title;\n}}\n" + ) + }; + let canonical = format!("{}{}", leaf("first"), leaf("second")); + for source in [ + canonical.replace("id: first;", "id: second;\nid: first;"), + canonical.replace("id: second;", "id: first;\nid: second;"), + canonical.replace("id: first;", "id: first;\nid: first;"), + ] { + assert_eq!( + parse_medui_source(&screen_with(&source)) + .expect("overwritten IDs must not collide"), + parse_medui_source(&screen_with(&canonical)).expect("canonical IDs are unique") + ); + } + let canonical = format!( + "Row {{\nid: row;\nheight: 10px;\n{} }}\n{}", + leaf("child"), + leaf("other") + ); + for source in [ + canonical.replace("id: row;", "id: other;\nid: row;"), + canonical.replace("id: row;", "id: child;\nid: row;"), + canonical.replace("id: child;", "id: row;\nid: child;"), + canonical.replace("id: row;", "id: row;\nid: row;"), + canonical + .replace("id: row;", "id: child;") + .replace("\n }", "\nid: row;\n}"), + ] { + assert_eq!( + parse_medui_source(&screen_with(&source)) + .expect("overwritten IDs must not collide"), + parse_medui_source(&screen_with(&canonical)).expect("canonical IDs are unique") + ); + } + } + + #[test] + fn final_duplicate_ids_report_the_later_effective_declaration() { + let leaf = "Label {\nid: shared;\nwidth: 10px;\nheight: 10px;\ntext: t(\"STR-X\");\ncolor: Theme.Colors.Title;\n}\n"; + for body in [ + format!("Row {{\nid: discarded;\nid: shared;\nheight: 10px;\n{leaf}}}\n"), + format!("Row {{\nid: discarded;\nheight: 10px;\n{leaf}id: shared;\n}}\n"), + ] { + let source = screen_with(&body); + let last_id_line = source + .lines() + .enumerate() + .filter(|(_, line)| *line == "id: shared;") + .last() + .unwrap() + .0 + + 1; + let errors = + parse_medui_source(&source).expect_err("the final row and child IDs still collide"); + assert_eq!(errors[0].code, code::DUPLICATE_NODE_ID); + assert_eq!(errors[0].line, Some(last_id_line as u32)); + } + } + #[test] fn parse_medui_source_is_deterministic_for_example_screens() { for source in [HELLO_WORLD_MEDUI, NEUROSENSE_MEDUI] { diff --git a/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs index ccdfa87..a0f24bd 100644 --- a/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs +++ b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs @@ -29,7 +29,7 @@ use std::{ process::Command, }; -use trustsc_ui_dsl_authoring::{Diagnostic, parse_medui_source}; +use trustsc_ui_dsl_authoring::{Diagnostic, parse_medui_bytes}; /// Phases this harness can genuinely observe. Anything else claimed in `medui-conformance.toml` /// is a claim without an adapter behind it. @@ -39,14 +39,7 @@ const RUNNABLE_CAPABILITIES: &[&str] = &["syntax"]; fn pinned_shared_conformance_cases() { let manifest = Manifest::read(&repo_root().join("medui-conformance.toml")); - for capability in &manifest.capabilities { - assert!( - RUNNABLE_CAPABILITIES.contains(&capability.as_str()), - "medui-conformance.toml claims `{capability}`, but this harness can only observe \ - {RUNNABLE_CAPABILITIES:?}. Add the adapter that checks that phase's normalized \ - observations before claiming it." - ); - } + assert_supported_claims(&manifest); let Some(root) = conformance_root() else { return; @@ -81,7 +74,8 @@ fn pinned_shared_conformance_cases() { } eprintln!( - "MedUI conformance: {} case(s) at {}; claimed {:?}; unclaimed and not asserted: {}", + "MedUI conformance: {} executed / {} compiler case(s) at {}; claimed {:?}; unclaimed and not asserted: {}", + cases.len() - skipped.len(), cases.len(), manifest.commit, manifest.capabilities, @@ -93,12 +87,27 @@ fn pinned_shared_conformance_cases() { ); } +fn assert_supported_claims(manifest: &Manifest) { + for capability in &manifest.capabilities { + assert!( + RUNNABLE_CAPABILITIES.contains(&capability.as_str()), + "medui-conformance.toml claims `{capability}`, but this harness can only observe \ + {RUNNABLE_CAPABILITIES:?}. Add the adapter that checks that phase's normalized \ + observations before claiming it." + ); + } +} + fn run_case(case: &Case, manifest: &Manifest) { - let source = fs::read_to_string(&case.source).unwrap_or_else(|error| { + let source = fs::read(&case.source).unwrap_or_else(|error| { panic!("{}: source {:?} should read: {error}", case.id, case.source) }); - match parse_medui_source(&source) { + assert_case_observation(case, manifest, &source); +} + +fn assert_case_observation(case: &Case, manifest: &Manifest, source: &[u8]) { + match parse_medui_bytes(source) { Ok(_) => assert!( case.expect_valid, "{}: this implementation accepted a source the pinned contract rejects", @@ -678,3 +687,43 @@ fn parse_integer(bytes: &[u8], at: &mut usize, path: &Path) -> Json { }), ) } + +#[test] +#[should_panic(expected = "but this harness can only observe")] +fn a_phase_without_an_adapter_cannot_be_claimed() { + let mut manifest = Manifest::read(&repo_root().join("medui-conformance.toml")); + manifest.capabilities.push("semantics".to_string()); + assert_supported_claims(&manifest); +} + +#[test] +fn the_gate_rejects_an_adapter_disagreement() { + let manifest = Manifest::read(&repo_root().join("medui-conformance.toml")); + let Some(root) = conformance_root() else { + return; + }; + assert_checkout_matches(&root, &manifest.commit); + let mut case = load_cases(&root) + .into_iter() + .find(|case| manifest.capabilities.contains(&case.phase) && case.expect_valid) + .expect("the pinned claimed phases must exercise an accepted source"); + // I/O and the positive control are outside the caught assertion: neither a missing fixture + // nor a parser rejection may masquerade as the expected adapter disagreement. + let source = fs::read(&case.source).expect("the accepted corpus source should read"); + assert_case_observation(&case, &manifest, &source); + case.expect_valid = false; + let panic = std::panic::catch_unwind(|| assert_case_observation(&case, &manifest, &source)) + .expect_err("the inverted expectation must fail"); + let message = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .expect("the disagreement assertion must provide its message"); + assert_eq!( + message, + format!( + "{}: this implementation accepted a source the pinned contract rejects", + case.id + ) + ); +} diff --git a/docs/dsl/conformance.md b/docs/dsl/conformance.md new file mode 100644 index 0000000..165006c --- /dev/null +++ b/docs/dsl/conformance.md @@ -0,0 +1,67 @@ +# Shared MedUI conformance baseline + +TrustSC adopts MedUI `v0.3.0-rc.1` at +`9a57f6462b6f8dbdf1f0b8b4519674f1c6235dbb`, the revision pinned by MduX. The exact commit in +[`medui-conformance.toml`](../../medui-conformance.toml) controls both CI's checkout and the test +harness. This adoption is tracked by [MduX #335](https://github.com/ambroise-leclerc/MduX/issues/335). + +## Declared coverage + +| Capability | TrustSC gate | Boundary | +|---|---|---| +| Syntax | All five pinned syntax cases, through `parse_medui_bytes` and the production parser | Expectations come from the pinned `case.json` files, including rejection codes and lines. | +| Diagnostic positions | `line-only` | Columns remain absent. A reported column fails this declaration rather than silently claiming full precision. | +| Semantics, layout, safety | Unclaimed | Local compilation exists, but the shared harness has no complete adapters for these phases' inputs and normalized observations. Claiming one fails the gate. | +| RENDERED, EVIDENCE | Unclaimed | Native verification checks/reports are not complete implementations of these observation profiles. No profile or pixel-equivalence claim follows from the syntax pass. | + +The new pin adds three syntax cases to the two previously checked. Duplicate authored IDs now fail +while parsing, across root components, Rows and their children; the compiled-node check remains +necessary for synthesized panel IDs and caller-edited ASTs. Invalid UTF-8 now produces `MEDUI-E004` +at its source line, through the public byte parser, file compiler, checker and Studio file endpoints. I/O failures remain +`MEDUI-E003`. The parser still carries no columns. + +The harness reports executed and unclaimed cases separately: five of the 27 compiler cases execute. +It fails if the checkout is absent in CI, its revision differs from the manifest, a claimed phase +has no adapter or no cases, or an observation disagrees with the corpus. Regression tests also +exercise a deliberately inverted corpus expectation and an unsupported phase claim. CI exposes +this gate as a named step before the broader test suite. + +## Known diagnostic gaps at this pin + +The diagnostic constants are an implementation subset, not a complete registry. E000/E001/E002 +belong to a recipe reader this crate does not provide. E017, E033/E034/E035 and E054 still use +legacy error paths instead of their registered identities; E053 is not implemented here. E070 +is a behavioral divergence: +a safety annotation does not require an otherwise optional Button/TextInput requirement, so such +a node can compile when its other checks succeed. The shared safety phase remains unclaimed. +These are local gaps against the newer registry, not missing definitions in MedUI itself. + +Duplicate-ID checking uses only each node's final `id:` value, preserving the parser's existing +last-value-wins behavior for repeated fields. Effective declarations are compared in source order, +including a Row whose final ID appears after its children. Overwritten values reserve no names. +Studio distinguishes missing/unreadable files (E003) from invalid UTF-8 (E004) on detail, frame and +proposal endpoints; valid UTF-8 syntax errors retain their original source text and hash for editing. +The gate's disagreement negative loads its source and runs a positive control before catching the +inverted expectation, then checks the exact mismatch message. + +## Reproduction and review + +Check out the exact MedUI commit above, then run from TrustSC: + +```sh +export MEDUI_CONFORMANCE_DIR=/path/to/pinned/MedUI +CI=1 cargo test --locked -p trustsc-ui-dsl-authoring --test shared_conformance -- --nocapture +cargo test --locked -p trustsc-ui-dsl-authoring -p trustsc-medui-check +``` + +Paired consumer heads and results belong in +[MduX's results table](https://github.com/ambroise-leclerc/MduX/blob/develop/docs/roadmap.md#314-per-capability-conformance-results). +A shared pin permits a shared syntax baseline at line precision; it does not substantiate the +unclaimed phases or profiles. MduX retains all four phases, full positions and both profiles. +Joint maintainer review of the paired results is still required before MduX #335 is signed off. + +Impact is potentially safety-relevant: earlier duplicate rejection and distinct encoding diagnostics +improve compiler conformance evidence without changing device rendering. The affected interfaces +are the host parser, file compiler and checker; their syntax and CLI tests supply the evidence. +No baked artifacts or device risk-control implementation changes here, and no certification or +production-readiness claim is made. diff --git a/docs/dsl/overview.md b/docs/dsl/overview.md index bc9f511..4fd1a38 100644 --- a/docs/dsl/overview.md +++ b/docs/dsl/overview.md @@ -5,6 +5,9 @@ The implementation-neutral contract is versioned in `medui-conformance.toml`. This directory documents TrustSC's Rust build, runtime, rendering, and evidence integration; where portable language rules differ, the pinned shared contract wins. +The [shared conformance baseline](conformance.md) records exactly which pinned observations +TrustSC claims and how CI checks them. + The MedUI DSL is a deterministic build-time language for authored medical UI screens in `TrustSC`. ## Goals diff --git a/medui-conformance.toml b/medui-conformance.toml index da887a4..3e48003 100644 --- a/medui-conformance.toml +++ b/medui-conformance.toml @@ -1,9 +1,9 @@ repository = "https://github.com/Compliatory/MedUI" -version = "0.1.0-candidate" +version = "0.3.0-rc.1" # The single source of truth for the pin: CI derives its `actions/checkout` ref from this line, # and `crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs` reads the same file, so the # workflow and the harness cannot drift apart. -commit = "c8cc45ecec2f2dfd84940b9efc17c613e691cc0d" +commit = "9a57f6462b6f8dbdf1f0b8b4519674f1c6235dbb" # The implementation already has richer local behavior, but only syntax is claimed until each # shared phase has a complete adapter that checks its normalized observations. capabilities = ["syntax"] diff --git a/tools/trustsc-medui-check/src/main.rs b/tools/trustsc-medui-check/src/main.rs index cf17ecf..02670b6 100644 --- a/tools/trustsc-medui-check/src/main.rs +++ b/tools/trustsc-medui-check/src/main.rs @@ -12,7 +12,7 @@ use std::process::ExitCode; use trustsc_ui_dsl_authoring::{ CompileOptions, Diagnostic, ImagePackages, Severity, TextPackages, code, - compile_screen_definition, parse_medui_source, + compile_screen_definition, parse_medui_bytes, }; /// Matches the fallback every other tool in this repo uses for a screen with no `surface:` pin @@ -62,7 +62,7 @@ fn main() -> ExitCode { } }; - let source = match std::fs::read_to_string(path) { + let source = match std::fs::read(path) { Ok(source) => source, Err(error) => { report_early_failure( @@ -75,7 +75,7 @@ fn main() -> ExitCode { } }; - let screen = match parse_medui_source(&source) { + let screen = match parse_medui_bytes(&source) { Ok(screen) => screen, Err(diagnostics) => { report(&diagnostics, path, format); diff --git a/tools/trustsc-medui-check/tests/cli.rs b/tools/trustsc-medui-check/tests/cli.rs index 57109c4..065c877 100644 --- a/tools/trustsc-medui-check/tests/cli.rs +++ b/tools/trustsc-medui-check/tests/cli.rs @@ -239,3 +239,15 @@ fn assert_object_matches(value: &serde_json::Value, schema: &serde_json::Value, ); } } + +#[test] +fn invalid_utf8_is_a_positioned_encoding_diagnostic_not_an_io_failure() { + let file = TempMeduiFile::new(""); + std::fs::write(file.path(), b"// comment\r\n\xff").unwrap(); + let output = run_json(file.path()); + assert!(!output.status.success()); + let envelope: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(envelope["findings"][0]["code"], "MEDUI-E004"); + assert_eq!(envelope["findings"][0]["line"], 2); + assert_eq!(envelope["findings"][0]["column"], 0); +} diff --git a/tools/trustsc-medui-studio/src/api.rs b/tools/trustsc-medui-studio/src/api.rs index 0580669..12907d9 100644 --- a/tools/trustsc-medui-studio/src/api.rs +++ b/tools/trustsc-medui-studio/src/api.rs @@ -12,8 +12,8 @@ use axum::Json; use serde::{Deserialize, Serialize}; use trustsc_ui_dsl_authoring::{ CompileOptions, CompiledScreenSpec, Diagnostic, ImagePackages, ScreenDefinition, - TextPackages, compile_screen_definition, enumerate_images, enumerate_numeric_templates, - enumerate_text_keys, parse_medui_source, serialize_screen, widget_catalog, + TextPackages, code, compile_screen_definition, enumerate_images, enumerate_numeric_templates, + enumerate_text_keys, parse_medui_bytes, parse_medui_source, serialize_screen, widget_catalog, }; use crate::render_bridge; @@ -76,7 +76,14 @@ struct CompileOutcome { } fn compile_source_with_defaults(state: &AppState, source: &str) -> CompileOutcome { - match parse_medui_source(source) { + compile_parsed_with_defaults(state, parse_medui_source(source)) +} + +fn compile_parsed_with_defaults( + state: &AppState, + parsed: Result>, +) -> CompileOutcome { + match parsed { Ok(screen) => compile_screen_with_defaults(state, screen), Err(diagnostics) => CompileOutcome { screen: None, @@ -134,6 +141,70 @@ fn diagnostics_message(diagnostics: &[Diagnostic]) -> String { .join("; ") } +/// Source text stays lossless for editing and concurrency hashes. A valid UTF-8 file may still +/// contain syntax errors: detail can show them and proposals can repair the original source. +struct LoadedMeduiSource { + text: String, + parsed: Result>, +} + +fn source_diagnostics_error(diagnostics: Vec) -> Response { + #[derive(Serialize)] + struct Envelope { + error: String, + code: &'static str, + diagnostics: Vec, + } + let error = diagnostics_message(&diagnostics); + let code = diagnostics + .first() + .map(|diagnostic| diagnostic.code) + .unwrap_or(code::UNEXPECTED_TOKEN); + ( + StatusCode::UNPROCESSABLE_ENTITY, + Json(Envelope { + error, + code, + diagnostics: dto::diagnostics_to_dto(diagnostics), + }), + ) + .into_response() +} + +async fn load_medui_source(file_path: PathBuf, id: &str) -> Result { + let bytes = match tokio::task::spawn_blocking(move || std::fs::read(file_path)).await { + Ok(Ok(bytes)) => bytes, + Ok(Err(error)) => { + let status = if error.kind() == std::io::ErrorKind::NotFound { + StatusCode::NOT_FOUND + } else { + StatusCode::INTERNAL_SERVER_ERROR + }; + return Err(coded_error( + status, + code::SOURCE_UNREADABLE, + format!("failed to read screen: {id}"), + )); + } + Err(_) => { + return Err(error_response( + StatusCode::INTERNAL_SERVER_ERROR, + "read task failed", + )); + } + }; + let parsed = parse_medui_bytes(&bytes); + match (String::from_utf8(bytes), parsed) { + (Ok(text), parsed) => Ok(LoadedMeduiSource { text, parsed }), + (Err(_), Err(diagnostics)) => Err(source_diagnostics_error(diagnostics)), + // An encoding disagreement is an internal error, never replacement characters in an edit. + (Err(_), Ok(_)) => Err(error_response( + StatusCode::INTERNAL_SERVER_ERROR, + "source decoder disagreed with parser", + )), + } +} + // --------------------------------------------------------------------------------------------- // GET /api/screens/{id} // --------------------------------------------------------------------------------------------- @@ -160,14 +231,12 @@ async fn screen_detail(State(state): State>, Path(id): Path path, Err(message) => return error_response(StatusCode::BAD_REQUEST, message), }; - let source = match tokio::task::spawn_blocking(move || std::fs::read_to_string(file_path)).await - { - Ok(Ok(source)) => source, - Ok(Err(_)) => return error_response(StatusCode::NOT_FOUND, format!("no such screen: {id}")), - Err(_) => return error_response(StatusCode::INTERNAL_SERVER_ERROR, "read task failed"), + let loaded = match load_medui_source(file_path, &id).await { + Ok(loaded) => loaded, + Err(response) => return response, }; - - let outcome = compile_source_with_defaults(&state, &source); + let source = loaded.text; + let outcome = compile_parsed_with_defaults(&state, loaded.parsed); // A screen that parses but fails to compile still declared its own `surface:` (if any) — // report that instead of silently falling back to the 800x480 default, which would give the // frontend the wrong canvas size for the diagnostics it's about to show. @@ -253,20 +322,13 @@ async fn frame_get(State(state): State>, Query(params): Query path, Err(message) => return error_response(StatusCode::BAD_REQUEST, message), }; - let source = match tokio::task::spawn_blocking(move || std::fs::read_to_string(file_path)).await - { - Ok(Ok(source)) => source, - Ok(Err(_)) => { - return error_response(StatusCode::NOT_FOUND, format!("no such screen: {}", params.screen)); - } - Err(_) => return error_response(StatusCode::INTERNAL_SERVER_ERROR, "read task failed"), + let loaded = match load_medui_source(file_path, ¶ms.screen).await { + Ok(loaded) => loaded, + Err(response) => return response, }; - - let screen = match parse_medui_source(&source) { + let screen = match loaded.parsed { Ok(screen) => screen, - Err(diagnostics) => { - return error_response(StatusCode::UNPROCESSABLE_ENTITY, diagnostics_message(&diagnostics)); - } + Err(diagnostics) => return source_diagnostics_error(diagnostics), }; render_response(&state, screen, params.locale).await @@ -489,13 +551,9 @@ async fn create_proposal( Ok(path) => path, Err(message) => return error_response(StatusCode::BAD_REQUEST, message), }; - let read_path = file_path.clone(); - let current_source = match tokio::task::spawn_blocking(move || std::fs::read_to_string(read_path)).await { - Ok(Ok(source)) => source, - Ok(Err(_)) => { - return error_response(StatusCode::NOT_FOUND, format!("no such screen: {}", request.screen_id)); - } - Err(_) => return error_response(StatusCode::INTERNAL_SERVER_ERROR, "read task failed"), + let current_source = match load_medui_source(file_path.clone(), &request.screen_id).await { + Ok(loaded) => loaded.text, + Err(response) => return response, }; if sha256_hex(current_source.as_bytes()) != request.base_source_sha256 { @@ -683,6 +741,87 @@ mod tests { assert_eq!(response.status(), StatusCode::BAD_REQUEST); } + #[tokio::test] + async fn file_endpoints_distinguish_invalid_utf8_from_missing_and_unreadable_sources() { + let temp = std::env::temp_dir().join(format!( + "trustsc-studio-source-errors-{}", + std::process::id() + )); + std::fs::create_dir_all(&temp).unwrap(); + std::fs::write(temp.join("invalid.medui"), b"// valid comment\r\n\xff").unwrap(); + std::fs::create_dir_all(temp.join("directory.medui")).unwrap(); + let app = crate::build_router(test_state_for(temp.clone(), None)); + for (file, status, code) in [ + ( + "invalid.medui", + StatusCode::UNPROCESSABLE_ENTITY, + "MEDUI-E004", + ), + ("missing.medui", StatusCode::NOT_FOUND, "MEDUI-E003"), + ( + "directory.medui", + StatusCode::INTERNAL_SERVER_ERROR, + "MEDUI-E003", + ), + ] { + let mut responses = Vec::new(); + for uri in [ + format!("/api/screens/{file}"), + format!("/api/frame?screen={file}"), + ] { + responses.push( + app.clone() + .oneshot(HttpRequest::get(uri).body(Body::empty()).unwrap()) + .await + .unwrap(), + ); + } + responses.push( + post_proposal( + &app, + json!({ + "screen_id": file, + "screen": hello_screen_dto(), + "base_source_sha256": "irrelevant: reading fails first", + "title": "Repair screen", + }), + ) + .await, + ); + for response in responses { + assert_eq!(response.status(), status, "{file}"); + let body = json_body(response).await; + assert_eq!(body["code"], code, "{file}: {body}"); + if code == "MEDUI-E004" { + assert_eq!(body["diagnostics"][0]["line"], 2); + assert!(body["diagnostics"][0]["column"].is_null()); + } + } + } + // UTF-8 syntax errors remain editable: source and its byte-exact hash must survive. + let source = "// operator note: é\r\nnot a screen\r\n"; + std::fs::write(temp.join("syntax.medui"), source).unwrap(); + let response = app + .oneshot( + HttpRequest::get("/api/screens/syntax.medui") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = json_body(response).await; + assert_eq!(body["source"], source); + assert_eq!(body["source_sha256"], super::sha256_hex(source.as_bytes())); + assert!( + !body["compiled"]["diagnostics"] + .as_array() + .unwrap() + .is_empty() + ); + std::fs::remove_dir_all(&temp).unwrap(); + } + #[tokio::test] async fn screens_detail_reports_the_declared_surface_when_compile_fails() { let temp = std::env::temp_dir().join(format!( diff --git a/tools/trustsc-medui-studio/src/main.rs b/tools/trustsc-medui-studio/src/main.rs index 24036e0..156f164 100644 --- a/tools/trustsc-medui-studio/src/main.rs +++ b/tools/trustsc-medui-studio/src/main.rs @@ -236,9 +236,9 @@ fn scan_screens(repo: &Path) -> Vec { .unwrap_or(&absolute) .to_string_lossy() .replace('\\', "/"); - let screen_name = std::fs::read_to_string(&absolute) + let screen_name = std::fs::read(&absolute) .ok() - .and_then(|source| trustsc_ui_dsl_authoring::parse_medui_source(&source).ok()) + .and_then(|source| trustsc_ui_dsl_authoring::parse_medui_bytes(&source).ok()) .map(|screen| screen.id) .unwrap_or_else(|| "".to_string()); ScreenEntry {