From f572288ff96d86f385398a9cb53ea65469d75cf4 Mon Sep 17 00:00:00 2001 From: leader Date: Sun, 29 Nov 2026 00:16:35 +0900 Subject: [PATCH] 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!([])); +}