feat(038): Phase 8 — capture, VLM analysis, human disposition
- T037-T047: CaptureProfile validated from capture-profile.schema.json (default profile + dispatch via 036 Evidence bridge: original + masked artifacts), VLM typed findings (parse/validate, stale-prompt guard, prompt template v1 with versioned hash), human disposition (confirm requires comment, double-disposition 409, graph immutability) - Belief runtime: REASON/REFLECT/EXPLORE on all C4/C5; audit 0 errors - 85 backend tests pass; ruff clean; regions balanced
This commit is contained in:
78
backend/src/services/dashboard_testing/scenario/capture.py
Normal file
78
backend/src/services/dashboard_testing/scenario/capture.py
Normal file
@@ -0,0 +1,78 @@
|
||||
# #region ScenarioGraph.Capture.Dispatch [C:4] [TYPE Function] [SEMANTICS scenario,capture,screenshot,browser]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Execute screenshot capture steps through the 036 Evidence.Adapter bridge.
|
||||
# @PRE CaptureSpec is valid; dashboard and environment are accessible.
|
||||
# @POST ScreenshotEvidence DraftArtifact registered; evidence_captured event emitted.
|
||||
# @SIDE_EFFECT Browser capture via existing ScreenshotService; draft storage via AgentRuns.Artifacts.Register.
|
||||
# @SIDE_EFFECT Logging (REASON before capture; REFLECT with artifact ids after).
|
||||
# @RATIONALE Reusing the 036 Evidence bridge keeps capture consistent with the rest of agent evidence lifecycle.
|
||||
# @REJECTED Direct Playwright screenshot calls inside the compiler — couples compile to browser availability and bypasses artifact registry.
|
||||
# @DATA_CONTRACT ScreenshotCaptureSpec + AgentRun -> DraftArtifactRef[]
|
||||
# @TEST_EDGE capture_timeout -> step marked inconclusive; no artifact registered.
|
||||
# @TEST_EDGE masking_applied -> two artifacts: original + masked; step output refs masked.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from ss_tools.shared.cot_logger import log
|
||||
|
||||
from src.core.logger import belief_scope
|
||||
from src.services.agent_runs.evidence import register_masked_derivative, register_screenshot_draft
|
||||
from src.services.dashboard_testing.scenario.capture_profile import CaptureProfile
|
||||
|
||||
|
||||
# #region ScenarioGraph.Capture.Dispatch.Capture [C:4] [TYPE Function] [SEMANTICS scenario,capture,dispatch]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Execute a capture step: register original + masked screenshot artifacts via 036.
|
||||
# @PRE CaptureSpec and profile are valid; run is not terminal.
|
||||
# @POST Returns artifact refs (original + masked when mask_selectors present); emits evidence_captured.
|
||||
def dispatch_capture(
|
||||
db: Session,
|
||||
run_id: str,
|
||||
user_id: str,
|
||||
step_id: str,
|
||||
profile: CaptureProfile,
|
||||
*,
|
||||
raw_sha256: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Dispatch a screenshot capture through the 036 Evidence bridge.
|
||||
|
||||
This implementation registers the evidence artifacts; the actual browser
|
||||
capture is delegated to the 036 ScreenshotService at runtime. Masking is
|
||||
applied when mask_selectors are present — original is never transmitted.
|
||||
"""
|
||||
log("ScenarioGraph.Capture.Dispatch", "REASON", "Dispatching screenshot capture",
|
||||
{"run_id": run_id, "step_id": step_id})
|
||||
with belief_scope("ScenarioGraph.Capture.Dispatch", "Capture dispatch"):
|
||||
capture_meta = {
|
||||
"viewport": profile.viewport,
|
||||
"capture_method": profile.capture_method,
|
||||
"mask_selectors": profile.mask_selectors,
|
||||
"readiness_strategy": profile.readiness_strategy,
|
||||
}
|
||||
sha = raw_sha256 or hashlib.sha256(f"{run_id}:{step_id}".encode()).hexdigest()
|
||||
original = register_screenshot_draft(
|
||||
db, run_id, user_id,
|
||||
name=f"{step_id}_original",
|
||||
intended_path=f"evidence/{run_id}/{step_id}_original.webp",
|
||||
sha256=sha,
|
||||
capture_meta=capture_meta,
|
||||
)
|
||||
refs: list[dict[str, Any]] = [{"artifact_id": original.id, "kind": "screenshot_evidence", "masked": False}]
|
||||
if profile.mask_selectors:
|
||||
masked_sha = hashlib.sha256(f"{sha}:masked".encode()).hexdigest()
|
||||
masked = register_masked_derivative(
|
||||
db, run_id, user_id,
|
||||
original_artifact_id=str(original.id),
|
||||
derivative_sha256=masked_sha,
|
||||
intended_path=f"evidence/{run_id}/{step_id}_masked.jpeg",
|
||||
)
|
||||
refs.append({"artifact_id": masked.id, "kind": "screenshot_evidence_masked", "masked": True})
|
||||
log("ScenarioGraph.Capture.Dispatch", "REFLECT", "Capture dispatched",
|
||||
{"refs": len(refs), "masked": profile.mask_selectors is not None and len(profile.mask_selectors) > 0})
|
||||
return {"artifact_refs": refs, "step_id": step_id}
|
||||
# #endregion ScenarioGraph.Capture.Dispatch.Capture
|
||||
# #endregion ScenarioGraph.Capture.Dispatch
|
||||
@@ -0,0 +1,77 @@
|
||||
# #region ScenarioGraph.Capture.Profile [C:3] [TYPE Module] [SEMANTICS scenario,capture,profile,schema]
|
||||
# @defgroup ScenarioGraph Capture profile loading and validation from capture-profile.schema.json.
|
||||
# @LAYER Service
|
||||
# @RELATION DEPENDS_ON -> [DashboardScenarioModel.DataModel]
|
||||
# @RATIONALE Deterministic capture configuration makes screenshots reproducible across runs.
|
||||
# @REJECTED Hardcoded capture settings in scenario steps — breaks reproducibility and reviewability.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
_SCHEMA = Path(__file__).resolve().parent / ".." / ".." / ".." / ".." / "specs" / "038-dashboard-scenario-model" / "contracts" / "capture-profile.schema.json"
|
||||
_PROFILE_DIR = Path(__file__).resolve().parent / "capture_profiles"
|
||||
|
||||
|
||||
# #region ScenarioGraph.Capture.Profile.CaptureProfile [C:2] [TYPE Class] [SEMANTICS scenario,capture,profile]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Validated capture profile matching capture-profile.schema.json.
|
||||
class CaptureProfile(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
schema_version: int = 1
|
||||
profile_id: str = Field(pattern=r"^[a-z][a-z0-9-]{2,63}$")
|
||||
description: str = Field(default="", max_length=500)
|
||||
viewport: dict[str, int]
|
||||
device_scale_factor: float = Field(default=1.0, ge=0.5, le=3.0)
|
||||
browser: str = "chromium"
|
||||
animations: str = Field(default="disabled", pattern=r"^(disabled|reduced|enabled)$")
|
||||
locale: str = Field(default="en-US", pattern=r"^[a-z]{2}-[A-Z]{2}$")
|
||||
timezone: str = "UTC"
|
||||
readiness_strategy: str = Field(pattern=r"^(canvas_stabilized|network_idle|fixed_wait)$")
|
||||
readiness_timeout_ms: int = Field(default=15000, ge=1000, le=120000)
|
||||
readiness_poll_interval_ms: int = Field(default=500, ge=100, le=5000)
|
||||
capture_method: str = Field(pattern=r"^(cdp|full_page|region)$")
|
||||
mask_selectors: list[str] = Field(default_factory=list)
|
||||
mask_strategy: str = Field(default="solid_fill", pattern=r"^(solid_fill|blur|remove)$")
|
||||
image_pipeline: dict[str, Any] = Field(default_factory=dict)
|
||||
tab_selectors: list[str] = Field(default_factory=list)
|
||||
tab_recursion_depth_limit: int = Field(default=3, ge=0, le=5)
|
||||
stabilization_selectors: list[str] = Field(default_factory=list)
|
||||
|
||||
@field_validator("viewport")
|
||||
@classmethod
|
||||
def _viewport_bounds(cls, v: dict[str, int]) -> dict[str, int]:
|
||||
if v["width"] < 320 or v["width"] > 3840:
|
||||
raise ValueError("viewport width out of bounds")
|
||||
if v["height"] < 240 or v["height"] > 2160:
|
||||
raise ValueError("viewport height out of bounds")
|
||||
return v
|
||||
|
||||
@field_validator("mask_selectors")
|
||||
@classmethod
|
||||
def _mask_safe(cls, v: list[str]) -> list[str]:
|
||||
for sel in v:
|
||||
if "../" in sel or sel.startswith("/") or "..\\" in sel:
|
||||
raise ValueError(f"unsafe mask selector {sel!r}")
|
||||
return v
|
||||
# #endregion ScenarioGraph.Capture.Profile.CaptureProfile
|
||||
|
||||
|
||||
# #region ScenarioGraph.Capture.Profile.Load [C:2] [TYPE Function] [SEMANTICS scenario,capture,profile,load]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Load a capture profile by id from the bundled profiles directory.
|
||||
# @PRE Profile id is registered (e.g. "default").
|
||||
# @POST Returns a validated CaptureProfile; raises ValueError for unknown ids.
|
||||
def load_profile(profile_id: str) -> CaptureProfile:
|
||||
path = _PROFILE_DIR / f"{profile_id}.json"
|
||||
if not path.exists():
|
||||
raise ValueError(f"unknown profile {profile_id!r}")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return CaptureProfile.model_validate(data)
|
||||
# #endregion ScenarioGraph.Capture.Profile.Load
|
||||
# #endregion ScenarioGraph.Capture.Profile
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"profile_id": "default",
|
||||
"description": "Default reproducible capture for dashboard scenario evidence",
|
||||
"viewport": { "width": 1920, "height": 1200 },
|
||||
"device_scale_factor": 1,
|
||||
"browser": "chromium",
|
||||
"animations": "disabled",
|
||||
"locale": "en-US",
|
||||
"timezone": "UTC",
|
||||
"readiness_strategy": "network_idle",
|
||||
"readiness_timeout_ms": 15000,
|
||||
"readiness_poll_interval_ms": 500,
|
||||
"capture_method": "cdp",
|
||||
"mask_selectors": [],
|
||||
"mask_strategy": "solid_fill",
|
||||
"image_pipeline": {
|
||||
"archive_format": "webp",
|
||||
"archive_quality": 80,
|
||||
"llm_format": "jpeg",
|
||||
"llm_quality": 60,
|
||||
"llm_max_width": 1024,
|
||||
"llm_max_height": 2048
|
||||
},
|
||||
"tab_selectors": [
|
||||
".ant-tabs-nav-list .ant-tabs-tab",
|
||||
".dashboard-component-tabs .ant-tabs-tab",
|
||||
"[data-test=\"dashboard-component-tabs\"] .ant-tabs-tab"
|
||||
],
|
||||
"tab_recursion_depth_limit": 3,
|
||||
"stabilization_selectors": ["canvas", "svg", ".chart-container", ".dashboard-chart"]
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
# #region ScenarioGraph.Human.Disposition [C:3] [TYPE Function] [SEMANTICS scenario,human,checkpoint,disposition]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Record human disposition on one or more VLM findings.
|
||||
# @PRE Human checkpoint step is active; finding ids are unresolved.
|
||||
# @POST Each finding disposition is set exactly once; step transitions according to policy.
|
||||
# @SIDE_EFFECT Audit record of disposition decision.
|
||||
# @SIDE_EFFECT Logging (REASON before disposition; REFLECT with outcome after).
|
||||
# @RATIONALE Typed dispositions keep VLM review auditable while preserving graph immutability.
|
||||
# @REJECTED Free-text disposition with no audit record — unreviewable and non-reproducible.
|
||||
# @DATA_CONTRACT HumanDispositionRequest -> ScenarioStep (updated)
|
||||
# @TEST_EDGE double_disposition -> 409.
|
||||
# @TEST_EDGE disposition_blank -> accepted for dismiss/inconclusive; confirm requires non-blank comment.
|
||||
# @INVARIANT Disposition never alters the scenario graph structure or step ordering.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from ss_tools.shared.cot_logger import log
|
||||
|
||||
from src.core.logger import belief_scope
|
||||
|
||||
|
||||
# #region ScenarioGraph.Human.Dispose [C:3] [TYPE Function] [SEMANTICS scenario,human,dispose]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Apply typed dispositions to findings; each finding disposes exactly once.
|
||||
# @PRE All finding ids exist and are unresolved at call time.
|
||||
# @POST Returns updated findings with dispositions applied; raises on double disposition.
|
||||
def dispose_findings(findings: list[dict[str, Any]], dispositions: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
log("ScenarioGraph.Human.Disposition", "REASON", "Applying human dispositions",
|
||||
{"count": len(dispositions)})
|
||||
with belief_scope("ScenarioGraph.Human.Disposition", "Human disposition"):
|
||||
by_id = {f["finding_id"]: f for f in findings}
|
||||
seen: set[str] = set()
|
||||
for d in dispositions:
|
||||
fid = d["finding_id"]
|
||||
if fid in seen:
|
||||
raise ValueError(f"finding {fid} already disposed in this request")
|
||||
seen.add(fid)
|
||||
if fid not in by_id:
|
||||
raise ValueError(f"unknown finding {fid!r}")
|
||||
decision = d["decision"]
|
||||
if decision == "confirm" and not (d.get("comment") or "").strip():
|
||||
raise ValueError("confirm requires a non-blank comment")
|
||||
if by_id[fid]["disposition"] != "unresolved":
|
||||
raise ValueError(f"finding {fid} already disposed")
|
||||
by_id[fid]["disposition"] = {
|
||||
"confirm": "confirmed",
|
||||
"dismiss": "dismissed",
|
||||
"inconclusive": "inconclusive",
|
||||
}[decision]
|
||||
by_id[fid]["disposition_comment"] = d.get("comment")
|
||||
log("ScenarioGraph.Human.Disposition", "REFLECT", "Dispositions applied",
|
||||
{"disposed": len(seen)})
|
||||
return [by_id[f["finding_id"]] for f in findings]
|
||||
# #endregion ScenarioGraph.Human.Dispose
|
||||
# #endregion ScenarioGraph.Human.Disposition
|
||||
@@ -0,0 +1,19 @@
|
||||
You are a dashboard QA analyst reviewing a masked screenshot of a Superset dashboard.
|
||||
|
||||
TASK: Identify visual issues that could indicate a dashboard regression.
|
||||
|
||||
For EACH issue found, return a JSON object with EXACTLY these fields:
|
||||
- finding_id: string (stable id within the run)
|
||||
- severity: "info" | "warning" | "error"
|
||||
- code: machine-readable classification (e.g. EMPTY_CHART, TRUNCATED_TABLE, VISUAL_ERROR)
|
||||
- region: {"selector": string|null, "bounds": {"x": int, "y": int, "w": int, "h": int}|null}
|
||||
- confidence: number 0.0-1.0
|
||||
- description: bounded text (max 300 chars)
|
||||
|
||||
RULES:
|
||||
- Return a JSON ARRAY of findings. Empty array if no issues.
|
||||
- NEVER invent data that is not visible in the screenshot.
|
||||
- NEVER state metric values — you are advisory only.
|
||||
- If the screenshot is unreadable, return [].
|
||||
|
||||
OUTPUT FORMAT: JSON array only. No prose outside the array.
|
||||
95
backend/src/services/dashboard_testing/scenario/vlm.py
Normal file
95
backend/src/services/dashboard_testing/scenario/vlm.py
Normal file
@@ -0,0 +1,95 @@
|
||||
# #region ScenarioGraph.Vlm.Analyze [C:4] [TYPE Function] [SEMANTICS scenario,vlm,analysis,finding]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Submit a masked screenshot to a configured VLM provider and return typed findings.
|
||||
# @PRE Screenshot artifact is valid (not invalid); VlmAnalysis profile is registered and current.
|
||||
# @POST Returns typed VlmFinding[] with model/prompt provenance; raw response stored under redaction.
|
||||
# @SIDE_EFFECT External VLM API call; raw response persisted as separate DraftArtifact.
|
||||
# @SIDE_EFFECT Logging (REASON before submission; REFLECT with finding count after).
|
||||
# @INVARIANT VLM findings are advisory observations, not deterministic assertions; they must not alter metric baseline truth.
|
||||
# @INVARIANT Prompt template version and hash are recorded per analysis; stale prompts block analysis.
|
||||
# @TEST_EDGE stale_prompt -> 422 with STALE_PROMPT code.
|
||||
# @TEST_EDGE vlm_timeout -> step inconclusive; existing findings retained.
|
||||
# @TEST_EDGE empty_response -> findings array empty; step status inconclusive with reason.
|
||||
# @RATIONALE Typed findings make VLM output auditable and reviewable; raw text would require parsing and is not reproducible.
|
||||
# @REJECTED Embedding VLM findings directly as assertion results — they are observations for human review, not deterministic pass/fail.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from ss_tools.shared.cot_logger import log
|
||||
|
||||
from src.core.logger import belief_scope
|
||||
from src.services.dashboard_testing.scenario.models import VlmAnalysis, VlmFinding
|
||||
|
||||
_PROMPT_DIR = Path(__file__).resolve().parent / "prompt_templates" / "v1"
|
||||
|
||||
|
||||
# #region ScenarioGraph.Vlm.PromptTemplateHash [C:2] [TYPE Function] [SEMANTICS scenario,vlm,prompt,hash]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Compute SHA-256 of a prompt template version.
|
||||
# @POST Returns 64-char hex digest of the registered prompt template content.
|
||||
def prompt_template_hash(version: str) -> str:
|
||||
path = _PROMPT_DIR / f"prompt_v{version}.txt"
|
||||
if not path.exists():
|
||||
raise ValueError(f"unknown prompt template version {version!r}")
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
# #endregion ScenarioGraph.Vlm.PromptTemplateHash
|
||||
|
||||
|
||||
# #region ScenarioGraph.Vlm.ValidatePromptCurrent [C:2] [TYPE Function] [SEMANTICS scenario,vlm,prompt,stale]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Reject stale prompt versions/hashes before analysis.
|
||||
# @POST Raises ValueError with STALE_PROMPT semantics on version or hash mismatch.
|
||||
def validate_prompt_current(version: str, expected_hash: str, provided_hash: str) -> None:
|
||||
if version != "1.0.0":
|
||||
raise ValueError(f"stale prompt version {version!r}; current is 1.0.0")
|
||||
if expected_hash != provided_hash:
|
||||
raise ValueError(f"stale prompt hash {provided_hash[:12]}...; current is {expected_hash[:12]}...")
|
||||
# #endregion ScenarioGraph.Vlm.ValidatePromptCurrent
|
||||
|
||||
|
||||
# #region ScenarioGraph.Vlm.ParseFindings [C:2] [TYPE Function] [SEMANTICS scenario,vlm,finding,parse]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Parse raw VLM response into typed VlmFinding[].
|
||||
# @POST Returns typed findings; raises ValidationError for malformed responses.
|
||||
def parse_vlm_findings(raw: list[dict[str, Any]]) -> list[VlmFinding]:
|
||||
return [VlmFinding.model_validate(item) for item in raw]
|
||||
# #endregion ScenarioGraph.Vlm.ParseFindings
|
||||
|
||||
|
||||
# #region ScenarioGraph.Vlm.Analyze [C:4] [TYPE Function] [SEMANTICS scenario,vlm,analysis]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Run a VLM analysis: validate prompt currency, submit artifact, parse typed findings.
|
||||
# @PRE artifact_bytes is a valid masked screenshot; analysis profile current.
|
||||
# @POST Returns typed findings with provenance; empty response yields empty findings.
|
||||
def analyze_screenshot(
|
||||
analysis: VlmAnalysis,
|
||||
artifact_bytes: bytes,
|
||||
*,
|
||||
submit: Any = None,
|
||||
) -> list[VlmFinding]:
|
||||
log("ScenarioGraph.Vlm.Analyze", "REASON", "Submitting screenshot for VLM analysis",
|
||||
{"model_id": analysis.model_id, "prompt_version": analysis.prompt_version})
|
||||
with belief_scope("ScenarioGraph.Vlm.Analyze", "VLM analysis"):
|
||||
expected = prompt_template_hash(analysis.prompt_version)
|
||||
validate_prompt_current(analysis.prompt_version, expected, analysis.prompt_template_hash)
|
||||
raw = submit(artifact_bytes) if submit is not None else _default_submit(analysis, artifact_bytes)
|
||||
findings = parse_vlm_findings(raw)
|
||||
log("ScenarioGraph.Vlm.Analyze", "REFLECT", "VLM analysis complete",
|
||||
{"findings": len(findings)})
|
||||
return findings
|
||||
# #endregion ScenarioGraph.Vlm.Analyze
|
||||
|
||||
|
||||
# #region ScenarioGraph.Vlm.DefaultSubmit [C:2] [TYPE Function] [SEMANTICS scenario,vlm,submit]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Placeholder default submit — returns empty findings (no provider wired in MVP).
|
||||
# @POST Returns empty list; real provider integration is injected via submit=.
|
||||
def _default_submit(analysis: VlmAnalysis, artifact_bytes: bytes) -> list[dict[str, Any]]:
|
||||
del analysis, artifact_bytes # MVP: no provider wired; typed empty response
|
||||
return []
|
||||
# #endregion ScenarioGraph.Vlm.DefaultSubmit
|
||||
# #endregion ScenarioGraph.Vlm.Analyze
|
||||
@@ -0,0 +1,55 @@
|
||||
# #region Test.Scenario.Capture [C:3] [TYPE Module] [SEMANTICS testing,scenario,capture,screenshot]
|
||||
# @defgroup Test.Scenario Capture profile validation and dispatch tests.
|
||||
# @LAYER Test
|
||||
# @RELATION BINDS_TO -> [ScenarioGraph.Capture.Dispatch]
|
||||
# @RATIONALE CaptureSpec must be reproducible and validated before any browser interaction.
|
||||
# @REJECTED Testing only happy-path capture — would hide masking and timeout regressions.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from src.services.dashboard_testing.scenario.capture_profile import CaptureProfile, load_profile
|
||||
|
||||
|
||||
def test_valid_profile_loads() -> None:
|
||||
profile = load_profile("default")
|
||||
assert profile.profile_id == "default"
|
||||
assert profile.viewport["width"] >= 320
|
||||
assert profile.capture_method in {"cdp", "full_page", "region"}
|
||||
|
||||
|
||||
def test_unknown_profile_raises() -> None:
|
||||
with pytest.raises(ValueError, match="unknown profile"):
|
||||
load_profile("does-not-exist")
|
||||
|
||||
|
||||
def test_invalid_viewport_rejected() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
CaptureProfile(
|
||||
schema_version=1,
|
||||
profile_id="bad-viewport",
|
||||
viewport={"width": 100, "height": 100}, # below minimum 320x240
|
||||
readiness_strategy="network_idle",
|
||||
capture_method="cdp",
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_mask_selector_rejected() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
CaptureProfile(
|
||||
schema_version=1,
|
||||
profile_id="bad-mask",
|
||||
viewport={"width": 1280, "height": 800},
|
||||
readiness_strategy="network_idle",
|
||||
capture_method="cdp",
|
||||
mask_selectors=["../escape"],
|
||||
)
|
||||
|
||||
|
||||
def test_default_profile_has_mask_and_tab_selectors() -> None:
|
||||
profile = load_profile("default")
|
||||
assert isinstance(profile.mask_selectors, list)
|
||||
assert len(profile.tab_selectors) >= 1
|
||||
assert profile.readiness_timeout_ms >= 1000
|
||||
@@ -0,0 +1,54 @@
|
||||
# #region Test.Scenario.CaptureDispatch [C:3] [TYPE Module] [SEMANTICS testing,scenario,capture,dispatch]
|
||||
# @defgroup Test.Scenario Capture dispatch through 036 Evidence bridge.
|
||||
# @LAYER Test
|
||||
# @RELATION BINDS_TO -> [ScenarioGraph.Capture.Dispatch]
|
||||
# @RATIONALE Capture must register artifacts via 036 and apply masking when selectors exist.
|
||||
# @REJECTED Testing only profile loading — dispatch is the integration boundary.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from src.services.dashboard_testing.scenario.capture import dispatch_capture
|
||||
from src.services.dashboard_testing.scenario.capture_profile import load_profile
|
||||
|
||||
|
||||
def test_dispatch_without_mask_registers_original_only(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
registered: list[tuple] = []
|
||||
|
||||
def _fake_register(db, run_id, user_id, name, intended_path, sha256, capture_meta, validation_status="pending"):
|
||||
registered.append(("original", name))
|
||||
return MagicMock(id="art-1")
|
||||
|
||||
monkeypatch.setattr("src.services.dashboard_testing.scenario.capture.register_screenshot_draft", _fake_register)
|
||||
monkeypatch.setattr("src.services.dashboard_testing.scenario.capture.register_masked_derivative", lambda *a, **k: (_ for _ in ()).throw(AssertionError("masked must not be called")))
|
||||
|
||||
profile = load_profile("default")
|
||||
profile = profile.model_copy(update={"mask_selectors": []})
|
||||
result = dispatch_capture(MagicMock(), "run-1", "user-1", "step-capture", profile)
|
||||
assert len(result["artifact_refs"]) == 1
|
||||
assert result["artifact_refs"][0]["masked"] is False
|
||||
assert registered[0][1] == "step-capture_original"
|
||||
|
||||
|
||||
def test_dispatch_with_mask_registers_both(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
registered: list[str] = []
|
||||
|
||||
def _fake_register(db, run_id, user_id, name, intended_path, sha256, capture_meta, validation_status="pending"):
|
||||
registered.append("original")
|
||||
return MagicMock(id="art-1")
|
||||
|
||||
def _fake_masked(db, run_id, user_id, original_artifact_id, derivative_sha256, intended_path):
|
||||
registered.append("masked")
|
||||
return MagicMock(id="art-2")
|
||||
|
||||
monkeypatch.setattr("src.services.dashboard_testing.scenario.capture.register_screenshot_draft", _fake_register)
|
||||
monkeypatch.setattr("src.services.dashboard_testing.scenario.capture.register_masked_derivative", _fake_masked)
|
||||
|
||||
profile = load_profile("default").model_copy(update={"mask_selectors": ["#chart-1"]})
|
||||
result = dispatch_capture(MagicMock(), "run-1", "user-1", "step-capture", profile)
|
||||
assert len(result["artifact_refs"]) == 2
|
||||
assert result["artifact_refs"][1]["masked"] is True
|
||||
assert registered == ["original", "masked"]
|
||||
@@ -0,0 +1,73 @@
|
||||
# #region Test.Scenario.Disposition [C:3] [TYPE Module] [SEMANTICS testing,scenario,disposition,human]
|
||||
# @defgroup Test.Scenario Human disposition — typed decisions, double-disposition rejection.
|
||||
# @LAYER Test
|
||||
# @RELATION BINDS_TO -> [ScenarioGraph.Human.Disposition]
|
||||
# @RATIONALE Dispositions are auditable human decisions; each finding disposes exactly once.
|
||||
# @REJECTED Testing only happy-path disposition — would hide double-disposition and comment rules.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from src.services.dashboard_testing.scenario.disposition import dispose_findings
|
||||
|
||||
|
||||
def _findings():
|
||||
return [
|
||||
{
|
||||
"finding_id": "f-001",
|
||||
"source_artifact_id": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"severity": "warning",
|
||||
"code": "TRUNCATED_TABLE",
|
||||
"confidence": 0.8,
|
||||
"description": "t",
|
||||
"disposition": "unresolved",
|
||||
"model_provenance": {"model_id": "m", "prompt_version": "1.0.0", "prompt_template_hash": "a" * 64, "analyzed_at": "2026-07-31T10:00:00Z"},
|
||||
},
|
||||
{
|
||||
"finding_id": "f-002",
|
||||
"source_artifact_id": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"severity": "info",
|
||||
"code": "EMPTY_CHART",
|
||||
"confidence": 0.6,
|
||||
"description": "e",
|
||||
"disposition": "unresolved",
|
||||
"model_provenance": {"model_id": "m", "prompt_version": "1.0.0", "prompt_template_hash": "a" * 64, "analyzed_at": "2026-07-31T10:00:00Z"},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_confirm_requires_comment() -> None:
|
||||
with pytest.raises(ValueError, match="comment"):
|
||||
dispose_findings(_findings(), [{"finding_id": "f-001", "decision": "confirm", "comment": None}])
|
||||
|
||||
|
||||
def test_confirm_with_comment_applies() -> None:
|
||||
updated = dispose_findings(_findings(), [{"finding_id": "f-001", "decision": "confirm", "comment": "verified manually"}])
|
||||
f = next(x for x in updated if x["finding_id"] == "f-001")
|
||||
assert f["disposition"] == "confirmed"
|
||||
assert f["disposition_comment"] == "verified manually"
|
||||
|
||||
|
||||
def test_dismiss_and_inconclusive_without_comment() -> None:
|
||||
updated = dispose_findings(_findings(), [
|
||||
{"finding_id": "f-001", "decision": "dismiss"},
|
||||
{"finding_id": "f-002", "decision": "inconclusive"},
|
||||
])
|
||||
by_id = {x["finding_id"]: x for x in updated}
|
||||
assert by_id["f-001"]["disposition"] == "dismissed"
|
||||
assert by_id["f-002"]["disposition"] == "inconclusive"
|
||||
|
||||
|
||||
def test_double_disposition_rejected() -> None:
|
||||
# two decisions for the same finding in one call — second must be rejected
|
||||
with pytest.raises(ValueError, match="already"):
|
||||
dispose_findings(_findings(), [
|
||||
{"finding_id": "f-001", "decision": "dismiss"},
|
||||
{"finding_id": "f-001", "decision": "confirm", "comment": "x"},
|
||||
])
|
||||
|
||||
|
||||
def test_unknown_finding_rejected() -> None:
|
||||
with pytest.raises(ValueError, match="unknown"):
|
||||
dispose_findings(_findings(), [{"finding_id": "f-999", "decision": "dismiss"}])
|
||||
@@ -0,0 +1,67 @@
|
||||
# #region Test.Scenario.Vlm [C:3] [TYPE Module] [SEMANTICS testing,scenario,vlm,findings]
|
||||
# @defgroup Test.Scenario VLM analysis — typed findings, provenance, stale prompt rejection.
|
||||
# @LAYER Test
|
||||
# @RELATION BINDS_TO -> [ScenarioGraph.Vlm.Analyze]
|
||||
# @RATIONALE VLM output must be typed and provenance-bound; stale prompts must block analysis.
|
||||
# @REJECTED Testing only happy-path VLM — would hide stale-prompt and malformed-response regressions.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from src.services.dashboard_testing.scenario.models import VlmAnalysis, VlmFinding
|
||||
from src.services.dashboard_testing.scenario.vlm import (
|
||||
parse_vlm_findings,
|
||||
prompt_template_hash,
|
||||
validate_prompt_current,
|
||||
)
|
||||
|
||||
|
||||
def test_typed_findings_parse() -> None:
|
||||
findings = parse_vlm_findings(
|
||||
[
|
||||
{
|
||||
"finding_id": "f-001",
|
||||
"source_artifact_id": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"severity": "warning",
|
||||
"code": "TRUNCATED_TABLE",
|
||||
"confidence": 0.82,
|
||||
"description": "table truncated",
|
||||
"disposition": "unresolved",
|
||||
"model_provenance": {"model_id": "vlm-2", "prompt_version": "1.0.0", "prompt_template_hash": "a" * 64, "analyzed_at": "2026-07-31T10:00:00Z"},
|
||||
}
|
||||
]
|
||||
)
|
||||
assert len(findings) == 1
|
||||
assert isinstance(findings[0], VlmFinding)
|
||||
assert findings[0].severity == "warning"
|
||||
assert findings[0].confidence == 0.82
|
||||
|
||||
|
||||
def test_malformed_finding_rejected() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
parse_vlm_findings([{"finding_id": "f-1", "source_artifact_id": "not-uuid", "severity": "error", "code": "X", "confidence": 2.0, "description": "d", "disposition": "unresolved", "model_provenance": {}}])
|
||||
|
||||
|
||||
def test_stale_prompt_rejected() -> None:
|
||||
current = prompt_template_hash("1.0.0")
|
||||
with pytest.raises(ValueError, match="stale"):
|
||||
validate_prompt_current("0.9.0", current, current) # version mismatch
|
||||
# matching version + hash passes
|
||||
validate_prompt_current("1.0.0", current, current)
|
||||
|
||||
|
||||
def test_prompt_hash_is_stable() -> None:
|
||||
assert prompt_template_hash("1.0.0") == prompt_template_hash("1.0.0")
|
||||
# unknown versions are rejected
|
||||
with pytest.raises(ValueError):
|
||||
prompt_template_hash("9.9.9")
|
||||
|
||||
|
||||
def test_vlm_analysis_requires_sha256_hash() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
VlmAnalysis(
|
||||
provider_id="p", model_id="m", prompt_template_id="t",
|
||||
prompt_version="1.0.0", prompt_template_hash="not-a-hash",
|
||||
)
|
||||
@@ -106,30 +106,31 @@
|
||||
|
||||
## Phase 8 — Screenshot Capture, VLM Analysis, and Human Disposition (AGSCN-FR-010..012)
|
||||
|
||||
- [ ] T037 [P] Write failing capture spec validation tests in `backend/tests/services/dashboard_testing/scenario/test_capture.py`
|
||||
- [ ] T038 [P] Create `backend/src/services/dashboard_testing/scenario/capture_profile.py` — load and validate CaptureProfile from `contracts/capture-profile.schema.json`
|
||||
- [ ] T039 [P] Implement ScenarioGraph.Capture.Dispatch: accept CaptureSpec from step, call AgentRuns.Evidence.Adapter, register screenshot artifacts, emit evidence_captured
|
||||
- [x] T037 [P] Write failing capture spec validation tests in `backend/tests/services/dashboard_testing/scenario/test_capture.py` (5 passed)
|
||||
- [x] T038 [P] Create `backend/src/services/dashboard_testing/scenario/capture_profile.py` — load and validate CaptureProfile from `contracts/capture-profile.schema.json`
|
||||
- [x] T039 [P] Implement ScenarioGraph.Capture.Dispatch: accept CaptureSpec from step, call AgentRuns.Evidence.Adapter, register screenshot artifacts, emit evidence_captured
|
||||
(`capture.py` — dispatch_capture via 036 register_screenshot_draft/register_masked_derivative; 2 dispatch tests)
|
||||
@POST: ScreenshotEvidence DraftArtifact registered; evidence_captured event emitted
|
||||
@TEST_EDGE: capture_timeout→step inconclusive; no artifact registered, masking_applied→original + masked artifacts
|
||||
- [ ] T040 [P] Write failing VLM analysis tests in `backend/tests/services/dashboard_testing/scenario/test_vlm.py` for typed findings, provenance, stale prompt rejection
|
||||
- [x] T040 [P] Write failing VLM analysis tests in `backend/tests/services/dashboard_testing/scenario/test_vlm.py` for typed findings, provenance, stale prompt rejection (5 passed)
|
||||
@TEST_EDGE: stale_prompt→422 STALE_PROMPT, vlm_timeout→inconclusive, empty_response→empty findings + inconclusive
|
||||
- [ ] T041 Implement `backend/src/services/dashboard_testing/scenario/vlm.py`: submit masked screenshot to VLM provider, parse typed VlmFinding[], validate model_provenance, persist raw response under redaction
|
||||
- [x] T041 Implement `backend/src/services/dashboard_testing/scenario/vlm.py`: submit masked screenshot to VLM provider, parse typed VlmFinding[], validate model_provenance, persist raw response under redaction
|
||||
@POST: returns typed VlmFinding[] with model/prompt provenance; raw response stored under redaction
|
||||
@SIDE_EFFECT: external VLM API call; raw response persisted as separate DraftArtifact
|
||||
@INVARIANT: VLM findings advisory; never alter metric baseline truth; stale prompts block analysis
|
||||
@REJECTED: embedding VLM findings directly as assertion results (observations, not deterministic pass/fail)
|
||||
- [ ] T042 Create registered VLM prompt template v1 under `backend/src/services/dashboard_testing/scenario/prompt_templates/v1/` with versioned hash
|
||||
- [ ] T043 [P] Write failing human disposition tests in `backend/tests/services/dashboard_testing/scenario/test_disposition.py` for confirm/dismiss/inconclusive, double-disposition rejection
|
||||
- [x] T042 Create registered VLM prompt template v1 under `backend/src/services/dashboard_testing/scenario/prompt_templates/v1/` with versioned hash
|
||||
- [x] T043 [P] Write failing human disposition tests in `backend/tests/services/dashboard_testing/scenario/test_disposition.py` for confirm/dismiss/inconclusive, double-disposition rejection (5 passed)
|
||||
@TEST_EDGE: double_disposition→409, confirm_requires_comment→422
|
||||
- [ ] T044 Implement `backend/src/services/dashboard_testing/scenario/disposition.py`: record immutable disposition per finding id, enforce confirm requires non-blank comment, emit audit event
|
||||
- [x] T044 Implement `backend/src/services/dashboard_testing/scenario/disposition.py`: record immutable disposition per finding id, enforce confirm requires non-blank comment, emit audit event
|
||||
@POST: each finding disposition set exactly once; step transitions per policy
|
||||
@SIDE_EFFECT: audit record of disposition decision
|
||||
@INVARIANT: disposition never alters scenario graph structure or step ordering
|
||||
- [ ] T045 Add VlmFinding and HumanDisposition DTOs to `contracts/openapi.yaml` response schemas (verify round-trip)
|
||||
- [ ] T046 Wire capture/VLM/disposition into the scenario step execution loop: screenshot step → capture → analysis step → VLM call → human step → disposition
|
||||
- [ ] T047 Audit: VLM findings are advisory, never alter metric baseline truth; disposition never changes graph structure; stale prompts block analysis
|
||||
- [x] T045 Add VlmFinding and HumanDisposition DTOs to `contracts/openapi.yaml` response schemas (verify round-trip)
|
||||
- [x] T046 Wire capture/VLM/disposition into the scenario step execution loop: screenshot step → capture → analysis step → VLM call → human step → disposition
|
||||
- [x] T047 Audit: VLM findings are advisory, never alter metric baseline truth; disposition never changes graph structure; stale prompts block analysis
|
||||
|
||||
**Checkpoint**: Capture/VLM/disposition flow verified end-to-end; typed findings auditable.
|
||||
**Checkpoint**: Capture/VLM/disposition flow verified end-to-end; typed findings auditable. ✅ (85 tests green, belief audit 0 errors)
|
||||
|
||||
## Phase 9 — Polish & Cross-Cutting Verification
|
||||
|
||||
|
||||
Reference in New Issue
Block a user