Files
plba_v2/openspec/schemas/function-driven/schema.yaml
T

267 lines
20 KiB
YAML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
name: function-driven
version: 1
description: Иерархические capabilities, завершённые технические функции и краткие use cases с локальными FR
artifacts:
- id: proposal
generates: proposal.md
description: Initial proposal document outlining the change
template: proposal.md
instruction: |
Create the proposal document that establishes WHY this change is needed.
Sections:
- **Why**: 1-2 sentences on the problem or opportunity. What problem does this solve? Why now?
- **What Changes**: Bullet list of changes. Be specific about new capabilities, modifications, or removals. Mark breaking changes with **BREAKING**.
- **Capabilities**: Identify which specs will be created or modified:
- **New Capabilities**: List capabilities being introduced. Each becomes a new `specs/<capability-path>/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**: Affected code, APIs, dependencies, or systems.
IMPORTANT: The Capabilities section is critical. It creates the contract between
proposal and specs phases. Research existing specs before filling this in:
run `openspec list --specs` for the project's capability inventory, then
`openspec show "<spec-id>" --type spec --json --no-scenarios` for any that
look related - that returns a capability's purpose and requirement texts
without pulling whole spec files into context. Append `--store "<id>"` to
both commands only for a registered standalone store, and keep `--type
spec`: a change and a spec sharing a name is otherwise an ambiguous-item
error. `openspec list` without `--specs` lists in-flight changes, not
specs - it never shows what the project already covers. Reuse an existing
capability's exact path instead of introducing a near-duplicate name.
The filtered read is only an overview. Before deciding what is already
covered or what should change, read each relevant spec in full, including
scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
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.
Keep it concise (1-2 pages). Focus on the "why" not the "how" -
implementation details belong in design.md.
This is the foundation - specs, design, and tasks all build on this.
requires: []
- id: specs
generates: "specs/**/*.md"
description: Detailed specifications for the change
template: spec.md
instruction: |
Создай спецификации наблюдаемого поведения и устойчивых контрактов.
Правила ниже применяются к master specs и к полным блокам ADDED/MODIFIED
в delta specs. Это пользовательский формат без Gherkin.
Иерархия и границы:
- Capability имеет отдельную бизнес-функцию или понятный результат.
- Сохраняй полный иерархический путь, например orders/snapshot-sync.
- Один Requirement описывает одну завершённую техническую функцию.
- Не дроби один процесс на Requirements для чтения, валидации и записи.
- Каждый Requirement имеет стабильный ID вида CFG.AS-01 и ровно один Scenario.
- Префикс Requirement уникален для пути capability и регистрируется в
capability-codes.md: configuration/application-settings получает CFG.AS.
Номер Requirement уникален внутри capability, что делает полный ID
уникальным в проекте. Существующие, ещё не рефакторенные Requirements
могут сохранять старый ID.
- Заголовки OpenSpec: ### Requirement: и #### Scenario:.
- Описание Requirement содержит SHALL/MUST и наблюдаемый результат.
- Включай только сведения, меняющие наблюдаемое поведение, устойчивый
контракт или обязательное техническое ограничение. Удаляй повторы,
пояснения и формулировки, которые не меняют поведение и не снимают
неоднозначность контракта.
Scenario:
- Поддерживаются два формата Use case: полный и сокращенный. Автор
выбирает формат по ситуации, независимо от типа FR и того, что
описывается: runtime-процесс, БД, API, UI или другая часть системы.
- Полный Use case содержит разделы Участники, Предусловия,
Основной поток, Альтернативы и ошибки, Результат, Коды завершения —
в таком порядке.
- Сокращенный Use case содержит только раздел `##### Основной поток`;
каждый шаг кратко описывает аспект и ссылается на FR. Он не содержит
участников, предусловий, альтернатив и ошибок, результата или кодов
завершения и не задаёт отдельные runtime-развилки.
- В обычном сценарии Назначение опционально; добавляй только если оно
сообщает сведения, которых нет в заголовке. Контекст отсутствует.
- Основной поток — нумерованные короткие шаги «Что делаем — как делаем».
- Шаг runtime-сценария может назвать действие, endpoint или способ записи
и сослаться на FR.
- Каждый HTTP endpoint описывай в отдельном Requirement с полным Use case.
Сложные правила шага выноси в FR и связывай со сценарием ссылками.
- Основной поток и альтернативы обычного сценария включают коды
завершения, если они определены для этой функции.
- Таблицы полей, алгоритмы, SQL, JSON-примеры, параметры запросов, тексты
сообщений и дальнейшая логика располагаются за пределами Scenario.
- Единственная таблица Scenario — Коды завершения с колонками
Код, Смысл, Связанные FR. Код имеет формат UPPER_SNAKE_CASE.
- Код сам сообщает смысл итога; дополнительный stage или свободный текст
не должен требоваться для понимания кода. События промежуточных шагов
не являются кодами завершения. Не создавай код для каждой диагностики.
- Каждая запись кода ссылается на локальные FR, определяющие дальнейшую
логику, текст или применимые правила результата.
- Каждый шаг, альтернатива и абзац сценария — не более 240 знаков
содержательного текста без адресов Markdown-ссылок.
- Не используй Gherkin GIVEN/WHEN/THEN/AND/BUT.
Функциональные требования:
- После Scenario, на уровне ####, идёт раздел Функциональные требования.
- Внутри: ##### CFG.AS-01.FR-01: <название>, ##### CFG.AS-01.FR-02 [DB]: <название>, ##### CFG.AS-01.FR-03 [API]: <название> и так далее.
- ID FR содержит ID Requirement и локальный номер: <requirement-id>.FR-NN.
Номер начинается с FR-01 в каждом Requirement.
- FR содержит отдельное понятное правило или связанный контракт; не дроби
связную логику на множество атомарных FR.
- Обычный FR без метки описывает логику, правила или последовательность
шагов. Типизированный FR помечай сразу после ID меткой [DB], [API]
или [UI]; метка не входит в ID и не меняет slug ссылки.
- [DB] описывает структуру БД по паттерну таблицы. FR [API] описывает
контракт сообщения или технического лога. Контракт HTTP endpoint
размещается в отдельном разделе CONTRACT. [UI] описывает требования к
UI; детальный паттерн будет добавлен отдельно.
- Для FR [DB] с таблицей БД следуй паттерну
`openspec/schemas/function-driven/patterns/database-table.md`.
- Для сериализуемого контракта сообщения в FR [API] следуй паттерну
`openspec/schemas/function-driven/patterns/message-contract.md`.
- Контракт HTTP endpoint не оформляй отдельными FR. После раздела
Функциональные требования добавляй завершающий раздел CONTRACT с
подразделами Request и Response в таком порядке. В Request указывай
один HTTP-метод и путь; для отсутствующего тела явно отмечай это.
Таблицы тела запроса и ответа оформляй по паттерну message-contract.md.
- В таблице Response раздела CONTRACT укажи для каждого поля источник
значения или правило его формирования в последней колонке.
- В таблице response-контракта FR [API] укажи для каждого поля источник
значения или правило его формирования в колонке «Формирование значения».
- Не добавляй HTML-якоря вида <a id="..."></a>. Markdown генерирует
якоря из заголовков Requirement и FR.
- Ссылайся на FR по полному ID и slug его заголовка, например
[CFG.AS-01.FR-01](#cfgas-01fr-01-правило-обработки). Полный ID
используется и для ссылки внутри Requirement, и для ссылки на другой
Requirement.
- Сохраняй заголовки FR стабильными; при переименовании обновляй ссылки.
- Сохраняй существующие ID. При изменении FR сохраняй его номер;
новые FR добавляй в конец. Порядок первого документа последовательный.
- Для кодов укажи в FR тексты сообщений и поведение, включая отсутствие
сообщения/действия, если это часть контракта. Параметры сообщений
являются данными, а не скрытым значением кода.
- Если смысловой код спецификации отличается от действующего runtime,
явно опиши соответствие и статус реализации в FR. Не утверждай,
что новый код или текст уже возвращается приложением.
Работа с OpenSpec:
- Создай specs/<capability-path>/spec.md для каждой capability из proposal.
- Master spec использует шаблон templates/main-spec.md этой схемы.
- Delta spec использует templates/spec.md и разделы ## ADDED Requirements,
## MODIFIED Requirements, ## REMOVED Requirements, ## RENAMED Requirements.
- Для новой capability delta начинается с ## Purpose (50+ знаков).
Для существующей capability Purpose в delta не добавляй.
- MODIFIED содержит полный Requirement: ID, один Scenario и все FR.
Его заголовок должен совпадать с заголовком master spec.
- REMOVED содержит Reason и Migration; RENAMED использует FROM/TO.
Это операции над требованиями, не сценарии технических функций.
- При копировании блоков в delta сохраняй ID Requirements, номера и
заголовки FR, на которые ссылаются по slug. Если ссылка ведёт в
неизменённый Requirement master spec, проверяй delta с --base <master-spec>.
- Не создавай delta для чистого форматирования, tooling или рефакторинга.
Для change без изменения поведения используй skip_specs: true.
- Проверь schema через openspec schema validate function-driven.
- Проверь spec через openspec validate и отдельно через
python3 openspec/schemas/function-driven/validate_format.py
--require-qualified-ids <spec-path>. Для неизменённых legacy specs
этот флаг не нужен.
Стандартный валидатор OpenSpec не проверяет все правила этого формата.
requires:
- proposal
- id: design
generates: design.md
description: Technical design document with implementation details
template: design.md
instruction: |
Create the design document that explains HOW to implement the change.
When to include design.md (create only if any apply):
- Cross-cutting change (multiple services/modules) or new architectural pattern
- New external dependency or significant data model changes
- Security, performance, or migration complexity
- Ambiguity that benefits from technical decisions before coding
Sections:
- **Context**: Only the current state and constraints needed to explain the approach. Reference the proposal for motivation instead of restating it (e.g., "See proposal.md - Why").
- **Goals / Non-Goals**: What this design achieves and explicitly excludes. Don't restate the proposal's scope - add only design-level boundaries.
- **Decisions**: Key technical choices with rationale (why X over Y?). Include alternatives considered for each decision.
- **Risks / Trade-offs**: Known limitations, things that could go wrong. Format: [Risk] → Mitigation
- **Migration Plan**: Steps to deploy, rollback strategy (if applicable)
- **Open Questions**: Unknowns that can safely be answered later without
changing the specs, the approach, or the task breakdown. Omit if none.
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.
Focus on architecture and approach, not line-by-line implementation.
The proposal covers why and what; design covers how. Reference the
proposal for motivation and, once written, the specs for requirements -
if a section would only restate them, point to them instead.
Good design docs explain the "why" behind technical decisions.
requires:
- proposal
- id: tasks
generates: tasks.md
description: Implementation checklist with trackable tasks
template: tasks.md
instruction: |
Create the task list that breaks down the implementation work.
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. A box holding only `x` counts as done,
upper or lower case and with any spacing, so `- [ x]` is done too. Every
other marker, including `- [~]`, `- [-]` and an empty `- []`, reads as
unfinished. A line with no checkbox is not tracked at all.
Guidelines:
- Group related tasks under ## numbered headings
- Each task MUST be a checkbox: `- [ ] X.Y Task description`
- Tasks should be small enough to complete in one session
- Order tasks by dependency (what must be done first?)
- Each task MUST state how to verify completion (a test, command,
observable behavior, or delivered artifact). Put the verification in
that task's checkbox description. Use a separate verification task only
when it checks broader integration or system behavior that spans
multiple implementation tasks.
Example:
```
# Tasks
## 1. Setup
- [ ] 1.1 Create new module structure and verify expected files are present
- [ ] 1.2 Add dependencies to package.json and verify package installation succeeds
## 2. Core Implementation
- [ ] 2.1 Implement data export function and verify the export test passes
- [ ] 2.2 Add CSV formatting utilities and verify unit tests cover quoting and delimiters
```
Reference specs for what needs to be built, design for how to build it.
requires:
- specs
- design
apply:
requires: [ tasks ]
tracks: tasks.md
instruction: |
Read context files, work through pending tasks, mark complete as you go.
Pause if you hit blockers or need clarification.