diff --git a/backend/src/api/routes/git/_config_routes.py b/backend/src/api/routes/git/_config_routes.py index 9f4e3efa6..7b6afbbfd 100644 --- a/backend/src/api/routes/git/_config_routes.py +++ b/backend/src/api/routes/git/_config_routes.py @@ -4,6 +4,8 @@ # @LAYER API +from datetime import UTC, datetime + from fastapi import Depends, HTTPException from sqlalchemy.orm import Session @@ -15,7 +17,7 @@ from src.api.routes.git_schemas import ( from src.core.database import get_db from src.core.logger import belief_scope from src.dependencies import has_permission -from src.models.git import GitServerConfig +from src.models.git import GitServerConfig, GitStatus from ._deps import get_git_service from ._router import router @@ -126,27 +128,24 @@ async def test_git_config( with belief_scope("test_git_config"): _git_service = get_git_service() pat_to_use = config.pat - if pat_to_use == "********": - if config.config_id: - db_config = ( - db.query(GitServerConfig) - .filter(GitServerConfig.id == config.config_id) - .first() - ) - if db_config: - pat_to_use = db_config.pat - else: - db_config = ( - db.query(GitServerConfig) - .filter(GitServerConfig.url == config.url) - .first() - ) - if db_config: - pat_to_use = db_config.pat + db_config: GitServerConfig | None = None + if not (pat_to_use or "").strip() or pat_to_use == "********": + lookup = ( + GitServerConfig.id == config.config_id + if config.config_id + else GitServerConfig.url == config.url + ) + db_config = db.query(GitServerConfig).filter(lookup).first() + if db_config: + pat_to_use = db_config.pat success = await _git_service.test_connection( config.provider, config.url, pat_to_use ) + if db_config: + db_config.status = GitStatus.CONNECTED if success else GitStatus.FAILED + db_config.last_validated = datetime.now(UTC) + db.commit() if success: return {"status": "success", "message": "Connection successful"} else: diff --git a/backend/src/models/storage.py b/backend/src/models/storage.py index 821a41c42..bc29d6aff 100644 --- a/backend/src/models/storage.py +++ b/backend/src/models/storage.py @@ -14,6 +14,7 @@ class FileCategory(str, Enum): REPOSITORY = "repositories" CHAT_UPLOADS = "chat_uploads" MIGRATION_FAILED = "migrations_failed" + DRAFT = "drafts" # #endregion Models.Storage.FileCategory # #region Models.Storage.StorageConfig [C:1] [TYPE Class] diff --git a/backend/src/services/agent_runs/artifacts.py b/backend/src/services/agent_runs/artifacts.py index 23c6dc08d..c00af3af2 100644 --- a/backend/src/services/agent_runs/artifacts.py +++ b/backend/src/services/agent_runs/artifacts.py @@ -13,15 +13,28 @@ from typing import IO from ss_tools.shared.cot_logger import log +from src.models.storage import FileCategory + class DraftStorage: - """File-based storage for draft artifacts outside the Git repository.""" + """File-based storage for draft artifacts outside the Git repository. + + Delegates all I/O to the central StorageService (file manager) under the + FileCategory.DRAFT directory, so drafts live inside the configured storage root + (settings.storage.root_path) with the shared path-traversal guard. + """ def __init__(self, storage_root: str | Path | None = None): - root = Path(storage_root) if storage_root else Path("data/drafts") - self._root = root.resolve() - if not self._root.exists(): - self._root.mkdir(parents=True, exist_ok=True) + from src.dependencies import get_storage_service + + if storage_root is not None: + self._storage = get_storage_service(storage_root) + else: + self._storage = get_storage_service() # configured settings.storage.root_path + # Legacy root used before draft storage was routed through StorageService + # (drafts previously landed in ./data/drafts). Read fallback keeps already-stored + # drafts downloadable after the root switch without a full migration. + self._legacy_root = Path("data/drafts").resolve() # ── Store ────────────────────────────────────────────────── @@ -31,48 +44,48 @@ class DraftStorage: The content_ref is NEVER a filesystem path returned to clients. """ content_ref = f"draft:{run_id}:{sha256}" - file_path = self._ref_to_path(content_ref) - file_path.parent.mkdir(parents=True, exist_ok=True) - file_path.write_bytes(data) + self._storage.save_bytes(FileCategory.DRAFT, f"{run_id}/{sha256}", data) log("AgentRuns.Artifacts", "REASON", "Draft stored", {"run_id": run_id, "sha256": sha256[:12], "size": len(data)}) return content_ref def store_stream(self, run_id: str, sha256: str, stream: IO[bytes]) -> str: - """Store from a file-like stream. Computes sha256 on the fly.""" + """Store from a file-like stream. Verifies sha256 on the fly.""" hasher = hashlib.sha256() content_ref = f"draft:{run_id}:{sha256}" - file_path = self._ref_to_path(content_ref) - file_path.parent.mkdir(parents=True, exist_ok=True) - - with open(file_path, "wb") as f: - while True: - chunk = stream.read(65536) - if not chunk: - break - hasher.update(chunk) - f.write(chunk) + data = stream.read() + hasher.update(data) actual_hash = hasher.hexdigest() if actual_hash != sha256: - file_path.unlink() raise ValueError( f"sha256 mismatch: expected {sha256[:12]}, got {actual_hash[:12]}") + self._storage.save_bytes(FileCategory.DRAFT, f"{run_id}/{sha256}", data) log("AgentRuns.Artifacts", "REFLECT", "Draft stored from stream", - {"run_id": run_id, "sha256": sha256[:12], "size": file_path.stat().st_size}) + {"run_id": run_id, "sha256": sha256[:12], "size": len(data)}) return content_ref # ── Retrieve ─────────────────────────────────────────────── + def _read_path(self, content_ref: str) -> Path | None: + """Resolve draft bytes: configured storage first, then the legacy ./data/drafts + root for drafts stored before the StorageService switch.""" + rel = self._ref_to_path(content_ref) + primary = self._storage.get_path(FileCategory.DRAFT, rel) + if primary.exists(): + return primary + legacy = self._legacy_root / rel + return legacy if legacy.exists() else None + def retrieve(self, content_ref: str) -> bytes | None: """Retrieve draft bytes by opaque content_ref. Returns None if the draft does not exist. """ - file_path = self._ref_to_path(content_ref) - if not file_path.exists(): + file_path = self._read_path(content_ref) + if file_path is None: return None log("AgentRuns.Artifacts", "REASON", "Draft retrieved", @@ -81,8 +94,8 @@ class DraftStorage: def retrieve_stream(self, content_ref: str) -> IO[bytes] | None: """Retrieve draft as a file-like stream.""" - file_path = self._ref_to_path(content_ref) - if not file_path.exists(): + file_path = self._read_path(content_ref) + if file_path is None: return None return open(file_path, "rb") @@ -90,9 +103,8 @@ class DraftStorage: def delete(self, content_ref: str) -> bool: """Delete stored draft bytes. Returns True if file was removed.""" - file_path = self._ref_to_path(content_ref) - if file_path.exists(): - file_path.unlink() + deleted = self._storage.delete(FileCategory.DRAFT, self._ref_to_path(content_ref)) + if deleted: log("AgentRuns.Artifacts", "REASON", "Draft deleted", {"content_ref": content_ref[:30]}) return True @@ -100,7 +112,7 @@ class DraftStorage: def cleanup_run(self, run_id: str) -> int: """Remove all drafts for a run. Returns count of deleted files.""" - run_dir = self._root / run_id + run_dir = self._storage.get_path(FileCategory.DRAFT, run_id) count = 0 if run_dir.exists(): for f in run_dir.iterdir(): @@ -113,8 +125,11 @@ class DraftStorage: # ── Internal ─────────────────────────────────────────────── - def _ref_to_path(self, content_ref: str) -> Path: - """Map opaque content_ref to a filesystem path (NEVER exposed to clients).""" + def _ref_to_path(self, content_ref: str) -> str: + """Validate opaque content_ref and return its relative path (run_id/sha256). + + NEVER exposed to clients — only used to resolve within the DRAFT category. + """ # Sanity: ensure no path traversal if ".." in content_ref or "/" in content_ref: raise ValueError("content_ref must not contain path separators") @@ -125,7 +140,7 @@ class DraftStorage: # Validate sha256 format if len(sha256) != 64 or not all(c in "0123456789abcdef" for c in sha256): raise ValueError("invalid sha256 in content_ref") - return self._root / run_id / sha256 + return f"{run_id}/{sha256}" # ── Singleton for app-wide use ───────────────────────────────── @@ -136,7 +151,7 @@ _draft_storage: DraftStorage | None = None def get_draft_storage(storage_root: str | None = None) -> DraftStorage: global _draft_storage if _draft_storage is None: - root = storage_root or os.environ.get("DRAFT_STORAGE_ROOT", "data/drafts") + root = storage_root or os.environ.get("DRAFT_STORAGE_ROOT") _draft_storage = DraftStorage(root) return _draft_storage # #endregion Services.AgentRuns.Artifacts diff --git a/backend/tests/api/test_git_config_routes.py b/backend/tests/api/test_git_config_routes.py index e41ad979b..01e1aaab0 100644 --- a/backend/tests/api/test_git_config_routes.py +++ b/backend/tests/api/test_git_config_routes.py @@ -301,4 +301,64 @@ class TestTestGitConfig: }) assert resp.status_code == 200 mock_service.test_connection.assert_called_with("GITHUB", "https://github.com", "ghp_url_resolved") + + def test_connection_persists_status_on_success(self): + """Stored config status is set to CONNECTED on successful test.""" + from src.core.database import get_db + from src.models.git import GitStatus + mock_db = MagicMock() + existing = _make_mock_config(id="cfg-1", pat="ghp_resolved") + + mock_q = MagicMock() + mock_f = MagicMock() + mock_f.first.return_value = existing + mock_q.filter.return_value = mock_f + mock_db.query.return_value = mock_q + + mock_service = AsyncMock() + mock_service.test_connection.return_value = True + + with patch("src.api.routes.git._config_routes.get_git_service", return_value=mock_service): + client = _make_client({get_db: lambda: mock_db}) + resp = client.post("/api/git/config/test", json={ + "name": "Test", + "provider": "GITHUB", + "url": "https://github.com", + "pat": "********", + "config_id": "cfg-1", + }) + assert resp.status_code == 200 + assert existing.status == GitStatus.CONNECTED + assert existing.last_validated is not None + mock_db.commit.assert_called_once() + + def test_connection_persists_status_on_failure(self): + """Stored config status is set to FAILED on failed test.""" + from src.core.database import get_db + from src.models.git import GitStatus + mock_db = MagicMock() + existing = _make_mock_config(id="cfg-1", pat="ghp_resolved") + + mock_q = MagicMock() + mock_f = MagicMock() + mock_f.first.return_value = existing + mock_q.filter.return_value = mock_f + mock_db.query.return_value = mock_q + + mock_service = AsyncMock() + mock_service.test_connection.return_value = False + + with patch("src.api.routes.git._config_routes.get_git_service", return_value=mock_service): + client = _make_client({get_db: lambda: mock_db}) + resp = client.post("/api/git/config/test", json={ + "name": "Test", + "provider": "GITHUB", + "url": "https://github.com", + "pat": "********", + "config_id": "cfg-1", + }) + assert resp.status_code == 400 + assert existing.status == GitStatus.FAILED + assert existing.last_validated is not None + mock_db.commit.assert_called_once() # #endregion Test.Api.GitConfigRoutes diff --git a/backend/tests/services/agent_runs/test_artifacts.py b/backend/tests/services/agent_runs/test_artifacts.py index 6cdc8744c..48d6b1ac9 100644 --- a/backend/tests/services/agent_runs/test_artifacts.py +++ b/backend/tests/services/agent_runs/test_artifacts.py @@ -9,6 +9,7 @@ from io import BytesIO import pytest import tempfile +from src.models.storage import FileCategory from src.services.agent_runs.artifacts import DraftStorage @@ -88,4 +89,34 @@ class TestDelete: def test_delete_nonexistent_returns_false(self, storage): assert storage.delete("draft:run-1:" + "c" * 64) is False + + +class TestLegacyFallback: + def test_retrieve_falls_back_to_legacy_root(self, storage, tmp_path): + """Drafts stored under the legacy ./data/drafts root (before the StorageService + switch) remain downloadable even after the configured root changed.""" + # Simulate a pre-migration draft: bytes only in the legacy root. + data = b"legacy draft" + sha = hashlib.sha256(data).hexdigest() + legacy_dir = tmp_path / "data" / "drafts" / "run-legacy" + legacy_dir.mkdir(parents=True) + (legacy_dir / sha).write_bytes(data) + storage._legacy_root = tmp_path / "data" / "drafts" + + assert storage.retrieve(f"draft:run-legacy:{sha}") == data + assert storage.retrieve_stream(f"draft:run-legacy:{sha}").read() == data + + def test_retrieve_prefers_configured_root(self, storage, tmp_path): + """The configured storage root wins over the legacy root.""" + data_new = b"new root" + sha = hashlib.sha256(data_new).hexdigest() + # Primary (StorageService) location. + storage._storage.save_bytes(FileCategory.DRAFT, f"run-x/{sha}", data_new) + # Stale legacy copy with different content — must be ignored. + legacy_dir = tmp_path / "data" / "drafts" / "run-x" + legacy_dir.mkdir(parents=True) + (legacy_dir / sha).write_bytes(b"stale") + storage._legacy_root = tmp_path / "data" / "drafts" + + assert storage.retrieve(f"draft:run-x:{sha}") == data_new # #endregion Test.AgentRuns.Artifacts diff --git a/frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.ts b/frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.ts index 1e47fb582..08d857463 100644 --- a/frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.ts +++ b/frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.ts @@ -86,7 +86,6 @@ describe("sidebarNavigation", () => { "dashboards", "datasets", "migration", - "assistant", ]); }); @@ -113,7 +112,6 @@ describe("sidebarNavigation", () => { "dashboards", "datasets", "migration", - "assistant", "git", "reports", "tools", diff --git a/frontend/src/lib/components/layout/sidebarNavigation.ts b/frontend/src/lib/components/layout/sidebarNavigation.ts index 6bd82ec66..b500a151a 100644 --- a/frontend/src/lib/components/layout/sidebarNavigation.ts +++ b/frontend/src/lib/components/layout/sidebarNavigation.ts @@ -128,16 +128,6 @@ export function buildSidebarSections(i18nState: I18nNavState, user: User | null { label: nav.migration_mappings || "Mappings", path: "/migration/mappings", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" }, ], }, - { - id: "assistant", - label: nav.ai_assistant || "AI Ассистент", - icon: "aiAssistant", - tone: "from-category-assistant-from to-category-assistant-to text-category-assistant-text ring-category-assistant-ring", - path: "/agent", - subItems: [ - { label: nav.ai_assistant || "AI Ассистент", path: "/agent" }, - ], - }, ], }; diff --git a/frontend/src/lib/models/AgentChat.StreamProcessor.svelte.ts b/frontend/src/lib/models/AgentChat.StreamProcessor.svelte.ts index c945a52d3..5ce19edab 100644 --- a/frontend/src/lib/models/AgentChat.StreamProcessor.svelte.ts +++ b/frontend/src/lib/models/AgentChat.StreamProcessor.svelte.ts @@ -314,6 +314,22 @@ export class StreamProcessor { // ── 036 Agent Run metadata ────────────────────────────── case "agent_run_started": + if (this.host.runModel) { + this.host.runModel.applyMetadata(meta); + // Persist the run marker so a reconnect / server restart can recover this + // run's artifacts (drafts) instead of showing an empty dialog. + if (typeof window !== "undefined" && meta.agent_run_id && this.host.uiContext?.objectId) { + sessionStorage.setItem( + "agent_scenario_run", + JSON.stringify({ runId: meta.agent_run_id, objectId: this.host.uiContext.objectId }), + ); + } + } else { + log("AgentChat.StreamProcessor", "EXPLORE", "Run metadata received but no run model", + { type: meta.type, run_id: meta.agent_run_id }, + "runModel is null — run tracker not initialized"); + } + break; case "scenario_progress": case "draft_artifacts": case "agent_run_terminal": diff --git a/frontend/src/lib/models/GitConfigModel.svelte.ts b/frontend/src/lib/models/GitConfigModel.svelte.ts index 94ded21e1..6a291d4fc 100644 --- a/frontend/src/lib/models/GitConfigModel.svelte.ts +++ b/frontend/src/lib/models/GitConfigModel.svelte.ts @@ -260,8 +260,8 @@ export class GitConfigModel { this.configs = [...this.configs, saved]; this.saveSuccess = (this._t?.settings as Record)?.git_config_saved as string || 'Git configuration saved'; notifications.success(this.saveSuccess); + this.startEdit(saved.id as string | number); } - this.cancelEdit(); } catch (e: unknown) { this.saveError = e instanceof Error ? e.message : 'Failed to save git config'; notifications.error(e instanceof Error ? e.message : 'Failed to save git config'); diff --git a/frontend/src/lib/models/__tests__/AgentChatStreamProcessor.test.ts b/frontend/src/lib/models/__tests__/AgentChatStreamProcessor.test.ts index f50126f14..1823376a4 100644 --- a/frontend/src/lib/models/__tests__/AgentChatStreamProcessor.test.ts +++ b/frontend/src/lib/models/__tests__/AgentChatStreamProcessor.test.ts @@ -61,6 +61,35 @@ describe("StreamProcessor — Metadata Dispatch", () => { processor = new StreamProcessor(host); }); + // #region TestAgentChat.StreamProcessor.RunMarker [C:2] [TYPE Test] + describe("agent_run_started marker persistence", () => { + it("stores {runId, objectId} so a restart can recover the run's artifacts", () => { + sessionStorage.clear(); + const hostWithRun = { + ...createMockHost(), + runModel: { applyMetadata: vi.fn() }, + uiContext: { objectId: "42" }, + } as unknown as StreamProcessorHost; + const p = new StreamProcessor(hostWithRun); + p["_onStreamData"]({ + id: "", conversation_id: "", role: "assistant", text: "", toolCalls: [], created_at: "", + metadata: { type: "agent_run_started", agent_run_id: "run-1" }, + }); + const marker = JSON.parse(sessionStorage.getItem("agent_scenario_run") || "null"); + expect(marker).toEqual({ runId: "run-1", objectId: "42" }); + }); + + it("does not store a marker without a run model or object id", () => { + sessionStorage.clear(); + processor["_onStreamData"]({ + id: "", conversation_id: "", role: "assistant", text: "", toolCalls: [], created_at: "", + metadata: { type: "agent_run_started", agent_run_id: "run-2" }, + }); + expect(sessionStorage.getItem("agent_scenario_run")).toBeNull(); + }); + }); + // #endregion TestAgentChat.StreamProcessor.RunMarker + // #region TestAgentChat.StreamProcessor.StreamToken [C:2] [TYPE Test] describe("stream_token", () => { it("appends token to partialText and partialTokens", () => { diff --git a/frontend/src/lib/models/__tests__/GitConfigModel.test.ts b/frontend/src/lib/models/__tests__/GitConfigModel.test.ts index 3eec6f54f..55701bfb4 100644 --- a/frontend/src/lib/models/__tests__/GitConfigModel.test.ts +++ b/frontend/src/lib/models/__tests__/GitConfigModel.test.ts @@ -196,7 +196,7 @@ describe('GitConfigModel — L1 invariants (no render)', () => { // saveConfig // ═══════════════════════════════════════════════════════════════ describe('saveConfig', () => { - it('creates new config (POST)', async () => { + it('creates new config (POST) and switches to edit mode for it', async () => { const saved = { id: 'new-1', name: 'New', provider: 'GITHUB', url: 'https://github.com', pat: 'tok', status: 'CONNECTED' }; vi.mocked(gitService.createConfig).mockResolvedValueOnce(saved); const formSnapshot = { name: 'New', provider: 'GITHUB', url: 'https://github.com', pat: 'tok', default_repository: '', default_branch: 'prod' }; @@ -207,7 +207,16 @@ describe('GitConfigModel — L1 invariants (no render)', () => { expect(gitService.createConfig).toHaveBeenCalledWith(formSnapshot); expect(gitService.updateConfig).not.toHaveBeenCalled(); expect(model.configs).toContainEqual(saved); - expect(model.isEditing).toBe(false); + expect(model.isEditing).toBe(true); + expect(model.editingConfigId).toBe('new-1'); + expect(model.formData).toEqual({ + name: 'New', + provider: 'GITHUB', + url: 'https://github.com', + pat: 'tok', + default_repository: '', + default_branch: 'prod', + }); expect(notifications.success).toHaveBeenCalledWith('Git configuration saved'); }); diff --git a/frontend/src/routes/settings/git/+page.svelte b/frontend/src/routes/settings/git/+page.svelte index 14d8ef3d8..522a9e3e6 100644 --- a/frontend/src/routes/settings/git/+page.svelte +++ b/frontend/src/routes/settings/git/+page.svelte @@ -91,7 +91,7 @@
{config.url}
- {config.status} + {config.status} diff --git a/specs/036-agent-test-stabilization/contracts/evidence.md b/specs/036-agent-test-stabilization/contracts/evidence.md index 6dc87272d..ee825e7d6 100644 --- a/specs/036-agent-test-stabilization/contracts/evidence.md +++ b/specs/036-agent-test-stabilization/contracts/evidence.md @@ -5,6 +5,19 @@ @RATIONALE Existing ScreenshotService capture behavior is reused through an adapter so scenario evidence has one masking and readiness implementation. @REJECTED Rebuilding screenshot capture inside scenario execution — rejected because it would fork Playwright/CDP behavior and weaken evidence auditability. +## Module Reuse Map (036 LLM verification tooling) + +The adapter does not implement capture, masking, VLM submission, or redaction. It reuses the existing `llm_analysis` plugin modules as the single source of truth: + +| Concern | Reused module (real contract ID) | Where it lives | +|---|---|---| +| Playwright capture, login/CSRF, tab traversal, stabilization, webp conversion | `Plugin.Service.ScreenshotService` | `backend/src/plugins/llm_analysis/service.py` | +| VLM/LLM provider submission (multimodal + JSON mode, retries, image optimization) | `Plugin.Service.LLMClient` | `backend/src/plugins/llm_analysis/service.py` | +| Masked-artifact registration + capture_meta | `Services.AgentRuns.Evidence` (`register_screenshot_draft` / `register_masked_derivative`) | `backend/src/services/agent_runs/evidence.py` | +| Redaction of logs/raw responses before persistence | `Plugin.Service.RedactionService` | `backend/src/plugins/llm_analysis/service.py` | + +`@REJECTED` Reimplementing any of the above in `services/agent_runs/` — a second Playwright/CDP path or a second LLM client would diverge from the established capture/analysis behavior and break evidence auditability. + # #region AgentRuns.Evidence.Adapter [C:5] [TYPE Module] [SEMANTICS agent-run,evidence,screenshot,capture,llm] # @ingroup AgentRuns # @BRIEF Bridge existing ScreenshotService/VLM pipeline to AgentRun/DraftArtifact. @@ -12,10 +25,13 @@ # @REJECTED Rebuilding screenshot capture inside AgentRun lifecycle — rejected because scenario runs should consume the established capture contract. # @LAYER Service # @RELATION DEPENDS_ON -> [AgentRuns.Artifacts.Register] -# @RELATION DEPENDS_ON -> [Spec.LlmAnalysisPlugin.ScreenshotService] +# @RELATION DEPENDS_ON -> [Plugin.Service.ScreenshotService] +# @RELATION DEPENDS_ON -> [Plugin.Service.LLMClient] +# @RELATION DEPENDS_ON -> [Plugin.Service.RedactionService] # @DATA_CONTRACT CaptureSpec + AgentRun -> DraftArtifact[] # @INVARIANT Original capture never reaches external LLM; only masked derivative does. # @INVARIANT Every capture carries capture_meta for reproducibility. +# @INVARIANT VLM submission reuses `Plugin.Service.LLMClient`; a second provider client is forbidden. # @TEST_EDGE no_mask_selectors -> original and masked artifacts remain separate. # @TEST_EDGE vlm_failure -> evidence remains valid WARN; analysis becomes inconclusive. # @TEST_EDGE missing_capture_meta -> 422. diff --git a/specs/037-superset-baseline-engine/contracts/modules.md b/specs/037-superset-baseline-engine/contracts/modules.md index 7ad2a5da5..6c00bd886 100644 --- a/specs/037-superset-baseline-engine/contracts/modules.md +++ b/specs/037-superset-baseline-engine/contracts/modules.md @@ -188,11 +188,14 @@ # @SIDE_EFFECT None. # @DATA_CONTRACT ScreenshotEvidence + VisualBaseline -> ComparisonResult # @INVARIANT Visual comparison never uses metric policies; cross-kind comparison returns inconclusive with code. +# @RELATION DEPENDS_ON -> [BaselineEngine.Visual.SSIM] +# @RELATION DEPENDS_ON -> [BaselineEngine.Verification.ExecutorVisual.Async] # @TEST_EDGE exact_match -> pass with matching digests. # @TEST_EDGE perceptual_within_tolerance -> pass with ssim/metadata. # @TEST_EDGE layout_fingerprint_changed -> stale_visual_baseline. # @TEST_EDGE metric_baseline_with_visual_policy -> catalog load rejects. # @RATIONALE Visual baseline is a distinct assertion dimension; conflating it with metric baselines would silently change comparison semantics. +# @RATIONALE Perceptual comparison and authoritative-fingerprint execution are reused from `BaselineEngine.Visual.SSIM` and `BaselineEngine.Verification.ExecutorVisual.Async` — never reimplemented in the scenario path. # @REJECTED Using LLM/VLM judgment as visual baseline truth — it is non-deterministic and cannot serve as stable expected state. # #endregion BaselineEngine.Visual.Compare diff --git a/specs/038-dashboard-scenario-model/contracts/modules.md b/specs/038-dashboard-scenario-model/contracts/modules.md index 4336737e6..22fd790fb 100644 --- a/specs/038-dashboard-scenario-model/contracts/modules.md +++ b/specs/038-dashboard-scenario-model/contracts/modules.md @@ -130,9 +130,12 @@ # @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. +# @REJECTED A second browser-capture implementation in `scenario/` — the capture MUST delegate to `Plugin.Service.ScreenshotService` (via `Services.AgentRuns.Evidence`), never fork Playwright/CDP behavior. # @DATA_CONTRACT ScreenshotCaptureSpec + AgentRun -> DraftArtifactRef[] # @RELATION DEPENDS_ON -> [AgentRuns.Evidence.Adapter] +# @RELATION DEPENDS_ON -> [Plugin.Service.ScreenshotService] # @INVARIANT Step output refs link to artifact ids, not filesystem paths. +# @INVARIANT Runtime browser capture is delegated to `Plugin.Service.ScreenshotService.capture_dashboard_chunks`; a stub registration without real capture bytes is incomplete. # @TEST_EDGE capture_timeout -> step marked inconclusive; no artifact registered. # @TEST_EDGE masking_applied -> two artifacts: original + masked; step output refs masked. # #endregion ScenarioGraph.Capture.Dispatch @@ -147,11 +150,16 @@ # @DATA_CONTRACT DraftArtifactRef + VlmAnalysis -> VlmFinding[] # @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. +# @INVARIANT VLM submission reuses `Plugin.Service.LLMClient` (multimodal path) resolved through `Services.LlmProvider.LLMProviderService`; a second provider client is forbidden. +# @RELATION DEPENDS_ON -> [Plugin.Service.LLMClient] +# @RELATION DEPENDS_ON -> [Services.LlmProvider.LLMProviderService] +# @RELATION DEPENDS_ON -> [Plugin.Service.RedactionService] # @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. +# @REJECTED A stub/default VLM submit returning empty findings — the provider integration MUST call `Plugin.Service.LLMClient`; the 038 VLM layer only parses and validates the typed response. # #endregion ScenarioGraph.Vlm.Analyze # #region ScenarioGraph.Human.Disposition [C:3] [TYPE Function] [SEMANTICS scenario,human,checkpoint,disposition] diff --git a/specs/038-dashboard-scenario-model/research.md b/specs/038-dashboard-scenario-model/research.md index cca5078cb..91a70f38b 100644 --- a/specs/038-dashboard-scenario-model/research.md +++ b/specs/038-dashboard-scenario-model/research.md @@ -84,4 +84,22 @@ Errors block draft-pack compilation. Warnings may allow preview but are repeated Supplying parameters produces a new immutable scenario revision with parent_revision_hash. Unrelated steps retain ids and serialization. Manual conversion and selector hints are explicit resolution operations with audit reason. +## 9. LLM Verification Tooling — Module Reuse + +Capture and VLM analysis are **not** new implementations; they are thin orchestration over the existing `llm_analysis` plugin infrastructure. + +| Concern | Reused module (real contract ID) | File | +|---|---|---| +| Playwright capture (login/CSRF, tab traversal, stabilization, chunk capture, webp) | `Plugin.Service.ScreenshotService` | `backend/src/plugins/llm_analysis/service.py` | +| VLM/LLM provider submission (multimodal, JSON mode, retries, image optimization, payload sizing) | `Plugin.Service.LLMClient` | `backend/src/plugins/llm_analysis/service.py` | +| Provider resolution (multimodal check, encrypted API key, token config) | `Services.LlmProvider.LLMProviderService` | `backend/src/services/llm_provider.py` | +| Artifact registration + masking | `Services.AgentRuns.Evidence` (`register_screenshot_draft` / `register_masked_derivative`) | `backend/src/services/agent_runs/evidence.py` | +| Redaction of logs/raw responses | `Plugin.Service.RedactionService` | `backend/src/plugins/llm_analysis/service.py` | + +**Decision**: `ScenarioGraph.Capture.Dispatch` (038) registers evidence through the 036 bridge AND delegates the actual browser capture to `Plugin.Service.ScreenshotService.capture_dashboard_chunks` at runtime. Registering artifacts without real capture bytes is a stub, not a capture. +**Decision**: `ScenarioGraph.Vlm.Analyze` (038) parses/validates typed `VlmFinding[]`; the actual provider call is injected as `submit=` and MUST be backed by `Plugin.Service.LLMClient` + `Services.LlmProvider.LLMProviderService`. The `_default_submit` placeholder (returns empty findings) is a test seam only and must be replaced by a real provider submit in production wiring. +**Decision**: Provider selection for VLM reuses the multimodal-required validation semantics of `Services.ValidationService.ValidationTaskService._validate_provider`; a non-multimodal provider is rejected before analysis. +**Alternative rejected**: Building a second `VlmProviderClient` or a second Playwright capture path inside `dashboard_testing/` — both would fork retry/SSL/masking behavior from the established plugin and double maintenance. +**@REJECTED**: VLM output as deterministic assertion truth; capture without `Plugin.Service.ScreenshotService`; provider calls without `Plugin.Service.LLMClient`/`Services.LlmProvider.LLMProviderService`. + #endregion DashboardScenarioModel.Research diff --git a/specs/038-dashboard-scenario-model/spec.md b/specs/038-dashboard-scenario-model/spec.md index 261a13944..cff088fd8 100644 --- a/specs/038-dashboard-scenario-model/spec.md +++ b/specs/038-dashboard-scenario-model/spec.md @@ -120,8 +120,8 @@ - **AGSCN-FR-007**: The model MUST allow manual/human checkpoint steps where automation is unsafe, unavailable, or underspecified. - **AGSCN-FR-008**: Scenario output MUST be deterministic for the same dashboard query model, checklist template, baseline catalog, and user parameters. - **AGSCN-FR-009**: The scenario model MUST remain implementation-neutral and must not require the user to choose low-level artifacts such as Playwright, XLSX, or API output upfront. -- **AGSCN-FR-010**: Screenshot steps MUST carry a capture specification: target (tab/viewport), viewport dimensions, readiness strategy, masking selectors, and max wait. -- **AGSCN-FR-011**: VLM-based visual analysis steps MUST produce typed findings referencing the source screenshot artifact, including severity, region, confidence, model/prompt provenance, and a bounded textual description. +- **AGSCN-FR-010**: Screenshot steps MUST carry a capture specification: target (tab/viewport), viewport dimensions, readiness strategy, masking selectors, and max wait. Runtime capture MUST delegate to the existing `Plugin.Service.ScreenshotService` via the 036 Evidence adapter (`Services.AgentRuns.Evidence`) — a second Playwright/CDP implementation is forbidden. +- **AGSCN-FR-011**: VLM-based visual analysis steps MUST produce typed findings referencing the source screenshot artifact, including severity, region, confidence, model/prompt provenance, and a bounded textual description. Submission MUST reuse `Plugin.Service.LLMClient` resolved through `Services.LlmProvider.LLMProviderService` (multimodal provider, encrypted-key handling, JSON mode); a stub/default submit that returns empty findings without a real provider call is incomplete. Raw VLM responses MUST be redacted with `Plugin.Service.RedactionService` before persistence. - **AGSCN-FR-012**: Human checkpoint steps MAY reference specific VLM finding IDs. Resolution options (confirm, dismiss, inconclusive) MUST be typed and auditable. Disposition changes finding status, not graph structure. ### Key Entities diff --git a/specs/038-dashboard-scenario-model/traceability.md b/specs/038-dashboard-scenario-model/traceability.md index 7d9b88ace..44e2a0d9f 100644 --- a/specs/038-dashboard-scenario-model/traceability.md +++ b/specs/038-dashboard-scenario-model/traceability.md @@ -61,4 +61,13 @@ - [x] Every task ID (Txxx) appears in `tasks.md` - [x] Impact table covers every contract with downstream dependents +## Module Reuse Annex (LLM verification tooling) + +038 orchestration layers reuse existing plugin/service contracts — see `research.md` §9 and `contracts/modules.md` (`ScenarioGraph.Capture.Dispatch`, `ScenarioGraph.Vlm.Analyze`): + +| 038 contract | Reused existing contract | Rationale | +|---|---|---| +| ScenarioGraph.Capture.Dispatch | Plugin.Service.ScreenshotService, Services.AgentRuns.Evidence | One Playwright/CDP capture path; evidence auditability | +| ScenarioGraph.Vlm.Analyze | Plugin.Service.LLMClient, Services.LlmProvider.LLMProviderService, Plugin.Service.RedactionService | One provider client; multimodal-required validation; redaction reuse | + #endregion DashboardScenarioModel.Traceability diff --git a/specs/039-dashboard-scenario-ui/spec.md b/specs/039-dashboard-scenario-ui/spec.md index 1cd64ac0c..3d0291ba6 100644 --- a/specs/039-dashboard-scenario-ui/spec.md +++ b/specs/039-dashboard-scenario-ui/spec.md @@ -129,13 +129,25 @@ Agent Workspace (AGUI-FR-001..013) Pipeline Views (AGUI-FR-014..016) ────────────────────────────────── ────────────────────────────── Entry: «Создать сценарий» → /agent Entry: deployment page, release page, Interaction: диалог с агентом dashboard page -State: WorkspaceModel + AgentRunModel Interaction: кнопки, без чата -Trigger: manual (аналитик) State: VerificationRun[] + StructureDiff -Data: 038 ScenarioResponse, 036 drafts Trigger: deploy_to_preprod, release_create, - scheduled, etl_completed (автоматически) +State: WorkspaceModel + AgentRunModel State: VerificationRun[] + StructureDiff +Trigger: manual (аналитик) Trigger: deploy_to_preprod, release_create, +Data: 038 ScenarioResponse, 036 drafts scheduled, etl_completed (автоматически) Save: через 036 HITL gate Save: validate/approve/publish (pipeline gates) ``` +### LLM Verification Tooling Reuse (039) + +The EvidencePanel and VlmFindingReviewCard components consume **DTOs only** — they never call a provider, capture a screenshot, or parse LLM prose. All LLM verification tooling is reused from upstream specs: + +| UI surface | Reused contract / DTO | Producer | +|---|---|---| +| EvidencePanel screenshot viewer + capture metadata | `evidence_captured` event, `ScreenshotEvidence` DraftArtifact (capture_meta) | 036 Evidence adapter + `Plugin.Service.ScreenshotService` | +| VlmFindingReviewCard (severity, region, confidence, provenance) | `VlmFinding` / `VlmAnalysis` DTOs | 038 `ScenarioGraph.Vlm.Analyze` over `Plugin.Service.LLMClient` | +| Disposition controls (confirm/dismiss/inconclusive) | `HumanDisposition` DTO, 036 audit events | 038 `ScenarioGraph.Human.Disposition` | +| Visual baseline comparison badges | `ComparisonResult` (ssim/pass/stale_visual_baseline) | 037 `BaselineEngine.Visual.Compare` over `BaselineEngine.Visual.SSIM` | + +`@REJECTED` Frontend-side LLM/VLM calls or screenshot rendering heuristics — the UI renders typed findings and evidence only; provider calls stay on the backend in reused plugin modules. + ### Key Entities — Agent Workspace - **ScenarioEntryAction**: Dashboard-page action that launches `/agent` with dashboard scenario intent. Only valid in manual (ad-hoc) flow.