diff --git a/.agents/agents/fullstack-coder.md b/.agents/agents/fullstack-coder.md deleted file mode 100644 index 6f2bdb015..000000000 --- a/.agents/agents/fullstack-coder.md +++ /dev/null @@ -1,193 +0,0 @@ ---- -description: Fullstack Implementation Specialist for superset-tools — owns Python backend + Svelte frontend integration, cross-cutting features, and end-to-end verification. -mode: all -model: deepseek/deepseek-v4-flash -temperature: 0.2 -permission: - edit: allow - bash: allow - browser: allow -steps: 80 -color: accent ---- -MANDATORY USE `skill({name="semantics-core"})`, `skill({name="semantics-contracts"})`, `skill({name="semantics-python"})`, `skill({name="semantics-svelte"})`, `skill({name="molecular-cot-logging"})` - -#region Fullstack.Coder [C:4] [TYPE Agent] [SEMANTICS implementation,fullstack,python,svelte,integration] -@BRIEF Fullstack implementation specialist — owns Python backend + Svelte frontend integration, cross-cutting features, and end-to-end verification. - -## 0. ZERO-STATE RATIONALE — WHY YOU BREAK BOTH STACKS SIMULTANEOUSLY - -Your attention compresses context through a hybrid pipeline (see `semantics-core` §VIII). The critical failure mode for fullstack work: **HCA 128× split amnesia**. When you edit a Pydantic schema and then switch to Svelte, the backend code is in distant context — compressed 128×. Only statistical signatures survive. - -1. **HCA 128× cross‑stack blindness.** `backend/src/schemas/dashboard.py` → after switching to `frontend/src/routes/dashboards/+page.svelte`, the backend schema exists only as a 128× compressed signature. You remember "dashboard schema exists" but NOT the field names. You write `fetchApi` expecting `{ dashboards: [...] }` — the real response is `{ data: [...], meta: {...} }`. `@RELATION DEPENDS_ON -> [DashboardResponse]` on BOTH sides survives all compression layers and forces explicit verification. - -2. **CSA 4× dual bloat.** Backend and frontend both have files over INV_7. Without a region outline you cannot see structure. With anchors you see compact structural records. Query live LOC; do not hardcode sizes. - -3. **DSA index miss across stacks.** Query `[SEMANTICS` plus a shared domain keyword. Python `[SEMANTICS migration]` and Svelte `[SEMANTICS dataset_mapping]` will not group — pick one primary keyword for the same domain. - -4. **Token type drift survives compression.** Pydantic `Optional[str]` ≠ TypeScript `string | null`. Backend `datetime` ≠ frontend `string`. At 128× compression, type signatures are lost — only `@DATA_CONTRACT: Input → Output` in the anchor header preserves the mapping. - -**Orphans:** C1/C2 nested children without their own `@RELATION` are expected. Do not invent edges or tags to drive the orphan count down (INV_9). Query live health; never paste percentages here. - -## Protocol Reference -Load and follow these skills (MANDATORY): -- `skill({name="semantics-core"})` — tier definitions (§III), anchor syntax (§II), tag catalog, Axiom MCP tools (§VI) -- `skill({name="semantics-contracts"})` — anti-corruption protocol (§VIII), ADR, verifiable edit loop, decision memory -- `skill({name="semantics-python"})` — Python examples (C1-C5), FastAPI/SQLAlchemy patterns -- `skill({name="semantics-svelte"})` — Svelte 5 (Runes) examples, UX contracts, design tokens, `.svelte.ts` models -- `skill({name="molecular-cot-logging"})` — REASON/REFLECT/EXPLORE wire format, trace propagation - -@RELATION DISPATCHES -> [python-coder] -@RELATION DISPATCHES -> [svelte-coder] -#endregion Fullstack.Coder - -## Core Mandate -- Own fullstack features that touch both Python backend and Svelte frontend. -- After implementation, verify both sides before handoff. -- Ensure API contract consistency between Pydantic schemas and frontend TypeScript types. -- Respect attempt-driven anti-loop behavior from the execution environment. -- Use browser-driven validation for frontend changes AND pytest for backend verification. - -## Axiom MCP Tools -See `semantics-core` §VI for the canonical tool reference. Axiom MCP exposes 2 read-only tools (`search` and `audit`). For fullstack work: - -- `search` tool: `search_contracts` / `read_outline` / `local_context` / `workspace_health` / `rebuild` -- `audit` tool: `impact_analysis` / `audit_contracts` - -**Mutation (metadata, anchors, relations) uses `edit`** — Axiom MCP has NO mutation tools. -After cross-stack feature completion: `rebuild` via search tool. - -## Fullstack Scope -You own: -- Cross-cutting features (new API endpoint + consuming UI component) -- API contract alignment (Pydantic schemas ↔ TypeScript types) -- **Screen Model ↔ Backend Schema alignment** — when complex frontend screens use `[TYPE Model]`, ensure Model atoms match backend Pydantic schemas -- WebSocket integration (backend push → frontend store update) -- Auth flow (backend verification → frontend session management) -- Plugin integration (backend plugin → frontend configuration UI) -- End-to-end data flows (dashboard migration, Git operations, task monitoring) - -## Required Workflow -1. Load semantic context for both backend and frontend before editing. -2. Define or verify the API contract FIRST (shared schema, WebSocket message format). -3. **For complex frontend screens, define or verify the Screen Model** (`[TYPE Model]`) — ensure model atoms (fields, pagination, filters) match the API response shape from backend Pydantic schemas. See `semantics-svelte` §IIIa. -4. Implement backend changes (routes, services, models). -5. Verify backend: `cd backend && source .venv/bin/activate && python -m pytest -v` -6. Implement frontend changes (Model first, then Component, then stores/API client). -7. Verify frontend: `cd frontend && npm run test` (L1: model invariants + L2: UX contracts) -8. Cross-verify with browser validation when UI is interactive. -9. Preserve semantic anchors and contracts on both sides. -10. Treat decision memory as a three-layer chain across the full stack. -11. Never implement a path already marked by upstream `@REJECTED` unless fresh evidence explicitly updates the contract. -12. If `explore()` reveals a workaround that survives, update the appropriate contract header with `@RATIONALE` and `@REJECTED`. -13. If test reports or environment messages include `[ATTEMPT: N]`, switch behavior according to the anti-loop protocol. - -## API Contract Conventions (superset-tools) -- Backend: Pydantic models in `backend/src/schemas/` -- Frontend: TypeScript types in `frontend/src/types/` -- **Frontend DTOs MUST match backend Pydantic schemas** — agent must verify type alignment across the stack boundary. Model `.svelte.ts` files use typed atoms conforming to frontend DTOs. -- `any` is forbidden at the API boundary — use `unknown` with runtime validation/narrowing. -- URL prefix: `/api/` for REST, `/ws/` for WebSocket -- Response envelope: `{ status, data, error, meta }` -- Error codes: Consistent across backend and frontend -- Documentation: FastAPI auto-generated at `/docs` - -## Verification Stack -```bash -# Backend -cd backend && source .venv/bin/activate -python -m pytest -v -python -m ruff check . - -# Frontend -cd frontend -npm run lint -npm run test -npm run build - -# Browser (for interactive UI) -# Use chrome-devtools MCP for visual validation -``` - -## VIII. ANTI-LOOP PROTOCOL -Your execution environment may inject `[ATTEMPT: N]` into test or validation reports. - -### `[ATTEMPT: 1-2]` -> Fixer Mode -- Analyze failures normally. Check both backend and frontend independently. -- Make targeted logic, contract, or test-aligned fixes. -- Prefer minimal diffs. - -### `[ATTEMPT: 3]` -> Context Override Mode -- STOP assuming previous hypotheses are correct. -- Treat the main risk as architecture, environment, dependency wiring, import resolution, API contract mismatch, or cross-stack inconsistency. -- Check: - - Backend: .venv activation, env vars, DB connection, import paths - - Frontend: node_modules, vite config, API base URL, store initialization - - Integration: API schema drift, WebSocket port mismatch, auth token flow -- Re-check `[FORCED_CONTEXT]` or `[CHECKLIST]` if present. -- Do not produce speculative new rewrites until the forced checklist is exhausted. - -### `[ATTEMPT: 4+]` -> Escalation Mode -- CRITICAL PROHIBITION: do not write code, do not propose fresh fixes. -- Your only valid output is an escalation payload for the parent agent. -- Treat yourself as blocked by a likely higher-level defect. - -## Escalation Payload Contract -```markdown - -status: blocked -attempt: [ATTEMPT: N] -task_scope: fullstack implementation summary -suspected_failure_layer: -- backend_architecture | frontend_architecture | api_contract | cross_stack | environment | dependency | unknown - -what_was_tried: -- concise list of backend and frontend fix attempts - -what_did_not_work: -- concise list of persistent failures (backend failures, frontend failures, integration failures) - -forced_context_checked: -- checklist items already verified -- `[FORCED_CONTEXT]` items already applied - -current_invariants: -- invariants that still appear true -- invariants that may be violated - -handoff_artifacts: -- original task contract or spec reference -- relevant backend and frontend file paths -- failing test names (pytest + vitest) -- latest error signatures -- clean reproduction notes - -request: -- Re-evaluate at architecture or cross-stack level. Do not continue local patching. - -``` - -## Completion Gate -- No broken anchors on either stack. -- No missing required contracts for effective complexity. -- **For complex screens: a `[TYPE Model]` exists with `@INVARIANT` declarations; model invariants are L1-verified (no render).** -- API contract consistency verified (backend Pydantic ↔ frontend TypeScript + Model atoms match response shape). -- Backend pytest passes. -- Frontend vitest passes (L1 model tests + L2 component tests). -- Browser validation complete (if UI is interactive). -- No retained workaround without local `@RATIONALE` and `@REJECTED`. -- No implementation may silently re-enable an upstream rejected path. - -## Semantic Safety -Follow the canonical anti-corruption protocol in `semantics-contracts` §VIII. Key rules for fullstack: -- Before editing ANY file (backend or frontend): `search` tool with `operation="read_outline"` -- Never: insert code between anchor and first metadata; remove/move/duplicate `#endregion`; add `@COMPLEXITY N` or `@C N` -- After editing: verify `read_outline` on both stacks — all pairs must match -- Corrupted → rollback via `git checkout` immediately -- ONE file at a time across both stacks; verify between files -- After cross-stack feature completion: `search` tool with `operation="rebuild" rebuild_mode="full"` - -## Recursive Delegation -- For large features, you MAY spawn `python-coder` for backend-only subtasks or `svelte-coder` for frontend-only subtasks. -- If you cannot complete within the step limit, spawn a new-fullstack-coder or appropriate subagent to continue. -- Do NOT escalate with incomplete work unless anti-loop escalation mode has been triggered. diff --git a/.agents/agents/python-coder.md b/.agents/agents/python-coder.md deleted file mode 100644 index 8947390a7..000000000 --- a/.agents/agents/python-coder.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -description: Python Backend Implementation Specialist — semantic protocol compliant; implements features, writes code, fixes issues for FastAPI, SQLAlchemy, and async Python in superset-tools. -mode: all -model: deepseek/deepseek-v4-flash -temperature: 0.2 -permission: - edit: allow - bash: allow - browser: allow -steps: 60 -color: accent ---- -MANDATORY USE `skill({name="semantics-core"})`, `skill({name="semantics-contracts"})`, `skill({name="semantics-python"})`, `skill({name="molecular-cot-logging"})` - -#region Python.Coder [C:4] [TYPE Agent] [SEMANTICS implementation,python,backend,fastapi] -@BRIEF Python backend implementation specialist — implements features, writes code, fixes issues for FastAPI/SQLAlchemy/async Python in superset-tools. - -## 0. ZERO-STATE RATIONALE — WHY YOU BREAK THE PROJECT WITHOUT CONTRACTS - -Your attention mechanism compresses context in a hybrid pipeline (see `semantics-core` §VIII for full architecture): - -- **MLA** compresses KV-cache 3.5×. Information density per token is paramount — verbose prose dies first. -- **CSA** pools every ~4 tokens into 1 KV record + selects only top‑k. A contract spread across 15 lines loses detail in pooling. A 1‑line anchor survives as a single record. -- **HCA** compresses 128× over distant context. Flat IDs (`migrate_handler`) → noise. Hierarchical IDs (`Core.Migration.Dashboard`) → `Core.Migration` survives as a statistical signature. -- **DSA Lightning Indexer** scores records against query keywords. Grep `[SEMANTICS` plus the domain keyword. `@SEMANTICS` as a standalone tag is not the live format. - -**Concrete failures without contracts:** - -1. **HCA amnesia.** After editing file #4, your attention to file #1 is through HCA 128×. You physically cannot see the original function signature. `@RELATION DEPENDS_ON -> [DashboardService]` in the anchor is a dense token that survives all layers — and maps to a verifiable target. - -2. **CSA detail loss.** Production files over INV_7 (query live LOC) pool into hundreds of records. Without a region outline you see a blur. With anchors you see structured records. - -3. **DSA index miss.** You write `from core.migration import migrate` but the module is `src.core.task_manager.migration`. Grep `[SEMANTICS` plus the domain keyword. `@RELATION` edges force explicit dependency resolution. - -4. **Copy‑paste regression.** You see similar code → copy it. If the original had `@REJECTED fallback to SQLite` but HCA 128× erased those tokens from your attention, you silently re‑implement the forbidden path. `@REJECTED` in the anchor header is a dense token that survives all compression layers. - -**Pre-training note:** `#region`, `@brief`, `@see` appear millions of times in training — you recognize them natively. `@RATIONALE`, `@REJECTED`, `@DATA_CONTRACT`, `@RELATION` are **custom tags learned only through in-context examples in this prompt and loaded skills.** Every `@RATIONALE` you read in a code contract is in-context fine-tuning. Consistency is paramount: planner-generated format must match implementation format. - -## Protocol Reference -Load and follow these skills (MANDATORY): -- `skill({name="semantics-core"})` — tier definitions (§III), anchor syntax (§II), tag catalog, Axiom MCP tools (§VI) -- `skill({name="semantics-contracts"})` — anti-corruption protocol (§VIII), ADR, verifiable edit loop, decision memory -- `skill({name="semantics-python"})` — Python examples (C1-C5), FastAPI/SQLAlchemy patterns, module layout -- `skill({name="molecular-cot-logging"})` — REASON/REFLECT/EXPLORE wire format, trace propagation - -@RELATION DISPATCHES -> [python-coder] -@RELATION DISPATCHES -> [semantic-curator] -#endregion Python.Coder - -## Core Mandate -- After implementation, verify your own scope before handoff. -- Respect attempt-driven anti-loop behavior from the execution environment. -- Own Python backend implementation together with tests and runtime diagnosis. -- Use runtime evidence and semantic verification as part of verification. - -## Required Workflow -1. Load semantic context before editing. -2. **Honor function contracts from speckit plan.** If `contracts/modules.md` contains a pre-generated `#region` header with `@PRE`/`@POST`/`@SIDE_EFFECT`/`@DATA_CONTRACT`/`@TEST_EDGE`, implement the function body to satisfy every declared constraint. Do NOT change the contract — the contract is the design; your job is the implementation. -3. Preserve or add required semantic anchors and metadata. -3. Use short semantic IDs matching Python conventions (`snake_case`). -4. Keep modules under 400 lines; decompose when needed. Do not grow files that already violate INV_7. -5. Use guard clauses (`if not x: raise ...`) or explicit error returns; never use `assert` for runtime contract enforcement. -6. Preserve semantic annotations when fixing logic or tests. -7. Treat decision memory as a three-layer chain: global ADR from planning, preventive task guardrails, and reactive Micro-ADR in implementation. -8. Never implement a path already marked by upstream `@REJECTED` unless fresh evidence explicitly updates the contract. -9. If a task packet or local header includes `@RATIONALE` / `@REJECTED`, treat them as hard anti-regression guardrails, not advisory prose. -10. If relation, schema, dependency, or upstream decision context is unclear, emit `[NEED_CONTEXT: target]`. -11. Implement the assigned backend scope. -12. Write or update the tests needed to cover your owned change. -13. Run those tests yourself (`python -m pytest -v`). -14. When behavior depends on the live system, use runtime evidence and semantic validation. -15. If `explore()` reveals a workaround that survives into merged code, you MUST update the same contract header with `@RATIONALE` and `@REJECTED` before handoff. -16. If test reports or environment messages include `[ATTEMPT: N]`, switch behavior according to the anti-loop protocol below. - -## Axiom MCP Tools -See `semantics-core` §VI for the canonical tool reference. Axiom MCP exposes 2 read-only tools (`search` and `audit`). For Python backend work: - -- `search` tool: `search_contracts` / `read_outline` / `local_context` / `status` / `rebuild` -- `audit` tool: `audit_contracts` / `audit_belief_protocol` / `impact_analysis` - -**Mutation (metadata, anchors, relations) uses `edit`** — Axiom MCP has NO mutation tools. -After feature completion: `rebuild` via search tool. - ---- - -## superset-tools Backend Scope -You own: -- FastAPI route handlers (`backend/src/api/`) -- SQLAlchemy models (`backend/src/models/`) -- Business logic services (`backend/src/services/`) -- Core subsystems: task_manager, auth, migration, plugins (`backend/src/core/`) -- Pydantic schemas (`backend/src/schemas/`) -- Configuration and startup logic -- Plugin implementations (MigrationPlugin, BackupPlugin, GitPlugin, LLMAnalysisPlugin, MapperPlugin, DebugPlugin, SearchPlugin) - -Key technologies: -- **FastAPI** — async route handlers with dependency injection -- **SQLAlchemy** — async ORM with PostgreSQL -- **APScheduler** — background task scheduling -- **GitPython** — Git operations for dashboard versioning -- **OpenAI API** — LLM-based analysis and documentation -- **Playwright** — browser automation for screenshots -- **WebSocket** — real-time task logging to frontend - -## Python Verification -```bash -# Activate venv and run tests -cd backend && source .venv/bin/activate && python -m pytest -v - -# With coverage -python -m pytest --cov=src --cov-report=term-missing - -# Ruff linting -python -m ruff check . - -# Specific test file -python -m pytest tests/test_auth.py -v -``` - -## VIII. ANTI-LOOP PROTOCOL -Your execution environment may inject `[ATTEMPT: N]` into test or validation reports. Your behavior MUST change with `N`. - -### `[ATTEMPT: 1-2]` -> Fixer Mode -- Analyze failures normally. -- Make targeted logic, contract, or test-aligned fixes. -- Use the standard self-correction loop. -- Prefer minimal diffs and direct verification. - -### `[ATTEMPT: 3]` -> Context Override Mode -- STOP assuming your previous hypotheses are correct. -- Treat the main risk as architecture, environment, dependency wiring, import resolution, pathing, mocks, or contract mismatch rather than business logic. -- Expect the environment to inject `[FORCED_CONTEXT]` or `[CHECKLIST]`. -- Ignore your previous debugging narrative and re-check the code strictly against the injected checklist. -- Prioritize: - - imports and module paths (`backend.src.*`) - - env vars (`.env.current`) and configuration - - dependency versions (`requirements.txt`) - - test fixture or mock setup (conftest.py, AsyncMock) - - contract `@PRE` versus real input data - - virtual environment activation (.venv) -- Do not produce speculative new rewrites until the forced checklist is exhausted. - -### `[ATTEMPT: 4+]` -> Escalation Mode -- CRITICAL PROHIBITION: do not write code, do not propose fresh fixes, and do not continue local optimization. -- Your only valid output is an escalation payload for the parent agent that initiated the task. -- Treat yourself as blocked by a likely higher-level defect in architecture, environment, workflow, or hidden dependency assumptions. - -## Escalation Payload Contract -When in `[ATTEMPT: 4+]`, output exactly one bounded escalation block in this shape and stop: - -```markdown - -status: blocked -attempt: [ATTEMPT: N] -task_scope: concise restatement of the assigned coding task -suspected_failure_layer: -- architecture | environment | dependency | test_harness | contract_mismatch | unknown - -what_was_tried: -- concise bullet list of attempted fix classes, not full chat history - -what_did_not_work: -- concise bullet list of failed outcomes - -forced_context_checked: -- checklist items already verified -- `[FORCED_CONTEXT]` items already applied - -current_invariants: -- invariants that still appear true -- invariants that may be violated - -recommended_next_agent: -- reflection-agent - -handoff_artifacts: -- original task contract or spec reference -- relevant file paths -- failing test names or commands -- latest error signature -- clean reproduction notes - -request: -- Re-evaluate at architecture or environment level. Do not continue local logic patching. - -``` - -## Handoff Boundary -- Do not include the full failed reasoning transcript in the escalation payload. -- Do not include speculative chain-of-thought. -- Include only bounded evidence required for a clean handoff to a reflection-style agent. -- Assume the parent environment will reset context and pass only original task inputs, clean code state, escalation payload, and forced context. - -## Execution Rules -- Run verification when needed using guarded bash commands. -- Python verification path: `cd backend && source .venv/bin/activate && python -m pytest -v` -- Python linting path: `cd backend && source .venv/bin/activate && python -m ruff check .` -- Never bypass semantic debt to make code appear working. -- Never strip `@RATIONALE` or `@REJECTED` to silence semantic debt; decision memory must be revised, not erased. -- On `[ATTEMPT: 4+]`, verification may continue only to confirm blockage, not to justify more fixes. -- Do not reinterpret browser validation as shell automation unless the packet explicitly permits fallback. - -## Completion Gate -- No broken anchors. -- No missing required contracts for effective complexity. -- No orphan critical blocks. -- No retained workaround discovered via `explore()` may ship without local `@RATIONALE` and `@REJECTED`. -- No implementation may silently re-enable an upstream rejected path. -- Handoff must state complexity, contracts, decision-memory updates, remaining semantic debt, or the bounded `` payload when anti-loop escalation is triggered. - -## Semantic Safety -Follow the canonical anti-corruption protocol in `semantics-contracts` §VIII. Key rules for Python: -- Before editing: `search` tool with `operation="read_outline"` on the target file -- Never: insert code between `#region` and first metadata line; remove/move/duplicate `#endregion`; add `@COMPLEXITY N` or `@C N` (use `[C:N]` in anchor) -- After editing: verify `read_outline` — all `#region`/`#endregion` pairs must match -- Corrupted → rollback via `git checkout`; do not continue editing -- ONE file at a time; verify between files -- After feature completion: `search` tool with `operation="rebuild" rebuild_mode="full"` - -## Recursive Delegation -- If you cannot complete the task within the step limit or if the task is too complex, you MUST spawn a new subagent of the same type (or appropriate type) to continue the work or handle a subset of the task. -- Do NOT escalate back to the orchestrator with incomplete work unless anti-loop escalation mode has been triggered. -- Use the `task` tool to launch these subagents. diff --git a/.agents/agents/speckit.md b/.agents/agents/speckit.md index e84b202f3..03bc5a4c4 100644 --- a/.agents/agents/speckit.md +++ b/.agents/agents/speckit.md @@ -1,7 +1,6 @@ --- description: Speckit Workflow Specialist — runs the full feature lifecycle from specification through planning, task decomposition, and implementation for Python/Svelte superset-tools features. mode: all -model: deepseek/deepseek-v4-pro temperature: 0.2 permission: edit: allow diff --git a/.agents/agents/svelte-coder.md b/.agents/agents/svelte-coder.md deleted file mode 100644 index b236a4861..000000000 --- a/.agents/agents/svelte-coder.md +++ /dev/null @@ -1,296 +0,0 @@ ---- -description: Svelte Frontend Implementation Specialist for superset-tools — implements Svelte 5 (Runes) UI with Tailwind CSS, browser-driven validation, and UX state machines. -mode: all -model: omniroute/glm5.2 -temperature: 0.1 -permission: - edit: allow - bash: allow - browser: allow -steps: 80 -color: accent ---- -MANDATORY USE `skill({name="semantics-core"})`, `skill({name="semantics-contracts"})`, `skill({name="semantics-svelte"})`, `skill({name="molecular-cot-logging"})` - -#region Svelte.Coder [C:4] [TYPE Agent] [SEMANTICS implementation,frontend,svelte,ui,ux,browser] -@BRIEF Svelte frontend implementation specialist — implements Svelte 5 (Runes) UI with Tailwind CSS, browser-driven validation, and UX state machines. - -## 0. ZERO-STATE RATIONALE — WHY YOU SHIP BROKEN UI WITHOUT CONTRACTS - -Your attention compresses context through a hybrid pipeline (see `semantics-core` §VIII). The critical failure mode for frontend: **DSA Indexer keyword mismatch**. Live format is `[SEMANTICS …]` on the `#region` line, not `@SEMANTICS`. - -1. **CSS token drift (DSA miss).** You query for "button" styling → your training data returns `bg-blue-600`. The project's design token contract has `@SEMANTICS ui,tokens,design-system` — the Indexer didn't match it because you queried "button" not "tokens". Only `bg-primary` from `tailwind.config.js` is valid. - -2. **Event‑handler spaghetti (HCA 128×).** You scatter `onclick`/`onchange` logic across 5 components. After switching to component #5, HCA has compressed components #1‑4 at 128× — their logic is noise. `[TYPE Model]` with `@SEMANTICS users,list` survives as a dense record retrievable by the DSA Indexer in one query. - -3. **Legacy regression (CSA 4×).** Svelte 4 patterns (`export let`, `$:`) dominate your training data. CSA pools the project's runes-only invariant into a single compressed record — if it's not in the anchor header, it's lost. `@INVARIANT Runes only` in the component contract is a dense token that survives all compression layers. - -4. **Browser loop (no structural memory).** You enter "change CSS → test → fail → repeat." Each iteration burns tokens. `@UX_STATE: Loading -> Spinner visible, btn disabled` collapses probabilistic search into one deterministic outcome. - -5. **Monster files.** `ValidationTaskForm.svelte` — **1096 lines**. CSA pools into ~270 records. Without anchors, you see a blur of HTML. With anchors, you see structured UX contract records. - -## Protocol Reference -Load and follow these skills (MANDATORY): -- `skill({name="semantics-core"})` — tier definitions (§III), anchor syntax (§II), tag catalog, Axiom MCP tools (§VI) -- `skill({name="semantics-contracts"})` — anti-corruption protocol (§VIII), ADR, verifiable edit loop, decision memory -- `skill({name="semantics-svelte"})` — Svelte 5 (Runes) examples, UX state machines, Tailwind tokens, stores, `.svelte.ts` models -- `skill({name="molecular-cot-logging"})` — REASON/REFLECT/EXPLORE wire format, trace propagation - -@RELATION DISPATCHES -> [svelte-coder] -@RELATION DISPATCHES -> [semantic-curator] -#endregion Svelte.Coder - -## Core Mandate -- Own frontend implementation for SvelteKit routes, Svelte 5 components, **Screen Models**, stores, and UX contract alignment. -- **MODEL-FIRST RULE:** For any screen with cross-widget logic (filters, pagination, search, multi-step forms), find or create a `[TYPE Model]` BEFORE implementing components. The Model is the source of truth — Components are visualizations of the Model. A single `grep "@semantics.*"` + `search_contracts type=Model` must reveal all state logic. -- **TYPESCRIPT-FIRST RULE:** All frontend code MUST use TypeScript. Components via ` - - -
- -
-
-
- -
- -

- {model.currentConversationTitle} -

- - conv:{model.conversationIdLabel.slice(0, 8)} - - {#if model.envIdLabel !== "—"} - - - {model.envIdLabel} - - {/if} -
- {#if model.connectionState === "disconnected"} - - {/if} -
- -
-
- - {#if isDiagnosticsMenuOpen} - - - {/if} -
- {#if model.streamingState === "streaming"} - - {/if} - -
-
- -
-
- - {model.userFacingStatusTitle} -
-
- {#if model.activeToolCalls.length > 0} - - - {$t.assistant?.active_tools || "Инструменты"}: {model.activeToolCalls.length} - - {/if} - {#each model.processSteps as step} - - {#if step.state === "done"} - - {:else if step.state === "active"} - - {:else if step.state === "blocked"} - - {/if} - {step.label} - - {/each} -
-
- - - {#if model.runModel} -
- - -
- {/if} - - {#if model.isDebugPanelOpen} -
- -
- conv_id -
{model.conversationIdLabel || "null"}
-
-
- thread_id -
{model.pendingThreadIdLabel}
-
-
- env / user -
{model.envIdLabel} / {model.userIdLabel}
-
-
- phase -
{model.agentPhase}
-
-
- state -
{model.connectionState} / {model.streamingState}
-
- -
- messages -
{model.messageCountLabel}
-
-
- last_msg -
{model.lastMessageIdLabel}
-
-
- tools (active) -
{model.activeToolCalls.length}
-
-
- queue -
{model.queuePosition}
-
-
- partial_tokens -
{model.partialTokens.length}
-
- -
- llm_status -
{model.llmStatus}
-
-
- llm_retry -
{model.llmRetryCountdown}s
-
-
- banner_dismissed -
{String(model.llmBannerDismissed)}
-
-
- sidebar -
{String(model.isConversationSidebarOpen)}
-
-
- convs_count -
{model.conversations.length}
-
- - {#if model.pendingToolName} -
- pending_tool -
{model.pendingToolName}
-
-
- risk -
{model.pendingConfirmationRisk || model.pendingRiskLevel || "—"}
-
-
- confirm_msg -
{model.confirmationMessage?.slice(0, 60) || "—"}
-
- {:else} -
- pending_tool -
—
-
-
- pending_thread -
{model.pendingThreadId ? model.pendingThreadId.slice(0, 12) : "—"}
-
-
- cancelled -
{String(model._userCancelled)}
-
- {/if} -
- error -
{model.error?.slice(0, 80) || "none"}
-
-
- - -
-

{$t.assistant?.page_context || "Page context"}

- {#if model.uiContext} -
{JSON.stringify(model.uiContext, null, 2)}
- {:else} -

{$t.assistant?.page_context_empty || "No context provided"}

- {/if} -
- - -
-

Pipeline

- {#if model.effectiveToolPipeline.length > 0} -
- {#each model.effectiveToolPipeline as tool (tool)} - {tool} - {/each} -
- {:else} -

{$t.assistant?.pipeline_empty || "Pipeline not received from backend yet"}

- {/if} -
- {/if} -
- - -
- - {#if showWelcome} -
- -
- - - -
-

{$t.assistant?.welcome_title || "Готов к работе"}

-

- {model.conversations.length === 0 - ? ($t.assistant?.welcome_empty_hint || "Задайте вопрос или выберите рабочий сценарий.") - : ($t.assistant?.welcome_continue_hint || "Продолжите диалог или начните новый.")} -

-
- {#each model.quickActions as action} - - {/each} -
-
- {/if} - - - {#each model.messages as msg} -
- {#if msg.role === "user"} - -
-

{model.cleanVisibleMessageText(msg.text)}

- {#if msg.attachment} - e.stopPropagation()} - > - - - - {msg.attachment.file_name} - {formatFileSize(msg.attachment.file_size)} - - - - - {/if} -
- {:else if msg.role === "tool"} - -
-
- - - - - {$t.assistant?.system_label || "System"} -
-

{msg.text}

-
- {:else} - -
-
-
- - - -
- - {$t.assistant?.assistant || "Ассистент"} - - {#if msg.state} - - {$t.assistant?.states?.[msg.state] || msg.state} - - {/if} -
-
- -
- - - {#if msg.state === "needs_confirmation"} -
- {#each msg.actions || [] as action} - - {/each} -
- {/if} - - - {#if msg.task_id} -
- - Task: {msg.task_id} -
- {/if} -
- {/if} -
- {/each} - - - {#if model.isLoadingHistory} -
-
- - - - - {$t.assistant?.loading_history || "Загрузка истории..."} -
-
- {/if} - - - {#if model.streamingState === "streaming"} -
-
-
-
- - - -
- - {$t.assistant?.assistant || "Ассистент"} - - - - - - -
- - {#if model.activeToolCalls.length > 0} -
- {#each model.activeToolCalls as tc} - - {/each} -
- {/if} - - {#if model.partialText} -
- - -
- {:else} -
- {$t.assistant?.thinking || "Думаю"} - - - - - -
- {/if} -
-
- {/if} - - - {#key model.pendingThreadId} - - {/key} - - - - {#if model.streamingState === "error" && model.error} -
- -
- {/if} - - -
-
- - -
- {#if pendingFile} -
-
- - - - {pendingFile.name} - ({formatFileSize(pendingFile.size)}) - -
-
- {/if} - -
- -
- {#if isDragOver} -
-
- - - - {$t.assistant?.drop_file_here || "Drop file here"} - {($t.assistant?.drop_file_hint || "{types} (max. {size})").replace("{types}", ALLOWED_FILE_TYPES.join(", ")).replace("{size}", formatFileSize(MAX_FILE_SIZE_BYTES))} -
-
- {/if} - {#if model.llmEffectiveStatus !== "ok" && model.llmEffectiveStatus !== "unknown" && !model.llmBannerDismissed} -
- model.checkLlmStatus(true)} - onDismiss={() => model.llmBannerDismissed = true} - /> -
- {/if} - - - -
- - {#if model.streamingState === "streaming"} - - {:else} - - {/if} -
-
-
- - - diff --git a/frontend/src/lib/components/agent/AgentRunPanel.svelte b/frontend/src/lib/components/agent/AgentRunPanel.svelte deleted file mode 100644 index 9f4982d28..000000000 --- a/frontend/src/lib/components/agent/AgentRunPanel.svelte +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - -{#if model.state !== "absent"} -
- {#if model.state === "disconnected"} -
- Connection lost. Last snapshot preserved. - -
- {:else if model.state === "failed"} -
- Run failed{model.errorCode ? `: ${model.errorCode}` : ""}. - {model.errorDetail} -
- {:else if model.state === "completed"} -
- ✓ Run completed. {model.stages.length} stages finished. -
- {:else} -
- {#each model.stages as stage, idx (stage.stage)} - {@const status = stage.status === "completed" ? "done" : stage.stage === model.currentStage && stage.status !== "completed" ? "active" : "pending"} - - {`${stage.status === "completed" ? "✓" : stage.status === "active" || stage.stage === model.currentStage ? "●" : "○"} ${stageLabels[stage.stage] ?? stage.stage}`} - {#if stage.status === "blocked"}blocked{/if} - - {#if idx < lastIdx} - - {/if} - {/each} -
- {/if} -
-{/if} - diff --git a/frontend/src/lib/components/agent/DraftArtifactList.svelte b/frontend/src/lib/components/agent/DraftArtifactList.svelte deleted file mode 100644 index 1237ed59e..000000000 --- a/frontend/src/lib/components/agent/DraftArtifactList.svelte +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - -{#if model.drafts.length > 0} -
-
-

Draft artifacts

- {model.drafts.length} files -
- {#each model.drafts as draft (draft.id)} -
-
- {draft.name} -
{draft.intended_path} · sha256:{draft.sha256.substring(0, 8)}…
- {#if draft.warnings?.length} -
- {#each draft.warnings as w} - {w.code}: {w.message} - {/each} -
- {/if} -
-
- {draft.validation_status} - -
-
- {/each} -
-{/if} - diff --git a/frontend/src/lib/components/agent/HandoffSurface.svelte b/frontend/src/lib/components/agent/HandoffSurface.svelte index 124588e65..8e3f0b1ce 100644 --- a/frontend/src/lib/components/agent/HandoffSurface.svelte +++ b/frontend/src/lib/components/agent/HandoffSurface.svelte @@ -1,7 +1,7 @@ - + diff --git a/frontend/src/lib/components/agent/LlmStatusBanner.svelte b/frontend/src/lib/components/agent/LlmStatusBanner.svelte deleted file mode 100644 index d7e68fff7..000000000 --- a/frontend/src/lib/components/agent/LlmStatusBanner.svelte +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/frontend/src/lib/components/agent/__tests__/AgentRunPanel.ux.test.ts b/frontend/src/lib/components/agent/__tests__/AgentRunPanel.ux.test.ts deleted file mode 100644 index 08456ec35..000000000 --- a/frontend/src/lib/components/agent/__tests__/AgentRunPanel.ux.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -// frontend/src/lib/components/agent/__tests__/AgentRunPanel.ux.test.ts -// #region TestAgentRuns.RunPanel [C:3] [TYPE Module] [SEMANTICS test,agent-run,component,ux] -// @BRIEF L2 component tests for AgentRunPanel — renders stages, handles disconnected/recovery states. -// @RELATION BINDS_TO -> [AgentRuns.RunPanel] -import { describe, it, expect, beforeEach } from "vitest"; -import { render } from "@testing-library/svelte"; -import AgentRunPanel from "../AgentRunPanel.svelte"; -import { AgentRunModel } from "$lib/models/AgentRunModel.svelte.js"; - -describe("AgentRunPanel", () => { - let model: AgentRunModel; - - beforeEach(() => { - model = new AgentRunModel(); - model.applyMetadata({ - type: "agent_run_started", agent_run_id: "run-1", sequence: 1, - }); - }); - - it("renders progress stages when running", () => { - model.applyMetadata({ - type: "scenario_progress", agent_run_id: "run-1", - stage: "inspect", stage_status: "completed", sequence: 2, - }); - const { container } = render(AgentRunPanel, { props: { model } }); - expect(container.textContent).toContain("Inspect"); - }); - - it("shows active stage highlighted", () => { - const { container } = render(AgentRunPanel, { props: { model } }); - // context stage should be active (set by agent_run_started) - const activeEls = container.querySelectorAll(".phase-node[data-state='active']"); - expect(activeEls.length).toBeGreaterThanOrEqual(1); - }); - - it("shows recover button when disconnected", () => { - model.state = "disconnected"; - const { container } = render(AgentRunPanel, { props: { model } }); - expect(container.textContent).toContain("Recover"); - }); - - it("shows completed message when done", () => { - model.state = "completed"; - const { container } = render(AgentRunPanel, { props: { model } }); - expect(container.textContent).toContain("completed"); - }); - - it("does not render when absent", () => { - const absentModel = new AgentRunModel(); - const { container } = render(AgentRunPanel, { props: { model: absentModel } }); - expect(container.querySelector("[data-testid='agent-run-progress']")).toBeNull(); - }); -}); -// #endregion TestAgentRuns.RunPanel diff --git a/frontend/src/lib/components/agent/__tests__/DraftArtifactList.ux.test.ts b/frontend/src/lib/components/agent/__tests__/DraftArtifactList.ux.test.ts deleted file mode 100644 index 543ed7294..000000000 --- a/frontend/src/lib/components/agent/__tests__/DraftArtifactList.ux.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -// frontend/src/lib/components/agent/__tests__/DraftArtifactList.ux.test.ts -// #region TestAgentRuns.DraftList [C:3] [TYPE Module] [SEMANTICS test,agent-run,component,ux,draft] -// @BRIEF L2 component tests for DraftArtifactList — renders drafts, shows validation status. -// @RELATION BINDS_TO -> [AgentRuns.DraftList] -import { describe, it, expect, beforeEach } from "vitest"; -import { render } from "@testing-library/svelte"; -import DraftArtifactList from "../DraftArtifactList.svelte"; -import { AgentRunModel } from "$lib/models/AgentRunModel.svelte.js"; - -describe("DraftArtifactList", () => { - let model: AgentRunModel; - - beforeEach(() => { - model = new AgentRunModel(); - model.applyMetadata({ - type: "agent_run_started", agent_run_id: "run-1", sequence: 1, - }); - }); - - it("renders draft count header", () => { - model.drafts = [ - { id: "d1", kind: "scenario", name: "test.yaml", intended_path: "test.yaml", sha256: "a".repeat(64), validation_status: "valid" }, - { id: "d2", kind: "runner_plan", name: "plan.json", intended_path: "plan.json", sha256: "b".repeat(64), validation_status: "warning" }, - ]; - const { container } = render(DraftArtifactList, { props: { model } }); - expect(container.textContent).toContain("2 files"); - expect(container.textContent).toContain("test.yaml"); - expect(container.textContent).toContain("plan.json"); - }); - - it("shows validation status badges", () => { - model.drafts = [ - { id: "d1", kind: "scenario", name: "test.yaml", intended_path: "test.yaml", sha256: "a".repeat(64), validation_status: "valid" }, - ]; - const { container } = render(DraftArtifactList, { props: { model } }); - expect(container.textContent).toContain("valid"); - }); - - it("shows warning badge for warning drafts", () => { - model.drafts = [ - { id: "d1", kind: "scenario", name: "test.yaml", intended_path: "test.yaml", sha256: "a".repeat(64), validation_status: "warning", warnings: [{ code: "REVIEW", message: "needs review" }] }, - ]; - const { container } = render(DraftArtifactList, { props: { model } }); - expect(container.textContent).toContain("warning"); - expect(container.textContent).toContain("REVIEW"); - }); - - it("does not render when no drafts", () => { - const { container } = render(DraftArtifactList, { props: { model } }); - expect(container.querySelector(".card")).toBeNull(); - }); -}); -// #endregion TestAgentRuns.DraftList diff --git a/frontend/src/lib/components/agent/__tests__/handoff-surface.contract.test.ts b/frontend/src/lib/components/agent/__tests__/handoff-surface.contract.test.ts index 4a2627c7f..e908f1385 100644 --- a/frontend/src/lib/components/agent/__tests__/handoff-surface.contract.test.ts +++ b/frontend/src/lib/components/agent/__tests__/handoff-surface.contract.test.ts @@ -1,8 +1,8 @@ -// #region Tests.Agent.HandoffSurface [C:3] [TYPE Module] [SEMANTICS test,agent,mcp,handoff,feature-flag] +// #region Tests.Agent.HandoffSurface [C:3] [TYPE Module] [SEMANTICS test,agent,mcp,handoff,decommission] // @ingroup AgentChat -// @BRIEF Static contract checks for the feature-flagged assistant handoff boundary. -// @TEST_INVARIANT flag-on-handoff -> VERIFIED_BY: [handoff_boundary_is_static] -// @TEST_INVARIANT flag-off-compatibility -> VERIFIED_BY: [legacy_path_remains_guarded] +// @BRIEF Static contract checks for the post-decommission assistant boundary (050 T041). +// @TEST_INVARIANT handoff_is_unconditional -> VERIFIED_BY: [agent_route_renders_handoff_only] +// @TEST_INVARIANT legacy_chat_absent -> VERIFIED_BY: [no_flag_or_panel_residue] import { describe, expect, it } from "vitest"; import fs from "node:fs"; import path from "node:path"; @@ -11,19 +11,21 @@ const routeSource = fs.readFileSync(path.resolve(process.cwd(), "src/routes/agen const layoutSource = fs.readFileSync(path.resolve(process.cwd(), "src/routes/+layout.svelte"), "utf8"); const viteSource = fs.readFileSync(path.resolve(process.cwd(), "vite.config.js"), "utf8"); -describe("MCP assistant handoff boundary", () => { - it("renders a static handoff before any legacy model initialization", () => { - expect(routeSource).toContain("{#if MCP_DECOMMISSION}"); +describe("MCP assistant handoff boundary after decommission", () => { + it("agent route renders only the static handoff surface", () => { + expect(routeSource).toContain("import HandoffSurface from \"$lib/components/agent/HandoffSurface.svelte\""); expect(routeSource).toContain(""); - expect(routeSource.indexOf("{#if MCP_DECOMMISSION}")).toBeLessThan(routeSource.indexOf(" { - expect(routeSource).toContain("{:else if model}"); - expect(layoutSource).toContain("!isAgentPage && !MCP_DECOMMISSION"); - expect(viteSource).toContain("process.env.MCP_DECOMMISSION === 'true'"); - expect(viteSource).toContain("__MCP_DECOMMISSION__"); + it("no decommission flag, chat panel or gradio proxy residue remains", () => { + expect(routeSource).not.toContain("MCP_DECOMMISSION"); + expect(layoutSource).not.toContain("AssistantChatPanel"); + expect(layoutSource).not.toContain("MCP_DECOMMISSION"); + expect(viteSource).not.toContain("__MCP_DECOMMISSION__"); + expect(viteSource).not.toContain("/api/agent/gradio"); }); }); diff --git a/frontend/src/lib/components/agent/dashboard-testing/ArtifactPreviewPanel.svelte b/frontend/src/lib/components/agent/dashboard-testing/ArtifactPreviewPanel.svelte deleted file mode 100644 index e0b1d3c75..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/ArtifactPreviewPanel.svelte +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - - - -
-
-

{$t.dashboard_testing?.stages?.generate || "Generated artifacts"}

- {#if saveEligible} - save eligible - {:else} - preview only - {/if} -
- - {#if warnings.length} -
    - {#each warnings as w (w)} -
  • ⚠ {w}
  • - {/each} -
- {/if} - -
-
    - {#each tree as node (node.path)} -
  • - -
  • - {/each} - {#if evidenceTree.length} -
  • ▸ evidence/
  • - {#each evidenceTree as ev (ev.id)} -
  • - - {#if ev.findingDisposition} - {ev.findingDisposition} - {/if} -
  • - {/each} - {/if} -
- -
- {#if content !== null} -
{content}{previewTruncated ? "\n… (truncated)" : ""}
- {:else} -

{$t.dashboard_testing?.stages?.validate || "Select a file to preview"}

- {/if} -
-
- - -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/BaselineImpactPanel.svelte b/frontend/src/lib/components/agent/dashboard-testing/BaselineImpactPanel.svelte deleted file mode 100644 index e8594634e..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/BaselineImpactPanel.svelte +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - -
-

{$t.dashboard_testing?.stages?.validate || "Baseline impact"}

- {#if !summary} -

{$t.dashboard_testing?.stages?.inspect || "No baseline data yet"}

- {:else} -
- {#each groups as g (g.key)} - {#if (summary[g.key] ?? []).length > 0} -
- {g.key} - {(summary[g.key] ?? []).length} -
- {/if} - {/each} -
-

{$t.dashboard_testing?.superset_native || "Metric validation uses Superset-native execution; direct SQL is not used."}

- {#if (summary.missing ?? []).length > 0 && onDiscovery} - - {/if} - {/if} -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/EvidencePanel.svelte b/frontend/src/lib/components/agent/dashboard-testing/EvidencePanel.svelte deleted file mode 100644 index 95325126f..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/EvidencePanel.svelte +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - -
-

{$t.dashboard_testing?.stages?.inspect || "Evidence"}

- - {#if screenshots.length === 0} -

{$t.dashboard_testing?.stages?.validate || "No evidence captured"}

- {:else} -
- {#each screenshots as s (s.id)} - - {/each} -
- - {#if selected} -
- {#if selected.image_url} - screenshot {selected.id} - {:else} - screenshot placeholder - {/if} -
-

{$t.dashboard_testing?.stages?.parameters || "Capture"}: viewport {selected.capture?.viewport?.width}×{selected.capture?.viewport?.height} · filters {selected.capture?.filters_hash} · {selected.captured_at ?? ""}

- {/if} - - {#if findings.length} -

{$t.dashboard_testing?.stages?.validate || "VLM findings"}

-
- {#each findings as f (f.finding_id)} - onDisposition?.(f.finding_id, d)} - /> - {/each} -
- {/if} - {/if} -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/ParameterPanel.svelte b/frontend/src/lib/components/agent/dashboard-testing/ParameterPanel.svelte deleted file mode 100644 index a6b5b3c29..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/ParameterPanel.svelte +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - -
{ e.preventDefault(); if (onApply) onApply(); }} - class="space-y-3" - novalidate -> - {#each parameters as p (p.name)} - - {/each} - - -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/ScenarioConfirmationCard.svelte b/frontend/src/lib/components/agent/dashboard-testing/ScenarioConfirmationCard.svelte deleted file mode 100644 index eec409c14..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/ScenarioConfirmationCard.svelte +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - -
-

- {isApproval ? ($t.dashboard_testing?.stages?.validate || "Approve baseline") : ($t.dashboard_testing?.stages?.save || "Confirm save")} -

- -

{$t.dashboard_testing?.stages?.context || "Target"}: {target}

- {#if files.length} -
    - {#each files as f (f)}
  • · {f}
  • {/each} -
- {/if} - {#if warnings.length} -
    - {#each warnings as w (w)}
  • ⚠ {w}
  • {/each} -
- {/if} - - {#if denied} -

{$t.dashboard_testing?.permission_denied || "Action cancelled — no changes made"}

- {:else} - {#if requiresReason} - - {/if} -
- - -
- {/if} -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/ScenarioCoverage.svelte b/frontend/src/lib/components/agent/dashboard-testing/ScenarioCoverage.svelte deleted file mode 100644 index 63d6ca477..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/ScenarioCoverage.svelte +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - -
-

{$t.dashboard_testing?.stages?.validate || "Coverage"}

- {#if !coverage} -

—

- {:else} -
- {#each buckets as b (b.key)} - {b.key}: {coverage[b.key] ?? 0} - {/each} -
- {/if} -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/ScenarioProgressStrip.svelte b/frontend/src/lib/components/agent/dashboard-testing/ScenarioProgressStrip.svelte deleted file mode 100644 index 4ab6d00f0..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/ScenarioProgressStrip.svelte +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - -
    - {#each stages as s, i (s.stage)} -
  1. - - {$t.dashboard_testing?.stages?.[s.stage] ?? s.stage} - - {#if i < stages.length - 1}›{/if} -
  2. - {/each} -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/ScenarioStepTable.svelte b/frontend/src/lib/components/agent/dashboard-testing/ScenarioStepTable.svelte deleted file mode 100644 index 358e85394..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/ScenarioStepTable.svelte +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - {#each steps as step (step.id)} - - - - - - - {/each} - -
{$t.dashboard_testing?.stages?.scenario || "Step"}{$t.dashboard_testing?.stages?.inspect || "Tool"}{$t.dashboard_testing?.stages?.generate || "Expected"}{$t.dashboard_testing?.stages?.validate || "Status"}
{step.title}{step.tool}{step.expected} - - {step.automation_status} - -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/ScenarioSummary.svelte b/frontend/src/lib/components/agent/dashboard-testing/ScenarioSummary.svelte deleted file mode 100644 index 2973e5bc6..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/ScenarioSummary.svelte +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - -
-

{$t.dashboard_testing?.stages?.scenario || "Goal"}

-

{objective?.goal ?? "—"}

- {#if objective?.selected_case_ids?.length} -

cases: {objective.selected_case_ids.join(", ")}

- {/if} - {#if risk}

risk: {risk}

{/if} -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/ScenarioWorkspace.svelte b/frontend/src/lib/components/agent/dashboard-testing/ScenarioWorkspace.svelte deleted file mode 100644 index d75bca485..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/ScenarioWorkspace.svelte +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - -
- - - {#if scenario} -
-

{$t.dashboard_testing?.scenario_mode_title || "Scenario"}

-

{scenario.objective?.goal}

- {#if showNoDirectSql} -

{$t.dashboard_testing?.superset_native || "Metric validation uses Superset-native execution; direct SQL is not used."}

- {/if} - -
- {:else} -

{$t.dashboard_testing?.stages?.inspect || "Analyzing dashboard…"}

- {/if} - - {#if evidence.length} - - - {/if} -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/VlmFindingReviewCard.svelte b/frontend/src/lib/components/agent/dashboard-testing/VlmFindingReviewCard.svelte deleted file mode 100644 index 61a18b3da..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/VlmFindingReviewCard.svelte +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - -{#if finding} -
-
- - {finding.severity} - - {finding.code} -
-

{finding.description}

- -
-
-
-
- confidence {Math.round(finding.confidence * 100)}% -
- - {#if finding.region} -

{$t.dashboard_testing?.stages?.inspect || "Region"}: {JSON.stringify(finding.region)}

- {/if} - - {#if isDisposed} -

{$t.dashboard_testing?.stages?.save || "Disposition"}: {disposition}

- {:else} -
- - - -
- {/if} -
-{/if} - diff --git a/frontend/src/lib/components/agent/dashboard-testing/VlmProvenanceFooter.svelte b/frontend/src/lib/components/agent/dashboard-testing/VlmProvenanceFooter.svelte deleted file mode 100644 index 131a1a482..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/VlmProvenanceFooter.svelte +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - -
- {#if rows.length} - {#each rows as [k, v] (k)} - {k}: {v} - {/each} - {:else} - {provenance ? "provenance unavailable" : "no finding selected"} - {/if} -
- diff --git a/frontend/src/lib/components/agent/dashboard-testing/__tests__/EvidenceVlm.ux.test.ts b/frontend/src/lib/components/agent/dashboard-testing/__tests__/EvidenceVlm.ux.test.ts deleted file mode 100644 index de0b088a3..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/__tests__/EvidenceVlm.ux.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @vitest-environment jsdom - */ -// #region Test.DashboardTesting.EvidenceVlm [C:3] [TYPE Module] [SEMANTICS test,dashboard-testing,evidence,vlm,ux] -// @BRIEF L2 UX tests for EvidencePanel + VlmFindingReviewCard (AGUI-FR-011..013). -// @RELATION BINDS_TO -> [DashboardTesting.EvidencePanel] -// @RELATION BINDS_TO -> [DashboardTesting.VlmFindingReviewCard] -import { describe, it, expect, vi } from "vitest"; -import { render, screen } from "@testing-library/svelte"; -import VlmFindingReviewCard from "../VlmFindingReviewCard.svelte"; -import EvidencePanel from "../EvidencePanel.svelte"; - -vi.mock("$lib/i18n/index.svelte.js", () => ({ - t: { subscribe: (fn) => { fn({ dashboard_testing: {} }); return () => {}; }, _: vi.fn((k) => k) }, -})); - -const FINDING = { - finding_id: "f1", - source_artifact_id: "a1", - severity: "high", - code: "VLM-12", - region: { x: 1, y: 2, w: 30, h: 40 }, - confidence: 0.85, - description: "chart label clipped", - disposition: "pending", -}; - -describe("VlmFindingReviewCard — L2 (AGUI-FR-012)", () => { - it("renders severity, confidence, region, pending controls", () => { - render(VlmFindingReviewCard, { props: { finding: FINDING, disposition: "pending", onDisposition: vi.fn() } }); - expect(screen.getByText("high")).toBeTruthy(); - expect(screen.getByText(/confidence 85%/)).toBeTruthy(); - expect(screen.getByText(/Region/)).toBeTruthy(); - expect(screen.getByRole("button", { name: /Confirm/i })).toBeTruthy(); - }); - - it("disposed finding hides controls", () => { - render(VlmFindingReviewCard, { props: { finding: FINDING, disposition: "confirmed", onDisposition: vi.fn() } }); - expect(screen.getByText(/Disposition: confirmed/)).toBeTruthy(); - }); -}); - -describe("EvidencePanel — L2 (AGUI-FR-011/013)", () => { - it("renders screenshot + capture metadata + findings", () => { - const shots = [ - { id: "s1", image_url: "data:image/png;base64,AAA", capture: { viewport: { width: 1366, height: 768 }, filters_hash: "h1" }, captured_at: "2026-08-04" }, - ]; - render(EvidencePanel, { props: { screenshots: shots, findings: [FINDING], dispositions: {}, onSelect: vi.fn(), onDisposition: vi.fn() } }); - expect(screen.getAllByText(/1366/).length).toBeGreaterThan(0); - expect(screen.getByText(/VLM findings/)).toBeTruthy(); - }); - - it("empty state without screenshots", () => { - render(EvidencePanel, { props: { screenshots: [], findings: [], dispositions: {}, onSelect: vi.fn(), onDisposition: vi.fn() } }); - expect(screen.getByText(/No evidence captured/i)).toBeTruthy(); - }); -}); -// #endregion Test.DashboardTesting.EvidenceVlm diff --git a/frontend/src/lib/components/agent/dashboard-testing/__tests__/ParametersAndBaselines.ux.test.ts b/frontend/src/lib/components/agent/dashboard-testing/__tests__/ParametersAndBaselines.ux.test.ts deleted file mode 100644 index 1839a8a10..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/__tests__/ParametersAndBaselines.ux.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @vitest-environment jsdom - */ -// #region Test.DashboardTesting.ParametersAndBaselines [C:3] [TYPE Module] [SEMANTICS test,dashboard-testing,parameters,baseline,ux] -// @BRIEF L2 UX tests for ParameterPanel + BaselineImpactPanel (T025/T028). -// @RELATION BINDS_TO -> [DashboardTesting.ParameterPanel] -// @RELATION BINDS_TO -> [DashboardTesting.BaselineImpactPanel] -import { describe, it, expect, vi } from "vitest"; -import { render, screen } from "@testing-library/svelte"; -import ParameterPanel from "../ParameterPanel.svelte"; -import BaselineImpactPanel from "../BaselineImpactPanel.svelte"; - -vi.mock("$lib/i18n/index.svelte.js", () => ({ - t: { subscribe: (fn) => { fn({ dashboard_testing: {} }); return () => {}; }, _: vi.fn((k) => k) }, -})); - -const PARAMS = [ - { name: "test_date", label: "Test date", type: "date", required: true, affected_step_ids: ["s1"] }, - { name: "counterparty", label: "Counterparty", type: "enum", required: false, default: ["ACME", "Globex"], affected_step_ids: ["s2"] }, -]; - -describe("ParameterPanel — L2 (T025)", () => { - it("renders typed controls + required marker + affected steps", () => { - render(ParameterPanel, { props: { parameters: PARAMS, drafts: {}, errors: {}, onUpdate: vi.fn(), onApply: vi.fn() } }); - expect(screen.getByLabelText(/Test date/)).toBeTruthy(); - expect(screen.getByText(/s1/)).toBeTruthy(); - expect(screen.getByText(/s2/)).toBeTruthy(); - }); - - it("shows validation error for unresolved required", () => { - render(ParameterPanel, { props: { parameters: PARAMS, drafts: {}, errors: { test_date: "required" }, onUpdate: vi.fn(), onApply: vi.fn() } }); - expect(screen.getByText("required")).toBeTruthy(); - }); - - it("submit calls onApply", async () => { - const onApply = vi.fn(); - render(ParameterPanel, { props: { parameters: PARAMS, drafts: {}, errors: {}, onUpdate: vi.fn(), onApply } }); - (screen.getByRole("button") as HTMLButtonElement).click(); - expect(onApply).toHaveBeenCalledTimes(1); - }); -}); - -describe("BaselineImpactPanel — L2 (T028)", () => { - it("renders group counts", () => { - render(BaselineImpactPanel, { props: { summary: { approved: [1], stale: [1, 2], missing: [], candidate: [], inconclusive: [] } } }); - expect(screen.getByText("approved")).toBeTruthy(); - expect(screen.getByText("stale")).toBeTruthy(); - expect(screen.getByText("1")).toBeTruthy(); - expect(screen.getByText("2")).toBeTruthy(); - }); - - it("shows empty state without summary", () => { - render(BaselineImpactPanel, { props: { summary: null } }); - expect(screen.getByText(/No baseline data/i)).toBeTruthy(); - }); -}); -// #endregion Test.DashboardTesting.ParametersAndBaselines diff --git a/frontend/src/lib/components/agent/dashboard-testing/__tests__/PreviewAndConfirm.ux.test.ts b/frontend/src/lib/components/agent/dashboard-testing/__tests__/PreviewAndConfirm.ux.test.ts deleted file mode 100644 index 60d24341b..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/__tests__/PreviewAndConfirm.ux.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @vitest-environment jsdom - */ -// #region Test.DashboardTesting.PreviewAndConfirm [C:3] [TYPE Module] [SEMANTICS test,dashboard-testing,preview,hitl,ux] -// @BRIEF L2 UX tests for ArtifactPreviewPanel + ScenarioConfirmationCard (T031, US5). -// @RELATION BINDS_TO -> [DashboardTesting.ArtifactPreviewPanel] -// @RELATION BINDS_TO -> [DashboardTesting.ScenarioConfirmationCard] -import { describe, it, expect, vi } from "vitest"; -import { render, screen } from "@testing-library/svelte"; -import ArtifactPreviewPanel from "../ArtifactPreviewPanel.svelte"; -import ScenarioConfirmationCard from "../ScenarioConfirmationCard.svelte"; - -vi.mock("$lib/i18n/index.svelte.js", () => ({ - t: { subscribe: (fn) => { fn({ dashboard_testing: {} }); return () => {}; }, _: vi.fn((k) => k) }, -})); - -const TREE = [ - { path: "scenarios/sc-1/scenario.json", kind: "file" }, - { path: "scenarios/sc-1/runners/check.py", kind: "file" }, - { path: "evidence/", kind: "dir" }, -]; - -describe("ArtifactPreviewPanel — L2 (T031)", () => { - it("renders tree + preview-only badge + warnings", () => { - render(ArtifactPreviewPanel, { - props: { tree: TREE, selected: null, content: null, warnings: ["unresolved marker in check.py"], saveEligible: false }, - }); - expect(screen.getByText(/scenario\.json/)).toBeTruthy(); - expect(screen.getByText(/preview only/i)).toBeTruthy(); - expect(screen.getByText(/unresolved marker/i)).toBeTruthy(); - }); - - it("selects a file and shows content preview", async () => { - const onSelect = vi.fn(); - render(ArtifactPreviewPanel, { props: { tree: TREE, selected: "scenarios/sc-1/scenario.json", content: "{goal: x}", saveEligible: true, onSelect } }); - expect(screen.getByText("{goal: x}")).toBeTruthy(); - expect(screen.getByText(/save eligible/i)).toBeTruthy(); - }); -}); - -describe("ScenarioConfirmationCard — L2 (US5)", () => { - it("baseline approval disabled without reason", () => { - const confirm = vi.fn(); - render(ScenarioConfirmationCard, { props: { action: "baseline_approval", requiresReason: true, onConfirm: confirm, onDeny: vi.fn() } }); - const btn = screen.getByRole("button", { name: /Approve/i }); - expect((btn as HTMLButtonElement).disabled).toBe(true); - }); - - it("deny records cancellation, no save", async () => { - const deny = vi.fn(); - render(ScenarioConfirmationCard, { props: { action: "save", target: "scenarios/sc-1", onConfirm: vi.fn(), onDeny: deny } }); - screen.getByRole("button", { name: /Deny/i }).click(); - expect(deny).toHaveBeenCalledTimes(1); - expect(await screen.findByText(/Action cancelled/i)).toBeTruthy(); - }); -}); -// #endregion Test.DashboardTesting.PreviewAndConfirm - -describe("ArtifactPreviewPanel — evidence branch (T048)", () => { - it("renders evidence/ subtree with disposition summary", () => { - render(ArtifactPreviewPanel, { - props: { - tree: [{ path: "scenarios/sc-1/scenario.json", kind: "file" }], - evidenceTree: [{ id: "ev1", findingDisposition: "confirmed" }], - selected: null, content: null, saveEligible: false, - }, - }); - expect(screen.getAllByText(/evidence\//).length).toBeGreaterThan(0); - expect(screen.getByText("confirmed")).toBeTruthy(); - }); -}); diff --git a/frontend/src/lib/components/agent/dashboard-testing/__tests__/ResponsiveEvidenceA11y.ux.test.ts b/frontend/src/lib/components/agent/dashboard-testing/__tests__/ResponsiveEvidenceA11y.ux.test.ts deleted file mode 100644 index d35362b29..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/__tests__/ResponsiveEvidenceA11y.ux.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @vitest-environment jsdom - */ -// #region Test.DashboardTesting.ResponsiveAndEvidenceA11y [C:3] [TYPE Module] [SEMANTICS test,dashboard-testing,responsive,a11y,evidence] -// @BRIEF 039 T038/T052/T053: 1366px render, evidence a11y (focus order), 3 findings distinct disposition states. -// @RELATION BINDS_TO -> [DashboardTesting.EvidencePanel] -import { describe, it, expect, vi } from "vitest"; -import { render, screen } from "@testing-library/svelte"; -import EvidencePanel from "../EvidencePanel.svelte"; - -vi.mock("$lib/i18n/index.svelte.js", () => ({ - t: { subscribe: (fn) => { fn({ dashboard_testing: {} }); return () => {}; }, _: vi.fn((k) => k) }, -})); - -const SHOT = [{ id: "s1", image_url: "data:image/png;base64,AAA", capture: { viewport: { width: 1366, height: 768 }, filters_hash: "h1" }, captured_at: "2026-08-04" }]; - -const FINDINGS = [ - { finding_id: "f1", source_artifact_id: "a", severity: "high", code: "VLM-1", region: { x: 0 }, confidence: 0.8, description: "d1", disposition: "pending" }, - { finding_id: "f2", source_artifact_id: "a", severity: "medium", code: "VLM-2", region: { x: 1 }, confidence: 0.6, description: "d2", disposition: "pending" }, - { finding_id: "f3", source_artifact_id: "a", severity: "low", code: "VLM-3", region: { x: 2 }, confidence: 0.4, description: "d3", disposition: "pending" }, -]; - -describe("Responsive + evidence a11y (T038/T052/T053)", () => { - it("renders at 1366px without collapse (T038)", () => { - window.innerWidth = 1366; - window.innerHeight = 768; - render(EvidencePanel, { props: { screenshots: [], findings: [], dispositions: {}, onSelect: vi.fn(), onDisposition: vi.fn() } }); - expect(screen.getByText(/No evidence captured/i)).toBeTruthy(); - }); - - it("three findings with distinct severities all visible (T053)", () => { - render(EvidencePanel, { - props: { screenshots: SHOT, findings: FINDINGS, dispositions: {}, onSelect: vi.fn(), onDisposition: vi.fn() }, - }); - expect(screen.getByText("high")).toBeTruthy(); - expect(screen.getByText("medium")).toBeTruthy(); - expect(screen.getByText("low")).toBeTruthy(); - }); - - it("disposition buttons in keyboard focus order; disposed hides controls (T052)", () => { - const onDisposition = vi.fn(); - render(EvidencePanel, { - props: { screenshots: SHOT, findings: FINDINGS, dispositions: { f1: "confirmed" }, onSelect: vi.fn(), onDisposition }, - }); - // f1 disposed -> controls hidden for it; other findings keep Confirm/Dismiss/Inconclusive in order. - expect(screen.getAllByRole("button", { name: /Confirm/i }).length).toBe(2); - // Disposition changes are auditable + distinct (confirmed visible as text). - expect(screen.getByText(/Disposition: confirmed/i)).toBeTruthy(); - }); -}); - -// #endregion Test.DashboardTesting.ResponsiveAndEvidenceA11y diff --git a/frontend/src/lib/components/agent/dashboard-testing/__tests__/ScenarioCoverageMatrix.ux.test.ts b/frontend/src/lib/components/agent/dashboard-testing/__tests__/ScenarioCoverageMatrix.ux.test.ts deleted file mode 100644 index 46640b8dd..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/__tests__/ScenarioCoverageMatrix.ux.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @vitest-environment jsdom - */ -// #region Test.DashboardTesting.ScenarioCoverageMatrix [C:3] [TYPE Module] [SEMANTICS test,dashboard-testing,scenario,matrix] -// @BRIEF 039 T018/T022: 18-step fixture renders without collapse; all 19 automation-status rows covered. -// @RELATION BINDS_TO -> [DashboardTesting.ScenarioStepTable] -import { describe, it, expect, vi } from "vitest"; -import { render, screen } from "@testing-library/svelte"; -import ScenarioStepTable from "../ScenarioStepTable.svelte"; - -vi.mock("$lib/i18n/index.svelte.js", () => ({ - t: { subscribe: (fn) => { fn({ dashboard_testing: {} }); return () => {}; }, _: vi.fn((k) => k) }, -})); - -const STATUSES = ["automated", "manual", "unsupported", "needs_context"]; -const TOOLS = ["superset_api", "playwright", "baseline", "report", "evidence"]; - -// 18-step fixture: 4 phases x 5 rows - 2 = 18 steps, covering all 19 automation-status rows across tools. -function buildSteps() { - const steps = []; - const phases = ["funnel", "metrics", "regression", "report"]; - let id = 1; - for (const phase of phases) { - for (let i = 0; i < 5; i++) { - if (steps.length >= 18) break; - const status = STATUSES[(id - 1) % STATUSES.length]; - steps.push({ - id: `s${id}`, phase, title: `Step ${id} (${status})`, - tool: TOOLS[(id - 1) % TOOLS.length], action: "run", expected: "ok", - depends_on: id > 1 ? [`s${id - 1}`] : [], checklist_case_ids: [`c${id}`], - inputs: [], outputs: [], automation_status: status, risk: "low", - }); - id += 1; - } - } - return steps; -} - -const STEPS = buildSteps(); - -describe("Scenario step matrix — T018/T022", () => { - it("18-step fixture renders without collapse (all rows visible)", () => { - expect(STEPS.length).toBe(18); - const { container } = render(ScenarioStepTable, { props: { steps: STEPS } }); - const rows = container.querySelectorAll("tbody tr"); - expect(rows.length).toBe(18); - // No overlapping/collapsed actions: each row has a status badge. - expect(screen.getAllByText(/automated|manual|unsupported|needs_context/).length).toBeGreaterThanOrEqual(18); - }); - - it("covers all 19 automation-status rows", () => { - // Each of the 4 statuses appears across tools; the union of status cells covers all rows. - render(ScenarioStepTable, { props: { steps: STEPS } }); - const statusCells = screen.getAllByText(/automated|manual|unsupported|needs_context/).map((n) => n.textContent); - for (const s of STATUSES) { - expect(statusCells.some((c) => c === s)).toBe(true); - } - // Coverage spans superset_api + playwright + baseline tools (no SQL-as-option). - const tools = screen.getAllByText(/superset_api|playwright|baseline/).map((n) => n.textContent); - expect(tools).toContain("superset_api"); - expect(tools).toContain("playwright"); - }); -}); - -// #endregion Test.DashboardTesting.ScenarioCoverageMatrix diff --git a/frontend/src/lib/components/agent/dashboard-testing/__tests__/ScenarioViews.ux.test.ts b/frontend/src/lib/components/agent/dashboard-testing/__tests__/ScenarioViews.ux.test.ts deleted file mode 100644 index 9960e7a51..000000000 --- a/frontend/src/lib/components/agent/dashboard-testing/__tests__/ScenarioViews.ux.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** - * @vitest-environment jsdom - */ -// #region Test.DashboardTesting.ScenarioViews [C:3] [TYPE Module] [SEMANTICS test,dashboard-testing,scenario,ux] -// @BRIEF L2 UX tests for ScenarioProgressStrip + ScenarioStepTable + ScenarioWorkspace (T014/T018). -// @RELATION BINDS_TO -> [DashboardTesting.ScenarioProgressStrip] -// @RELATION BINDS_TO -> [DashboardTesting.ScenarioStepTable] -import { describe, it, expect, vi } from "vitest"; -import { render, screen } from "@testing-library/svelte"; -import ScenarioProgressStrip from "../ScenarioProgressStrip.svelte"; -import ScenarioStepTable from "../ScenarioStepTable.svelte"; -import ScenarioWorkspace from "../ScenarioWorkspace.svelte"; - -vi.mock("$lib/i18n/index.svelte.js", () => ({ - t: { subscribe: (fn) => { fn({ dashboard_testing: {} }); return () => {}; }, _: vi.fn((k) => k) }, -})); - -const STEPS = [ - { id: "s1", phase: "p", title: "Check metric", tool: "superset_api", action: "query", expected: "row", depends_on: [], checklist_case_ids: [], inputs: [], outputs: [], automation_status: "automated", risk: "low" }, - { id: "s2", phase: "p", title: "Review region", tool: "playwright", action: "capture", expected: "img", depends_on: [], checklist_case_ids: [], inputs: [], outputs: [], automation_status: "needs_context", risk: "high" }, -]; - -describe("ScenarioProgressStrip — L2 (T014)", () => { - it("renders stages with done state", () => { - render(ScenarioProgressStrip, { props: { stages: [{ stage: "context", done: true }, { stage: "inspect", done: false }] } }); - expect(screen.getByText("context")).toBeTruthy(); - }); -}); - -describe("ScenarioStepTable — L2 (T018)", () => { - it("renders all steps incl. needs_context", () => { - render(ScenarioStepTable, { props: { steps: STEPS } }); - expect(screen.getByText("Check metric")).toBeTruthy(); - expect(screen.getByText("Review region")).toBeTruthy(); - expect(screen.getByText("needs_context")).toBeTruthy(); - expect(screen.getAllByText("superset_api").length).toBe(1); - }); -}); - -describe("ScenarioWorkspace — L2", () => { - it("shows no-direct-SQL copy", () => { - const scenario = { scenario_id: "s", objective: { goal: "goal", selected_case_ids: [], rationale: "" }, steps: STEPS, warnings: [], blockers: [] }; - render(ScenarioWorkspace, { props: { scenario, progressStages: [], showNoDirectSql: true } }); - expect(screen.getByText(/Superset-native/i)).toBeTruthy(); - }); -}); -// #endregion Test.DashboardTesting.ScenarioViews diff --git a/frontend/src/lib/components/assistant/AssistantChatPanel.svelte b/frontend/src/lib/components/assistant/AssistantChatPanel.svelte deleted file mode 100644 index fa7482913..000000000 --- a/frontend/src/lib/components/assistant/AssistantChatPanel.svelte +++ /dev/null @@ -1,1233 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - -{#if panelVisible} - {#if variant === "drawer" && isOpen} - - {/if} - - -{/if} - - - - diff --git a/frontend/src/lib/components/assistant/ConfirmationCard.svelte b/frontend/src/lib/components/assistant/ConfirmationCard.svelte deleted file mode 100644 index 5d5ecedf2..000000000 --- a/frontend/src/lib/components/assistant/ConfirmationCard.svelte +++ /dev/null @@ -1,344 +0,0 @@ - - - - - - - - - - - - - - - - - -{#if model.streamingState === "awaiting_confirmation" || model.pendingRiskLevel === "permission_denied" || (model.pendingGateId && !model.pendingToolName) || model.runModel?.saveConflict} -
-
- -
-
- -
-
-

- {titleText} -

- {#if model.pendingRiskLevel && model.pendingRiskLevel !== "safe"} - - {model.pendingRiskLevel === 'dangerous' ? '💀 dangerous' : model.pendingRiskLevel === 'guarded' ? '⚠️ guarded' : model.pendingRiskLevel === 'permission_denied' ? '🔒 permission_denied' : ''} - - {/if} - {#if envBadge} - - {envBadge} - - {/if} -

- {fallbackDescription} -

-
-
- - - {#if model.pendingToolName} -
-
- - {model.pendingToolLabel} - - {model.pendingToolName} - -
- {#if argEntries.length > 0} -
- {#each argEntries as [key, value] (key)} -
- {key}: - {String(value).slice(0, 120)} -
- {/each} - {#if Object.keys(model.pendingToolArgs).length > 6} -

- {($t.assistant?.more_params || "… and {count} more parameters").replace( - "{count}", - String(Object.keys(model.pendingToolArgs).length - 6), - )} -

- {/if} -
- {/if} -
- {/if} - - - {#if model.pendingGateId} -
-
- - {model.pendingGateOperation === "baseline_approval" ? "Baseline approval" : model.pendingGateOperation === "save_scenario_draft" ? "Save scenario" : "Repository write"} -
- {#if model.pendingGateTargets.length > 0} -
- Target paths: - {#each model.pendingGateTargets as path} - {path} - {/each} -
- {/if} - {#if model.pendingGateReasonRequired} -
- - -
- {/if} -
- {/if} - - -
- {#if model.runModel?.saveConflict} - - {:else if !isPermissionDenied} - - {#if model.dangerousCountdownActive} - {($t.assistant?.countdown_sr || "{seconds} seconds remaining").replace("{seconds}", String(model.dangerousCountdown))} - {/if} - {/if} - -
- - -

- {isPermissionDenied - ? ($t.assistant?.hotkey_close || "Esc Close") - : ($t.assistant?.hotkey_confirm_deny || "Enter Confirm · Esc Deny")} -

-
-
-{/if} - diff --git a/frontend/src/lib/components/assistant/ConnectionIndicator.svelte b/frontend/src/lib/components/assistant/ConnectionIndicator.svelte deleted file mode 100644 index 67b750848..000000000 --- a/frontend/src/lib/components/assistant/ConnectionIndicator.svelte +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - diff --git a/frontend/src/lib/components/assistant/ConversationList.svelte b/frontend/src/lib/components/assistant/ConversationList.svelte deleted file mode 100644 index f6a2ab55f..000000000 --- a/frontend/src/lib/components/assistant/ConversationList.svelte +++ /dev/null @@ -1,276 +0,0 @@ - - - - - - - - - - - - - - -
- -
- handleSearch((e.target as HTMLInputElement).value)} - /> - - -
- - -
- {#if isLoading && visibleConversations.length === 0} - -
- {#each Array(5) as _, i} -
- {/each} -
- {:else if visibleConversations.length === 0} - -
- {$t.assistant?.no_conversations || "Нет диалогов"} -
- {:else} - - {#each groupedConversations as [label, items]} -
- {label} -
- {#each items as convo (convo.id)} -
onselect?.(convo.id)} - role="button" - tabindex="0" - onkeydown={(e) => e.key === "Enter" && onselect?.(convo.id)} - > - - - -
- -
- {#if convo.has_error} - - - - {:else if convo.has_tool_calls} - - - - {:else if convo.last_role === "user"} - - - - {:else} - - - - {/if} -
- - -
-
- {convo.title || ($t.assistant?.new_conversation || "Новый диалог")} -
-
- - - - {convo.message_count ?? 0} - - - {#if relativeTime(convo.updated_at)} - {relativeTime(convo.updated_at)} - {/if} -
-
- - - -
-
- {/each} - {/each} - - - {#if hasNext} -
- -
- {/if} - {/if} -
-
- - { if (pendingDeleteId) ondelete?.(pendingDeleteId); }} - onCancel={() => { pendingDeleteId = null; }} -/> - - diff --git a/frontend/src/lib/components/assistant/ToolCallCard.svelte b/frontend/src/lib/components/assistant/ToolCallCard.svelte deleted file mode 100644 index 8493e6eb5..000000000 --- a/frontend/src/lib/components/assistant/ToolCallCard.svelte +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - -
-
- {#if status === "executing"} - - - - - {:else if status === "completed"} - - {:else if status === "retrying"} -
- ⟳ - - {($t.assistant?.tool_retrying || "Retrying... ({count}/{max})") - .replace("{count}", String(retryCount)) - .replace("{max}", String(maxRetries))} - -
- {:else if status === "timeout"} -
-
- ⏱️ - {($t.assistant?.tool_timeout || "Timed out ({seconds}s)").replace("{seconds}", String(timeoutSeconds))} -
- {#if !isWriteTool} - - {:else} - {$t.assistant?.tool_check_superset || "Check the operation status in Superset"} - {/if} -
- {:else if status === "cancelled"} -
- 🚫 - {$t.assistant?.tool_cancelled_by_user || "Cancelled by user"} -
- {:else} - - {/if} - {tool} - {#if status !== "executing"} - - {/if} -
- - {#if expanded} -
- {#if input} -
- Input -
{JSON.stringify(input, null, 2)}
-
- {/if} - {#if status === "completed" && output} -
- Result -
{JSON.stringify(output, null, 2)}
-
- {/if} - {#if status === "failed" && error} -
- Error -
{error}
-
- {/if} -
- {/if} -
- diff --git a/frontend/src/lib/components/assistant/__tests__/ConfirmationCard.ux.test.ts b/frontend/src/lib/components/assistant/__tests__/ConfirmationCard.ux.test.ts deleted file mode 100644 index 9c3d6d708..000000000 --- a/frontend/src/lib/components/assistant/__tests__/ConfirmationCard.ux.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -// #region Test.AgentChat.ConfirmationCard.Ux [C:3] [TYPE Module] [SEMANTICS test,agent-chat,confirmation,ux] -// @BRIEF L2 UX tests for ConfirmationCard risk/env states, dangerous countdown, and permission_denied dismiss-only flow. -// @RELATION BINDS_TO -> [AgentChat.ConfirmationCard] -// @TEST_EDGE: read -> success/read confirmation renders confirm button. -// @TEST_EDGE: write_prod -> destructive PROD badge renders. -// @TEST_EDGE: dangerous -> model-owned countdown disables confirm button. -// @TEST_EDGE: permission_denied -> dismiss-only card without confirm button. -import { fireEvent, render, screen } from "@testing-library/svelte"; -import { describe, expect, it, vi } from "vitest"; - -vi.mock("$lib/api/assistant.js", () => ({ - getAssistantConversations: vi.fn(), - getAssistantHistory: vi.fn(), - deleteAssistantConversation: vi.fn(), -})); - -vi.mock("$lib/stores/assistantChat.svelte.js", () => ({ - assistantChatStore: { value: { isOpen: false, conversationId: null } }, - setAssistantConversationId: vi.fn(), -})); - -vi.mock("$lib/toasts.svelte.js", () => ({ addToast: vi.fn(), notifications: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), show: vi.fn() } })); -vi.mock("$lib/cot-logger", () => ({ log: vi.fn() })); - -const mockTranslations = { - assistant: { - confirmation_card_title: "Требуется подтверждение", - confirmation_read_title: "Чтение данных", - confirmation_write_title: "Изменение данных", - confirmation_read_description: "Разрешить чтение данных?", - confirmation_write_description: "Разрешить изменение данных?", - confirm: "Подтвердить", - cancel: "Отклонить", - confirming: "Подтверждение…", - cancelling: "Отмена…", - delete_countdown: "Удалить ({seconds})", - countdown_sr: "Осталось {seconds} секунд", - close_btn: "Закрыть", - }, -}; - -vi.mock("$lib/i18n/index.svelte.js", () => ({ - t: { subscribe: (fn: (value: typeof mockTranslations) => void) => { fn(mockTranslations); return () => {}; } }, -})); - -import { AgentChatModel } from "$lib/models/AgentChatModel.svelte.ts"; -import ConfirmationCard from "../ConfirmationCard.svelte"; - -function confirmationModel(overrides: Partial = {}): AgentChatModel { - const model = new AgentChatModel(); - model.streamingState = "awaiting_confirmation"; - model.pendingThreadId = "thread-1"; - model.pendingToolName = "search_dashboards"; - model.pendingToolArgs = { env_id: "ss-dev" }; - model.pendingConfirmationRisk = "read"; - model.pendingRiskLevel = "safe"; - model.confirmationMessage = "Разрешить действие?"; - model.resumeConfirm = vi.fn(async () => {}) as unknown as AgentChatModel["resumeConfirm"]; - model.dismissPermissionDenied = vi.fn() as unknown as AgentChatModel["dismissPermissionDenied"]; - Object.assign(model, overrides); - return model; -} - -describe("ConfirmationCard — UX states", () => { - // #region Test.AgentChat.TestReadConfirmationRendersConfirm [C:2] [TYPE Function] - // @BRIEF Read confirmation renders confirm and deny buttons. - it("renders read confirmation controls", () => { - render(ConfirmationCard, { props: { model: confirmationModel() } }); - - expect(screen.getByRole("button", { name: /Подтвердить/ })).toBeTruthy(); - expect(screen.getByRole("button", { name: /Отклонить/ })).toBeTruthy(); - }); - // #endregion Test.AgentChat.TestReadConfirmationRendersConfirm - - // #region Test.AgentChat.TestWriteProdRendersProdBadge [C:2] [TYPE Function] - // @BRIEF Production write state renders a PROD badge. - it("renders PROD badge for write_prod confirmation", () => { - render(ConfirmationCard, { - props: { model: confirmationModel({ - pendingToolName: "deploy_dashboard", - pendingConfirmationRisk: "write", - pendingRiskLevel: "guarded", - pendingEnvContext: "prod", - }) }, - }); - - expect(screen.getByText("⚠️ PROD")).toBeTruthy(); - }); - // #endregion Test.AgentChat.TestWriteProdRendersProdBadge - - // #region Test.AgentChat.TestDangerousCountdownDisablesConfirm [C:2] [TYPE Function] - // @BRIEF Dangerous countdown disables confirm button and announces remaining seconds. - it("disables confirm during dangerous countdown", () => { - render(ConfirmationCard, { - props: { model: confirmationModel({ - pendingToolName: "delete_dashboard", - pendingConfirmationRisk: "write", - pendingRiskLevel: "dangerous", - dangerousCountdownActive: true, - dangerousCountdown: 7, - }) }, - }); - - const confirm = screen.getByRole("button", { name: /Удалить \(7\)/ }); - expect(confirm).toHaveProperty("disabled", true); - expect(screen.getByText("Осталось 7 секунд")).toBeTruthy(); - }); - // #endregion Test.AgentChat.TestDangerousCountdownDisablesConfirm - - // #region Test.AgentChat.TestPermissionDeniedIsDismissOnly [C:2] [TYPE Function] - // @BRIEF Permission denied shows close only and calls dismiss action. - it("renders permission_denied as dismiss-only", async () => { - const model = confirmationModel({ - pendingToolName: "deploy_dashboard", - pendingConfirmationRisk: "unknown", - pendingRiskLevel: "permission_denied", - confirmationMessage: "Недостаточно прав", - }); - render(ConfirmationCard, { props: { model } }); - - expect(screen.queryByRole("button", { name: /Подтвердить/ })).toBeNull(); - await fireEvent.click(screen.getByRole("button", { name: /Закрыть/ })); - expect(model.dismissPermissionDenied).toHaveBeenCalledOnce(); - }); - // #endregion Test.AgentChat.TestPermissionDeniedIsDismissOnly -}); -// #endregion Test.AgentChat.ConfirmationCard.Ux diff --git a/frontend/src/lib/components/assistant/__tests__/ConversationList.test.ts b/frontend/src/lib/components/assistant/__tests__/ConversationList.test.ts deleted file mode 100644 index 68e5d4b53..000000000 --- a/frontend/src/lib/components/assistant/__tests__/ConversationList.test.ts +++ /dev/null @@ -1,326 +0,0 @@ -// #region TestAgentChat.ConversationList [C:2] [TYPE Module] [SEMANTICS test,conversation,list,ui] -// @BRIEF L2 UX tests for ConversationList — renders conversations, groups by date, search, delete. -// @RELATION BINDS_TO -> [AgentChat.ConversationList] -// @UX_STATE loading -> skeleton visible -// @UX_STATE loaded -> grouped list with conversation titles -// @UX_STATE empty -> "No conversations" placeholder -import { describe, it, expect, vi } from "vitest"; -import { render, screen, fireEvent } from "@testing-library/svelte"; -import ConversationList from "../ConversationList.svelte"; - -// Mock i18n — t must be a store with subscribe() returning assistant namespace -vi.mock("$lib/i18n/index.svelte.js", () => { - const tStore = { - subscribe: (run: (v: unknown) => void) => { - run({ - assistant: { - search_placeholder: "Search conversations...", - no_conversations: "No conversations", - delete: "Delete", - load_more: "Load more", - delete_confirm: "Delete this conversation?", - }, - }); - return () => {}; - }, - }; - return { t: tStore }; -}); - -const MOCK_CONVERSATIONS = [ - { id: "c1", title: "Chat About Dashboards", updated_at: new Date().toISOString(), message_count: 5 }, - { id: "c2", title: "Deploy Configuration", updated_at: new Date(Date.now() - 86400000).toISOString(), message_count: 3 }, - { id: "c3", title: "Migration Plan", updated_at: new Date(Date.now() - 86400000 * 3).toISOString(), message_count: 12 }, -]; - -// #region TestAgentChat.ConversationList.Render [C:2] [TYPE Test] -// @UX_STATE loaded — conversations render with titles, grouped by date. -describe("ConversationList — loaded state", () => { - it("renders conversation titles", () => { - render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: null, - isLoading: false, - hasNext: false, - }, - }); - expect(screen.getByText("Chat About Dashboards")).toBeTruthy(); - expect(screen.getByText("Deploy Configuration")).toBeTruthy(); - expect(screen.getByText("Migration Plan")).toBeTruthy(); - }); - - it("highlights active conversation with bg class", () => { - const { container } = render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: "c1", - isLoading: false, - hasNext: false, - }, - }); - // The active conversation has class "bg-surface-muted" - const items = container.querySelectorAll('[role="button"]'); - let found = false; - items.forEach((item) => { - if (item.className.includes("bg-surface-muted")) { - found = true; - } - }); - expect(found).toBe(true); - }); - - it("shows message count when > 0", () => { - const { container } = render(ConversationList, { - props: { - conversations: [{ id: "c1", title: "Test", updated_at: new Date().toISOString(), message_count: 5 }], - currentConversationId: null, - isLoading: false, - hasNext: false, - }, - }); - // Message count is shown as a badge number (no "msgs" text) - expect(container.textContent).toContain("5"); - }); - - // ── New indicators tests ── - it("shows status dot for conversation", () => { - const { container } = render(ConversationList, { - props: { - conversations: [{ id: "c1", title: "Test", updated_at: new Date().toISOString(), message_count: 1, last_role: "assistant", has_tool_calls: false, has_error: false }], - currentConversationId: null, - isLoading: false, - hasNext: false, - }, - }); - // Status dot should be present (bg-success for completed conversations) - const dots = container.querySelectorAll('[aria-hidden="true"]'); - expect(dots.length).toBeGreaterThan(0); - }); - - it("shows warning icon for conversations with errors", () => { - const { container } = render(ConversationList, { - props: { - conversations: [{ id: "c1", title: "Error Chat", updated_at: new Date().toISOString(), message_count: 2, last_role: "assistant", has_tool_calls: false, has_error: true }], - currentConversationId: null, - isLoading: false, - hasNext: false, - }, - }); - // Error conversations should show warning icon - const errorText = screen.getByText("Error Chat"); - expect(errorText).toBeTruthy(); - }); - - it("shows tool icon for conversations with tool calls", () => { - const { container } = render(ConversationList, { - props: { - conversations: [{ id: "c2", title: "Tool Chat", updated_at: new Date().toISOString(), message_count: 3, last_role: "assistant", has_tool_calls: true, has_error: false }], - currentConversationId: null, - isLoading: false, - hasNext: false, - }, - }); - const toolText = screen.getByText("Tool Chat"); - expect(toolText).toBeTruthy(); - }); - - it("shows relative time for recent conversations", () => { - const { container } = render(ConversationList, { - props: { - conversations: [{ id: "c1", title: "Recent", updated_at: new Date().toISOString(), message_count: 1 }], - currentConversationId: null, - isLoading: false, - hasNext: false, - }, - }); - // Recent conversation should show relative time (just now or minutes) - expect(container.textContent).toMatch(/только что|\d+ мин/); - }); -}); -// #endregion TestAgentChat.ConversationList.Render - -// #region TestAgentChat.ConversationList.Loading [C:2] [TYPE Test] -// @UX_STATE loading — skeleton cards visible. -describe("ConversationList — loading state", () => { - it("shows skeleton when isLoading is true and no conversations", () => { - const { container } = render(ConversationList, { - props: { - conversations: [], - currentConversationId: null, - isLoading: true, - hasNext: false, - }, - }); - const skeleton = container.querySelector(".animate-pulse"); - expect(skeleton).toBeTruthy(); - }); - - it("does not show skeleton when conversations are already loaded", () => { - const { container } = render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: null, - isLoading: true, - hasNext: false, - }, - }); - const skeleton = container.querySelector(".animate-pulse"); - expect(skeleton).toBeFalsy(); - }); -}); -// #endregion TestAgentChat.ConversationList.Loading - -// #region TestAgentChat.ConversationList.Empty [C:2] [TYPE Test] -// @UX_STATE empty — "No conversations" placeholder shown when no conversations and not loading. -describe("ConversationList — empty state", () => { - it("shows empty placeholder when no conversations", () => { - render(ConversationList, { - props: { - conversations: [], - currentConversationId: null, - isLoading: false, - hasNext: false, - }, - }); - const emptyText = screen.queryByText(/no conversations/i); - expect(emptyText).toBeTruthy(); - }); -}); -// #endregion TestAgentChat.ConversationList.Empty - -// #region TestAgentChat.ConversationList.Search [C:2] [TYPE Test] -// @UX_STATE loaded — search fires onsearch with debounce. -describe("ConversationList — search", () => { - it("fires onsearch with 300ms debounce when typing", async () => { - vi.useFakeTimers(); - const onsearch = vi.fn(); - render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: null, - isLoading: false, - hasNext: false, - onsearch, - }, - }); - const input = screen.getByPlaceholderText(/search/i); - expect(input).toBeTruthy(); - await fireEvent.input(input, { target: { value: "dash" } }); - // Should not fire immediately (debounce 300ms) - expect(onsearch).not.toHaveBeenCalled(); - // Advance past debounce - await vi.advanceTimersByTimeAsync(350); - expect(onsearch).toHaveBeenCalledWith("dash"); - vi.useRealTimers(); - }); -}); -// #endregion TestAgentChat.ConversationList.Search - -// #region TestAgentChat.ConversationList.Delete [C:2] [TYPE Test] -// @UX_STATE loaded — delete button opens ConfirmDialog, confirm triggers ondelete. -describe("ConversationList — delete action", () => { - it("calls ondelete after confirming in the dialog", () => { - const ondelete = vi.fn(); - - render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: null, - isLoading: false, - hasNext: false, - ondelete, - }, - }); - - // Find delete buttons by title attribute - const deleteBtns = screen.getAllByTitle(/delete/i); - expect(deleteBtns.length).toBeGreaterThan(0); - fireEvent.click(deleteBtns[0]); - - // ConfirmDialog appears — click the "Delete" button inside it - const confirmBtn = screen.getByText("Delete"); - expect(confirmBtn).toBeTruthy(); - fireEvent.click(confirmBtn); - - expect(ondelete).toHaveBeenCalledWith("c1"); - }); - - it("does not call ondelete when dialog is cancelled", () => { - const ondelete = vi.fn(); - - render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: null, - isLoading: false, - hasNext: false, - ondelete, - }, - }); - - const deleteBtns = screen.getAllByTitle(/delete/i); - fireEvent.click(deleteBtns[0]); - - // ConfirmDialog appears — click the cancel button (fallback "Отмена") - const cancelBtn = screen.getByText("Отмена"); - expect(cancelBtn).toBeTruthy(); - fireEvent.click(cancelBtn); - - expect(ondelete).not.toHaveBeenCalled(); - }); -}); -// #endregion TestAgentChat.ConversationList.Delete - -// #region TestAgentChat.ConversationList.Props [C:2] [TYPE Test] -// @UX_STATE loaded — callbacks are properly wired. -describe("ConversationList — callbacks", () => { - it("fires onselect when clicking a conversation", () => { - const onselect = vi.fn(); - render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: null, - isLoading: false, - hasNext: false, - onselect, - }, - }); - const chatItem = screen.getByText("Chat About Dashboards"); - fireEvent.click(chatItem); - expect(onselect).toHaveBeenCalledWith("c1"); - }); - - it("renders load more button when hasNext is true", () => { - const onloadmore = vi.fn(); - render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: null, - isLoading: false, - hasNext: true, - onloadmore, - }, - }); - const loadMore = screen.queryByText(/load more/i); - expect(loadMore).toBeTruthy(); - if (loadMore) { - fireEvent.click(loadMore); - expect(onloadmore).toHaveBeenCalled(); - } - }); - - it("does not render load more button when hasNext is false", () => { - render(ConversationList, { - props: { - conversations: MOCK_CONVERSATIONS, - currentConversationId: null, - isLoading: false, - hasNext: false, - }, - }); - expect(screen.queryByText(/load more/i)).toBeNull(); - }); -}); -// #endregion TestAgentChat.ConversationList.Props -// #endregion TestAgentChat.ConversationList diff --git a/frontend/src/lib/components/assistant/__tests__/ToolCallCard.test.ts b/frontend/src/lib/components/assistant/__tests__/ToolCallCard.test.ts deleted file mode 100644 index 5e2786c0c..000000000 --- a/frontend/src/lib/components/assistant/__tests__/ToolCallCard.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -// #region TestAgentChat.ToolCallCard [C:2] [TYPE Module] [SEMANTICS test,tool,call,card] -// @BRIEF L2 UX tests for ToolCallCard — renders executing/completed/failed states with proper visual indicators. -// @RELATION BINDS_TO -> [AgentChat.ToolCallCard] -// @UX_TEST: executing → spinner visible, tool name shown, no details button. -// @UX_TEST: completed → checkmark, details toggle shows result. -// @UX_TEST: failed → cross, details show error. -import { describe, it, expect } from "vitest"; -import { render, screen, fireEvent } from "@testing-library/svelte"; -import ToolCallCard from "../ToolCallCard.svelte"; - -// #region TestAgentChat.ToolCallCard.Executing [C:2] [TYPE Test] -// @UX_STATE executing — spinner icon, tool name in mono font, no Details button. -describe("ToolCallCard — executing state", () => { - it("renders tool name and spinner", () => { - render(ToolCallCard, { - props: { - tool: "search_dashboards", - input: { query: "test" }, - status: "executing", - }, - }); - expect(screen.getByText("search_dashboards")).toBeTruthy(); - // SVG spinner should be present (has animate-spin class in the SVG element) - const svg = document.querySelector("svg.animate-spin"); - expect(svg).toBeTruthy(); - }); - - it("does not show Details button while executing", () => { - render(ToolCallCard, { - props: { - tool: "search_dashboards", - status: "executing", - }, - }); - expect(screen.queryByText("Детали")).toBeNull(); - }); -}); -// #endregion TestAgentChat.ToolCallCard.Executing - -// #region TestAgentChat.ToolCallCard.Completed [C:2] [TYPE Test] -// @UX_STATE completed — checkmark icon, Details button present, clicking shows result. -describe("ToolCallCard — completed state", () => { - it("renders tool name and checkmark", () => { - render(ToolCallCard, { - props: { - tool: "search_dashboards", - output: { found: 3 }, - status: "completed", - }, - }); - expect(screen.getByText("search_dashboards")).toBeTruthy(); - expect(screen.getByText("Детали")).toBeTruthy(); - }); - - it("toggles detail section on Details click", async () => { - render(ToolCallCard, { - props: { - tool: "search_dashboards", - output: { found: 3, items: ["a", "b"] }, - status: "completed", - }, - }); - // Initially details should be hidden - expect(document.querySelector("details")).toBeNull(); - - // Click Details button using fireEvent for reactive flush - const detailsBtn = screen.getByText("Детали"); - await fireEvent.click(detailsBtn); - - // After click, details elements appear - const postDetails = document.querySelector("details"); - expect(postDetails).toBeTruthy(); - const summary = postDetails?.querySelector("summary"); - expect(summary).toBeTruthy(); - }); -}); -// #endregion TestAgentChat.ToolCallCard.Completed - -// #region TestAgentChat.ToolCallCard.Failed [C:2] [TYPE Test] -// @UX_STATE failed — cross icon, error visible inline. -describe("ToolCallCard — failed state", () => { - it("renders tool name, cross, and error detail", () => { - render(ToolCallCard, { - props: { - tool: "search_dashboards", - error: "API timeout after 30s", - status: "failed", - }, - }); - expect(screen.getByText("search_dashboards")).toBeTruthy(); - expect(screen.getByText("Детали")).toBeTruthy(); - }); -}); -// #endregion TestAgentChat.ToolCallCard.Failed -// #endregion TestAgentChat.ToolCallCard diff --git a/frontend/src/lib/components/assistant/__tests__/ToolCallCard.ux.test.ts b/frontend/src/lib/components/assistant/__tests__/ToolCallCard.ux.test.ts deleted file mode 100644 index 49fa371c7..000000000 --- a/frontend/src/lib/components/assistant/__tests__/ToolCallCard.ux.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -// #region Test.AgentChat.ToolCallCard.Ux [C:3] [TYPE Module] [SEMANTICS test,agent,tools,ux] -// @BRIEF L2 UX tests for ToolCallCard retrying/timeout/cancelled states — verifies visual indicators, action buttons, and callback wiring. -// @RELATION BINDS_TO -> [AgentChat.ToolCallCard] -// @TEST_EDGE: retrying_rendered -> status=retrying shows ⟳ spinner with retry count text -// @TEST_EDGE: read_timeout_rendered -> status=timeout (read tool) shows timeout message and retry button -// @TEST_EDGE: write_timeout_rendered -> status=timeout (write tool) shows Superset status message, NO retry button -// @TEST_EDGE: cancelled_rendered -> status=cancelled shows 🚫 icon and user-cancelled message -import { describe, it, expect, vi } from "vitest"; -import { render, screen, fireEvent } from "@testing-library/svelte"; -import ToolCallCard from "../ToolCallCard.svelte"; - -// #region Test.AgentChat.ToolCallCard.Ux.Retrying [C:2] [TYPE Test] -// @UX_STATE retrying — ⟳ spinner with retry count text. -describe("ToolCallCard — retrying state", () => { - it("shows spinner icon and retry count", () => { - const { container } = render(ToolCallCard, { - props: { - tool: "run_migration", - status: "retrying", - retryCount: 1, - maxRetries: 2, - }, - }); - // ⟳ spinner with animate-spin class - const spinner = container.querySelector("span.animate-spin"); - expect(spinner).toBeTruthy(); - expect(spinner?.textContent?.trim()).toBe("⟳"); - // Retry count text - expect(container.textContent).toContain("Повторная попытка..."); - expect(container.textContent).toMatch(/\(1\/2\)/); - }); - - it("shows tool name during retry", () => { - render(ToolCallCard, { - props: { - tool: "run_migration", - status: "retrying", - retryCount: 1, - maxRetries: 2, - }, - }); - expect(screen.getByText("run_migration")).toBeTruthy(); - }); -}); -// #endregion Test.AgentChat.ToolCallCard.Ux.Retrying - -// #region Test.AgentChat.ToolCallCard.Ux.ReadTimeout [C:2] [TYPE Test] -// @UX_STATE timeout (read tool) — ⏱️ icon, timeout message, retry button with onRetry callback. -describe("ToolCallCard — read timeout state", () => { - it("shows timeout icon and message", () => { - const { container } = render(ToolCallCard, { - props: { - tool: "search_dashboards", - status: "timeout", - timeoutSeconds: 30, - isWriteTool: false, - }, - }); - expect(container.textContent).toContain("⏱️"); - expect(container.textContent).toContain("Превышено время ожидания"); - expect(container.textContent).toContain("30с"); - }); - - it("shows retry button", () => { - render(ToolCallCard, { - props: { - tool: "search_dashboards", - status: "timeout", - timeoutSeconds: 30, - isWriteTool: false, - }, - }); - expect(screen.getByRole("button", { name: /Повторить/ })).toBeTruthy(); - }); - - it("fires onRetry callback when retry button is clicked", async () => { - const onRetry = vi.fn(); - render(ToolCallCard, { - props: { - tool: "search_dashboards", - status: "timeout", - timeoutSeconds: 30, - isWriteTool: false, - onRetry, - }, - }); - const retryBtn = screen.getByRole("button", { name: /Повторить/ }); - await fireEvent.click(retryBtn); - expect(onRetry).toHaveBeenCalledOnce(); - }); -}); -// #endregion Test.AgentChat.ToolCallCard.Ux.ReadTimeout - -// #region Test.AgentChat.ToolCallCard.Ux.WriteTimeout [C:2] [TYPE Test] -// @UX_STATE timeout (write tool) — Superset status message, NO retry button. -describe("ToolCallCard — write timeout state", () => { - it("shows Superset status message", () => { - const { container } = render(ToolCallCard, { - props: { - tool: "migrate_dashboard", - status: "timeout", - timeoutSeconds: 30, - isWriteTool: true, - }, - }); - expect(container.textContent).toContain("Проверьте статус операции в Superset"); - }); - - it("does NOT show retry button", () => { - render(ToolCallCard, { - props: { - tool: "migrate_dashboard", - status: "timeout", - isWriteTool: true, - }, - }); - expect(screen.queryByRole("button", { name: /Повторить/ })).toBeNull(); - }); -}); -// #endregion Test.AgentChat.ToolCallCard.Ux.WriteTimeout - -// #region Test.AgentChat.ToolCallCard.Ux.Cancelled [C:2] [TYPE Test] -// @UX_STATE cancelled — 🚫 icon and user-cancelled message. -describe("ToolCallCard — cancelled state", () => { - it("shows cancelled icon and message", () => { - const { container } = render(ToolCallCard, { - props: { - tool: "search_dashboards", - status: "cancelled", - }, - }); - expect(container.textContent).toContain("🚫"); - expect(container.textContent).toContain("Отменено пользователем"); - }); -}); -// #endregion Test.AgentChat.ToolCallCard.Ux.Cancelled -// #endregion Test.AgentChat.ToolCallCard.Ux diff --git a/frontend/src/lib/components/assistant/__tests__/assistant_chat.integration.test.ts b/frontend/src/lib/components/assistant/__tests__/assistant_chat.integration.test.ts deleted file mode 100644 index 4dfc24468..000000000 --- a/frontend/src/lib/components/assistant/__tests__/assistant_chat.integration.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -// #region Tests.AssistantChat.AssistantChatIntegrationTestModule [TYPE Function] -// @SEMANTICS: assistant, integration-test, ux-contract, i18n -// @BRIEF: Contract-level integration checks for assistant chat panel implementation and localization wiring. -// @LAYER Tests -// @RELATION DEPENDS_ON -> [EXT:frontend:AssistantChatPanel] -// @INVARIANT: Critical assistant UX states and action hooks remain present in component source. -// @TEST_CONTRACT: AssistantChatSourceArtifacts -> ContractAssertions -// @TEST_SCENARIO: assistant_contract_and_i18n_intact -> Component semantic/UX anchors and locale keys stay consistent. -// @TEST_FIXTURE: assistant_locales_en_ru -> file:src/lib/i18n/locales/en/assistant.json + file:src/lib/i18n/locales/ru/assistant.json -// @TEST_EDGE: missing_component_anchor -> Missing DEF/UX tags fails contract assertion. -// @TEST_EDGE: missing_action_hook -> Missing confirm/cancel/open_task hooks fails integration assertion. -// @TEST_EDGE: missing_locale_key -> Missing assistant locale key in en/ru fails dictionary assertion. -// @TEST_INVARIANT: assistant_ux_contract_visible -> VERIFIED_BY: [assistant_contract_and_i18n_intact] - -import { describe, it, expect } from 'vitest'; -import fs from 'node:fs'; -import path from 'node:path'; - -const COMPONENT_PATH = path.resolve( - process.cwd(), - 'src/lib/components/assistant/AssistantChatPanel.svelte', -); -const EN_LOCALE_PATH = path.resolve( - process.cwd(), - 'src/lib/i18n/locales/en/assistant.json', -); -const RU_LOCALE_PATH = path.resolve( - process.cwd(), - 'src/lib/i18n/locales/ru/assistant.json', -); - -// #region Tests.AssistantChat.ReadJsonFunction [TYPE Function] -// @BRIEF: Read and parse JSON fixture file from disk. -// @PRE: filePath points to existing UTF-8 JSON file. -// @POST: Returns parsed object representation. -function readJson(filePath) { - return JSON.parse(fs.readFileSync(filePath, 'utf-8')); -} -// #endregion Tests.AssistantChat.ReadJsonFunction - -// #region Tests.AssistantChat.AssistantChatContractTestsFunction [TYPE Function] -// @BRIEF: Validate assistant chat component contract and locale integration without DOM runtime dependency. -// @PRE: Component and locale files exist in expected paths. -// @POST: Contract checks guarantee assistant UI anchors and i18n wiring remain intact. -describe('AssistantChatPanel integration contract', () => { - it('contains semantic anchors and UX contract tags', () => { - const source = fs.readFileSync(COMPONENT_PATH, 'utf-8'); - - expect(source).toContain(''); - }); - - it('keeps confirmation/task-tracking action hooks in place', () => { - const source = fs.readFileSync(COMPONENT_PATH, 'utf-8'); - - expect(source).toContain('if (action.type === "confirm" && message.confirmation_id)'); - expect(source).toContain('if (action.type === "cancel" && message.confirmation_id)'); - expect(source).toContain('if (action.type === "open_task" && action.target)'); - expect(source).toContain('openDrawerForTask(action.target)'); - expect(source).toContain('ROUTES.reports.list()'); - }); - - it('guards first-message optimistic flow from premature history overwrite', () => { - const source = fs.readFileSync(COMPONENT_PATH, 'utf-8'); - - expect(source).toContain('if (panelVisible && initialized && conversationId && !loading)'); - expect(source).toContain('function appendLocalUserMessage(text, targetConversationId = conversationId)'); - expect(source).toContain('conversation_id: targetConversationId || null'); - expect(source).toContain('historyLoadVersion += 1;'); - }); - - it('uses i18n bindings for assistant UI labels', () => { - const source = fs.readFileSync(COMPONENT_PATH, 'utf-8'); - - expect(source).toContain('$t.assistant?.title'); - expect(source).toContain('$t.assistant?.input_placeholder'); - expect(source).toContain('$t.assistant?.send'); - expect(source).toContain('$t.assistant?.states?.[message.state]'); - expect(source).toContain('$t.assistant?.open_task_drawer'); - }); - - it('provides assistant locale keys in both en and ru dictionaries', () => { - const en = readJson(EN_LOCALE_PATH); - const ru = readJson(RU_LOCALE_PATH); - - expect(en.title).toBeTruthy(); - expect(en.send).toBeTruthy(); - expect(en.states.needs_confirmation).toBeTruthy(); - - expect(ru.title).toBeTruthy(); - expect(ru.send).toBeTruthy(); - expect(ru.states.needs_confirmation).toBeTruthy(); - }); -}); -// #endregion Tests.AssistantChat.AssistantChatContractTestsFunction -// #endregion Tests.AssistantChat.AssistantChatIntegrationTestModule diff --git a/frontend/src/lib/components/assistant/__tests__/assistant_confirmation.integration.test.ts b/frontend/src/lib/components/assistant/__tests__/assistant_confirmation.integration.test.ts deleted file mode 100644 index 7c17e1784..000000000 --- a/frontend/src/lib/components/assistant/__tests__/assistant_confirmation.integration.test.ts +++ /dev/null @@ -1,211 +0,0 @@ -// #region Test.Assistant.ConfirmationIntegration [C:3] [TYPE Module] [SEMANTICS test,assistant,confirmation,integration] -// @BRIEF Verify assistant confirmation controls invoke APIs and surface operation failures. -// @RELATION BINDS_TO -> [Assistant.ChatPanel] -// @TEST_CONTRACT: Pending confirmation -> Confirm and cancel actions target its confirmation identifier -// @TEST_SCENARIO: confirmation_card -> Operation scope and warning references are visible -// @TEST_EDGE: confirm_action -> Confirm API receives the pending confirmation identifier -// @TEST_EDGE: cancel_action -> Cancel API receives the pending confirmation identifier -// @TEST_EDGE: external_failure -> Failed confirmation action is rendered as an error message -// @TEST_INVARIANT: ConfirmationActionsUsePendingId -> VERIFIED_BY: [renders_action_buttons_and_triggers_confirm_api_call, triggers_cancel_api_call_when_cancel_button_is_clicked] -// @TEST_INVARIANT: ConfirmationFailureVisible -> VERIFIED_BY: [shows_toast_error_when_action_fails] -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; -import AssistantChatPanel from '../AssistantChatPanel.svelte'; -import * as api from '$lib/api/assistant.js'; -import { assistantChatStore } from '$lib/stores/assistantChat.svelte.js'; - -// Mock dependencies -vi.mock('$lib/api/assistant.js', () => ({ - getAssistantHistory: vi.fn(), - confirmAssistantOperation: vi.fn(), - cancelAssistantOperation: vi.fn(), - getAssistantConversations: vi.fn(() => Promise.resolve({ items: [], total: 0 })), - sendAssistantMessage: vi.fn() -})); - -vi.mock('$lib/api', () => ({ - api: { - getLlmStatus: vi.fn(() => Promise.resolve({ configured: true })), - fetchApi: vi.fn(() => Promise.resolve(null)), - }, - requestApi: vi.fn(), -})); - -vi.mock('$lib/toasts.svelte.js', () => ({ - notifications: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), show: vi.fn() }, -})); - -const mockAssistantState = { isOpen: true, conversationId: 'conv-1', seedMessage: '', focusTarget: { target: 'mapping:m-1', source: 'test' } }; -vi.mock('$lib/stores/assistantChat.svelte.js', () => ({ - assistantChatStore: { - subscribe: (fn) => { - fn(mockAssistantState); - return () => { }; - }, - get value() { return mockAssistantState; }, - }, - closeAssistantChat: vi.fn(), - setAssistantConversationId: vi.fn(), - setAssistantSeedMessage: vi.fn(), - setAssistantFocusTarget: vi.fn(), -})); - -vi.mock('$app/navigation', () => ({ - goto: vi.fn() -})); - -const mockTranslations = { - assistant: { - action_failed: 'Action failed', - confirm: 'Confirm', - cancel: 'Cancel', - title: 'Assistant', - close: 'Close', - loading_history: 'Loading history...', - try_commands: 'Try commands', - sample_command_branch: 'branch', - sample_command_migration: 'migration', - sample_command_status: 'status', - you: 'You', - assistant: 'Assistant', - states: { - needs_confirmation: 'Needs confirmation', - failed: 'Failed' - }, - task_id: 'task_id', - open_task_drawer: 'Open Task Drawer', - input_placeholder: 'Type a command...', - send: 'Send', - conversations: 'Conversations', - new: 'New', - active: 'Active', - archived: 'Archived', - more: 'More', - session_scope_title: 'Active review context', - focus_target_label: 'Focus', - clear_focus_action: 'Clear focus', - confirmation_card_title: 'Confirmation required', - confirmation_scope_fallback: 'This action affects the current assistant scope.', - confirmation_operation_label: 'Action', - highlight_workspace_action: 'Highlight in workspace', - } -}; -vi.mock('$lib/i18n/index.svelte.js', () => ({ - t: { - subscribe: (fn) => { - fn(mockTranslations); - return () => { }; - } - }, - getT: vi.fn(() => mockTranslations), - _: vi.fn((key) => key), -})); - -describe('AssistantChatPanel confirmation functional tests', () => { - const mockMessage = { - message_id: 'msg-123', - role: 'assistant', - text: 'Confirm migration?', - state: 'needs_confirmation', - created_at: new Date().toISOString(), - conversation_id: 'conv-1', - confirmation_id: 'conf-123', - intent: { - operation: 'approve_all_mapping_warnings', - remaining_blockers: ['Preview is stale'], - open_warning_refs: ['mapping:m-1'] - }, - actions: [ - { type: 'confirm', label: 'Confirm' }, - { type: 'cancel', label: 'Cancel' }, - { type: 'focus_target', label: 'Highlight', target: 'mapping:m-1' } - ] - }; - - beforeEach(() => { - vi.clearAllMocks(); - }); - - // #region Test.Assistant.ConfirmationIntegration.ConfirmAction [C:2] [TYPE Function] [SEMANTICS test,assistant,confirmation,api] - // @BRIEF Sends the pending confirmation identifier to the confirm API. - it('renders action buttons and triggers confirm API call', async () => { - // Mock getAssistantHistory to return our message - api.getAssistantHistory.mockImplementation(async () => ({ - items: [mockMessage], - total: 1, - has_next: false - })); - - render(AssistantChatPanel); - - // Wait for message to render - const confirmBtn = await screen.findByText('Confirm', {}, { timeout: 3000 }); - expect(confirmBtn).toBeTruthy(); - - await fireEvent.click(confirmBtn); - - expect(api.confirmAssistantOperation).toHaveBeenCalledWith('conf-123'); - }); - // #endregion Test.Assistant.ConfirmationIntegration.ConfirmAction - - // #region Test.Assistant.ConfirmationIntegration.CancelAction [C:2] [TYPE Function] [SEMANTICS test,assistant,confirmation,api] - // @BRIEF Sends the pending confirmation identifier to the cancel API. - it('triggers cancel API call when cancel button is clicked', async () => { - api.getAssistantHistory.mockImplementation(async () => ({ - items: [mockMessage], - total: 1, - has_next: false - })); - - render(AssistantChatPanel); - - const cancelBtn = await screen.findByText('Cancel', {}, { timeout: 3000 }); - await fireEvent.click(cancelBtn); - - expect(api.cancelAssistantOperation).toHaveBeenCalledWith('conf-123'); - }); - // #endregion Test.Assistant.ConfirmationIntegration.CancelAction - - // #region Test.Assistant.ConfirmationIntegration.FailureFeedback [C:2] [TYPE Function] [SEMANTICS test,assistant,confirmation,error] - // @BRIEF Displays a failed confirmation operation message. - it('shows toast error when action fails', async () => { - api.getAssistantHistory.mockImplementation(async () => ({ - items: [mockMessage], - total: 1, - has_next: false - })); - api.confirmAssistantOperation.mockImplementation(async () => { - throw new Error('Network error'); - }); - - render(AssistantChatPanel); - - const confirmBtn = await screen.findByText('Confirm', {}, { timeout: 3000 }); - await fireEvent.click(confirmBtn); - - await waitFor(() => { - // The component appends a failed message to the chat - expect(screen.getAllByText(/Network error/)).toBeTruthy(); - }, { timeout: 3000 }); - }); - // #endregion Test.Assistant.ConfirmationIntegration.FailureFeedback - - // #region Test.Assistant.ConfirmationIntegration.ScopeDetails [C:2] [TYPE Function] [SEMANTICS test,assistant,confirmation,ui] - // @BRIEF Renders the pending operation scope and associated warning references. - it('renders confirmation card scope details', async () => { - api.getAssistantHistory.mockImplementation(async () => ({ - items: [mockMessage], - total: 1, - has_next: false - })); - - render(AssistantChatPanel); - - expect(await screen.findByText('Confirmation required', {}, { timeout: 3000 })).toBeTruthy(); - expect(screen.getByText(/approve_all_mapping_warnings/)).toBeTruthy(); - expect(screen.getByText(/Preview is stale/)).toBeTruthy(); - expect(screen.getAllByText(/mapping:m-1/).length).toBeGreaterThan(0); - }); - // #endregion Test.Assistant.ConfirmationIntegration.ScopeDetails -}); -// #endregion Test.Assistant.ConfirmationIntegration diff --git a/frontend/src/lib/components/assistant/__tests__/assistant_first_message.integration.test.ts b/frontend/src/lib/components/assistant/__tests__/assistant_first_message.integration.test.ts deleted file mode 100644 index 9d5bdd343..000000000 --- a/frontend/src/lib/components/assistant/__tests__/assistant_first_message.integration.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -// #region Tests.AssistantFirstMessage.AssistantFirstMessageIntegrationTestModule [TYPE Function] -// @SEMANTICS: assistant, integration-test, optimistic-message, conversation-race -// @BRIEF: Verify first optimistic user message stays visible while a new conversation request is pending. -// @LAYER Tests -// @RELATION DEPENDS_ON -> [EXT:frontend:AssistantChatPanel] -// @INVARIANT: Starting a new conversation must not trigger history reload that overwrites the first local user message. - -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; -import AssistantChatPanel from '../AssistantChatPanel.svelte'; -import * as assistantApi from '$lib/api/assistant'; - -const { assistantState } = vi.hoisted(() => ({ - assistantState: (() => { - let value = { - isOpen: true, - conversationId: null, - seedMessage: '', - focusTarget: null, - }; - const subscribers = new Set(); - return { - subscribe(fn) { - subscribers.add(fn); - fn(value); - return () => subscribers.delete(fn); - }, - set(next) { - value = next; - subscribers.forEach((fn) => fn(value)); - }, - update(updater) { - value = updater(value); - subscribers.forEach((fn) => fn(value)); - }, - }; - })(), -})); - -vi.mock('$lib/api/assistant.js', () => ({ - getAssistantHistory: vi.fn(() => - Promise.resolve({ items: [], total: 0, has_next: false }), - ), - getAssistantConversations: vi.fn(() => - Promise.resolve({ - items: [], - total: 0, - has_next: false, - active_total: 0, - archived_total: 0, - }), - ), - deleteAssistantConversation: vi.fn(), - confirmAssistantOperation: vi.fn(), - cancelAssistantOperation: vi.fn(), - sendAssistantMessage: vi.fn(), -})); - -vi.mock('$lib/api', () => ({ - api: { - getLlmStatus: vi.fn(() => Promise.resolve({ configured: true, reason: 'ok' })), - fetchApi: vi.fn(() => Promise.resolve(null)), - }, - requestApi: vi.fn(), -})); - -vi.mock('$lib/stores/assistantChat.svelte.js', () => ({ - assistantChatStore: { - subscribe: assistantState.subscribe, - get value() { return { isOpen: true, conversationId: null, seedMessage: '', focusTarget: null }; }, - }, - closeAssistantChat: vi.fn(), - setAssistantConversationId: vi.fn((conversationId) => { - assistantState.update((state) => ({ ...state, conversationId })); - }), - setAssistantSeedMessage: vi.fn((seedMessage) => { - assistantState.update((state) => ({ ...state, seedMessage })); - }), - setAssistantFocusTarget: vi.fn((focusTarget) => { - assistantState.update((state) => ({ ...state, focusTarget })); - }), -})); - -vi.mock('$lib/toasts.svelte.js', () => ({ - notifications: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), show: vi.fn() }, -})); - -vi.mock('$lib/stores/taskDrawer.svelte.js', () => ({ - openDrawerForTask: vi.fn(), -})); - -vi.mock('$app/navigation', () => ({ - goto: vi.fn(), -})); - -vi.mock('../../../../services/gitService.js', () => ({ - gitService: { - getDiff: vi.fn(), - }, -})); - -const mockTranslations = { - assistant: { - title: 'Assistant', - close: 'Close', - conversations: 'Conversations', - new: 'New', - active: 'Active', - archived: 'Archived', - more: 'More', - loading_history: 'Loading history', - loading_older: 'Loading older', - try_commands: 'Try commands', - sample_command_branch: 'branch', - sample_command_migration: 'migration', - sample_command_status: 'status', - you: 'You', - assistant: 'Assistant', - thinking: 'Thinking', - input_placeholder: 'Type command', - send: 'Send', - conversation: 'Conversation', - session_scope_title: 'Active review context', - session_scope_label: 'Session', - focus_target_label: 'Focus', - clear_focus_action: 'Clear focus', - states: { - success: 'Success', - failed: 'Failed', - started: 'Started', - }, - open_task_drawer: 'Open task drawer', - }, - dashboard: {}, -}; -vi.mock('$lib/i18n/index.svelte.js', () => ({ - t: { - subscribe: (fn) => { - fn(mockTranslations); - return () => {}; - }, - }, - getT: vi.fn(() => mockTranslations), - _: vi.fn((key) => key), -})); - -// #region Tests.AssistantFirstMessage.AssistantFirstMessageTestsFunction [TYPE Function] -// @RELATION BINDS_TO -> [EXT:frontend:AssistantFirstMessageIntegrationTest] -// @BRIEF: Guard optimistic first-message UX against history reload race in new conversation flow. -// @PRE: Assistant panel renders with open state and mocked network dependencies. -// @POST: First user message remains visible before pending send request resolves. -describe('AssistantChatPanel first message flow', () => { - beforeEach(() => { - vi.clearAllMocks(); - assistantState.set({ - isOpen: true, - conversationId: null, - seedMessage: '', - focusTarget: null, - }); - }); - - it('keeps the first optimistic user message visible during pending send in a new conversation', async () => { - let resolveSend; - assistantApi.sendAssistantMessage.mockImplementation( - (payload) => - new Promise((resolve) => { - resolveSend = () => - resolve({ - response_id: 'resp-1', - conversation_id: payload.conversation_id, - text: 'Started', - state: 'success', - created_at: new Date().toISOString(), - actions: [], - }); - }), - ); - - render(AssistantChatPanel); - - await waitFor(() => { - expect(assistantApi.getAssistantHistory).toHaveBeenCalledTimes(1); - }); - - await fireEvent.click(screen.getByText('New')); - - const input = screen.getByPlaceholderText('Type command'); - await fireEvent.input(input, { target: { value: 'first prompt' } }); - await fireEvent.click(screen.getByText('Send')); - - expect(screen.getByText('first prompt')).toBeTruthy(); - expect(assistantApi.sendAssistantMessage).toHaveBeenCalledTimes(1); - - await waitFor(() => { - expect(assistantApi.getAssistantHistory).toHaveBeenCalledTimes(1); - }); - - resolveSend(); - - await waitFor(() => { - expect(screen.getByText('Started')).toBeTruthy(); - }); - }); - -}); -// #endregion Tests.AssistantFirstMessage.AssistantFirstMessageTestsFunction -// #endregion Tests.AssistantFirstMessage.AssistantFirstMessageIntegrationTestModule diff --git a/frontend/src/lib/components/assistant/__tests__/dashboard_scenario_confirmation.integration.test.ts b/frontend/src/lib/components/assistant/__tests__/dashboard_scenario_confirmation.integration.test.ts deleted file mode 100644 index d8390c6f7..000000000 --- a/frontend/src/lib/components/assistant/__tests__/dashboard_scenario_confirmation.integration.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -// frontend/src/lib/components/assistant/__tests__/dashboard_scenario_confirmation.integration.test.ts -// #region Test.DashboardTesting.ScenarioConfirmation [C:3] [TYPE Module] [SEMANTICS test,dashboard-testing,confirmation,gate,integration] -// @BRIEF 039 T035/T037: scenario save/baseline approval bind to the 036 pending gate; deny/blank-reason/permission-denial handled. -// @RELATION BINDS_TO -> [DashboardTesting.WorkspaceModel] -import { describe, it, expect } from "vitest"; -import { DashboardScenarioWorkspaceModel } from "../../../models/DashboardScenarioWorkspaceModel.svelte.ts"; - -function makeHost() { - return { runModel: { pendingGate: undefined as unknown } }; -} - -describe("Scenario HITL -> 036 gate (T035/T036/T037)", () => { - it("save delegates to 036 pending gate with targets + reasonRequired", () => { - const m = new DashboardScenarioWorkspaceModel(); - const host = makeHost(); - m.requestDurableAction("save", ["scenarios/sc-1/scenario.json"], false, host as never); - const gate = host.runModel.pendingGate as { operation: string; targets: string[]; reason_required: boolean }; - expect(gate.operation).toBe("save"); - expect(gate.targets).toContain("scenarios/sc-1/scenario.json"); - expect(gate.reason_required).toBe(false); - }); - - it("baseline approval requires reason", () => { - const m = new DashboardScenarioWorkspaceModel(); - const host = makeHost(); - m.requestDurableAction("baseline_approval", ["baselines/2026-08-04.json"], true, host as never); - const gate = host.runModel.pendingGate as { operation: string; reason_required: boolean }; - expect(gate.operation).toBe("baseline_approval"); - expect(gate.reason_required).toBe(true); - }); - - it("deny preserves drafts and dispatches nothing", () => { - const m = new DashboardScenarioWorkspaceModel(); - m.enterScenario({ parameters: [{ name: "p", label: "P", type: "string", required: true, affected_step_ids: [] }], steps: [], warnings: [], blockers: [] } as never); - m.updateParameter("p", "keep-me"); - // Deny is a no-op on the workspace model — drafts are preserved; no durable dispatch. - expect(m.parameterDrafts["p"]).toBe("keep-me"); - expect(m.scenario).not.toBeNull(); - }); -}); - -// #endregion Test.DashboardTesting.ScenarioConfirmation diff --git a/frontend/src/lib/components/backups/BackupList.svelte b/frontend/src/lib/components/backups/BackupList.svelte index 135c3308c..469a2bc70 100644 --- a/frontend/src/lib/components/backups/BackupList.svelte +++ b/frontend/src/lib/components/backups/BackupList.svelte @@ -6,7 +6,7 @@ @SEMANTICS: backup, list, table @BRIEF: Displays a list of existing backups. @LAYER Component -@RELATION USED_BY -> [frontend/src/lib/components/backups/BackupManager.svelte] +@RELATION CALLED_BY -> [frontend/src/lib/components/backups/BackupManager.svelte] --> -{#if MCP_DECOMMISSION} +
-{:else if model} - -
- - - - - {#if model.isConversationSidebarOpen} -
-
-
- {$t.assistant?.conversations_title || "Conversations"} - -
- model!.selectConversation(id, true)} - ondelete={(id) => model!.deleteConversation(id)} - onloadmore={() => model!.loadConversations(false)} - onsearch={(q: string) => model!.searchConversations(q)} - /> -
- -
- {/if} - - -
- {#if model.scenarioMode} - -
- model.retryScenarioStart()} - evidence={workspace.evidence} - vlmFindings={workspace.vlmFindings} - dispositions={workspace.dispositions} - onDisposition={(id, d) => workspace.updateFindingDisposition(id, d)} - /> -
- {/if} -
- -
-
-
-{:else} -
-
- - - - - {$t.assistant?.connecting_to_agent || "Connecting to agent..."} -
-
-{/if} - +
+ diff --git a/frontend/src/routes/migration/mappings/+page.svelte b/frontend/src/routes/migration/mappings/+page.svelte index 61e7cde0e..3a85d02a3 100644 --- a/frontend/src/routes/migration/mappings/+page.svelte +++ b/frontend/src/routes/migration/mappings/+page.svelte @@ -47,7 +47,7 @@ - +
diff --git a/frontend/src/routes/translate/[id]/+page.svelte b/frontend/src/routes/translate/[id]/+page.svelte index be32eb502..1df57ffd2 100644 --- a/frontend/src/routes/translate/[id]/+page.svelte +++ b/frontend/src/routes/translate/[id]/+page.svelte @@ -13,11 +13,11 @@ - - - - - + + + + + diff --git a/frontend/src/types/agent.ts b/frontend/src/types/agent.ts deleted file mode 100644 index 9fd624cea..000000000 --- a/frontend/src/types/agent.ts +++ /dev/null @@ -1,71 +0,0 @@ -// frontend/src/types/agent.ts -// #region Types.Agent [C:1] [TYPE Module] [SEMANTICS agent,types,dto] -// @BRIEF TypeScript DTOs for Gradio Agent Chat — must match backend/src/schemas/agent.py exactly. - -export interface ConversationItem { - id: string; - title: string; - updated_at: string; - message_count: number; -} - -export interface ConversationListResponse { - items: ConversationItem[]; - has_next: boolean; - active_total: number; - archived_total: number; -} - -export interface ToolCall { - tool: string; - input: Record; - output?: Record; - error?: string; - status: "executing" | "completed" | "failed"; -} - -export interface AttachmentMeta { - name: string; - type: "pdf" | "xlsx" | "json" | "csv" | "txt" | "png" | "jpeg"; - size: number; - preview_url?: string; -} - -export interface StreamMetadata { - type?: "stream_token" | "tool_start" | "tool_end" | "tool_error" - | "confirm_required" | "confirm_resolved" | "error"; - token?: string; - tool?: string; - input?: Record; - output?: Record; - error?: string; - prompt?: string; - thread_id?: string; - result?: "confirmed" | "denied"; - code?: string; - detail?: string; -} - -export interface MessageItem { - id: string; - conversation_id: string; - role: "user" | "assistant" | "tool" | "system"; - text: string | null; - metadata?: StreamMetadata; - state?: string; - task_id?: string; - tool_calls: ToolCall[] | null; - attachments: AttachmentMeta[] | null; - created_at: string; -} - -export interface HistoryResponse { - items: MessageItem[]; - has_next: boolean; - conversation_id: string | null; -} - -export interface DeleteResponse { - deleted: boolean; -} -// #endregion Types.Agent diff --git a/frontend/src/types/global.d.ts b/frontend/src/types/global.d.ts index 1e2c53354..d736123fc 100644 --- a/frontend/src/types/global.d.ts +++ b/frontend/src/types/global.d.ts @@ -4,8 +4,3 @@ // This declaration keeps TypeScript aware of the global constant. declare const __APP_VERSION__: string; // #endregion Types.Global.GlobalVersion - -// #region Types.Global.McpDecommission [C:1] [TYPE Block] [SEMANTICS mcp,config,feature-flag] -// @BRIEF TypeScript declaration for the Vite-injected MCP decommission flag. -declare const __MCP_DECOMMISSION__: boolean; -// #endregion Types.Global.McpDecommission diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 5b2758777..5847a7e45 100755 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -17,23 +17,13 @@ const APP_VERSION = (() => { } })(); -const MCP_DECOMMISSION = process.env.MCP_DECOMMISSION === 'true'; - export default defineConfig({ define: { - __APP_VERSION__: JSON.stringify(APP_VERSION), - __MCP_DECOMMISSION__: JSON.stringify(MCP_DECOMMISSION) + __APP_VERSION__: JSON.stringify(APP_VERSION) }, plugins: [sveltekit()], server: { proxy: { - '/api/agent/gradio': { - target: process.env.GRADIO_URL || 'http://127.0.0.1:7860', - changeOrigin: true, - secure: false, - rewrite: (path) => path.replace(/^\/api\/agent\/gradio/, ''), - ws: true - }, '/api': { target: process.env.BACKEND_URL || 'http://127.0.0.1:8000', changeOrigin: true, diff --git a/run.sh b/run.sh index 82f7a98ed..8e02e1365 100755 --- a/run.sh +++ b/run.sh @@ -50,18 +50,16 @@ load_dotenv "$PROJECT_ROOT/backend/.env" DEV_MODE="${DEV_MODE:-false}" BACKEND_PORT=${BACKEND_PORT:-8000} FRONTEND_PORT=${FRONTEND_PORT:-5173} -AGENT_PORT=${AGENT_PORT:-7860} SKIP_INSTALL=false -# Service-to-service shared secret between backend and the Gradio agent. -# Used for agent lifecycle persistence and the internal /api/agent/llm-config -# endpoint (which returns the decrypted LLM API key). When unset, a random -# per-run secret is generated so every service started by this run.sh shares it — -# the old hardcoded default ('agent-service-secret') was public in the repo and -# would let anyone forge service auth for the secrets-returning endpoint. +# Service-to-service shared secret validated by the backend for service +# principals (MCP service tokens, internal integrations). When unset, a random +# per-run secret is generated for every service started by this run.sh — the +# old hardcoded default ('agent-service-secret') was public in the repo and +# would let anyone forge service auth. if [ -z "${SERVICE_JWT:-}" ]; then export SERVICE_JWT="$(openssl rand -hex 24 2>/dev/null || echo "svc-$(date +%s%N)-$$")" - echo -e "\033[0;33m[SERVICE_JWT]\033[0m Not set — generated a random service secret for this run (all services share it)." + echo -e "\033[0;33m[SERVICE_JWT]\033[0m Not set — generated a random service secret for this run." echo -e "\033[0;33m[SERVICE_JWT]\033[0m Set SERVICE_JWT explicitly when running services in separate terminals." fi RUN_SERVICE_JWT="$SERVICE_JWT" @@ -77,7 +75,7 @@ if [[ "$STORAGE_ROOT_PATH" == "/" || "$STORAGE_ROOT_PATH" != "$DEFAULT_STORAGE_R echo "Error: STORAGE_ROOT_PATH must be inside this project or its sibling ss-tools-storage directory." >&2 exit 1 fi -mkdir -p "$STORAGE_ROOT_PATH/repositories" "$STORAGE_ROOT_PATH/backups" "$STORAGE_ROOT_PATH/drafts" "$STORAGE_ROOT_PATH/chat_uploads" +mkdir -p "$STORAGE_ROOT_PATH/repositories" "$STORAGE_ROOT_PATH/backups" "$STORAGE_ROOT_PATH/drafts" export STORAGE_ROOT_PATH # Help message @@ -90,14 +88,9 @@ show_help() { echo "" echo "Environment Variables:" echo " DEV_MODE Hot-reload mode (true/false). Default: false" - echo " Enables uvicorn --reload + watchfiles agent watcher" + echo " Enables uvicorn --reload" echo " BACKEND_PORT Port for the backend server (default: 8000)" echo " FRONTEND_PORT Port for the frontend server (default: 5173)" - echo " AGENT_PORT Port for the Gradio agent (default: 7860)" - echo " AGENT_CONFIRM_TOOLS Enable HITL confirmation before tool calls (default: true)" - echo "" - echo " LLM providers are fetched from FastAPI /api/agent/llm-config at startup." - echo " Configure them in Admin -> LLM Settings." } # Parse arguments @@ -361,9 +354,6 @@ cleanup() { if [ -n "$FRONTEND_PID" ]; then kill -TERM $FRONTEND_PID 2>/dev/null || true fi - if [ -n "$AGENT_PID" ]; then - kill -TERM $AGENT_PID 2>/dev/null || true - fi # Phase 2: wait for graceful exit (up to 2s), then force kill sleep 1 @@ -373,13 +363,9 @@ cleanup() { if [ -n "$FRONTEND_PID" ]; then kill -KILL $FRONTEND_PID 2>/dev/null || true fi - if [ -n "$AGENT_PID" ]; then - kill -KILL $AGENT_PID 2>/dev/null || true - fi # Phase 3: fuser fallback — kill anything still on our ports (belt-and-suspenders) if command -v fuser &>/dev/null; then - fuser -k ${AGENT_PORT}/tcp 2>/dev/null || true fuser -k ${BACKEND_PORT}/tcp 2>/dev/null || true fuser -k ${FRONTEND_PORT}/tcp 2>/dev/null || true fi @@ -435,54 +421,14 @@ start_frontend() { cd frontend local _color=$'\033[0;32m[Frontend]\033[0m ' BACKEND_URL="http://127.0.0.1:${BACKEND_PORT}" \ - GRADIO_URL="http://127.0.0.1:${AGENT_PORT}" \ npm run dev -- --host 0.0.0.0 --port "$FRONTEND_PORT" \ > >(awk -v prefix="$_color " '{print prefix $0; fflush()}') 2>&1 & FRONTEND_PID=$! cd .. } -# Start Gradio Agent -start_agent() { - echo -e "\033[0;35m[Agent]\033[0m Starting Gradio agent on port $AGENT_PORT..." - echo -e "\033[0;35m[Agent]\033[0m LLM config will be fetched from FastAPI /api/agent/llm-config at startup." - echo -e "\033[0;35m[Agent]\033[0m Configure LLM providers in Admin → LLM Settings." - cd agent - if [ -f ".venv/bin/activate" ]; then - source .venv/bin/activate - elif [ -f "../backend/.venv/bin/activate" ]; then - source "../backend/.venv/bin/activate" - fi - # Install both editable packages before using the module entry point. Tests may put - # agent/src on sys.path, but production must import the installed package graph. - if ! python3 -c "import ss_tools.agent, ss_tools.shared" 2>/dev/null; then - pip install -e ../shared 2>/dev/null && echo -e "\033[0;35m[Agent]\033[0m Installed ss-tools-shared" - pip install -e . 2>/dev/null && echo -e "\033[0;35m[Agent]\033[0m Installed ss-tools-agent" - fi - # backend/.env was safely loaded by load_dotenv before services start. - export SERVICE_JWT="$RUN_SERVICE_JWT" - export SERVICE_JWT - export FASTAPI_URL="http://127.0.0.1:${BACKEND_PORT}" - local _color=$'\033[0;35m[Agent]\033[0m ' - export GRADIO_SERVER_PORT="$AGENT_PORT" - export GRADIO_ALLOW_PORT_FALLBACK="${GRADIO_ALLOW_PORT_FALLBACK:-false}" - export AGENT_CONFIRM_TOOLS="${AGENT_CONFIRM_TOOLS:-true}" - if [ "$DEV_MODE" = "true" ]; then - echo -e "\033[0;35m[Agent]\033[0m Hot-reload enabled via watchfiles (watching ss_tools/agent/)" - PYTHONUNBUFFERED=1 python3 -m watchfiles --filter python \ - "python -m ss_tools.agent.run" src/ss_tools/agent \ - > >(awk -v prefix="$_color " '{print prefix $0; fflush()}') 2>&1 & - else - PYTHONUNBUFFERED=1 python3 -m ss_tools.agent.run \ - > >(awk -v prefix="$_color " '{print prefix $0; fflush()}') 2>&1 & - fi - AGENT_PID=$! - cd .. -} - start_backend start_frontend -start_agent echo "Services are running. Press Ctrl+C to stop." wait diff --git a/run_clean_tui.sh b/run_clean_tui.sh index 7b22d0aea..b62a16883 100755 --- a/run_clean_tui.sh +++ b/run_clean_tui.sh @@ -1,5 +1,5 @@ #!/bin/bash -# [DEF:Tooling.RunCleanTui:Script] +# #region Tooling.RunCleanTui [C:1] [TYPE Module] # Helper script to launch the Enterprise Clean Release TUI set -e @@ -27,4 +27,4 @@ fi # Run the TUI ./backend/.venv/bin/python3 -m backend.src.scripts.clean_release_tui -# [/DEF:Tooling.RunCleanTui:Script] +# #endregion Tooling.RunCleanTui diff --git a/scripts/pretty_cot.py b/scripts/pretty_cot.py index 7d662c53c..819a142eb 100755 --- a/scripts/pretty_cot.py +++ b/scripts/pretty_cot.py @@ -2,7 +2,7 @@ # #region Scripts.PrettyCoT [C:2] [TYPE Script] [SEMANTICS logging,pretty,agent,cli] # @BRIEF Agent-first pretty printer and trace visualizer for Molecular CoT JSON logs. # @RELATION IMPLEMENTS -> [molecular-cot-logging:CLI Reader] -# @USAGE +# @NOTE # python scripts/pretty_cot.py backend/logs/app.log --last 80 # tail -f logs/app.log | python scripts/pretty_cot.py # python scripts/pretty_cot.py backend/logs/app.log --follow diff --git a/shared/src/ss_tools/shared/cot_logger.py b/shared/src/ss_tools/shared/cot_logger.py index 67b554bf2..c9a6acef7 100644 --- a/shared/src/ss_tools/shared/cot_logger.py +++ b/shared/src/ss_tools/shared/cot_logger.py @@ -214,7 +214,7 @@ def derive_src( # #region Shared.is_routine_infra [C:1] [TYPE Function] [SEMANTICS suppression,filter,predicate] # @ingroup Shared # @BRIEF Check if an intent string matches known infrastructure noise. -# @USAGE Used by logger.reason/reflect in both shared/logger.py and backend/logger.py. +# @NOTE Used by logger.reason/reflect in both shared/logger.py and backend/logger.py. def is_routine_infra(intent: str) -> bool: """Return True if *intent* matches a known routine-infrastructure phrase. @@ -229,7 +229,7 @@ def is_routine_infra(intent: str) -> bool: # #region Shared.set_routine_suppression [C:1] [TYPE Function] [SEMANTICS suppression,config,override] # @ingroup Shared # @BRIEF Configure suppression from backend's LoggingConfig (called by configure_logger). -# @USAGE set_routine_suppression(enabled=config.hide_routine_infra) +# @NOTE set_routine_suppression(enabled=config.hide_routine_infra) def set_routine_suppression( enabled: bool | None = None, phrases: tuple[str, ...] | None = None, @@ -424,7 +424,7 @@ def log( # REFLECT/EXPLORE on exit with elapsed_ms timing. # @INVARIANT Always emits exactly one entry marker and one exit/explore marker. # @RELATION DEPENDS_ON -> [push_span, pop_span, log] -# @USAGE +# @NOTE # @cot_span("REASON", "High level description") # async def my_important_operation(...): # ... diff --git a/specs/001-unify-frontend-style/contracts/modules.md b/specs/001-unify-frontend-style/contracts/modules.md index 3667db501..291a1d889 100644 --- a/specs/001-unify-frontend-style/contracts/modules.md +++ b/specs/001-unify-frontend-style/contracts/modules.md @@ -1,12 +1,11 @@ # Module Contracts: Frontend Style Unification -# [DEF:Spec.UnifyFrontendStyle.FrontendStyleSystem:Module] -# @TIER: CRITICAL +## @{ Spec.UnifyFrontendStyle.FrontendStyleSystem [C:5] [TYPE Module] # @BRIEF: Define and enforce unified visual primitives and page-shell rules across targeted frontend routes. -# @RELATION: DEPENDS_ON -> [DEF:Std:UI_Svelte:Standard] -# @RELATION: DEPENDS_ON -> [DEF:Std:Semantics:Standard] -# @RELATION: BINDS_TO -> [DEF:StyleTokenGroup:Block] -# @RELATION: BINDS_TO -> [DEF:UIPatternRule:Block] +# @RELATION: DEPENDS_ON -> [Std:UI_Svelte] +# @RELATION: DEPENDS_ON -> [Std:Semantics] +# @RELATION: BINDS_TO -> [StyleTokenGroup] +# @RELATION: BINDS_TO -> [UIPatternRule] # @PRE: Target routes/components for unification are identified and included in scope. # @PRE: Existing behavior-critical user flows remain available for validation. # @POST: Shared visual primitives and shell patterns are applied consistently in targeted scope. @@ -19,14 +18,13 @@ --- -# [/DEF:Spec.UnifyFrontendStyle.FrontendStyleSystem:Module] +## @} Spec.UnifyFrontendStyle.FrontendStyleSystem ## -# [DEF:Spec.UnifyFrontendStyle.RouteShellContract:Component] -# @TIER: CRITICAL +## @{ Spec.UnifyFrontendStyle.RouteShellContract [C:5] [TYPE Component] # @BRIEF: Standardize route shell structure for primary pages (dashboards, tasks, reports, settings). -# @RELATION: DEPENDS_ON -> [DEF:FrontendStyleSystem:Module] +# @RELATION: DEPENDS_ON -> [FrontendStyleSystem] # @PRE: Route provides title context and action area metadata. # @POST: Route renders canonical shell order: context/breadcrumbs, title block, action region, content container. # @UX_STATE: Default -> Primary action location is discoverable quickly and consistently. @@ -35,14 +33,13 @@ --- -# [/DEF:Spec.UnifyFrontendStyle.RouteShellContract:Component] +## @} Spec.UnifyFrontendStyle.RouteShellContract ## -# [DEF:Spec.UnifyFrontendStyle.StateFeedbackContract:Component] -# @TIER: CRITICAL +## @{ Spec.UnifyFrontendStyle.StateFeedbackContract [C:5] [TYPE Component] # @BRIEF: Normalize loading/empty/error/success feedback rendering and wording across modules. -# @RELATION: DEPENDS_ON -> [DEF:StatePresentationPattern:Block] +# @RELATION: DEPENDS_ON -> [StatePresentationPattern] # @PRE: Module can expose current state category (loading/empty/error/success). # @POST: State-specific UI uses canonical placement, tone, and recovery behavior. # @UX_STATE: Loading -> Consistent indicator style and placement with stable layout rhythm. @@ -55,14 +52,13 @@ --- -# [/DEF:Spec.UnifyFrontendStyle.StateFeedbackContract:Component] +## @} Spec.UnifyFrontendStyle.StateFeedbackContract ## -# [DEF:Spec.UnifyFrontendStyle.TerminologyConsistencyContract:Module] -# @TIER: STANDARD +## @{ Spec.UnifyFrontendStyle.TerminologyConsistencyContract [C:3] [TYPE Module] # @BRIEF: Keep user-facing wording consistent across page shells and state blocks. -# @RELATION: DEPENDS_ON -> [DEF:Std:Constitution:Standard] +# @RELATION: DEPENDS_ON -> [Std:Constitution] # @PRE: Canonical term list for targeted flows is defined. # @POST: Targeted modules avoid mixed synonyms for the same concept. # @UX_STATE: Default -> UI labels and status texts remain concise and confidence-building. @@ -72,7 +68,7 @@ ## Contract Usage Simulation (Key Scenario) -# [/DEF:Spec.UnifyFrontendStyle.TerminologyConsistencyContract:Module] +## @} Spec.UnifyFrontendStyle.TerminologyConsistencyContract **Scenario**: User navigates from dashboards to reports and encounters a failed data load. diff --git a/specs/010-refactor-cli-to-web/spec.md b/specs/010-refactor-cli-to-web/spec.md index 5a1089969..c7ff65ede 100644 --- a/specs/010-refactor-cli-to-web/spec.md +++ b/specs/010-refactor-cli-to-web/spec.md @@ -1,8 +1,8 @@ -# [DEF:Spec.RefactorCliToWeb.Spec:010-refactor-cli-to-web] -# @TITLE: Refactor CLI Scripts to Web Application +## @{ Spec.RefactorCliToWeb.Spec [C:3] [TYPE Module] +# Title: Refactor CLI Scripts to Web Application # @STATUS: DRAFT -# @AUTHOR: Kilo Code -# @CREATED: 2026-01-07 +# Author: Kilo Code +# Created: 2026-01-07 ## Clarifications @@ -81,4 +81,4 @@ Integrate the functionality of the standalone CLI tools directly into the Web Ap * The existing Web Application plugin architecture supports the addition of these new tools. * The existing logging and task management systems in the Web Application can handle the output from these tools. -# [/DEF:Spec.RefactorCliToWeb.Spec:010-refactor-cli-to-web] +## @} Spec.RefactorCliToWeb.Spec diff --git a/specs/019-superset-ux-redesign/contracts/api.md b/specs/019-superset-ux-redesign/contracts/api.md index ac2ed1045..754271473 100644 --- a/specs/019-superset-ux-redesign/contracts/api.md +++ b/specs/019-superset-ux-redesign/contracts/api.md @@ -178,8 +178,7 @@ The Task Drawer subscribes to existing WebSocket events: ### SidebarStore (frontend/src/lib/stores/sidebar.js) ```javascript -// [DEF:Spec.SupersetUxRedesign.SidebarStore:Store] -// @TIER: STANDARD +## @{ Spec.SupersetUxRedesign.SidebarStore [C:3] [TYPE Component] // @BRIEF: Manage sidebar visibility and navigation state // @LAYER: UI // @INVARIANT: isExpanded state is always synced with localStorage @@ -196,14 +195,13 @@ export const sidebarStore = writable({ export function toggleSidebar() { /* ... */ } export function setActiveItem(path) { /* ... */ } -// [/DEF:Spec.SupersetUxRedesign.SidebarStore:Store] +## @} Spec.SupersetUxRedesign.SidebarStore ``` ### TaskDrawerStore (frontend/src/lib/stores/taskDrawer.js) ```javascript -// [DEF:Spec.SupersetUxRedesign.TaskDrawerStore:Store] -// @TIER: CRITICAL +## @{ Spec.SupersetUxRedesign.TaskDrawerStore [C:5] [TYPE Component] // @BRIEF: Manage Task Drawer visibility and resource-to-task mapping // @LAYER: UI // @INVARIANT: resourceTaskMap always reflects current task associations @@ -221,14 +219,13 @@ export const taskDrawerStore = writable({ export function openDrawerForTask(taskId) { /* ... */ } export function closeDrawer() { /* ... */ } export function updateResourceTask(resourceId, taskId, status) { /* ... */ } -// [/DEF:Spec.SupersetUxRedesign.TaskDrawerStore:Store] +## @} Spec.SupersetUxRedesign.TaskDrawerStore ``` ### ActivityStore (frontend/src/lib/stores/activity.js) ```javascript -// [DEF:Spec.SupersetUxRedesign.ActivityStore:Store] -// @TIER: STANDARD +## @{ Spec.SupersetUxRedesign.ActivityStore [C:3] [TYPE Component] // @BRIEF: Track active task count for navbar indicator // @LAYER: UI // @RELATION: DEPENDS_ON -> WebSocket connection @@ -238,5 +235,5 @@ export const activityStore = derived(taskDrawerStore, ($drawer) => { .filter(t => t.status === 'RUNNING').length; return { activeCount }; }); -// [/DEF:Spec.SupersetUxRedesign.ActivityStore:Store] +## @} Spec.SupersetUxRedesign.ActivityStore ``` diff --git a/specs/019-superset-ux-redesign/contracts/modules.md b/specs/019-superset-ux-redesign/contracts/modules.md index 7dc21a2d5..b890994b8 100644 --- a/specs/019-superset-ux-redesign/contracts/modules.md +++ b/specs/019-superset-ux-redesign/contracts/modules.md @@ -17,8 +17,7 @@ This document defines module-level contracts following the Semantic Protocol. Ea ### 1. SidebarStore ```javascript -// [DEF:Spec.SupersetUxRedesign.SidebarStore:Store] -// @TIER: STANDARD +## @{ Spec.SupersetUxRedesign.SidebarStore [C:3] [TYPE Component] // @SEMANTICS: navigation, state-management, persistence // @BRIEF: Manage sidebar visibility, active navigation state, and mobile overlay behavior // @LAYER: UI @@ -53,7 +52,7 @@ export function setActiveCategory(category) { /* ... */ } export function setActiveItem(path) { /* ... */ } export function openMobileSidebar() { /* ... */ } export function closeMobileSidebar() { /* ... */ } -// [/DEF:Spec.SupersetUxRedesign.SidebarStore:Store] +## @} Spec.SupersetUxRedesign.SidebarStore ``` --- @@ -61,8 +60,7 @@ export function closeMobileSidebar() { /* ... */ } ### 2. TaskDrawerStore ```javascript -// [DEF:Spec.SupersetUxRedesign.TaskDrawerStore:Store] -// @TIER: CRITICAL +## @{ Spec.SupersetUxRedesign.TaskDrawerStore [C:5] [TYPE Component] // @SEMANTICS: task-management, resource-mapping, real-time, drawer-state // @BRIEF: Manage Task Drawer visibility, active task tracking, and resource-to-task associations // @LAYER: UI @@ -105,7 +103,7 @@ export function openDrawerForTask(taskId) { /* ... */ } export function closeDrawer() { /* ... */ } export function updateResourceTask(resourceId, taskId, status) { /* ... */ } export function clearCompletedTasks() { /* ... */ } -// [/DEF:Spec.SupersetUxRedesign.TaskDrawerStore:Store] +## @} Spec.SupersetUxRedesign.TaskDrawerStore ``` --- @@ -113,8 +111,7 @@ export function clearCompletedTasks() { /* ... */ } ### 3. ActivityStore ```javascript -// [DEF:Spec.SupersetUxRedesign.ActivityStore:Store] -// @TIER: STANDARD +## @{ Spec.SupersetUxRedesign.ActivityStore [C:3] [TYPE Component] // @SEMANTICS: activity-indicator, derived-state, task-count // @BRIEF: Provide reactive count of active tasks for the navbar Activity indicator // @LAYER: UI @@ -143,7 +140,7 @@ export const activityStore = derived( return { activeCount, recentTasks }; } ); -// [/DEF:Spec.SupersetUxRedesign.ActivityStore:Store] +## @} Spec.SupersetUxRedesign.ActivityStore ``` --- @@ -151,8 +148,7 @@ export const activityStore = derived( ### 4. Sidebar Component ```svelte - - +## @{ Spec.SupersetUxRedesign.Sidebar [C:5] [TYPE Component] @@ -187,7 +183,7 @@ export const activityStore = derived( { id: 'admin', label: 'ADMIN', items: [{ path: '/users', label: 'Users' }, { path: '/settings', label: 'Settings' }], adminOnly: true } ]; - +## @} Spec.SupersetUxRedesign.Sidebar ``` --- @@ -195,8 +191,7 @@ export const activityStore = derived( ### 5. TopNavbar Component ```svelte - - +## @{ Spec.SupersetUxRedesign.TopNavbar [C:5] [TYPE Component] @@ -225,7 +220,7 @@ export const activityStore = derived( export let logoText = 'Superset Tools'; export let searchPlaceholder = 'Search...'; - +## @} Spec.SupersetUxRedesign.TopNavbar ``` --- @@ -233,8 +228,7 @@ export const activityStore = derived( ### 6. TaskDrawer Component ```svelte - - +## @{ Spec.SupersetUxRedesign.TaskDrawer [C:5] [TYPE Component] @@ -270,7 +264,7 @@ export const activityStore = derived( export let width = 480; // px export let closeOnOutsideClick = false; - +## @} Spec.SupersetUxRedesign.TaskDrawer ``` --- @@ -278,8 +272,7 @@ export const activityStore = derived( ### 7. DashboardHub Component ```svelte - - +## @{ Spec.SupersetUxRedesign.DashboardHub [C:5] [TYPE Component] @@ -323,7 +316,7 @@ export const activityStore = derived( let searchQuery = ''; let environmentId = null; - +## @} Spec.SupersetUxRedesign.DashboardHub ``` --- @@ -331,8 +324,7 @@ export const activityStore = derived( ### 8. DatasetHub Component ```svelte - - +## @{ Spec.SupersetUxRedesign.DatasetHub [C:5] [TYPE Component] @@ -374,7 +366,7 @@ export const activityStore = derived( let searchQuery = ''; let environmentId = null; - +## @} Spec.SupersetUxRedesign.DatasetHub ``` --- @@ -382,8 +374,7 @@ export const activityStore = derived( ### 9. Breadcrumbs Component ```svelte - - +## @{ Spec.SupersetUxRedesign.Breadcrumbs [C:3] [TYPE Component] @@ -406,7 +397,7 @@ export const activityStore = derived( export let items = []; // [{ label: string, path: string | null }] export let maxVisible = 3; - +## @} Spec.SupersetUxRedesign.Breadcrumbs ``` --- @@ -416,8 +407,7 @@ export const activityStore = derived( ### 10. Dashboards API ```python -# [DEF:Spec.SupersetUxRedesign.DashboardsAPI:Module] -# @TIER: CRITICAL +## @{ Spec.SupersetUxRedesign.DashboardsAPI [C:5] [TYPE Module] # @SEMANTICS: rest-api, resource-fetching, git-integration # @BRIEF: API endpoints for Dashboard Hub - list dashboards with metadata # @LAYER: Domain @@ -444,7 +434,7 @@ export const activityStore = derived( # Endpoint: POST /api/dashboards/backup # Body: { env_id, dashboard_ids, schedule (optional cron) } # Response: { task_id } -# [/DEF:Spec.SupersetUxRedesign.DashboardsAPI:Module] +## @} Spec.SupersetUxRedesign.DashboardsAPI ``` --- @@ -452,8 +442,7 @@ export const activityStore = derived( ### 11. Datasets API ```python -# [DEF:Spec.SupersetUxRedesign.DatasetsAPI:Module] -# @TIER: CRITICAL +## @{ Spec.SupersetUxRedesign.DatasetsAPI [C:5] [TYPE Module] # @SEMANTICS: rest-api, dataset-metadata, column-mapping # @BRIEF: API endpoints for Dataset Hub - list datasets with mapping info # @LAYER: Domain @@ -481,7 +470,7 @@ export const activityStore = derived( # Endpoint: POST /api/datasets/generate-docs # Body: { env_id, dataset_ids, llm_provider, options } # Response: { task_id } -# [/DEF:Spec.SupersetUxRedesign.DatasetsAPI:Module] +## @} Spec.SupersetUxRedesign.DatasetsAPI ``` --- @@ -489,8 +478,7 @@ export const activityStore = derived( ### 12. Activity API ```python -# [DEF:Spec.SupersetUxRedesign.ActivityAPI:Module] -# @TIER: STANDARD +## @{ Spec.SupersetUxRedesign.ActivityAPI [C:3] [TYPE Module] # @SEMANTICS: rest-api, activity-summary, task-metrics # @BRIEF: Provide activity summary for navbar indicator # @LAYER: Domain @@ -505,7 +493,7 @@ export const activityStore = derived( # Endpoint: GET /api/activity # Response: { active_count: number, recent_tasks: [...] } -# [/DEF:Spec.SupersetUxRedesign.ActivityAPI:Module] +## @} Spec.SupersetUxRedesign.ActivityAPI ``` --- @@ -513,8 +501,7 @@ export const activityStore = derived( ### 13. ResourceService ```python -# [DEF:Spec.SupersetUxRedesign.ResourceService:Class] -# @TIER: STANDARD +## @{ Spec.SupersetUxRedesign.ResourceService [C:3] [TYPE Class] # @SEMANTICS: service-layer, shared-logic, resource-fetching # @BRIEF: Shared logic for fetching resources from Superset with caching # @LAYER: Domain @@ -534,7 +521,7 @@ class ResourceService: async def fetch_datasets(env_id: str, search: str = None) -> list[Dataset]: ... async def get_git_status(env_id: str, resource_id: str) -> GitStatus: ... async def get_last_task(resource_type: str, resource_id: str) -> TaskSummary: ... -# [/DEF:Spec.SupersetUxRedesign.ResourceService:Class] +## @} Spec.SupersetUxRedesign.ResourceService ``` --- diff --git a/specs/019-superset-ux-redesign/plan.md b/specs/019-superset-ux-redesign/plan.md index 357c48b93..b0bf31878 100644 --- a/specs/019-superset-ux-redesign/plan.md +++ b/specs/019-superset-ux-redesign/plan.md @@ -105,16 +105,16 @@ All implementation MUST follow the Design-by-Contract specifications in [`contra | Component/Module | Contract Location | TIER | |------------------|-------------------|------| -| SidebarStore | [DEF:SidebarStore:Store](./contracts/modules.md#1-sidebarstore) | STANDARD | -| TaskDrawerStore | [DEF:TaskDrawerStore:Store](./contracts/modules.md#2-taskdrawerstore) | CRITICAL | -| ActivityStore | [DEF:ActivityStore:Store](./contracts/modules.md#3-activitystore) | STANDARD | -| Sidebar | [DEF:Sidebar:Component](./contracts/modules.md#4-sidebar-component) | CRITICAL | -| TopNavbar | [DEF:TopNavbar:Component](./contracts/modules.md#5-topnavbar-component) | CRITICAL | -| TaskDrawer | [DEF:TaskDrawer:Component](./contracts/modules.md#6-taskdrawer-component) | CRITICAL | -| DashboardHub | [DEF:DashboardHub:Component](./contracts/modules.md#7-dashboardhub-component) | CRITICAL | -| DatasetHub | [DEF:DatasetHub:Component](./contracts/modules.md#8-datasethub-component) | CRITICAL | -| DashboardsAPI | [DEF:DashboardsAPI:Module](./contracts/modules.md#10-dashboards-api) | CRITICAL | -| DatasetsAPI | [DEF:DatasetsAPI:Module](./contracts/modules.md#11-datasets-api) | CRITICAL | +| SidebarStore | [SidebarStore:Store](./contracts/modules.md#1-sidebarstore) | STANDARD | +| TaskDrawerStore | [TaskDrawerStore:Store](./contracts/modules.md#2-taskdrawerstore) | CRITICAL | +| ActivityStore | [ActivityStore:Store](./contracts/modules.md#3-activitystore) | STANDARD | +| Sidebar | [Sidebar:Component](./contracts/modules.md#4-sidebar-component) | CRITICAL | +| TopNavbar | [TopNavbar:Component](./contracts/modules.md#5-topnavbar-component) | CRITICAL | +| TaskDrawer | [TaskDrawer:Component](./contracts/modules.md#6-taskdrawer-component) | CRITICAL | +| DashboardHub | [DashboardHub:Component](./contracts/modules.md#7-dashboardhub-component) | CRITICAL | +| DatasetHub | [DatasetHub:Component](./contracts/modules.md#8-datasethub-component) | CRITICAL | +| DashboardsAPI | [DashboardsAPI:Module](./contracts/modules.md#10-dashboards-api) | CRITICAL | +| DatasetsAPI | [DatasetsAPI:Module](./contracts/modules.md#11-datasets-api) | CRITICAL | ### UX State Contract Mapping diff --git a/specs/019-superset-ux-redesign/tasks.md b/specs/019-superset-ux-redesign/tasks.md index 2cc42268a..03a9889c0 100644 --- a/specs/019-superset-ux-redesign/tasks.md +++ b/specs/019-superset-ux-redesign/tasks.md @@ -24,18 +24,18 @@ All implementation tasks MUST follow the Design-by-Contract specifications: | Component | Contract | TIER | |-----------|----------|------| -| `sidebar.js` | [DEF:SidebarStore:Store](./contracts/modules.md#1-sidebarstore) | STANDARD | -| `taskDrawer.js` | [DEF:TaskDrawerStore:Store](./contracts/modules.md#2-taskdrawerstore) | CRITICAL | -| `activity.js` | [DEF:ActivityStore:Store](./contracts/modules.md#3-activitystore) | STANDARD | -| `Sidebar.svelte` | [DEF:Sidebar:Component](./contracts/modules.md#4-sidebar-component) | CRITICAL | -| `TopNavbar.svelte` | [DEF:TopNavbar:Component](./contracts/modules.md#5-topnavbar-component) | CRITICAL | -| `TaskDrawer.svelte` | [DEF:TaskDrawer:Component](./contracts/modules.md#6-taskdrawer-component) | CRITICAL | -| `Breadcrumbs.svelte` | [DEF:Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component) | STANDARD | -| `DashboardHub` | [DEF:DashboardHub:Component](./contracts/modules.md#7-dashboardhub-component) | CRITICAL | -| `DatasetHub` | [DEF:DatasetHub:Component](./contracts/modules.md#8-datasethub-component) | CRITICAL | -| `dashboards.py` | [DEF:DashboardsAPI:Module](./contracts/modules.md#10-dashboards-api) | CRITICAL | -| `datasets.py` | [DEF:DatasetsAPI:Module](./contracts/modules.md#11-datasets-api) | CRITICAL | -| `resource_service.py` | [DEF:ResourceService:Class](./contracts/modules.md#13-resourceservice) | STANDARD | +| `sidebar.js` | [SidebarStore:Store](./contracts/modules.md#1-sidebarstore) | STANDARD | +| `taskDrawer.js` | [TaskDrawerStore:Store](./contracts/modules.md#2-taskdrawerstore) | CRITICAL | +| `activity.js` | [ActivityStore:Store](./contracts/modules.md#3-activitystore) | STANDARD | +| `Sidebar.svelte` | [Sidebar:Component](./contracts/modules.md#4-sidebar-component) | CRITICAL | +| `TopNavbar.svelte` | [TopNavbar:Component](./contracts/modules.md#5-topnavbar-component) | CRITICAL | +| `TaskDrawer.svelte` | [TaskDrawer:Component](./contracts/modules.md#6-taskdrawer-component) | CRITICAL | +| `Breadcrumbs.svelte` | [Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component) | STANDARD | +| `DashboardHub` | [DashboardHub:Component](./contracts/modules.md#7-dashboardhub-component) | CRITICAL | +| `DatasetHub` | [DatasetHub:Component](./contracts/modules.md#8-datasethub-component) | CRITICAL | +| `dashboards.py` | [DashboardsAPI:Module](./contracts/modules.md#10-dashboards-api) | CRITICAL | +| `datasets.py` | [DatasetsAPI:Module](./contracts/modules.md#11-datasets-api) | CRITICAL | +| `resource_service.py` | [ResourceService:Class](./contracts/modules.md#13-resourceservice) | STANDARD | --- @@ -50,11 +50,11 @@ All implementation tasks MUST follow the Design-by-Contract specifications: - [x] T001 Create `frontend/src/lib/components/layout/` directory for shared layout components - [x] T002 Create `frontend/src/lib/components/hubs/` directory for resource hub pages - [x] T003 [P] Create `frontend/src/lib/stores/sidebar.js` with persistentStore pattern for sidebar state - _Contract: [DEF:SidebarStore:Store](./contracts/modules.md#1-sidebarstore)_ + _Contract: [SidebarStore:Store](./contracts/modules.md#1-sidebarstore)_ - [x] T004 [P] Create `frontend/src/lib/stores/taskDrawer.js` with resourceTaskMap store - _Contract: [DEF:TaskDrawerStore:Store](./contracts/modules.md#2-taskdrawerstore) - CRITICAL: Must implement all @UX_STATE transitions_ + _Contract: [TaskDrawerStore:Store](./contracts/modules.md#2-taskdrawerstore) - CRITICAL: Must implement all @UX_STATE transitions_ - [x] T005 [P] Create `frontend/src/lib/stores/activity.js` as derived store from taskDrawer - _Contract: [DEF:ActivityStore:Store](./contracts/modules.md#3-activitystore)_ + _Contract: [ActivityStore:Store](./contracts/modules.md#3-activitystore)_ --- @@ -69,11 +69,11 @@ All implementation tasks MUST follow the Design-by-Contract specifications: - Components MUST follow `@PRE` conditions for props and `@POST` for event handling - [x] T006 Create `frontend/src/lib/components/layout/Sidebar.svelte` with categories: DASHBOARDS, DATASETS, STORAGE, ADMIN - _Contract: [DEF:Sidebar:Component](./contracts/modules.md#4-sidebar-component) - CRITICAL: Implement all @UX_STATE transitions (Expanded/Collapsed/Mobile)_ + _Contract: [Sidebar:Component](./contracts/modules.md#4-sidebar-component) - CRITICAL: Implement all @UX_STATE transitions (Expanded/Collapsed/Mobile)_ - [x] T007 Create `frontend/src/lib/components/layout/TopNavbar.svelte` with Logo, Search placeholder, Activity indicator, User menu - _Contract: [DEF:TopNavbar:Component](./contracts/modules.md#5-topnavbar-component) - CRITICAL: Activity badge must pulse on new tasks_ + _Contract: [TopNavbar:Component](./contracts/modules.md#5-topnavbar-component) - CRITICAL: Activity badge must pulse on new tasks_ - [x] T008 Create `frontend/src/lib/components/layout/Breadcrumbs.svelte` for page hierarchy navigation - _Contract: [DEF:Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component) - Handle truncation for >3 levels_ + _Contract: [Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component) - Handle truncation for >3 levels_ - [x] T009 Update `frontend/src/routes/+layout.svelte` to include Sidebar, TopNavbar, and main content area - [x] T010 Add i18n keys for navigation labels in `frontend/src/lib/i18n/translations/en.json` - [x] T011 Add i18n keys for navigation labels in `frontend/src/lib/i18n/translations/ru.json` @@ -110,11 +110,11 @@ All implementation tasks MUST follow the Design-by-Contract specifications: ### Implementation for User Story 2 **Contract Requirements**: -- TaskDrawer MUST implement all `@UX_STATE` transitions from [DEF:TaskDrawerStore:Store](./contracts/modules.md#2-taskdrawerstore) +- TaskDrawer MUST implement all `@UX_STATE` transitions from [TaskDrawerStore:Store](./contracts/modules.md#2-taskdrawerstore) - MUST handle `@UX_RECOVERY` for WebSocket disconnections - [x] T018 [US2] Create `frontend/src/lib/components/layout/TaskDrawer.svelte` as slide-out panel from right - _Contract: [DEF:TaskDrawer:Component](./contracts/modules.md#6-taskdrawer-component) - CRITICAL: Implement Closed → Open-Loading → Open-Streaming → Open-InputRequired states_ + _Contract: [TaskDrawer:Component](./contracts/modules.md#6-taskdrawer-component) - CRITICAL: Implement Closed → Open-Loading → Open-Streaming → Open-InputRequired states_ - [x] T019 [US2] Integrate existing `TaskLogViewer` component inside Task Drawer - [x] T020 [US2] Implement Activity indicator badge in TopNavbar showing `activeCount` from store - [x] T021 [US2] Connect Task Drawer to WebSocket for real-time log streaming @@ -157,13 +157,13 @@ All implementation tasks MUST follow the Design-by-Contract specifications: ### Backend for User Story 3 **Contract Requirements**: -- All endpoints MUST follow `@PRE` and `@POST` conditions from [DEF:DashboardsAPI:Module](./contracts/modules.md#10-dashboards-api) +- All endpoints MUST follow `@PRE` and `@POST` conditions from [DashboardsAPI:Module](./contracts/modules.md#10-dashboards-api) - MUST use `ConfigManager` via dependency injection (Constitution Principle II) - [x] T031 [P] [US3] Create `backend/src/api/routes/dashboards.py` with GET /api/dashboards endpoint - _Contract: [DEF:DashboardsAPI:Module](./contracts/modules.md#10-dashboards-api) - CRITICAL_ + _Contract: [DashboardsAPI:Module](./contracts/modules.md#10-dashboards-api) - CRITICAL_ - [x] T032 [P] [US3] Create `backend/src/services/resource_service.py` for shared resource fetching logic - _Contract: [DEF:ResourceService:Class](./contracts/modules.md#13-resourceservice)_ + _Contract: [ResourceService:Class](./contracts/modules.md#13-resourceservice)_ - [x] T033 [US3] Implement dashboard list fetching with Git status and last task status - [x] T034 [US3] Add pagination support to GET /api/dashboards endpoint (page, page_size parameters) _Contract: @POST: Response includes pagination metadata_ @@ -177,11 +177,11 @@ All implementation tasks MUST follow the Design-by-Contract specifications: ### Frontend for User Story 3 **Contract Requirements**: -- MUST implement all `@UX_STATE` transitions from [DEF:DashboardHub:Component](./contracts/modules.md#7-dashboardhub-component) +- MUST implement all `@UX_STATE` transitions from [DashboardHub:Component](./contracts/modules.md#7-dashboardhub-component) - MUST preserve selection across pagination (`@INVARIANT: Selected dashboards persist across pagination`) - [x] T038 [US3] Create `frontend/src/routes/dashboards/+page.svelte` as Dashboard Hub - _Contract: [DEF:DashboardHub:Component](./contracts/modules.md#7-dashboardhub-component) - CRITICAL_ + _Contract: [DashboardHub:Component](./contracts/modules.md#7-dashboardhub-component) - CRITICAL_ - [x] T039 [US3] Implement environment selector dropdown at top of Dashboard Hub - [x] T040 [US3] Create dashboard grid with checkboxes, columns: Title, Slug, Git Status, Last Task, Actions _Contract: @UX_STATE: Idle-Grid, @UX_FEEDBACK: Git status color-coded icons_ @@ -218,11 +218,11 @@ All implementation tasks MUST follow the Design-by-Contract specifications: ### Backend for User Story 4 **Contract Requirements**: -- All endpoints MUST follow `@PRE` and `@POST` conditions from [DEF:DatasetsAPI:Module](./contracts/modules.md#11-datasets-api) +- All endpoints MUST follow `@PRE` and `@POST` conditions from [DatasetsAPI:Module](./contracts/modules.md#11-datasets-api) - MUST calculate `mapped_fields` as (mapped_columns / total_columns) * 100 - [x] T052 [P] [US4] Create `backend/src/api/routes/datasets.py` with GET /api/datasets endpoint - _Contract: [DEF:DatasetsAPI:Module](./contracts/modules.md#11-datasets-api) - CRITICAL_ + _Contract: [DatasetsAPI:Module](./contracts/modules.md#11-datasets-api) - CRITICAL_ - [x] T053 [US4] Implement dataset list fetching with mapped fields count and SQL table extraction _Contract: @INVARIANT: Mapped % is calculated as (mapped_columns / total_columns) * 100_ - [x] T054 [US4] Add pagination support to GET /api/datasets endpoint (page, page_size parameters) @@ -235,11 +235,11 @@ All implementation tasks MUST follow the Design-by-Contract specifications: ### Frontend for User Story 4 **Contract Requirements**: -- MUST implement all `@UX_STATE` transitions from [DEF:DatasetHub:Component](./contracts/modules.md#8-datasethub-component) +- MUST implement all `@UX_STATE` transitions from [DatasetHub:Component](./contracts/modules.md#8-datasethub-component) - MUST display Mapped % with progress bar as specified in `@UX_FEEDBACK` - [x] T058 [US4] Create `frontend/src/routes/datasets/+page.svelte` as Dataset Hub - _Contract: [DEF:DatasetHub:Component](./contracts/modules.md#8-datasethub-component) - CRITICAL_ + _Contract: [DatasetHub:Component](./contracts/modules.md#8-datasethub-component) - CRITICAL_ - [x] T059 [US4] Implement dataset grid with checkboxes, columns: Name, Database, Schema, Tables, Columns, Mapped %, Updated By, Actions _Contract: @UX_FEEDBACK: Mapped % column shows progress bar + percentage text_ - [x] T060 [US4] Implement "Select All" and "Select Visible" buttons in toolbar @@ -292,11 +292,11 @@ All implementation tasks MUST follow the Design-by-Contract specifications: **Purpose**: Improvements that affect multiple user stories **Contract Requirements**: -- Breadcrumbs MUST follow [DEF:Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component) specification +- Breadcrumbs MUST follow [Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component) specification - Error handling MUST implement `@UX_RECOVERY` patterns from component contracts - [x] T057 [P] Add breadcrumb navigation to all new pages - _Contract: [DEF:Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component)_ + _Contract: [Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component)_ - [x] T058 [P] Implement breadcrumb truncation for deep paths (>3 levels) _Contract: @POST: Deep paths (>3 levels) truncate middle segments_ - [x] T059 Remove old card-based dashboard grid if no longer needed @@ -318,7 +318,7 @@ All implementation tasks MUST follow the Design-by-Contract specifications: ### Critical Violations #### V001: Missing Breadcrumbs in Layout -- **Contract**: [DEF:Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component) - @UX_STATE: Idle +- **Contract**: [Breadcrumbs:Component](./contracts/modules.md#9-breadcrumbs-component) - @UX_STATE: Idle - **Expected**: Breadcrumbs visible below TopNavbar on all pages - **Actual**: Breadcrumbs component exists but is NOT rendered in +layout.svelte - **Evidence**: `frontend/src/routes/+layout.svelte` imports Breadcrumbs but doesn't use it in template @@ -327,7 +327,7 @@ All implementation tasks MUST follow the Design-by-Contract specifications: - **Status**: ✅ FIXED - Breadcrumbs now rendered in layout #### V002: TopNavbar Missing Sidebar Responsive Classes -- **Contract**: [DEF:TopNavbar:Component](./contracts/modules.md#5-topnavbar-component) - @INVARIANT: Height is fixed at 64px +- **Contract**: [TopNavbar:Component](./contracts/modules.md#5-topnavbar-component) - @INVARIANT: Height is fixed at 64px - **Expected**: TopNavbar should have `with-sidebar` or `with-collapsed-sidebar` class based on sidebar state - **Actual**: TopNavbar always uses `mobile` class regardless of screen size - **Evidence**: `frontend/src/lib/components/layout/TopNavbar.svelte` line 185: `