From af81424fc24c156203f5639523b6fb7feac93546 Mon Sep 17 00:00:00 2001 From: Suslov-MD Date: Sat, 28 Nov 2026 19:02:34 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=D1=81=D1=85=D0=B5=D0=BC=D1=8B=20=D1=8F?= =?UTF-8?q?=D0=B4=D1=80=D0=B0=20=D1=81=D0=BF=D0=B5=D1=86=D0=B8=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B8=20=D0=B6=D1=83=D1=80?= =?UTF-8?q?=D0=BD=D0=B0=D0=BB=20=D0=BD=D0=BE=D1=80=D0=BC=D0=B0=D1=82=D0=B8?= =?UTF-8?q?=D0=B2=D0=BD=D1=8B=D1=85=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B9=20(BHL-010,=20BHL-016)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JSON Schema 2020-12 для Domain, Capability, Parameter, Atomic Requirement и Normative Change; level/lifecycle/статус библиотеки раздельно; ID dom-, cap-, req-, param-, chg- валидируются паттернами. Канонический журнал — spec/CHANGELOG.yaml (требования ссылаются history_ref, история не дублируется). Черновик SemVer-политики — D-039 (proposed). Тесты ajv: 7, включая отрицательные фикстуры. --- ...и-BHS-на-согласование-до-первого-релиза.md | 30 ++++ ...ктировать-JSON-Schema-ядра-спецификации.md | 9 +- ...ых-изменений-и-черновик-SemVer-политики.md | 9 +- package-lock.json | 59 +++++++ package.json | 1 + spec/CHANGELOG.yaml | 5 + spec/schemas/capability.schema.json | 23 +++ spec/schemas/domain.schema.json | 18 ++ spec/schemas/normative-change.schema.json | 31 ++++ spec/schemas/parameter.schema.json | 87 ++++++++++ spec/schemas/requirement.schema.json | 129 ++++++++++++++ tests/spec-schemas.test.mjs | 157 ++++++++++++++++++ 12 files changed, 556 insertions(+), 2 deletions(-) create mode 100644 backlog/decisions/decision-039 - D-039.-Черновик-SemVer-политики-BHS-на-согласование-до-первого-релиза.md create mode 100644 spec/CHANGELOG.yaml create mode 100644 spec/schemas/capability.schema.json create mode 100644 spec/schemas/domain.schema.json create mode 100644 spec/schemas/normative-change.schema.json create mode 100644 spec/schemas/parameter.schema.json create mode 100644 spec/schemas/requirement.schema.json create mode 100644 tests/spec-schemas.test.mjs diff --git a/backlog/decisions/decision-039 - D-039.-Черновик-SemVer-политики-BHS-на-согласование-до-первого-релиза.md b/backlog/decisions/decision-039 - D-039.-Черновик-SemVer-политики-BHS-на-согласование-до-первого-релиза.md new file mode 100644 index 0000000..805df4e --- /dev/null +++ b/backlog/decisions/decision-039 - D-039.-Черновик-SemVer-политики-BHS-на-согласование-до-первого-релиза.md @@ -0,0 +1,30 @@ +--- +id: decision-039 +title: D-039. Черновик SemVer-политики BHS (на согласование до первого релиза) +date: '2026-11-28T16:01:00Z' +status: proposed +--- +## Context + + +D-030 требует формальной политики до первого релиза. Нужна семантика 0.x: ужесточение, ослабление, добавление, удаление; совместимость схем; независимые версии CLI, спецификации и реализаций (D-003, D-011). Неизменяемость опубликованных релизов. + + +## Decision + + +Версии спецификации, CLI и референсных реализаций независимы; версия спецификации публикуется в Release Manifest. Спецификация 0.x.y: patch — CLARIFIED и правки не-нормативных частей без изменения обязанностей; minor — ADDED, STRENGTHENED, RELAXED, DEPRECATED (для STRENGTHENED/REMOVED обязателен migration); REMOVED в 0.x допускается только с migration и предварительным DEPRECATED. 1.0.0 — фиксация ядра модели; далее major — REMOVED/STRENGTHENED без migration, minor — совместимые дополнения и ужесточения с migration, patch — уточнения. Схемы: добавление необязательных полей — patch, новая обязательность или изменение семантики поля — minor/major по смыслу; версии схем следуют версии спецификации. Опубликованный релиз неизменяем: исправление — новый релиз (D-011). CLI версионируется независимо; совместимость с версиями спецификации описывает матрица поддержки. + + +## Consequences + + +Потребитель по номеру версии понимает характер нормативных изменений; миграция обязана там, где поведение может сломаться; независимость версий позволяет выпускать CLI чаще спецификации. + + +## Alternatives + + +Единая версия всего артефакта — противоречит независимости D-003; календарное версионирование — не передаёт характер изменений; политика «только major при любом ужесточении» — блокировала бы рост 0.x. + + diff --git a/backlog/tasks/bhl-010 - Спроектировать-JSON-Schema-ядра-спецификации.md b/backlog/tasks/bhl-010 - Спроектировать-JSON-Schema-ядра-спецификации.md index 8f7da17..f2290d5 100644 --- a/backlog/tasks/bhl-010 - Спроектировать-JSON-Schema-ядра-спецификации.md +++ b/backlog/tasks/bhl-010 - Спроектировать-JSON-Schema-ядра-спецификации.md @@ -1,9 +1,10 @@ --- id: BHL-010 title: Спроектировать JSON Schema ядра спецификации -status: To Do +status: Done assignee: [] created_date: '2026-11-28T14:25:12Z' +updated_date: '2026-11-28T15:56:58Z' labels: [] milestone: m-1 dependencies: @@ -35,3 +36,9 @@ ordinal: 10000 - [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов - [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг + +## Final Summary + + +spec/schemas: domain, capability, parameter, requirement (draft 2020-12, additionalProperties:false). Покрыты все поля §5 задания; level (RFC 2119) / lifecycle / статус библиотеки — раздельные поля без смешанных enum; ID dom-/cap-/req-/param- детерминированно валидируются паттернами. Тесты tests/spec-schemas.test.mjs: 5 (позитивные фикстуры, отрицательные: статус-в-level, уровень-в-lifecycle, чужие поля, несогласованные ограничения параметров). npm run quality зелёный. + diff --git a/backlog/tasks/bhl-016 - Спроектировать-журнал-нормативных-изменений-и-черновик-SemVer-политики.md b/backlog/tasks/bhl-016 - Спроектировать-журнал-нормативных-изменений-и-черновик-SemVer-политики.md index 5fde400..b7b7341 100644 --- a/backlog/tasks/bhl-016 - Спроектировать-журнал-нормативных-изменений-и-черновик-SemVer-политики.md +++ b/backlog/tasks/bhl-016 - Спроектировать-журнал-нормативных-изменений-и-черновик-SemVer-политики.md @@ -1,9 +1,10 @@ --- id: BHL-016 title: Спроектировать журнал нормативных изменений и черновик SemVer-политики -status: To Do +status: Done assignee: [] created_date: '2026-11-28T14:25:27Z' +updated_date: '2026-11-28T16:02:33Z' labels: [] milestone: m-1 dependencies: @@ -34,3 +35,9 @@ ordinal: 16000 - [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов - [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг + +## Final Summary + + +spec/schemas/normative-change.schema.json: классы ADDED/STRENGTHENED/RELAXED/CLARIFIED/DEPRECATED/REMOVED, версия релиза, ссылка на затронутые требования, факультативные migration/motivation. Канонический источник — spec/CHANGELOG.yaml (изменения: [], требования ссылаются history_ref). Черновик SemVer-политики — решение D-039 (proposed, на согласование до первого релиза). Тесты: 7 в spec-schemas; npm run quality зелёный. + diff --git a/package-lock.json b/package-lock.json index 9f92451..b196875 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.2.0", "devDependencies": { "@earendil-works/pi-coding-agent": "1.4.0", + "ajv": "^8.20.0", "backlog.md": "^1.57.4", "marked": "18.1.1", "yaml": "2.9.1" @@ -815,6 +816,23 @@ "node": ">= 20" } }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, "node_modules/backlog.md": { "version": "1.57.4", "resolved": "https://registry.npmjs.org/backlog.md/-/backlog.md-1.57.4.tgz", @@ -1062,6 +1080,13 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, "node_modules/fast-sha256": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", @@ -1069,6 +1094,23 @@ "dev": true, "license": "Unlicense" }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fetch-blob": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", @@ -1322,6 +1364,13 @@ "node": ">=16" } }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/jwa": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", @@ -1591,6 +1640,16 @@ "dev": true, "license": "MIT" }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/retry": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", diff --git a/package.json b/package.json index 5cc3b24..875fa4d 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ }, "devDependencies": { "@earendil-works/pi-coding-agent": "1.4.0", + "ajv": "^8.20.0", "backlog.md": "^1.57.4", "marked": "18.1.1", "yaml": "2.9.1" diff --git a/spec/CHANGELOG.yaml b/spec/CHANGELOG.yaml new file mode 100644 index 0000000..ec9c6b5 --- /dev/null +++ b/spec/CHANGELOG.yaml @@ -0,0 +1,5 @@ +# Канонический журнал нормативных изменений BHS (D-011). +# Каждая запись валидируется схемой spec/schemas/normative-change.schema.json. +# Требования ссылаются на этот журнал через history_ref и не дублируют историю. +# Публикация записей — вместе с релизом спецификации (Release Manifest, BHL-027). +changes: [] diff --git a/spec/schemas/capability.schema.json b/spec/schemas/capability.schema.json new file mode 100644 index 0000000..f754af3 --- /dev/null +++ b/spec/schemas/capability.schema.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/capability.schema.json", + "title": "Capability", + "description": "Средний уровень иерархии Domain → Capability → Atomic Requirement (D-009).", + "type": "object", + "additionalProperties": false, + "required": ["id", "domain", "title", "description"], + "properties": { + "id": { + "type": "string", + "pattern": "^cap-[a-z0-9]+(-[a-z0-9]+)*$", + "description": "Постоянный идентификатор (D-031)." + }, + "domain": { + "type": "string", + "pattern": "^dom-[a-z0-9]+(-[a-z0-9]+)*$", + "description": "Ссылка на существующий домен; целостность проверяет валидатор (BHL-011)." + }, + "title": { "type": "string", "minLength": 3 }, + "description": { "type": "string", "minLength": 10 } + } +} diff --git a/spec/schemas/domain.schema.json b/spec/schemas/domain.schema.json new file mode 100644 index 0000000..936da2d --- /dev/null +++ b/spec/schemas/domain.schema.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/domain.schema.json", + "title": "Domain", + "description": "Верхний уровень иерархии спецификации BHS (D-009).", + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "description"], + "properties": { + "id": { + "type": "string", + "pattern": "^dom-[a-z0-9]+(-[a-z0-9]+)*$", + "description": "Постоянный идентификатор (D-031): не зависит от имени, пути и позиции." + }, + "title": { "type": "string", "minLength": 3 }, + "description": { "type": "string", "minLength": 10 } + } +} diff --git a/spec/schemas/normative-change.schema.json b/spec/schemas/normative-change.schema.json new file mode 100644 index 0000000..4cf48cc --- /dev/null +++ b/spec/schemas/normative-change.schema.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/normative-change.schema.json", + "title": "Normative Change", + "description": "Запись канонического журнала нормативных изменений BHS (D-011). История в требованиях не дублируется: требование несёт только history_ref.", + "type": "object", + "additionalProperties": false, + "required": ["id", "release", "date", "type", "requirements", "description"], + "properties": { + "id": { + "type": "string", + "pattern": "^chg-[a-z0-9]+(-[a-z0-9]+)*$", + "description": "Постоянный идентификатор (D-031)." + }, + "release": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$", + "description": "Версия спецификации, в которой изменение опубликовано." + }, + "date": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }, + "type": { "enum": ["ADDED", "STRENGTHENED", "RELAXED", "CLARIFIED", "DEPRECATED", "REMOVED"] }, + "requirements": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "pattern": "^req-[a-z0-9]+(-[a-z0-9]+)*$" } + }, + "description": { "type": "string", "minLength": 10 }, + "motivation": { "type": "string", "minLength": 3 }, + "migration": { "type": "string", "minLength": 3, "description": "Инструкция переноса для потребителей при REMOVED/STRENGTHENED." } + } +} diff --git a/spec/schemas/parameter.schema.json b/spec/schemas/parameter.schema.json new file mode 100644 index 0000000..af34d13 --- /dev/null +++ b/spec/schemas/parameter.schema.json @@ -0,0 +1,87 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/parameter.schema.json", + "title": "Parameter", + "description": "Типизированный параметр требования (D-018): значение переопределяется только в пределах ограничений.", + "type": "object", + "additionalProperties": false, + "required": ["id", "type", "description"], + "properties": { + "id": { + "type": "string", + "pattern": "^param-[a-z0-9]+(-[a-z0-9]+)*$", + "description": "Постоянный идентификатор (D-031)." + }, + "type": { "enum": ["boolean", "integer", "number", "string", "enum"] }, + "description": { "type": "string", "minLength": 10 }, + "default": {}, + "unit": { "type": "string", "minLength": 1 }, + "constraints": { + "type": "object", + "additionalProperties": false, + "properties": { + "minimum": { "type": "number" }, + "maximum": { "type": "number" }, + "values": { "type": "array", "minItems": 1, "items": { "type": ["string", "integer", "number", "boolean"] } }, + "pattern": { "type": "string" }, + "minLength": { "type": "integer", "minimum": 0 }, + "maxLength": { "type": "integer", "minimum": 1 } + } + }, + "overridable_by": { + "type": "array", + "minItems": 0, + "uniqueItems": true, + "items": { "enum": ["profile", "project"] }, + "default": ["profile", "project"] + } + }, + "allOf": [ + { + "if": { "properties": { "type": { "const": "boolean" } }, "required": ["type"] }, + "then": { + "properties": { + "default": { "type": "boolean" }, + "constraints": { "type": "object", "additionalProperties": false, "properties": {} } + } + } + }, + { + "if": { "properties": { "type": { "const": "integer" } }, "required": ["type"] }, + "then": { + "properties": { + "default": { "type": "integer" }, + "constraints": { "type": "object", "additionalProperties": false, "properties": { "minimum": { "type": "integer" }, "maximum": { "type": "integer" } } } + } + } + }, + { + "if": { "properties": { "type": { "const": "number" } }, "required": ["type"] }, + "then": { + "properties": { + "default": { "type": "number" }, + "constraints": { "type": "object", "additionalProperties": false, "properties": { "minimum": { "type": "number" }, "maximum": { "type": "number" } } } + } + } + }, + { + "if": { "properties": { "type": { "const": "string" } }, "required": ["type"] }, + "then": { + "properties": { + "default": { "type": "string" }, + "constraints": { "type": "object", "additionalProperties": false, "properties": { "pattern": { "type": "string" }, "minLength": { "type": "integer", "minimum": 0 }, "maxLength": { "type": "integer", "minimum": 1 } } } + } + } + }, + { + "if": { "properties": { "type": { "const": "enum" } }, "required": ["type"] }, + "then": { + "required": ["constraints"], + "properties": { + "default": {}, + "constraints": { "type": "object", "additionalProperties": false, "required": ["values"], "properties": { "values": { "type": "array", "minItems": 1, "items": { "type": ["string", "integer", "number", "boolean"] } } } } + } + } + } + ] +} diff --git a/spec/schemas/requirement.schema.json b/spec/schemas/requirement.schema.json new file mode 100644 index 0000000..08a9ff9 --- /dev/null +++ b/spec/schemas/requirement.schema.json @@ -0,0 +1,129 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/requirement.schema.json", + "title": "Atomic Requirement", + "description": "Минимальная независимо проверяемая нормативная единица (D-009, §5 задания 0.1.0). Нормативный уровень, жизненный цикл и статус библиотечного материала — разные сущности (D-029, исправление §5.7 продолжения).", + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "domain", + "capability", + "title", + "statement", + "level", + "rationale", + "applicability", + "acceptance_criteria", + "verification", + "expected_evidence", + "lifecycle" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^req-[a-z0-9]+(-[a-z0-9]+)*$", + "description": "Постоянный идентификатор (D-031): не зависит от названия, пути и позиции; освобождённые идентификаторы не переиспользуются (проверка — валидатор)." + }, + "domain": { "type": "string", "pattern": "^dom-[a-z0-9]+(-[a-z0-9]+)*$" }, + "capability": { "type": "string", "pattern": "^cap-[a-z0-9]+(-[a-z0-9]+)*$" }, + "title": { "type": "string", "minLength": 3, "maxLength": 120 }, + "statement": { + "type": "string", + "minLength": 10, + "description": "Нормативная формулировка с ключевым словом RFC 2119/8174 (D-029); сверка слова с полем level — задача валидатора (BHL-011)." + }, + "level": { + "enum": ["MUST", "MUST NOT", "SHOULD", "SHOULD NOT", "MAY"], + "description": "Нормативный уровень; не смешивается с жизненным циклом и статусом библиотеки." + }, + "rationale": { "type": "string", "minLength": 10 }, + "applicability": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["when"], + "properties": { + "when": { "type": "string", "minLength": 3 }, + "unless": { "type": "string", "minLength": 3 } + } + } + }, + "parameters": { + "type": "array", + "items": { "$ref": "https://baseline-harness.dev/spec/schemas/parameter.schema.json" }, + "description": "Типизированные параметры (D-018); переопределение вне ограничений отклоняет валидатор." + }, + "acceptance_criteria": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["criterion"], + "properties": { + "criterion": { "type": "string", "minLength": 3 }, + "measure": { "type": "string", "minLength": 3 } + } + } + }, + "verification": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "procedure"], + "properties": { + "kind": { "enum": ["deterministic", "semantic", "hybrid"] }, + "procedure": { "type": "string", "minLength": 10 }, + "automation": { "type": "string", "minLength": 1 } + } + }, + "expected_evidence": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "description"], + "properties": { + "kind": { + "enum": ["file", "command-output", "test-run", "session-observation", "review-note", "hash", "other"] + }, + "description": { "type": "string", "minLength": 3 } + } + } + }, + "relations": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["target", "kind"], + "properties": { + "target": { "type": "string", "pattern": "^req-[a-z0-9]+(-[a-z0-9]+)*$" }, + "kind": { "enum": ["depends-on", "refines", "related", "supersedes"] } + } + } + }, + "antipatterns": { + "type": "array", + "items": { "type": "string", "pattern": "^ant-[a-z0-9]+(-[a-z0-9]+)*$" } + }, + "lifecycle": { + "type": "object", + "additionalProperties": false, + "required": ["status"], + "properties": { + "status": { "enum": ["draft", "proposed", "accepted", "deprecated", "removed"] }, + "since": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }, + "note": { "type": "string", "minLength": 3 } + } + }, + "history_ref": { + "type": "string", + "minLength": 3, + "description": "Ссылка на канонический источник истории нормативных изменений (spec/CHANGELOG.yaml, BHL-016); история не дублируется." + } + } +} diff --git a/tests/spec-schemas.test.mjs b/tests/spec-schemas.test.mjs new file mode 100644 index 0000000..56d8b5a --- /dev/null +++ b/tests/spec-schemas.test.mjs @@ -0,0 +1,157 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { parseDocument } from 'yaml'; +import Ajv2020 from 'ajv/dist/2020.js'; + +const root = path.join(path.dirname(import.meta.dirname), 'spec', 'schemas'); +const load = (name) => JSON.parse(readFileSync(path.join(root, name), 'utf8')); + +const ajv = new Ajv2020({ strict: true, strictTypes: false, allErrors: true }); +for (const name of ['domain', 'capability', 'parameter', 'requirement', 'normative-change']) { + const schema = load(`${name}.schema.json`); + assert.ok(ajv.validateSchema(schema), `${name}: некорректная JSON Schema`); + ajv.addSchema(schema); +} + +const validate = (name, data) => ajv.validate(`https://baseline-harness.dev/spec/schemas/${name}.schema.json`, data); + +const domain = { + id: 'dom-skill-quality', + title: 'Качество навыков', + description: 'Требования к формулировке, проверке и поддержке агентных навыков.', +}; + +const capability = { + id: 'cap-skill-verification', + domain: 'dom-skill-quality', + title: 'Проверка навыков', + description: 'Навыки проходят воспроизводимую проверку до принятия в реестр.', +}; + +const parameter = { + id: 'param-prep-budget', + type: 'integer', + description: 'Часов подготовки ограниченного эксперимента до первого наблюдения.', + default: 2, + constraints: { minimum: 0, maximum: 8 }, + overridable_by: ['profile'], +}; + +const requirement = { + id: 'req-skill-verify-before-accept', + domain: 'dom-skill-quality', + capability: 'cap-skill-verification', + title: 'Проверка навыка до принятия', + statement: 'Новый или изменённый навык MUST проверяться на воспроизводимом сценарии до принятия в реестр.', + level: 'MUST', + rationale: 'Непроверенный навык даёт ложную уверенность: грабли источников фиксировали подмену проверки чтением.', + applicability: [{ when: 'изменение SKILL.md или его ресурсов', unless: 'правка опечатки без изменения смысла' }], + parameters: [parameter], + acceptance_criteria: [ + { criterion: 'Сценарий проверки описан и воспроизводим', measure: 'повторный прогон даёт тот же исход' }, + ], + verification: { + kind: 'hybrid', + procedure: 'Детерминированная проверка структуры плюс семантический прогон на подставном агенте.', + automation: 'bhl audit', + }, + expected_evidence: [ + { kind: 'test-run', description: 'Журнал прогона сценария с фиксированными входными данными' }, + ], + relations: [{ target: 'req-skill-structure-valid', kind: 'depends-on' }], + antipatterns: ['ant-skill-untested'], + lifecycle: { status: 'proposed', since: '2026-11-28' }, + history_ref: 'spec/CHANGELOG.yaml', +}; + +test('схемы ядра спецификации корректны как JSON Schema', () => { + for (const name of ['domain', 'capability', 'parameter', 'requirement']) { + assert.ok(ajv.validateSchema(load(`${name}.schema.json`))); + } +}); + +test('положительные фикстуры проходят схемы', () => { + assert.deepEqual(validate('domain', domain).errors ?? [], []); + assert.deepEqual(validate('capability', capability).errors ?? [], []); + assert.deepEqual(validate('parameter', parameter).errors ?? [], []); + assert.deepEqual(validate('requirement', requirement).errors ?? [], []); +}); + +test('параметры разных типов проходят и падают на несогласованных ограничениях', () => { + const ok = [ + { id: 'param-flag', type: 'boolean', description: 'Признак обязательности отчёта.', default: true }, + { id: 'param-name', type: 'string', description: 'Префикс имён артефактов.', default: 'bhl', constraints: { maxLength: 8 } }, + { id: 'param-mode', type: 'enum', description: 'Режим вывода.', default: 'json', constraints: { values: ['json', 'plain'] } }, + ]; + for (const item of ok) assert.deepEqual(validate('parameter', item).errors ?? [], [], item.id); + assert.ok(!validate('parameter', { ...ok[0], default: 'yes' }), 'boolean с текстовым default'); + assert.ok(!validate('parameter', { ...ok[1], default: 7 }), 'string с числовым default'); + assert.ok(!validate('parameter', { id: 'param-mode', type: 'enum', description: 'Режим вывода.' }), 'enum без constraints.values'); + assert.ok(!validate('parameter', { ...parameter, constraints: { minimum: 'x' } }), 'integer с нечисловым minimum'); + assert.ok(!validate('parameter', { ...parameter, constraints: { values: ['a'] } }), 'integer со списком values'); +}); + +test('атомарное требование: обязательные поля и разделение enum', () => { + for (const field of ['id', 'statement', 'level', 'rationale', 'verification', 'lifecycle']) { + const broken = structuredClone(requirement); + delete broken[field]; + assert.ok(!validate('requirement', broken), `обязательное поле ${field}`); + } + const levelAsLibraryStatus = structuredClone(requirement); + levelAsLibraryStatus.level = 'ready'; + assert.ok(!validate('requirement', levelAsLibraryStatus), 'статус библиотеки в level недопустим'); + const lifecycleAsLevel = structuredClone(requirement); + lifecycleAsLevel.lifecycle = { status: 'MUST' }; + assert.ok(!validate('requirement', lifecycleAsLevel), 'нормативный уровень в lifecycle недопустим'); + const badId = structuredClone(requirement); + badId.id = 'REQ_Skill_Verify'; + assert.ok(!validate('requirement', badId), 'нестабильный формат ID'); + const unknownField = structuredClone(requirement); + unknownField.priority = 1; + assert.ok(!validate('requirement', unknownField), 'неизвестное поле запрещено'); + const badEvidence = structuredClone(requirement); + badEvidence.expected_evidence = [{ kind: 'vibes', description: 'ощущение' }]; + assert.ok(!validate('requirement', badEvidence), 'неизвестный класс доказательств'); +}); + +test('домен и возможность: ID и обязательные поля', () => { + assert.ok(validate('domain', domain)); + assert.ok(!validate('domain', { ...domain, id: 'skill-quality' }), 'ID домена без префикса dom-'); + assert.ok(!validate('domain', { ...domain, owner: 'qwen' }), 'неизвестное поле'); + assert.ok(validate('capability', capability)); + assert.ok(!validate('capability', { ...capability, domain: 'cap-skill-quality' }), 'ссылка на домен не того типа'); +}); + +test('нормативное изменение: классы, версия релиза и обязательные поля', () => { + const change = { + id: 'chg-2026-11-28-verify-skill', + release: '0.1.0', + date: '2026-11-28', + type: 'ADDED', + requirements: ['req-skill-verify-before-accept'], + description: 'Требование проверки навыка до принятия введено в спецификацию.', + motivation: 'Непроверенные навыки фиксировались как готовые без доказательств.', + }; + assert.deepEqual(validate('normative-change', change).errors ?? [], []); + for (const type of ['ADDED', 'STRENGTHENED', 'RELAXED', 'CLARIFIED', 'DEPRECATED', 'REMOVED']) { + assert.ok(validate('normative-change', { ...change, type }), type); + } + assert.ok(!validate('normative-change', { ...change, type: 'CHANGED' }), 'неизвестный класс изменения'); + assert.ok(!validate('normative-change', { ...change, release: 'v0.1' }), 'нестрогий формат версии'); + assert.ok(!validate('normative-change', { ...change, requirements: [] }), 'изменение без затронутых требований'); + assert.ok(!validate('normative-change', { ...change, requirements: ['cap-skill-verification'] }), 'ссылка не на требование'); + const { migration: _omit, ...withoutMigration } = change; + assert.ok(validate('normative-change', withoutMigration), 'migration факультативна'); +}); + +test('канонический журнал изменений существует и проходит схему', () => { + const doc = parseDocument(readFileSync(path.join(path.dirname(root), 'CHANGELOG.yaml'), 'utf8')); + assert.equal(doc.errors.length, 0); + const { changes } = doc.toJS(); + assert.ok(Array.isArray(changes)); + for (const entry of changes) { + assert.deepEqual(validate('normative-change', entry).errors ?? [], [], entry.id); + } +});