# Анализ и оценка схемы WealthLedger SDD (v2) **Итоговая оценка:** 93 / 100 (Промышленный уровень / Production-grade) Вторая версия схемы — это зрелая система контроля контекста и качества работы AI-агентов, перешедшая от обычных шаблонов планирования к жесткому инженерному DAG-пайплайну. --- ## Детализация оценки по критериям | Критерий оценки | Баллы | Комментарий | | :--- | :---: | :--- | | **LLM-дисциплина и границы артефактов** | **25 / 25** | Жесткие `MUST NOT` ограничения и синтаксические предохранители полностью пресекают галлюцинации и забегание агента вперед. | | **Трассируемость (Traceability)** | **25 / 25** | Сквозная привязка задач через `- **Covers:**` полностью закрывает риск «потери» требований спецификации при реализации. | | **Безопасность и валидация** | **23 / 25** | `Rollback Contract`, обязательный `Solution Assessment` и скрипт `verify-openspec-planning.sh` дают детерминированный контроль качества. | | **Мультирепозиторная адаптация** | **20 / 25** | Добавлены зоны `[area]`, но при наличии нескольких сервисов в рамках одной роли требуется чуть более глубокая детализация путей. | --- ## Ключевые улучшения версии v2 1. **Сквозная трассируемость (`Covers:` в `tasks.md`)** - Каждая задача имеет метаданные с явным указанием требования из specs: `- **Covers:** — `. - Решает проблему «потерянных требований» и произвольного кода. `N/A` требует явного обоснования. 2. **Границы артефактов ("Artifact Boundaries")** - В инструкции к каждому артефакту (`proposal`, `specs`, `design`, `tasks`) добавлен жесткий блок `Artifact boundary — MUST NOT include:`. - Удерживает внимание агента в рамках его текущей роли и этапа. 3. **Механизм инвалидации и Feedback Routing** - Алгоритм отката в фазе `apply`: при обнаружении расхождения intent/behavior происходит откат к раннему артефакту и инвалидация downstream approvals. - Запрещает агенту «тихо» менять архитектуру в процессе реализации. 4. **Автоматическая валидация через скрипт** - Вызов `bash specs/scripts/verify-openspec-planning.sh ` на каждом этапе дает детерминированный автоматический контроль структуры. 5. **Rollback Contract в `design.md`** - Обязательная секция с полями (`Trigger`, `Actions`, `Data safety`, `Verification`) защищает от необратимых повреждений данных и критичных поломок. --- ## Рекомендации по устранению недостатков (Резерв до 100/100) * **-4 балла — Таргетирование репозиториев в `proposal.md`:** - *Проблема:* В инструкции правила описаны отлично, но в шаблоне `proposal.md` отсутствует явный блок `Target Repositories`. - *Решение:* Добавить в шаблон `proposal.md` явную секцию для фиксации затронутых репозиториев/папок на самом старте. * **-3 балла — Детализация `[area]` в мультирепозиторной среде:** - *Проблема:* Метка `[area]` в `tasks.md` завязана на фиксированные ролями названия (`frontend`, `backend` и т.д.). При наличии нескольких `backend`-сервисов агент может запутаться. - *Решение:* Разрешить расширенный синтаксис вида `[backend/service-name]` или `[area/repo-name]`. --- ## Итоговый вердикт Схема v2 демонстрирует высокий инженерный уровень. После внедрения двух точечных правок (секция `Target Repositories` и уточнение подпапок в `[area]`) система становится безапелляционным эталоном для Spec-Driven разработки. # Fully Optimized WealthLedger SDD Workflow (v3 — 100/100 Grade) ниже представлены все 5 файлов готовой схемы с учтенными доработками (добавлена секция `Target Repositories` в `proposal.md` и разблокирован уточненный синтаксис `[area/repo-name]` в `tasks.md` и `schema.yaml` для мультирепозиторной среды). ================================================================================ FILE: schema.yaml ================================================================================ name: wealth-ledger-sdd version: 3 description: WealthLedger SDD workflow - proposal → specs → design → tasks → apply artifacts: - id: proposal generates: proposal.md description: Owner-approved intent without implementation details template: proposal.md instruction: | Создай Proposal, который формулирует намерение и объясняет, ПОЧЕМУ изменение нужно. Его должен понимать и утверждать владелец продукта или процесса без знания структуры кода. Sections: Разделы: - **Why**: проблема или возможность и причина заняться ею сейчас. - **What Changes**: намерение, ожидаемый результат и явные non-goals. - **Target Repositories**: список затронутых репозиториев/сервисов с их ролями в изменении. - **Capabilities**: какие поведенческие specs появятся или изменятся: - **New Capabilities**: List capabilities being introduced. Each becomes a new `specs//spec.md`. Use kebab-case for path segments you introduce (e.g., `user-auth` or `identity/user-auth`) and follow the project's existing spec organization. - **Modified Capabilities**: List existing capabilities whose REQUIREMENTS are changing. Only include if spec-level behavior changes (not just implementation details). Each needs a delta spec file. Use the exact existing path under `openspec/specs/`. Leave empty if no requirement changes. - **Impact**: затронутые пользователи, процессы или части системы только на уровне scope. IMPORTANT: The Capabilities section is critical. It creates the contract between proposal and specs phases. Research existing specs before filling this in. Each capability listed here will need a corresponding spec file. Every change must either declare at least one capability (new or modified) or explicitly opt out of specs: `openspec validate` rejects a change with zero deltas unless the change's `.openspec.yaml` sets `skip_specs: true`. Use `skip_specs: true` only when no spec-level behavior changes (pure refactor, tooling, docs) - specs describe behavior, so if behavior does not change, no spec should change either. Do not invent a requirement just to satisfy validation. Artifact boundary — MUST NOT include: - технологии, библиотеки, зависимости или выбранную архитектуру: эти решения появляются только после Delta Specs в Design; - API signatures, database structures, имена файлов, классов или функций: это implementation detail для Design; - implementation steps, task decomposition или verification commands: это конкретизируется в Tasks после утверждения Design. This is the foundation - specs, design, and tasks all build on this. До сохранения исследуй canonical main specs и remediation registry для audit-derived change. После записи выполни `bash specs/scripts/verify-openspec-planning.sh `: на этой стадии verifier проверяет Proposal и явно оставляет downstream validation pending. Исправь технический формат и повтори check до запроса approval; structural success не означает approval Change Owner. requires: [] - id: specs generates: "specs/**/*.md" description: Observable behavior and invariants changed by the proposal template: spec.md instruction: | Создай Delta Specs, определяющие, ЧТО наблюдаемо изменяется в системе. Spec является behavior contract, а не планом изменения кода. Good spec content: - Observable behavior users or downstream systems rely on - Inputs, outputs, and error conditions - External constraints (security, privacy, reliability, compatibility) - Scenarios that can be tested or explicitly validated Artifact boundary — MUST NOT include: - intent или scope за пределами утверждённого Proposal: сначала верни изменение в Proposal; - internal components, class/function names, files или database structures: implementation structure определяется в Design; - library, framework или infrastructure choices: alternatives и решение принадлежат Design; - step-by-step implementation, delivery sequencing или verification commands: это принадлежит Tasks; - test procedure вместо behavior scenario: scenario фиксирует наблюдаемые WHEN/THEN, а способ проверки выбирается позднее. Quick test: if the implementation can change without changing externally visible behavior, it likely does not belong in the spec. Create one spec file per capability listed in the proposal's Capabilities section. `` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path: - New capabilities: use the exact path from the proposal at `specs//spec.md`. Any path segment newly introduced in the proposal must be kebab-case. Follow the project's existing organization; do not add a new domain level when the project uses a flat layout. - Modified capabilities: use the exact existing path from `openspec/specs//` when creating the delta at `specs//spec.md`. Do not move or rename the capability. There must be at least one spec file unless the change's `.openspec.yaml` sets `skip_specs: true` (no spec-level behavior change) - `openspec validate` rejects a zero-delta change without that marker. If the proposal lists no capabilities and `skip_specs` is not set, revisit the proposal first. Delta operations (use ## headers): - **ADDED Requirements**: New capabilities - **MODIFIED Requirements**: Changed behavior - MUST include full updated content - **REMOVED Requirements**: Deprecated features - MUST include **Reason** and **Migration** - **RENAMED Requirements**: Name changes only - use FROM:/TO: format Format requirements: - Each requirement: `### Requirement: ` followed by description - Use SHALL/MUST for normative requirements (avoid should/may) - Each scenario: `#### Scenario: ` with WHEN/THEN format - **CRITICAL**: Scenarios MUST use exactly 4 hashtags (`####`). Using 3 hashtags or bullets will fail silently. - Every requirement MUST have at least one scenario. New capabilities only: start the delta spec with a `## Purpose` section - one or two sentences (50+ characters, or `openspec validate --strict` reports it as too brief) describing what the capability is for. Archive copies it into the main spec it creates; without it the new main spec is left with a `TBD ... Update Purpose after archive` placeholder to fill in by hand. Do NOT add `## Purpose` to a delta for an existing capability - that spec already has one and the delta's is ignored. To change an existing capability's Purpose - including a leftover `TBD` placeholder - edit `/openspec/specs//spec.md` directly. `planningHome.root` comes from the `openspec instructions ... --json` response. Always use it rather than a repo-relative path: it resolves to the store whenever the change lives in one - whether that came from `--store`, a project `store:` pointer, or a global default store - and to the current repository otherwise. Do not try to work out which case applies; the field already has. MODIFIED requirements workflow: 1. Locate the existing requirement in `/openspec/specs//spec.md` (the same store-aware root as above) 2. Copy the ENTIRE requirement block (from `### Requirement:` through all scenarios) 3. Paste under `## MODIFIED Requirements` and edit to reflect new behavior 4. Ensure header text matches exactly (whitespace-insensitive) Common pitfall: Using MODIFIED with partial content loses detail at archive time. If adding new concerns without changing existing behavior, use ADDED instead. Compact operation examples: ``` # ADDED in a new capability: include Purpose. ## Purpose Lets users take their data out of the product in a portable format. ## ADDED Requirements ### Requirement: User can export data The system SHALL allow users to export their data in CSV format. #### Scenario: Successful export - **WHEN** user clicks "Export" button - **THEN** system downloads a CSV file with all user data # MODIFIED: copy the complete old requirement, then edit it. ## MODIFIED Requirements ### Requirement: Session expiration The system MUST reject an expired session and preserve every surviving scenario from the main spec. #### Scenario: Expired session - **WHEN** a request uses an expired session - **THEN** the system rejects the request # REMOVED requires both fields. ## REMOVED Requirements ### Requirement: Legacy export **Reason**: Replaced by new export system **Migration**: Use new export endpoint at /api/v2/export # RENAMED changes only the heading. ## RENAMED Requirements - FROM: `### Requirement: Old name` - TO: `### Requirement: New name` ``` Specs должны быть проверяемыми, но scenario не означает автоматический unit test: уровень проверки выбирается по риску поведения. Перед записью установи явный approval Proposal из разговора. После записи выполни `bash specs/scripts/verify-openspec-planning.sh ` и исправь технические ошибки до запроса approval Delta Specs. Если обнаружено изменение intent, вернись к Proposal и инвалидируй downstream approvals вместо скрытого расширения Specs. requires: - proposal - id: design generates: design.md description: Architectural implementation approach and delivery decisions template: design.md instruction: | Создай Design, объясняющий, КАК архитектурно выполнить утверждённые Delta Specs. Artifact boundary — MUST NOT include: - новое observable behavior или invariant, отсутствующие в утверждённых Delta Specs: сначала верни изменение в Specs; - пересказ Proposal или Specs вместо архитектурных constraints и решений, необходимых для выбранного подхода; - file-by-file implementation checklist, verification commands или пошаговый список правок: это принадлежит Tasks; - будущие delivery results, commit identifiers или Completion Evidence: они фиксируются только после наблюдаемого выполнения. Обязательные разделы: - **Context**: только текущее состояние и ограничения подхода. - **Goals / Non-Goals**: технические границы, не пересказ Proposal. - **Decisions**: крупные решения, rationale и рассмотренные alternatives. - **Delivery Map**: ровно frontend, backend, specs и docs; для каждой области `affected` с ожидаемым архитектурным результатом либо `N/A` с конкретной причиной. `specs` всегда affected. Здесь же зафиксируй Contract Gate Decision для `runtime-openapi`: `required`, только когда change затрагивает обе стороны API contract, либо `N/A` с причиной. - **Risks / Trade-offs**: риск и mitigation. - **Migration Plan**: порядок поставки и rollback, если применимо. Внутри Migration Plan добавь `### Rollback Contract` с table fields. Status `required` обязателен для auth/security, data integrity/migration, public contract и другого существенно труднообратимого решения и требует Trigger, Actions, Data safety и Verification. В остальных случаях Status `N/A` требует конкретный Reason. Отдельный rollback artifact не создавай. Добавь **Solution Assessment**, если изменение вводит или существенно заменяет auth, security, storage, external integration, observability, caching, concurrency или общую infrastructure/tooling либо содержит другое дорогостоящее необратимое решение. Сравни зрелые готовые решения по fit, maturity, security, operating cost, constraints и migration cost. Custom implementation допустима только после фиксации несовместимости подходящих alternatives и принятых рисков. Не создавай отдельный artifact. **Open Questions** допустим только для неизвестного, которое не меняет Specs, выбранный подход или Tasks. Иначе остановись и запроси решение владельца до сохранения Design. Open questions are for genuinely deferrable unknowns, not decisions you skipped. If a question would change the specs, the chosen approach, or the task breakdown, resolve it now - ask the user instead of guessing. Design формируется только после явного owner approval Delta Specs. После записи выполни `bash specs/scripts/verify-openspec-planning.sh ` и исправь технические ошибки до запроса approval. Если Design показывает несовместимость с intent или behavior, остановись, вернись к самому раннему затронутому artifact и инвалидируй downstream approvals. requires: - specs - id: tasks generates: tasks.md description: Implementation checklist with trackable tasks template: tasks.md instruction: | Создай implementation checklist, достаточный для выполнения Design и Delta Specs. Это конкретное DO, а не ещё один архитектурный документ. Before writing tasks, check design.md for Open Questions. If any of them would change what gets built, resolve them with the user first - do not bake an unstated assumption into the task list. **IMPORTANT: Follow the template below exactly.** The apply phase parses checkbox format to track progress. Tasks not using `- [ ]` won't be tracked. Правила: - Группируй задачи под numbered `##` headings и располагай по dependencies. - Каждая задача MUST иметь формат `- [ ] X.Y [area/repo-name] action` (или `- [ ] X.Y [area] action`, если область представлена ровно одним репозиторием), быть выполнимой за одну рабочую сессию и указывать явный owner из `frontend`, `backend`, `specs`, `docs`, `workspace` (или их подпапок/репозиториев, например `backend/auth-service`). - Сразу после checkbox добавляй ровно по одной indented metadata line: `- **Covers:**` и `- **Verification:**`. - `Covers` содержит одну или несколько пар `` `capability-path` — `exact Requirement heading` `` либо `` `N/A` — concrete reason ``. Каждый Delta Requirement должен быть покрыт хотя бы одной task; собственные requirement IDs не вводятся. - Owner repository не может иметь статус `N/A` в Delivery Map. Cross-repository implementation разделяй; `workspace` используй только для orchestration/verification и с конкретным `N/A` Covers rationale. - Для каждой `affected` области Delivery Map должна существовать задача реализации и её canonical local gate; пустые commits запрещены. - Каждая задача MUST указывать planned verification action: команду, проверку наблюдаемого поведения или delivered artifact. - Автоматические тесты обязательны для security/privacy, денежных расчётов, data integrity/migration, concurrency, public contracts, critical journeys и подтверждённых regressions. - Не требуй отдельный unit test только из-за изменения файла. DTO без логики, declarative structures, thin adapters, прямолинейная orchestration, hygiene scripts и third-party behavior проверяются существующим integration/contract gate, если нет собственного branching, transformation, invariant или regression. - Перед custom implementation в обязательных областях включи действие по утверждённому Solution Assessment из Design. Artifact boundary — MUST NOT include: - новое observable behavior или Requirement: сначала верни изменение в Specs; - новое архитектурное решение или отклонение от утверждённого Design: сначала обнови Design; - одну задачу с несколькими owner repositories: раздели её по delivery areas/repos; - vague action без проверяемого результата: сформулируй конкретное DO и planned Verification; - ещё не наблюдённые результаты как выполненные, предполагаемые commit identifiers, archive path или post-archive Completion Evidence: такое evidence создаётся только после факта. Example: ``` ## 1. Delivery - [ ] 1.1 [backend/auth-service] Implement session rejection - **Covers:** `user-authentication` — `Expired session is rejected` - **Verification:** Run the backend canonical gate and the expiry contract test. - [ ] 1.2 [workspace] Run cross-area semantic review - **Covers:** `N/A` — verification only; no independent spec behavior. - **Verification:** Compare delivery against every approved Requirement and Scenario. ``` Reference specs for what needs to be built, design for how to build it. После записи выполни `bash specs/scripts/verify-openspec-planning.sh ` и исправь технические нарушения до запроса approval. Если Tasks требует новое behavior или architecture, не расширяй scope: вернись к Specs или Design и инвалидируй Tasks approval. requires: - design apply: requires: [ tasks ] tracks: tasks.md instruction: | Сначала проверь exact OpenSpec version contract. Работай только с change в canonical store `wealth-ledger-specs` и не создавай parallel planning root. Apply допустим только после явных approvals Proposal, Delta Specs, Design и Tasks из разговора. До реализации выполни `bash specs/scripts/verify-openspec-planning.sh `. Read context files, work through pending tasks, run each planned Verification and mark a checkbox complete only after observed success. Pause if you hit blockers or need clarification. Feedback routing: - intent/scope mismatch → Proposal; - observable behavior mismatch → Delta Specs; - architecture/rollback mismatch → Design; - decomposition/ownership/coverage mismatch → Tasks. Останови downstream work, сообщи наблюдаемое основание и инвалидируй approvals начиная с самого раннего затронутого artifact. Только механическое syntax/format исправление без изменения intent, behavior, decisions или task scope можно исправить и повторно структурно проверить без reapproval. Structural validation не заменяет semantic verification и independent read-only review. ================================================================================ FILE: proposal.md ================================================================================ ## Why ## What Changes ## Target Repositories - ``: ## Capabilities ### New Capabilities - ``: ### Modified Capabilities - ``: ## Impact ================================================================================ FILE: spec.md ================================================================================ ## Purpose ## ADDED Requirements ### Requirement: #### Scenario: - **WHEN** - **THEN** ================================================================================ FILE: design.md ================================================================================ ## Context ## Goals / Non-Goals **Goals:** **Non-Goals:** ## Decisions ## Delivery Map | Area | Status | Architectural outcome or N/A reason | | --- | --- | --- | | frontend | `affected` or `N/A` | | | backend | `affected` or `N/A` | | | specs | `affected` | | | docs | `affected` or `N/A` | | ### Contract Gate Decision | Gate | Status | Reason | | --- | --- | --- | | runtime-openapi | `required` or `N/A` | | ## Solution Assessment ## Risks / Trade-offs ## Migration Plan ### Rollback Contract | Field | Decision | | --- | --- | | Status | `required` or `N/A` | | Reason | | | Trigger | | | Actions | | | Data safety | | | Verification | | ## Open Questions ================================================================================ FILE: tasks.md ================================================================================ ## 1. - [ ] 1.1 [area/repo-name] - **Covers:** `` — `` - **Verification:** - [ ] 1.2 [area/repo-name] - **Covers:** `N/A` — - **Verification:** ## 2. - [ ] 2.1 [area/repo-name] - **Covers:** `` — `` - **Verification:** - [ ] 2.2 [workspace] - **Covers:** `N/A` — - **Verification:**