Schemas — formal

Назначение: машино-читаемые YAML frontmatter схемы для всех типов артефактов RENAR. Используются substrate-native валидаторами (CI hooks, document validators, application-level constraints) для проверки conformance. Источники: research/14-requirement-schema-draft.md (requirements), research/17-specification-schema-and-templates.md (specifications).

Этот документ — reference. Нормативные определения структуры — в standard/06-requirements-hierarchy.md, standard/07-adapt.md, standard/08-specifications.md, standard/09-test-cases.md.


1. Common frontmatter (все артефакты требований и SPEC)

Поля, общие для BR/SR/TR/UIC/AIC/INT-SR/SPEC-*:

# === Identity ===
id: "<TYPE>-NN[.N]"                   # immutable; pattern зависит от типа
title: "<short, descriptive>"
type: BR | SR | TR | UIC | AIC | INT-SR | SPEC-ARCH | SPEC-API | SPEC-DATA | SPEC-INT | SPEC-PROC | SPEC-UI | SPEC-AI | SPEC-SEC | SPEC-OPS
slug: "<kebab-case>"                  # auto-derived from title

# === Scope ===
level: system | subsystem | module
scope:
  system: "<system-id>"
  subsystem: "<subsystem-id>"         # null если level=system

# === Lifecycle ===
status: draft | review | approved | verified | deprecated | replaced | obsolete | frozen
priority: must | should | could       # MoSCoW; SAFe — через WSJF (см. BR-specific)

# === Provenance: source ===
source:
  adapt: "ADAPT-NNN"                  # canonical источник (Forward §N)
  adapt-section: "Forward §N.N"
  tz-section: "§N.N"                  # informative — для traceability до ТЗ
  document-ref: "<substrate-native-ref>"   # pinned ревизия source-документа

# === Hierarchy (дерево требований) ===
parent:
  id: "<parent-id>"                   # required для SR (→BR), TR (→SR); optional для BR
  ref: "<substrate-native-ref>"
children: []                          # auto-derived

# === Связь с SPEC (граф) ===
constrained-by: []                    # для SR — список SPEC-* типизированных ссылок
implements-spec: []                   # для TR — какие SPEC реализуются
depends-on: []                        # между SPEC

# === Verification ===
verified-by: []                       # auto-derived; список TC IDs
verifies-business-goal: ""            # optional, ссылка на BR.business-goal-id

# === AI provenance (RENAR-4+ обязательно для approved) ===
ai-provenance:
  generated-by: "<vendor>-<model>@<date>"
  prompt-template: "<template-path>@<version>"
  context-tokens: integer
  output-tokens: integer
  generation-time-ms: integer
  generated-at: "<ISO-8601>"
  human-edits: boolean                # true required для approved

# === AI cost budget (optional) ===
ai-budget:
  context-tokens-target: integer
  context-tokens-actual: integer
  output-tokens-target: integer
  output-tokens-actual: integer
  generation-time-target-ms: integer

# === Замена ===
replaces: "<old-id>"
replaced-by: "<new-id>"
deprecated-date: "<ISO date>"

# === Schema versioning ===
schema-version: "1.0"

2. BR — Business Requirement

# Extends common §1, дополнительно:

business-context:
  stakeholder: "<role>"               # required
  business-goal: "<short statement>"  # required
  kpi-impact:
    - kpi: "<KPI name>"
      direction: increase | decrease
      target: "<measurable>"

business-outcome:                     # required для QG-4
  measurement-type: kpi | survey | observation | usage
  kpi-name: "<KPI>"
  measurement-method: "<how>"
  baseline-value: number
  baseline-measured-at: "<ISO date>"
  target-value: number
  target-met-by: "<ISO date>"
  current-value:
    value: number
    measured-at: "<ISO date>"
    achievement: "<percent>"

prioritization:
  framework: WSJF | RICE | MoSCoW
  wsjf-score: number
  prioritized-at: "<ISO date>"
  prioritized-by: "<role>"

data-classification:
  contains-pii: boolean
  contains-financial: boolean
  contains-health: boolean
  contains-children-data: boolean
  retention-days: integer
  data-residency: ["RU" | "EU" | "US" | ...]

compliance:
  - { standard: "ISO 27001:2022", control: "<id>", rationale: "..." }
  - { standard: "GDPR", article: "Art.NN" }
  - { standard: "ФЗ-152", article: "ст.NN" }

ai-act:
  risk-class: prohibited | high | limited | minimal
  rationale: "<reason>"
  high-risk-domain: boolean

3. SR — System Requirement

# Extends common §1, дополнительно:

parent:
  id: "BR-NN"                         # required

derived-from-adapt: "ADAPT-NNN §N.N"  # canonical источник
constrained-by:                       # типизированные рёбра к SPEC-*
  - "SPEC-UI-NN"
  - "SPEC-API-NN"
  - "SPEC-DATA-NN"
  - "SPEC-SEC-NN"

quality-characteristic:               # ISO/IEC 25010
  - functional-suitability
  - performance-efficiency
  - compatibility
  - usability
  - reliability
  - security
  - maintainability
  - portability

# Inherited from parent BR (если применимо):
# data-classification, compliance, ai-act

4. TR — Task Requirement

# Extends common §1, дополнительно:

parent:
  id: "SR-NN"                         # required

implements-spec: []                   # SPEC-* которые реализуются этой задачей
estimated-effort: "<short statement>" # optional, free-form

5. SPEC-* common schema

Все 9 типов SPEC делят общую структуру (см. §1) + следующие SPEC-specific поля:

type: SPEC-ARCH | SPEC-API | SPEC-DATA | SPEC-INT | SPEC-PROC | SPEC-UI | SPEC-AI | SPEC-SEC | SPEC-OPS

referenced-by: []                     # auto-derived; SR/TR/SPEC ссылающиеся на этот SPEC
depends-on: []                        # SPEC от которых этот зависит
compliance-refs: []                   # ISO / GDPR / ФЗ-152 / AI Act / NIST AI RMF

Обязательные разделы body:

## Назначение
## Scope (входит / не входит)
## <Type-specific sections — см. §6>
## Связь с требованиями
## Связь с другими SPEC
## Verification
## Open questions

6. SPEC type-specific extensions

6.1 SPEC-ARCH — Architecture

arch-style: monolith | microservices | modular-monolith | serverless | hybrid
deployment-model: cloud | on-prem | hybrid | edge
tech-stack:
  languages: []
  frameworks: []
  data-stores: []
  message-brokers: []
quality-attributes:
  - { name: latency, target: "p95 < 200ms" }
  - { name: availability, target: "99.9%" }

Industry reference: arc42, C4 model, ISO/IEC/IEEE 42010.

6.2 SPEC-API — API Contract

api-style: rest | graphql | grpc | websocket | async-events
api-version: "v1.2.0"
versioning-strategy: url-path | header | query-param | content-negotiation
authentication: bearer-jwt | api-key | oauth2 | mtls | none
rate-limits:
  - { endpoint: "*", limit: "1000/min/key" }
contract-file:
  format: openapi-3.1 | asyncapi-2.6 | proto3
  location: "contracts/<name>.yaml"

Industry reference: OpenAPI 3.1, AsyncAPI 2.6, gRPC IDL.

6.3 SPEC-DATA — Data Model

data-style: relational | document | graph | columnar | hybrid
storage-engine: postgresql | mysql | couchdb | mongodb | clickhouse | ...
schema-version: "1.4.0"
pii-classification:
  - { entity: User, fields: [email, phone], level: PII-high }
retention-policies:
  - { entity: Order, period: "7 years", basis: "tax law" }
migration-strategy: forward-only | reversible | dual-write

Industry reference: ISO/IEC 11179, JSON Schema.

6.4 SPEC-INT — Integration

integration-pattern: request-response | event-driven | message-queue | webhook | file-transfer
direction: outbound | inbound | bidirectional
counterparty:
  system: "<external-system-name>"
  contract-owner: "<team-or-vendor>"
  contract-ref: "<external-spec-url>"
sla:
  availability: "99.5%"
  latency-p95: "500ms"
  fallback: "queue + retry; manual reconciliation after 24h"
idempotency: guaranteed | best-effort | none

Industry reference: Enterprise Integration Patterns (Hohpe), ISO/IEC 19944. Заменяет legacy INT-SR.

6.5 SPEC-PROC — Process / Workflow

process-style: bpmn | state-machine | saga | choreography | orchestration
state-count: integer
participants:
  - { role: customer, system: client-portal }
  - { role: agent, system: back-office }
sla:
  end-to-end: "2 business hours"
compensation: defined | not-applicable | manual

Industry reference: BPMN 2.0 (OMG), ISO/IEC 19510, Saga pattern.

6.6 SPEC-UI — UI / UX

ui-platform: web | mobile-ios | mobile-android | desktop | tv | embedded
target-users:
  - { role: end-customer, persona: "ADAPT-NNN §X.Y" }
design-system: "<reference-or-internal>"
accessibility-level: WCAG-A | WCAG-AA | WCAG-AAA
i18n: required | not-required
mockup-links:
  - { tool: figma, url: "<link>", version: "v3" }
baseline-images:
  - "ai-concepts/baselines/SPEC-UI-NN-screen-01.png"

Industry reference: WCAG 2.2, Material Design / Apple HIG. Заменяет legacy UIC.

6.7 SPEC-AI — AI / ML

ai-pattern: rag | fine-tuning | prompt-engineering | tool-use | multi-agent | embedding-only
production-model:
  vendor: anthropic | openai | google | local
  model: "<model-name>"
  version: "<exact-version>"
judge-model:                          # ОБЯЗАН отличаться от production
  vendor: "<different-vendor>"
  model: "<different-model>"
context-strategy:
  embedding-model: "<model>"
  chunk-size: integer
  chunk-overlap: integer
  vector-store: pinecone | weaviate | pgvector | qdrant
eval-strategy:
  metric: accuracy | f1 | rouge | custom-rubric
  threshold: number
  baseline-dataset: "<path>"
cost-budget:
  tokens-per-request-target: integer
  tokens-per-request-ceiling: integer
  monthly-budget-usd: number

Industry reference: ISO/IEC 23894, NIST AI RMF. Заменяет legacy AIC. Изоляция: judge-model.vendor ≠ production-model.vendor (нормативно).

6.8 SPEC-SEC — Security

security-domains:
  - authentication
  - authorization
  - data-protection
  - audit
  - secrets-management
auth-model:
  authn: jwt-bearer | oauth2-pkce | mtls | passkey
  authz: rbac | abac | relbac
data-classification:
  - { class: PII-high, fields: [...] }
  - { class: PCI, fields: [...] }
threat-model-method: STRIDE | PASTA | OCTAVE
compliance:
  - ISO-27001
  - GDPR
  - ФЗ-152
  - PCI-DSS-4

Industry reference: STRIDE (Microsoft), OWASP ASVS 4.0, ISO/IEC 27001, NIST 800-53.

6.9 SPEC-OPS — Operations

deployment-style: kubernetes | vm | serverless | docker-compose | bare-metal
environments:
  - { name: dev, purpose: development, scale: minimal }
  - { name: staging, purpose: integration-testing, scale: half-prod }
  - { name: prod, purpose: production, scale: full }
slo:
  availability: "99.9%"
  error-budget-month: "43m"
  latency-p95: "300ms"
observability:
  logs: elastic | loki | cloudwatch
  metrics: prometheus | datadog | cloudwatch
  traces: jaeger | tempo | x-ray
disaster-recovery:
  rto: "<duration>"
  rpo: "<duration>"

Industry reference: Google SRE Book, ITIL v4, ISO/IEC 20000.


7. ADAPT schema

ADAPT — отдельный артефакт (см. standard/07-adapt.md, research/18-adapt-document.md).

# === Identity ===
id: ADAPT-NNN                         # immutable; sequential per project
title: "Адаптация ТЗ <name>"
type: ADAPT

# === Source ===
source-tz:
  id: TZ-YYYY-NNN
  signed-date: "<ISO-date>"
  signed-by-client: "<name-role>"
  document-ref: "<substrate-native-ref>"
parent-adapt:                         # для delta-ADAPT; null для main
  id: ADAPT-NNN
  delta-tz: TZ-YYYY-NNN

# === Lifecycle ===
status: draft | review | approved | frozen | obsolete
created: "<ISO-date>"
last-updated: "<ISO-date>"

approval:                             # required для approved
  client-signature:
    signed-by: "<name>"
    role: "<role>"
    organization: "<client-org>"
    signed-at: "<ISO-datetime>"
    signature-ref: "<substrate-native-ref>"
  architect-signature:
    signed-by: "<name>"
    role: architect
    signed-at: "<ISO-datetime>"

# === Auto-derived ===
generates-requirements: []            # BR/SR выведенные из этого ADAPT
generates-specs: []                   # SPEC-* выведенные
open-questions-count: integer         # должен быть 0 для approved
resolved-questions-count: integer

# === AI provenance ===
ai-provenance:
  generated-by: "<vendor>-<model>@<date>"
  prompt-template: "<template-path>@<version>"
  context-tokens: integer
  output-tokens: integer
  human-edits: boolean                # true required для approved

Backward записи (внутри body):

# Каждая B-NNN запись:
id: B-NNN                             # immutable
category: contradiction | gap | hidden-assumption | feasibility | regulatory | terminology | scope
status: open | asked-to-client | answered | resolved | frozen
tz-section: "§N.N"
description: "..."
asked-to-client: "<ISO-date>"
client-answer:
  signed-by: "<name>"
  signed-at: "<ISO-datetime>"
  channel: email | docusign | zoom-transcript | written-letter
  text: "..."
resolution: "..."                     # как ответ интегрирован в Forward

8. TC — Test Case

# === Identity ===
id: "TC-NN[.N]"
title: "<descriptive>"
level: TC
type: system | acceptance | ux | eval | contract

# === Lifecycle ===
status: draft | ready | passing | failing | obsolete

# === Verification mapping ===
verifies:                             # required, ≥1
  - id: "<requirement-id>"            # SR/BR/SPEC-*
    ref: "<substrate-native-ref>"
    requirement-version: "<semver>"   # immutable lock to req version

negative: boolean                     # required: pos или neg

# === Test specification ===
prerequisites: ["<condition>", ...]
environment: dev | staging | prod | eval

# === Automation ===
automation:
  status: automated | manual-pending
  location: "<path-to-implementation>"
  runner: pytest | jest | go-test | playwright | vlm-judge | ragas | pact | other
  manual-pending-until: "<ISO date>"  # required если status=manual-pending
  manual-pending-reason: "<why>"

# === Last run (bot-only) ===
last-run:
  date: "<ISO timestamp>"
  result: pass | fail | skipped | n/a
  ci-run-url: "<URL>"
  agent-run-id: "<id>"
  requirement-version: "<semver>"     # должна совпадать с verifies[].requirement-version
  judge-report: "<for ux/eval>"

# === UX-specific (type=ux) ===
ux:
  persona: "<role>"
  scenario-ref: "<SPEC-UI reference>"
  device: desktop | mobile | tablet
  viewport: "<WxH>"
  mockup-baseline: "<path>"
  vlm-judge:
    model: "<judge-model>"
    pass-criteria: ["<criterion>", ...]
    fail-criteria: ["<criterion>", ...]

# === Eval-specific (type=eval) ===
eval:
  dataset:
    location: "<path>"
    version: "<semver>"
    size: integer
  metrics:
    - { name: "<metric>", method: "<how>", threshold: "<expr>" }
  baseline:
    run-id: "<id>"
    "<metric>": number
  regression-rule: "<expression>"

# === Inherited ===
ai-provenance: { ... }

9. Validation rules (cross-field)

Не выражаемые в чистой JSON Schema, требуют custom validator:

ПравилоОписание
ID immutableПри изменении файла поле id не меняется. Substrate-нативная проверка: diff на ID.
parent existsДля SR — parent BR существует и в статусе ≥ approved.
source.adapt approvedДля BR/SR/SPEC — ADAPT в source.adapt имеет статус approved или frozen.
verified-by consistencyTCs в verified-by имеют verifies[].id совпадающий с этим артефактом.
requirement-version lockTC.last-run.requirement-version совпадает с verifies[].requirement-version.
derived-from-adapt only for SR/SPECПоле допустимо только в SR и SPEC-*; не в BR/TR.
AIC/SPEC-AI requires ai-actДля AI-артефакта поле ai-act.risk-class обязательно.
Data residency consistencyЕсли SR.data-classification.data-residency includes RU, parent BR то же.
Compliance hierarchySR не может иметь compliance вне набора parent BR (или нужно явное extension justification).
TC automated requires locationautomation.status: automatedautomation.location непустое.
Negative TC mandatoryНа каждый SR существует TC с negative: true (QG-2 verified-by-TC требование, RENAR Core Правило 4).
ADAPT open-questions == 0 for approvedApproval ADAPT блокируется, пока есть open или asked-to-client backward записи.
Judge isolation (SPEC-AI)judge-model.vendorproduction-model.vendor.
SPEC depends-on acyclicГраф depends-on между SPEC — DAG (нет циклов).

10. Substrate isomorphism

Те же артефакты на разных substrate. Mapping для git (YAML frontmatter) ↔ Raven (документная БД):

Поле (canonical)git (YAML frontmatter)Raven (CouchDB doc)
idid_id = <project>:<doc-type>:<slug>, поле slug
type: BRtype: BRlevel: "BT"
type: SPEC-APItype: SPEC-APIdoc_type: "spec_api"
parent.idparent.idparent
children(auto-derived)children (auto-derived)
statusstatusstatus
priorityprioritypriority
source.adaptsource.adaptcreated_from_adapt
constrained-by[]constrained-byconstrained_by (subdoc array)
verified-by[](auto-derived)linked_tests
ai-provenance.*nested objectnested subdocument
compliancecompliance arraycompliance subdoc
data-classificationnested objectnested subdoc
business-outcomenested objectnested subdoc
replaces / replaced-bystring IDreplaces / replaced_by

Migration script git ↔ Raven использует эту таблицу. Substrate-нативные имена полей могут отличаться, но семантика и invariants сохраняются через capabilities V1-V6 (см. 01-glossary.md §2.7).


11. Schema versioning

Каждый артефакт имеет поле schema-version (semver). При несовпадении версии файла и текущей schema validator предлагает migration.

ИзменениеBump
Новое необязательное полеminor (1.0 → 1.1)
Новое обязательное полеmajor (1.0 → 2.0) + migration script
Удаление поляmajor + migration script
Изменение enumminor если добавление, major если удаление
Переименование поляmajor + migration script

Текущая версия schemas: 1.0-draft (Phase 7 наполнение).


12. JSON Schema fragment example (BR)

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://renar.tech/schemas/br.json",
  "title": "Business Requirement",
  "type": "object",
  "required": ["id", "title", "type", "status", "priority", "source", "ai-provenance"],
  "properties": {
    "id": {
      "type": "string",
      "pattern": "^BR-[0-9]{2}(\\.[0-9]+)?$"
    },
    "title": { "type": "string", "minLength": 5, "maxLength": 100 },
    "type": { "const": "BR" },
    "status": {
      "enum": ["draft", "review", "approved", "verified", "deprecated", "replaced", "obsolete"]
    },
    "priority": { "enum": ["must", "should", "could"] },
    "source": {
      "type": "object",
      "required": ["adapt"],
      "properties": {
        "adapt": { "type": "string", "pattern": "^ADAPT-[0-9]{3}(-delta-[0-9]+)?$" },
        "adapt-section": { "type": "string" },
        "tz-section": { "type": "string" }
      }
    },
    "ai-provenance": {
      "type": "object",
      "required": ["generated-by", "generated-at"],
      "properties": {
        "generated-by": {
          "type": "string",
          "pattern": "^[a-z]+-[a-z0-9-]+@[0-9]{4}-[0-9]{2}-[0-9]{2}$"
        },
        "human-edits": { "type": "boolean" }
      }
    }
  }
}

Аналогичные JSON Schemas для SR/TR/SPEC-*/TC/ADAPT — в reference/schemas/ (TODO Phase 8).


Schemas reference RENAR 1.0-draft — см. также 01-glossary.md, standard/06-09 для нормативных определений.