refactor: drop check.cjs and translate wealth-ledger-sdd-lab schema (WealthLedger/specs#66)

Readiness rules move to a manual checklist with fixed gate semantics.
Analysis artifacts live under analysis/; templates and instructions are in Russian.
This commit is contained in:
2026-10-30 13:34:19 +03:00
parent a2d2df3b5a
commit d5a0e942a3
18 changed files with 668 additions and 847 deletions
@@ -1,294 +0,0 @@
#!/usr/bin/env node
// Deterministic checks for wealth-ledger-sdd-lab changes. OpenSpec CLI 1.13.1 has no conditional
// artifacts, gate records or archive policy, so this file covers only what the CLI cannot.
// It is the single source for profile, ordering, gate and readiness rules; schema.yaml points here.
// Semantic quality (contradictions, invented facts, design fit) stays with reviewers.
//
// Usage: node check.cjs <plan|apply|archive> <change-name> [--root <openspec-root>]
// plan — artifact consistency while planning; missing gates are notes, not errors.
// apply — plan + every apply blocker is an error.
// archive — apply + all tasks done, G4 approved, lab retrospective.
// Exit: 0 ok, 1 violations, 2 invocation/environment error.
"use strict";
const fs = require("node:fs");
const path = require("node:path");
const SA_MODULES = ["data-mapping", "failure-model", "nfr", "observability"];
// Primary file of each conditional artifact, relative to the change directory.
const PRIMARY = {
research: "research.md",
"ux-design": "ux-design.md",
"system-analysis": "system-analysis/system-analysis.md",
"data-mapping": "system-analysis/data-mapping.md",
"failure-model": "system-analysis/failure-model.md",
nfr: "system-analysis/nfr.md",
observability: "system-analysis/observability.md",
"security-analysis": "security-analysis.md",
"test-cases": "test-cases",
"docs-impact": "docs-impact.md",
};
const CONDITIONAL = Object.keys(PRIMARY);
// A selected conditional input must exist before any of these files is written.
const BEFORE_SOLUTION = ["design.md", "qa-analysis.md", "tasks.md"];
const DOWNSTREAM = {
research: ["specs", ...BEFORE_SOLUTION],
"ux-design": BEFORE_SOLUTION,
"system-analysis": BEFORE_SOLUTION,
...Object.fromEntries(SA_MODULES.map((id) => [id, BEFORE_SOLUTION])),
"security-analysis": BEFORE_SOLUTION,
"test-cases": ["tasks.md"],
"docs-impact": ["tasks.md"],
};
// Gate that may approve each artifact. Complex changes approve system analysis at G2 (contract-first).
const SA_IDS = ["system-analysis", ...SA_MODULES];
const allowedGates = (id, complex, hasG2) => {
if (id === "proposal") return ["G1"];
if (id === "change-profile") return ["G1", "G2", "G3"]; // later profile changes need a recorded decision
if (id === "specs") return hasG2 ? ["G2"] : ["G3"];
if (SA_IDS.includes(id)) return complex ? ["G2"] : hasG2 ? ["G2", "G3"] : ["G3"];
return ["G3"];
};
const NOT_APPROVED = new Set(["research", "process-record"]); // input context / the log itself
const REF = /`([a-z0-9][a-z0-9/-]*)`\s*[—–-]\s*`([^`]+)`/g;
const fail = (msg) => { console.error(msg); process.exit(2); };
const args = process.argv.slice(2);
const [mode, changeName] = args;
if (!["plan", "apply", "archive"].includes(mode) || !changeName) {
fail("Usage: node check.cjs <plan|apply|archive> <change-name> [--root <openspec-root>]");
}
const rootIdx = args.indexOf("--root");
if (rootIdx > 0 && !args[rootIdx + 1]) fail("--root needs a path");
const root = path.resolve(rootIdx > 0 ? args[rootIdx + 1] : path.join(__dirname, "..", ".."));
const changeDir = path.join(root, "changes", changeName);
if (!fs.existsSync(changeDir)) fail(`Change directory not found: ${changeDir}`);
const errors = [];
const warnings = [];
const notes = [];
const rel = (p) => path.relative(changeDir, p);
const read = (p) => fs.readFileSync(p, "utf8");
const at = (p) => path.join(changeDir, p);
const walk = (dir) => fs.existsSync(dir)
? fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)])
: [];
const present = (p) => p === "test-cases" || p === "specs"
? walk(at(p)).some((f) => f.endsWith(".md"))
: fs.existsSync(at(p));
const mdFiles = walk(changeDir).filter((f) => f.endsWith(".md"));
const strip = (s) => (s ?? "").replace(/`/g, "").trim();
// Columns: fixed count, the last cell keeps any `|` it contains.
const tableRows = (text, heading, columns) => {
const section = text.split(/^## /m).find((s) => s.startsWith(heading));
if (!section) return null;
return section.split("\n").filter((l) => /^\|/.test(l)).slice(2).map((l) => {
const parts = l.replace(/^\|/, "").replace(/\|\s*$/, "").split("|");
return [...parts.slice(0, columns - 1), parts.slice(columns - 1).join("|")].map((c) => c.trim());
});
};
finishIfMissing();
const record = read(at("process-record.md"));
// 1. Unfilled templates.
for (const f of mdFiles) {
if (read(f).includes("<!-- guide:")) errors.push(`${rel(f)}: unfilled template guide comment remains`);
}
// 2. Mode, class, Change Profile.
const labMode = (record.match(/\*\*Mode:\*\*\s*(lab|delivery)\b/i) || [])[1]?.toLowerCase();
if (!labMode) errors.push("process-record.md: **Mode:** must be `lab` or `delivery`");
const klass = (record.match(/\*\*Class:\*\*\s*(standard|complex)\b/i) || [])[1]?.toLowerCase();
if (!klass) errors.push("process-record.md: **Class:** must be `standard` or `complex`");
const complex = klass === "complex";
const hasG2 = labMode === "lab" || complex;
const profile = new Map();
for (const [rawId, selected, reason] of tableRows(record, "Change Profile", 3) ?? []) {
const id = strip(rawId);
if (!CONDITIONAL.includes(id)) { errors.push(`Change Profile: unknown artifact '${id}'`); continue; }
if (!/^(yes|no)$/i.test(strip(selected))) errors.push(`Change Profile: '${id}' Selected must be yes|no`);
if (!reason) errors.push(`Change Profile: '${id}' needs a trigger or reason`);
profile.set(id, /^yes$/i.test(strip(selected)));
}
const pending = [];
for (const id of CONDITIONAL) {
if (!profile.has(id)) { errors.push(`Change Profile: no decision for '${id}'`); continue; }
const has = present(PRIMARY[id]);
if (profile.get(id) && !has) {
const consumer = DOWNSTREAM[id].find(present);
if (consumer) errors.push(`'${id}' is selected but ${PRIMARY[id]} does not exist while ${consumer} was already written`);
else pending.push(id);
}
if (!profile.get(id) && has) errors.push(`'${id}' is not selected but ${PRIMARY[id]} exists; select it through a gate decision or remove the file`);
}
for (const id of SA_MODULES) {
if (profile.get(id) && !profile.get("system-analysis")) errors.push(`'${id}' requires system-analysis to be selected`);
}
if (fs.existsSync(at("system-analysis")) && !present(PRIMARY["system-analysis"])) {
errors.push("system-analysis/ exists without system-analysis/system-analysis.md");
}
// 3. Requirement references resolve; delta requirements are covered.
const skipSpecs = present(".openspec.yaml") && /^skip_specs:\s*true/m.test(read(at(".openspec.yaml")));
if (skipSpecs && present("specs")) errors.push("skip_specs: true but specs/ contains delta files");
const deltaReqs = [];
const known = new Map();
const removed = new Set();
const addKnown = (cap, h) => (known.get(cap) ?? known.set(cap, new Set()).get(cap)).add(h);
const key = (cap, req) => `${cap}\u0000${req}`;
for (const f of walk(at("specs")).filter((x) => x.endsWith("spec.md"))) {
const cap = path.relative(at("specs"), path.dirname(f)).split(path.sep).join("/");
let op = null;
const seen = new Set();
for (const line of read(f).split("\n")) {
op = (line.match(/^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements/) || [])[1] ?? op;
const req = (line.match(/^### Requirement:\s*(.+?)\s*$/) || [])[1];
if (req) {
if (seen.has(req)) errors.push(`specs/${cap}/spec.md: duplicate Requirement '${req}'`);
seen.add(req);
if (op === "REMOVED") removed.add(key(cap, req));
else addKnown(cap, req);
if (op === "ADDED" || op === "MODIFIED") deltaReqs.push(key(cap, req));
}
const to = (line.match(/^-?\s*TO:\s*`?###\s*Requirement:\s*(.+?)`?\s*$/) || [])[1];
if (to) addKnown(cap, to);
}
}
for (const f of walk(path.join(root, "specs")).filter((x) => x.endsWith("spec.md"))) {
const cap = path.relative(path.join(root, "specs"), path.dirname(f)).split(path.sep).join("/");
for (const m of read(f).matchAll(/^### Requirement:\s*(.+?)\s*$/gm)) {
if (!removed.has(key(cap, m[1]))) addKnown(cap, m[1]);
}
}
const refs = (text) => [...text.matchAll(REF)].map((m) => ({ cap: m[1], req: m[2] }));
for (const f of mdFiles.filter((x) => !rel(x).startsWith(`specs${path.sep}`))) {
for (const { cap, req } of refs(read(f))) {
if (!known.get(cap)?.has(req)) errors.push(`${rel(f)}: unknown requirement reference \`${cap}\` — \`${req}\``);
}
}
const tasksPath = at("tasks.md");
const tasksText = fs.existsSync(tasksPath) ? read(tasksPath) : "";
const coversLines = tasksText.split("\n").filter((l) => /\*\*Covers:\*\*/.test(l)).join("\n");
const taskCover = new Set(refs(coversLines).map((r) => key(r.cap, r.req)));
const qaText = [at("qa-analysis.md"), ...walk(at("test-cases"))].filter(fs.existsSync).map(read).join("\n");
const qaCover = new Set(refs(qaText).map((r) => key(r.cap, r.req)));
for (const k of deltaReqs) {
const label = k.replace("\u0000", "` — `");
if (tasksText && !taskCover.has(k)) errors.push(`tasks.md: delta requirement \`${label}\` has no task Covers`);
if (present("qa-analysis.md") && !qaCover.has(k)) warnings.push(`qa-analysis: delta requirement \`${label}\` has no verification reference (allowed only with a stated risk reason)`);
}
if (!skipSpecs && present("specs") && deltaReqs.length === 0) warnings.push("no ADDED/MODIFIED requirements found in delta specs");
// 4. Test case identity and traceability.
const tcIds = new Set();
for (const f of walk(at("test-cases")).filter((x) => x.endsWith(".md"))) {
for (const block of read(f).split(/^###\s+(?=TC-)/m).slice(1)) {
const id = block.split(/\s/)[0];
if (tcIds.has(id)) errors.push(`${rel(f)}: duplicate test case id ${id}`);
tcIds.add(id);
if (!refs(block).length) errors.push(`${rel(f)}: test case ${id} has no requirement reference`);
}
}
// 5. Contracts and diagrams are referenced, JSON parses, required task kinds exist.
const saText = walk(at("system-analysis")).filter((f) => f.endsWith(".md")).map(read).join("\n");
const contracts = walk(at("system-analysis/contracts"));
for (const f of [...contracts, ...walk(at("system-analysis/diagrams"))]) {
if (!saText.includes(path.basename(f))) errors.push(`${rel(f)}: not referenced from any system-analysis/*.md`);
if (f.endsWith(".json")) {
try { JSON.parse(read(f)); } catch (e) { errors.push(`${rel(f)}: invalid JSON (${e.message})`); }
}
}
const taskLines = tasksText.split("\n").filter((l) => /^\s*[-*+]\s*\[.?\]/.test(l));
if (tasksText) {
if (!taskLines.some((l) => /Independent Review:/.test(l))) errors.push("tasks.md: no `Independent Review:` task");
if (contracts.length && !taskLines.some((l) => /Contract Parity:/.test(l))) errors.push("tasks.md: contracts exist but no `Contract Parity:` task");
if (profile.get("docs-impact") === false && !/^## Docs Impact/m.test(tasksText)) {
errors.push("tasks.md: docs-impact not selected, so a `## Docs Impact` section (changes or no-change reason) is required");
}
}
// 6. Gate Log: chronological; invalidating Gn withdraws Gn and every later gate.
const gates = new Map();
const order = [];
for (const [rawGate, , scope, validation, , decision] of tableRows(record, "Gate Log", 6) ?? []) {
const id = (strip(rawGate).match(/^G[1-4]\b/) || [])[0];
if (!id) continue;
if (/^invalidated\b/i.test(decision)) {
for (const g of [...gates.keys()]) if (g >= id) gates.delete(g);
continue;
}
if (!/^approved\b/i.test(decision)) continue;
if (!/"[^"]+"|«[^»]+»/.test(decision)) errors.push(`Gate ${id}: approval must quote the Change Owner decision`);
if (!validation) errors.push(`Gate ${id}: approval has no validation evidence`);
const prior = ["G1", "G2", "G3", "G4"].filter((g) => g < id && (g !== "G2" || hasG2));
if (prior.some((g) => !gates.has(g))) errors.push(`Gate ${id}: approved before ${prior.filter((g) => !gates.has(g)).join(", ")}`);
const ids = strip(scope).split(/[,\s]+/).filter(Boolean);
for (const a of ids) {
if (id !== "G4" && !allowedGates(a, complex, hasG2).includes(id)) errors.push(`Gate ${id}: '${a}' must be approved at ${allowedGates(a, complex, hasG2).join(" or ")}`);
}
gates.set(id, ids);
order.push(id);
}
if (gates.has("G1") && !gates.get("G1").includes("change-profile")) errors.push("Gate G1: scope must include change-profile");
// 7. Readiness.
const artifactPaths = [
["proposal", "proposal.md"], ["specs", "specs"], ["design", "design.md"],
["qa-analysis", "qa-analysis.md"], ["tasks", "tasks.md"],
...CONDITIONAL.map((id) => [id, PRIMARY[id]]),
];
const approvedScope = new Set([...gates.values()].flat());
const required = hasG2 ? ["G1", "G2", "G3"] : ["G1", "G3"];
const missingGates = required.filter((g) => !gates.has(g));
const unapproved = artifactPaths.filter(([id, p]) => !NOT_APPROVED.has(id) && present(p) && !approvedScope.has(id)).map(([id]) => id);
const blockers = [
...(tasksText ? [] : ["tasks.md missing"]),
...(missingGates.length ? [`missing gates: ${missingGates.join(", ")}`] : []),
...(unapproved.length ? [`not in any approved gate scope: ${unapproved.join(", ")}`] : []),
...(pending.length ? [`selected but missing: ${pending.join(", ")}`] : []),
];
notes.push(`apply-ready: ${blockers.length || errors.length ? `no (${[...blockers, ...(errors.length ? ["errors"] : [])].join("; ")})` : "yes"}`);
if (mode !== "plan") blockers.forEach((b) => errors.push(`apply blocker: ${b}`));
const sequence = ["proposal", "process-record", "research", "specs", "ux-design", "system-analysis",
...SA_MODULES, "security-analysis", "design", "qa-analysis", "test-cases", "docs-impact", "tasks"];
const pathOf = Object.fromEntries([...artifactPaths, ["process-record", "process-record.md"]]);
const next = sequence.find((id) => {
if (CONDITIONAL.includes(id) && !profile.get(id)) return false;
if (id === "specs" && skipSpecs) return false;
return !present(pathOf[id]);
});
notes.push(`next artifact: ${next ?? "none (planning complete for this profile)"}`);
// 8. Archive readiness. Native archive treats any non-[x] marker as open, so descoped work is
// removed from tasks.md by a gate decision and recorded in "Descoped Work".
if (mode === "archive") {
for (const l of taskLines) if (!/\[x\]/i.test(l)) errors.push(`tasks.md: open task: ${l.trim()}`);
for (const [task, reason, gate] of tableRows(record, "Descoped Work", 3) ?? []) {
if (task && (!reason || !/^G[1-4]$/.test(strip(gate)))) errors.push(`Descoped Work '${task}': needs reason and approving gate`);
}
if (!gates.has("G4")) errors.push("Gate G4 Delivery Acceptance is not approved");
if (labMode === "lab") {
const retro = record.split(/^## /m).find((s) => s.startsWith("Retrospective")) ?? "";
if (!retro.replace(/^Retrospective.*\n/, "").trim()) errors.push("process-record.md: Retrospective is empty (lab mode)");
if ((tableRows(record, "Lab Journal", 9) ?? []).length < gates.size) warnings.push("Lab Journal has fewer rows than approved gates");
}
}
finish();
function finishIfMissing() {
if (fs.existsSync(at("process-record.md"))) return;
errors.push("process-record.md is missing: Change Profile and Gate Log are required");
finish();
}
function finish() {
for (const n of notes) console.log(`note: ${n}`);
for (const w of warnings) console.log(`warning: ${w}`);
for (const e of errors) console.log(`error: ${e}`);
console.log(errors.length ? `FAIL ${mode} ${changeName}: ${errors.length} error(s)` : `OK ${mode} ${changeName}`);
process.exit(errors.length ? 1 : 0);
}
File diff suppressed because it is too large Load Diff
@@ -1,28 +1,28 @@
# Data Mapping
<!-- guide: Field-level transformation between systems. Large mappings go to a
machine-checkable file in contracts/ and are referenced here. Remove guides. -->
<!-- Преобразование данных между системами по полям. Большой mapping — машиночитаемый
файл в contracts/ со ссылкой отсюда. -->
## Source and Target
| Mapping | Source (owner) | Target (owner) | Direction | Trigger |
| Mapping | Источник (владелец) | Цель (владелец) | Направление | Trigger |
| --- | --- | --- | --- | --- |
## Field Mapping
| Target field | Source field(s) | Transformation | Unit / currency / scale | Nullability | Default | Validation | On failure |
| Поле цели | Поля источника | Преобразование | Единица / валюта / scale | Nullability | Default | Валидация | При ошибке |
| --- | --- | --- | --- | --- | --- | --- | --- |
## Invariants
<!-- guide: Conservation rules that must hold after mapping, e.g. "total = sum of
positions + cash; each money unit counted once", sign conventions, rounding
point. Each invariant references the spec requirement it protects. -->
<!-- Правила сохранения после mapping, например «итог = сумма позиций + кэш; каждая
денежная единица учтена один раз», знаки, точка округления. Каждый инвариант
ссылается на защищаемый Requirement. -->
## Double-counting and Classification Risks
<!-- guide: Every source record type that could fall into two target aggregates,
and the rule that assigns it to exactly one. -->
<!-- Каждый тип исходной записи, который может попасть в два агрегата, и правило,
относящее его ровно к одному. -->
## Transformation Errors
@@ -1,22 +1,22 @@
# Engineering Design
<!-- guide: How affected repositories implement approved specs and system
obligations. Reference upstream ids; do not restate them. Remove guides. -->
<!-- Как affected repositories реализуют утверждённые specs и системные обязательства.
Ссылайся на upstream ids, не пересказывай. -->
## Inputs
<!-- guide: Exact upstream artifacts this design implements (specs, selected
system-analysis modules, ux-design, security-analysis). -->
<!-- Точные upstream-артефакты, которые реализует этот design (specs, выбранные
модули analysis/, ux-design, security-analysis). -->
## Architecture Drivers
<!-- guide: Requirements, NFR ids, constraints and risks that force decisions. -->
<!-- Requirements, ids NFR, ограничения и риски, которые вынуждают решения. -->
## Technical Goals / Non-Goals
## Implementation Impact Map
| Area | Affected | Outcome or N/A reason |
| Область | Затронута | Результат или причина N/A |
| --- | --- | --- |
| main | | |
| frontend | | |
@@ -24,8 +24,8 @@
## Decisions
<!-- guide: Per decision: context, chosen option, rejected alternatives, driver it
satisfies. Group by repository when that helps. -->
<!-- На каждое решение: контекст, выбранный вариант, отвергнутые альтернативы, driver.
Группируй по repository, если это помогает. -->
## Components and Responsibilities
@@ -33,16 +33,16 @@
## Contract Implementation
<!-- guide: How each contract is produced/consumed and how published OpenAPI is
compared with the target contract. N/A when no contracts changed. -->
<!-- Как каждый контракт производится/потребляется и как опубликованный OpenAPI
сравнивается с target-контрактом. N/A, если контракты не менялись. -->
## Cross-cutting Implementation
## UI Implementation
<!-- guide: With ux-design.md: component composition, state, data fetching, how
each UI state is produced — no restated UX. Without ux-design.md: state
new/changed, reuse or N/A with reason, plus the needed screen/state detail. -->
<!-- С ux-design: композиция компонентов, state, data fetching, как получается каждое
UI-состояние — без пересказа UX. Без ux-design: new/changed/reuse или N/A с
причиной и нужные детали экранов/состояний. -->
## Developer Verification Strategy
@@ -50,8 +50,8 @@
## Solution Assessment
<!-- guide: Required for new auth, security, storage, integration, observability,
caching, concurrency or shared tooling; otherwise N/A with reason. -->
<!-- Обязателен для нового auth, security, storage, интеграции, observability,
кеширования, конкурентности или общего tooling; иначе N/A с причиной. -->
## Risks / Trade-offs
@@ -1,12 +1,12 @@
# Documentation Impact
<!-- guide: Plan only; docs/ is edited by [docs] tasks. Remove guides. -->
<!-- Только план; docs/ правят tasks `[docs]`. -->
## Summary
## Documentation Changes
| Action | Target | Category | Resulting AS-IS | Source | Verification |
| Action | Target | Category | Итоговое AS-IS | Source | Verification |
| --- | --- | --- | --- | --- | --- |
## Diagram Promotion
@@ -1,19 +1,18 @@
# Failure Model
<!-- guide: Boundary-level failure semantics. Implementation of mechanisms (queues,
locks, libraries) belongs to design.md. Remove guides before G3. -->
<!-- Семантика отказов на границах. Реализация механизмов (очереди, locks,
библиотеки) — в design.md. -->
## Failure Scenarios
| ID | Boundary / step | Failure | Detection | Required system behavior | Observable result | Requirement |
| ID | Граница / шаг | Отказ | Обнаружение | Требуемое поведение системы | Наблюдаемый результат | Requirement |
| --- | --- | --- | --- | --- | --- | --- |
## Timeouts and Retries
## Idempotency and Duplicate Handling
<!-- guide: Idempotency key, scope, retention; what a duplicate request/event
yields. -->
<!-- Ключ идемпотентности, scope, срок хранения; что даёт повторный запрос/событие. -->
## Ordering and Concurrency
@@ -1,14 +1,13 @@
# Non-Functional Requirements
<!-- guide: Only measurable constraints that change design or verification.
Each row needs a threshold and a way to measure it. Remove guides. -->
<!-- Только измеримые ограничения, которые меняют design или проверку. У каждой
строки есть порог и способ измерения. -->
| ID | Category | Requirement | Threshold | Measurement / evidence | Rationale / source |
| ID | Категория | Требование | Порог | Измерение / evidence | Обоснование / источник |
| --- | --- | --- | --- | --- | --- |
## Constraints Without Thresholds
<!-- guide: Constraints that are real but not measurable yet; state why and who
decides the threshold. -->
<!-- Реальные, но пока неизмеримые ограничения: почему нет порога и кто его решит. -->
## Open Questions
@@ -1,11 +1,10 @@
# Observability
<!-- guide: What must be observable and why; not which SDK, exporter or logger
(design.md). Remove guides before G3. -->
<!-- Что должно быть наблюдаемо и зачем; не какой SDK, exporter или logger (design.md). -->
## Semantic Events
| Event | Trigger | Required attributes | Consumer / purpose |
| Событие | Trigger | Обязательные атрибуты | Потребитель / назначение |
| --- | --- | --- | --- |
## Logs, Metrics and Traces
@@ -14,11 +13,11 @@
## SLI and Alert Conditions
| SLI | Definition | Target | Alert condition |
| SLI | Определение | Цель | Условие алерта |
| --- | --- | --- | --- |
## Diagnostic Scenarios
<!-- guide: "When X happens, an operator can determine Y from Z." -->
<!-- «Когда X, оператор определяет Y по Z». -->
## Open Questions
@@ -1,17 +1,21 @@
# Process Record
**Mode:** <!-- guide: lab | delivery -->
**Class:** <!-- guide: standard | complex -->
**Issue:** <!-- guide: Gitea Issue link -->
**Mode:** <!-- lab | delivery -->
**Class:** <!-- standard | complex -->
**Issue:** <!-- ссылка на Gitea Issue -->
## Change Profile
<!-- guide: One row per conditional artifact, all ten rows required. Selected =
yes|no. Reason cites the concrete trigger from the instruction table or why
it does not apply; "lab practice" is a valid reason only in lab mode and
must name the practice. -->
<!-- Строка на каждый условный артефакт, все десять обязательны. Выбран = yes|no.
Причина называет конкретный trigger из instruction артефакта или объясняет, почему
он не применим; «lab: практика …» допустима только в lab и называет практику.
Пример:
| failure-model | yes | синхронизация брокера повторяет неидемпотентную запись |
| nfr | no | нет новых обязательств по задержке, объёму или хранению |
| data-mapping | yes | lab: практика data mapping |
Плохо: `| nfr | no | N/A |` — причина должна объяснять, почему не нужно. -->
| Artifact | Selected | Reason |
| Артефакт | Выбран | Причина |
| --- | --- | --- |
| research | | |
| ux-design | | |
@@ -26,32 +30,38 @@
## Gate Log
<!-- guide: Append-only, chronological. Scope = artifact ids covered by the
decision. Validation = commands run and their results, review verdicts.
Decision = `approved "<quoted owner words>"`, `rejected`, `changes requested`
or `invalidated: <reason>`. Never write a decision the owner did not give. -->
<!-- Только дописывание, по хронологии. Scope — ids артефактов в решении.
Validation — выполненные команды и результаты, вердикты review.
Decision — `approved "<дословные слова владельца>"`, `rejected`,
`changes requested` или `invalidated: <причина>`. Никогда не записывай решение,
которого владелец не давал. ПОСЛЕДНЯЯ строка gate — его состояние; более поздняя
rejected / changes requested / invalidated снимает этот gate и все последующие.
Пример:
| G1 | 2026-10-29 | proposal, change-profile | `openspec validate` OK; readiness: plan OK | product-analyst: 1 major — закрыт в Open Decisions | approved "ок, идём дальше" (сессия) |
| G2 | 2026-10-30 | specs | `openspec validate --strict` OK; readiness: plan OK | qa-engineer: в Scenario нет значения THEN | changes requested |
Плохо: `approved` без цитаты владельца; строка G4 со Scope `design`. -->
| Gate | Date | Scope | Validation | Findings | Decision |
| Gate | Дата | Scope | Validation | Findings | Decision |
| --- | --- | --- | --- | --- | --- |
## Descoped Work
<!-- guide: Tasks removed from tasks.md after G3. Reason and approving gate are
required. Leave the header row only when nothing was descoped. -->
<!-- Tasks, удалённые из tasks.md после G3. Причина и gate решения обязательны.
Если ничего не снято — только строка заголовка. -->
| Task | Reason | Gate |
| Task | Причина | Gate |
| --- | --- | --- |
## Lab Journal
<!-- guide: lab mode: one row per completed stage, written right after it.
Unique findings = what this stage found that no other stage did.
Cost = subagent calls, approximate tokens or time. delivery mode: optional. -->
<!-- lab: строка на каждую завершённую стадию, сразу после неё. Уникальные находки —
то, что нашла только эта стадия. Стоимость — вызовы сабагентов, примерно токены
или время. delivery: необязательно. -->
| Stage | Role / subagent | Unique findings | Decisions | Risks found / excluded | Handoff issues | Skills | Cost | Transferable |
| Стадия | Роль / сабагент | Уникальные находки | Решения | Риски найдены / исключены | Проблемы передачи | Skills | Стоимость | Переносимо |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
## Retrospective
<!-- guide: Written after G4. Which stages paid off, which were redundant for this
class of change, what to change in the schema. Facts first, then opinion. -->
<!-- После G4. Какие стадии окупились, какие были лишними для этого класса change,
что поменять в schema. Сначала факты, потом мнение. -->
@@ -1,7 +1,6 @@
# Proposal
<!-- guide: Language of the Change Owner. No files, APIs, tables, libraries,
diagrams or test plans. Remove every guide comment before G1. -->
<!-- Язык Change Owner. Без файлов, API, таблиц, библиотек, диаграмм и тест-планов. -->
## Why
@@ -23,14 +22,16 @@
## Success Criteria
<!-- Каждый критерий измерим или наблюдаем: что увидит пользователь или владелец. -->
## Evidence
<!-- guide: Facts that justify the change, each with a source: Issue, research
(link or `research.md`), incident, measurement. Mark hypotheses as such. -->
<!-- Факты, обосновывающие change, каждый с источником: Issue, research (ссылка или
`analysis/research.md`), инцидент, измерение. Гипотезы помечай явно. -->
## Assumptions / Dependencies
## Open Decisions
<!-- guide: Decisions not yet taken that may change scope. Each item: question,
who decides, what blocks until it is answered. Empty only if none exist. -->
<!-- Ещё не принятые решения, способные изменить scope. Каждое: вопрос, кто решает,
что блокируется до ответа. Пусто, только если таких нет. -->
@@ -1,20 +1,24 @@
# QA Analysis
<!-- guide: Risk-based system verification strategy. Reference scenarios; do not
restate them. No developer unit/component test plans. Remove guides. -->
<!-- Risk-based стратегия системной проверки. Ссылайся на Scenarios, не пересказывай.
Без планов developer unit/component tests. -->
## Risk Assessment
| Risk | Affected requirements | Likelihood | Impact | Verification depth |
| Риск | Затронутые требования | Вероятность | Ущерб | Глубина проверки |
| --- | --- | --- | --- | --- |
## Coverage Matrix
<!-- guide: One row per delta requirement. Check = system-level way of proving
it; test case ids when test-cases is selected; or "not verified: <risk
reason>". -->
<!-- Строка на каждый delta Requirement. Проверка — системный способ доказать его;
ids test cases, если выбран test-cases; либо «not verified: <риск-причина>».
Покрытие — только строки этой таблицы; упоминание требования в другом месте
файла покрытием не считается. REMOVED требует проверки миграции/регрессии.
Пример:
| `portfolio/holdings` — `Итог портфеля не учитывает дубли операций` | повторный импорт того же файла брокера, итог не меняется | API | TC-HOLD-001 |
| `portfolio/holdings` — `Портфель показывает валюту` | not verified: только отображение, проверено ревью Scenario; риск низкий | — | — | -->
| Requirement | Check | Level | Test cases |
| Requirement | Проверка | Уровень | Test cases |
| --- | --- | --- | --- |
## Negative and Boundary Focus
@@ -30,5 +34,3 @@
## Regression Impact
## Gaps / Blockers
<!-- guide: Each gap names its routing destination artifact. -->
@@ -1,7 +1,7 @@
# Product Research
<!-- guide: Input context, not a requirement source. Every claim is marked
[F] fact with source, [I] interpretation or [H] hypothesis. Remove guides. -->
<!-- Входной контекст, не источник требований. Каждое утверждение помечено:
[F] факт с источником, [I] интерпретация, [H] гипотеза. -->
## Problem Statement
@@ -11,7 +11,7 @@
## Existing Solutions and Alternatives
| Option | What it does | Strengths | Weaknesses | Source |
| Вариант | Что делает | Сильные стороны | Слабые стороны | Источник |
| --- | --- | --- | --- | --- |
## Evidence & Sources
@@ -24,5 +24,5 @@
## Recommendation
<!-- guide: build / do not build / narrow scope / research more, with reasons.
"Do not build" is a valid outcome. -->
<!-- делать / не делать / сузить scope / исследовать дальше — с причинами.
«Не делать» — допустимый итог. -->
@@ -1,7 +1,7 @@
# Security Analysis
<!-- guide: Threat model of this change only. Reference security NFR rows by id;
do not restate them. No generic checklist. Remove guides before G3. -->
<!-- Threat model только этого change. На security-NFR ссылайся по id, не
пересказывай. Без универсального чек-листа. -->
## Scope
@@ -11,16 +11,16 @@
## Threats
| ID | Threat (STRIDE) | Attack scenario | Asset / boundary | Existing control | Likelihood / impact |
| ID | Угроза (STRIDE) | Сценарий атаки | Актив / граница | Существующий контроль | Вероятность / ущерб |
| --- | --- | --- | --- | --- | --- |
## Recommended Mitigations
| Threat | Mitigation | Owner artifact (specs / system-analysis / design) |
| Угроза | Mitigation | Артефакт-владелец (specs / system-analysis / design) |
| --- | --- | --- |
## Residual Risks
## Validation Requirements
<!-- guide: Evidence needed before G4: review focus, negative tests, tooling. -->
<!-- Evidence, нужные до G4: фокус review, негативные тесты, инструменты. -->
@@ -1,18 +1,32 @@
<!--
Choose only the sections this delta needs; delete this guide before approval.
Оставь только нужные этой дельте разделы; комментарий удали до approval.
New capability only: add `## Purpose` with 1–2 sentences (50+ characters).
Existing capability: do not add Purpose.
Только новая capability: `## Purpose` в 1–2 предложения (от 50 символов).
Существующая capability: Purpose не добавляй.
Supported operations:
- `## ADDED Requirements`: new complete Requirement blocks.
- `## MODIFIED Requirements`: full existing Requirement blocks with every
surviving Scenario, then edited behavior; heading matches exactly.
- `## REMOVED Requirements`: Requirement heading plus **Reason** and **Migration**.
- `## RENAMED Requirements`: `FROM:` and `TO:` heading pairs only.
Операции:
- `## ADDED Requirements` — новые полные блоки Requirement.
- `## MODIFIED Requirements` — полный существующий блок со всеми сохраняемыми
Scenario, затем изменённое поведение; heading совпадает точно.
- `## REMOVED Requirements` — heading Requirement плюс **Reason** и **Migration**.
- `## RENAMED Requirements` — только пары `FROM:` и `TO:`.
Every normative Requirement uses BCP 14 (RFC 2119 + RFC 8174) uppercase
SHALL/MUST deliberately, and at least one `#### Scenario:` with `- **WHEN**`
and `- **THEN**`. Lowercase must/should/may are ordinary language.
Do not leave empty operation sections or a sample Requirement.
Каждый нормативный Requirement осознанно использует BCP 14 (RFC 2119 + RFC 8174)
uppercase SHALL/MUST и минимум один `#### Scenario:` с `- **WHEN**` и
`- **THEN**`. Строчные «must/should/may» — обычный язык.
Не оставляй пустые разделы операций и образцы.
Пример:
## ADDED Requirements
### Requirement: Итог портфеля не учитывает дубли операций
Система SHALL учитывать каждый идентификатор операции брокера в итоге портфеля
не более одного раза.
#### Scenario: Одна операция импортирована дважды
- **WHEN** операция `op-1` на 100.00 RUB импортирована дважды
- **THEN** итог портфеля увеличивается ровно на 100.00 RUB
Плохо: «Система SHALL корректно обрабатывать дубли» — нет наблюдаемого критерия;
«THEN итог правильный» — нет ожидаемого значения; один Requirement на импорт,
отображение и экспорт сразу — раздели по поведению.
-->
@@ -1,12 +1,11 @@
# System Analysis
<!-- guide: Hub document. Owns context, boundaries, flows overview and contract
semantics; details live in selected modules and are referenced, not copied.
Remove guides before G3. -->
<!-- Hub. Владеет контекстом, границами, обзором flows и семантикой контрактов;
детали — в выбранных модулях, на них ссылаются, а не копируют. -->
## Requirement Coverage
| Requirement | Flow / contract | Module |
| Requirement | Flow / контракт | Модуль |
| --- | --- | --- |
## System Context and Boundaries
@@ -19,32 +18,32 @@
## Data Ownership
| Data | Source of truth | Writers | Readers |
| Данные | Источник истины | Пишут | Читают |
| --- | --- | --- | --- |
## Interaction Flows
<!-- guide: Reference diagrams/*.mmd; text only for what a diagram cannot carry. -->
<!-- Ссылки на diagrams/*.mmd; текст — только для того, что диаграмма не передаёт. -->
## Contracts
<!-- guide: Per contract: producer/consumer, operation/event, version, file in
contracts/, compatibility class (additive / breaking), published source it
must match after implementation. -->
<!-- На каждый контракт: producer/consumer, операция/событие, версия, файл в
contracts/, класс совместимости (additive / breaking), опубликованный источник,
с которым он обязан совпасть после реализации. -->
| Contract | Producer → Consumer | File | Compatibility | Published source |
| Контракт | Producer → Consumer | Файл | Совместимость | Опубликованный источник |
| --- | --- | --- | --- | --- |
## Error Semantics
<!-- guide: Business vs technical failures at boundaries. Detailed retry/
idempotency/recovery belongs to failure-model.md when selected. -->
<!-- Бизнес- и технические отказы на границах. Подробные retry/идемпотентность/
восстановление — в failure-model.md, если выбран. -->
## Compatibility / Migration
## Detailed Modules
<!-- guide: Link each selected module (data-mapping, failure-model, nfr,
observability) with one line on what it decides. -->
<!-- Ссылка на каждый выбранный модуль (data-mapping, failure-model, nfr,
observability) и одна строка о том, что он решает. -->
## Open Questions
@@ -1,18 +1,24 @@
# Tasks
<!-- guide: Task line format:
- [ ] X.Y [main|frontend|backend|docs|specs] <Kind>: <action + outcome>
- **Covers:** `capability` — `Requirement heading` pairs, or `N/A` — <reason>
- **Source:** exact upstream artifact section / contract / docs-impact entry
- **Verification:** owner-controlled command, observable check or artifact
- **Depends on:** task ids or none
<!-- Формат task:
- [ ] X.Y [main|frontend|backend|docs|specs] <Kind>: <действие + результат>
- **Covers:** пары `capability` — `Requirement heading` или `N/A` — <причина>
- **Source:** точный раздел upstream-артефакта / контракт / запись docs-impact
- **Verification:** команда владельца, наблюдаемая проверка или артефакт
- **Depends on:** ids tasks или none
Kinds: Implementation, Migration, Automated Testing, Contract Parity, Docs,
Independent Review, QA Verification, Verification. Remove guides before G3. -->
Independent Review, QA Verification, Verification.
Пример:
- [ ] 2.1 [backend] Implementation: пропускать операции, чей внешний id уже сохранён
- **Covers:** `portfolio/holdings` — `Итог портфеля не учитывает дубли операций`
- **Source:** design.md Decisions D2; analysis/failure-model.md F3
- **Verification:** `npm run verify` в backend; повторный импорт fixture оставляет итог 100.00
- **Depends on:** 1.1
Плохо: «Verification: проверить, что работает»; Covers с heading, которого нет в specs. -->
## 1. <!-- guide: delivery phase -->
## 1. <!-- этап delivery -->
## Docs Impact
<!-- guide: Only when docs-impact is not selected: list docs/ targets with
resulting AS-IS, or one concrete no-change reason. Delete when docs-impact.md
exists. -->
<!-- Только если docs-impact не выбран: targets в docs/ с итоговым AS-IS или одна
конкретная причина без изменений. Удали раздел, если есть analysis/docs-impact.md. -->
@@ -1,10 +1,10 @@
# Test Cases — <!-- guide: area -->
# Test Cases — <!-- область -->
<!-- guide: One file per area under test-cases/. A case adds concrete data, steps
or an oracle that the scenario does not already state; otherwise reference the
scenario from qa-analysis instead of writing a case. Remove guides. -->
<!-- Один файл на область в analysis/test-cases/. Case добавляет конкретные данные,
шаги или oracle, которых нет в Scenario; иначе qa-analysis ссылается на Scenario,
а case не пишется. -->
### TC-<!-- guide: AREA-NNN --> <!-- guide: title -->
### TC-<!-- AREA-NNN --> <!-- название -->
- **Verifies:** `capability` — `Requirement heading` / Scenario
- **Risk / Priority:**
@@ -13,4 +13,4 @@
- **Steps:**
1.
- **Expected Results:**
- **Automation Candidate:** <!-- guide: yes (level) | no (reason) -->
- **Automation Candidate:** <!-- yes (уровень) | no (причина) -->
@@ -1,15 +1,14 @@
# UX Design
<!-- guide: Interaction design of observable behavior from Delta Specs. Reference
requirements as `capability` — `Requirement heading`; do not restate them.
No server architecture, contracts or component/state-management choices.
Remove guides before G3. -->
<!-- Interaction design observable behavior из Delta Specs. Ссылайся на требования
как `capability` — `Requirement heading`, не пересказывай. Без серверной
архитектуры, контрактов и выбора компонентов/state management. -->
## User Goals
## User Flows
<!-- guide: Mermaid flowchart or numbered steps per flow, with entry and exit points. -->
<!-- Mermaid flowchart или нумерованные шаги на каждый flow, с точками входа и выхода. -->
## Information Architecture and Screen Structure
@@ -17,7 +16,7 @@
## UI States
| Screen / region | Loading | Empty | Error | Success | Partial / stale |
| Экран / область | Loading | Empty | Error | Success | Partial / stale |
| --- | --- | --- | --- | --- | --- |
## Validation Feedback
@@ -26,15 +25,15 @@
## Accessibility
<!-- guide: Keyboard path, focus order, names/roles, contrast, non-color cues. -->
<!-- Путь с клавиатуры, порядок фокуса, имена/роли, контраст, признаки не только цветом. -->
## Design System Reuse
## Materials
<!-- guide: Inline Markdown by default; local files follow the Visual Package rule. -->
<!-- По умолчанию inline Markdown; локальные файлы — по правилу Visual Package. -->
| Material ID | Relative path / reference | Screen/state and purpose | SHA-256 |
| ID материала | Относительный путь / ссылка | Экран/состояние и назначение | SHA-256 |
| --- | --- | --- | --- |
## Open UX Questions