From f572288ff96d86f385398a9cb53ea65469d75cf4 Mon Sep 17 00:00:00 2001 From: leader Date: Sun, 29 Nov 2026 00:16:35 +0900 Subject: [PATCH 1/3] Verify Figma states and requirements before claiming completion devup_feature_trace gains optional stateChecks, requirements, designGaps and changes inputs that return a verification matrix: - per-state groups (default/hover/active/focus/selected/disabled) comparing Figma size, position, colour, border and typography with implementation values, optional pixel checks through devup_visual_compare, and expected component-set variant states; missing design, missing capture and static-only states stay unverified - requirement verdicts (verified/unverified/not-applicable) with evidence, screen/component/state scope and browser-verification-required for interaction or visual requirements proven only statically - Figma data gaps (missing nodes/properties, failed reads/exports) with the screens, states and requirements they block; claims gate design-match and completion - change impact for shared components, shared vs screen-only config scope, static vs observed result counts - a review report per change and an ordered followUp for unfinished verification, documented in the guide (section 17) and the devup-implementation-plan skill Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_CHxB9HNH9RXXboczwgIMk.json | 7 + .../devup-mcp/src/server/feature_trace/run.rs | 79 ++- .../server/feature_trace/types_and_helpers.rs | 2 +- .../src/server/feature_trace_tests.rs | 67 ++ .../server/handlers/devup_feature_trace.rs | 2 +- .../server/mod_parts/state_and_services.rs | 2 + .../skills/devup-implementation-plan/SKILL.md | 56 ++ .../devup-mcp/src/server/skills/manifest.json | 4 +- .../src/server/text/devup-feature-trace.md | 2 +- .../src/server/text/guide-GUIDE-c682b0c5.md | 56 ++ crates/devup-mcp/src/server/tools.rs | 12 + .../src/server/verification_matrix.rs | 16 + .../requirements_and_report.rs | 602 ++++++++++++++++++ .../verification_matrix/states_and_gaps.rs | 322 ++++++++++ .../src/server/verification_matrix/style.rs | 381 +++++++++++ .../src/server/verification_matrix/types.rs | 294 +++++++++ .../src/server/verification_matrix_tests.rs | 368 +++++++++++ 17 files changed, 2263 insertions(+), 9 deletions(-) create mode 100644 .changepacks/changepack_log_CHxB9HNH9RXXboczwgIMk.json create mode 100644 crates/devup-mcp/src/server/verification_matrix.rs create mode 100644 crates/devup-mcp/src/server/verification_matrix/requirements_and_report.rs create mode 100644 crates/devup-mcp/src/server/verification_matrix/states_and_gaps.rs create mode 100644 crates/devup-mcp/src/server/verification_matrix/style.rs create mode 100644 crates/devup-mcp/src/server/verification_matrix/types.rs create mode 100644 crates/devup-mcp/src/server/verification_matrix_tests.rs diff --git a/.changepacks/changepack_log_CHxB9HNH9RXXboczwgIMk.json b/.changepacks/changepack_log_CHxB9HNH9RXXboczwgIMk.json new file mode 100644 index 00000000..334efda9 --- /dev/null +++ b/.changepacks/changepack_log_CHxB9HNH9RXXboczwgIMk.json @@ -0,0 +1,7 @@ +{ + "changes": { + "Cargo.toml": "Minor" + }, + "note": "Add a per-state and per-requirement verification matrix to devup_feature_trace: Figma-vs-implementation state comparisons, requirement verdicts with scope and evidence, Figma data gaps that block design-match claims, change impact, a user review report and an ordered follow-up for unfinished verification", + "date": "2026-11-28T14:35:15.989000Z" +} diff --git a/crates/devup-mcp/src/server/feature_trace/run.rs b/crates/devup-mcp/src/server/feature_trace/run.rs index dc353120..cc728e62 100644 --- a/crates/devup-mcp/src/server/feature_trace/run.rs +++ b/crates/devup-mcp/src/server/feature_trace/run.rs @@ -1,8 +1,17 @@ - - +#[cfg(test)] pub(super) async fn run( input: FeatureTraceInput, artifacts: &ArtifactStore, +) -> Result { + run_with(input, artifacts, None).await +} + +/// The trace, with the output policy that lets state checks reuse +/// devup_visual_compare for their optional pixel comparisons. +pub(super) async fn run_with( + input: FeatureTraceInput, + artifacts: &ArtifactStore, + policy: Option<&super::output::OutputPolicy>, ) -> Result { let max_items = input.max_items.unwrap_or(100); if !(1..=200).contains(&max_items) { @@ -34,6 +43,11 @@ pub(super) async fn run( ] .into_iter() .any(supplied) + && input.state_checks.is_empty() + && !input + .requirements + .iter() + .any(|r| !r.targets.is_empty() || supplied(&r.figma_node_id)) { return Ok(json!({"status":"REFUSED","message":ACCEPTED})); } @@ -447,11 +461,22 @@ pub(super) async fn run( "implementedEvidence":implemented.get(*state), "reason":"Presence records explicit state declarations or App Router boundary components only. Missing evidence is unknown, never assumed absent; runtime coverage requires tests."})).collect::>(); let acceptance=input.acceptance_criteria.iter().map(|criterion|json!({"criterion":criterion,"status":"UNVERIFIED","reason":"Caller acceptance text is preserved without semantic interpretation; supply tests or inspect the linked evidence."})).collect::>(); - let summary = summarize( + let mut summary = summarize( &chain, &anchor_status, ui["truncation"]["truncated"] == true, ); + let verification = verification(&input, &ui, &root, artifacts, policy).await; + if let Some(claims) = verification.as_ref().map(|v| &v["claims"]) { + let required = summary["required"].as_array_mut().unwrap(); + for reason in array(&claims["completionBlockedBy"]) { + required.push(json!(format!( + "Do not claim a design match or a finished verification: {}", + text(reason) + ))); + } + summary["verification"] = json!({"designMatch":claims["designMatch"],"verificationComplete":claims["verificationComplete"]}); + } let mut navigation_graph = super::navigation::graph( &design.evidence["interactiveCandidates"], &navigation_sources, @@ -469,7 +494,7 @@ pub(super) async fn run( Ok(bound( json!({"status":"OK","summary":summary,"projectRoot":root,"anchors":{"routePath":input.route_path,"figmaNodeId":input.figma_node_id,"artifactId":input.artifact_id,"operationId":input.operation_id,"apiPath":input.api_path,"method":input.method,"componentPath":input.component_path,"tableName":input.table_name},"requirement":input.requirement,"acceptanceMatrix":acceptance, "chain":chain,"artifacts":traced_artifacts.into_values().collect::>(),"sourceOwnership":ownership,"reuseCandidates":reuse,"designContract":comparisons,"requiredStates":states, - "navigationGraph":navigation_graph, + "navigationGraph":navigation_graph,"verification":verification, "designEvidence":design.evidence,"designDiagnostics":design.diagnostics,"diagnostics":diagnostics, "inventoryEvidence":{"uiTruncation":ui["truncation"],"uiLimits":ui["limits"],"uiDiagnostics":ui["diagnostics"],"uiExcludedPaths":ui["excludedPaths"],"unparsedFiles":ui["unparsedFiles"],"api":{"found":api["found"],"excludedPaths":api["excludedPaths"],"authorityNote":api["authorityNote"],"issues":array(&api["specs"]).iter().filter(|v|v.get("parseError").is_some()||v.get("readError").is_some()).collect::>()}, "db":{"found":db["found"],"excludedPaths":db["excludedPaths"],"authorityNote":db["authorityNote"],"issues":array(&db["tables"]).iter().filter(|v|v.get("parseError").is_some()||v.get("readError").is_some()).collect::>()} @@ -478,6 +503,52 @@ pub(super) async fn run( max_items, )) } +/// The verification matrix over the caller's states, requirements, gaps and changes. +async fn verification( + input: &FeatureTraceInput, + ui: &Value, + root: &Path, + artifacts: &ArtifactStore, + policy: Option<&super::output::OutputPolicy>, +) -> Option { + use super::verification_matrix::{MatrixContext, MatrixInput, build}; + let matrix = MatrixInput { + state_checks: &input.state_checks, + requirements: &input.requirements, + design_gaps: &input.design_gaps, + changes: &input.changes, + component_path: input.component_path.as_deref(), + }; + if matrix.is_empty() { + return None; + } + let lookup = match input + .artifact_id + .as_deref() + .filter(|id| !id.trim().is_empty()) + { + Some(id) => Some( + artifacts + .get(id) + .await + .ok_or("artifactId is missing or expired; the design data could not be read."), + ), + None => None, + }; + let payload = lookup + .as_ref() + .and_then(|l| l.as_ref().ok()) + .map(|l| l.payload.clone()); + let context = MatrixContext { + ui, + root, + payload: payload.as_deref(), + artifact_unavailable: lookup.and_then(|l| l.err()).map(str::to_owned), + policy, + store: artifacts, + }; + build(&context, &matrix).await +} /// Normalise a caller-supplied component path to the inventory's `a/b/c.tsx` form. fn anchor_path(path: &str) -> String { let unified = path.trim().replace('\\', "/"); diff --git a/crates/devup-mcp/src/server/feature_trace/types_and_helpers.rs b/crates/devup-mcp/src/server/feature_trace/types_and_helpers.rs index fae9db2c..6d550ce7 100644 --- a/crates/devup-mcp/src/server/feature_trace/types_and_helpers.rs +++ b/crates/devup-mcp/src/server/feature_trace/types_and_helpers.rs @@ -568,7 +568,7 @@ fn bound(mut value: Value, max_items: usize) -> Value { .as_object() .unwrap() .iter() - .filter(|(k, _)| !matches!(k.as_str(), "truncation" | "limits" | "status" | "summary")) + .filter(|(k, _)| !matches!(k.as_str(), "truncation" | "limits" | "status" | "summary" | "verification")) .max_by_key(|(_, v)| v.to_string().len()) .map(|(k, _)| k.clone()); let Some(key) = key else { diff --git a/crates/devup-mcp/src/server/feature_trace_tests.rs b/crates/devup-mcp/src/server/feature_trace_tests.rs index f0d71808..c61b526c 100644 --- a/crates/devup-mcp/src/server/feature_trace_tests.rs +++ b/crates/devup-mcp/src/server/feature_trace_tests.rs @@ -411,3 +411,70 @@ async fn unreadable_or_escaping_component_anchor_is_a_required_fix() { assert!(!v["summary"]["required"].as_array().unwrap().is_empty()); } } + +#[tokio::test] +async fn state_checks_are_explicit_anchors_and_gate_completion_claims() { + let f = Fixture::new(); + let v = f + .trace(json!({"stateChecks":[{"target":"components/UserForm.tsx","routePath":"/users","state":"hover", + "design":{"width":10},"implementation":{"width":10}}]})) + .await; + assert_eq!(v["status"], "OK", "{v}"); + let state = &v["verification"]["stateGroups"][0]["states"][0]; + assert_eq!(state["verdict"], "unverified"); + assert_eq!(state["browserVerificationRequired"], true); + assert_eq!(v["summary"]["verification"]["designMatch"], "blocked"); + assert!( + v["summary"]["required"] + .as_array() + .unwrap() + .iter() + .any(|r| r + .as_str() + .unwrap() + .starts_with("Do not claim a design match")) + ); + let impact = &v["verification"]["changeImpact"][0]; + assert_eq!(impact["path"], "components/UserForm.tsx"); + assert_eq!(impact["affectedScreens"], json!(["/users"])); +} + +#[tokio::test] +async fn untargeted_requirements_stay_refused_and_old_calls_are_unchanged() { + let f = Fixture::new(); + let refused = f + .trace(json!({"requirements":[{"id":"R","text":"anchorless prose"}]})) + .await; + assert_eq!(refused["status"], "REFUSED"); + let plain = f.trace(json!({"routePath":"/users"})).await; + assert!(plain["verification"].is_null()); + assert!(plain["summary"].get("verification").is_none()); +} + +#[tokio::test] +async fn a_missing_artifact_is_a_design_gap_for_state_checks() { + let f = Fixture::new(); + let v = f + .trace(json!({"artifactId":"gone","stateChecks":[{"target":"Button","state":"default","figmaNodeId":"1:1", + "design":{"width":1},"implementation":{"width":1},"implementationSource":"browser"}]})) + .await; + assert_eq!(v["verification"]["designData"]["complete"], false); + assert_eq!( + v["verification"]["designData"]["gaps"][0]["kind"], + "read-failed" + ); + assert_eq!(v["verification"]["claims"]["designMatch"], "blocked"); +} + +#[test] +fn verification_inputs_reject_unknown_fields() { + let parsed = serde_json::from_value::( + json!({"stateChecks":[{"target":"x","state":"hover","bogus":1}]}), + ); + assert!(parsed.is_err()); + let parsed = serde_json::from_value::( + json!({"requirements":[{"id":"r","text":"t","check":"interaction","targets":[{"routePath":"/"}]}]}), + ) + .unwrap(); + assert_eq!(parsed.requirements.len(), 1); +} diff --git a/crates/devup-mcp/src/server/handlers/devup_feature_trace.rs b/crates/devup-mcp/src/server/handlers/devup_feature_trace.rs index 966a7015..37b51d30 100644 --- a/crates/devup-mcp/src/server/handlers/devup_feature_trace.rs +++ b/crates/devup-mcp/src/server/handlers/devup_feature_trace.rs @@ -10,7 +10,7 @@ impl DevupServer { &self, Parameters(input): Parameters, ) -> Result { - let result = feature_trace::run(input, &self.artifacts) + let result = feature_trace::run_with(input, &self.artifacts, Some(&self.output_policy)) .await .map_err(to_mcp_error)?; Ok(tool_result(result)) diff --git a/crates/devup-mcp/src/server/mod_parts/state_and_services.rs b/crates/devup-mcp/src/server/mod_parts/state_and_services.rs index 64d6cc94..30de1fad 100644 --- a/crates/devup-mcp/src/server/mod_parts/state_and_services.rs +++ b/crates/devup-mcp/src/server/mod_parts/state_and_services.rs @@ -102,6 +102,8 @@ mod validation; mod validation_guidance; #[path = "../verdict_scope.rs"] mod verdict_scope; +#[path = "../verification_matrix.rs"] +mod verification_matrix; #[path = "../visual_compare.rs"] mod visual_compare; diff --git a/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md b/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md index be6a434f..0f4a8d56 100644 --- a/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md +++ b/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md @@ -679,6 +679,62 @@ These rules apply to every plan this workflow produces. Treat `DEVUP_DESIGN_COMPONENT_WIDTH_MISMATCH` as an automatically resolved design placement error. The screen plan records the strict same-width majority, the expected master and a correct sibling instance, plus native-node PNG comparisons when available (otherwise `render=unavailable`). Follow that assumption without another question. Header/Footer/Nav remains one responsive component across widths, not a second variant. Audit planning substitutes the correct sibling's height and children at screen width and the suspect's original y position. The original whole-page PNG still depicts the design error and must not be accepted as a corrected-page visual reference. +## Verify states and requirements, report for review + +Use `devup_feature_trace` as the verification matrix. Static source reading and +browser observation are kept apart everywhere: a value read from source is +`static`, and static evidence never verifies rendered behaviour. + +- **Before implementing**, read `reuseCandidates` (existing components and + style patterns), `verification.changeImpact` (every screen that imports a + component you will change: `shared` means the change reaches all of them) and + `verification.configScope` (shared files such as `devup.json` or the root + layout versus screen-only files). Put a value only one screen needs in that + screen's files. +- **States.** Send one `stateChecks` row per state of a component or screen + (default, hover, active, focus, selected, disabled, ...): `target`, + `routePath`, `state`, the Figma `figmaNodeId` of that state (with + `artifactId` its size, position, colour, border and typography are read from + the snapshot; component-set variants become `expectedStates`), the measured + `implementation` values and `implementationSource` (`browser` when read from + computed style in a browser). Add `visual` (the `devup_visual_compare` input) + only when a pixel comparison is needed. A state without a design or a capture, + an expected state nobody checked, and a static-only state are `unverified`, + never a pass. Capture only to compare or to analyse a failure. +- **Requirements.** Send each design spec card (`origin: design-spec-card`) + and user requirement as `requirements` with its `targets` (route, component, + state, Figma node) and `check` kind. Verdicts are `verified`, `unverified` + or `not-applicable` with `reason`, `evidence` and `scope`. Interaction and + visual requirements need browser, automated-test or manual evidence; static + passes leave them `browser-verification-required`. A requirement reaching + several screens (`scope.multiScreen`, `sharedComponents`) needs evidence on + every screen in `scope.screens`. +- **Incomplete Figma data.** `verification.designData.gaps` lists each missing + node or property with its cause (from the artifact, plus `designGaps` you add + for failed reads or exports) and `cannotJudge` names the screens, states and + requirements it blocks. While `claims.designMatch` or + `claims.verificationComplete` is `blocked`, do not report a design match or + a finished verification. +- **Review report.** Pass `changes` (summary, route, files, requirementIds). + `reviewReport.changes` gives the user, per change, the path to open, the + steps, the expected result and the results split into automated, browser, + manual and static. Captures appear only for failed visual comparisons; write + a separate capture summary only when the user asks for one. +- **When a verification cannot be finished**, follow `followUp.order`: + 1. find the cause; fix what is inside the request's scope and verify again + (`followUp.fixInScope` carries the next action); + 2. finish other work that does not depend on it; + 3. only when a user permission or an external environment change is + required, ask once, briefly: the unfinished verification and the cause + found so far, the recommended fix and what it would verify, and the action + or permission needed (record it as `blocker` with `cause`, + `recommendation`, `verifies`, `userAction`; `followUp.askUser` names any + field still missing); + 4. keep doing unaffected work while waiting; + 5. report what cannot be resolved with the attempts made and the remaining + constraint (`blocker.kind: unresolvable` with `attempts`; listed in + `followUp.unresolved`). + ## Delivery quality Apply `developmentContract` and `behaviorPlan` on every export. Read the bundled diff --git a/crates/devup-mcp/src/server/skills/manifest.json b/crates/devup-mcp/src/server/skills/manifest.json index c4ea20df..ac567eed 100644 --- a/crates/devup-mcp/src/server/skills/manifest.json +++ b/crates/devup-mcp/src/server/skills/manifest.json @@ -99,8 +99,8 @@ "documents": [ { "path": "SKILL.md", - "bytes": 48735, - "sha256": "5fe7b752fb5f830e8efda50cb33e1e6ae23db22d6725544139d4fc70401f83d3" + "bytes": 52386, + "sha256": "9e97e444543da65a55d2957efe3d614339ca79627f047dd6d672a89829ac906a" } ], "sourceUrl": "https://github.com/dev-five-git/devup-mcp/blob/HEAD/crates/devup-mcp/src/server/skills/devup-implementation-plan", diff --git a/crates/devup-mcp/src/server/text/devup-feature-trace.md b/crates/devup-mcp/src/server/text/devup-feature-trace.md index f8b3b69f..2ba52e0d 100644 --- a/crates/devup-mcp/src/server/text/devup-feature-trace.md +++ b/crates/devup-mcp/src/server/text/devup-feature-trace.md @@ -1 +1 @@ -Read-only cross-layer feature slice and acceptance matrix from explicit anchors: routePath, figmaNodeId/artifactId, operationId or apiPath+method, componentPath, tableName. Refuses anchorless prose. Returns evidence-backed or UNVERIFIED hops, generated-source ownership, ranked UI reuse, literal design binding versus request/response fields, required-state coverage, and named truncation caps. Optional requirement/acceptanceCriteria are echoed without semantic interpretation. componentTsx is a caller-declared Figma export; artifactId uses the cached snapshot. Static parsing never proves runtime behavior. \ No newline at end of file +Read-only cross-layer feature slice and acceptance matrix from explicit anchors: routePath, figmaNodeId/artifactId, operationId or apiPath+method, componentPath, tableName. Refuses anchorless prose. Returns evidence-backed or UNVERIFIED hops, generated-source ownership, ranked UI reuse, literal design binding versus request/response fields, required-state coverage, and named truncation caps. Optional requirement/acceptanceCriteria are echoed without semantic interpretation. componentTsx is a caller-declared Figma export; artifactId uses the cached snapshot. Static parsing never proves runtime behavior. Optional verification inputs (stateChecks, requirements, designGaps, changes) return verification: per-state groups comparing Figma size/position/colour/border/typography (from artifactId or design values) with implementation values, optional devup_visual_compare pixels, and expected component-set variant states; requirement verdicts verified/unverified/not-applicable with evidence, screen/component/state scope and browser-verification-required for interaction or visual requirements proven only statically; Figma gaps (missing nodes/properties, failed reads/exports) with what they block; changeImpact and configScope; a reviewReport per change (path, steps, expected, automated/browser/manual/static results, captures only for failures); followUp in the order fix-in-scope, continue independent work, ask the user only for permissions or environment, keep working, report unresolved with attempts; and claims gating design-match and completion. Missing design or capture is unverified, never a pass. See devup://guide/usage section 17. \ No newline at end of file diff --git a/crates/devup-mcp/src/server/text/guide-GUIDE-c682b0c5.md b/crates/devup-mcp/src/server/text/guide-GUIDE-c682b0c5.md index 8dbc7d94..33580d95 100644 --- a/crates/devup-mcp/src/server/text/guide-GUIDE-c682b0c5.md +++ b/crates/devup-mcp/src/server/text/guide-GUIDE-c682b0c5.md @@ -423,6 +423,62 @@ with evidence after `maxFixAttempts` as incomplete. Before reporting done, run the runtime audit for every confirmed URL at every required width (default 1440/1100/858/390), read the report, fix failures and rerun until every cell passes. Missing cells are not-run and block completion. At drawn widths require rendered completeness and page, section and asset visual comparisons. Check sequence-order and section-layout at every width. Ask known site, structure and URL decisions up front in one runtime question call, not per-section rounds. New user-owned decisions after confirm still use the question tool. Show evidence first; keep table approval separate from individual decisions in the same call. Use headers up to 30 characters and two to four options, recommended first and labelled "(Recommended)". Never ask for numbers in chat. Record the chosen answer, decision id, affected model/endpoint/file and rationale with existing defer/assume actions; do not invent an ask action. Update source models and re-confirm ERD changes before dependent work. Without a question tool, report the limitation and leave the decision unresolved. Workers escalate to the supervisor; continue independent work while answers are pending. +## 17. Verify states and requirements, report for review + +Use `devup_feature_trace` as the verification matrix. Static source reading and +browser observation are kept apart everywhere: a value read from source is +`static`, and static evidence never verifies rendered behaviour. + +- **Before implementing**, read `reuseCandidates` (existing components and + style patterns), `verification.changeImpact` (every screen that imports a + component you will change: `shared` means the change reaches all of them) and + `verification.configScope` (shared files such as `devup.json` or the root + layout versus screen-only files). Put a value only one screen needs in that + screen's files. +- **States.** Send one `stateChecks` row per state of a component or screen + (default, hover, active, focus, selected, disabled, ...): `target`, + `routePath`, `state`, the Figma `figmaNodeId` of that state (with + `artifactId` its size, position, colour, border and typography are read from + the snapshot; component-set variants become `expectedStates`), the measured + `implementation` values and `implementationSource` (`browser` when read from + computed style in a browser). Add `visual` (the `devup_visual_compare` input) + only when a pixel comparison is needed. A state without a design or a capture, + an expected state nobody checked, and a static-only state are `unverified`, + never a pass. Capture only to compare or to analyse a failure. +- **Requirements.** Send each design spec card (`origin: design-spec-card`) + and user requirement as `requirements` with its `targets` (route, component, + state, Figma node) and `check` kind. Verdicts are `verified`, `unverified` + or `not-applicable` with `reason`, `evidence` and `scope`. Interaction and + visual requirements need browser, automated-test or manual evidence; static + passes leave them `browser-verification-required`. A requirement reaching + several screens (`scope.multiScreen`, `sharedComponents`) needs evidence on + every screen in `scope.screens`. +- **Incomplete Figma data.** `verification.designData.gaps` lists each missing + node or property with its cause (from the artifact, plus `designGaps` you add + for failed reads or exports) and `cannotJudge` names the screens, states and + requirements it blocks. While `claims.designMatch` or + `claims.verificationComplete` is `blocked`, do not report a design match or + a finished verification. +- **Review report.** Pass `changes` (summary, route, files, requirementIds). + `reviewReport.changes` gives the user, per change, the path to open, the + steps, the expected result and the results split into automated, browser, + manual and static. Captures appear only for failed visual comparisons; write + a separate capture summary only when the user asks for one. +- **When a verification cannot be finished**, follow `followUp.order`: + 1. find the cause; fix what is inside the request's scope and verify again + (`followUp.fixInScope` carries the next action); + 2. finish other work that does not depend on it; + 3. only when a user permission or an external environment change is + required, ask once, briefly: the unfinished verification and the cause + found so far, the recommended fix and what it would verify, and the action + or permission needed (record it as `blocker` with `cause`, + `recommendation`, `verifies`, `userAction`; `followUp.askUser` names any + field still missing); + 4. keep doing unaffected work while waiting; + 5. report what cannot be resolved with the attempts made and the remaining + constraint (`blocker.kind: unresolvable` with `attempts`; listed in + `followUp.unresolved`). + ## After the work: /devup-retro When a piece of devup-mcp work is finished, `/devup-retro` (the `devup-retro` diff --git a/crates/devup-mcp/src/server/tools.rs b/crates/devup-mcp/src/server/tools.rs index 9381088c..c15c5ddd 100644 --- a/crates/devup-mcp/src/server/tools.rs +++ b/crates/devup-mcp/src/server/tools.rs @@ -611,4 +611,16 @@ pub struct FeatureTraceInput { /// Per-array response cap, default 100, maximum 200. Byte cap is 65536. #[schemars(range(min = 1, max = 200))] pub max_items: Option, + /// States (default/hover/active/focus/selected/disabled...) of components or screens, grouped by target and compared with Figma. + #[serde(default)] + pub state_checks: Vec, + /// Design spec cards and user requirements linked to screens, components and states. + #[serde(default)] + pub requirements: Vec, + /// Figma nodes or properties a read or export did not deliver, beyond those found in artifactId. + #[serde(default)] + pub design_gaps: Vec, + /// Changes to describe in the user review report. + #[serde(default)] + pub changes: Vec, } diff --git a/crates/devup-mcp/src/server/verification_matrix.rs b/crates/devup-mcp/src/server/verification_matrix.rs new file mode 100644 index 00000000..f6ab9196 --- /dev/null +++ b/crates/devup-mcp/src/server/verification_matrix.rs @@ -0,0 +1,16 @@ +//! Per-state and per-requirement verification matrix for `devup_feature_trace`. +//! +//! Pure verdict logic over caller evidence, the cached Figma snapshot and the +//! static UI inventory. It never launches a browser. Missing design, missing +//! capture, static-only evidence and incomplete Figma data are `unverified`, +//! never a pass, and they block design-match and completion claims. + +// Source sections share this module to preserve privacy and test names. +include!("verification_matrix/types.rs"); +include!("verification_matrix/style.rs"); +include!("verification_matrix/states_and_gaps.rs"); +include!("verification_matrix/requirements_and_report.rs"); + +#[cfg(test)] +#[path = "verification_matrix_tests.rs"] +mod tests; diff --git a/crates/devup-mcp/src/server/verification_matrix/requirements_and_report.rs b/crates/devup-mcp/src/server/verification_matrix/requirements_and_report.rs new file mode 100644 index 00000000..dc35b153 --- /dev/null +++ b/crates/devup-mcp/src/server/verification_matrix/requirements_and_report.rs @@ -0,0 +1,602 @@ +/// Routes that statically import a component, from the UI inventory. +fn component_routes(ui: &Value, path: &str) -> Option<(BTreeSet, usize)> { + let path = normalize_path(path); + let component = array(&ui["components"]) + .iter() + .find(|c| text(&c["path"]) == path)?; + let sites = array(&component["importedBy"]); + let routes = sites + .iter() + .flat_map(|site| { + array(&site["routes"]) + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + }) + .collect(); + Some((routes, sites.len())) +} + +fn looks_like_file(target: &str) -> bool { + target.contains('/') + || [".tsx", ".ts", ".jsx", ".js"] + .iter() + .any(|e| target.ends_with(e)) +} + +/// Who is affected when a component changes: every screen importing it. +fn change_impact(ctx: &MatrixContext<'_>, paths: &BTreeSet) -> Vec { + paths + .iter() + .map(|path| match component_routes(ctx.ui, path) { + Some((routes, sites)) => { + let scope = match routes.len() { + 0 if sites == 0 => "unreferenced", + 0 => "shared-layout-or-unrouted", + 1 if sites <= 1 => "screen-only", + _ => "shared", + }; + json!({"path":path,"scope":scope,"affectedScreens":routes,"importSites":sites, + "basis":"static import reachability; rendering on each screen is unverified until browser-checked", + "action":if scope == "shared" {"A change here applies to every affected screen: verify each of them, or make the change a screen-level prop/variant."} else {"A change here stays on its screen."}}) + } + None => json!({"path":path,"scope":"unknown","affectedScreens":[], + "basis":"Not in the bounded UI inventory; affected screens are unknown, not none."}), + }) + .collect() +} + +/// Shared configuration (applies to every screen) versus screen-only files. +fn config_scope(ctx: &MatrixContext<'_>) -> Value { + let mut owners = BTreeSet::from([String::new()]); + for route in array(&ctx.ui["routes"]) { + if let Some(owner) = route["appliesTo"].as_str().filter(|o| *o != ".") { + owners.insert(owner.to_owned()); + } + } + let mut shared = vec![]; + for owner in &owners { + let prefix = if owner.is_empty() { + String::new() + } else { + format!("{owner}/") + }; + for (file, kind) in [ + ("devup.json", "theme tokens"), + ("src/app/layout.tsx", "root layout"), + ("app/layout.tsx", "root layout"), + ("src/app/globals.css", "global styles"), + ("app/globals.css", "global styles"), + (".devup/screen-plan.config.json", "screen-plan config"), + ] { + let path = format!("{prefix}{file}"); + if ctx.root.join(&path).is_file() { + shared + .push(json!({"path":path,"kind":kind,"appliesTo":"every screen of this app"})); + } + } + } + let screen_only = array(&ctx.ui["routes"]) + .iter() + .map(|r| json!({"path":r["page"],"route":r["route"],"appliesTo":"this screen only"})) + .collect::>(); + json!({"shared":shared,"screenOnly":screen_only, + "rule":"Put a value that only one screen needs in that screen's files; change shared files only when every listed screen should change."}) +} + +fn evidence_row(e: &RequirementEvidence) -> Value { + json!({"source":e.source.as_str(),"status":e.status,"detail":e.detail,"routePath":e.route_path,"reference":e.reference}) +} + +/// Verdict for one requirement: verified, unverified or not-applicable, with its evidence and scope. +fn evaluate_requirement( + ctx: &MatrixContext<'_>, + requirement: &TracedRequirement, + states: &[Value], + gaps: &[Value], +) -> Value { + let mut routes = BTreeSet::new(); + let mut components = BTreeSet::new(); + let mut shared = vec![]; + let mut scope_notes = vec![]; + let mut target_states = vec![]; + for target in &requirement.targets { + if let Some(route) = present(&target.route_path) { + routes.insert(route.to_owned()); + } + if let Some(path) = present(&target.component_path) { + let path = normalize_path(path); + match component_routes(ctx.ui, &path) { + Some((found, _)) => { + if found.len() > 1 { + shared.push(json!({"component":path,"screens":found})); + } + routes.extend(found); + } + None => scope_notes.push(format!( + "{path} is not in the UI inventory; screens using it are unknown." + )), + } + components.insert(path); + } + if let Some(state) = present(&target.state) { + target_states.push((target.clone(), normalize_state(state))); + } + } + let nodes = requirement + .targets + .iter() + .filter_map(|t| present(&t.figma_node_id)) + .chain(present(&requirement.figma_node_id)) + .collect::>(); + let blocking_gaps = nodes + .iter() + .flat_map(|node| gaps_for(ctx.payload, gaps, node)) + .collect::>(); + // States linked by target (component path or screen) and state name. + let linked = states + .iter() + .filter(|s| { + target_states.iter().any(|(t, state)| { + text(&s["state"]) == state + && (present(&t.component_path).is_some_and(|p| normalize_path(p) == normalize_path(text(&s["target"]))) + || present(&t.route_path).is_some_and(|r| s["routePath"] == r) + || present(&t.figma_node_id).is_some_and(|n| s["figmaNodeId"] == n)) + }) + }) + .map(|s| json!({"target":s["target"],"routePath":s["routePath"],"figmaNodeId":s["figmaNodeId"],"state":s["state"],"verdict":s["verdict"],"source":s["implementationSource"],"visual":s["visual"]["verdict"]})) + .collect::>(); + let unlinked_states = target_states + .iter() + .filter(|(t, state)| { + !linked.iter().any(|l| { + l["state"] == state.as_str() + && (present(&t.component_path) + .is_some_and(|p| normalize_path(p) == normalize_path(text(&l["target"]))) + || present(&t.route_path).is_some_and(|r| l["routePath"] == r) + || present(&t.figma_node_id).is_some_and(|n| l["figmaNodeId"] == n)) + }) + }) + .map(|(_, s)| s.clone()) + .collect::>(); + let evidence = requirement + .evidence + .iter() + .map(evidence_row) + .collect::>(); + let failing = requirement + .evidence + .iter() + .any(|e| e.status == EvidenceStatus::Fail) + || linked.iter().any(|l| l["verdict"] == "failed"); + let accepted = |e: &&RequirementEvidence| { + e.status == EvidenceStatus::Pass + && match requirement.check { + RequirementCheck::Interaction | RequirementCheck::Visual => e.source.observed(), + _ => true, + } + }; + let passing = requirement + .evidence + .iter() + .filter(accepted) + .collect::>(); + let static_pass_only = requirement + .evidence + .iter() + .any(|e| e.status == EvidenceStatus::Pass && !e.source.observed()) + && passing.is_empty(); + let states_ok = !linked.is_empty() && linked.iter().all(|l| l["verdict"] == "verified"); + let proven = (!passing.is_empty() || states_ok) + && unlinked_states.is_empty() + && linked.iter().all(|l| l["verdict"] == "verified"); + // Every screen in scope needs its own evidence once the scope has several. + let covered = routes + .iter() + .filter(|route| { + routes.len() == 1 + || passing + .iter() + .any(|e| present(&e.route_path) == Some(route.as_str())) + || linked + .iter() + .any(|l| l["routePath"] == route.as_str() && l["verdict"] == "verified") + }) + .cloned() + .collect::>(); + let uncovered = routes.difference(&covered).cloned().collect::>(); + let needs_browser = matches!( + requirement.check, + RequirementCheck::Interaction | RequirementCheck::Visual + ) && passing.is_empty() + && !states_ok; + let (verdict, outcome, reason) = if let Some(reason) = + present(&requirement.not_applicable_reason) + { + ("not-applicable", "not-applicable", reason.to_owned()) + } else if requirement.targets.is_empty() && requirement.figma_node_id.is_none() { + ( + "unverified", + "unlinked", + "Not linked to any screen, component, state or design node.".to_owned(), + ) + } else if failing { + ( + "unverified", + "failed", + "Evidence or a linked state failed; fix it and verify again.".to_owned(), + ) + } else if !blocking_gaps.is_empty() { + ("unverified", "design-data-incomplete", "The linked Figma data is incomplete, so the requirement cannot be judged against the design.".to_owned()) + } else if needs_browser { + ("unverified", "browser-verification-required", if static_pass_only { + "Only static evidence was supplied; this user-visible behaviour needs browser or automated-test evidence." + } else { + "No observed evidence; this user-visible behaviour needs browser or automated-test evidence." + }.to_owned()) + } else if !proven { + ( + "unverified", + "missing-evidence", + if unlinked_states.is_empty() { + "No passing evidence was supplied.".to_owned() + } else { + format!( + "Linked states have no state check: {}.", + unlinked_states.join(", ") + ) + }, + ) + } else if !uncovered.is_empty() { + ( + "unverified", + "scope-not-covered", + format!( + "Evidence does not cover every screen in scope: {}.", + uncovered.join(", ") + ), + ) + } else { + ( + "verified", + "verified", + "Passing evidence covers every linked screen and state.".to_owned(), + ) + }; + json!({"id":requirement.id,"text":requirement.text,"origin":requirement.origin,"figmaNodeId":requirement.figma_node_id, + "check":requirement.check,"verdict":verdict,"outcome":outcome,"reason":reason, + "browserVerificationRequired":outcome == "browser-verification-required", + "scope":{"screens":routes,"components":components,"states":target_states.iter().map(|(_, s)| s).collect::>(), + "sharedComponents":shared,"multiScreen":routes.len() > 1,"uncoveredScreens":uncovered,"notes":scope_notes}, + "linkedStates":linked,"evidence":evidence,"designDataGaps":blocking_gaps, + "attempts":requirement.attempts,"blocker":requirement.blocker}) +} + +/// The usual way to put a control into a state, for a review step. +fn state_step(target: &str, state: &str) -> String { + match state { + "default" => format!("Look at {target} without interacting"), + "hover" => format!("Move the pointer over {target}"), + "active" => format!("Press and hold {target}"), + "focus" => format!("Press Tab until {target} has keyboard focus"), + "selected" => format!("Select {target}"), + "disabled" => format!("Bring {target} into its disabled condition"), + other => format!("Bring {target} into the {other} state"), + } +} + +/// One review entry per change: where to look, in what order, what to expect, +/// and the results separated by who produced them. +fn review_report(input: &MatrixInput<'_>, requirements: &[Value], states: &[Value]) -> Value { + let derived; + let changes = if input.changes.is_empty() { + derived = input + .requirements + .iter() + .map(|r| ReviewChange { + id: Some(r.id.clone()), + summary: r.text.clone(), + route_path: r.targets.iter().find_map(|t| t.route_path.clone()), + requirement_ids: vec![r.id.clone()], + ..ReviewChange::default() + }) + .collect::>(); + &derived + } else { + input.changes + }; + let entries = changes.iter().map(|change| { + let linked = requirements + .iter() + .filter(|r| change.requirement_ids.iter().any(|id| r["id"] == id.as_str())) + .collect::>(); + let route = present(&change.route_path).map(str::to_owned).or_else(|| { + linked.iter().find_map(|r| array(&r["scope"]["screens"]).first().and_then(Value::as_str).map(str::to_owned)) + }); + let mut steps = change.steps.clone(); + if steps.is_empty() { + if let Some(route) = &route { + steps.push(format!("Open {route}")); + } + for state in linked.iter().flat_map(|r| array(&r["linkedStates"])) { + steps.push(state_step(text(&state["target"]), text(&state["state"]))); + } + } + let expected = present(&change.expected).map(str::to_owned).unwrap_or_else(|| { + let texts = linked.iter().map(|r| text(&r["text"])).collect::>(); + if texts.is_empty() { change.summary.clone() } else { texts.join("; ") } + }); + let mut results = BTreeMap::<&str, Vec>::from([("automated", vec![]), ("browser", vec![]), ("manual", vec![]), ("static", vec![])]); + for requirement in &linked { + for e in array(&requirement["evidence"]) { + let bucket = match text(&e["source"]) { + "automated-test" => "automated", + "browser" => "browser", + "manual" => "manual", + _ => "static", + }; + results.get_mut(bucket).unwrap().push(json!({"requirement":requirement["id"],"status":e["status"],"detail":e["detail"],"reference":e["reference"]})); + } + for state in array(&requirement["linkedStates"]) { + let bucket = if state["source"] == "static" { "static" } else { "browser" }; + results.get_mut(bucket).unwrap().push(json!({"requirement":requirement["id"],"state":state["state"],"target":state["target"],"status":state["verdict"]})); + } + } + let captures = states + .iter() + .filter(|s| s["verdict"] == "failed" && s["capture"]["diffPath"].is_string()) + .filter(|s| linked.iter().any(|r| array(&r["linkedStates"]).iter().any(|l| l["state"] == s["state"] && l["target"] == s["target"]))) + .map(|s| json!({"state":s["state"],"target":s["target"],"diffPath":s["capture"]["diffPath"]})) + .collect::>(); + let verdict = if linked.iter().any(|r| r["verdict"] == "unverified") { + "unverified" + } else if !linked.is_empty() && linked.iter().all(|r| r["verdict"] == "not-applicable") { + "not-applicable" + } else if linked.is_empty() { + "unverified" + } else { + "verified" + }; + json!({"id":change.id,"summary":change.summary,"path":route,"files":change.files,"steps":steps,"expected":expected, + "verdict":verdict,"results":results,"captures":captures, + "missingReviewPath":route.is_none() && change.steps.is_empty()}) + }).collect::>(); + json!({"changes":entries, + "rules":["Give the user each change's path, steps and expected result; keep automated, browser, manual and static results apart.", + "Attach a capture only for a visual comparison or a failure analysis; write a separate capture summary only when asked."]}) +} + +const FOLLOW_UP_ORDER: &[&str] = &[ + "1. Find the cause; fix what is inside this request's scope and verify again.", + "2. Finish any other work that does not depend on the blocked item.", + "3. Only when a user permission or an external environment change is required: state the unfinished verification and its cause, the recommended fix and what it would verify, and the action or permission needed; ask once.", + "4. Keep doing unaffected work while waiting for the answer.", + "5. Report what cannot be resolved with the attempts made and the remaining constraint.", +]; + +/// Sort every unfinished item into the follow-up order. +fn follow_up(states: &[Value], requirements: &[Value], gaps: &[Value]) -> Value { + let mut fix = vec![]; + let mut ask = vec![]; + let mut unresolved = vec![]; + let items = states + .iter() + .filter(|s| s["verdict"] != "verified") + .map(|s| { + ( + format!("state {} {}", text(&s["target"]), text(&s["state"])), + s, + ) + }) + .chain( + requirements + .iter() + .filter(|r| r["verdict"] == "unverified") + .map(|r| (format!("requirement {}", text(&r["id"])), r)), + ); + for (item, row) in items { + let attempts = row["attempts"].clone(); + let blocker = &row["blocker"]; + match text(&blocker["kind"]) { + "permission" | "environment" | "external" => { + let missing = ["recommendation", "verifies", "userAction"] + .into_iter() + .filter(|k| blocker[*k].as_str().is_none_or(|s| s.trim().is_empty())) + .collect::>(); + ask.push(json!({"item":item,"kind":blocker["kind"],"cause":blocker["cause"],"recommendation":blocker["recommendation"], + "verifies":blocker["verifies"],"userAction":blocker["userAction"],"attempts":attempts,"incompleteRequest":missing})); + } + "unresolvable" => unresolved.push( + json!({"item":item,"attempts":attempts,"remainingConstraint":blocker["cause"]}), + ), + _ => { + let next = if row["designDataGaps"] + .as_array() + .is_some_and(|g| !g.is_empty()) + { + "Re-export the missing nodes with devup_figma_export (or devup_figma_measure for geometry), then rerun this trace." + } else if row["verdict"] == "failed" || row["outcome"] == "failed" { + "Fix the implementation in scope, then capture again and rerun this trace." + } else if row["browserVerificationRequired"] == true + || row["outcome"] == "browser-verification-required" + { + "Observe it in a browser (devup_runtime_audit plan/ingest, or computed styles of the rendered state) and rerun with implementationSource or evidence source browser." + } else { + "Supply the missing design reference or capture; if it cannot exist, record a blocker with its cause and recommendation." + }; + fix.push(json!({"item":item,"reason":row["reason"],"nextAction":next,"attempts":attempts})); + } + } + } + json!({"order":FOLLOW_UP_ORDER,"fixInScope":fix,"askUser":ask,"unresolved":unresolved, + "continueWhileWaiting":!ask.is_empty(),"designDataGapCount":gaps.len()}) +} + +/// Whether design-match and completion may be claimed, and why not. +fn claims(states: &[Value], requirements: &[Value], gaps: &[Value]) -> Value { + let mut design = vec![]; + if !gaps.is_empty() { + design.push(format!( + "{} Figma node/property gaps: incomplete design data cannot establish a design match.", + gaps.len() + )); + } + let open_states = states.iter().filter(|s| s["verdict"] != "verified").count(); + if open_states > 0 { + design.push(format!("{open_states} states are failed or unverified.")); + } + let mut complete = design.clone(); + let open_requirements = requirements + .iter() + .filter(|r| r["verdict"] == "unverified") + .count(); + if open_requirements > 0 { + complete.push(format!("{open_requirements} requirements are unverified.")); + } + let design_match = if states.is_empty() && gaps.is_empty() { + "not-evaluated" + } else if design.is_empty() { + "allowed" + } else { + "blocked" + }; + json!({"designMatch":design_match,"verificationComplete":if complete.is_empty() {"allowed"} else {"blocked"}, + "designMatchBlockedBy":design,"completionBlockedBy":complete}) +} + +/// The whole matrix, or `None` when the caller supplied none of its inputs. +pub(super) async fn build(ctx: &MatrixContext<'_>, input: &MatrixInput<'_>) -> Option { + if input.is_empty() { + return None; + } + let focus = input + .state_checks + .iter() + .filter_map(|c| present(&c.figma_node_id)) + .chain(input.requirements.iter().flat_map(|r| { + r.targets + .iter() + .filter_map(|t| present(&t.figma_node_id)) + .chain(present(&r.figma_node_id)) + })) + .map(str::to_owned) + .collect::>(); + let gaps = collect_gaps(ctx, input, &focus); + let groups = state_groups(ctx, input, &gaps).await; + let states = groups + .iter() + .flat_map(|g| array(&g["states"]).iter().cloned()) + .collect::>(); + let requirements = input + .requirements + .iter() + .map(|r| evaluate_requirement(ctx, r, &states, &gaps)) + .collect::>(); + let mut components = input + .state_checks + .iter() + .map(|c| c.target.as_str()) + .filter(|t| looks_like_file(t)) + .chain( + input + .requirements + .iter() + .flat_map(|r| r.targets.iter().filter_map(|t| present(&t.component_path))), + ) + .chain( + input + .changes + .iter() + .flat_map(|c| c.files.iter().map(String::as_str)) + .filter(|t| looks_like_file(t)), + ) + .map(normalize_path) + .collect::>(); + if let Some(path) = input.component_path.filter(|p| !p.trim().is_empty()) { + components.insert(normalize_path(path)); + } + let affected_by_gaps = gaps + .iter() + .map(|g| { + let node = text(&g["nodeId"]); + let hit = |n: &Value| { + n.as_str().is_some_and(|n| { + node == "*" + || within(ctx.payload, node, n) + || g["referencedBy"] + .as_str() + .is_some_and(|p| within(ctx.payload, p, n)) + }) + }; + let screens = states + .iter() + .filter(|s| hit(&s["figmaNodeId"])) + .filter_map(|s| s["routePath"].as_str()) + .chain( + requirements + .iter() + .filter(|r| { + hit(&r["figmaNodeId"]) + || array(&r["designDataGaps"]) + .iter() + .any(|x| x["nodeId"] == g["nodeId"]) + }) + .flat_map(|r| { + array(&r["scope"]["screens"]) + .iter() + .filter_map(Value::as_str) + }), + ) + .collect::>(); + let reqs = requirements + .iter() + .filter(|r| { + array(&r["designDataGaps"]) + .iter() + .any(|x| x["nodeId"] == g["nodeId"]) + }) + .map(|r| r["id"].clone()) + .collect::>(); + let state_rows = states + .iter() + .filter(|s| hit(&s["figmaNodeId"])) + .map(|s| json!({"target":s["target"],"state":s["state"]})) + .collect::>(); + let mut row = g.clone(); + row["cannotJudge"] = json!({"screens":screens,"requirements":reqs,"states":state_rows}); + row + }) + .collect::>(); + let static_results = states + .iter() + .filter(|s| s["implementationSource"] == "static") + .count() + + requirements + .iter() + .flat_map(|r| array(&r["evidence"])) + .filter(|e| e["source"] == "static") + .count(); + let observed_results = states + .iter() + .filter(|s| s["implementationSource"] != "static" && s["missing"] != true) + .count() + + requirements + .iter() + .flat_map(|r| array(&r["evidence"])) + .filter(|e| e["source"] != "static") + .count(); + let review = review_report(input, &requirements, &states); + Some(json!({ + "claims":claims(&states, &requirements, &gaps), + "stateGroups":groups, + "requirements":requirements, + "designData":{"complete":gaps.is_empty(),"gaps":affected_by_gaps, + "rule":"Never declare a design match or a finished verification from incomplete Figma data."}, + "changeImpact":change_impact(ctx, &components), + "configScope":config_scope(ctx), + "resultsBySource":{"static":static_results,"observed":observed_results, + "meaning":"static = read from source; observed = browser, automated test or manual. Static results never prove rendered behaviour."}, + "reviewReport":review, + "followUp":follow_up(&states, &requirements, &gaps), + })) +} diff --git a/crates/devup-mcp/src/server/verification_matrix/states_and_gaps.rs b/crates/devup-mcp/src/server/verification_matrix/states_and_gaps.rs new file mode 100644 index 00000000..daa4af55 --- /dev/null +++ b/crates/devup-mcp/src/server/verification_matrix/states_and_gaps.rs @@ -0,0 +1,322 @@ +const STATE_WORDS: &[&str] = &[ + "default", "hover", "active", "focus", "selected", "disabled", "error", "loading", "empty", +]; + +/// True when `node` is `ancestor` or lies inside it in the snapshot tree. +fn within(payload: Option<&CollectedPayload>, node: &str, ancestor: &str) -> bool { + if node == ancestor { + return true; + } + let Some(payload) = payload else { + return false; + }; + let mut current = node.to_owned(); + let mut seen = BTreeSet::new(); + while seen.insert(current.clone()) { + let Some(parent) = payload + .snapshot + .nodes + .get(¤t) + .and_then(|n| n.typed_view().string("parentId").map(str::to_owned)) + else { + return false; + }; + if parent == ancestor { + return true; + } + current = parent; + } + false +} + +/// The states a node's component set declares through its variants. +fn variant_states(payload: &CollectedPayload, node_id: &str) -> BTreeSet { + let nodes = &payload.snapshot.nodes; + let mut states = BTreeSet::new(); + let Some(node) = nodes.get(node_id) else { + return states; + }; + let view = node.typed_view(); + let master = if node.node_type == "INSTANCE" { + view.string("mainComponentId").and_then(|id| nodes.get(id)) + } else { + Some(node) + }; + let set = view + .string("mainComponentSetId") + .and_then(|id| nodes.get(id)) + .or_else(|| { + let parent = master?.typed_view().string("parentId")?; + nodes.get(parent) + }) + .filter(|set| set.node_type == "COMPONENT_SET"); + let Some(set) = set else { + return states; + }; + for child in set.typed_view().child_ids().filter_map(|id| nodes.get(id)) { + let Some(variants) = child + .typed_view() + .value("variantProperties") + .and_then(Value::as_object) + else { + continue; + }; + for (key, value) in variants { + let Some(value) = value.as_str() else { + continue; + }; + let key = key.to_ascii_lowercase(); + let state = normalize_state(value); + if key.contains("state") + || key.contains("status") + || key.contains("interaction") + || STATE_WORDS.contains(&state.as_str()) + { + states.insert(state); + } + } + } + states +} + +/// Every place the design data is incomplete: caller-declared gaps, failed +/// screens, error diagnostics, failed asset exports, unreadable fields and +/// children referenced but never collected under the nodes being verified. +fn collect_gaps( + ctx: &MatrixContext<'_>, + input: &MatrixInput<'_>, + focus: &BTreeSet, +) -> Vec { + let mut gaps = input + .design_gaps + .iter() + .map(|g| json!({"nodeId":g.node_id,"property":g.property,"kind":g.kind,"cause":g.cause,"source":"caller"})) + .collect::>(); + if let Some(reason) = &ctx.artifact_unavailable { + gaps.push(json!({"nodeId":"*","property":null,"kind":"read-failed","cause":reason,"source":"artifact"})); + } + let Some(payload) = ctx.payload else { + return gaps; + }; + for failure in &payload.failures { + gaps.push(json!({"nodeId":failure.node_id,"property":null,"kind":"read-failed", + "cause":format!("{:?}: {}", failure.error_code, failure.message),"retryable":failure.retryable,"source":"export"})); + } + for diagnostic in &payload.snapshot.diagnostics { + let severe = diagnostic.severity == Some(DiagnosticSeverity::Error) + || matches!( + diagnostic.fidelity_impact, + Some(FidelityImpact::Failed | FidelityImpact::Lossy) + ); + if let (true, Some(node)) = (severe, &diagnostic.node_id) { + let kind = if diagnostic.property.is_some() { + "missing-property" + } else { + "read-failed" + }; + gaps.push(json!({"nodeId":node,"property":diagnostic.property,"kind":kind, + "cause":format!("{}: {}", diagnostic.code, diagnostic.message),"source":"snapshot-diagnostic"})); + } + } + for asset in payload + .assets + .iter() + .filter(|a| a.status == devup_mcp_figma::AssetStatus::Failed) + { + gaps.push(json!({"nodeId":asset.node_id,"property":asset.field,"kind":"export-failed", + "cause":format!("{}{}", asset.error_code.as_deref().unwrap_or("asset export failed"), + asset.error_detail.as_deref().map(|d| format!(": {d}")).unwrap_or_default()),"source":"asset-export"})); + } + // Unreadable fields and missing children only matter under verified nodes. + let mut pending = focus.iter().cloned().collect::>(); + let mut seen = BTreeSet::new(); + while let Some(id) = pending.pop() { + if !seen.insert(id.clone()) || seen.len() > 5_000 { + continue; + } + let Some(node) = payload.snapshot.nodes.get(&id) else { + if !focus.contains(&id) { + continue; + } + gaps.push(json!({"nodeId":id,"property":null,"kind":"missing-node","cause":"The node is not in the cached snapshot (not collected, paginated out or failed to read).","source":"snapshot"})); + continue; + }; + for (field, reason) in &node.field_errors { + gaps.push( + json!({"nodeId":id,"property":field,"kind":"missing-property","cause":reason, + "affectedProperties":field_properties(field),"source":"snapshot"}), + ); + } + for child in node.typed_view().child_ids() { + if payload.snapshot.nodes.contains_key(child) { + pending.push(child.to_owned()); + } else { + gaps.push(json!({"nodeId":child,"property":null,"kind":"missing-node","referencedBy":id, + "cause":"Listed as a child but absent from the cached snapshot.","source":"snapshot"})); + } + } + } + gaps +} + +/// Gaps that make a node's comparison incomplete: on the node or inside it. +fn gaps_for(payload: Option<&CollectedPayload>, gaps: &[Value], node: &str) -> Vec { + gaps.iter() + .filter(|g| { + let id = text(&g["nodeId"]); + id == "*" + || within(payload, id, node) + || g["referencedBy"] + .as_str() + .is_some_and(|p| within(payload, p, node)) + }) + .map(|g| json!({"nodeId":g["nodeId"],"property":g["property"],"kind":g["kind"]})) + .collect() +} + +/// Evaluate one state check. Async only for the optional pixel comparison, +/// which goes through the existing devup_visual_compare path unchanged. +async fn evaluate_state(ctx: &MatrixContext<'_>, check: &StateCheck, gaps: &[Value]) -> Value { + let state = normalize_state(&check.state); + let mut design = BTreeMap::new(); + let mut design_gaps = vec![]; + let node = present(&check.figma_node_id); + if let (Some(node), Some(payload)) = (node, ctx.payload) { + design = design_from_snapshot(payload, node); + } + if let Some(node) = node { + design_gaps = gaps_for(ctx.payload, gaps, node); + } + if let Some(explicit) = &check.design { + design.extend(snapshot_props(explicit)); + } + let implementation = check + .implementation + .as_ref() + .map(snapshot_props) + .unwrap_or_default(); + let tolerance = check.tolerance_px.unwrap_or(0.5).clamp(0.0, 8.0); + let comparisons = compare_props(&design, &implementation, tolerance); + let visual = match (&check.visual, ctx.policy) { + (None, _) => None, + (Some(_), None) => Some( + json!({"verdict":"error","message":"Pixel comparison needs the server output policy; call through devup_feature_trace on a running server."}), + ), + (Some(visual), Some(policy)) => Some( + match super::visual_compare::compare(visual.clone(), policy, ctx.store).await { + Ok(result) => { + json!({"verdict":result["verdict"],"changedBounds":result["visual"]["changedBounds"], + "changedRatio":result["visual"]["changedRatio"],"environment":result["environment"]["status"], + "diffPath":result["diffPath"],"nextAction":result["nextAction"],"tool":"devup_visual_compare"}) + } + Err(error) => { + json!({"verdict":"error","message":error.to_string(),"tool":"devup_visual_compare"}) + } + }, + ), + }; + let mismatches = comparisons + .iter() + .filter(|c| c["status"] == "mismatch") + .count(); + let not_measured = comparisons + .iter() + .filter(|c| c["status"] == "not-measured") + .map(|c| c["property"].clone()) + .collect::>(); + let visual_verdict = visual.as_ref().map(|v| text(&v["verdict"]).to_owned()); + let has_design = !design.is_empty() || check.visual.is_some(); + let has_capture = !implementation.is_empty() || check.visual.is_some(); + let observed = check.implementation_source.observed(); + let static_only = !implementation.is_empty() && !observed; + let (verdict, reason) = if mismatches > 0 || visual_verdict.as_deref() == Some("fail") { + ( + "failed", + "The implementation differs from the design; fix it and verify again.", + ) + } else if !has_design { + ( + "unverified", + "No design for this state: no Figma node values, design values or visual reference were supplied.", + ) + } else if !has_capture { + ( + "unverified", + "No capture of this state: no implementation values or screenshot were supplied.", + ) + } else if !design_gaps.is_empty() { + ( + "unverified", + "The Figma data for this state is incomplete; a match on partial data is not a design match.", + ) + } else if !not_measured.is_empty() { + ( + "unverified", + "Some design properties were not measured on the implementation.", + ) + } else if visual_verdict.as_deref().is_some_and(|v| v != "pass") { + ( + "unverified", + "The pixel comparison was inconclusive or could not run.", + ) + } else if static_only { + ( + "unverified", + "Values were read from source only; the rendered state needs browser verification.", + ) + } else { + ( + "verified", + "Every design property matched an observed implementation value.", + ) + }; + let capture_needed = verdict == "failed" && check.visual.is_none(); + json!({"target":check.target,"routePath":check.route_path,"state":state,"declaredState":check.state, + "figmaNodeId":check.figma_node_id,"verdict":verdict,"reason":reason, + "implementationSource":check.implementation_source.as_str(), + "browserVerificationRequired":verdict != "failed" && static_only, + "comparisons":comparisons,"mismatchCount":mismatches,"notMeasured":not_measured, + "visual":visual,"designDataGaps":design_gaps, + "capture":{"needed":capture_needed,"diffPath":visual.as_ref().map(|v| v["diffPath"].clone()), + "rule":"Capture only for a visual comparison or to analyse a failure."}, + "attempts":check.attempts,"blocker":check.blocker}) +} + +/// Group states by component/screen and list expected states nobody checked. +async fn state_groups( + ctx: &MatrixContext<'_>, + input: &MatrixInput<'_>, + gaps: &[Value], +) -> Vec { + let mut groups = BTreeMap::<(String, Option), (Vec, BTreeSet)>::new(); + for check in input.state_checks { + let row = evaluate_state(ctx, check, gaps).await; + let key = ( + normalize_path(&check.target), + present(&check.route_path).map(str::to_owned), + ); + let entry = groups.entry(key).or_default(); + entry + .1 + .extend(check.expected_states.iter().map(|s| normalize_state(s))); + if let (Some(payload), Some(node)) = (ctx.payload, present(&check.figma_node_id)) { + entry.1.extend(variant_states(payload, node)); + } + entry.0.push(row); + } + groups + .into_iter() + .map(|((target, route), (mut states, expected))| { + let checked = states.iter().map(|s| text(&s["state"]).to_owned()).collect::>(); + for missing in expected.difference(&checked) { + states.push(json!({"target":target,"routePath":route,"state":missing,"verdict":"unverified", + "reason":"Expected state with no design comparison or capture supplied; it is not a pass.", + "missing":true,"browserVerificationRequired":false,"comparisons":[],"capture":{"needed":false}})); + } + let count = |v: &str| states.iter().filter(|s| s["verdict"] == v).count(); + json!({"target":target,"routePath":route,"expectedStates":expected, + "counts":{"verified":count("verified"),"failed":count("failed"),"unverified":count("unverified")}, + "states":states}) + }) + .collect() +} diff --git a/crates/devup-mcp/src/server/verification_matrix/style.rs b/crates/devup-mcp/src/server/verification_matrix/style.rs new file mode 100644 index 00000000..0f3e5dfe --- /dev/null +++ b/crates/devup-mcp/src/server/verification_matrix/style.rs @@ -0,0 +1,381 @@ +/// A compared property value: a length or number, or a colour/family string. +#[derive(Debug, Clone, PartialEq)] +enum Prop { + Num(f64), + Text(String), +} +impl Prop { + fn to_json(&self) -> Value { + match self { + Self::Num(n) => json!((n * 1000.0).round() / 1000.0), + Self::Text(s) => json!(s), + } + } +} + +/// Property name -> the category the requirement names it under. +const PROPERTIES: &[(&str, &str)] = &[ + ("width", "size"), + ("height", "size"), + ("x", "position"), + ("y", "position"), + ("color", "color"), + ("backgroundColor", "color"), + ("borderColor", "border"), + ("borderWidth", "border"), + ("borderRadius", "border"), + ("fontFamily", "typography"), + ("fontSize", "typography"), + ("fontWeight", "typography"), + ("lineHeight", "typography"), + ("letterSpacing", "typography"), +]; + +/// Snapshot fields that carry each property; a field error there is a gap. +const FIELD_PROPERTIES: &[(&str, &[&str])] = &[ + ("width", &["width"]), + ("height", &["height"]), + ("absoluteBoundingBox", &["x", "y"]), + ("fills", &["color", "backgroundColor"]), + ("strokes", &["borderColor", "borderWidth"]), + ("strokeWeight", &["borderWidth"]), + ("cornerRadius", &["borderRadius"]), + ("fontName", &["fontFamily", "fontWeight"]), + ("fontSize", &["fontSize"]), + ("fontWeight", &["fontWeight"]), + ("lineHeight", &["lineHeight"]), + ("letterSpacing", &["letterSpacing"]), + ( + "styledTextSegments", + &[ + "fontFamily", + "fontSize", + "fontWeight", + "lineHeight", + "letterSpacing", + "color", + ], + ), +]; + +fn category(property: &str) -> &'static str { + PROPERTIES + .iter() + .find(|(name, _)| *name == property) + .map(|(_, c)| *c) + .unwrap_or("other") +} + +/// The compared properties an unreadable snapshot field would have produced. +fn field_properties(field: &str) -> &'static [&'static str] { + FIELD_PROPERTIES + .iter() + .find(|(name, _)| *name == field) + .map(|(_, p)| *p) + .unwrap_or(&[]) +} + +fn snapshot_props(style: &StyleSnapshot) -> BTreeMap<&'static str, Prop> { + let mut props = BTreeMap::new(); + let numbers = [ + ("x", style.x), + ("y", style.y), + ("width", style.width), + ("height", style.height), + ("borderWidth", style.border_width), + ("borderRadius", style.border_radius), + ("fontSize", style.font_size), + ("fontWeight", style.font_weight), + ("lineHeight", style.line_height), + ("letterSpacing", style.letter_spacing), + ]; + for (name, value) in numbers { + if let Some(value) = value.filter(|v| v.is_finite()) { + props.insert(name, Prop::Num(value)); + } + } + let texts = [ + ("color", &style.color), + ("backgroundColor", &style.background_color), + ("borderColor", &style.border_color), + ("fontFamily", &style.font_family), + ]; + for (name, value) in texts { + if let Some(value) = present(value) { + props.insert(name, Prop::Text(value.to_owned())); + } + } + props +} + +/// The first visible solid paint as #rrggbbaa. +fn solid_paint(paints: Option<&Value>) -> Option { + let paint = array(paints?).iter().find(|p| p["visible"] != false)?; + if paint["type"] != "SOLID" { + return None; + } + let channel = |key: &str| paint["color"][key].as_f64(); + let alpha = + paint["color"]["a"].as_f64().unwrap_or(1.0) * paint["opacity"].as_f64().unwrap_or(1.0); + let byte = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Some(format!( + "#{:02x}{:02x}{:02x}{:02x}", + byte(channel("r")?), + byte(channel("g")?), + byte(channel("b")?), + byte(alpha) + )) +} + +/// A Figma length that is `12`, `{unit:"PIXELS",value:12}` or a percent of the font size. +fn figma_length(value: Option<&Value>, font_size: Option) -> Option { + let value = value?; + if let Some(n) = value.as_f64() { + return Some(n); + } + let amount = value["value"].as_f64()?; + match text(&value["unit"]) { + "PIXELS" => Some(amount), + "PERCENT" => font_size.map(|size| size * amount / 100.0), + _ => None, + } +} + +fn font_weight_from_style(style: &str) -> Option { + let style = style.to_ascii_lowercase().replace([' ', '-'], ""); + [ + ("thin", 100.0), + ("extralight", 200.0), + ("ultralight", 200.0), + ("light", 300.0), + ("regular", 400.0), + ("normal", 400.0), + ("medium", 500.0), + ("semibold", 600.0), + ("demibold", 600.0), + ("extrabold", 800.0), + ("ultrabold", 800.0), + ("bold", 700.0), + ("black", 900.0), + ("heavy", 900.0), + ] + .iter() + .find(|(name, _)| style.starts_with(name)) + .map(|(_, weight)| *weight) +} + +/// The design values of one node, read from the cached snapshot. Unreadable +/// fields and missing nodes are reported by `collect_gaps`. +fn design_from_snapshot(payload: &CollectedPayload, node_id: &str) -> BTreeMap<&'static str, Prop> { + let mut props = BTreeMap::new(); + let Some(node) = payload.snapshot.nodes.get(node_id) else { + return props; + }; + let view = node.typed_view(); + if let Some(width) = view.number("width") { + props.insert("width", Prop::Num(width)); + } + if let Some(height) = view.number("height") { + props.insert("height", Prop::Num(height)); + } + let origin = payload + .target + .node_id + .as_deref() + .filter(|origin| *origin != node_id) + .and_then(|origin| payload.snapshot.nodes.get(origin)) + .and_then(|n| n.typed_view().value("absoluteBoundingBox").cloned()); + if let (Some(origin), Some(own)) = (origin, view.value("absoluteBoundingBox")) + && let (Some(ox), Some(oy), Some(x), Some(y)) = ( + origin["x"].as_f64(), + origin["y"].as_f64(), + own["x"].as_f64(), + own["y"].as_f64(), + ) + { + props.insert("x", Prop::Num(x - ox)); + props.insert("y", Prop::Num(y - oy)); + } + let is_text = node.node_type == "TEXT"; + let segment = view + .value("styledTextSegments") + .and_then(|s| s.as_array()) + .and_then(|s| s.first()) + .cloned() + .unwrap_or(Value::Null); + let field = |name: &str| { + view.value(name) + .filter(|v| !v.is_null() && v.get("$error").is_none()) + .or_else(|| segment.get(name).filter(|v| !v.is_null())) + }; + if let Some(color) = solid_paint(field("fills")) { + props.insert( + if is_text { "color" } else { "backgroundColor" }, + Prop::Text(color), + ); + } + if let Some(color) = solid_paint(view.value("strokes")) { + props.insert("borderColor", Prop::Text(color)); + if let Some(weight) = view.number("strokeWeight") { + props.insert("borderWidth", Prop::Num(weight)); + } + } + if let Some(radius) = view.number("cornerRadius") { + props.insert("borderRadius", Prop::Num(radius)); + } + if is_text { + let font_size = field("fontSize").and_then(Value::as_f64); + if let Some(size) = font_size { + props.insert("fontSize", Prop::Num(size)); + } + if let Some(name) = field("fontName") { + if let Some(family) = name["family"].as_str() { + props.insert("fontFamily", Prop::Text(family.to_owned())); + } + if let Some(weight) = name["style"].as_str().and_then(font_weight_from_style) { + props.insert("fontWeight", Prop::Num(weight)); + } + } + if let Some(weight) = field("fontWeight").and_then(Value::as_f64) { + props.insert("fontWeight", Prop::Num(weight)); + } + if let Some(line) = figma_length(field("lineHeight"), font_size) { + props.insert("lineHeight", Prop::Num(line)); + } + if let Some(spacing) = figma_length(field("letterSpacing"), font_size) { + props.insert("letterSpacing", Prop::Num(spacing)); + } + } + props +} + +/// RGBA bytes from the colour spellings CSS computed style and Figma use. +fn parse_color(value: &str) -> Option<[u8; 4]> { + let value = value.trim().to_ascii_lowercase(); + if value == "transparent" { + return Some([0, 0, 0, 0]); + } + if let Some(hex) = value.strip_prefix('#') { + let digits = match hex.len() { + 3 | 4 => hex.chars().flat_map(|c| [c, c]).collect::(), + 6 | 8 => hex.to_owned(), + _ => return None, + }; + let byte = |i: usize| u8::from_str_radix(digits.get(i..i + 2)?, 16).ok(); + return Some([ + byte(0)?, + byte(2)?, + byte(4)?, + if digits.len() == 8 { byte(6)? } else { 255 }, + ]); + } + let inner = value + .strip_prefix("rgba(") + .or_else(|| value.strip_prefix("rgb("))? + .strip_suffix(')')?; + let parts = inner + .split([',', ' ', '/']) + .filter(|p| !p.is_empty()) + .collect::>(); + if !(3..=4).contains(&parts.len()) { + return None; + } + let channel = |p: &str| -> Option { + if let Some(percent) = p.strip_suffix('%') { + return Some( + (percent.parse::().ok()? / 100.0 * 255.0) + .round() + .clamp(0.0, 255.0) as u8, + ); + } + Some(p.parse::().ok()?.round().clamp(0.0, 255.0) as u8) + }; + let alpha = match parts.get(3) { + None => 255, + Some(p) => { + if let Some(percent) = p.strip_suffix('%') { + (percent.parse::().ok()? / 100.0 * 255.0) + .round() + .clamp(0.0, 255.0) as u8 + } else { + (p.parse::().ok()? * 255.0).round().clamp(0.0, 255.0) as u8 + } + } + }; + Some([ + channel(parts[0])?, + channel(parts[1])?, + channel(parts[2])?, + alpha, + ]) +} + +fn first_family(value: &str) -> String { + value + .split(',') + .next() + .unwrap_or("") + .trim() + .trim_matches(['"', '\'']) + .to_ascii_lowercase() +} + +/// Compare every design property with the implementation. A property the +/// implementation did not measure is `not-measured`, never a match. +fn compare_props( + design: &BTreeMap<&'static str, Prop>, + implementation: &BTreeMap<&'static str, Prop>, + tolerance: f64, +) -> Vec { + design + .iter() + .map(|(name, expected)| { + let mut row = + json!({"property":name,"category":category(name),"design":expected.to_json()}); + let Some(actual) = implementation.get(name) else { + row["status"] = json!("not-measured"); + return row; + }; + row["implementation"] = actual.to_json(); + let (matched, detail) = match (expected, actual) { + (Prop::Num(a), Prop::Num(b)) => { + let limit = if *name == "fontWeight" { + 0.0 + } else { + tolerance + }; + let delta = b - a; + row["delta"] = json!((delta * 1000.0).round() / 1000.0); + ( + delta.abs() <= limit + f64::EPSILON, + format!("tolerance {limit}px"), + ) + } + (Prop::Text(a), Prop::Text(b)) if *name == "fontFamily" => ( + first_family(a) == first_family(b), + "first family, case-insensitive".into(), + ), + (Prop::Text(a), Prop::Text(b)) => match (parse_color(a), parse_color(b)) { + (Some(x), Some(y)) => { + let max = x + .iter() + .zip(y) + .map(|(p, q)| p.abs_diff(q)) + .max() + .unwrap_or(0); + row["maxChannelDelta"] = json!(max); + (max <= 1, "RGBA channel delta up to 1".into()) + } + _ => ( + a.trim().eq_ignore_ascii_case(b.trim()), + "unparsed colour, literal comparison".into(), + ), + }, + _ => (false, "value types differ".into()), + }; + row["status"] = json!(if matched { "match" } else { "mismatch" }); + row["rule"] = json!(detail); + row + }) + .collect() +} diff --git a/crates/devup-mcp/src/server/verification_matrix/types.rs b/crates/devup-mcp/src/server/verification_matrix/types.rs new file mode 100644 index 00000000..694efff9 --- /dev/null +++ b/crates/devup-mcp/src/server/verification_matrix/types.rs @@ -0,0 +1,294 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use devup_mcp_figma::{CollectedPayload, DiagnosticSeverity, FidelityImpact}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use super::{artifacts::ArtifactStore, output::OutputPolicy, tools::VisualCompareInput}; + +/// Who observed a value or a result. Static source reading never proves what a +/// browser renders, so it is reported apart from browser observation. +#[derive( + Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, +)] +#[serde(rename_all = "kebab-case")] +pub enum EvidenceSource { + #[default] + Static, + Browser, + AutomatedTest, + Manual, +} +impl EvidenceSource { + fn as_str(self) -> &'static str { + match self { + Self::Static => "static", + Self::Browser => "browser", + Self::AutomatedTest => "automated-test", + Self::Manual => "manual", + } + } + fn observed(self) -> bool { + !matches!(self, Self::Static) + } +} + +/// Measured style values for one state. Lengths are CSS logical pixels +/// (Figma logical units); position is relative to the same origin on both +/// sides (the screen frame). Colours accept #rgb, #rrggbb, #rrggbbaa, rgb() and +/// rgba(). A property absent on either side is not compared. +#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = serde_json::json!({"not": {}})))] +pub struct StyleSnapshot { + pub x: Option, + pub y: Option, + pub width: Option, + pub height: Option, + pub color: Option, + pub background_color: Option, + pub border_color: Option, + pub border_width: Option, + pub border_radius: Option, + pub font_family: Option, + pub font_size: Option, + pub font_weight: Option, + pub line_height: Option, + pub letter_spacing: Option, +} + +/// Why a verification cannot be finished inside the current request. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum BlockerKind { + /// The user must grant an access or run something the agent may not. + Permission, + /// An external environment (server, credentials, device, data) must change. + Environment, + /// A design or decision owned by someone else is missing. + External, + /// Tried and cannot be resolved in this request. + Unresolvable, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = serde_json::json!({"not": {}})))] +pub struct VerificationBlocker { + pub kind: BlockerKind, + /// The cause found so far. + pub cause: String, + /// The recommended resolution. + pub recommendation: Option, + /// What the recommended resolution would let the agent verify. + pub verifies: Option, + /// The action or permission needed from the user. + pub user_action: Option, +} + +/// One state (default, hover, active, focus, selected, disabled, ...) of a +/// component or screen, with the Figma design and the implementation capture. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = serde_json::json!({"not": {}})))] +pub struct StateCheck { + /// Component file path or screen id the state belongs to; checks with the same target and routePath are grouped. + pub target: String, + pub route_path: Option, + pub state: String, + /// Figma node drawing this state. With artifactId its size, position, colour, border and typography are read from the cached snapshot. + pub figma_node_id: Option, + /// Design values; each overrides the value read from the snapshot. + pub design: Option, + /// Implementation values for this state. + pub implementation: Option, + /// Who measured `implementation`; default static (source reading). + #[serde(default)] + pub implementation_source: EvidenceSource, + /// Pixel comparison through devup_visual_compare (same input), only when a visual comparison is needed. + pub visual: Option, + /// Geometry and typography tolerance in CSS px, default 0.5. + #[schemars(range(min = 0.0, max = 8.0))] + pub tolerance_px: Option, + /// States this target must cover; missing ones are reported unverified. + #[serde(default)] + pub expected_states: Vec, + /// Fix or verification attempts already made, for the unresolved report. + #[serde(default)] + pub attempts: Vec, + pub blocker: Option, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum RequirementOrigin { + /// A design specification card in Figma. + DesignSpecCard, + #[default] + User, + AcceptanceCriteria, +} + +/// How a requirement can be proven. Interaction and visual requirements need +/// observed evidence; static source reading never proves them. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum RequirementCheck { + #[default] + Static, + Visual, + Interaction, + Data, + Content, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = serde_json::json!({"not": {}})))] +pub struct RequirementTarget { + pub route_path: Option, + pub component_path: Option, + pub state: Option, + pub figma_node_id: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum EvidenceStatus { + Pass, + Fail, + NotRun, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = serde_json::json!({"not": {}})))] +pub struct RequirementEvidence { + pub source: EvidenceSource, + pub status: EvidenceStatus, + pub detail: String, + /// The screen this evidence was observed on; required to cover each screen of a multi-screen requirement. + pub route_path: Option, + /// Test name, report path or diff path. + pub reference: Option, +} + +/// A design spec card or user requirement linked to screens, components and states. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = serde_json::json!({"not": {}})))] +pub struct TracedRequirement { + pub id: String, + pub text: String, + #[serde(default)] + pub origin: RequirementOrigin, + /// The spec card node when origin is design-spec-card. + pub figma_node_id: Option, + #[serde(default)] + pub targets: Vec, + #[serde(default)] + pub check: RequirementCheck, + /// Set only when the requirement does not apply; the reason is reported. + pub not_applicable_reason: Option, + #[serde(default)] + pub evidence: Vec, + #[serde(default)] + pub attempts: Vec, + pub blocker: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum DesignGapKind { + MissingNode, + MissingProperty, + ExportFailed, + ReadFailed, +} + +/// A Figma node or property a read or export did not deliver. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = serde_json::json!({"not": {}})))] +pub struct DesignGap { + pub node_id: String, + pub property: Option, + pub kind: DesignGapKind, + pub cause: String, +} + +/// One change to review, with the path the user follows to check it. +#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = serde_json::json!({"not": {}})))] +pub struct ReviewChange { + pub id: Option, + pub summary: String, + pub route_path: Option, + #[serde(default)] + pub files: Vec, + #[serde(default)] + pub steps: Vec, + pub expected: Option, + #[serde(default)] + pub requirement_ids: Vec, +} + +/// Everything the matrix reads besides the caller's own lists. +pub(super) struct MatrixContext<'a> { + pub ui: &'a Value, + pub root: &'a Path, + pub payload: Option<&'a CollectedPayload>, + /// The caller named an artifact that could not be read. + pub artifact_unavailable: Option, + pub policy: Option<&'a OutputPolicy>, + pub store: &'a ArtifactStore, +} + +pub(super) struct MatrixInput<'a> { + pub state_checks: &'a [StateCheck], + pub requirements: &'a [TracedRequirement], + pub design_gaps: &'a [DesignGap], + pub changes: &'a [ReviewChange], + pub component_path: Option<&'a str>, +} +impl MatrixInput<'_> { + pub(super) fn is_empty(&self) -> bool { + self.state_checks.is_empty() + && self.requirements.is_empty() + && self.design_gaps.is_empty() + && self.changes.is_empty() + } +} + +fn text(value: &Value) -> &str { + value.as_str().unwrap_or("") +} +fn array(value: &Value) -> &[Value] { + value.as_array().map(Vec::as_slice).unwrap_or(&[]) +} +fn present(value: &Option) -> Option<&str> { + value.as_deref().map(str::trim).filter(|s| !s.is_empty()) +} +fn normalize_path(path: &str) -> String { + path.trim() + .replace('\\', "/") + .trim_start_matches("./") + .to_owned() +} + +/// One spelling per state so `pressed` and `active` are one row. +pub(super) fn normalize_state(state: &str) -> String { + let state = state.trim().to_ascii_lowercase().replace([' ', '_'], "-"); + match state.as_str() { + "pressed" | "press" | "active" => "active".into(), + "hovered" | "hover" | "mouse-over" => "hover".into(), + "focused" | "focus" | "focus-visible" | "focusvisible" => "focus".into(), + "enabled" | "normal" | "rest" | "idle" | "default" | "base" => "default".into(), + "checked" | "selected" | "current" => "selected".into(), + "disabled" => "disabled".into(), + _ => state, + } +} diff --git a/crates/devup-mcp/src/server/verification_matrix_tests.rs b/crates/devup-mcp/src/server/verification_matrix_tests.rs new file mode 100644 index 00000000..da5d16ee --- /dev/null +++ b/crates/devup-mcp/src/server/verification_matrix_tests.rs @@ -0,0 +1,368 @@ +use super::*; +use crate::server::artifacts::w3_tests; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use sha2::Digest as _; + +const WHITE: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4////fwAJ+wP9KobjigAAAABJRU5ErkJggg=="; +const BLACK: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAX+XDSwAAAABJRU5ErkJggg=="; + +struct Dir(std::path::PathBuf); +impl Dir { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "verification-matrix-{}-{}", + std::process::id(), + rand::random::() + )); + std::fs::create_dir_all(&root).unwrap(); + Self(root) + } +} +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn node(value: Value) -> devup_mcp_figma::RawNode { + serde_json::from_value(value).unwrap() +} + +/// A screen frame holding a Button instance whose set declares +/// Default/Hover/Disabled variants, with a red 120x40 radius-8 fill. +fn payload() -> CollectedPayload { + let mut payload = w3_tests::payload(); + let nodes = &mut payload.snapshot.nodes; + nodes.insert("1:1".into(), node(json!({"id":"1:1","type":"FRAME","fields":{"name":"Screen","width":400,"height":300, + "absoluteBoundingBox":{"x":100,"y":100,"width":400,"height":300},"childrenIds":["2:1","2:9"]}}))); + nodes.insert("2:1".into(), node(json!({"id":"2:1","type":"INSTANCE","fields":{"name":"Button","parentId":"1:1", + "mainComponentId":"3:1","width":120,"height":40,"cornerRadius":8, + "absoluteBoundingBox":{"x":110,"y":120,"width":120,"height":40}, + "fills":[{"type":"SOLID","color":{"r":1,"g":0,"b":0}}],"childrenIds":[]}}))); + nodes.insert("3:0".into(), node(json!({"id":"3:0","type":"COMPONENT_SET","fields":{"name":"Button","childrenIds":["3:1","3:2","3:3"]}}))); + for (id, state) in [("3:1", "Default"), ("3:2", "Hover"), ("3:3", "Disabled")] { + nodes.insert(id.into(), node(json!({"id":id,"type":"COMPONENT","fields":{"parentId":"3:0","variantProperties":{"State":state}}}))); + } + nodes.insert("2:9".into(), node(json!({"id":"2:9","type":"TEXT","fields":{"name":"Title","parentId":"1:1","fontSize":20, + "fontName":{"family":"Inter","style":"Semi Bold"},"lineHeight":{"unit":"PIXELS","value":28}, + "fills":[{"type":"SOLID","color":{"r":0,"g":0,"b":0}}]}}))); + payload +} + +fn ui() -> Value { + json!({"routes":[{"route":"/a","page":"app/a/page.tsx","appliesTo":"."},{"route":"/b","page":"app/b/page.tsx","appliesTo":"."}], + "components":[ + {"path":"components/Button.tsx","importedBy":[{"path":"app/a/page.tsx","routes":["/a"]},{"path":"app/b/page.tsx","routes":["/b"]}]}, + {"path":"components/Hero.tsx","importedBy":[{"path":"app/a/page.tsx","routes":["/a"]}]}]}) +} + +struct Run { + dir: Dir, + ui: Value, + payload: Option, + unavailable: Option, + policy: Option, + store: ArtifactStore, +} +impl Run { + fn new() -> Self { + Self { dir: Dir::new(), ui: ui(), payload: Some(payload()), unavailable: None, policy: None, store: ArtifactStore::default() } + } + async fn matrix(&self, input: Value) -> Value { + let input: super::super::tools::FeatureTraceInput = serde_json::from_value(input).unwrap(); + let context = MatrixContext { + ui: &self.ui, + root: &self.dir.0, + payload: self.payload.as_ref(), + artifact_unavailable: self.unavailable.clone(), + policy: self.policy.as_ref(), + store: &self.store, + }; + let matrix = MatrixInput { + state_checks: &input.state_checks, + requirements: &input.requirements, + design_gaps: &input.design_gaps, + changes: &input.changes, + component_path: input.component_path.as_deref(), + }; + build(&context, &matrix).await.unwrap() + } +} + +fn button_values() -> Value { + json!({"x":10,"y":20,"width":120,"height":40,"backgroundColor":"rgb(255, 0, 0)","borderRadius":8}) +} +fn state<'a>(matrix: &'a Value, target: &str, state: &str) -> &'a Value { + array(&matrix["stateGroups"]) + .iter() + .flat_map(|g| array(&g["states"])) + .find(|s| s["target"] == target && s["state"] == state) + .unwrap_or_else(|| panic!("{target} {state}: {matrix}")) +} + +#[tokio::test] +async fn states_are_grouped_and_missing_or_static_states_are_never_a_pass() { + let run = Run::new(); + let m = run.matrix(json!({"stateChecks":[ + {"target":"components/Button.tsx","routePath":"/a","state":"Default","figmaNodeId":"2:1","implementation":button_values(),"implementationSource":"browser"}, + {"target":"components/Button.tsx","routePath":"/a","state":"hovered","figmaNodeId":"2:1","implementation":button_values()} + ]})).await; + let groups = array(&m["stateGroups"]); + assert_eq!(groups.len(), 1, "{m}"); + assert_eq!(groups[0]["expectedStates"], json!(["default", "disabled", "hover"])); + let default = state(&m, "components/Button.tsx", "default"); + assert_eq!(default["verdict"], "verified", "{default}"); + let categories = array(&default["comparisons"]).iter().map(|c| text(&c["category"])).collect::>(); + assert_eq!(categories, BTreeSet::from(["border", "color", "position", "size"])); + let hover = state(&m, "components/Button.tsx", "hover"); + assert_eq!(hover["verdict"], "unverified"); + assert_eq!(hover["browserVerificationRequired"], true); + let disabled = state(&m, "components/Button.tsx", "disabled"); + assert_eq!(disabled["verdict"], "unverified"); + assert_eq!(disabled["missing"], true); + assert_eq!(groups[0]["counts"], json!({"verified":1,"failed":0,"unverified":2})); + assert_eq!(m["claims"]["designMatch"], "blocked"); + assert_eq!(m["claims"]["verificationComplete"], "blocked"); +} + +#[tokio::test] +async fn mismatches_fail_with_property_deltas_and_ask_for_a_capture() { + let run = Run::new(); + let mut values = button_values(); + values["width"] = json!(121); + values["backgroundColor"] = json!("#00ff00"); + let m = run.matrix(json!({"stateChecks":[ + {"target":"Button","state":"default","figmaNodeId":"2:1","implementation":values,"implementationSource":"browser"}, + {"target":"Title","state":"default","figmaNodeId":"2:9","implementationSource":"browser", + "implementation":{"fontFamily":"\"Inter\", sans-serif","fontSize":20,"fontWeight":600,"lineHeight":28.4,"color":"#000"}} + ]})).await; + let button = state(&m, "Button", "default"); + assert_eq!(button["verdict"], "failed"); + assert_eq!(button["mismatchCount"], 2); + let width = array(&button["comparisons"]).iter().find(|c| c["property"] == "width").unwrap(); + assert_eq!(width["delta"], 1.0); + assert_eq!(button["capture"]["needed"], true); + let title = state(&m, "Title", "default"); + assert_eq!(title["verdict"], "verified", "{title}"); + assert!(array(&title["comparisons"]).iter().all(|c| c["category"] == "typography" || c["category"] == "color")); + // The failed default plus the hover and disabled variants nobody checked. + let items = array(&m["followUp"]["fixInScope"]).iter().map(|f| text(&f["item"]).to_owned()).collect::>(); + assert_eq!(items, ["state Button default", "state Button disabled", "state Button hover"]); +} + +#[tokio::test] +async fn a_state_without_design_or_capture_is_unverified() { + let run = Run::new(); + let m = run.matrix(json!({"stateChecks":[ + {"target":"Card","state":"selected","implementation":{"width":10},"implementationSource":"browser"}, + {"target":"Card","state":"focus","design":{"width":10}}, + {"target":"Card","state":"default","design":{"width":10,"height":5},"implementation":{"width":10},"implementationSource":"browser"} + ]})).await; + assert!(text(&state(&m, "Card", "selected")["reason"]).starts_with("No design")); + assert!(text(&state(&m, "Card", "focus")["reason"]).starts_with("No capture")); + let partial = state(&m, "Card", "default"); + assert_eq!(partial["verdict"], "unverified"); + assert_eq!(partial["notMeasured"], json!(["height"])); +} + +#[tokio::test] +async fn visual_comparisons_reuse_devup_visual_compare() { + let mut run = Run::new(); + std::fs::write(run.dir.0.join("ref.png"), STANDARD.decode(WHITE).unwrap()).unwrap(); + std::fs::write(run.dir.0.join("same.png"), STANDARD.decode(WHITE).unwrap()).unwrap(); + std::fs::write(run.dir.0.join("other.png"), STANDARD.decode(BLACK).unwrap()).unwrap(); + let reference = sha2::Sha256::digest(STANDARD.decode(WHITE).unwrap()).iter().map(|b| format!("{b:02x}")).collect::(); + let environment = json!({"schemaVersion":1,"tsxResource":{"uri":"devup://artifact/test/manifest","sha256":"a".repeat(64)}, + "referenceResource":{"uri":"file://ref.png","sha256":reference},"viewport":{"width":1,"height":1,"deviceScaleFactor":1}, + "captureContext":{"innerWidth":1,"innerHeight":1,"devicePixelRatio":1,"visualViewportScale":1,"rootCssZoom":1,"bodyCssZoom":1}, + "themePath":"devup.json","assetDirectory":"public","fontManifest":[{"family":"Test","sha256":"b".repeat(64)}], + "renderer":{"name":"playwright-chromium","version":"1"},"devupUiVersion":"1","actualPng":"other.png", + "environmentStatus":"valid","os":"test","locale":"en-US","timezone":"UTC"}); + let checks = json!({"stateChecks":[ + {"target":"Hero","state":"default","visual":{"actual":"other.png","reference":{"path":"ref.png"},"diffPath":"diff.png","environment":environment}}, + {"target":"Hero","state":"hover","visual":{"actual":"same.png","reference":{"path":"ref.png"}}} + ]}); + let without_policy = run.matrix(checks.clone()).await; + assert_eq!(state(&without_policy, "Hero", "default")["visual"]["verdict"], "error"); + assert_eq!(state(&without_policy, "Hero", "default")["verdict"], "unverified"); + run.policy = Some(OutputPolicy::from_roots(vec![run.dir.0.clone()]).unwrap()); + let m = run.matrix(checks).await; + let failed = state(&m, "Hero", "default"); + assert_eq!(failed["verdict"], "failed", "{failed}"); + assert_eq!(failed["visual"]["tool"], "devup_visual_compare"); + assert!(failed["capture"]["diffPath"].as_str().unwrap().ends_with("diff.png")); + assert_eq!(failed["capture"]["needed"], false); + // A page comparison without an environment manifest is inconclusive. + assert_eq!(state(&m, "Hero", "hover")["verdict"], "unverified"); +} + +#[tokio::test] +async fn requirements_link_scope_and_demand_observed_evidence() { + let run = Run::new(); + let m = run.matrix(json!({"requirements":[ + {"id":"R1","text":"Button shows hover colour","origin":"design-spec-card","figmaNodeId":"2:1","check":"interaction", + "targets":[{"componentPath":"./components/Button.tsx"}], + "evidence":[{"source":"static","status":"pass","detail":"_hover prop present"}]}, + {"id":"R2","text":"Print layout","notApplicableReason":"No print stylesheet in scope","targets":[{"routePath":"/a"}]}, + {"id":"R3","text":"Floating prose"}, + {"id":"R4","text":"Button label is bold","check":"content","targets":[{"componentPath":"components/Button.tsx"}], + "evidence":[{"source":"browser","status":"pass","detail":"bold on /a","routePath":"/a"}]}, + {"id":"R5","text":"Hero copy","check":"content","targets":[{"componentPath":"components/Hero.tsx"}], + "evidence":[{"source":"automated-test","status":"pass","detail":"hero.test.tsx"}]} + ]})).await; + let find = |id: &str| array(&m["requirements"]).iter().find(|r| r["id"] == id).unwrap().clone(); + let r1 = find("R1"); + assert_eq!(r1["verdict"], "unverified"); + assert_eq!(r1["outcome"], "browser-verification-required"); + assert_eq!(r1["scope"]["screens"], json!(["/a", "/b"])); + assert_eq!(r1["scope"]["multiScreen"], true); + assert_eq!(r1["scope"]["sharedComponents"][0]["component"], "components/Button.tsx"); + assert_eq!(find("R2")["verdict"], "not-applicable"); + assert_eq!(find("R3")["outcome"], "unlinked"); + let r4 = find("R4"); + assert_eq!(r4["outcome"], "scope-not-covered"); + assert_eq!(r4["scope"]["uncoveredScreens"], json!(["/b"])); + assert_eq!(find("R5")["verdict"], "verified"); + let impact = array(&m["changeImpact"]); + let scope = |path: &str| impact.iter().find(|i| i["path"] == path).unwrap()["scope"].clone(); + assert_eq!(scope("components/Button.tsx"), "shared"); + assert_eq!(scope("components/Hero.tsx"), "screen-only"); +} + +#[tokio::test] +async fn requirements_follow_their_linked_states() { + let run = Run::new(); + let m = run.matrix(json!({ + "stateChecks":[{"target":"components/Hero.tsx","routePath":"/a","state":"default","design":{"width":10},"implementation":{"width":10},"implementationSource":"browser"}], + "requirements":[ + {"id":"V1","text":"Hero matches","check":"visual","targets":[{"componentPath":"components/Hero.tsx","state":"default"}]}, + {"id":"V2","text":"Hero hover","check":"visual","targets":[{"componentPath":"components/Hero.tsx","state":"hover"}]}] + })).await; + let find = |id: &str| array(&m["requirements"]).iter().find(|r| r["id"] == id).unwrap().clone(); + assert_eq!(find("V1")["verdict"], "verified", "{m}"); + assert_eq!(find("V2")["verdict"], "unverified"); + assert_eq!(m["claims"]["designMatch"], "allowed"); + assert_eq!(m["claims"]["verificationComplete"], "blocked"); +} + +#[tokio::test] +async fn incomplete_figma_data_names_gaps_and_what_cannot_be_judged() { + let mut run = Run::new(); + let mut payload = payload(); + payload.snapshot.nodes.get_mut("2:1").unwrap().field_errors.insert("fills".into(), "fills could not be read".into()); + payload.snapshot.nodes.get_mut("1:1").unwrap().fields.insert("childrenIds".into(), json!(["2:1", "2:9", "9:9"])); + payload.failures.push(devup_mcp_figma::ScreenFailure { + node_id: "8:8".into(), + error_code: devup_mcp_figma::ErrorCode::DevupInvalidInput, + message: "timed out".into(), + retryable: true, + }); + run.payload = Some(payload); + let m = run.matrix(json!({ + "stateChecks":[{"target":"components/Button.tsx","routePath":"/a","state":"default","figmaNodeId":"2:1","implementation":button_values(),"implementationSource":"browser"}], + "requirements":[{"id":"S1","text":"Screen matches","check":"visual","figmaNodeId":"1:1","targets":[{"routePath":"/a"}], + "evidence":[{"source":"browser","status":"pass","detail":"looked right"}]}], + "designGaps":[{"nodeId":"7:7","kind":"export-failed","cause":"image render refused"}] + })).await; + let gaps = array(&m["designData"]["gaps"]); + assert_eq!(m["designData"]["complete"], false); + let kinds = gaps.iter().map(|g| (text(&g["nodeId"]), text(&g["kind"]))).collect::>(); + for expected in [("2:1", "missing-property"), ("9:9", "missing-node"), ("8:8", "read-failed"), ("7:7", "export-failed")] { + assert!(kinds.contains(&expected), "{expected:?}: {gaps:?}"); + } + let fills = gaps.iter().find(|g| g["nodeId"] == "2:1").unwrap(); + assert_eq!(fills["cause"], "fills could not be read"); + assert_eq!(fills["cannotJudge"]["screens"], json!(["/a"])); + assert_eq!(state(&m, "components/Button.tsx", "default")["verdict"], "unverified"); + let s1 = &m["requirements"][0]; + assert_eq!(s1["outcome"], "design-data-incomplete", "{s1}"); + assert_eq!(m["claims"]["designMatch"], "blocked"); + assert!(array(&m["followUp"]["fixInScope"]).iter().any(|f| text(&f["nextAction"]).contains("devup_figma_export"))); +} + +#[tokio::test] +async fn an_unreadable_artifact_blocks_every_design_comparison() { + let mut run = Run::new(); + run.payload = None; + run.unavailable = Some("artifactId is missing or expired".into()); + let m = run.matrix(json!({"stateChecks":[{"target":"Button","state":"default","figmaNodeId":"2:1","design":{"width":1},"implementation":{"width":1},"implementationSource":"browser"}]})).await; + assert_eq!(state(&m, "Button", "default")["verdict"], "unverified"); + assert_eq!(m["designData"]["gaps"][0]["nodeId"], "*"); +} + +#[tokio::test] +async fn review_report_gives_path_steps_expectation_and_separate_results() { + let run = Run::new(); + let m = run.matrix(json!({ + "stateChecks":[{"target":"components/Button.tsx","routePath":"/a","state":"hover","design":{"width":1},"implementation":{"width":1},"implementationSource":"browser"}], + "requirements":[{"id":"R1","text":"Hover darkens the button","check":"interaction", + "targets":[{"routePath":"/a","componentPath":"components/Button.tsx","state":"hover"}], + "evidence":[{"source":"automated-test","status":"pass","detail":"button.spec","routePath":"/a"}, + {"source":"manual","status":"pass","detail":"checked by hand","routePath":"/b"}]}], + "changes":[{"summary":"Button hover colour","requirementIds":["R1"],"files":["components/Button.tsx"]}] + })).await; + let change = &m["reviewReport"]["changes"][0]; + assert_eq!(change["path"], "/a"); + assert_eq!(change["steps"], json!(["Open /a", "Move the pointer over components/Button.tsx"])); + assert_eq!(change["expected"], "Hover darkens the button"); + assert_eq!(array(&change["results"]["automated"]).len(), 1); + assert_eq!(array(&change["results"]["manual"]).len(), 1); + assert_eq!(array(&change["results"]["browser"]).len(), 1); + assert_eq!(change["captures"], json!([])); + assert_eq!(change["verdict"], "verified", "{m}"); + assert_eq!(m["resultsBySource"]["static"], 0); +} + +#[tokio::test] +async fn follow_up_orders_fixes_questions_and_unresolved_items() { + let run = Run::new(); + let m = run.matrix(json!({"requirements":[ + {"id":"P","text":"Login flow","check":"interaction","targets":[{"routePath":"/a"}], + "blocker":{"kind":"permission","cause":"Staging needs a test account","recommendation":"Provide a test account"}}, + {"id":"U","text":"Safari rendering","check":"visual","targets":[{"routePath":"/a"}],"attempts":["Tried WebKit in Playwright"], + "blocker":{"kind":"unresolvable","cause":"No macOS runner available"}}, + {"id":"F","text":"Fails","check":"static","targets":[{"routePath":"/a"}],"evidence":[{"source":"static","status":"fail","detail":"lint error"}]} + ]})).await; + let follow = &m["followUp"]; + assert_eq!(array(&follow["order"]).len(), 5); + assert_eq!(follow["askUser"][0]["incompleteRequest"], json!(["verifies", "userAction"])); + assert_eq!(follow["continueWhileWaiting"], true); + assert_eq!(follow["unresolved"][0]["attempts"], json!(["Tried WebKit in Playwright"])); + assert_eq!(follow["unresolved"][0]["remainingConstraint"], "No macOS runner available"); + assert!(text(&follow["fixInScope"][0]["nextAction"]).starts_with("Fix the implementation")); +} + +#[tokio::test] +async fn config_scope_separates_shared_files_from_screen_files() { + let run = Run::new(); + std::fs::write(run.dir.0.join("devup.json"), "{}").unwrap(); + let m = run.matrix(json!({"changes":[{"summary":"x","files":["components/Unknown.tsx"]}]})).await; + assert_eq!(m["configScope"]["shared"][0]["path"], "devup.json"); + assert_eq!(array(&m["configScope"]["screenOnly"]).len(), 2); + assert_eq!(m["changeImpact"][0]["scope"], "unknown"); + assert_eq!(m["reviewReport"]["changes"][0]["missingReviewPath"], true); +} + +#[test] +fn colours_and_states_normalise() { + assert_eq!(parse_color("#f00"), Some([255, 0, 0, 255])); + assert_eq!(parse_color("rgba(255, 0, 0, 0.5)"), Some([255, 0, 0, 128])); + assert_eq!(parse_color("rgb(255 0 0 / 50%)"), Some([255, 0, 0, 128])); + assert_eq!(normalize_state("Pressed"), "active"); + assert_eq!(normalize_state("focus-visible"), "focus"); + assert_eq!(normalize_state("Checked"), "selected"); + assert_eq!(font_weight_from_style("Semi Bold"), Some(600.0)); +} + +#[tokio::test] +async fn a_figma_state_target_without_a_state_check_is_not_linked() { + let run = Run::new(); + let m = run.matrix(json!({ + "stateChecks":[{"target":"Other","state":"hover","figmaNodeId":"2:9","design":{"width":1},"implementation":{"width":1},"implementationSource":"browser"}], + "requirements":[{"id":"N","text":"Button hover","check":"static","targets":[{"figmaNodeId":"2:1","state":"hover"}], + "evidence":[{"source":"static","status":"pass","detail":"prop present"}]}] + })).await; + let requirement = &m["requirements"][0]; + assert_eq!(requirement["outcome"], "missing-evidence", "{requirement}"); + assert_eq!(requirement["linkedStates"], json!([])); +} From aee1b21dab2cb9590b03fd23965bbb2289d53435 Mon Sep 17 00:00:00 2001 From: leader Date: Sun, 29 Nov 2026 00:40:09 +0900 Subject: [PATCH 2/3] Encode request-shaped UI motion criteria as checks Sequential entrances, animation units, order and direction, dropdown and accordion behaviour, once-per-visit entrances, emphasis loops and reduced motion switched on mid-use become guide rules, developmentContract identifiers, devup_ui_validate rules and devup_runtime_audit checks (reveal sequence/unit/order/direction, reduced-motion-toggle, and a new disclosure motion kind). The shared motion controller now settles marked groups when reduced motion is switched on while the page is open. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_YpvjxS4lM2N45tl-Cz0qN.json | 7 + .../src/ui_validate/motion_contract.rs | 308 ++++++++++++++++++ .../src/ui_validate/motion_contract_tests.rs | 110 +++++++ .../src/ui_validate/motion_keyframes.rs | 59 +++- .../src/ui_validate/motion_quality.rs | 38 ++- .../src/server/behavior_contracts/detect.rs | 2 +- .../behavior_contracts/motion_templates.rs | 2 +- .../behavior_contracts/templates/Reveal.tsx | 15 +- .../templates/motion-runtime.ts | 12 +- .../src/server/behavior_contracts/tests.rs | 9 + .../src/server/development_contract.rs | 26 +- .../server/runtime_audit/motion_evidence.rs | 30 +- .../server/runtime_audit/motion_validation.rs | 91 +++++- .../src/server/runtime_audit/tests.rs | 2 +- .../src/server/runtime_audit/write_plan.rs | 2 + .../devfive-frontend/references/animation.md | 113 ++++++- .../references/delivery-quality.md | 7 +- .../skills/devup-implementation-plan/SKILL.md | 13 + .../devup-mcp/src/server/skills/manifest.json | 12 +- .../src/server/text/devup-runtime-audit.md | 2 +- .../src/server/text/devup-ui-validate.md | 2 +- .../devup-mcp/tests/export_project_theme.rs | 4 +- crates/devup-mcp/tests/runtime_audit_tool.rs | 2 +- harness/runtime-audit/disclosure-checks.mjs | 111 +++++++ harness/runtime-audit/motion-checks.mjs | 5 +- harness/runtime-audit/reveal-checks.mjs | 61 +++- harness/runtime-audit/sequence-checks.mjs | 174 ++++++++++ .../test/keyframes-motion.test.mjs | 5 +- .../test/motion-contract.test.mjs | 156 +++++++++ harness/runtime-audit/test/reveal.test.mjs | 8 +- harness/runtime-audit/test/sequence.test.mjs | 107 ++++++ 31 files changed, 1438 insertions(+), 57 deletions(-) create mode 100644 .changepacks/changepack_log_YpvjxS4lM2N45tl-Cz0qN.json create mode 100644 crates/devup-mcp-devup-ui/src/ui_validate/motion_contract.rs create mode 100644 crates/devup-mcp-devup-ui/src/ui_validate/motion_contract_tests.rs create mode 100644 harness/runtime-audit/disclosure-checks.mjs create mode 100644 harness/runtime-audit/sequence-checks.mjs create mode 100644 harness/runtime-audit/test/motion-contract.test.mjs create mode 100644 harness/runtime-audit/test/sequence.test.mjs diff --git a/.changepacks/changepack_log_YpvjxS4lM2N45tl-Cz0qN.json b/.changepacks/changepack_log_YpvjxS4lM2N45tl-Cz0qN.json new file mode 100644 index 00000000..1a28c7f2 --- /dev/null +++ b/.changepacks/changepack_log_YpvjxS4lM2N45tl-Cz0qN.json @@ -0,0 +1,7 @@ +{ + "changes": { + "Cargo.toml": "Minor" + }, + "note": "Encode request-shaped UI motion criteria: sequential entrances, units, order and direction, disclosures, once-per-visit entrances, emphasis loops and reduced motion switched on mid-use, as guide rules, contract identifiers, ui_validate rules and runtime audit checks", + "date": "2026-11-28T15:33:47.462000Z" +} \ No newline at end of file diff --git a/crates/devup-mcp-devup-ui/src/ui_validate/motion_contract.rs b/crates/devup-mcp-devup-ui/src/ui_validate/motion_contract.rs new file mode 100644 index 00000000..1d769f4f --- /dev/null +++ b/crates/devup-mcp-devup-ui/src/ui_validate/motion_contract.rs @@ -0,0 +1,308 @@ +//! Motion shapes a request fixes, proven from the source. +//! +//! The request itself is not visible here, so a sequential entrance is read +//! from the marker the implementation carries for it: +//! `data-reveal-sequence="sequential"` on the group (or ``, or a selector keyed on that attribute). Inside such +//! a group each unit must finish before the next starts. +//! +//! - `sequence-overlaps`: an item of a sequential group waits less per index +//! than its own animation lasts (`animationDelay: calc(var(--i) * 60ms)` +//! with `animationDuration: 400ms`, or `delay: i * 0.06` with +//! `duration: 0.4`), so items overlap where the request asked for one after +//! another. The short-stagger bound (`stagger-too-long`) does not apply +//! inside such a group: a step as long as the item is what it asks for. +//! - `sequence-animates-container`: the sequential group itself carries the +//! entrance, so every item moves at once with its parent. +//! - `disclosure-collapsed-focusable`: a panel collapsed by height +//! (`h`/`maxH`/`gridTemplateRows` switched to `0`) keeps focusable content +//! with nothing (`inert`, `hidden`, `visibility`, `display`) taking it out +//! of the tab order, so keyboard focus lands inside a closed panel. +//! - `disclosure-fixed-max-height`: the panel opens to a fixed `maxHeight` +//! rather than its content height, so the timing is wrong for short content +//! and long content is cut off. +//! - `disclosure-unmounts-form` (info): a panel with form fields renders only +//! while open (`open && <…>`), so collapsing it discards what +//! was typed. +//! +//! The same pass records the first animation that repeats forever (an +//! emphasis loop): reduced motion must stop it as it stops an entrance. +use super::keyframes::{Bag, Declared}; +use super::{Severity, Violation, attribute, expression, property, site, string}; +use oxc_ast::ast::*; +use oxc_ast_visit::{Visit, walk}; +use oxc_span::Span; + +const HEIGHT_PROPS: &[&str] = &["h", "height", "maxH", "maxHeight", "gridTemplateRows"]; +/// Present at all, these take content out of the tab order. +const HIDING_PROPS: &[&str] = &["inert", "hidden"]; +/// These do when they switch with the state (`visibility={open ? … : 'hidden'}`). +const SWITCHED_PROPS: &[&str] = &["visibility", "display"]; +const SEQUENTIAL_SELECTORS: &[&str] = &["data-reveal-sequence=\"sequential\"", "data-reveal-sequence='sequential'"]; + +#[derive(Default)] +pub(super) struct Contract { + pub findings: Vec, + /// Source ranges of sequential groups: a long stagger there is asked for. + pub sequential: Vec, + pub first_repeat: Option, +} + +impl Contract { + pub(super) fn in_sequence(&self, span: Span) -> bool { + self.sequential.iter().any(|group| group.start <= span.start && span.end <= group.end) + } +} + +pub(super) fn collect(program: &Program<'_>, source: &str, declared: &Declared) -> Contract { + let mut visitor = Visitor { source, declared, contract: Contract::default(), depth: 0 }; + visitor.visit_program(program); + visitor.contract +} + +struct Visitor<'s, 'd> { + source: &'s str, + declared: &'d Declared, + contract: Contract, + /// Depth inside sequential groups. + depth: usize, +} + +fn marks_sequence(node: &JSXOpeningElement<'_>) -> bool { + let named = |name: &str| attribute(node, name).and_then(string) == Some("sequential"); + named("data-reveal-sequence") + || (named("sequence") && node.name.get_identifier_name().is_some_and(|name| name.ends_with("Group"))) +} + +fn zero_like(expression: &Expression<'_>) -> bool { + match expression.get_inner_expression() { + Expression::NumericLiteral(number) => number.value == 0.0, + Expression::StringLiteral(text) => matches!(text.value.trim(), "0" | "0px" | "0fr" | "0%" | "0rem"), + _ => false, + } +} + +/// A fixed length: `600`, `'1000px'`, `'40rem'`, `'100vh'`. +fn fixed_length(expression: &Expression<'_>) -> bool { + match expression.get_inner_expression() { + Expression::NumericLiteral(number) => number.value > 0.0, + Expression::StringLiteral(text) => { + let text = text.value.trim(); + ["px", "rem", "em", "vh"].iter().any(|unit| { + text.strip_suffix(unit).is_some_and(|number| number.parse::().is_ok_and(|value| value > 0.0)) + }) + } + _ => false, + } +} + +/// `delay: i * 0.06` (either order): the per-item step, in seconds. +fn framer_step(object: &ObjectExpression<'_>) -> Option<(Span, f64)> { + let delay = object.properties.iter().find_map(|item| match item { + ObjectPropertyKind::ObjectProperty(entry) if entry.key.static_name().is_some_and(|key| key == "delay") => Some(&**entry), + _ => None, + })?; + let Expression::BinaryExpression(binary) = delay.value.get_inner_expression() else { + return None; + }; + if binary.operator != BinaryOperator::Multiplication { + return None; + } + match (binary.left.get_inner_expression(), binary.right.get_inner_expression()) { + (Expression::NumericLiteral(number), other) | (other, Expression::NumericLiteral(number)) + if !matches!(other, Expression::NumericLiteral(_)) => + { + Some((delay.span, number.value)) + } + _ => None, + } +} + +/// What a subtree holds that matters to a collapsed panel. +#[derive(Default)] +struct Holds { + focusable: bool, + field: bool, +} + +impl<'a> Visit<'a> for Holds { + fn visit_jsx_opening_element(&mut self, node: &JSXOpeningElement<'a>) { + let name = node.name.get_identifier_name().map(|name| name.to_string()).unwrap_or_default(); + let field = matches!(name.as_str(), "input" | "textarea" | "select") + || ["Input", "Textarea", "TextArea", "Select", "Field", "Checkbox", "Radio"].iter().any(|part| name.contains(part)); + let control = matches!(name.as_str(), "button" | "summary") + || ["Button", "Link", "Switch"].iter().any(|part| name.contains(part)) + || attribute(node, "href").is_some() + || attribute(node, "tabIndex").is_some_and(|tab| string(tab) != Some("-1") && !expression(tab).is_some_and(|value| matches!(value, Expression::UnaryExpression(_)))); + self.field |= field; + self.focusable |= field || control; + walk::walk_jsx_opening_element(self, node); + } +} + +fn holds(children: &oxc_allocator::Vec<'_, JSXChild<'_>>) -> Holds { + let mut found = Holds::default(); + for child in children { + found.visit_jsx_child(child); + } + found +} + +/// Whether the element, or its only element child, takes the collapsed +/// content out of the tab order. +fn hides_collapsed(element: &JSXElement<'_>) -> bool { + let own = |node: &JSXOpeningElement<'_>| { + HIDING_PROPS.iter().any(|name| attribute(node, name).is_some()) + || SWITCHED_PROPS.iter().any(|name| matches!(attribute(node, name).and_then(expression), Some(Expression::ConditionalExpression(_)))) + || node.attributes.iter().any(|item| matches!(item, JSXAttributeItem::SpreadAttribute(_))) + }; + if own(&element.opening_element) { + return true; + } + let mut children = element.children.iter().filter_map(|child| match child { + JSXChild::Element(inner) => Some(inner), + _ => None, + }); + matches!((children.next(), children.next()), (Some(only), None) if own(&only.opening_element)) +} + +/// A condition named as a disclosure state: `open`, `isOpen`, `expanded`… +fn disclosure_condition(expression: &Expression<'_>) -> bool { + let name = match expression.get_inner_expression() { + Expression::Identifier(name) => name.name.as_str(), + Expression::StaticMemberExpression(member) => member.property.name.as_str(), + _ => return false, + } + .to_ascii_lowercase(); + name.ends_with("open") || name.ends_with("expanded") || matches!(name.as_str(), "show" | "shown" | "isshown") +} + +fn overlay(element: &JSXElement<'_>) -> bool { + element.opening_element.name.get_identifier_name().is_some_and(|name| { + ["Modal", "Dialog", "Drawer", "Sheet", "Toast", "Tooltip"].iter().any(|part| name.contains(part)) || name == "dialog" + }) +} + +impl Visitor<'_, '_> { + fn report(&mut self, span: Span, rule: &'static str, severity: Severity, message: String, help: &'static str) { + self.contract.findings.push(site::violation(self.source, span, rule, severity, message, help)); + } + + fn overlaps(&mut self, span: Span, step: f64, duration: f64) { + if self.depth == 0 || step + 1e-9 >= duration { + return; + } + self.report(span, "sequence-overlaps", Severity::Warning, + format!("This sequential group starts each item {}ms after the previous one, while each item animates for {}ms, so items overlap.", (step * 1000.0).round(), (duration * 1000.0).round()), + "For a sequential entrance, start each unit when the previous one has finished: make the per-index delay at least the item's duration (for example calc(var(--reveal-index) * (400ms + var(--reveal-gap, 0ms)))), and shorten duration or gap if the whole sequence runs long. Overlap only when the request explicitly asks for it, and then drop the sequential marker."); + } + + fn check_bag(&mut self, bag: &Bag<'_, '_>) { + if let Some(span) = bag.loop_span(self.declared) { + self.contract.first_repeat.get_or_insert(span); + } + if let (Some((span, step)), Some(duration)) = (bag.stagger_step(), bag.duration_seconds()) { + self.overlaps(span, step, duration); + } + } + + fn check_disclosure(&mut self, element: &JSXElement<'_>) { + let node = &element.opening_element; + for name in HEIGHT_PROPS { + let Some(found) = attribute(node, name) else { continue }; + let Some(Expression::ConditionalExpression(conditional)) = expression(found) else { continue }; + let open = match (zero_like(&conditional.consequent), zero_like(&conditional.alternate)) { + (true, false) => &conditional.alternate, + (false, true) => &conditional.consequent, + _ => continue, + }; + if name.starts_with("max") && fixed_length(open) { + self.report(found.span, "disclosure-fixed-max-height", Severity::Warning, + "This panel opens to a fixed max-height, not to its content height.".into(), + "Animate to the content's own height: gridTemplateRows from 0fr to 1fr with an inner overflow-hidden wrapper, height: auto with interpolate-size/calc-size, or the measured scrollHeight. Then short content is not timed for a tall box, long content is not cut off, and the elements below move with the real height."); + } + if !hides_collapsed(element) && holds(&element.children).focusable { + self.report(found.span, "disclosure-collapsed-focusable", Severity::Warning, + "This panel collapses to zero height but its links, buttons or fields stay in the tab order.".into(), + "Take the collapsed content out of the tab order: inert={!open} (or visibility hidden after the close transition ends, or hidden once closed). Keep the panel mounted so form values survive closing and reopening."); + } + return; + } + } +} + +impl<'a> Visit<'a> for Visitor<'_, '_> { + fn visit_jsx_element(&mut self, node: &JSXElement<'a>) { + let sequence = marks_sequence(&node.opening_element); + if sequence { + self.contract.sequential.push(node.span); + let own = Bag::of_element(&node.opening_element); + let library = ["whileInView", "initial", "animate"].iter().find_map(|name| attribute(&node.opening_element, name)).map(|attribute| attribute.span); + let container = library.or_else(|| (own.declares_animation() && !own.loops()).then_some(node.opening_element.span)); + if let Some(span) = container { + self.report(span, "sequence-animates-container", Severity::Warning, + "The sequential group itself carries the entrance, so all of its items move together with it.".into(), + "Leave the group still and animate each unit (card, row, step or section the request names) on its own, one after another. Animate the whole container only when the request asks for the group to enter as one."); + } + } + self.check_disclosure(node); + self.depth += usize::from(sequence); + walk::walk_jsx_element(self, node); + self.depth -= usize::from(sequence); + } + + fn visit_jsx_opening_element(&mut self, node: &JSXOpeningElement<'a>) { + let bag = Bag::of_element(node); + self.check_bag(&bag); + // A motion library loop: `transition={{ repeat: Infinity }}`, unless + // all it animates is a rotation (a spinner). + let repeats = attribute(node, "transition").and_then(expression).is_some_and(|transition| { + matches!(transition, Expression::ObjectExpression(object) if matches!(property(object, "repeat"), Some(Expression::Identifier(name)) if name.name == "Infinity")) + }); + let spins = attribute(node, "animate").and_then(expression).is_some_and(|animate| { + matches!(animate, Expression::ObjectExpression(object) if object.properties.len() == 1 && property(object, "rotate").is_some()) + }); + if repeats && !spins { + self.contract.first_repeat.get_or_insert(node.span); + } + walk::walk_jsx_opening_element(self, node); + } + + fn visit_object_expression(&mut self, node: &ObjectExpression<'a>) { + self.check_bag(&Bag::of_object(node)); + if let Some((span, step)) = framer_step(node) + && let Some(Expression::NumericLiteral(duration)) = property(node, "duration") + { + self.overlaps(span, step, duration.value); + } + walk::walk_object_expression(self, node); + } + + fn visit_object_property(&mut self, node: &ObjectProperty<'a>) { + let sequence = node.key.static_name().is_some_and(|key| SEQUENTIAL_SELECTORS.iter().any(|marker| key.contains(marker))); + if sequence { + self.contract.sequential.push(node.span); + } + self.depth += usize::from(sequence); + walk::walk_object_property(self, node); + self.depth -= usize::from(sequence); + } + + fn visit_logical_expression(&mut self, node: &LogicalExpression<'a>) { + if node.operator == LogicalOperator::And + && disclosure_condition(&node.left) + && let Expression::JSXElement(element) = node.right.get_inner_expression() + && !overlay(element) + && holds(&element.children).field + { + self.report(node.span, "disclosure-unmounts-form", Severity::Info, + "This panel's form fields are rendered only while it is open, so closing it discards what was typed.".into(), + "For a dropdown or accordion that holds a form, keep the panel mounted and collapse it (height to 0 with inert while closed) so values survive closing and reopening. Leave it when the reset is intended."); + } + walk::walk_logical_expression(self, node); + } +} + +#[cfg(test)] +#[path = "motion_contract_tests.rs"] +mod tests; diff --git a/crates/devup-mcp-devup-ui/src/ui_validate/motion_contract_tests.rs b/crates/devup-mcp-devup-ui/src/ui_validate/motion_contract_tests.rs new file mode 100644 index 00000000..e13e3dad --- /dev/null +++ b/crates/devup-mcp-devup-ui/src/ui_validate/motion_contract_tests.rs @@ -0,0 +1,110 @@ +//! Request-shaped motion rules: each failing shape, and the correct form +//! that must stay silent. +use super::super::{findings, reduced_motion_finding}; + +const RISE: &str = "const rise = keyframes({ from: { opacity: 0, transform: 'translateY(16px)' }, to: { opacity: 1, transform: 'translateY(0)' } });"; + +fn rules(body: &str) -> Vec<&'static str> { + findings(&format!("{RISE}\n{body}")).into_iter().map(|finding| finding.rule).filter(|rule| *rule != "entrance-uses-motion-library").collect() +} + +#[test] +fn a_sequential_group_starts_each_item_after_the_previous_one_finished() { + for body in [ + // Each card waits 60ms while it animates for 400ms: they overlap. + r#"const C = () => {cards.map((card, i) => )}"#, + // The group component form. + r#"const C = () => {cards.map((card, i) => )}"#, + // A selector keyed on the marker. + r#"const item = css({ selectors: { '[data-reveal-sequence="sequential"][data-reveal-state="in"] &': { animationName: rise, animationDuration: '0.4s', animationDelay: 'calc(var(--i) * 0.2s)' } } })"#, + // A motion library: delay per index shorter than the duration. + r#"const C = () =>
    {steps.map((step, i) => )}
"#, + ] { + assert_eq!(rules(body), ["sequence-overlaps"], "{body}"); + } + for body in [ + // A step as long as the item: the next starts when this one ends, + // and the short-stagger bound does not apply inside the group. + r#"const C = () => {cards.map((card, i) => )}"#, + r#"const C = () =>
    {steps.map((step, i) => )}
"#, + // Not marked sequential: an overlapping short stagger is the default. + r#"const C = () => {cards.map((card, i) => )}"#, + // Duration not readable here: unknown, not reported. + r#"const C = () => {cards.map((card, i) => )}"#, + ] { + assert_eq!(rules(body), Vec::<&str>::new(), "{body}"); + } + // Outside a sequential group a long step is still too long. + let unmarked = r#"const C = () => {cards.map((card, i) => )}"#; + assert_eq!(rules(unmarked), ["stagger-too-long"]); +} + +#[test] +fn a_sequential_group_does_not_animate_as_one_container() { + for body in [ + r#"const C = () => "#, + r#"const C = () =>
  • "#, + ] { + assert!(rules(body).contains(&"sequence-animates-container"), "{body}"); + } + let still = r#"const C = () => "#; + assert_eq!(rules(still), Vec::<&str>::new()); +} + +#[test] +fn a_collapsed_panel_leaves_no_focus_and_opens_to_its_content_height() { + for body in [ + r#"const C = () => Terms"#, + r#"const C = () => "#, + ] { + assert_eq!(rules(body), ["disclosure-collapsed-focusable"], "{body}"); + } + let fixed = r#"const C = () =>

    Answer

    "#; + assert_eq!(rules(fixed), ["disclosure-fixed-max-height"]); + for body in [ + // inert on the panel or on its only child. + r#"const C = () => "#, + r#"const C = () => Terms"#, + // Nothing focusable inside. + r#"const C = () =>

    Answer

    "#, + // Not a collapse. + r#"const C = () => X"#, + ] { + assert_eq!(rules(body), Vec::<&str>::new(), "{body}"); + } +} + +#[test] +fn a_panel_that_holds_a_form_stays_mounted_while_closed() { + let found = findings(r#"const C = () => {isOpen && }"#, + // Not a disclosure state. + r#"const C = () => {user && }"#, + ] { + assert!(findings(source).is_empty(), "{source}"); + } +} + +#[test] +fn a_repeating_emphasis_needs_reduced_motion_handling_too() { + let pulse = "const pulse = keyframes({ '50%': { transform: 'scale(1.06)' } });"; + for source in [ + format!("{pulse}\nconst C = () => "), + format!("{pulse}\nconst C = () => "), + "const C = () => ".to_owned(), + ] { + let finding = reduced_motion_finding(&source).unwrap_or_else(|| panic!("{source}")); + assert_eq!(finding.rule, "motion-without-reduced-motion"); + assert!(finding.message.contains("repeating emphasis"), "{source}"); + } + let handled = format!("{pulse}\nconst C = () => "); + assert!(reduced_motion_finding(&handled).is_none()); +} diff --git a/crates/devup-mcp-devup-ui/src/ui_validate/motion_keyframes.rs b/crates/devup-mcp-devup-ui/src/ui_validate/motion_keyframes.rs index 53e80824..1d271f21 100644 --- a/crates/devup-mcp-devup-ui/src/ui_validate/motion_keyframes.rs +++ b/crates/devup-mcp-devup-ui/src/ui_validate/motion_keyframes.rs @@ -15,6 +15,8 @@ use oxc_span::Span; pub(super) struct Frames { hides: bool, moves: bool, + /// Every frame only rotates: a loading spinner, not an emphasis. + spins: bool, } /// `keyframes({ from: {…}, to: {…} })`, also as `Devup.keyframes(…)`. @@ -41,9 +43,31 @@ fn frames(object: &ObjectExpression<'_>) -> Frames { hides: property(first, "opacity").is_some_and(is_zero) || matches!(property(first, "visibility"), Some(Expression::StringLiteral(text)) if text.value == "hidden"), moves: ["transform", "translate", "scale"].iter().any(|key| property(first, key).is_some()), + spins: only_rotates(object), } } +fn only_rotates(object: &ObjectExpression<'_>) -> bool { + let mut any = false; + for item in &object.properties { + let ObjectPropertyKind::ObjectProperty(frame) = item else { return false }; + let Expression::ObjectExpression(style) = frame.value.get_inner_expression() else { return false }; + for item in &style.properties { + let ObjectPropertyKind::ObjectProperty(entry) = item else { return false }; + let rotates = match (entry.key.static_name().as_deref(), literal_text(entry.value.get_inner_expression())) { + (Some("rotate"), _) => true, + (Some("transform"), Some(text)) => text.split(')').map(str::trim).filter(|part| !part.is_empty()).all(|part| part.starts_with("rotate")), + _ => false, + }; + if !rotates { + return false; + } + any = true; + } + } + any +} + /// `const rise = keyframes({…})` declarations of this file, by name. pub(super) struct Declared(pub Vec<(String, Frames)>); @@ -148,7 +172,40 @@ impl<'b, 'a> Bag<'b, 'a> { BACKGROUND_PROPS.iter().any(|name| self.entry(name).is_some()) } - fn loops(&self) -> bool { + /// Whether the bag names an animation (`animationName`/`animation`). + pub(super) fn declares_animation(&self) -> bool { + self.entry("animationName").is_some() || self.entry("animation").is_some() + } + + /// The span of an animation of this file's keyframes that repeats + /// forever (an emphasis or a pulse), if any. A spinner, which only + /// rotates, and keyframes declared elsewhere are not counted. + pub(super) fn loop_span(&self, declared: &Declared) -> Option { + if !self.loops() { + return None; + } + let frames = ["animationName", "animation"].iter().find_map(|key| declared.referenced(self.entry(key)?.expression?))?; + if frames.spins { + return None; + } + self.entry("animationIterationCount").or_else(|| self.entry("animation")).map(|entry| entry.span) + } + + /// How long one item's animation or transition runs, in seconds: the + /// longhand, else the first duration token of the `animation` shorthand. + pub(super) fn duration_seconds(&self) -> Option { + if let Some(text) = self.text("animationDuration").or_else(|| self.text("transitionDuration")) { + return duration(text); + } + let shorthand = match self.entry("animation")?.expression? { + Expression::StringLiteral(text) => text.value.to_string(), + Expression::TemplateLiteral(template) => template.quasis.iter().map(|quasi| quasi.value.raw.as_str()).collect::>().join(" "), + _ => return None, + }; + shorthand.split_whitespace().find_map(duration) + } + + pub(super) fn loops(&self) -> bool { let shorthand = self.entry("animation").and_then(|entry| entry.expression).is_some_and(|expression| match expression { Expression::TemplateLiteral(template) => template.quasis.iter().any(|quasi| quasi.value.raw.contains("infinite")), Expression::StringLiteral(text) => text.value.contains("infinite"), diff --git a/crates/devup-mcp-devup-ui/src/ui_validate/motion_quality.rs b/crates/devup-mcp-devup-ui/src/ui_validate/motion_quality.rs index 1784f9cc..9b1ff58c 100644 --- a/crates/devup-mcp-devup-ui/src/ui_validate/motion_quality.rs +++ b/crates/devup-mcp-devup-ui/src/ui_validate/motion_quality.rs @@ -30,6 +30,11 @@ //! - `entrance-per-element` (info): a heading or a control carries its own //! entrance; the entrance belongs to the content group around it. //! +//! Rules a request shapes (a sequential group, a disclosure, a repeating +//! emphasis) are in [`contract`]: `sequence-overlaps`, +//! `sequence-animates-container`, `disclosure-collapsed-focusable`, +//! `disclosure-fixed-max-height` and `disclosure-unmounts-form`. +//! //! Every rule reads both styles: framer-motion props (`initial`, //! `whileInView`, `viewport`, `transition`) and Devup UI keyframes //! (`keyframes()`, `animationName`/`animation`, `animationTimeline`, @@ -37,6 +42,8 @@ //! `IntersectionObserver`), see [`keyframes`]. #[path = "motion_keyframes.rs"] mod keyframes; +#[path = "motion_contract.rs"] +mod contract; use super::{Severity, Violation, site}; use oxc_allocator::Allocator; @@ -52,7 +59,21 @@ const BACKGROUND_PROPS: &[&str] = &["bg", "bgColor", "bgImage", "background", "backgroundColor", "backgroundImage"]; pub(super) fn findings(source: &str) -> Vec { - collect(source).map(|collector| collector.findings).unwrap_or_default() + let Some(collector) = collect(source) else { + return Vec::new(); + }; + let Collector { findings, contract, .. } = collector; + // A sequential group asks for a step as long as each item: the + // short-stagger bound is not its rule there. + let mut findings: Vec = findings + .into_iter() + .filter(|finding| { + finding.rule != "stagger-too-long" + || !contract.in_sequence(oxc_span::Span::new(finding.byte_range[0] as u32, finding.byte_range[1] as u32)) + }) + .collect(); + findings.extend(contract.findings); + findings } /// One finding for a file that animates content into view while nothing in it @@ -62,14 +83,19 @@ pub fn reduced_motion_finding(source: &str) -> Option { if handles_reduced_motion(source) { return None; } - let span = collect(source)?.first_entrance?; + let collector = collect(source)?; + let (span, message) = match (collector.first_entrance, collector.contract.first_repeat) { + (Some(span), _) => (span, "Entrance motion is added, and no validated source handles prefers-reduced-motion."), + (None, Some(span)) => (span, "A repeating emphasis animation is added, and no validated source handles prefers-reduced-motion, so it keeps running for readers who asked for less motion."), + (None, None) => return None, + }; Some(site::violation( source, span, "motion-without-reduced-motion", Severity::Warning, - "Entrance motion is added, and no validated source handles prefers-reduced-motion.".into(), - "Leave content in place for reduced motion: _motionReduce={{ animation: 'none' }} on the animated element (Devup UI), a prefers-reduced-motion media rule, or useReducedMotion()/ for a motion library. Validate the shared rule or provider together with this file if it lives elsewhere.", + message.into(), + "Leave content in place for reduced motion and stop repeating effects: _motionReduce={{ animation: 'none' }} on the animated element (Devup UI), a prefers-reduced-motion media rule, or useReducedMotion()/ for a motion library. A CSS media rule also applies when the preference is switched on while the page is open; a value read once at load does not. Validate the shared rule or provider together with this file if it lives elsewhere.", )) } @@ -133,8 +159,10 @@ fn collect(source: &str) -> Option> { } let mut components = MotionComponents(Vec::new(), keyframes::Declared(Vec::new())); components.visit_program(&parsed.program); + let contract = contract::collect(&parsed.program, source, &components.1); let mut collector = Collector { source, + contract, findings: Vec::new(), first_entrance: None, optional: 0, @@ -180,6 +208,8 @@ impl<'a> Visit<'a> for MotionComponents { struct Collector<'s> { source: &'s str, findings: Vec, + /// What the request-shaped rules found (`motion_contract.rs`). + contract: contract::Contract, first_entrance: Option, /// Depth inside `AnimatePresence` or a conditional render: such an /// element mounts on the client later, so its initial style is not diff --git a/crates/devup-mcp/src/server/behavior_contracts/detect.rs b/crates/devup-mcp/src/server/behavior_contracts/detect.rs index 0d043b3f..78a87540 100644 --- a/crates/devup-mcp/src/server/behavior_contracts/detect.rs +++ b/crates/devup-mcp/src/server/behavior_contracts/detect.rs @@ -431,7 +431,7 @@ pub(super) fn section_entrance( node, json!({"sectionHeight":node.typed_view().number("height"),"belowFirstContentSection":true}), json!({ - "pattern":"devup-ui-static-keyframes-reveal","scope":"selected major below-fold sections, not every text or control","implementation":"Reveal.tsx: Devup UI keyframes() with animationFillMode both, animationTimeline view() and animationRange entry 0% entry min(100%, 240px) on an inner wrapper; no animation library","serverMarkup":"the resting style is the visible content and the hidden start exists only in the keyframes; never prehide SSR content","fallback":"the shared controller marks data-reveal-state once for groups on a clock (data-reveal=timed) and where view timelines are unsupported; it never hides content already on screen","motion":"short upward translation and fade, complete once the block is in view","reducedMotion":"_motionReduce animation none","focus":"_focusWithin animation none","timing":"implementation choice, not captured Figma motion","rules":"devfive-frontend/references/animation.md","verify":["start/middle/end frames","trigger position","scroll re-entry","fast scroll","reload","back/forward","bfcache","client navigation","delayed and failed images","focus","reduced motion","JavaScript disabled","stagger and progress timing"] + "pattern":"devup-ui-static-keyframes-reveal","scope":"selected major below-fold sections, not every text or control","implementation":"Reveal.tsx: Devup UI keyframes() with animationFillMode both, animationTimeline view() and animationRange entry 0% entry min(100%, 240px) on an inner wrapper; no animation library","serverMarkup":"the resting style is the visible content and the hidden start exists only in the keyframes; never prehide SSR content","fallback":"the shared controller marks data-reveal-state once for groups on a clock (data-reveal=timed) and where view timelines are unsupported; it never hides content already on screen","motion":"short upward translation and fade, complete once the block is in view","reducedMotion":"_motionReduce animation none","focus":"_focusWithin animation none","timing":"implementation choice, not captured Figma motion","rules":"devfive-frontend/references/animation.md","verify":["start/middle/end frames","trigger position","scroll re-entry","fast scroll","reload","back/forward","bfcache","client navigation","delayed and failed images","focus","reduced motion","reduced motion switched on mid-use","JavaScript disabled","stagger and progress timing"] }), )) } diff --git a/crates/devup-mcp/src/server/behavior_contracts/motion_templates.rs b/crates/devup-mcp/src/server/behavior_contracts/motion_templates.rs index 8c187f6d..cb6eaf98 100644 --- a/crates/devup-mcp/src/server/behavior_contracts/motion_templates.rs +++ b/crates/devup-mcp/src/server/behavior_contracts/motion_templates.rs @@ -27,7 +27,7 @@ pub(super) fn attach(result: &mut Value) { result["revealTsx"] = json!(include_str!("templates/Reveal.tsx")); } result["motionBindings"] = json!({"version":1,"bindings":bindings, - "integration":"Keep generated server TSX. Bind semantic selectors and validated API values; mount MotionController once in the persistent server layout with those bindings. Keep the original captured palette/indicator/progress markup. Selectors are required, never guessed from node IDs. A section entrance is static CSS: wrap the section's content group (not the painted section) in Reveal, or RevealGroup with RevealItem for staggered cards and RevealLine/RevealStep for a progress line, and bind section-entrance to [data-reveal].", + "integration":"Keep generated server TSX. Bind semantic selectors and validated API values; mount MotionController once in the persistent server layout with those bindings. Keep the original captured palette/indicator/progress markup. Selectors are required, never guessed from node IDs. A section entrance is static CSS: wrap the section's content group (not the painted section) in Reveal, or RevealGroup with RevealItem for staggered cards (sequence=\"sequential\" when the request asks for one unit after another) and RevealLine/RevealStep for a progress line, and bind section-entrance to [data-reveal].", "files":if reveals { json!({"motionControllerTsx":"MotionController.tsx","motionRuntime":"motion-runtime.ts","revealTsx":"Reveal.tsx"}) } else { json!({"motionControllerTsx":"MotionController.tsx","motionRuntime":"motion-runtime.ts"}) }, "entranceStyle":"devup-ui-static-keyframes", "playback":"Continuous marquee/steps have no pause controls; set respectReducedMotion:false only for an explicit continuous-playback requirement.", diff --git a/crates/devup-mcp/src/server/behavior_contracts/templates/Reveal.tsx b/crates/devup-mcp/src/server/behavior_contracts/templates/Reveal.tsx index 762c534b..4354e2d1 100644 --- a/crates/devup-mcp/src/server/behavior_contracts/templates/Reveal.tsx +++ b/crates/devup-mcp/src/server/behavior_contracts/templates/Reveal.tsx @@ -48,12 +48,18 @@ export function Reveal(props: RevealProps) { * steps along a progress line. One trigger for the whole group (the shared * MotionController marks it once when it enters), items delayed by their * index. Give each item ``. + * + * `sequence="sequential"` is for a request that the items appear + * sequentially: each item starts only when the previous one has finished + * (`index * (400ms + --reveal-gap)`), never overlapping. The group itself + * never moves. For row by row, give every card of a row the row's index at + * the current layout. */ -export function RevealGroup(props: RevealProps) { - return ; +export function RevealGroup({ sequence, ...props }: RevealProps & { sequence?: 'sequential' }) { + return ; } -/** One item of a `RevealGroup`: waits `index * 60ms`, then rises. */ +/** One item of a `RevealGroup`: waits `index * 60ms` (or, in a sequential group, until the previous item has finished), then rises. */ export function RevealItem({ index, style, ...props }: RevealProps & { index: number }) { return ( diff --git a/crates/devup-mcp/src/server/behavior_contracts/templates/motion-runtime.ts b/crates/devup-mcp/src/server/behavior_contracts/templates/motion-runtime.ts index dcfc5010..3be2b80b 100644 --- a/crates/devup-mcp/src/server/behavior_contracts/templates/motion-runtime.ts +++ b/crates/devup-mcp/src/server/behavior_contracts/templates/motion-runtime.ts @@ -237,14 +237,22 @@ export function mountMotion(root: ParentNode, bindings: MotionBinding[]) { if (!(event.target instanceof Element)) return; for (let node = event.target.closest(`[${state}]`); node; node = node.parentElement?.closest(`[${state}]`) ?? null) settle(node, 'shown'); }; + // Reduced motion switched on while the page is open: every marked group is + // shown in place at once, whether it was waiting or mid-entrance. A rule + // read only at attach time would leave a running entrance to finish. + const motionQuery = matchMedia('(prefers-reduced-motion: reduce)'); + const stillness = () => { + if (!motionQuery.matches || !reveals.some(binding => binding.respectReducedMotion !== false)) return; + root.querySelectorAll(`[${state}]`).forEach(node => settle(node, 'shown')); + }; const mutations = new MutationObserver(refresh); const cleanup = () => { - mutations.disconnect(); revealObserver.disconnect(); root.removeEventListener('focusin', focus); + mutations.disconnect(); revealObserver.disconnect(); root.removeEventListener('focusin', focus); motionQuery.removeEventListener('change', stillness); [...active.values()].reverse().forEach(entry => entry.cleanup()); active.clear(); // Nothing stays hidden once the marker is gone. pending.forEach(node => node.removeAttribute(state)); pending.clear(); }; - try { refresh(); mutations.observe(root, { childList: true, subtree: true }); root.addEventListener('focusin', focus); } + try { refresh(); mutations.observe(root, { childList: true, subtree: true }); root.addEventListener('focusin', focus); motionQuery.addEventListener('change', stillness); } catch (error) { cleanup(); throw error; } return cleanup; } diff --git a/crates/devup-mcp/src/server/behavior_contracts/tests.rs b/crates/devup-mcp/src/server/behavior_contracts/tests.rs index 3ea1c618..70ced61a 100644 --- a/crates/devup-mcp/src/server/behavior_contracts/tests.rs +++ b/crates/devup-mcp/src/server/behavior_contracts/tests.rs @@ -287,6 +287,7 @@ fn page_footer_and_reveal_recommendations_preserve_readable_server_content() { } assert_eq!(entrance["reducedMotion"], "_motionReduce animation none"); assert!(entrance["verify"].as_array().unwrap().contains(&json!("bfcache"))); + assert!(entrance["verify"].as_array().unwrap().contains(&json!("reduced motion switched on mid-use"))); let reveal = result["revealTsx"].as_str().unwrap(); for term in ["import { Box, keyframes } from '@devup-ui/react'", "animationTimeline=\"view()\"", "animationRange=\"entry 0% entry min(100%, 240px)\"", "animationFillMode=\"both\"", "_motionReduce={{ animation: 'none' }}", "_focusWithin={{ animation: 'none' }}", "calc(var(--reveal-index) * 60ms)", "export function RevealLine"] { assert!(reveal.contains(term), "Reveal.tsx lacks {term}"); @@ -297,9 +298,17 @@ fn page_footer_and_reveal_recommendations_preserve_readable_server_content() { // The shared controller only marks state; it holds no entrance animation. let runtime = result["motionRuntime"].as_str().unwrap(); assert!(runtime.contains("data-reveal-state") && runtime.contains("CSS.supports('animation-timeline: view()')")); + // Reduced motion switched on mid-use stops a running entrance at once. + assert!(runtime.contains("motionQuery.addEventListener('change', stillness)") && runtime.contains("settle(node, 'shown')")); assert!(!runtime.contains("translateY("), "the runtime animates no entrance"); assert_eq!(result["motionBindings"]["files"]["revealTsx"], "Reveal.tsx"); assert_eq!(result["motionBindings"]["entranceStyle"], "devup-ui-static-keyframes"); + // The request decides the motion: what to record before implementing, + // and a sequential group that never overlaps its items. + for term in ["sequence?: 'sequential'", "data-reveal-sequence={sequence}", "[data-reveal-sequence=\"sequential\"][data-reveal-state=\"in\"] &", "calc(var(--reveal-index) * (400ms + var(--reveal-gap, 0ms)))"] { + assert!(reveal.contains(term), "Reveal.tsx lacks {term}"); + } + assert!(result["motionBindings"]["integration"].as_str().unwrap().contains("sequence=\"sequential\"")); assert_eq!( result["behaviorPlan"]["pageContracts"][0]["implementation"]["minHeight"], "100dvh" diff --git a/crates/devup-mcp/src/server/development_contract.rs b/crates/devup-mcp/src/server/development_contract.rs index 49ee326b..f3b5e0fc 100644 --- a/crates/devup-mcp/src/server/development_contract.rs +++ b/crates/devup-mcp/src/server/development_contract.rs @@ -30,6 +30,10 @@ pub(super) const REQUIREMENTS: &[&str] = &[ "default-entrance-and-transition-motion", "devup-ui-static-keyframes-motion", "one-shot-reveals-without-ssr-flash", + "motion-request-first", + "sequential-no-overlap", + "disclosure-height-and-focus", + "emphasis-reduced-motion", "canonical-semantic-assets", "landing-detail-api-db-single-source", "user-approved-plan-before-implementation", @@ -44,6 +48,7 @@ pub(super) const COMPLETION_EVIDENCE: &[&str] = &[ "animation-start-middle-end-frames", "motion-trigger-reentry-history-and-image-failure", "stagger-total-and-progress-sync-timing", + "mid-sequence-motion", "changed-empty-and-failing-api", "all-public-assets-and-persisted-url-references", ]; @@ -51,7 +56,7 @@ pub(super) const COMPLETION_EVIDENCE: &[&str] = &[ pub(super) fn attach(result: &mut Value) { if !result.is_object() { return; } result["developmentContract"] = json!({ - "version": 6, + "version": 7, "guide": "devup://guide/usage#behavior-and-data-contracts", "alwaysApplies": true, "requirements": REQUIREMENTS, @@ -69,7 +74,7 @@ mod tests { attach(&mut result); assert_eq!(result["developmentContract"]["alwaysApplies"], true); assert_eq!(result["developmentContract"]["staticExportProvesApplicationBehavior"], false); - assert_eq!(result["developmentContract"]["version"], 6); + assert_eq!(result["developmentContract"]["version"], 7); let requirements = result["developmentContract"]["requirements"].as_array().unwrap(); for required in ["route-owned-page-body", "devup-api-only", "stop-affected-api-gaps", "paired-e2e-and-native-figma-visuals"] { assert!(requirements.contains(&json!(required))); @@ -90,6 +95,13 @@ yourself", "carries no offer", super::super::skills::RETRO_OFFER_FIELD] { "default-entrance-and-transition-motion", "devup-ui-static-keyframes-motion", "one-shot-reveals-without-ssr-flash", + // The request decides the motion: what moves, in what unit, + // order and direction, and how disclosures and emphasis behave. + // Identifiers are short: they ride in every export reply. + "motion-request-first", + "sequential-no-overlap", + "disclosure-height-and-focus", + "emphasis-reduced-motion", ] { assert!(requirements.contains(&json!(required)), "{required}"); } @@ -99,12 +111,18 @@ yourself", "carries no offer", super::super::skills::RETRO_OFFER_FIELD] { "animation-start-middle-end-frames", "motion-trigger-reentry-history-and-image-failure", "stagger-total-and-progress-sync-timing", + "mid-sequence-motion", ] { assert!(evidence.contains(&json!(required)), "{required}"); } for (document, terms) in [ (RULES, &["without being asked", "plays once", "opacity: 0", "prefers-reduced-motion", "back/forward", "failed images", "keyframes", "animationTimeline"][..]), - (MOTION_RULES, &["user stated", "keyframes", "animationTimeline=\"view()\"", "animationRange", "animationFillMode", "_motionReduce", "_focusWithin", "IntersectionObserver", "data-reveal", "framer-motion", "stagger", "background", "Progress line", "hydration", "JavaScript disabled", "focus", "start, a middle and the end", "Trigger timing", "Fast scroll", "back/forward", "block one", "unverified"][..]), + (MOTION_RULES, &["user stated", "keyframes", "animationTimeline=\"view()\"", "animationRange", "animationFillMode", "_motionReduce", "_focusWithin", "IntersectionObserver", "data-reveal", "framer-motion", "stagger", "background", "Progress line", "hydration", "JavaScript disabled", "focus", "start, a middle and the end", "Trigger timing", "Fast scroll", "back/forward", "block one", "unverified", + // The request-shaped rules. + "Request-specific instructions", "finishes before the next", "data-reveal-sequence", "numbered list", "same row", "actually laid out", + "reaches each number", "content height", "interrupted", "inert", "form values", "once per visit", + "new visit", "bfcache", "emphasis", "returns to its resting state", "switched on while", "Record before implementing", + "reduced-motion-toggle", "sequence", "disclosure", "combined", "Order and direction"][..]), ] { for term in terms { assert!(document.contains(term), "missing motion policy: {term}"); @@ -144,6 +162,6 @@ yourself", "carries no offer", super::super::skills::RETRO_OFFER_FIELD] { unique.sort(); unique.dedup(); assert_eq!(unique.len(), REQUIREMENTS.len() + COMPLETION_EVIDENCE.len()); - assert_eq!((REQUIREMENTS.len(), COMPLETION_EVIDENCE.len()), (23, 8)); + assert_eq!((REQUIREMENTS.len(), COMPLETION_EVIDENCE.len()), (27, 9)); } } diff --git a/crates/devup-mcp/src/server/runtime_audit/motion_evidence.rs b/crates/devup-mcp/src/server/runtime_audit/motion_evidence.rs index 137ff41e..86ca69b2 100644 --- a/crates/devup-mcp/src/server/runtime_audit/motion_evidence.rs +++ b/crates/devup-mcp/src/server/runtime_audit/motion_evidence.rs @@ -11,11 +11,19 @@ const MOBILE_MAX_WIDTH: u32 = 767; const DESKTOP_MIN_WIDTH: u32 = 1024; -const REVEAL_SCENARIOS: [&str; 12] = [ +const REVEAL_SCENARIOS: [&str; 13] = [ "fast-scroll", "reload", "history", "bfcache", "client-nav", "image-delay", "image-failure", - "focus", "reduced-motion", "no-script", "stagger", "progress-sync", + "focus", "reduced-motion", "reduced-motion-toggle", "no-script", "stagger", "progress-sync", ]; +/// What a request can fix about a group's entrance, each named exactly: +/// how its units follow each other, what one unit is, the play order and +/// where each unit starts from (one value, or one per unit in play order). +const REVEAL_SEQUENCES: [&str; 3] = ["sequential", "overlap", "together"]; +const REVEAL_UNITS: [&str; 5] = ["item", "card", "step", "section", "row"]; +const REVEAL_ORDERS: [&str; 2] = ["document", "reverse"]; +const REVEAL_DIRECTIONS: [&str; 4] = ["from-right", "from-left", "from-bottom", "from-top"]; + fn viewport_class(width: u32) -> &'static str { if width <= MOBILE_MAX_WIDTH { "mobile" @@ -114,6 +122,12 @@ fn motion_evidence_row(policy: &OutputPolicy, report_dir: &Path, at: &MotionChec let stagger = &measured["scenarios"]["stagger"]; if stagger["stepsMs"].is_array() { row["stagger"] = json!({"stepsMs": stagger["stepsMs"], "spanMs": stagger["spanMs"], "totalMs": stagger["totalMs"], "bounds": stagger["bounds"]}); + // What the request fixed (sequence, unit, order, direction) and + // how each unit actually played. + if stagger["contract"].is_object() { + let contract = &stagger["contract"]; + row["stagger"]["sequence"] = json!({"mode": contract["sequence"], "status": contract["status"], "units": contract["units"], "failures": contract["failures"], "unverified": contract["unverified"]}); + } } let sync = &measured["scenarios"]["progress-sync"]; if sync["gaps"].is_array() { @@ -206,6 +220,18 @@ mod motion_evidence_tests { motion_evidence_row(&policy, &std::env::temp_dir(), &MotionCheckAt { screen: "home", viewport: &viewport(width), index: 0, check: &reveal_check(), item: item.as_ref(), status }) } + #[test] + fn a_sequence_verdict_is_carried_into_the_evidence_row() { + let mut scenarios = every_scenario(); + scenarios["stagger"] = json!({"status": "fail", "stepsMs": [60, 60], "spanMs": 120, "totalMs": 520, "bounds": null, + "contract": {"sequence": "sequential", "status": "fail", "units": [{"items": [0], "startMs": 0, "endMs": 400}, {"items": [1], "startMs": 60, "endMs": 460}], + "failures": ["unit 2 started 340ms before unit 1 finished"], "unverified": []}}); + let row = row(390, "fail", Some(measured(scenarios))); + assert_eq!(row["stagger"]["sequence"]["mode"], "sequential"); + assert_eq!(row["stagger"]["sequence"]["failures"][0], "unit 2 started 340ms before unit 1 finished"); + assert_eq!(row["scenarios"]["reduced-motion-toggle"], "pass"); + } + #[test] fn a_candidate_is_verified_only_by_passing_mobile_and_desktop_checks() { let rows = vec![row(390, "pass", Some(measured(every_scenario()))), row(1440, "pass", Some(measured(every_scenario())))]; diff --git a/crates/devup-mcp/src/server/runtime_audit/motion_validation.rs b/crates/devup-mcp/src/server/runtime_audit/motion_validation.rs index a6b2e920..6820e4e4 100644 --- a/crates/devup-mcp/src/server/runtime_audit/motion_validation.rs +++ b/crates/devup-mcp/src/server/runtime_audit/motion_validation.rs @@ -8,15 +8,17 @@ fn validate_motion(value: Option<&Value>) -> Result<(), DevupError> { .filter(|id| !id.is_empty()) .ok_or_else(|| invalid("motion needs its exact behavior candidateId"))?, )?; - if !matches!(kind, "marquee" | "count-up" | "steps" | "tabs" | "reveal") { + if !matches!(kind, "marquee" | "count-up" | "steps" | "tabs" | "reveal" | "disclosure") { return Err(invalid( - "motion.kind must be marquee, count-up, steps, tabs or reveal", + "motion.kind must be marquee, count-up, steps, tabs, reveal or disclosure", )); } for key in match kind { "marquee" => vec!["target", "track"], "steps" => vec!["target", "steps", "progress"], "tabs" => vec!["target", "links", "indicator", "next"], + // The control that opens and closes it, and the collapsing panel. + "disclosure" => vec!["target", "panel"], _ => vec!["target"], } { let selector = value[key] @@ -61,11 +63,42 @@ fn validate_motion(value: Option<&Value>) -> Result<(), DevupError> { }; // What a reveal alone accepts: the animated items of a group, the // progress line, the control to focus and the link to leave the page by. - let reveal_only = ["scenarios", "items", "progress", "focus", "navigate", "settleMs", "maxStepMs", "maxSpanMs", "maxTotalMs", "syncToleranceMs", "progressMs"]; + let reveal_only = ["scenarios", "items", "progress", "focus", "navigate", "settleMs", "maxStepMs", "maxSpanMs", "maxTotalMs", "syncToleranceMs", "progressMs", "sequence", "unit", "order", "direction"]; if kind != "reveal" && let Some(key) = reveal_only.iter().find(|key| value.get(**key).is_some()) { return Err(invalid(format!("motion.{key} is for reveal only"))); } + // A disclosure names a form field to type into and the element after + // the panel that must move with it; both optional. + let disclosure_only = ["panel", "field", "after"]; + if kind != "disclosure" && let Some(key) = disclosure_only.iter().find(|key| value.get(**key).is_some()) { + return Err(invalid(format!("motion.{key} is for disclosure only"))); + } + let (_field, _after) = (semantic("field")?, semantic("after")?); let (items, progress, _focus, navigate) = (semantic("items")?, semantic("progress")?, semantic("focus")?, semantic("navigate")?); + // What the request fixed about a group. Each is judged per unit, so the + // group's items are required. + let named_value = |key: &str, allowed: &[&str]| -> Result { + match value.get(key) { + None => Ok(false), + Some(text) if text.as_str().is_some_and(|text| allowed.contains(&text)) => Ok(true), + Some(_) => Err(invalid(format!("motion.{key} takes {}", allowed.join(", ")))), + } + }; + let mut stated = named_value("sequence", &REVEAL_SEQUENCES)? | named_value("unit", &REVEAL_UNITS)? | named_value("order", &REVEAL_ORDERS)?; + if let Some(direction) = value.get("direction") { + let valid = match direction { + Value::String(text) => REVEAL_DIRECTIONS.contains(&text.as_str()), + Value::Array(list) => !list.is_empty() && list.len() <= 64 && list.iter().all(|item| item.as_str().is_some_and(|text| REVEAL_DIRECTIONS.contains(&text))), + _ => false, + }; + if !valid { + return Err(invalid(format!("motion.direction takes {} (or one per unit, in play order)", REVEAL_DIRECTIONS.join(", ")))); + } + stated = true; + } + if stated && items.is_none() { + return Err(invalid("motion.sequence, unit, order and direction are judged per item: name the group's items with a semantic motion.items selector")); + } if let Some(scenarios) = value.get("scenarios") { let valid = scenarios.as_array().is_some_and(|items| { items.len() <= REVEAL_SCENARIOS.len() @@ -106,6 +139,56 @@ fn validate_motion(value: Option<&Value>) -> Result<(), DevupError> { #[cfg(test)] mod motion_contract_tests { use super::*; + + #[test] + fn a_request_shaped_group_names_its_sequence_unit_order_and_direction_exactly() { + let sequential = json!({"kind":"reveal","candidateId":"section-entrance:steps","target":"#steps","items":"li","sequence":"sequential","unit":"step","order":"reverse","direction":"from-right","scenarios":["stagger","reduced-motion-toggle"]}); + assert!(validate_motion(Some(&sequential)).is_ok()); + let rows = json!({"kind":"reveal","candidateId":"section-entrance:cards","target":"#cards","items":".card","sequence":"sequential","unit":"row","direction":["from-left","from-right"]}); + assert!(validate_motion(Some(&rows)).is_ok()); + for patch in [ + json!({"sequence":"staggered"}), + json!({"unit":"column"}), + json!({"order":"random"}), + json!({"direction":"right-to-left"}), + json!({"direction":[]}), + json!({"direction":["from-left", 3]}), + ] { + let mut changed = sequential.clone(); + for (key, value) in patch.as_object().unwrap() { + changed[key] = value.clone(); + } + assert!(validate_motion(Some(&changed)).is_err(), "{changed}"); + } + // Judged per item: no items, no verdict. + let mut bare = sequential.clone(); + bare.as_object_mut().unwrap().remove("items"); + assert!(validate_motion(Some(&bare)).is_err()); + // Group fields belong to a reveal. + let tabs = json!({"kind":"tabs","candidateId":"tabs:1","target":"nav","links":"a","indicator":"i","next":"a","sequence":"sequential"}); + assert!(validate_motion(Some(&tabs)).is_err()); + } + + #[test] + fn a_disclosure_names_its_control_and_panel_semantically() { + let accordion = json!({"kind":"disclosure","candidateId":"disclosure:faq-1","target":"#faq-1 button","panel":"#faq-1 [role=region]","field":"#faq-1 input","after":"#faq-2","durationMs":300}); + assert!(validate_motion(Some(&accordion)).is_ok()); + for patch in [ + json!({"panel":null}), + json!({"panel":"[data-figma-node-id]"}), + json!({"field":""}), + json!({"after":"[data-source-node]"}), + json!({"items":".row"}), + ] { + let mut changed = accordion.clone(); + for (key, value) in patch.as_object().unwrap() { + if value.is_null() { changed.as_object_mut().unwrap().remove(key); } else { changed[key] = value.clone(); } + } + assert!(validate_motion(Some(&changed)).is_err(), "{changed}"); + } + let reveal = json!({"kind":"reveal","candidateId":"section-entrance:1","target":"#news","panel":"#x"}); + assert!(validate_motion(Some(&reveal)).is_err()); + } #[test] fn motion_probes_need_candidate_identity_semantics_and_bounded_measurements() { let valid = json!({"kind":"count-up","candidateId":"count-up:stat","target":"#patent-count","finalValue":2000,"durationMs":1600}); @@ -134,7 +217,7 @@ mod motion_contract_tests { assert!(validate_motion(Some(&timeline)).is_ok()); let group = json!({"kind":"reveal","candidateId":"section-entrance:3","target":"#cards","items":".card","scenarios":["stagger","client-nav"],"navigate":"#about"}); assert!(validate_motion(Some(&group)).is_ok()); - assert_eq!(REVEAL_SCENARIOS.len(), 12); + assert_eq!(REVEAL_SCENARIOS.len(), 13); for patch in [ json!({"scenarios":["fast-scrol"]}), json!({"scenarios":["progress-sync"]}), diff --git a/crates/devup-mcp/src/server/runtime_audit/tests.rs b/crates/devup-mcp/src/server/runtime_audit/tests.rs index 96f706af..90791bd9 100644 --- a/crates/devup-mcp/src/server/runtime_audit/tests.rs +++ b/crates/devup-mcp/src/server/runtime_audit/tests.rs @@ -61,7 +61,7 @@ mod tests { ) .await .unwrap(); - assert_eq!(planned["template"]["files"].as_array().unwrap().len(), 16); + assert_eq!(planned["template"]["files"].as_array().unwrap().len(), 18); let imported = std::process::Command::new("node") .args(["--input-type=module", "-e", "await import('./run.mjs')"]) .current_dir(dir.join("runner")) diff --git a/crates/devup-mcp/src/server/runtime_audit/write_plan.rs b/crates/devup-mcp/src/server/runtime_audit/write_plan.rs index db3060b8..39318ba8 100644 --- a/crates/devup-mcp/src/server/runtime_audit/write_plan.rs +++ b/crates/devup-mcp/src/server/runtime_audit/write_plan.rs @@ -74,6 +74,8 @@ fn write_plan( ("regression-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/regression-checks.mjs").as_slice()), ("motion-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/motion-checks.mjs").as_slice()), ("reveal-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/reveal-checks.mjs").as_slice()), + ("sequence-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/sequence-checks.mjs").as_slice()), + ("disclosure-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/disclosure-checks.mjs").as_slice()), ( "data-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/data-checks.mjs").as_slice(), diff --git a/crates/devup-mcp/src/server/skills/devfive-frontend/references/animation.md b/crates/devup-mcp/src/server/skills/devfive-frontend/references/animation.md index 8a3b130e..af0b8654 100644 --- a/crates/devup-mcp/src/server/skills/devfive-frontend/references/animation.md +++ b/crates/devup-mcp/src/server/skills/devfive-frontend/references/animation.md @@ -16,6 +16,77 @@ or for what CSS cannot express (gesture-driven or physics motion, exit animations of unmounting elements, shared-layout transitions); say so when you do. +## 0. Read the request first + +Request-specific instructions override every default in this guide. Where a +request describes motion, the rules below say what its words mean; where it +says nothing, sections 1-3 apply. + +**Record before implementing.** For each motion, write down from the +request's own wording: the target (what moves), the unit (what moves at +once), the order, the direction of movement, the trigger (load, scroll into +view, click, after another motion) and the timing (duration, wait, repeat). +Put the record in the plan or the PR description; the runtime audit checks +are written from it (section 4). + +**Sequential means one unit after another.** If steps 1-4 "appear +sequentially", step 1 finishes entering, then step 2 starts, and so on: each +unit finishes before the next starts. Do not move the parent container as a +whole, and do not only offset start times so that several entrances overlap. +If the whole sequence runs long, shorten each unit's duration and the wait +between units instead. Overlapping entrances are used only when the request +asks for them. Mark such a group `data-reveal-sequence="sequential"` +(``) and give each item a delay of +`index * (duration + gap)`; `devup_ui_validate` reads the marker. + +**The unit comes from the wording.** "Card by card" moves one card at a +time, "row by row" one row at a time, "section by section" one section at a +time. "Sequentially" with no unit means one step at a time for a +numbered list and one card at a time for side-by-side cards. A card's background, +image, icon and text move together as one card. In a row-by-row entrance the +cards of the same row move together and the next row starts when that row +has finished; on a responsive page the rows are the rows actually laid out +at the current width (two rows of two on mobile can be one row of four on +desktop), so give each card its row index at that width, not its list +index. "Title, then cards one by one, then the steps" plays title, card 1, +card 2, card 3, then the steps. + +**Order and direction are separate.** "Moves from right to left" means each +element starts to the right and travels left; "the right card first" means +the right card plays first. When both are given, keep both. When each row is +given its own direction, keep the direction per row. A progress line linked +to cards keeps the stated condition: "the line is drawn, then the numbers +appear" means the numbers start one after another only once the line has +finished; "a card appears when the line reaches each number" means the +moment the drawn end of the line, as rendered, reaches each number. + +**Dropdowns and accordions.** Open and close to the content height, and let +the content below follow the change. A toggle interrupted part-way (closed +while opening, reopened while closing) continues from the current height, +never jumping to an end. A collapsed panel leaves no empty space and takes no +keyboard focus (`inert` while closed, or `visibility: hidden` once the close +has finished). Keep a panel that holds a form mounted, so form values survive +closing and reopening. Animate `grid-template-rows` from `0fr` to `1fr` (with +an inner `overflow: hidden` wrapper), or `height` to the measured content +height; never a fixed `max-height` guess. + +**A page entrance plays once per visit.** Leaving by a link and coming back, +a back/forward restore (including the bfcache) and a reload each start a +new visit. Within one visit, scrolling a block out of view and back does not +replay it. Content that has been shown must not vanish just before its +animation starts, and the page stays readable when the script is slow or +fails (section 3). + +**Entrance and repeating emphasis are separate motions.** "Appear, then +repeat 1-2-3-4" plays the entrance sequence once and then cycles the +emphasis one item at a time. When an emphasis ends, the element +returns to its resting state. Emphasising a circle or a border keeps the base design +and moves only the emphasised part. When reduced motion is on, or is +switched on while the page is in use, running effects and loops stop and +the content is usable at once: use a `prefers-reduced-motion` media rule +(`_motionReduce`), which applies the moment the preference changes, not a +value read once at load. + ## 1. Survey the page, then propose by role Walk the page's sections and repeated content before writing any motion. @@ -25,7 +96,7 @@ Choose by what a block is for, not by what can be animated: |-------|---------| | First viewport (hero, page title) | No scroll reveal. It is visible on load; at most one short settle that never starts hidden in server markup | | Section below the fold | One restrained entrance for the section's content group: short fade with a small upward move | -| Card grid, list, logo row, steps | The group enters together or with a short stagger (40-80ms per item, capped so the whole group finishes within about 400ms of stagger and one second in total) | +| Card grid, list, logo row, steps | The group enters together or with a short stagger (40-80ms per item, capped so the whole group finishes within about 400ms of stagger and one second in total). A request for a sequential entrance replaces this: one unit after another (section 0) | | Section with a painted background, image or band | The painted element stays fixed; an inner content wrapper moves | | Progress line, timeline, chart, graph | The line/graph advances in step with the items it connects: an item appears as the line reaches it, not before and not long after | | State change (tab, accordion, hover, selected) | A short `transition` on the properties that change | @@ -151,6 +222,10 @@ items animate from that: - Derive the delay from the item index (`--reveal-index`), never from a hardcoded list length, and keep the step at 40-80ms. +- A sequential group (section 0) is ``: + each item waits `index * (duration + gap)` (`--reveal-gap`, 0ms unless + set), so it starts when the previous one has finished. For row by row, + pass the row index at the current layout as `index`. - A progress line or graph shares one variable with its items. The line draws over `--reveal-line` and step `i` of `n` waits `calc(var(--reveal-line) * var(--reveal-index) / var(--reveal-count))`, so @@ -240,6 +315,35 @@ scenario below from a fresh load unless `scenarios` narrows the list: | `no-script` | the block is missing or hidden in the page served without JavaScript | | `stagger` | a step between `items` exceeds 150ms, the stagger span 450ms or the whole group 1000ms (`maxStepMs`, `maxSpanMs`, `maxTotalMs`) | | `progress-sync` | an item appears more than 200ms before or after the line reaches it (`progress` and `items` selectors) | +| `reduced-motion-toggle` | reduced motion is switched on while the block is entering, and an animation keeps running or the content stays hidden or displaced | + +What the request fixed is part of the check. On a group with `items`, set +`sequence` (`sequential`: each unit starts only after the previous one has +finished, and the group element itself must not animate; `together`; or +`overlap`, the default with the stagger bounds above), `unit` (`row` groups +the items by the rows actually laid out at the audited width; `item`, `card`, +`step` and `section` are one item each), `order` (`document` or `reverse`) +and `direction` (`from-right`, `from-left`, `from-bottom`, `from-top`, or one +per unit in play order). The `stagger` scenario then reports each unit's +start and end and fails a unit that starts before the previous one finished, +a row whose cards do not start together, the wrong order or the wrong +direction; a direction that could not be seen is unverified. + +A dropdown or accordion is a motion check of `kind: "disclosure"`: `target` +is the control that toggles it, `panel` the collapsing region, `field` +optionally a form field inside it and `after` optionally the element below +it. The check opens and closes it straight through and interrupted halfway, +and fails a collapsed panel that keeps height or keyboard focus, an open +panel that is not its content height, content below that does not follow, +an interruption that jumps instead of continuing, or a typed value lost on +closing and reopening. + +Write these checks from the record made before implementing (section 0), +and run them at a desktop and a mobile width, with slow loading, on a +revisit, by keyboard and with reduced motion. Still frames confirm the final +layout; order and timing are confirmed only from the browser playing them. +When shared motion code and page changes land in separate pull requests, +run the main checks again on the combined result. Results are never rounded up. A scenario with nothing to observe in the block (no image, no control, no items) is `not-applicable`. One that could not be @@ -253,7 +357,12 @@ mobile and a desktop width with nothing left unverified. `devup_ui_validate` reports what the source alone proves, for keyframes and for a motion library alike: `ssr-hidden-reveal`, `reveal-replays`, `reveal-moves-background`, `stagger-too-long`, `motion-without-reduced-motion` -and, as information, `entrance-uses-motion-library`. +(for entrances and for repeating emphasis loops) and, as information, +`entrance-uses-motion-library`. Inside a `data-reveal-sequence="sequential"` +group it reports `sequence-overlaps` (a per-item delay shorter than the +item's duration) and `sequence-animates-container` (the group itself +animates). For a disclosure it reports `disclosure-collapsed-focusable`, +`disclosure-fixed-max-height` and, as information, `disclosure-unmounts-form`. Still a judgement, not a measurement: whether motion suits the block at all. Report each item as verified or explicitly unverified, with the width it was diff --git a/crates/devup-mcp/src/server/skills/devfive-frontend/references/delivery-quality.md b/crates/devup-mcp/src/server/skills/devfive-frontend/references/delivery-quality.md index 9a1f803f..79ea70a6 100644 --- a/crates/devup-mcp/src/server/skills/devfive-frontend/references/delivery-quality.md +++ b/crates/devup-mcp/src/server/skills/devfive-frontend/references/delivery-quality.md @@ -370,7 +370,11 @@ before claiming completion. The installed copy of this document is | `motion-candidates-and-safe-progressive-enhancement` | Each `behaviorPlan` motion candidate (marquee, count-up, step cycle, sliding highlight, section entrance) is implemented as an enhancement of readable server markup | | `default-entrance-and-transition-motion` | Restrained entrance and transition motion is proposed by role and implemented without being asked; the user's stated design wins | | `devup-ui-static-keyframes-motion` | Motion is Devup UI `keyframes()` and CSS animation props extracted to static CSS; no animation library for entrances or transitions | -| `one-shot-reveals-without-ssr-flash` | A reveal completes when its content is visible and never replays, re-hides or flashes on hydration, reload, back/forward or client navigation | +| `one-shot-reveals-without-ssr-flash` | A reveal completes when its content is visible and never replays, re-hides or flashes on hydration, reload, back/forward or client navigation. A page entrance plays once per visit: leaving by a link and coming back, a back/forward (bfcache) restore and a reload are new visits; scrolling away and back within a visit does not replay; nothing already shown vanishes before its animation, and content is readable when the script is slow or fails | +| `motion-request-first` | Before implementing, each motion's target, unit, order, direction, trigger and timing are recorded from the request's wording; a request-specific instruction overrides every default (`animation.md`, "Read the request first"). The unit comes from the wording (card, row, section; a numbered list by step, side-by-side cards by card), a card's contents move together, rows are the rows actually laid out at that width, and play order and movement direction are kept separately | +| `sequential-no-overlap` | "Sequentially" means each unit finishes before the next starts: no parent-container animation and no overlapping stagger unless overlap is asked for; a progress line keeps its stated condition (drawn first, or a card as the line reaches each number) | +| `disclosure-height-and-focus` | Dropdowns and accordions open and close to their content height with the content below following, continue from the current height when interrupted, take no space and no keyboard focus while collapsed, and keep form values | +| `emphasis-reduced-motion` | A repeating emphasis is its own motion that starts after the entrance sequence, moves only the emphasised part and returns to the resting state; reduced motion, including when switched on mid-use, stops entrances and loops and leaves content usable | | `canonical-semantic-assets` | One asset registry, semantic file names, no duplicates or hash names | | `landing-detail-api-db-single-source` | Landing and detail values come from the same API and DB records | | `user-approved-plan-before-implementation` | The screen and project plans are confirmed only with `userApproval`: the user's own answer and, for screens, every approved URL; an agent never confirms on the user's behalf | @@ -387,6 +391,7 @@ before claiming completion. The installed copy of this document is | `animation-start-middle-end-frames` | The start, middle and end frame of each entrance, as measured opacity/transform values with a screenshot of each, at a mobile and a desktop width | | `motion-trigger-reentry-history-and-image-failure` | Trigger position, re-entry, fast scroll, reload, history, bfcache, client navigation, delayed and failed images, focus, reduced motion and no JavaScript for each reveal | | `stagger-total-and-progress-sync-timing` | For a group: stagger step, span and total time within bounds; for a progress line: each item within tolerance of the line reaching it | +| `mid-sequence-motion` | Measured in a real browser while playing: item 2 has not started while item 1 enters, each unit follows the previous one, units and directions are as requested, disclosures open, close and interrupt correctly, at desktop and mobile layouts, with slow loading, a revisit, keyboard use and reduced motion switched on mid-use (`sequence`, `reduced-motion-toggle`, `disclosure` motion checks). When shared motion code and page changes land in separate pull requests, the main motions are verified again on the combined result | | `changed-empty-and-failing-api` | Changed, empty and failing API states, against a disposable database | | `all-public-assets-and-persisted-url-references` | Every public asset and every persisted URL reference resolves | diff --git a/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md b/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md index be6a434f..38b0ac04 100644 --- a/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md +++ b/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md @@ -686,3 +686,16 @@ Apply `developmentContract` and `behaviorPlan` on every export. Read the bundled persistent server layouts, state/colour semantics, motion, all public assets and DB-to-API-to-UI verification. Inferred motion is an implementation requirement, not a claim that static generated markup is already interactive. + +Motion the request describes is recorded before it is implemented - target, +unit, order, direction, trigger and timing, from the request's own words - and +the request wins over every default (`devfive-frontend/references/animation.md`, +section 0). "Sequentially" means each unit finishes before the next starts; +dropdowns and accordions follow their content height, survive interruption and +leave no focus or space while closed; a page entrance plays once per visit; +emphasis loops are separate from the entrance and stop under reduced motion, +also when it is switched on mid-use. Write the `devup_runtime_audit` motion +checks from that record (`sequence`, `unit`, `order`, `direction`, +`reduced-motion-toggle`, `kind: "disclosure"`) and run them again on the +combined result when shared motion code and page changes land in separate +pull requests. diff --git a/crates/devup-mcp/src/server/skills/manifest.json b/crates/devup-mcp/src/server/skills/manifest.json index c4ea20df..000f5358 100644 --- a/crates/devup-mcp/src/server/skills/manifest.json +++ b/crates/devup-mcp/src/server/skills/manifest.json @@ -76,13 +76,13 @@ }, { "path": "references/delivery-quality.md", - "bytes": 29079, - "sha256": "51c4c81fb36a969f708696ab9becf15de5cc458ac50975ea496a5aa1546b80e8" + "bytes": 31255, + "sha256": "028b134597b68426832ab9638283f60458c6a2f4eb64c179d59817e3c28d1b01" }, { "path": "references/animation.md", - "bytes": 13837, - "sha256": "5cac2098bd4be5302e0b018e955b5ceb8ae83810d511b9bf99161b601d4d7a0e" + "bytes": 20806, + "sha256": "4c1d051299f1936308df0851e167bd295a8d58f645335af02147b8a7110c3d49" } ], "sourceUrl": "https://github.com/dev-five-git/devup-mcp/blob/HEAD/crates/devup-mcp/src/server/skills/devfive-frontend", @@ -99,8 +99,8 @@ "documents": [ { "path": "SKILL.md", - "bytes": 48735, - "sha256": "5fe7b752fb5f830e8efda50cb33e1e6ae23db22d6725544139d4fc70401f83d3" + "bytes": 49585, + "sha256": "5dc245ee16bb990cddbc19a9a7c6639ba657505f80050305d39e9ed54d24e6bb" } ], "sourceUrl": "https://github.com/dev-five-git/devup-mcp/blob/HEAD/crates/devup-mcp/src/server/skills/devup-implementation-plan", diff --git a/crates/devup-mcp/src/server/text/devup-runtime-audit.md b/crates/devup-mcp/src/server/text/devup-runtime-audit.md index d77d4d5a..49dfc486 100644 --- a/crates/devup-mcp/src/server/text/devup-runtime-audit.md +++ b/crates/devup-mcp/src/server/text/devup-runtime-audit.md @@ -7,7 +7,7 @@ Rendered completeness requires the frame height (default minimum 90%), listed se Selection proof: expect.selected requires semantic group/target locators, attribute aria-current or aria-selected, a true selection value, and 1..12 captured CSS paint values in styles. It checks exactly one visible selected control, actual computed paint, containment and optional content visibility. Use press(target,value) and back/forward/reload(no target/value) steps to test keyboard and browser history. A URL change or stale ARIA alone never proves visual selection. Markup also detects short-page footer gaps. -Motion checks measure intermediate values for marquee, count-up, steps, tabs and reveal, with explicit candidateId and semantic selectors. A reveal check measures an entrance whatever produced it. `motion.target` is the element that carries the entrance (the inner wrapper, not the painted section) and `motion.items` names the animated children of a group. It scrolls toward the target in small steps and records `measured.trigger` and `measured.frames` (start, middle and end opacity/transform, each with a screenshot): a scroll-linked entrance (CSS `animation-timeline: view()`) must be fully shown once the block is inside the viewport or half a screen of it is showing; a timed one must start no more than 1px off screen and not after the block has been fully visible for 400ms. It then scrolls the target out of view and back: content re-hidden while away, a replay on re-entry, or a target that cannot leave the viewport at that size (re-entry unobserved) fails. Then every scenario runs from a fresh load unless `motion.scenarios` narrows the list, each reported under `measured.scenarios`: fast-scroll (sample the first on-screen frames through the settled entrance; fail if shown content subsequently disappears or moves), reload and history (reload, or leave and go back, with the target on screen: it must never be hidden or displaced), bfcache (the same after a real back/forward-cache restore, in a browser started with the cache on), client-nav (follow `motion.navigate`, a link, and go back in the same document), image-delay and image-failure (images inside the target stalled or aborted: it still reveals at its reserved height), focus (a focused control inside an unrevealed target is painted, on screen and not trapped; `motion.focus` selects the control), reduced-motion (never hidden or moved while entering under prefers-reduced-motion), no-script (present and painted in the page served without JavaScript), stagger (steps between `motion.items` at most 150ms, stagger span 450ms, whole group 1000ms, or `maxStepMs`/`maxSpanMs`/`maxTotalMs`), progress-sync (with `motion.progress` and `motion.items`: each item within 200ms, or `motion.syncToleranceMs`, of the progress line reaching it). A scenario with nothing to observe in the block (no image, no control, no items) is `not-applicable`. One that could not be observed (no link named, a page the browser does not keep in bfcache, scroll not restored) is `unverified` and the check is `inconclusive`, never a pass; with an explicit `scenarios` list an unobservable scenario fails and the scenarios left out are listed in `measured.scenariosNotRun`. Ingest returns `motionEvidence`: one row per motion check per width (frames, trigger, re-entry, scenario statuses, stagger and progress timings, and what is unverified) and one line per candidate, `verified` only with a passing check at a mobile (<=767px) and a desktop (>=1024px) width and nothing left unverified. A no-clipped-content exception requires allowedMarquees naming one verified horizontal translating track; animation elsewhere never exempts a clipped container. Data-binding checks mutate only an explicitly isolated disposable SQLite database and compare baseline, changed, empty and error states across landing/list/detail. Completion independently rechecks source and artifact hashes, SQL snapshots and all required URL/width/motion/binding coverage. It always writes the canonical .devup/completion.json, optionally copying it to outputPath. Exported source alone never establishes application completion; see the completion guide for the staged contract. +Motion checks measure intermediate values for marquee, count-up, steps, tabs, reveal and disclosure, with explicit candidateId and semantic selectors. A reveal check measures an entrance whatever produced it. `motion.target` is the element that carries the entrance (the inner wrapper, not the painted section) and `motion.items` names the animated children of a group. It scrolls toward the target in small steps and records `measured.trigger` and `measured.frames` (start, middle and end opacity/transform, each with a screenshot): a scroll-linked entrance (CSS `animation-timeline: view()`) must be fully shown once the block is inside the viewport or half a screen of it is showing; a timed one must start no more than 1px off screen and not after the block has been fully visible for 400ms. It then scrolls the target out of view and back: content re-hidden while away, a replay on re-entry, or a target that cannot leave the viewport at that size (re-entry unobserved) fails. Then every scenario runs from a fresh load unless `motion.scenarios` narrows the list, each reported under `measured.scenarios`: fast-scroll (sample the first on-screen frames through the settled entrance; fail if shown content subsequently disappears or moves), reload and history (reload, or leave and go back, with the target on screen: it must never be hidden or displaced), bfcache (the same after a real back/forward-cache restore, in a browser started with the cache on), client-nav (follow `motion.navigate`, a link, and go back in the same document), image-delay and image-failure (images inside the target stalled or aborted: it still reveals at its reserved height), focus (a focused control inside an unrevealed target is painted, on screen and not trapped; `motion.focus` selects the control), reduced-motion (never hidden or moved while entering under prefers-reduced-motion), reduced-motion-toggle (switched on mid-entrance: every running animation in the block stops and the content is shown in place), no-script (present and painted in the page served without JavaScript), stagger (steps between `motion.items` at most 150ms, stagger span 450ms, whole group 1000ms, or `maxStepMs`/`maxSpanMs`/`maxTotalMs`), progress-sync (with `motion.progress` and `motion.items`: each item within 200ms, or `motion.syncToleranceMs`, of the progress line reaching it). What the request fixed is stated with `motion.items` and judged by stagger: `sequence` (`sequential`: each unit starts only after the previous one finished and the group element itself never animates; `together`; `overlap`, the default, with the bounds above), `unit` (`row` groups items by the rows laid out at the audited width; `item`/`card`/`step`/`section` are one item each), `order` (`document` or `reverse`) and `direction` (`from-right`, `from-left`, `from-bottom`, `from-top`, or one per unit in play order); `measured.scenarios.stagger.contract` lists each unit's start and end, failures and what could not be seen. A disclosure check (`kind: "disclosure"`, `target` the toggle control, `panel` the collapsing region, optional `field` and `after`) opens and closes it straight through and interrupted halfway and fails a collapsed panel with height or keyboard-focusable content, an open panel that is not its content height, a following element that does not move with it, an interruption that jumps, or a typed value lost by closing and reopening. A scenario with nothing to observe in the block (no image, no control, no items) is `not-applicable`. One that could not be observed (no link named, a page the browser does not keep in bfcache, scroll not restored) is `unverified` and the check is `inconclusive`, never a pass; with an explicit `scenarios` list an unobservable scenario fails and the scenarios left out are listed in `measured.scenariosNotRun`. Ingest returns `motionEvidence`: one row per motion check per width (frames, trigger, re-entry, scenario statuses, stagger and progress timings, and what is unverified) and one line per candidate, `verified` only with a passing check at a mobile (<=767px) and a desktop (>=1024px) width and nothing left unverified. A no-clipped-content exception requires allowedMarquees naming one verified horizontal translating track; animation elsewhere never exempts a clipped container. Data-binding checks mutate only an explicitly isolated disposable SQLite database and compare baseline, changed, empty and error states across landing/list/detail. Completion independently rechecks source and artifact hashes, SQL snapshots and all required URL/width/motion/binding coverage. It always writes the canonical .devup/completion.json, optionally copying it to outputPath. Exported source alone never establishes application completion; see the completion guide for the staged contract. Regression contracts run in a fresh Chromium context and are plan-bound. Use checks kind "regression" with regression.kind "sticky-header", "inquiry", "image-handoff" or "font-stability". The header checks both scroll directions, painted divider, logo/home action, default/hover/pressed link decoration and reduced motion. Inquiry checks approved description text and CTA, actual native/custom/radio selection, pressed paint, animated form validation and a mailto draft containing the selected synthetic fields. It observes the draft opening and does not send email. Image-handoff delays the next image response and its decode promise and samples visible frames. Font-stability delays explicitly listed same-origin preloads and measures first-viewport movement and CLS. The checked selectors match rendered application semantics. Item widths restrict the contract to its planned viewports. Use a "scroll" step with a semantic locator to capture a scrolled state. For Figma sections (including a header state or a hero image), add a capture check with a native node PNG reference and the exact nodeId. Set reference.maxLuminanceDelta when a mean brightness difference matters independently of changed-pixel ratio. Bind affected route/screenId/width/nodeId combinations in completion.requiredVisualStates, and required browser contracts in completion.requiredRegressions (routePath, screenId, width, kind). A different state at the same URL and width cannot satisfy those obligations. diff --git a/crates/devup-mcp/src/server/text/devup-ui-validate.md b/crates/devup-mcp/src/server/text/devup-ui-validate.md index 4b8176a7..cf4c97d0 100644 --- a/crates/devup-mcp/src/server/text/devup-ui-validate.md +++ b/crates/devup-mcp/src/server/text/devup-ui-validate.md @@ -1,6 +1,6 @@ Validate DevupUI TSX against a project's real devup.json: unknown $token references, hardcoded colors/lengths, unknown props on Box/Flex/Text/Center/Grid/Image, and non-static values inside css()/globalCss()/keyframes() calls. `ok` is decided by severity, not by count: errors fail, and `strict: true` also fails warnings. Hardcoded values with exact matching tokens are warnings with token advice; unmatched values are info without token advice and never fail strict mode. `okReason` distinguishes clean, clean-unverified-tokens, info-only, warnings-only, warnings-and-info, strict-warnings, and error-violations; `clean-unverified-tokens` means no violation was found but no devup.json was resolved, so the $token references this code makes were never checked. With paths or files, each source is checked against the nearest devup.json above it, so one call over a repository of several apps uses each app's own theme; `tokens.scopes` lists each theme with its file and reference counts, `tokens.verification` is verified, partial or skipped, and files no devup.json governs are named in `themeGuardrail.unverifiedPaths` and never counted as checked (`themeAvailable` and `tokens.unknownTokenCheckRan` are true only when every file was checked). A module-level const of the same file holding a literal or a keyframes()/css() name is a static value inside css()/globalCss()/keyframes() (`css({ animationName: spin })`); imports, parameters and call results remain `runtime-value`. A single tsx has no location, so at a repository root with several themes its tokens stay unverified unless sourceName gives its relative path (apps/front/src/Hero.tsx): the nearest devup.json above that location is then used and named in `tokens.devupJson`; the named file is never opened. Supplying neither tsx nor files is rejected rather than answered `clean`. Structural rules (file-placement, one-component-per-file, client-boundary, inline-style, react-query-states) run only in `files` bundle mode; framework-required default exports (page, layout, loading, error, not-found, template, and the metadata conventions) are exempt from file-placement. With projectRoot, a maskImage whose public SVG paints more than one colour warns `multicolor-mask` (use ), and a root-relative asset URL (src or url(...)) with no file under any public directory is an error (`asset-missing`), always failing `ok`. `themeNotes` summarizes each encountered empty token category once. Site completeness: an interactive element (as=a/button, Link, button, onClick) with no _hover or _focusVisible is a warning (interactive-states), one with no focus style is a warning (focus-style), too much motion - over 400ms, scale above 1.05, infinite - is a warning (too-much-motion), an icon-only button without aria-label is a warning (icon-button-label); a button with no _active, a _hover with no transition, motion with no _motionReduce and a nav link with no aria-current are info (button-active, hover-transition, motion-reduce, nav-current); a page or layout with no metadata export is a warning (page-metadata, files mode), and with projectRoot an app with no icon or favicon is a warning (app-icon). Navigation rules also report unmapped action candidates/accessibility warnings, missing static App Router href errors when projectRoot inventory is complete, and literal active-state info. Dynamic hrefs/custom routing and incomplete bundles remain unverified. Optional renderedHtml reports captured anchor counts separately from source coverage; neither proves runtime behavior. `checkedTokens` counts references and `availableTokenCount` counts definitions; they are not a ratio. Supply sectionCoverage from outputResults.tsx.sectionCoverage (or frames[].outputResults.tsx.sectionCoverage) to report omitted sections, images, masks and backgrounds as section-coverage errors. This compares literal JSX node identity and asset references across the supplied sources; it does not prove runtime visibility or component use. Omitted sectionCoverage leaves design coverage unverified. Default detail is summary: compact findings merged by source/rule/message (count for repeats), at most 100 rows, severity counts and layoutRiskCount. Use detail:"full" for all diagnostics including navigation and verificationScope. paths accepts files or recursive directories inside projectRoot, exclusive with tsx/files, up to 512 source files and 8 MiB; it runs bundle structural checks with the disk themes (nearest devup.json per file) and reports pathsRead. Directory reads skip generated and hidden directories. Supplied files retain their 64-file/1 MiB limits and never read their theme from disk; several supplied devup.json files each govern their own directory. -Entrance motion, from source alone (warnings), read in both styles - Devup UI static keyframes (keyframes() constants or inline calls, animationName/animation, animationTimeline, animationRange, animationDelay, selectors, in JSX props and in css()/styled objects) and a motion library (motion.* and components built with motion.create()/motion() in the same file). `ssr-hidden-reveal` - content that is invisible until something other than CSS shows it: a keyframes entrance on an element that itself rests at opacity 0 or visibility hidden, or is paused on its hidden first frame, or an element hidden until a selector keyed on a script-set attribute or class shows it; an always-rendered motion.* element whose initial (object, or a named variant declared on the same element) is opacity 0. Elements inside AnimatePresence or a conditional render are client-mounted and exempt. `reveal-replays` - a view-timeline entrance (animationTimeline="view()") with no animationRange that ends inside the entry (none, cover, contain, exit, or more than cover 50%), so the block is part-transparent mid-screen and fades out as it leaves; an IntersectionObserver callback that writes isIntersecting into a class, attribute or style (info when it merely never calls unobserve/disconnect); whileInView without viewport={{ once: true }} (useInView with no once/triggerOnce option is info, since its purpose is not visible). `stagger-too-long` - a per-item step above 150ms: animationDelay/transitionDelay of calc(var(--i) * step), a template of index * step, staggerChildren, or delay: index * step. `reveal-moves-background` - the element that carries the entrance (keyframes or whileInView) also paints a background, on itself or through its css() class, so the section paint moves with its content; a looping animation is not an entrance. `entrance-on-static-content` - an entrance on nav, header, footer, form, a form field, a label or a paragraph (by tag, as=, or motion.tag); `entrance-per-element` (info) - an entrance on a heading, button or link rather than on the content group. `motion-without-reduced-motion` (paths/files only) - entrance motion while no validated source, nor projectRoot/src in paths mode, handles reduced motion (a prop or key such as _motionReduce or _motionSafe, a prefers-reduced-motion media rule, useReducedMotion, MotionConfig reducedMotion; a comment or an unused import does not count). `entrance-uses-motion-library` (info, once per file) - an always-rendered entrance is driven by a runtime animation library where Devup UI keyframes would be static CSS. Keyframes declared in another module, values built elsewhere and options passed by reference cannot be read and are not reported. Trigger timing, intermediate frames, re-entry, history, bfcache, image loading and stagger timing are runtime evidence, measured by devup_runtime_audit, not checked here. +Entrance motion, from source alone (warnings), read in both styles - Devup UI static keyframes (keyframes() constants or inline calls, animationName/animation, animationTimeline, animationRange, animationDelay, selectors, in JSX props and in css()/styled objects) and a motion library (motion.* and components built with motion.create()/motion() in the same file). `ssr-hidden-reveal` - content that is invisible until something other than CSS shows it: a keyframes entrance on an element that itself rests at opacity 0 or visibility hidden, or is paused on its hidden first frame, or an element hidden until a selector keyed on a script-set attribute or class shows it; an always-rendered motion.* element whose initial (object, or a named variant declared on the same element) is opacity 0. Elements inside AnimatePresence or a conditional render are client-mounted and exempt. `reveal-replays` - a view-timeline entrance (animationTimeline="view()") with no animationRange that ends inside the entry (none, cover, contain, exit, or more than cover 50%), so the block is part-transparent mid-screen and fades out as it leaves; an IntersectionObserver callback that writes isIntersecting into a class, attribute or style (info when it merely never calls unobserve/disconnect); whileInView without viewport={{ once: true }} (useInView with no once/triggerOnce option is info, since its purpose is not visible). `stagger-too-long` - a per-item step above 150ms: animationDelay/transitionDelay of calc(var(--i) * step), a template of index * step, staggerChildren, or delay: index * step. `reveal-moves-background` - the element that carries the entrance (keyframes or whileInView) also paints a background, on itself or through its css() class, so the section paint moves with its content; a looping animation is not an entrance. `entrance-on-static-content` - an entrance on nav, header, footer, form, a form field, a label or a paragraph (by tag, as=, or motion.tag); `entrance-per-element` (info) - an entrance on a heading, button or link rather than on the content group. `motion-without-reduced-motion` (paths/files only) - entrance motion, or an emphasis animation that repeats forever (a rotation-only spinner excepted), while no validated source, nor projectRoot/src in paths mode, handles reduced motion (a prop or key such as _motionReduce or _motionSafe, a prefers-reduced-motion media rule, useReducedMotion, MotionConfig reducedMotion; a comment or an unused import does not count). `entrance-uses-motion-library` (info, once per file) - an always-rendered entrance is driven by a runtime animation library where Devup UI keyframes would be static CSS. Inside a group marked data-reveal-sequence="sequential" (or RevealGroup sequence="sequential", or a selector keyed on it): `sequence-overlaps` - a per-item delay step shorter than the item's own duration, so items overlap where the request asked for one after another (stagger-too-long does not apply there); `sequence-animates-container` - the group element itself carries the entrance. Disclosures: `disclosure-collapsed-focusable` - a panel whose h/height/maxH/maxHeight/gridTemplateRows switches to 0 keeps links, buttons or fields with no inert, hidden or switched visibility/display; `disclosure-fixed-max-height` - it opens to a fixed max-height instead of its content height; `disclosure-unmounts-form` (info) - `open && ` with form fields, so closing discards typed values. Keyframes declared in another module, values built elsewhere and options passed by reference cannot be read and are not reported. Trigger timing, intermediate frames, re-entry, history, bfcache, image loading and stagger timing are runtime evidence, measured by devup_runtime_audit, not checked here. `link-underline` warns when a native anchor, next/link (including import aliases), or polymorphic link has no explicit textDecoration. Set textDecoration="none" on the link or globalCss({ a: { textDecoration: 'none', color: 'inherit' } }); reset-css does not remove anchor underlines. Parsed globalCss anchor rules in the supplied bundle suppress this warning; paths mode also checks projectRoot/src within the source read limits. Hover-only decoration does not reset the resting state. `marquee-static` is informational: long single-line JSX text with at least three repeated separators and no keyframes/animation in the same file suggests a static scrolling strip. This is heuristic, not proof of animation intent or runtime behavior. diff --git a/crates/devup-mcp/tests/export_project_theme.rs b/crates/devup-mcp/tests/export_project_theme.rs index 14f044cb..8a3a56ba 100644 --- a/crates/devup-mcp/tests/export_project_theme.rs +++ b/crates/devup-mcp/tests/export_project_theme.rs @@ -202,12 +202,12 @@ async fn export_context_summarizes_a_large_project_under_fifteen_kib() -> anyhow let contract = &result["developmentContract"]; assert_eq!( contract["requirements"].as_array().map(Vec::len), - Some(23), + Some(27), "{contract}" ); assert_eq!( contract["completionEvidence"].as_array().map(Vec::len), - Some(8), + Some(9), "{contract}" ); for restored in [ diff --git a/crates/devup-mcp/tests/runtime_audit_tool.rs b/crates/devup-mcp/tests/runtime_audit_tool.rs index 0b9bc63b..3c1470c5 100644 --- a/crates/devup-mcp/tests/runtime_audit_tool.rs +++ b/crates/devup-mcp/tests/runtime_audit_tool.rs @@ -176,7 +176,7 @@ async fn consumer_template_is_allowlisted_and_missing_acquisitions_never_pass() assert!(!failed, "{planned}"); assert_eq!(planned["template"]["executed"], false); assert_eq!(planned["dimensionReferences"][0]["status"], "unverified"); - assert_eq!(planned["template"]["files"].as_array().unwrap().len(), 16); + assert_eq!(planned["template"]["files"].as_array().unwrap().len(), 18); let markup = std::fs::read_to_string(root.join("consumer-audit/markup-checks.mjs"))?; assert!(markup.contains("collectMarkup")); let runner = std::fs::read_to_string(root.join("consumer-audit/run.mjs"))?; diff --git a/harness/runtime-audit/disclosure-checks.mjs b/harness/runtime-audit/disclosure-checks.mjs new file mode 100644 index 00000000..62d8e3d4 --- /dev/null +++ b/harness/runtime-audit/disclosure-checks.mjs @@ -0,0 +1,111 @@ +// Disclosure (dropdown, accordion) check. It clicks the control and measures +// the panel's rendered height per frame, opening and closing straight through +// and interrupted halfway, then judges with evaluateDisclosure: the collapsed +// panel takes no space and no keyboard focus, the open panel is its content's +// height, what follows it moves with it, an interruption continues from the +// current height, and a typed value survives closing and reopening. +// +// Clicks and frame sampling run inside the page, so the time between a click +// and the first measured frame is a frame, not a round trip to the browser. +import { evaluateDisclosure } from './sequence-checks.mjs'; + +const FOCUSABLE = 'a[href],button,input,select,textarea,summary,[tabindex]:not([tabindex="-1"]),[contenteditable="true"]'; +const PROBE_VALUE = 'devup-disclosure-check'; + +function installDisclosureLibrary() { + if (window.__devupDisclosure) return; + const frame = () => new Promise(resolve => requestAnimationFrame(resolve)); + const height = node => node.getBoundingClientRect().height; + // Clicks the control, then records the panel's height every frame for + // `ms`; with `interruptAt`, clicks again that many ms in and records the + // height at that moment as `mid`. + const run = async (control, panel, ms, interruptAt) => { + control.click(); + const start = performance.now(), before = [], after = []; + let mid = null; + while (performance.now() - start < ms) { + await frame(); + if (interruptAt !== null && mid === null && performance.now() - start >= interruptAt) { mid = height(panel); control.click(); continue; } + (mid === null ? before : after).push(height(panel)); + } + return { before, mid, after }; + }; + // Waits until the height has not changed for 100ms (or `limit` ms pass). + const settle = async (panel, limit) => { + const start = performance.now(); + let last = height(panel), since = performance.now(); + while (performance.now() - start < limit) { + await frame(); + const now = height(panel); + if (Math.abs(now - last) > 0.1) { last = now; since = performance.now(); } else if (performance.now() - since >= 100) break; + } + return last; + }; + window.__devupDisclosure = { run, settle }; +} + +export async function runDisclosureCheck(page, options, measured) { + const ms = options.durationMs ?? 300; + const control = page.locator(options.target), panel = page.locator(options.panel); + if (await control.count() !== 1 || await panel.count() !== 1) throw new Error('disclosure target and panel must each match exactly one element'); + await page.evaluate(installDisclosureLibrary); + const handles = { control: await control.elementHandle(), panel: await panel.elementHandle() }; + // A settled state. Focus is tried on every control inside the panel: one + // that takes it is reachable by keyboard, whatever hides it visually. + const settled = async () => { + await page.evaluate(({ panel: node, limit }) => window.__devupDisclosure.settle(node, limit), { panel: handles.panel, limit: ms + 1500 }); + return panel.evaluate((node, config) => { + const previous = document.activeElement; + const reachable = [...node.querySelectorAll(config.focusable)].filter(element => { element.focus({ preventScroll: true }); return document.activeElement === element; }).length; + if (previous instanceof HTMLElement) previous.focus({ preventScroll: true }); else document.activeElement?.blur?.(); + const follower = config.after ? document.querySelector(config.after) : null; + // Content height: the panel's own, plus whatever a wrapper inside it + // cuts off with overflow hidden/clip. A scrolling list (auto/scroll) + // keeps its overflow reachable and is not counted. + const height = node.getBoundingClientRect().height; + const clipped = [node, ...node.querySelectorAll('*')].reduce((most, element) => { + const style = getComputedStyle(element); + return ['hidden', 'clip'].includes(style.overflowY) ? Math.max(most, element.scrollHeight - element.clientHeight) : most; + }, 0); + return { height, contentHeight: Math.max(node.scrollHeight, height + clipped), reachable, followerTop: follower ? follower.getBoundingClientRect().top + scrollY : null }; + }, { focusable: FOCUSABLE, after: options.after ?? null }); + }; + const run = (interruptAt = null) => page.evaluate(({ control: button, panel: node, ms: duration, interruptAt: at }) => window.__devupDisclosure.run(button, node, duration, at), { ...handles, ms: ms + 300, interruptAt }); + + // Closed first. The control's aria-expanded says which state it is in; + // without it, a panel with height is taken to be open. + const expanded = await control.getAttribute('aria-expanded'); + let start = await settled(); + if (expanded === 'true' || (expanded === null && start.height > 1)) { await run(); start = await settled(); } + const collapsed = [start]; + // Open straight through, frame by frame. + const opening = (await run()).before; + const open = await settled(); + const follower = options.after && start.followerTop !== null && open.followerTop !== null ? { closedTop: start.followerTop, openTop: open.followerTop, delta: open.followerTop - start.followerTop } : null; + let field = null; + if (options.field) { + await page.locator(options.field).fill(PROBE_VALUE); + field = { expected: PROBE_VALUE }; + } + // Closing, reopened 40% of the way: continues from the current height. + const closing = await run(ms * 0.4); + await settled(); + // Closed, then opening, closed again 40% of the way. + await run(); collapsed.push(await settled()); + const reopening = await run(ms * 0.4); + collapsed.push(await settled()); + if (field) { + await run(); await settled(); + field.actual = await page.locator(options.field).inputValue().catch(() => null); + } + const observed = { + collapsed, open, opening, follower, field, + interrupted: { close: { mid: closing.mid, after: closing.after, end: open.height }, open: { mid: reopening.mid, after: reopening.after, end: 0 } }, + }; + measured.disclosure = observed; + const verdict = evaluateDisclosure(observed); + measured.unverified = verdict.unverified; + if (verdict.status === 'fail') return { status: 'fail', reason: `Disclosure: ${verdict.failures.join('; ')}`, measured }; + if (verdict.status === 'unverified') return { status: 'inconclusive', reason: `Disclosure passed what was observed; unverified: ${verdict.unverified.join('; ')}`, measured }; + return { status: 'pass', reason: 'Collapsed with no space or focus, opened to content height, continued from the current height when interrupted, and kept form values', measured }; +} diff --git a/harness/runtime-audit/motion-checks.mjs b/harness/runtime-audit/motion-checks.mjs index 474edf13..0425b99b 100644 --- a/harness/runtime-audit/motion-checks.mjs +++ b/harness/runtime-audit/motion-checks.mjs @@ -1,6 +1,7 @@ // Motion checks observe actual rendered geometry and state, never a screenshot // or the presence of an animation declaration. Selectors are semantic app targets. import { REVEAL_SCENARIOS, runRevealCheck } from './reveal-checks.mjs'; +import { runDisclosureCheck } from './disclosure-checks.mjs'; export function installMotionProbe(configurations) { const records = Object.create(null), observed = new Map(); @@ -26,9 +27,11 @@ export { REVEAL_SCENARIOS }; export async function runMotionCheck(page, options, context = {}) { const measured = { kind: options?.kind, candidateId: options?.candidateId, samples: [] }; try { - if (!options || typeof options.target !== 'string' || !['marquee','count-up','steps','tabs','reveal'].includes(options.kind)) throw new Error('motion needs kind and semantic target'); + if (!options || typeof options.target !== 'string' || !['marquee','count-up','steps','tabs','reveal','disclosure'].includes(options.kind)) throw new Error('motion needs kind and semantic target'); const target = page.locator(options.target), ms = options.durationMs ?? 600; if (!(ms >= 80 && ms <= 10000) || await target.count() !== 1) throw new Error('motion duration/target is invalid or ambiguous'); + // A dropdown or accordion: clicked and measured by its own module. + if (options.kind === 'disclosure') return await runDisclosureCheck(page, options, measured); const sample = () => target.evaluate((node, config) => { const rect = element => { const box=element.getBoundingClientRect();return {x:box.x,y:box.y,width:box.width,height:box.height}; }; const list = selector => [...node.querySelectorAll(selector)]; diff --git a/harness/runtime-audit/reveal-checks.mjs b/harness/runtime-audit/reveal-checks.mjs index 49d11908..b3e17813 100644 --- a/harness/runtime-audit/reveal-checks.mjs +++ b/harness/runtime-audit/reveal-checks.mjs @@ -15,10 +15,12 @@ // observed is `unverified` (the check is then `inconclusive`, never `pass`), // and a scenario with nothing to observe in this block is `not-applicable`. +import { evaluateReducedMotionToggle, evaluateSequence } from './sequence-checks.mjs'; + /** Every scenario, in the order they run. Each starts from a fresh load. */ export const REVEAL_SCENARIOS = [ 'fast-scroll', 'reload', 'history', 'bfcache', 'client-nav', 'image-delay', 'image-failure', - 'focus', 'reduced-motion', 'no-script', 'stagger', 'progress-sync', + 'focus', 'reduced-motion', 'reduced-motion-toggle', 'no-script', 'stagger', 'progress-sync', ]; const FOCUSABLE = 'a[href],button,input,select,textarea,[tabindex]'; @@ -168,21 +170,25 @@ function installRevealLibrary() { const list = [...node.querySelectorAll(items)]; if (list.length < 2) return { verified: false, reason: 'fewer than two items matched' }; node.scrollIntoView({ block: 'center' }); - const start = performance.now(), startedAt = list.map(() => null), shownAt = list.map(() => null), hiddenOnce = list.map(() => false); - let scrollLinked = false; + const start = performance.now(), startedAt = list.map(() => null), shownAt = list.map(() => null), hiddenOnce = list.map(() => false), startShift = list.map(() => null); + let scrollLinked = false, containerAnimated = false; while (performance.now() - start < ms) { const now = performance.now() - start; + // The group element itself on a clock: its items move with it. + containerAnimated ||= node.getAnimations().some(animation => clocked(animation) && animation.playState === 'running'); list.forEach((item, index) => { - const opacity = paintedOpacity(item, node), moved = Math.abs(shiftOf(item)) > 0.1; + const opacity = paintedOpacity(item, node), matrix = new DOMMatrixReadOnly(getComputedStyle(item).transform), moved = Math.abs(matrix.m42) > 0.1 || Math.abs(matrix.m41) > 0.1; scrollLinked ||= item.getAnimations().some(animation => !clocked(animation)); - if (opacity < 0.01) { hiddenOnce[index] = true; startedAt[index] = null; shownAt[index] = null; return; } - if (hiddenOnce[index] && startedAt[index] === null) startedAt[index] = now; + if (opacity < 0.01) { hiddenOnce[index] = true; startedAt[index] = null; shownAt[index] = null; startShift[index] = { x: matrix.m41, y: matrix.m42 }; return; } + if (hiddenOnce[index] && startedAt[index] === null) { startedAt[index] = now; if (moved || !startShift[index]) startShift[index] = { x: matrix.m41, y: matrix.m42 }; } if (opacity === 1 && !moved) { if (shownAt[index] === null) shownAt[index] = now; } else shownAt[index] = null; }); if (shownAt.every(value => value !== null) && now > 100 && hiddenOnce.some(Boolean)) break; await frame(); } - return { verified: true, scrollLinked, observed: hiddenOnce.filter(Boolean).length, startedAt, shownAt }; + // Layout positions once settled: the rows the layout produced at this width. + const boxes = list.map(item => { const box = item.getBoundingClientRect(), matrix = new DOMMatrixReadOnly(getComputedStyle(item).transform); return { top: box.top - matrix.m42 + scrollY, left: box.left - matrix.m41 }; }); + return { verified: true, scrollLinked, observed: hiddenOnce.filter(Boolean).length, startedAt, shownAt, startShift, boxes, containerAnimated }; }; window.__devupReveal = { frame, sample, shown, intermediate, approach, enter, watch, timeItems }; @@ -201,6 +207,9 @@ async function library(page) { */ export async function runRevealCheck(page, options, measured, context = {}) { const ms = options.durationMs ?? 600, items = options.items ?? null, settle = options.settleMs ?? 400; + // How long a group may take: a sequential one plays its units one after + // another, so it is given longer unless the plan bounds it. + const groupMs = options.maxTotalMs ?? (options.sequence === 'sequential' ? 4000 : 1000); const locate = tab => tab.locator(options.target); const target = locate(page); const sampleOn = async tab => { await library(tab); return locate(tab).evaluate((node, selector) => window.__devupReveal.sample(node, selector), items); }; @@ -239,7 +248,7 @@ export async function runRevealCheck(page, options, measured, context = {}) { frames = { start: await frameAt('start', start) }; await page.waitForTimeout(Math.min(120, ms * 0.25)); const middle = await take(); frames.middle = await frameAt('middle', middle); - await page.waitForTimeout(ms + 30 + (items ? options.maxTotalMs ?? 1000 : 0)); + await page.waitForTimeout(ms + 30 + (items ? groupMs : 0)); const last = await take(); frames.end = await frameAt('end', last); valid = intermediate(middle) && shown(last) && !(trigger.verified && (trigger.startedOffscreen || trigger.late)); } @@ -302,19 +311,19 @@ export async function runRevealCheck(page, options, measured, context = {}) { if (name === 'fast-scroll') { await fresh(); const observed = await target.evaluate((node, config) => window.__devupReveal.enter(node, config.items, config.ms), - { items, ms: ms + 400 + (items ? options.maxTotalMs ?? 1000 : 0) }); + { items, ms: ms + 400 + (items ? groupMs : 0) }); if (observed.visibleFrames < 2) result = unverified('fewer than two on-screen frames were available'); else { result = { ...observed, status: !observed.flash && shown(observed.sample) ? 'pass' : 'fail' }; if (observed.flash) result.reason = 'An on-screen item was shown before the entrance hid or displaced it.'; } } else if (name === 'reload' || name === 'history') { - await fresh(); await center(page); await page.waitForTimeout(ms + 150 + (items ? options.maxTotalMs ?? 1000 : 0)); + await fresh(); await center(page); await page.waitForTimeout(ms + 150 + (items ? groupMs : 0)); if (name === 'reload') await page.reload({ waitUntil: 'load' }); else { await page.goto('about:blank'); await page.goBack({ waitUntil: 'load' }); if (page.url() !== url) throw new Error('back navigation did not return to the audited URL'); } result = verdict(await watchOn(page)); } else if (name === 'bfcache') { - result = await bfcache({ page, url, viewport, sibling, center, watchOn, ms, unverified, wait: ms + 150 + (items ? options.maxTotalMs ?? 1000 : 0), launch: context.launchRestorable }); + result = await bfcache({ page, url, viewport, sibling, center, watchOn, ms, unverified, wait: ms + 150 + (items ? groupMs : 0), launch: context.launchRestorable }); } else if (name === 'client-nav') { if (typeof options.navigate !== 'string') result = unverified('motion.navigate names no same-origin link to leave the page with, so client navigation was not exercised'); else { @@ -341,7 +350,7 @@ export async function runRevealCheck(page, options, measured, context = {}) { else { const handler = async route => { if (route.request().resourceType() !== 'image') return route.continue(); if (name === 'image-failure') return route.abort(); await new Promise(resolve => setTimeout(resolve, ms + 1500)); return route.continue().catch(() => {}); }; await page.route('**/*', handler); - try { await fresh('domcontentloaded'); await center(page); await page.waitForTimeout(ms + 150 + (items ? options.maxTotalMs ?? 1000 : 0)); const value = await sampleOn(page); result = { status: shown(value) && Math.abs(value.height - height) < 1 ? 'pass' : 'fail', sample: value, reservedHeight: height }; } + try { await fresh('domcontentloaded'); await center(page); await page.waitForTimeout(ms + 150 + (items ? groupMs : 0)); const value = await sampleOn(page); result = { status: shown(value) && Math.abs(value.height - height) < 1 ? 'pass' : 'fail', sample: value, reservedHeight: height }; } finally { await page.unroute('**/*', handler); } } } else if (name === 'focus') { @@ -380,6 +389,20 @@ export async function runRevealCheck(page, options, measured, context = {}) { }, items); result = verdict(observed); } finally { await page.emulateMedia({ reducedMotion: null }); } + } else if (name === 'reduced-motion-toggle') { + // Switched on while the entrance (or a repeating emphasis) runs: + // everything stops and the content is shown in place at once. + await fresh(); await center(page); await page.waitForTimeout(Math.min(120, ms * 0.25)); + const running = () => locate(page).evaluate(node => node.getAnimations({ subtree: true }).filter(animation => animation.playState === 'running').length); + const before = { running: await running() }; + await page.emulateMedia({ reducedMotion: 'reduce' }); + try { + await page.waitForTimeout(150); + const verdict = evaluateReducedMotionToggle(before, { running: await running(), sample: await sampleOn(page) }); + // Nothing on a clock (a scroll-linked entrance, or one already + // finished): there is nothing in this block for the switch to stop. + result = verdict.status === 'unverified' ? { ...absent(verdict.reason), before } : verdict; + } finally { await page.emulateMedia({ reducedMotion: null }); } } else if (name === 'no-script') { // Server markup is the content: with scripts off the block is there // and painted. @@ -394,7 +417,7 @@ export async function runRevealCheck(page, options, measured, context = {}) { else { await fresh(); const maxStep = options.maxStepMs ?? 150, maxSpan = options.maxSpanMs ?? 450, maxTotal = options.maxTotalMs ?? 1000; - const observed = await target.evaluate((node, config) => window.__devupReveal.timeItems(node, config.items, config.ms), { items, ms: maxTotal + ms + 1500 }); + const observed = await target.evaluate((node, config) => window.__devupReveal.timeItems(node, config.items, config.ms), { items, ms: groupMs + ms + 1500 }); if (!observed.verified) result = absent(observed.reason); else if (observed.scrollLinked && observed.observed === 0) result = { status: 'not-applicable', reason: 'items are scroll-linked: their state follows position, there is no clock to bound' }; else if (observed.observed === 0) result = unverified('no item was seen hidden before appearing, so no entrance was observed'); @@ -405,8 +428,16 @@ export async function runRevealCheck(page, options, measured, context = {}) { const totalMs = finished ? Math.max(...ends) - Math.min(...starts) : null; // A frame of jitter is not a reversed order. const ordered = steps.every(step => step === null || step >= -34); - const ok = finished && ordered && steps.every(step => step === null || step <= maxStep) && spanMs <= maxSpan && totalMs <= maxTotal; - result = { status: ok ? 'pass' : 'fail', items: observed.startedAt.length, startedAt: observed.startedAt, shownAt: observed.shownAt, stepsMs: steps, spanMs, totalMs, ordered, bounds: { maxStepMs: maxStep, maxSpanMs: maxSpan, maxTotalMs: maxTotal } }; + // A sequential or together group is judged by its own rule, not + // by the short-stagger bounds; order, unit and direction are + // judged whenever the plan states them. + const own = options.sequence === 'sequential' || options.sequence === 'together'; + const bounded = own || (finished && (ordered || options.order === 'reverse') && steps.every(step => step === null || step <= maxStep) && spanMs <= maxSpan && totalMs <= maxTotal); + const stated = options.sequence || options.unit || options.order || options.direction; + const contract = stated ? evaluateSequence(observed, { sequence: options.sequence, unit: options.unit, order: options.order, direction: options.direction, maxTotalMs: options.maxTotalMs }) : null; + const status = !bounded || contract?.status === 'fail' ? 'fail' : contract?.status === 'unverified' ? (explicit ? 'fail' : 'unverified') : 'pass'; + result = { status, items: observed.startedAt.length, startedAt: observed.startedAt, shownAt: observed.shownAt, startShift: observed.startShift, stepsMs: steps, spanMs, totalMs, ordered, bounds: own ? null : { maxStepMs: maxStep, maxSpanMs: maxSpan, maxTotalMs: maxTotal }, contract: contract ?? undefined }; + if (contract?.reason && status !== 'pass') result.reason = contract.reason; } } } else if (name === 'progress-sync') { diff --git a/harness/runtime-audit/sequence-checks.mjs b/harness/runtime-audit/sequence-checks.mjs new file mode 100644 index 00000000..5bfec686 --- /dev/null +++ b/harness/runtime-audit/sequence-checks.mjs @@ -0,0 +1,174 @@ +// Pure verdicts for motion the request shapes: the order and timing of the +// units of a group, the direction each unit moves in, a preference switched +// mid-use, and a disclosure (dropdown/accordion) opening and closing. The +// browser runners in reveal-checks.mjs and disclosure-checks.mjs measure; the +// functions here only judge what was measured, so they are tested without a +// browser. + +/** How the units of a group follow each other. */ +export const SEQUENCES = ['sequential', 'overlap', 'together']; +/** What moves at once: every item on its own, or every laid-out row. */ +export const UNITS = ['item', 'card', 'step', 'section', 'row']; +/** Where a unit starts before it moves into place. */ +export const DIRECTIONS = ['from-right', 'from-left', 'from-bottom', 'from-top']; +/** The order units play in: document order or its reverse. */ +export const ORDERS = ['document', 'reverse']; + +// One frame at 30fps: a start this close to the previous end is "after it". +const FRAME_MS = 34; +// Layout tops this close are one row. +const ROW_PX = 2; + +/** + * Groups item indices into the units that move at once. `row` reads the + * rows the layout actually produced at this width (item tops, transform + * excluded); every other unit is one item. + */ +export function unitsOf(boxes, unit) { + const indices = boxes.map((_, index) => index); + if (unit !== 'row') return indices.map(index => [index]); + const rows = []; + for (const index of [...indices].sort((a, b) => boxes[a].top - boxes[b].top || boxes[a].left - boxes[b].left)) { + const row = rows.find(candidate => Math.abs(boxes[candidate[0]].top - boxes[index].top) <= ROW_PX); + if (row) row.push(index); else rows.push([index]); + } + return rows.map(row => row.sort((a, b) => a - b)); +} + +const moved = (shift, direction) => { + if (!shift) return null; + if (direction === 'from-right') return shift.x > 0.5; + if (direction === 'from-left') return shift.x < -0.5; + if (direction === 'from-bottom') return shift.y > 0.5; + if (direction === 'from-top') return shift.y < -0.5; + return null; +}; + +/** + * Judges a group's timing against what the request fixed. + * + * `observed`: per item `startedAt`/`shownAt` (ms from the trigger, null when + * not seen), `startShift` ({x, y} translation on the first visible frame), + * `boxes` (layout {top, left}) and `containerAnimated` (the group element + * itself ran a clocked animation). `options`: `sequence`, `unit`, `order`, + * `direction` (one value, or one per unit in play order) and `maxTotalMs`. + */ +export function evaluateSequence(observed, options = {}) { + const tolerance = options.toleranceMs ?? FRAME_MS; + const sequence = options.sequence ?? 'overlap'; + const failures = [], unverified = []; + const starts = observed.startedAt.map((value, index) => value ?? observed.shownAt[index] ?? null); + let units = unitsOf(observed.boxes ?? observed.startedAt.map((_, index) => ({ top: 0, left: index })), options.unit); + if (options.order === 'reverse') units = units.reverse(); + const rows = units.map(items => { + const own = items.map(index => starts[index]), ends = items.map(index => observed.shownAt[index]); + return { + items, + startMs: own.some(value => value === null) ? null : Math.min(...own), + endMs: ends.some(value => value === null) ? null : Math.max(...ends), + spreadMs: own.some(value => value === null) ? null : Math.max(...own) - Math.min(...own), + }; + }); + if (rows.some(row => row.startMs === null || row.endMs === null)) { + unverified.push('an item was never seen entering and finishing'); + } + if (observed.containerAnimated && sequence !== 'together') { + failures.push('the group element itself animates, so its items move together with it instead of one unit at a time'); + } + rows.forEach((row, index) => { + // The items of one unit (a row's cards, a card's contents) move together. + if (row.spreadMs !== null && row.items.length > 1 && row.spreadMs > tolerance) { + failures.push(`unit ${index + 1} (items ${row.items.map(item => item + 1).join(', ')}) did not start together: ${Math.round(row.spreadMs)}ms apart`); + } + if (index === 0) return; + const previous = rows[index - 1]; + if (row.startMs === null || previous.startMs === null) return; + if (sequence === 'together') return; + if (row.startMs < previous.startMs - tolerance) { + failures.push(`unit ${index + 1} started before unit ${index} (expected ${options.order === 'reverse' ? 'reverse ' : ''}document order)`); + } else if (sequence === 'sequential' && previous.endMs !== null && row.startMs < previous.endMs - tolerance) { + failures.push(`unit ${index + 1} started ${Math.round(previous.endMs - row.startMs)}ms before unit ${index} finished`); + } + }); + if (sequence === 'together') { + const known = rows.map(row => row.startMs).filter(value => value !== null); + if (known.length > 1 && Math.max(...known) - Math.min(...known) > tolerance) failures.push(`units did not start together: ${Math.round(Math.max(...known) - Math.min(...known))}ms apart`); + } + if (options.direction) { + rows.forEach((row, index) => { + const direction = Array.isArray(options.direction) ? options.direction[index] : options.direction; + if (!direction) return; + for (const item of row.items) { + const verdict = moved(observed.startShift?.[item], direction); + if (verdict === null) unverified.push(`item ${item + 1} was not seen displaced, so its direction is unknown`); + else if (!verdict) failures.push(`item ${item + 1} did not enter ${direction}`); + } + }); + } + const known = rows.filter(row => row.startMs !== null && row.endMs !== null); + const totalMs = known.length ? Math.max(...known.map(row => row.endMs)) - Math.min(...known.map(row => row.startMs)) : null; + if (options.maxTotalMs !== undefined && totalMs !== null && totalMs > options.maxTotalMs) failures.push(`the whole sequence took ${Math.round(totalMs)}ms, over ${options.maxTotalMs}ms`); + const status = failures.length ? 'fail' : unverified.length ? 'unverified' : 'pass'; + return { status, reason: failures[0] ?? unverified[0], failures, unverified, sequence, units: rows, totalMs }; +} + +const shown = sample => sample.opacity === 1 && Math.abs(sample.translate) < 0.1; + +/** + * Reduced motion switched on while the page is open: whatever was running + * stops and the content is usable at once. `before.running` counts the + * animations running in the block when the preference changed; `after` + * holds the block's sample and what still runs shortly after. + */ +export function evaluateReducedMotionToggle(before, after) { + if (!before.running) return { status: 'unverified', reason: 'nothing was animating when the preference was switched on', before, after }; + if (after.running) return { status: 'fail', reason: `${after.running} animation(s) kept running after prefers-reduced-motion was switched on`, before, after }; + if (!shown(after.sample)) return { status: 'fail', reason: 'the content stayed hidden or displaced after prefers-reduced-motion was switched on', before, after }; + return { status: 'pass', before, after }; +} + +/** + * A disclosure opened and closed, both straight through and interrupted. + * + * `observed.collapsed`: settled closed states ({height, reachable} where + * `reachable` counts focusable controls inside that took focus). + * `observed.open`: the settled open state ({height, contentHeight}). + * `observed.opening`: heights per frame while opening. + * `observed.follower`: {closedTop, openTop, delta} of the element after the + * panel, when one was named. `observed.interrupted`: for `close` (closing, + * then reopened) and `open` (opening, then closed), the height when + * interrupted, the heights after, and the expected end. + * `observed.field`: {expected, actual} when a form field was named. + */ +export function evaluateDisclosure(observed) { + const failures = [], unverified = []; + const full = observed.open?.height ?? 0; + const moments = ['', ' after closing again', ' after an interrupted open']; + for (const [index, state] of (observed.collapsed ?? []).entries()) { + if (state.height > 1) failures.push(`collapsed panel${moments[index] ?? ''} still takes ${Math.round(state.height)}px`); + if (state.reachable > 0) failures.push(`${state.reachable} control(s) inside the collapsed panel still take keyboard focus`); + } + if (!(full > 1)) failures.push('the panel did not open'); + else if (Math.abs(full - observed.open.contentHeight) > 1) failures.push(`the open panel is ${Math.round(full)}px for ${Math.round(observed.open.contentHeight)}px of content: it does not follow its content height`); + const opening = observed.opening ?? []; + if (full > 1 && !opening.some(height => height > 1 && height < full - 1)) unverified.push('no intermediate height was seen while opening (instant, or faster than a frame)'); + if (observed.follower) { + const { delta } = observed.follower; + if (Math.abs(delta - full) > 2) failures.push(`the element after the panel moved ${Math.round(delta)}px for a ${Math.round(full)}px panel`); + } + for (const [name, run] of Object.entries(observed.interrupted ?? {})) { + if (!run) continue; + if (!(run.mid > 1 && run.mid < full - 1)) { unverified.push(`the ${name} was over before it could be interrupted`); continue; } + // Frame to frame from the moment of interruption: the click can land a + // few frames late, so the whole trace is read, not only its first value. + const limit = Math.max(8, full * 0.2), trace = [run.mid, ...run.after]; + const at = trace.findIndex((value, index) => index > 0 && Math.abs(value - trace[index - 1]) > limit); + if (!run.after.length) failures.push(`nothing was measured after interrupting the ${name}`); + else if (at > 0) failures.push(`interrupting the ${name} jumped from ${Math.round(trace[at - 1])}px to ${Math.round(trace[at])}px instead of continuing from the current height`); + const last = run.after.at(-1); + if (last !== undefined && Math.abs(last - run.end) > 1) failures.push(`after interrupting the ${name} the panel ended at ${Math.round(last)}px, not ${Math.round(run.end)}px`); + } + if (observed.field && observed.field.actual !== observed.field.expected) failures.push('the form value typed in the panel was lost after closing and reopening it'); + const status = failures.length ? 'fail' : unverified.length ? 'unverified' : 'pass'; + return { status, reason: failures[0] ?? unverified[0], failures, unverified }; +} diff --git a/harness/runtime-audit/test/keyframes-motion.test.mjs b/harness/runtime-audit/test/keyframes-motion.test.mjs index 1d017c12..816fd111 100644 --- a/harness/runtime-audit/test/keyframes-motion.test.mjs +++ b/harness/runtime-audit/test/keyframes-motion.test.mjs @@ -58,8 +58,9 @@ test('the shipped Devup UI keyframes reveal builds to static CSS and passes ever assert.equal(end.opacity,1,label);assert.equal(end.translate,0,label); assert.equal(section.measured.trigger.startedOffscreen,false);assert.equal(section.measured.trigger.late,false);assert.ok(section.measured.trigger.completeRatio<=1); assert.deepEqual(section.measured.reentry,{verified:true,replayed:false,hiddenWhileAway:false}); - assert.deepEqual(section.measured.notApplicable,['stagger','progress-sync'],label);assert.deepEqual(section.measured.unverified,[],label);assert.deepEqual(section.measured.scenariosNotRun,[]); - assert.deepEqual(Object.entries(section.measured.scenarios).filter(([,result])=>result.status==='pass').map(([name])=>name),REVEAL_SCENARIOS.filter(name=>!['stagger','progress-sync'].includes(name)),label); + // Scroll-linked: nothing on a clock for a mid-use reduced-motion switch to stop. + assert.deepEqual(section.measured.notApplicable,['reduced-motion-toggle','stagger','progress-sync'],label);assert.deepEqual(section.measured.unverified,[],label);assert.deepEqual(section.measured.scenariosNotRun,[]); + assert.deepEqual(Object.entries(section.measured.scenarios).filter(([,result])=>result.status==='pass').map(([name])=>name),REVEAL_SCENARIOS.filter(name=>!['reduced-motion-toggle','stagger','progress-sync'].includes(name)),label); assert.equal(section.measured.scenarios.bfcache.restoredFromBfcache,true);assert.equal(section.measured.scenarios['client-nav'].sameDocument,true); // The same section through the marker a browser without view timelines gets: one timed play. const {report:fallback}=await audit(viewport,'/?timed',{candidateId:'section-entrance:fallback',target:'#reveal',scenarios:['fast-scroll','reload','history','image-delay','image-failure','focus','reduced-motion','no-script']}); diff --git a/harness/runtime-audit/test/motion-contract.test.mjs b/harness/runtime-audit/test/motion-contract.test.mjs new file mode 100644 index 00000000..a006450e --- /dev/null +++ b/harness/runtime-audit/test/motion-contract.test.mjs @@ -0,0 +1,156 @@ +// Request-shaped motion in a real browser: a group played one unit after +// another (by item or by laid-out row, in either order and direction), reduced +// motion switched on mid-use, and a disclosure opened, closed and interrupted. +// Each correct page passes; each page that breaks one rule fails on it. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {createServer} from 'node:http'; +import {chromium} from 'playwright'; +import {runMotionCheck} from '../motion-checks.mjs'; + +const VIEWPORTS=[{width:390,height:844},{width:1440,height:900}]; +const spacer='
    '; + +// A card group on a clock. `step` is the wait per index; `rows` gives each +// card the index of the row it is laid out in; `reverse` plays the last card +// first; `container` animates the group itself; `reduce` is `css` (a media +// rule, live) or `load` (read once at load); `pulse` adds a looping emphasis. +const group=query=> { + const step=Number(query.get('step')),duration=Number(query.get('duration')),count=Number(query.get('count')??4); + const dx=Number(query.get('dx')??0),dy=Number(query.get('dy')??16),container=query.has('container'),pulse=query.has('pulse'),reduce=query.get('reduce')??'css'; + return `${spacer} +
    ${pulse?'':''}${Array.from({length:count},(_,index)=>`
    Card ${index+1}
    `).join('')}
    +${spacer}`; +}; + +// An accordion. `good` animates grid-template-rows to the content height, +// is inert while closed and keeps its field mounted. Every other mode breaks +// exactly one of those. +const accordion=mode=>` +

    Answer

    +

    After

    `; + +async function withPages(run) { + const server=createServer((request,response)=> { + const url=new URL(request.url,'http://local'); + const body=url.searchParams.get('kind')==='accordion'?accordion(url.searchParams.get('mode')):group(url.searchParams); + response.writeHead(200,{'content-type':'text/html','cache-control':'no-cache'});response.end(body); + }); + await new Promise(done=>server.listen(0,'127.0.0.1',done)); + const browser=await chromium.launch(); + try { + const check=async(query,options,viewport=VIEWPORTS[0])=> { + const tab=await browser.newPage({viewport}); + await tab.goto(`http://127.0.0.1:${server.address().port}/?${query}`); + const report=await runMotionCheck(tab,{candidateId:`motion:${query}`,durationMs:300,settleMs:150,...options}); + await tab.close();return report; + }; + await run(check); + } finally {await browser.close();await new Promise(done=>server.close(done));} +} + +const reveal=(extra={})=>({kind:'reveal',target:'#reveal',items:'.item',durationMs:300,scenarios:['stagger'],...extra}); +const stagger=report=>report.measured.scenarios.stagger; + +test('a sequential group plays each card after the previous one finished', {timeout:600000}, async()=> { + await withPages(async check=> { + for(const viewport of VIEWPORTS) { + const sequential=await check('step=300&duration=300',reveal({sequence:'sequential'}),viewport); + assert.equal(sequential.status,'pass',JSON.stringify(stagger(sequential))); + assert.equal(stagger(sequential).contract.units.length,4); + // A 60ms stagger overlaps: card 2 starts while card 1 is still entering. + const overlapped=stagger(await check('step=60&duration=300',reveal({sequence:'sequential'}),viewport)); + assert.equal(overlapped.status,'fail',JSON.stringify(overlapped)); + assert.match(overlapped.reason,/before unit 1 finished/); + } + // The group element animating moves every card at once. + const container=stagger(await check('step=0&duration=300&container=1',reveal({sequence:'sequential'}))); + assert.equal(container.status,'fail',JSON.stringify(container)); + assert.match(container.contract.failures.join(';'),/group element itself animates/); + }); +}); + +test('rows are the rows laid out at each width, and order and direction are both kept', {timeout:600000}, async()=> { + await withPages(async check=> { + // Two rows of two at 390px, one row of four at 1440px. + for(const [viewport,rows] of [[VIEWPORTS[0],2],[VIEWPORTS[1],1]]) { + const byRow=await check('step=300&duration=300&rows=1',reveal({sequence:'sequential',unit:'row'}),viewport); + assert.equal(byRow.status,'pass',JSON.stringify(stagger(byRow))); + assert.equal(stagger(byRow).contract.units.length,rows); + } + // Card by card is not row by row on mobile. + const cardByCard=stagger(await check('step=300&duration=300',reveal({sequence:'sequential',unit:'row'}))); + assert.equal(cardByCard.status,'fail',JSON.stringify(cardByCard)); + // "Right card first, moving from right to left". + const options=reveal({sequence:'sequential',order:'reverse',direction:'from-right'}); + assert.equal((await check('step=300&duration=300&reverse=1&dx=24&dy=0',options,VIEWPORTS[1])).status,'pass'); + const wrongOrder=stagger(await check('step=300&duration=300&dx=24&dy=0',options,VIEWPORTS[1])); + assert.match(wrongOrder.reason,/started before unit/); + const wrongDirection=stagger(await check('step=300&duration=300&reverse=1&dx=-24&dy=0',options,VIEWPORTS[1])); + assert.match(wrongDirection.reason,/did not enter from-right/); + }); +}); + +test('reduced motion switched on mid-use stops the entrance and the emphasis loop', {timeout:600000}, async()=> { + await withPages(async check=> { + const options=reveal({durationMs:800,scenarios:['reduced-motion-toggle']}); + const live=await check('step=0&duration=800&pulse=1&reduce=css',options); + assert.equal(live.measured.scenarios['reduced-motion-toggle'].status,'pass',JSON.stringify(live.measured.scenarios['reduced-motion-toggle'])); + // Read once at load: switching it on later changes nothing. + const once=(await check('step=0&duration=800&pulse=1&reduce=load',options)).measured.scenarios['reduced-motion-toggle']; + assert.equal(once.status,'fail',JSON.stringify(once)); + assert.match(once.reason,/kept running/); + }); +}); + +test('an accordion collapses to nothing, opens to its content and continues when interrupted', {timeout:600000}, async()=> { + await withPages(async check=> { + const options={kind:'disclosure',target:'#toggle',panel:'#panel',field:'#field',after:'#after',durationMs:300}; + for(const viewport of VIEWPORTS) { + const good=await check('kind=accordion&mode=good',options,viewport); + assert.equal(good.status,'pass',JSON.stringify(good)); + } + for(const [mode,reason] of [ + ['focusable',/take keyboard focus/], + ['padded',/still takes 24px/], + ['capped',/does not follow its content height/], + ['jump',/jumped from/], + ['unmount',/form value .* was lost/], + ]) { + const report=await check(`kind=accordion&mode=${mode}`,options); + assert.equal(report.status,'fail',`${mode}: ${JSON.stringify(report.measured.disclosure)}`); + assert.match(report.reason,reason,mode); + } + }); +}); diff --git a/harness/runtime-audit/test/reveal.test.mjs b/harness/runtime-audit/test/reveal.test.mjs index 6e2ecf99..8bdf28ae 100644 --- a/harness/runtime-audit/test/reveal.test.mjs +++ b/harness/runtime-audit/test/reveal.test.mjs @@ -24,6 +24,8 @@ node.removeAttribute('data-hidden'); const reduce=matchMedia('(prefers-reduced-motion: reduce)').matches&&mode!=='ignores-preference'; if(mode==='good' && node.getBoundingClientRect().top>=innerHeight && !reduce) node.style.opacity='0'; const play=()=>node.animate([{opacity:0,transform:'translateY(24px)'},{opacity:1,transform:'translateY(0)'}],{duration:300,easing:'linear'}); +// Reduced motion switched on mid-use ends what is running at once. +if(mode!=='ignores-preference')matchMedia('(prefers-reduced-motion: reduce)').addEventListener('change',event=>{if(event.matches)node.getAnimations().forEach(animation=>animation.finish());}); if(mode==='image-gated'){node.style.opacity='0';node.querySelector('img').addEventListener('load',()=>{node.style.opacity='';});} if(mode==='pageshow-replay')addEventListener('pageshow',event=>{if(event.persisted)play();}); if(mode==='rehide'||mode==='replay')new IntersectionObserver(entries=>entries.forEach(entry=> { @@ -133,7 +135,7 @@ test('a one-shot reveal passes at mobile and desktop; what could not be checked const all=await check('mode=good',{},viewport); assert.equal(all.status,'inconclusive',JSON.stringify(all)); assert.deepEqual(all.measured.unverified,['client-nav']);assert.deepEqual(all.measured.notApplicable,['stagger','progress-sync']);assert.deepEqual(all.measured.scenariosNotRun,[]); - assert.deepEqual(statuses(all),{'fast-scroll':'pass',reload:'pass',history:'pass',bfcache:'pass','client-nav':'unverified','image-delay':'pass','image-failure':'pass',focus:'pass','reduced-motion':'pass','no-script':'pass',stagger:'not-applicable','progress-sync':'not-applicable'}); + assert.deepEqual(statuses(all),{'fast-scroll':'pass',reload:'pass',history:'pass',bfcache:'pass','client-nav':'unverified','image-delay':'pass','image-failure':'pass',focus:'pass','reduced-motion':'pass','reduced-motion-toggle':'pass','no-script':'pass',stagger:'not-applicable','progress-sync':'not-applicable'}); assert.equal(all.measured.scenarios.bfcache.restoredFromBfcache,true); assert.equal(all.measured.mode,'timed');assert.equal(all.measured.trigger.verified,true);assert.equal(all.measured.trigger.startedOffscreen,false);assert.ok(all.measured.trigger.offscreenPx<=1); assert.deepEqual(all.measured.reentry,{verified:true,replayed:false,hiddenWhileAway:false}); @@ -237,7 +239,9 @@ test('client navigation away and back must not replay content that is on screen' test('a view-timeline reveal is measured by position: entry range, focus and reduced motion', {timeout:600000}, async()=> { await withPages(async check=> { - const scenarios=without('client-nav','stagger','progress-sync'); + // Scroll-linked: position is the state, nothing runs on a clock for a + // mid-use reduced-motion switch to stop. + const scenarios=without('client-nav','stagger','progress-sync','reduced-motion-toggle'); for(const viewport of VIEWPORTS) { const good=await check('kind=linked&mode=css-good',{scenarios},viewport); assert.equal(good.status,'pass',JSON.stringify(good));assert.equal(good.measured.mode,'scroll-linked'); diff --git a/harness/runtime-audit/test/sequence.test.mjs b/harness/runtime-audit/test/sequence.test.mjs new file mode 100644 index 00000000..48a7a781 --- /dev/null +++ b/harness/runtime-audit/test/sequence.test.mjs @@ -0,0 +1,107 @@ +// Verdicts on measured motion, without a browser: sequential and grouped +// entrances, order and direction, reduced motion switched on mid-use, and a +// disclosure opening and closing. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { evaluateDisclosure, evaluateReducedMotionToggle, evaluateSequence, unitsOf } from '../sequence-checks.mjs'; + +// Four cards in one row, 400ms each. +const row = left => ({ top: 100, left }); +const cards = (startedAt, extra = {}) => ({ + startedAt, shownAt: startedAt.map(value => value + 400), boxes: startedAt.map((_, index) => row(index * 100)), + startShift: startedAt.map(() => ({ x: 0, y: 16 })), containerAnimated: false, ...extra, +}); + +test('a sequential group starts each unit only after the previous one finished', () => { + const pass = evaluateSequence(cards([0, 400, 800, 1200]), { sequence: 'sequential' }); + assert.equal(pass.status, 'pass'); + assert.equal(pass.totalMs, 1600); + // A short stagger overlaps: card 2 starts while card 1 is still entering. + const overlapped = evaluateSequence(cards([0, 60, 120, 180]), { sequence: 'sequential' }); + assert.equal(overlapped.status, 'fail'); + assert.match(overlapped.reason, /unit 2 started 340ms before unit 1 finished/); + // The same timing is what an overlapping stagger asks for. + assert.equal(evaluateSequence(cards([0, 60, 120, 180]), { sequence: 'overlap' }).status, 'pass'); + // A frame of jitter is still "after". + assert.equal(evaluateSequence(cards([0, 380, 790, 1180]), { sequence: 'sequential' }).status, 'pass'); + // Bounded total when the plan bounds it. + assert.match(evaluateSequence(cards([0, 400, 800, 1200]), { sequence: 'sequential', maxTotalMs: 1200 }).reason, /1600ms, over 1200ms/); +}); + +test('the group element animating is not a sequence of units', () => { + const verdict = evaluateSequence(cards([0, 400, 800, 1200], { containerAnimated: true }), { sequence: 'sequential' }); + assert.equal(verdict.status, 'fail'); + assert.match(verdict.reason, /group element itself animates/); + assert.equal(evaluateSequence(cards([0, 0, 0, 0], { containerAnimated: true }), { sequence: 'together' }).status, 'pass'); + assert.match(evaluateSequence(cards([0, 0, 200, 0]), { sequence: 'together' }).reason, /did not start together/); +}); + +test('rows are read from the layout at this width and move as one unit', () => { + // Two rows of two at mobile width; four in a row at desktop. + const mobile = [{ top: 0, left: 0 }, { top: 0, left: 180 }, { top: 300, left: 0 }, { top: 300, left: 180 }]; + assert.deepEqual(unitsOf(mobile, 'row'), [[0, 1], [2, 3]]); + assert.deepEqual(unitsOf(mobile.map((_, index) => ({ top: 0, left: index * 300 })), 'row'), [[0, 1, 2, 3]]); + assert.deepEqual(unitsOf(mobile, 'card'), [[0], [1], [2], [3]]); + const rows = { startedAt: [0, 0, 400, 400], shownAt: [400, 400, 800, 800], boxes: mobile, startShift: mobile.map(() => ({ x: 0, y: 16 })) }; + assert.equal(evaluateSequence(rows, { sequence: 'sequential', unit: 'row' }).status, 'pass'); + // Card by card inside a row is not "row by row". + const split = { ...rows, startedAt: [0, 400, 800, 1200], shownAt: [400, 800, 1200, 1600] }; + assert.match(evaluateSequence(split, { sequence: 'sequential', unit: 'row' }).reason, /unit 1 \(items 1, 2\) did not start together/); +}); + +test('play order and movement direction are judged separately', () => { + // "The right card first, moving from right to left": reverse order, from-right. + const reverse = cards([1200, 800, 400, 0], { startShift: [0, 1, 2, 3].map(() => ({ x: 24, y: 0 })) }); + assert.equal(evaluateSequence(reverse, { sequence: 'sequential', order: 'reverse', direction: 'from-right' }).status, 'pass'); + // Right order, wrong direction. + assert.match(evaluateSequence(reverse, { sequence: 'sequential', order: 'reverse', direction: 'from-left' }).reason, /did not enter from-left/); + // Right direction, wrong order. + assert.match(evaluateSequence(reverse, { sequence: 'sequential', direction: 'from-right' }).reason, /started before unit/); + // One direction per row, in play order. + const boxes = [{ top: 0, left: 0 }, { top: 0, left: 100 }, { top: 200, left: 0 }, { top: 200, left: 100 }]; + const perRow = { startedAt: [0, 0, 400, 400], shownAt: [400, 400, 800, 800], boxes, startShift: [{ x: -20, y: 0 }, { x: -20, y: 0 }, { x: 20, y: 0 }, { x: 20, y: 0 }] }; + assert.equal(evaluateSequence(perRow, { sequence: 'sequential', unit: 'row', direction: ['from-left', 'from-right'] }).status, 'pass'); + assert.equal(evaluateSequence(perRow, { sequence: 'sequential', unit: 'row', direction: ['from-right', 'from-left'] }).status, 'fail'); + // Not seen displaced: the direction is unknown, never assumed. + assert.equal(evaluateSequence(cards([0, 400, 800, 1200], { startShift: [null, null, null, null] }), { sequence: 'sequential', direction: 'from-bottom' }).status, 'unverified'); +}); + +test('reduced motion switched on mid-use stops what runs and shows the content', () => { + const shown = { opacity: 1, translate: 0 }; + assert.equal(evaluateReducedMotionToggle({ running: 3 }, { running: 0, sample: shown }).status, 'pass'); + assert.match(evaluateReducedMotionToggle({ running: 3 }, { running: 1, sample: shown }).reason, /kept running/); + assert.match(evaluateReducedMotionToggle({ running: 3 }, { running: 0, sample: { opacity: 0.4, translate: 8 } }).reason, /stayed hidden or displaced/); + assert.equal(evaluateReducedMotionToggle({ running: 0 }, { running: 0, sample: shown }).status, 'unverified'); +}); + +const disclosure = (patch = {}) => ({ + collapsed: [{ height: 0, reachable: 0 }, { height: 0, reachable: 0 }, { height: 0, reachable: 0 }], + open: { height: 240, contentHeight: 240 }, + opening: [0, 60, 150, 220, 240], + follower: { closedTop: 500, openTop: 740, delta: 240 }, + interrupted: { close: { mid: 120, after: [118, 150, 190, 230, 240], end: 240 }, open: { mid: 110, after: [112, 80, 40, 10, 0], end: 0 } }, + field: { expected: 'x', actual: 'x' }, + ...patch, +}); + +test('a disclosure opens to its content, interrupts smoothly and keeps no focus or value loss', () => { + assert.equal(evaluateDisclosure(disclosure()).status, 'pass'); + const cases = [ + [{ collapsed: [{ height: 24, reachable: 0 }] }, /still takes 24px/], + [{ collapsed: [{ height: 0, reachable: 2 }] }, /2 control\(s\) inside the collapsed panel still take keyboard focus/], + [{ open: { height: 400, contentHeight: 240 } }, /does not follow its content height/], + [{ follower: { closedTop: 500, openTop: 500, delta: 0 } }, /moved 0px for a 240px panel/], + [{ interrupted: { close: { mid: 120, after: [0, 120, 240], end: 240 } } }, /jumped from 120px to 0px/], + [{ interrupted: { open: { mid: 110, after: [112, 80, 50, 30], end: 0 } } }, /ended at 30px, not 0px/], + [{ field: { expected: 'x', actual: '' } }, /form value .* was lost/], + ]; + for (const [patch, reason] of cases) { + const verdict = evaluateDisclosure(disclosure(patch)); + assert.equal(verdict.status, 'fail', JSON.stringify(patch)); + assert.match(verdict.failures.join('; '), reason); + } + // Too fast to see a middle or to interrupt: unverified, never passed. + const instant = evaluateDisclosure(disclosure({ opening: [0, 240], interrupted: { close: { mid: 240, after: [240], end: 240 } } })); + assert.equal(instant.status, 'unverified'); + assert.equal(instant.unverified.length, 2); +}); From 3f69ef93ce9e9f8b9b019b0d1ae314709e5f4b10 Mon Sep 17 00:00:00 2001 From: leader Date: Sun, 29 Nov 2026 01:11:04 +0900 Subject: [PATCH 3/3] Run the sequence verdict tests with the CI harness checks The pure sequence, unit, direction and disclosure verdict tests are loaded from checks.test.mjs, which CI already runs, so the workflow file does not need to change. Co-Authored-By: Claude Opus 5.5 --- harness/runtime-audit/test/checks.test.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/harness/runtime-audit/test/checks.test.mjs b/harness/runtime-audit/test/checks.test.mjs index 2c851b34..14c9bc78 100644 --- a/harness/runtime-audit/test/checks.test.mjs +++ b/harness/runtime-audit/test/checks.test.mjs @@ -1,3 +1,6 @@ +// The pure sequence, unit, direction and disclosure verdicts run with these +// in CI's node --test step. +import './sequence.test.mjs'; import assert from 'node:assert/strict'; import test from 'node:test';