This commit is contained in:
2026-06-05 15:01:34 +03:00
parent 50180aaa14
commit 4cef6af041
27 changed files with 13547 additions and 892 deletions

View File

@@ -1,56 +1,68 @@
# ss-tools Constitution
Конституция не дублирует правила — она объясняет, **почему** каждый принцип важен, и указывает, **где** искать полные инструкции.
The constitution does not duplicate rules — it explains **why** each principle matters and **where** to find full instructions.
## Core Principles
### I. Semantic Contract First
Каждая единица кода (функция, класс, модуль, компонент) должна быть аннотирована GRACE-Poly контрактом. Без контракта код невидим для семантического индекса, непроверяем агентом и недоступен для impact analysis.
Every code unit (function, class, module, component) MUST carry a GRACE-Poly contract. Without a contract, code is invisible to the semantic index, unverifiable by agents, and unreachable by impact analysis.
**Немедленные правила** → [ADR-0002](docs/adr/ADR-0002-semantic-protocol.md)
**Синтаксис и уровни сложности**`skill({name="semantics-core"})`
**Методология контрактов**`skill({name="semantics-contracts"})`
**Immediate rules** → [ADR-0002](docs/adr/ADR-0002-semantic-protocol.md)
**Syntax & complexity tiers**`skill({name="semantics-core"})`
**Contract methodology**`skill({name="semantics-contracts"})`
### II. Decision Memory
Каждый архитектурный выбор, отвергающий альтернативу, должен быть записан: `@RATIONALE` (почему выбран этот путь) и `@REJECTED` (что запрещено и почему). Без этого агенты переоткрывают уже исследованные тупики, а долгоживущие сессии накапливают невидимый архитектурный дрейф.
Every architectural choice that rejects an alternative MUST be recorded: `@RATIONALE` (why this path was chosen) and `@REJECTED` (what is forbidden and why). Without this, agents rediscover already-explored dead ends, and long-horizon sessions accumulate invisible architectural drift.
**Протокол ADR**`skill({name="semantics-contracts"})` §I
**Каталог решений** → [`docs/adr/`](docs/adr/)
**Правило запрета воскрешения**: silently reintroducing `@REJECTED` pattern = fatal regression. Требуется `<ESCALATION>`.
**ADR protocol**`skill({name="semantics-contracts"})` §I
**Decision catalog** → [`docs/adr/`](docs/adr/)
**Resurrection ban**: silently reintroducing a `@REJECTED` pattern = fatal regression. Requires `<ESCALATION>`.
### III. External Orchestrator
ss-tools — внешний оркестратор над Apache Superset, а не плагин внутри него. Это даёт: независимый релизный цикл, отсутствие связанности с миграциями Superset, изоляцию DevOps-привилегий от BI-привилегий.
ss-tools is an external orchestrator over Apache Superset, not a plugin inside it. This gives: independent release cycle, no coupling to Superset migrations, isolation of DevOps privileges from BI privileges.
**Полное обоснование** → [ADR-0003](docs/adr/ADR-0003-orchestrator-pattern.md)
**Full rationale** → [ADR-0003](docs/adr/ADR-0003-orchestrator-pattern.md)
### IV. Module Discipline
Файл >400 строк или функция с цикломатической сложностью >10 — сигнал к декомпозиции. Каноническая структура директорий исключает циклические импорты и путаницу агентов при длинных speckit-сессиях.
File >400 lines or function cyclomatic complexity >10 = signal to decompose. Canonical directory structure prevents circular imports and agent confusion in long speckit sessions.
**Структура и границы** → [ADR-0001](docs/adr/ADR-0001-module-layout.md)
**Structure & boundaries** → [ADR-0001](docs/adr/ADR-0001-module-layout.md)
### V. RBAC Enforcement
Все мутирующие операции требуют явной проверки роли. DevOps-привилегии (деплой, миграция, maintenance) отделены от BI-привилегий (просмотр дашбордов). Default-allow запрещён.
All mutating operations require explicit role check. DevOps privileges (deploy, migration, maintenance) are separated from BI privileges (dashboard viewing). Default-allow is forbidden.
**Модель ролей и паттерны** → [ADR-0005](docs/adr/ADR-0005-auth-rbac.md)
**Role model & patterns** → [ADR-0005](docs/adr/ADR-0005-auth-rbac.md)
### VI. Frontend — Svelte 5 Runes Only
Только runes-синтаксис (`$state`, `$derived`, `$effect`, `$props`). Устаревший синтаксис Svelte 4 создаёт путаницу и баги реактивности. `fromStore` + несколько `$derived` вызывают бесконечный reactive flush loop — задокументированный отказ.
Only runes syntax (`$state`, `$derived`, `$effect`, `$props`). Legacy Svelte 4 syntax creates confusion and reactivity bugs. `fromStore` + multiple `$derived` causes infinite reactive flush loop — documented rejection.
**Архитектура фронтенда** → [ADR-0006](docs/adr/ADR-0006-frontend-architecture.md)
**Запрет fromStore+$derived** → [ADR-0007](docs/adr/ADR-0007-rejected-fromStore-derived.md)
**Паттерны компонентов**`skill({name="semantics-svelte"})`
**Frontend architecture** → [ADR-0006](docs/adr/ADR-0006-frontend-architecture.md)
**fromStore+$derived rejection** → [ADR-0007](docs/adr/ADR-0007-rejected-fromStore-derived.md)
**Component patterns**`skill({name="semantics-svelte"})`
### VII. Test-Driven for C3+ Contracts
Контракты уровня C3 и выше требуют тестов, написанных до реализации. Тесты верифицируют `@PRE`/`@POST`/`@INVARIANT`, а не детали реализации. Минимум один тест должен явно проверять, что `@REJECTED` путь производит ожидаемый отказ.
C3+ contracts require tests written before implementation. Tests verify `@PRE`/`@POST`/`@INVARIANT`, not implementation details. Minimum one test must explicitly verify that the `@REJECTED` path produces the expected failure.
**Методология тестирования**`skill({name="semantics-testing"})`
**Testing methodology**`skill({name="semantics-testing"})`
### VIII. Attention-Optimized Contracts
All generated contracts (specs, code, tests) MUST be optimized for the attention compression pipeline (MLA 3.5× → CSA 4×+topk → HCA 128× → DSA Lightning Indexer). Contracts that violate these rules become invisible to the model after context compression — causing downstream hallucination.
**Attention architecture & rules**`skill({name="semantics-core"})` §VIII
**The four rules:**
- **ATTN_1**: First anchor line packs ID, complexity, type, and `@SEMANTICS` on ONE line (CSA 4× survival).
- **ATTN_2**: Hierarchical IDs: `Domain.Sub.Name` (HCA 128× survival).
- **ATTN_3**: Same-domain contracts share primary `@SEMANTICS` keyword (DSA Indexer grouping).
- **ATTN_4**: Contract ≤150 lines, module ≤400 lines (sliding window visibility).
## Development Workflow
@@ -58,13 +70,14 @@ ss-tools — внешний оркестратор над Apache Superset, а н
/speckit.specify → /speckit.clarify → /speckit.plan → /speckit.tasks → /speckit.implement
```
- Ни один этап не пропускается при наличии `[NEEDS CLARIFICATION]`
- Мутация контрактов: preview → apply, никогда сразу apply
- Все артефакты фичи — в `specs/<feature>/`, никогда в `.kilo/` или `.ai/`
**Rules:**
- No phase is skipped when `[NEEDS CLARIFICATION]` markers remain
- Contract mutation: preview → apply, never immediate apply
- All feature artifacts in `specs/<feature>/`, never in `.kilo/` or `.ai/`
## Verification Gates
| Gate | Команда |
| Gate | Command |
|------|---------|
| Backend tests | `cd backend && source .venv/bin/activate && python -m pytest -v` |
| Frontend tests | `cd frontend && npm run test` |
@@ -74,6 +87,6 @@ ss-tools — внешний оркестратор над Apache Superset, а н
## Governance
Конституция имеет приоритет над всеми остальными практиками разработки. Изменения требуют: документирования предложения, проверки на согласованность со всеми ADR, плана миграции затронутого кода, и bump версии.
The constitution takes precedence over all other development practices. Amendments require: documented proposal, consistency check against all ADRs, migration plan for affected code, and version bump.
**Version**: 1.0.0 | **Ratified**: 2026-05-22 | **Last Amended**: 2026-05-22
**Version**: 1.1.0 | **Ratified**: 2026-05-22 | **Last Amended**: 2026-06-05

View File

@@ -81,25 +81,47 @@ docker/ # Docker configurations
## Semantic Contract Guidance
> Use this section to drive Phase 1 artifacts, especially `contracts/modules.md`.
> See `semantics-core` §VIII for the attention architecture that these rules optimize for.
- Classify each planned module/component/model with `[C:N]` complexity in the `#region` anchor.
- Use canonical anchor syntax appropriate for each context:
- Python: `# #region ContractId [C:N] [TYPE TypeName] [SEMANTICS tags]` / `# #endregion ContractId`
- Svelte markup: `<!-- #region ContractId [C:N] [TYPE Component] [SEMANTICS tags] -->` / `<!-- #endregion ContractId -->`
- Svelte/TypeScript model: `// #region ModelName [C:N] [TYPE Model] [SEMANTICS tags]` / `// #endregion ModelName`
- Markdown/ADR: `## @{ ContractId [C:N] [TYPE TypeName]` / `## @} ContractId`
### Attention Compliance Gate (MANDATORY — validate before generating contracts)
Every contract generated in Phase 1 MUST pass these checks (from `semantics-core` §VIII):
| Rule | Check | Why |
|------|-------|-----|
| **ATTN_1** | First anchor line packs `[C:N] [TYPE] [SEMANTICS]` on ONE line | CSA 4× pooling spread-out anchors lose detail |
| **ATTN_2** | IDs are hierarchical: `Domain.Sub.Name` | HCA 128× flat IDs become noise |
| **ATTN_3** | Same-domain contracts share primary `@SEMANTICS` keyword | DSA Lightning Indexer scores by keyword match |
| **ATTN_4** | Contract 150 lines, module 400 lines | Sliding window must see entire contract |
### Anchor Syntax (canonical)
- Python: `# #region ContractId [C:N] [TYPE TypeName] [SEMANTICS tags]` / `# #endregion ContractId`
- Svelte markup: `<!-- #region ContractId [C:N] [TYPE Component] [SEMANTICS tags] -->` / `<!-- #endregion ContractId -->`
- Svelte/TypeScript model: `// #region ModelName [C:N] [TYPE Model] [SEMANTICS tags]` / `// #endregion ModelName`
- Markdown/ADR: `## @{ ContractId [C:N] [TYPE TypeName]` / `## @} ContractId`
- **Legacy `[DEF:id:Type]` syntax is deprecated** use `#region` format exclusively.
- **Model files use `.svelte.ts` extension** canonical format for contracts with Svelte reactive primitives (`$state`, `$derived`, `$effect`).
- Match contract density to complexity:
- C1: anchors only (DTOs, simple constants)
- C2: typically adds `@BRIEF` (utility functions, pure helpers)
- C3: typically adds `@RELATION`; Svelte also `@UX_STATE`; TypeScript also `@STATE`/`@ACTION`
- C4: typically adds `@PRE`, `@POST`, `@SIDE_EFFECT`; Python also `belief_scope`/`reason`/`reflect` markers; Svelte also `@UX_FEEDBACK`, `@UX_RECOVERY`, `@UX_REACTIVITY`
- C5: C4 + `@DATA_CONTRACT`, `@INVARIANT` + `@RATIONALE`/`@REJECTED` decision memory
- **Screen Models** (`[TYPE Model]`) are C4/C5 contracts that declare screen-level state, invariants, and actions. A component that reads/writes model state declares `@RELATION BINDS_TO -> [ModelId]`. See `semantics-svelte` §IIIa.
- Write relations only in canonical form: `@RELATION PREDICATE -> TARGET_ID`
- **Model files use `.svelte.ts` extension** canonical format for contracts with Svelte reactive primitives.
### Complexity & Metadata (typical — all tags allowed at all tiers)
- C1: anchors only (DTOs, simple constants)
- C2: typically adds `@BRIEF`
- C3: typically adds `@RELATION`; Svelte also `@UX_STATE`; TypeScript also `@STATE`/`@ACTION`
- C4: typically adds `@PRE`, `@POST`, `@SIDE_EFFECT`; Svelte also `@UX_FEEDBACK`, `@UX_RECOVERY`
- C5: C4 + `@DATA_CONTRACT`, `@INVARIANT` + `@RATIONALE`/`@REJECTED` decision memory
- **Screen Models** (`[TYPE Model]`) are C4/C5 contracts. Component binds via `@RELATION BINDS_TO -> [ModelId]`. See `semantics-svelte` §IIIa.
### Relations
- Canonical form: `@RELATION PREDICATE -> TARGET_ID`
- Allowed predicates: `DEPENDS_ON`, `CALLS`, `INHERITS`, `IMPLEMENTS`, `DISPATCHES`, `BINDS_TO`, `CALLED_BY`, `VERIFIES`.
- If any relation target, DTO, or contract dependency is unknown, emit `[NEED_CONTEXT: target]` instead of inventing placeholders.
- Unknown targets `[NEED_CONTEXT: target]` never invent placeholders.
- **Cross-stack edges are critical**: backend Pydantic schema MUST have `@RELATION` to frontend TypeScript DTO and vice versa (survives HCA 128× cross-stack amnesia).
### Function-Level Contracts (C3+ only)
For C3+ functions that are API endpoints, Screen Model actions, or orchestration functions, generate full `#region` headers with `@PRE`/`@POST`/`@SIDE_EFFECT`/`@DATA_CONTRACT`/`@TEST_EDGE` in `contracts/modules.md` under their parent module. See `speckit.plan.md` "Function-Level Contracts for C3+" for the canonical template. C1/C2 functions do NOT need pre-generated contracts only C3+.
## Complexity Tracking

View File

@@ -1,115 +1,78 @@
# Feature Specification: [FEATURE NAME]
#region FeatureSpec [C:3] [TYPE ADR] [SEMANTICS spec,requirements,feature]
@BRIEF Feature specification — WHAT the user needs and WHY. Implementation-free. Survives HCA 128× via @SEMANTICS grouping.
## Navigation (DSA Indexer keywords)
@SEMANTICS: spec, requirements, feature, [DOMAIN_KEYWORD_1], [DOMAIN_KEYWORD_2]
**Feature Branch**: `[###-feature-name]`
**Created**: [DATE]
**Status**: Draft
**Input**: User description: "$ARGUMENTS"
**Created**: [DATE] | **Status**: Draft
**Input**: "$ARGUMENTS"
## User Scenarios & Testing *(mandatory)*
## User Scenarios
<!--
IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance.
Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them,
you should still have a viable MVP (Minimum Viable Product) that delivers value.
Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical.
Think of each story as a standalone slice of functionality that can be:
- Developed independently
- Tested independently
- Deployed independently
- Demonstrated to users independently
-->
Each story is an independently testable unit. Prioritized P1 (MVP) → P2 → P3.
All stories share `@SEMANTICS` domain keywords from the feature header.
### User Story 1 - [Brief Title] (Priority: P1)
### Story 1 [Brief Title] (P1)
[Describe this user journey in plain language]
**Why P1**: [One sentence — value delivered]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [One sentence — how to verify this story alone]
**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
2. **Given** [initial state], **When** [action], **Then** [expected outcome]
**Acceptance**:
1. **Given** [state] **When** [action] **Then** [outcome]
2. **Given** [state] **When** [action] **Then** [outcome]
---
### User Story 2 - [Brief Title] (Priority: P2)
### Story 2 [Brief Title] (P2)
[Describe this user journey in plain language]
**Why P2**: [One sentence]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [One sentence]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
**Acceptance**:
1. **Given** [state] **When** [action] **Then** [outcome]
---
### User Story 3 - [Brief Title] (Priority: P3)
### Story 3 [Brief Title] (P3)
[Describe this user journey in plain language]
**Why P3**: [One sentence]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [One sentence]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
**Acceptance**:
1. **Given** [state] **When** [action] **Then** [outcome]
---
[Add more user stories as needed, each with an assigned priority]
### Edge Cases
- [boundary condition] → [expected behavior]
- [error scenario] → [expected recovery]
- [empty/null state] → [expected fallback]
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right edge cases.
-->
## Requirements
- What happens when [boundary condition]?
- How does system handle [error scenario]?
### Functional (IDs survive HCA 128× via hierarchical naming)
## Requirements *(mandatory)*
- **[DOMAIN]-FR-001**: [specific capability]
- **[DOMAIN]-FR-002**: [specific capability]
- **[DOMAIN]-FR-003**: [key interaction]
- **[DOMAIN]-FR-004**: [data requirement]
- **[DOMAIN]-FR-005**: [behavior requirement]
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right functional requirements.
-->
*Unclear requirements use:* `[NEEDS CLARIFICATION: topic]` — maximum 3 markers.
### Functional Requirements
### Key Entities
- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"]
- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"]
- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"]
- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"]
- **FR-005**: System MUST [behavior, e.g., "log all security events"]
- **[Entity]**: [What it represents, key attributes without implementation]
- **[Entity]**: [What it represents, relationships to other entities]
*Example of marking unclear requirements:*
## Success Criteria
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
- **SC-001**: [Measurable metric — time, throughput, percentage]
- **SC-002**: [Measurable metric]
- **SC-003**: [User-facing metric]
### Key Entities *(include if feature involves data)*
- **[Entity 1]**: [What it represents, key attributes without implementation]
- **[Entity 2]**: [What it represents, relationships to other entities]
## Success Criteria *(mandatory)*
<!--
ACTION REQUIRED: Define measurable success criteria.
These must be technology-agnostic and measurable.
-->
### Measurable Outcomes
- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"]
- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"]
- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"]
- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"]
#endregion FeatureSpec

View File

@@ -94,11 +94,24 @@ Examples of foundational tasks (adjust based on your project):
- [ ] T014 [P] [US1] Define TypeScript types in frontend/src/types/[feature].ts (DTOs matching backend Pydantic schemas)
- [ ] T015 [P] [US1] Create [ScreenName]Model in frontend/src/lib/models/[ScreenName]Model.svelte.ts
- [ ] T016 [P] [US1] Create [Entity] model in backend/src/models/[entity].py
- [ ] T017 [US1] Implement [Service] in backend/src/services/[service].py
- [ ] T018 [US1] Implement [endpoint/feature] in backend/src/api/[file].py
- [ ] T019 [US1] Create [Component] as thin rendering layer in frontend/src/routes/[...] (binds to model via @RELATION BINDS_TO -> [ModelId])
- [ ] T020 [US1] Add @INVARIANT validation in model actions
- [ ] T021 [US1] Add belief-runtime instrumentation in model actions for C4/C5 flows
- [ ] T017 [US1] Implement [function_name] in backend/src/api/[file].py
@PRE: [precondition 1], [precondition 2]
@POST: [output guarantee]
@DATA_CONTRACT: [InputDTO] → [OutputDTO]
@TEST_EDGE: [scenario→outcome], [scenario→outcome]
- [ ] T018 [US1] Implement [Service.action] in backend/src/services/[service].py
@PRE: [guard conditions]
@POST: [post state]
@SIDE_EFFECT: [external calls, DB writes]
@TEST_EDGE: [scenario→outcome]
- [ ] T019 [US1] Implement [Model.action] in frontend/src/lib/models/[Model].svelte.ts
@ACTION [action_name](params): [description]
@POST: [state guarantee]
@SIDE_EFFECT: [API call, store mutation]
@TEST_EDGE: [scenario→outcome]
- [ ] T020 [US1] Create [Component] in frontend/src/routes/[...] (bind to model via @RELATION BINDS_TO -> [ModelId])
- [ ] T021 [US1] Add @INVARIANT validation in model actions
- [ ] T022 [US1] Add belief-runtime instrumentation in model actions for C4/C5 flows
**Checkpoint**: At this point, User Story 1 should be fully functional and testable independently
@@ -161,6 +174,9 @@ Examples of foundational tasks (adjust based on your project):
- [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/
- [ ] TXXX Security hardening
- [ ] TXXX Run quickstart.md validation
- [ ] TXXX [P] **Attention compliance audit**: verify ATTN_1 (first-line density), ATTN_2 (hierarchical IDs), ATTN_3 (`@SEMANTICS` keyword consistency across same-domain contracts), ATTN_4 (contract ≤150 lines, module ≤400 lines) per `semantics-core` §VIII
- [ ] TXXX [P] **Semantic index rebuild**: `axiom_semantic_index rebuild rebuild_mode="full"` — 0 parse warnings required
- [ ] TXXX [P] **Orphan audit**: `axiom_semantic_context workspace_health` — confirm no new orphans from this feature
---
@@ -255,6 +271,7 @@ With multiple developers:
- Stop at any checkpoint to validate story independently
- Avoid: vague tasks, same file conflicts, cross-story dependencies that break independence
- Derive implementation tasks from semantic contracts in `contracts/modules.md`, especially `@PRE`, `@POST`, `@SIDE_EFFECT`, `@DATA_CONTRACT`, and UI `@UX_*` tags
- **For C3+ functions with pre-generated contracts: inline @PRE/@POST/@SIDE_EFFECT/@DATA_CONTRACT/@TEST_EDGE directly into the task description** (see format above at T017-T019). This eliminates cross-file navigation — the implementing agent sees the contract in the task line.
- For Complexity 4/5 Python modules, include tasks for belief-state logging paths with `logger.reason()`, `logger.reflect()`, and `belief_scope` where required
- For Complexity 5 or explicitly test-governed contracts, include tasks that cover `@TEST_CONTRACT`, `@TEST_SCENARIO`, `@TEST_FIXTURE`, `@TEST_EDGE`, and `@TEST_INVARIANT`
- Never create tasks from legacy `@TIER` alone; complexity is the primary execution signal

View File

@@ -1,8 +1,8 @@
# UX Reference: [FEATURE NAME]
#region UxReference [C:3] [TYPE ADR] [SEMANTICS ux, reference, [DOMAIN]]
@BRIEF UX interaction reference — persona, flows, states, and recovery paths. Drives `@UX_*` contract tags in Phase 1.
**Feature Branch**: `[###-feature-name]`
**Created**: [DATE]
**Status**: Draft
**Created**: [DATE] | **Status**: Draft
## 1. User Persona & Context
@@ -74,3 +74,5 @@ $ command --flag value
* **Style**: [e.g. Concise, Technical, Friendly, Verbose]
* **Terminology**: [e.g. Use "Repository" not "Repo", "Directory" not "Folder"]
#endregion UxReference