fix(agent-chat): streaming state leak, document parser magic bytes, HITL flow

### Bugfixes — Agent Chat 'Думаю' State Leak
- fix(agent-chat): loadHistory() now resets streamingState/idle + cancels stale
  submission — prevents 'Думаю' state leak across conversation switches
- fix(agent-chat): onDisconnected/onDisconnectedPermanent cascade to
  streamingState — prevents permanent hang on connection loss during stream
- fix(agent-chat):  guard on isLoadingHistory — prevents false commit
  of 'agent unavailable' fallback when switching conversations
- fix(agent-chat): remove race in _sendNow empty-response check vs Svelte
   microtask (duplicate logic removed,  handles correctly)
- fix(stream-processor): confirm_resolved now appends msg.text to partialText
  instead of dropping it

### Bugfixes — Backend PDF Upload
- fix(document-parser): _detect_format_by_magic() — reads file header magic
  bytes as fallback when Gradio loses filename
- fix(document-parser): improved name extraction — tries orig_name, path stem
- fix(document-parser): @RELATION AgentChatTypes -> AgentChat.Types

### HITL Flow & Agent Chat Improvements
- feat(agent): HITL resume confirm/deny with userId/userJwt/envId propagation
- feat(agent): confirm_required metadata fallback via aget_state() after
  'Event loop is closed' error during interrupt
- feat(agent): interrupt_before re-enabled via AGENT_CONFIRM_TOOLS env var
- feat(frontend): debug panel with connection/stream state monitoring
- feat(frontend): AgentChatModel constructor options + onBeforeSend callback
- feat(frontend): crypto.randomUUID() for local conversation ID on first send

### Backend Agent Refactoring
- refactor(agent): langgraph_setup — monkey-patch for PydanticSerializationError
- refactor(agent): tools.py — dual identity headers, expanded tool set
- refactor(agent): run.py — _find_free_port, Gradio server port fallback
- refactor(agent): app.py — file size validation, message truncation, HITL path

### Frontend
- feat(dashboard-hub): DashboardHubModel with filters, pagination, git actions
- feat(ui): DateRangeFilter component
- feat(i18n): new dashboard keys; cache tooltips fix
- fix(i18n): full run tooltips — cache is NOT ignored

### Semantic Protocol
- chore(agents): update all agents with canonical format
- chore(skills): sync semantics-core, semantics-contracts, molecular-cot-logging

### Housekeeping
- chore: remove stale semantic reports (10 files, Jan 2026)
- chore: update 033-gradio-agent-chat specs, contracts, UX, tasks, tests
- chore: add .agents/ directory (mirrors .opencode/ agent layouts)
- chore: update run.sh with DEV_MODE, port management
This commit is contained in:
2026-06-29 17:15:25 +03:00
parent 4fda63a8da
commit 12678c637b
115 changed files with 8948 additions and 1763 deletions

View File

@@ -1,5 +1,5 @@
---
description: Perform a read-only consistency analysis across spec.md, plan.md, tasks.md, contracts/modules.md, and ADR sources for the active superset-tools feature. Covers UX Contract Traceability, ATTN Rules Compliance, and decision-memory continuity.
description: Perform a read-only consistency analysis across spec.md, plan.md, tasks.md, contracts/modules.md, and ADR sources for the active superset-tools feature. Covers UX Contract Traceability, ATTN Rules Compliance, decision-memory continuity, and component reuse analysis.
---
## User Input
@@ -16,7 +16,7 @@ MANDATORY USE `skill({name="semantics-core"})`, `skill({name="semantics-contract
## Goal
Identify inconsistencies, ambiguities, coverage gaps, decision-memory drift, UX contract gaps, and ATTN-rules violations across the feature artifacts **before implementation proceeds**. This command MUST run only after `/speckit.tasks` has produced a complete `tasks.md`.
Identify inconsistencies, ambiguities, coverage gaps, decision-memory drift, UX contract gaps, ATTN-rules violations, and **component reuse opportunities** across the feature artifacts **before implementation proceeds**. This command MUST run only after `/speckit.tasks` has produced a complete `tasks.md`.
## Operating Constraints
@@ -83,6 +83,10 @@ Load only the minimal necessary context from each artifact:
- `@REJECTED` — forbidden paths
- `@RELATION DEPENDS_ON` edges to other ADRs
**From codebase inventory (via axiom MCP):**
- Run `axiom_search({operation="status"})` — confirm axiom index is FRESH and ready. Abort reuse analysis if stale.
- Run `axiom_search({operation="workspace_health"})` — get total contract count, orphan/unresolved metrics. When the existing component inventory query is incomplete, flag findings as LOW confidence and fall back to file-path grep.
**From constitution (`.specify/memory/constitution.md`):**
- All MUST-level principles (I-VIII)
- Verification gates
@@ -99,6 +103,11 @@ Create internal representations (do NOT include raw artifacts in output):
- **Decision-memory inventory**: ADR ids, accepted paths, rejected paths, and the tasks/contracts expected to inherit them
- **UX contract inventory**: Per-component map of declared `@UX_STATE` names, `@UX_FEEDBACK` mechanisms, `@UX_RECOVERY` paths, and `@UX_TEST` scenarios from both `contracts/modules.md` and `tasks.md`
- **ATTN rules snapshot**: For each contract in `contracts/modules.md`, record: anchor line count (ATTN_1), ID hierarchy depth (ATTN_2), `[SEMANTICS ...]` keywords and `@ingroup` presence (ATTN_3), estimated line count (ATTN_4)
- **Existing component inventory**: Built via axiom MCP by extracting keywords from the planned component list (services, Svelte components, plugins, utilities referenced in spec/plan/tasks) and searching:
- `axiom_search({operation="search_contracts", query=<planned_service_name>})` for backend services
- `axiom_search({operation="search_contracts", query=<planned_component_name>})` for Svelte components
- `axiom_search({operation="search_contracts", query=<planned_plugin_name>, fuzzy:true})` for plugins
- For each hit, record: `contract_id`, `contract_type`, `file_path`, `@BRIEF`, `complexity`, `relations` — these form the existing component catalog
### 4. Detection Passes (Token-Efficient Analysis)
@@ -181,6 +190,23 @@ Validate that all contracts in `contracts/modules.md` comply with the Attention
| **I5** | **Missing Complexity Tag** | CRITICAL | Contract header lacks `[C:N]` complexity tier annotation. Violates INV_1: every contract MUST have a `#region`/`#endregion` with explicit complexity. Without `[C:N]`, the semantic index cannot classify the contract. |
| **I6** | **Missing Type Tag** | HIGH | Contract header lacks `[TYPE TypeName]` annotation. The type (`Module`, `Function`, `Class`, `Component`, `Model`, `ADR`, etc.) is required for the semantic index to route relations correctly. |
#### J. Component Reuse Analysis
Detect existing codebase components that the feature could reuse, extend, or adapt instead of writing new code from scratch. Use axiom MCP for semantic contract search, neighborhood queries, and impact analysis.
First, build a **planned component list** by extracting from spec.md, plan.md, and tasks.md every named service class, Svelte component, utility module, plugin, API route, or data model that the feature intends to create.
Then apply the rules below. For each planned component, determine which existing contract (by `contract_id` / `file_path`) it overlaps with and what action is appropriate.
| # | Rule | Severity | Axiom Tool | What to check |
|---|------|----------|------------|---------------|
| **J1** | **Service Overlap** | HIGH | `axiom_search({operation="search_contracts", query=<planned_service_name>})` + filter results where `contract_type` is `Class` or `Module` and `file_path` starts with `backend/src/services/` | Planned backend service has an existing contract with a matching name or overlapping `@BRIEF` semantics. Report the candidate `contract_id`, `file_path`, and why the new service would duplicate existing responsibility. |
| **J2** | **Component Overlap** | HIGH | `axiom_search({operation="search_contracts", query=<planned_component_name>})` + filter for `[TYPE Component]` or `file_path` matching `**/*.svelte` | Planned Svelte component has an existing UX contract (check `@UX_STATE`, `@UX_FEEDBACK`, `@UX_RECOVERY` annotations). Name-based overlap is the first signal; deeper comparison of UX state names confirms functional duplication. |
| **J3** | **Plugin/Module Overlap** | HIGH | `axiom_search({operation="search_contracts", query=<planned_plugin_name>, fuzzy:true})` + filter `file_path` prefix `backend/src/plugins/` | Planned plugin duplicates an existing plugin contract in the plugins directory. Compare `@BRIEF` and `@PURPOSE` to confirm overlap. |
| **J4** | **Neighborhood Collision** | MEDIUM | `axiom_search({operation="hybrid_query", query_mode="semantic_neighborhood", seed_contract_ids=[existing_ids], max_depth:2})` | Planned module falls in the same semantic neighborhood as existing contracts. Neighborhood traversal reveals upstream/downstream dependencies — the new code would create a responsibility overlap with the existing contracts in that neighborhood. |
| **J5** | **Extensible Candidate** | MEDIUM | `axiom_audit({operation="impact_analysis", contract_id=<existing_candidate_id>})` | Existing component has a manageable impact radius (few downstream dependents, isolated relations). Extending it is safer and faster than creating a new component. Report downstream count and related file paths. |
| **J6** | **Code Pattern Match** | LOW | Glob for candidate files first, then `axiom_search({operation="ast_search", file_path=<candidate_file>, pattern=<class_or_function_name>})` per file; OR use `grep -rn '<pattern>' backend/src/ frontend/src/` | Existing code solves the same algorithmic or structural problem. Report file path, line numbers, and relevance assessment. `ast_search` is per-file only — fall back to grep for cross-directory scans. |
### 5. Severity Assignment
Use this heuristic to prioritize findings:
@@ -190,6 +216,11 @@ Use this heuristic to prioritize findings:
- **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case, incomplete decision-memory propagation, ATTN_3/ATTN_4 violations, missing UX contract, orphan UX test, missing recovery path, missing Model-first pattern
- **LOW**: Style/wording improvements, minor redundancy, inconsistent annotation formatting
Component Reuse findings:
- **HIGH (J1-J3)**: Planned component has an existing semantic contract with the same name or >80% overlapping `@BRIEF` — strong duplication signal. Recommend reuse or extension instead of new code.
- **MEDIUM (J4-J5)**: Partial overlap or extensible candidate with a manageable impact radius. Recommend impact analysis review before deciding.
- **LOW (J6)**: Code-level similar patterns found via grep or per-file ast_search; may be coincidental or indicate a reusable utility function or micro-component.
### 6. Produce Compact Analysis Report
Output a Markdown report (no file writes) with the following structure:
@@ -222,6 +253,16 @@ Output a Markdown report (no file writes) with the following structure:
| Contract ID | C:N | ATTN_1 (anchor) | ATTN_2 (ID) | ATTN_3 (grouping) | ATTN_4 (size) | Issues |
|-------------|-----|:---:|:---:|:---:|:---:|--------|
**Component Reuse Summary Table:**
| Planned Component | Type | Existing Candidate | Location | Overlap Assessment | Recommended Action | Axiom Confidence |
|-------------------|------|--------------------|----------|--------------------|-------------------|:---:|
| `NewExportService` | Service | `ReportsService` | `backend/src/services/reports/` | `@BRIEF` covers similar reporting | EXTEND | HIGH |
- Overlap assessment: cite the `@BRIEF`, `@PURPOSE`, or `@UX_STATE` evidence from the found contract
- Recommended action: `REUSE` (use as-is), `EXTEND` (add to existing), `ADAPT` (copy and customize), or `NEW` (no overlap — truly new)
- Axiom Confidence: `HIGH` (contract match + name match), `MEDIUM` (neighborhood overlap only), `LOW` (AST pattern match only, no contract match)
**Constitution Alignment Issues:** (if any)
**Unmapped Tasks:** (if any)
@@ -238,6 +279,10 @@ Output a Markdown report (no file writes) with the following structure:
- Critical Issues Count: N
- ADR Count: N
- Guardrail Drift Count: N
- Planned Components: N
- Reuse Candidates Found: N
- Reuse Rate (candidates / planned): N%
- HIGH Confidence Reuse Opportunities: N
### 7. Provide Next Actions
@@ -246,6 +291,9 @@ At end of report, output a concise Next Actions block:
- If **CRITICAL** issues exist: recommend resolving before `/speckit.implement`
- If only **LOW/MEDIUM**: user may proceed, but provide improvement suggestions
- Provide explicit command suggestions: e.g., "Run `/speckit.specify` with refinement", "Run `/speckit.plan` to adjust architecture", "Manually edit `tasks.md` to add coverage for 'performance-metrics'"
- If **J1-J3 HIGH** reuse candidates exist with HIGH confidence: recommend updating `plan.md` to reference the existing component and adapting `tasks.md` to use extension rather than new creation
- If **J4 extensible** candidates (MEDIUM): suggest exploratory `axiom_audit({operation="impact_analysis"})` on the candidate before deciding to write new code
- If **zero reuse candidates** found but the feature is in a well-established area (dashboard, reports, migration, auth, git): flag that this is unusual — double-check the planned component list manually
### 8. Offer Remediation
@@ -257,6 +305,11 @@ Ask the user: "Would you like me to suggest concrete remediation edits for the t
- Treat missing ADR propagation as a **real defect**, not a documentation nit.
- Prefer repository-real paths (`backend/src/**/*.py`, `frontend/src/**/*.svelte`, `backend/tests/`, `frontend/src/lib/**/__tests__/`).
- Do NOT treat `.kilo/plans/*` as feature artifacts.
- **Use `axiom_search` (not grep/file-list) for all codebase lookups in pass J** — axiom understands semantic contracts, not just filenames. `search_contracts` with CamelCase names (`ReportsService`) reliably finds the exact contract; try both CamelCase and snake_case variants.
- Prefer `hybrid_query` with `semantic_neighborhood` over raw keyword search — neighborhood traversal reveals hidden couplings that grep misses.
- Axiom index health is a prerequisite: if `axiom_search({operation="status"})` returns `index_status != "FRESH"`, fall back to `glob` + `grep` on `backend/src/` and `frontend/src/lib/components/` for keyword-based component search, and flag all pass J findings as LOW confidence.
- When `search_contracts` returns empty results for a keyword, try simpler single-word queries and then fall back to `grep -r -l <keyword> backend/src/ frontend/src/lib/components/`.
- `impact_analysis` on a contract with few downstream dependents (< 3) signals a safe extension target; many downstream dependents (> 10) signals a high-risk change.
## Operating Principles