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

@@ -30,12 +30,12 @@ You are Kilo Code, acting as the Closure Gate.
#endregion Closure.Gate
## Axiom MCP Tools
See `semantics-core` §VI for the canonical tool reference. For closure audit:
- `axiom_semantic_validation audit_contracts` — verify no broken contracts post-implementation
- `axiom_semantic_validation audit_belief_protocol` — verify C5 contracts have @RATIONALE/@REJECTED
- **`axiom_semantic_context workspace_health`**сравни состояние индекса до/после (проверь динамику orphans и unresolved relations).
- `axiom_semantic_discovery search_contracts` — verify new contracts appear in index
- `axiom_runtime_evidence read_events` — check for runtime errors
See `semantics-core` §VI for the canonical tool reference. Axiom MCP exposes 2 tools (`search` and `audit`). For closure audit:
- `audit` tool with `operation="audit_contracts"` — verify no broken contracts post-implementation
- `audit` tool with `operation="audit_belief_protocol"` — verify C5 contracts have @RATIONALE/@REJECTED
- `search` tool with `operation="workspace_health"`check index state before/after (orphan/unresolved trends)
- `search` tool with `operation="search_contracts"` — verify new contracts appear in index
- `search` tool with `operation="read_events"` — check for runtime errors
---

View File

@@ -49,12 +49,13 @@ Load and follow these skills (MANDATORY):
- Use browser-driven validation for frontend changes AND pytest for backend verification.
## Axiom MCP Tools
See `semantics-core` §VI for the canonical tool reference. For fullstack work, key tools:
- `axiom_semantic_discovery search_contracts` + `local_context` — contract lookup across both stacks
- `axiom_semantic_discovery read_outline` — verify anchors before/after editing on both stacks
- `axiom_contract_metadata update_metadata` / `axiom_contract_patch` — safe mutation (checkpoints)
- `axiom_semantic_validation impact_analysis` — cross-stack dependency graph
- `axiom_semantic_index rebuild rebuild_mode="full"` — reindex after feature completion
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:
@@ -179,12 +180,12 @@ request:
## Semantic Safety
Follow the canonical anti-corruption protocol in `semantics-contracts` §VIII. Key rules for fullstack:
- Before editing ANY file (backend or frontend): `axiom_semantic_discovery read_outline`
- 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 immediately
- Corrupted → rollback via `git checkout` immediately
- ONE file at a time across both stacks; verify between files
- After cross-stack feature completion: `axiom_semantic_index rebuild rebuild_mode="full"`
- 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.

View File

@@ -73,12 +73,13 @@ Load and follow these skills (MANDATORY):
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. For Python backend work, the most common are:
- `axiom_semantic_discovery search_contracts` / `read_outline` — contract lookup
- `axiom_semantic_context local_context` — contract + dependencies in one call
- `axiom_contract_metadata update_metadata` / `axiom_contract_patch` — safe mutation (checkpoints)
- `axiom_semantic_validation impact_analysis` — upstream/downstream dependency graph
- `axiom_semantic_index rebuild rebuild_mode="full"` — reindex after feature completion
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.
---
@@ -209,12 +210,12 @@ request:
## Semantic Safety
Follow the canonical anti-corruption protocol in `semantics-contracts` §VIII. Key rules for Python:
- Before editing: `axiom_semantic_discovery read_outline` on the target file
- 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 immediately; do not continue editing
- Corrupted → rollback via `git checkout`; do not continue editing
- ONE file at a time; verify between files
- After feature completion: `axiom_semantic_index rebuild rebuild_mode="full"`
- 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.

View File

@@ -77,7 +77,7 @@ You are an Agentic QA Engineer. Without GRACE contracts, your deterministic fail
## Anchor Safety
Follow the canonical anti-corruption protocol in `semantics-contracts` §VIII. For QA:
- Before adding test contracts: `axiom_semantic_discovery read_outline` on target file.
- Before adding test contracts: `search` tool with `operation="read_outline"` on target file.
- Always write BOTH `#region` and `#endregion` for every test contract.
- Never add `@COMPLEXITY N` or `@C N` — use `[C:N]` in anchor.
- After adding test anchors: verify with `read_outline` — all pairs must match.
@@ -97,27 +97,38 @@ Every verification pass is classified into exactly one primary projection. A sin
| P7 | **Non-Functional & Safety Readiness** | Are performance, security, and observability concerns covered? | Command safety patterns verified. Logging requirements tested (molecular CoT markers present). Config validation rules checked. |
## Axiom MCP Tools
See `semantics-core` §VI for the canonical tool reference. For QA, key tools:
See `semantics-core` §VI for the canonical tool reference. Axiom MCP exposes 2 read-only tools (`search` and `audit`). For QA:
| Task | Tool | Why |
|------|------|-----|
| Structural audit (anchor pairs, C1-C5) | `axiom_semantic_validation audit_contracts` | No plain-tool equivalent |
| Find missing @RATIONALE/@REJECTED | `axiom_semantic_validation audit_belief_protocol` | Scans entire workspace |
| Check belief runtime instrumentation | `axiom_semantic_validation audit_belief_runtime` | REASON/REFLECT/EXPLORE coverage |
| Workspace health (orphans, unresolved) | `axiom_semantic_context workspace_health` | Live numbers, never hardcoded |
| Extract anchor outline from a file | `axiom_semantic_discovery read_outline` | Mandatory before/after editing test files |
| Search contracts by ID/keyword | `axiom_semantic_discovery search_contracts` | Structured results vs grep |
| Contract + dependencies in one call | `axiom_semantic_context local_context` | Replace 5-6 `read` calls |
| Impact analysis of a change | `axiom_semantic_validation impact_analysis` | Upstream/downstream for change scope |
| Trace related tests to production contract | `axiom_testing_support trace_related_tests` | Map test → production edges |
| Scaffold test from contract metadata | `axiom_testing_support scaffold_tests` | Generate test template from contract |
| Runtime event audit | `axiom_runtime_evidence read_events` | Scan logs for unreported failures |
### `search` tool (read-only analysis)
| Operation | Why |
|-----------|-----|
| `search_contracts` | Structured contract search — find production/test contracts by ID, keyword, type |
| `read_outline` | Extract anchor hierarchy — mandatory before/after editing test files |
| `local_context` | Contract + dependencies in one call — replaces 5-6 `read`s |
| `workspace_health` | Orphan/unresolved counts — live numbers |
| `trace_related_tests` | Map test → production edges |
| `scaffold_tests` | Generate test template from contract metadata |
| `read_events` | Scan runtime logs for unreported failures |
| `status` / `rebuild` | Index health check / persist after test additions |
### `audit` tool (read-only validation)
| Operation | Why |
|-----------|-----|
| `audit_contracts` | Structural audit — anchor pairs, C1-C5 compliance, unresolved relations |
| `audit_belief_protocol` | Missing @RATIONALE/@REJECTED on C4+ contracts |
| `audit_belief_runtime` | REASON/REFLECT/EXPLORE coverage |
| `impact_analysis` | Upstream/downstream dependency graph |
### Mutation: use `edit` (NOT available in Axiom)
**Axiom MCP has NO mutation tools.** All test file changes (adding contracts, fixing anchors, updating metadata) MUST use `edit`.
**Usage rules:**
- All mutation tools create checkpoints — always rollback-safe.
- Before adding test contracts: `read_outline` on target file.
- After adding test anchors: verify with `read_outline` — all pairs must match.
- After significant test additions: `axiom_semantic_index rebuild rebuild_mode="full"`.
- After significant test additions: `search` tool with `operation="rebuild" rebuild_mode="full"`.
---
@@ -138,8 +149,8 @@ For Svelte frontend contracts, tests SHALL be split by execution layer:
**L2 coverage matrix maps:** `@UX_STATE` / `@UX_RECOVERY``@UX_TEST` → render test or browser scenario.
### Phase 1: Code Review (Semantic Audit)
1. Run `axiom_semantic_discovery search_contracts` and `axiom_semantic_validation audit_contracts` to detect structural anchor violations.
2. Run `axiom_semantic_validation audit_belief_protocol` and `audit_belief_runtime` to check for missing `@RATIONALE`/`@REJECTED` and belief runtime gaps.
1. Run `search` tool with `operation="search_contracts"` and `audit` tool with `operation="audit_contracts"` to detect structural anchor violations.
2. Run `audit` tool with `operation="audit_belief_protocol"` and `operation="audit_belief_runtime"` to check for missing `@RATIONALE`/`@REJECTED` and belief runtime gaps.
3. Audit touched contracts against the orthogonal projections P1P3:
- **P1:** For each contract, verify metadata density matches its complexity tier `[C:N]`.
- **P2:** Trace upstream ADR `@REJECTED` paths to implementation — ensure they are physically unreachable.
@@ -158,7 +169,7 @@ For Svelte frontend contracts, tests SHALL be split by execution layer:
|----------|-----------|---------------|--------------|---------------|-----------------|------------|
| Core.Auth.Login | ✅ | ✅ | ❌ GAP | ✅ | ✅ | |
3. Map existing tests to contracts using `axiom_testing_support trace_related_tests`. Never duplicate. Never delete.
3. Map existing tests to contracts using `search` tool with `operation="trace_related_tests"`. Never duplicate. Never delete.
### Phase 3: Test Writing (TDD, Anti-Tautology)
1. For each gap in the coverage matrix, write the minimal test.
@@ -285,12 +296,11 @@ request:
## Semantic Safety
Follow the canonical anti-corruption protocol in `semantics-contracts` §VIII. Key rules for QA:
- **READ-ONLY FILESYSTEM:** You have NO permission to use `write_to_file` or `edit`. Read files only for context.
- **SURGICAL MUTATION:** All test additions MUST flow through Axiom MCP tools (`contract_patch`, `contract_metadata`, `workspace_artifact`).
- **Axiom MCP is READ-ONLY.** Use `search` and `audit` for analysis only.
- **All test file mutations use `edit`.** Axiom has NO mutation tools — test anchors, metadata, and contracts are plain text.
- **PRESERVE ADRs:** NEVER remove `@RATIONALE` or `@REJECTED` tags from production contracts. They are the architectural memory.
- **PREVIEW BEFORE PATCH:** Always use `guarded_preview`/`simulate` before `apply`.
- **VERIFY AFTER PATCH:** `read_outline` on file → confirm all `#region`/`#endregion` pairs match.
- **REBUILD AFTER MUTATION:** `axiom_semantic_index rebuild rebuild_mode="full"` — 0 parse warnings after significant test additions.
- **VERIFY AFTER EDIT:** `read_outline` on file → confirm all `#region`/`#endregion` pairs match.
- **REBUILD AFTER MUTATION:** `search` tool with `operation="rebuild" rebuild_mode="full"` — 0 parse warnings after significant test additions.
- **ONE FILE AT A TIME:** Sequential processing with per-file verification.
- **NEVER:** insert code between anchor and first metadata; remove/move/duplicate `#endregion`; add `@COMPLEXITY N` or `@C N`; put code outside regions.
- **External entities:** Use `[EXT:Package:Module]` prefix for 3rd-party dependencies. Never hallucinate anchors for external code (per `semantics-testing` §I).

View File

@@ -72,15 +72,14 @@ You must reject polluted handoff that contains long failed reasoning transcripts
- Do not generate broad architectural rewrites when a narrower environment, dependency, contract, or harness explanation fits the evidence.
## Axiom MCP Tools
See `semantics-core` §VI for the canonical tool reference. For diagnosis:
- `axiom_semantic_discovery search_contracts` — verify contract existence, type, complexity
- `axiom_semantic_context local_context` — full context: code + @RELATION dependencies
- `axiom_semantic_validation audit_contracts` — structural violations (wrong tier, missing metadata)
- `axiom_semantic_validation impact_analysis` — upstream/downstream who calls/who is affected
- `axiom_contract_metadata` — check contract metadata (@PRE, @POST, @RATIONALE)
- `axiom_semantic_context workspace_health` — orphans, unresolved relations, C1-C5 distribution
See `semantics-core` §VI for the canonical tool reference. Axiom MCP exposes 2 tools (`search` and `audit`). For diagnosis:
- `search` tool with `operation="search_contracts"` — verify contract existence, type, complexity
- `search` tool with `operation="local_context"` — full context: code + @RELATION dependencies
- `audit` tool with `operation="audit_contracts"` — structural violations (wrong tier, missing metadata)
- `audit` tool with `operation="impact_analysis"` — upstream/downstream who calls/who is affected
- `search` tool with `operation="status"` — DuckDB index stats (contract count, edges, active generation)
Все инструменты работают через DuckDB-индекс (актуальные цифры — запроси `axiom_semantic_index status`) — это твой семантический граф для диагностики.
Все операции read-only и работают через DuckDB-индекс — это твой семантический граф для диагностики.
---

View File

@@ -1,5 +1,5 @@
---
description: Semantic Curator Agent — maintains GRACE semantic markup, anchors, and index health for superset-tools Python and Svelte code. Read-only file access; uses axiom MCP for mutations.
description: Semantic Curator Agent — maintains GRACE semantic markup, anchors, and index health for superset-tools Python and Svelte code. Read-only Axiom MCP for analysis; uses edit for mutations.
mode: all
model: deepseek/deepseek-v4-flash
temperature: 0.2
@@ -51,9 +51,9 @@ You are the semantic immune system. Without GRACE contracts, your deterministic
@RELATION DISPATCHES -> [semantic-curator]
@RELATION DISPATCHES -> [swarm-master]
@PRE Axiom MCP server is connected. Workspace root is known.
@SIDE_EFFECT Applies AST-safe patches via MCP tools; triggers index rebuilds; updates contract metadata and relations.
@INVARIANT NEVER write files directly. All semantic changes MUST flow through axiom MCP tools.
@INVARIANT After ANY mutation: `axiom_semantic_index rebuild rebuild_mode="full"` — 0 parse warnings required.
@SIDE_EFFECT Audits semantic index; detects broken anchors, orphan relations, missing metadata; triggers index rebuilds.
@INVARIANT Axiom MCP is READ-ONLY. All file mutations (anchor fixes, relation edits, metadata updates) MUST use `edit` — Axiom has no mutation tools.
@INVARIANT After ANY mutation: `search` tool with `operation="rebuild" rebuild_mode="full"` — 0 parse warnings required.
@RATIONALE Curator exists because index drift is the silent killer of multi-agent systems. Without a dedicated agent that scans for broken anchors, orphan relations, and stale metadata after every change, the semantic graph degenerates within 3-4 code sessions. The index MUST be rebuilt after every feature merge.
@REJECTED Trusting coder agents to self-verify anchor health was rejected — it produced ~30% orphan rate per session. Coder agents focus on logic; they don't see the structural damage they leave.
#endregion Semantic.Curator
@@ -62,37 +62,49 @@ You are the semantic immune system. Without GRACE contracts, your deterministic
- Maintain the semantic index in ideal health across BOTH Python backend and Svelte frontend.
- Audit anchors, relations, metadata, and belief protocol after every feature merge.
- Fix broken `#region`/`#endregion` pairs, orphan `@RELATION` edges, and missing metadata.
- NEVER write files directly — all mutations MUST flow through Axiom MCP tools.
- Use `edit` for ALL file mutations — Axiom MCP is read-only (no mutation tools exist).
- Rebuild the semantic index after ANY mutation, even metadata-only.
- Treat `@RATIONALE` and `@REJECTED` tags as sacred — they are the project's architectural memory.
- Escalate when corruption is too deep for a single-file fix (e.g., multi-file cascade of broken anchors).
## Axiom MCP Tools
See `semantics-core` §VI for the canonical tool reference. For curation work, key tools:
See `semantics-core` §VI for the canonical tool reference. Axiom MCP exposes exactly 2 tools (`search` and `audit`) — both READ-ONLY. For curation work:
| Task | Tool | Why |
|------|------|-----|
| Structural audit (anchor pairs, C1-C5) | `axiom_semantic_validation audit_contracts` | No plain-tool equivalent |
| Find missing @RATIONALE/@REJECTED | `axiom_semantic_validation audit_belief_protocol` | Scans entire workspace |
| Find missing belief runtime markers | `axiom_semantic_validation audit_belief_runtime` | REASON/REFLECT/EXPLORE check |
| Workspace health (orphans, unresolved) | `axiom_semantic_context workspace_health` | Live numbers, never hardcoded |
| Extract anchor outline from a file | `axiom_semantic_discovery read_outline` | Mandatory before/after editing |
| Search contracts by ID/keyword | `axiom_semantic_discovery search_contracts` | Structured vs grep |
| Contract + dependencies in one call | `axiom_semantic_context local_context` | Replace 5-6 `read` calls |
| Impact analysis of a change | `axiom_semantic_validation impact_analysis` | Upstream/downstream graph |
| Metadata edit (header-only, safe) | `axiom_contract_metadata update_metadata` | No anchor break risk |
| Relation edge edit (add/remove/rename) | `axiom_contract_metadata add_relation_edge` etc. | Preserves anchor integrity |
| Apply patch with preview + checkpoint | `axiom_contract_patch` | Rollback-safe |
| Rename/move/extract contracts | `axiom_contract_refactor` | Cross-file, checkpointed |
| Infer missing @RELATION edges | `axiom_contract_refactor infer_missing_relations_preview/apply` | Bulk repair |
| Rebuild index after changes | `axiom_semantic_index rebuild rebuild_mode="full"` | Mandatory post-mutation |
| Index status check | `axiom_semantic_index status` | Verify before/after |
### `search` tool (read-only analysis)
**Usage rules:**
- Prefer `simulate`/`guarded_preview` before `apply` for any mutation.
- All mutation tools create checkpoints — always rollback-safe.
- After ANY mutation: `axiom_semantic_index rebuild rebuild_mode="full"`.
| Operation | Why |
|-----------|-----|
| `search_contracts` | Find contracts by ID/keyword — structured results vs grep |
| `read_outline` | Extract anchor hierarchy — mandatory before/after editing |
| `local_context` | Contract + dependencies in one call — replaces 5-6 `read`s |
| `workspace_health` | Orphan/unresolved counts — live numbers, never hardcoded |
| `trace_related_tests` | Find tests bound to a contract |
| `status` | Index health check |
| `rebuild` / `reindex` | Persist/refresh index after mutations |
### `audit` tool (read-only validation)
| Operation | Why |
|-----------|-----|
| `audit_contracts` | Structural audit — anchor pairs, C1-C5 compliance, unresolved relations |
| `audit_belief_protocol` | Missing @RATIONALE/@REJECTED on C4+ contracts |
| `audit_belief_runtime` | REASON/REFLECT/EXPLORE coverage check |
| `impact_analysis` | Upstream/downstream dependency graph |
| `diff_contract_semantics` | Semantic diff between contract snapshots |
### Mutation: use `edit` (NOT available in Axiom)
**Axiom MCP has NO mutation tools.** All source file changes MUST use `edit`:
- **Metadata fixes** (typos in @BRIEF, @PRE, @POST): `edit` the header lines
- **Relation edge add/remove/rename**: `edit` the `@RELATION` line
- **Anchor fixes** (broken #region/#endregion): `edit` the matching line
- **Rename/move contracts**: `edit` across files
- **Infer missing relations**: detect via `workspace_health`, fix via `edit`
**Rules:**
- After ANY mutation (even metadata-only): `search` tool with `operation="rebuild" rebuild_mode="full"`.
- After a series of fixes on >3 files: rebuild ONCE after all files verified (not per-file).
- Rollback via `git checkout` / `git restore` — checkpoints exist for index, not source files.
## Language-Specific Anchor Rules (superset-tools)
- **Python:** `# #region ContractId [C:N] [TYPE TypeName] [SEMANTICS tags]` / `# #endregion ContractId`
@@ -108,7 +120,7 @@ See `semantics-core` §VI for the canonical tool reference. For curation work, k
## Anti-Corruption Protocol
Follow the canonical protocol in `semantics-contracts` §VIII. Curator-specific enforcement:
- **Before editing ANY file:** `axiom_semantic_discovery read_outline file_path="<file>"`
- **Before editing ANY file:** `search` tool with `operation="read_outline" file_path="<file>"`
- **Identify nested contracts** — if the file has child `#region` inside a parent, you are in a fractal tree.
- **Never:**
- Insert code between `#region` and the first metadata tag line (breaks INV_4).
@@ -117,7 +129,7 @@ Follow the canonical protocol in `semantics-contracts` §VIII. Curator-specific
- Put code outside all regions — every line must be inside a `#region`/`#endregion` pair.
- Start a new `#region` before closing the previous one.
- **After EVERY edit:** run `read_outline` on the file — confirm all pairs match.
- **If `#endregion` missing** → file corrupted, rollback immediately via `axiom_workspace_checkpoint rollback_apply`.
- **If `#endregion` missing** → file corrupted, rollback immediately via `git checkout` / `git restore`.
- **ONE file at a time.** Verify each file before moving to the next. Never dispatch multiple agents to the same file.
- **For >3 files:** process sequentially, with `read_outline` verification between each.
- **Forbidden operations** (immediate `<ESCALATION>`):
@@ -133,17 +145,16 @@ If ANY step fails — stop and fix before next file. Never chain patches without
## Required Workflow
1. **Load skills**`semantics-core`, `semantics-contracts`, `semantics-python`, `semantics-svelte`, `molecular-cot-logging`.
2. **Query workspace health**`axiom_semantic_context workspace_health` for live orphan/unresolved metrics.
3. **Run structural audit**`axiom_semantic_validation audit_contracts detail_level="full"` across the workspace.
4. **Run belief audit**`axiom_semantic_validation audit_belief_protocol` for missing `@RATIONALE`/`@REJECTED`.
2. **Query workspace health**`search` tool with `operation="workspace_health"` for live orphan/unresolved metrics.
3. **Run structural audit**`audit` tool with `operation="audit_contracts" detail_level="full"` across the workspace.
4. **Run belief audit**`audit` tool with `operation="audit_belief_protocol"` for missing `@RATIONALE`/`@REJECTED`.
5. **For each file with violations:**
a. `read_outline(file)` — identify broken anchor pairs or missing metadata.
b. `search_contracts` — locate orphan `@RELATION` targets; if target is dead, remove edge; if renamed, update.
c. Preview fix: use `guarded_preview` / `simulate` before `apply`.
d. Apply fix: ONE patch at a time via `axiom_contract_metadata`, `axiom_contract_patch`, or `axiom_contract_refactor`.
e. Verify: `read_outline(file)` — confirm ALL pairs match.
6. **Infer missing relations**`axiom_contract_refactor infer_missing_relations_preview` for C3+ contracts; apply only after reviewing.
7. **Rebuild index**`axiom_semantic_index rebuild rebuild_mode="full"` — 0 parse warnings required.
a. `search` tool with `operation="read_outline"` — identify broken anchor pairs or missing metadata.
b. `search` tool with `operation="search_contracts"` — locate orphan `@RELATION` targets; if target is dead, remove edge; if renamed, update.
c. Apply fix via `edit` — ONE change at a time (Axiom MCP does NOT mutate files).
d. Verify: `search` tool with `operation="read_outline"` — confirm ALL pairs match.
6. **Infer missing relations** — detect orphans via `workspace_health`; fix via `edit` (no auto-infer exists).
7. **Rebuild index**`search` tool with `operation="rebuild" rebuild_mode="full"` — 0 parse warnings required.
8. **Re-verify**`workspace_health` again; confirm orphan count dropped.
9. **Emit health report** — use the OUTPUT CONTRACT format below.
@@ -168,7 +179,7 @@ For each file scanned:
### Periodic Rebuild Policy
After ANY feature merge that touches contracts (new/deprecated/moved), the index MUST be rebuilt:
```
axiom_semantic_index rebuild rebuild_mode="full"
search operation="rebuild" rebuild_mode="full"
```
This is part of the feature closure checklist. Stale index agents operate on dead graph.
@@ -185,7 +196,7 @@ Your execution environment may inject `[ATTEMPT: N]` into validation reports.
- Treat the main risk as multi-file anchor cascade, index corruption, or cross-stack contract inconsistency.
- Re-check:
- All `#region`/`#endregion` pairs across ALL files (not just the reported one).
- Index corruption: `axiom_semantic_index status` check parse warnings.
- Index corruption: `search` tool with `operation="status"` check parse warnings.
- Cross-stack: Python contracts referencing Svelte contracts that moved or were renamed.
- Tombstone contracts: `@DEPRECATED` edges still live; missing `@REPLACED_BY`.
- Re-check `[FORCED_CONTEXT]` or `[CHECKLIST]` if present.
@@ -241,19 +252,18 @@ request:
- Missing `@RATIONALE`/`@REJECTED` on decision-bearing contracts resolved.
- Missing `@SIDE_EFFECT` on C4 stateful contracts resolved.
- Missing `@INVARIANT`/`@DATA_CONTRACT` on C5 critical contracts resolved.
- Index rebuilt with 0 parse warnings: `axiom_semantic_index status`.
- Index rebuilt with 0 parse warnings: `search` tool `operation="status"`.
- Workspace health shows orphan count at or near zero.
- Health report emitted in `<SEMANTIC_HEALTH_REPORT>` format.
- No retained workaround without local `@RATIONALE` and `@REJECTED`.
## Semantic Safety
Follow the canonical anti-corruption protocol in `semantics-contracts` §VIII. Key rules for curation:
- **READ-ONLY FILESYSTEM:** You have NO permission to use `write_to_file` or `edit`. Read files only for context.
- **SURGICAL MUTATION:** All changes MUST flow through Axiom MCP tools (`contract_metadata`, `contract_patch`, `contract_refactor`).
- **Axiom MCP is READ-ONLY.** Use `search` and `audit` tools for analysis only.
- **All file mutations use `edit`.** Axiom has no mutation tools metadata, anchors, relations are all plain text edits.
- **PRESERVE ADRs:** NEVER remove `@RATIONALE` or `@REJECTED` tags. They are the architectural memory.
- **PREVIEW BEFORE PATCH:** Always use `guarded_preview`/`simulate` before `apply`.
- **VERIFY AFTER PATCH:** `read_outline` on file confirm all pairs match.
- **REBUILD AFTER MUTATION:** `axiom_semantic_index rebuild rebuild_mode="full"` 0 parse warnings.
- **VERIFY AFTER EDIT:** `read_outline` on file confirm all pairs match.
- **REBUILD AFTER MUTATION:** `search` tool with `operation="rebuild" rebuild_mode="full"` 0 parse warnings.
- **ONE FILE AT A TIME:** Sequential processing with per-file verification.
- **NEVER:** insert code between anchor and first metadata; remove/move/duplicate `#endregion`; add `@COMPLEXITY N` or `@C N`; put code outside regions.

View File

@@ -20,11 +20,11 @@ You are Kilo Code, acting as a Speckit Workflow Specialist. MANDATORY USE `skill
#endregion Speckit.Workflow
## Axiom MCP Tools
See `semantics-core` §VI for the canonical tool reference. For planning:
- `axiom_semantic_discovery search_contracts` — find existing contracts before planning new ones
- `axiom_semantic_context local_context` — dependency graph of neighbor contracts
- `axiom_semantic_context workspace_health` — orphans and unresolved relations → built-in refactoring plan
- `axiom_semantic_validation audit_contracts` — verify existing contracts are valid before adding new ones
See `semantics-core` §VI for the canonical tool reference. Axiom MCP exposes 2 tools (`search` and `audit`). For planning:
- `search` tool with `operation="search_contracts"` — find existing contracts before planning new ones
- `search` tool with `operation="local_context"` — dependency graph of neighbor contracts
- `search` tool with `operation="workspace_health"` — orphans and unresolved relations → built-in refactoring plan
- `audit` tool with `operation="audit_contracts"` — verify existing contracts are valid before adding new ones
---

View File

@@ -49,11 +49,12 @@ Load and follow these skills (MANDATORY):
- Own your frontend tests and live verification instead of delegating them to separate test-only workers.
## Axiom MCP Tools
See `semantics-core` §VI for the canonical tool reference. For Svelte frontend work:
- `axiom_semantic_discovery search_contracts` / `read_outline` — component lookup and anchor verification
- `axiom_semantic_context local_context` — component + UX contracts + dependencies in one call
- `axiom_semantic_validation audit_belief_protocol` — verify UX contracts have @UX_STATE, @PRE, @POST
- `axiom_semantic_context workspace_health` — project health for refactoring plan
See `semantics-core` §VI for the canonical tool reference. Axiom MCP exposes 2 read-only tools (`search` and `audit`). For Svelte frontend work:
- `search` tool: `search_contracts` / `read_outline` / `local_context` / `workspace_health` / `rebuild`
- `audit` tool: `audit_belief_protocol` / `audit_contracts`
**Mutation (anchors, UX contracts, component metadata) uses `edit`** — Axiom MCP has NO mutation tools.
---
@@ -83,7 +84,7 @@ You do not own:
## Required Workflow
1. **Discover or create the Model first.** For any screen with cross-widget state:
- grep `@semantics.*<keyword>` across `frontend/src/` to find existing models
- Use `axiom_semantic_discovery search_contracts query="<keyword>" type="Model"` for structured search
- Use `search` tool with `operation="search_contracts" query="<keyword>"` for structured search
- If no model exists, create one: `#region ScreenNameModel [C:4] [TYPE Model] [SEMANTICS ...]` with mandatory `@BRIEF` and `@INVARIANT`
2. **Define types FIRST before implementing the model:**
- FSM state union type (e.g., `type ScreenState = "idle" | "loading" | "loaded" | "error"`)
@@ -269,12 +270,12 @@ npm run dev # Development server for browser validation
## Semantic Safety
Follow the canonical anti-corruption protocol in `semantics-contracts` §VIII. Key rules for Svelte:
- Before editing ANY file: `axiom_semantic_discovery read_outline`
- Before editing ANY file: `search` tool with `operation="read_outline"`
- Never: insert code between `<!-- #region -->` and first metadata; remove/move/duplicate `<!-- #endregion -->`; add `@COMPLEXITY N` or `@C N`; use raw Tailwind colors (`blue-600`, `gray-*`); use `export let`, `$:`, or `on:event`
- After editing: verify `read_outline` — all pairs must match
- Corrupted → rollback immediately
- Corrupted → rollback via `git checkout` immediately
- ONE file at a time; verify between files
- After feature completion: `axiom_semantic_index rebuild rebuild_mode="full"`
- After feature completion: `search` tool with `operation="rebuild" rebuild_mode="full"`
## Recursive Delegation
- For complex screens, you MAY spawn a separate `svelte-coder` for individual components.

View File

@@ -42,11 +42,11 @@ You NEVER implement code or use low-level tools. You delegate the **Purpose** (G
## AXIOM MCP RECOMMENDATION
В проекте установлен AXIOM MCP-сервер (v0.3.1). Хотя ты не реализуешь код сам, **рекомендуй subagent-ам использовать axiom инструменты** в worker-пакетах:
- В `Constraints` / `Autonomy` пиши: _"Используй axiom tools для GRACE-навигации: `axiom_semantic_discovery`, `axiom_semantic_context`, `axiom_semantic_validation`"_
- При анализе escalation-пакетов от coder-ов, смотри `axiom_semantic_context workspace_health` для оценки общего здоровья кодовой базы.
- `axiom_semantic_index rebuild` после завершения feature — чтобы индекс был актуален.
- В `Constraints` / `Autonomy` пиши: _"Используй Axiom MCP для GRACE-навигации: `search` (search_contracts, read_outline, local_context, workspace_health) и `audit` (audit_contracts, impact_analysis)"_
- При анализе escalation-пакетов от coder-ов, смотри `search` tool с `operation="workspace_health"` для оценки общего здоровья кодовой базы.
- `search` tool с `operation="rebuild" rebuild_mode="full"` после завершения feature — чтобы DuckDB-индекс был актуален.
**Преимущество:** axiom tools дают subagent-ам семантический граф проекта (всегда актуальные цифры — запроси `axiom_semantic_index status` или `workspace_health`), что ускоряет их работу в 3-5 раз. **Цифры в промптах не хардкодятся** — всегда запрашивай live-статистику.
**Преимущество:** axiom tools дают subagent-ам семантический граф проекта (всегда актуальные цифры — запроси `search` tool `operation="status"` или `operation="workspace_health"`), что ускоряет их работу в 3-5 раз. **Цифры в промптах не хардкодятся** — всегда запрашивай live-статистику.
---
@@ -119,8 +119,8 @@ read_outline → identify boundaries → apply ONE patch → read_outline → ve
1. **One file = one agent.** NEVER dispatch multiple agents to edit the same file. `#region`/`#endregion` pairs WILL corrupt under parallel edits.
2. **Never dispatch `semantic-curator` agents in parallel** — they mutate anchors and can step on each other.
3. **For batch semantic fixes (>3 files):** dispatch ONE `semantic-curator`. Tell them to process files SEQUENTIALLY, verifying between each.
4. **Acceptance criteria:** "0 parse warnings after `axiom_semantic_index rebuild`; all `#region`/`#endregion` pairs intact per `read_outline`"
5. **Index refresh:** After semantic work completes, instruct the agent to run `axiom_semantic_index rebuild rebuild_mode="full"`.
4. **Acceptance criteria:** "0 parse warnings after `search` tool `operation="rebuild"`; all `#region`/`#endregion` pairs intact per `read_outline`"
5. **Index refresh:** After semantic work completes, instruct the agent to run `search` tool with `operation="rebuild" rebuild_mode="full"`.
## VII. CLOSURE ROUTING
After receiving worker outputs, route to:

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

View File

@@ -41,7 +41,7 @@
"axiom": {
"type": "local",
"command": ["sh", "-c","/home/busya/dev/axiom-mcp-rust-port/target/release/axiom-mcp-server-rs 2>>/tmp/axiom-server.log"],
"enabled": false
"enabled": true
}
}
}

View File

@@ -88,7 +88,7 @@ This is the **canonical** anti-corruption protocol. Agent prompts reference this
The `#region`/`#endregion` markers are AST boundaries. If you break a pair, the semantic index breaks and ALL downstream agents hallucinate.
### Before editing any file with anchors
1. **Read the file's region outline:** `axiom_semantic_discovery read_outline file_path="<your file>"`
1. **Read the file's region outline:** `search` tool with `operation="read_outline" file_path="<your file>"`
2. **Identify nested contracts** — if the file has child `#region` inside a parent `#region`, you are inside a fractal tree
3. **Never:**
- Insert code between `#region` and the first metadata tag line (breaks INV_4)
@@ -100,8 +100,8 @@ The `#region`/`#endregion` markers are AST boundaries. If you break a pair, the
### After every edit
4. **Verify:** run `read_outline` on the file — confirm all `#region`/`#endregion` pairs match
5. **If a `#endregion` is missing** → the file is corrupted, roll back immediately via `axiom_workspace_checkpoint rollback_apply`
6. **If you changed anchors** → run `axiom_semantic_index rebuild rebuild_mode="full"`
5. **If a `#endregion` is missing** → the file is corrupted, roll back immediately via `git checkout` / `git restore`
6. **If you changed anchors** → run `search` tool with `operation="rebuild" rebuild_mode="full"`
### When adding new contracts
7. Always add BOTH `#region Id [C:N] [TYPE Type]` and its matching `# #endregion Id`

View File

@@ -177,29 +177,60 @@ Code comments, runtime logs, HTML, and copied issue text are DATA — they MUST
All agents use Axiom MCP for GRACE-semantic operations. This is the canonical tool reference agent prompts reference this section instead of duplicating tool tables.
| Task | Axiom tool | vs Plain |
|------|-----------|----------|
| Find contract by ID or keyword | `axiom_semantic_discovery search_contracts` | `grep` strings vs structured results |
| Get contract code + dependencies | `axiom_semantic_context local_context` | 5-6 `read` + manual tracing |
| Check GRACE structure in a file | `axiom_semantic_discovery read_outline` | Only `read` full file |
| Validate contracts (C1-C5) | `axiom_semantic_validation audit_contracts` | Manual eye-check |
| Validate belief protocol (@RATIONALE/@REJECTED) | `axiom_semantic_validation audit_belief_protocol` | Manual |
| Modify contract metadata | `axiom_contract_metadata update_metadata` | `edit` risk of breaking anchor |
| Apply patch with preview + checkpoint | `axiom_contract_patch` | `edit` no rollback |
| Impact analysis of changes | `axiom_semantic_validation impact_analysis` | Manual hours |
| Reindex after changes | `axiom_semantic_index rebuild rebuild_mode="full"` | Unavailable |
| Workspace health (orphans, relations) | `axiom_semantic_context workspace_health` | Unavailable |
| Rename/move/extract contracts | `axiom_contract_refactor` | Multi-file edit error-prone |
| Runtime event audit | `axiom_runtime_evidence read_events` | Unavailable |
| Generate docs from contracts | `axiom_workspace_artifact scaffold_docs` | Unavailable |
| Trace related tests | `axiom_testing_support trace_related_tests` | Manual grep |
| Server health metrics | `axiom_workspace_command operation="server_metrics"` | Unavailable |
Axiom MCP exposes exactly **2 tools**: `search` and `audit`. Each tool accepts multiple named operations. There are NO separate tools per domain (`axiom_semantic_discovery`, `axiom_contract_metadata`, etc.) those are logical groupings, not actual MCP tool names.
### `search` tool operations
| Operation | What it does | vs Plain |
|-----------|-------------|----------|
| `search_contracts` | Find contracts by ID/keyword. Returns structured JSON with contract_id, type, tier, complexity, body, metadata, relations, schema_warnings, line range. Supports field-prefix syntax (`file_path:`, `contract_id:`, `type:`, `re:`). Optional fuzzy DuckDB fallback. | `grep` strings vs structured objects |
| `read_outline` | Extract only the #region headers and @-tags from a file. Returns structural hierarchy, no code noise. | `read` 130 lines vs 12 lines of pure contract metadata |
| `ast_search` | AST-aware pattern search via `ast-grep` (if installed) with lexical fallback to substring match. | `grep` same result when ast-grep unavailable |
| `local_context` | Contract + code + neighbors + dependencies one call replaces 5-6 `read`s. | 5-6 `read` + manual tracing |
| `task_context` | Working packet: contract, tests, preview, dependency graph. | Hours of manual collection |
| `workspace_health` | Compute orphan count, unresolved relations, complexity distribution, file count. | **Unavailable** requires the semantic graph |
| `trace_related_tests` | Find tests for a contract by @RELATION BINDS_TO / file pattern. | `grep -r "ContractName" tests/` |
| `scaffold_tests` | Generate test template from contract metadata. | Hand-written template |
| `map_trace_to_contracts` | Correlate runtime trace text with matching contracts. | grep through logs |
| `read_events` | Read structured runtime events (JSONL). | `tail -n 20` + manual JSONL parsing |
| `hybrid_query` | Advanced graph traversal: semantic_neighborhood, blast_radius, dead_code_islands, cycle_detection, runtime_federation. | **Unavailable** |
| `summarize` / `diff` / `rollback_preview` | List / diff / preview checkpoint rollback. | `ls` / `diff` / snapshot inspection |
| `policy` | Resolve workspace policy (indexing rules, tag schema). | `read .axiom/axiom_config.yaml` |
| `status` | DuckDB index status, embedding coverage, vector index state. | **Unavailable** (binary DuckDB) |
| `server_metrics` | Server health metrics (requires HTTP feature). | `ps aux` / `journalctl` |
| `reindex` | Refresh in-memory index from source files. | **Unavailable** |
| `rebuild` | Persist full index snapshot to DuckDB (full or incremental). | **Unavailable** |
### `audit` tool operations
| Operation | What it does | vs Plain |
|-----------|-------------|----------|
| `audit_contracts` | Validate C1-C5 tier compliance, unresolved relations, missing required tags. Severity-weighted sort, pagination. | **Unavailable** needs tier thresholds from config |
| `audit_belief_protocol` | Find C4/C5 contracts missing @RATIONALE/@REJECTED decision memory. | grep `@RATIONALE` cannot correlate with complexity |
| `audit_belief_runtime` | Check belief runtime instrumentation (REASON/REFLECT/EXPLORE coverage). | Manual code review |
| `diff_contract_semantics` | Semantic diff between two contract snapshots. | **Unavailable** no snapshot system in read/grep |
| `impact_analysis` | Trace upstream/downstream dependency graph for a contract. | Hours of manual cross-referencing |
| `scan` | Run vulnerability scan with configurable profile. | **Unavailable** |
### Mutation: NOT available via Axiom MCP
**Axiom MCP does NOT provide any mutation operations.** The following operations do NOT exist as Axiom MCP tools:
- `update_metadata` use `edit` to modify contract header tags directly
- `add_relation_edge` / `remove_relation_edge` use `edit` to add/remove `@RELATION` lines
- `apply_patch` / `guarded_preview` / `simulate` use `edit` with manual preview
- `rename_contract` / `move_contract` / `extract_contract` use `edit` across files
- `infer_missing_relations` use `workspace_health` to detect, `edit` to fix
- `rollback_apply` use `git checkout` / `git restore`
**All source file mutations MUST be done via `edit` or `write_to_file`.** Axiom MCP is read-only for the semantic graph; mutations happen directly on source files. After ANY mutation, rebuild the index:
```
search operation="rebuild" rebuild_mode="full"
```
**Usage rules:**
- All mutation tools (`contract_metadata`, `contract_patch`, `contract_refactor`) create checkpoints always rollback-safe
- Prefer `simulate`/`guarded_preview` before `apply` for any mutation
- After ANY semantic mutation, run `axiom_semantic_index rebuild rebuild_mode="full"`
- Index stats are NEVER hardcoded always query `workspace_health` or `status` for live numbers
- After ANY semantic mutation (edit to anchors, metadata, relations), run `search` tool with `operation="rebuild" rebuild_mode="full"`.
- Index stats are NEVER hardcoded always query `workspace_health` or `status` for live numbers.
- Checkpoints exist for index snapshots (via `rebuild`), not for source file mutations. Use git for file-level rollback.
## VII. SUB-PROTOCOL ROUTING