Перенос выполнен git mv: spec/ → products/bhs-spec/spec/ — корень нормативного дерева и корень сборки релизного артефакта, docs/spec/ → products/bhs-spec/docs/ — сгенерированные страницы. Каталоги spec/ и docs/ в корне лаборатории исчезли, история не переписана: 90 файлов ушли переименованиями, новых коммитов достаточно. Содержимое сохранено. 58 нормативных YAML/JSON и 31 сгенерированная страница байт-идентичны прежнему состоянию — сверка списков SHA-256 до и после переноса расхождений не дала, перегенерация docs/ не потребовалась. Единственный изменённый файл дерева — spec/README.md (45769aaf… → 47e3bd12…): перенацелены цели ссылок и путь команды сборки, потому что глубина каталога выросла на два уровня. Факты и нормативный текст не правлены, записей chg-… не добавлялось: README не нормативная сущность. Из него же убраны markdown-ссылки в приватные каталоги лаборатории (backlog/, backlog/decisions/, library/, корневые schemas/) — они остались текстом, иначе проверка продуктовых границ по BHL-071 AC #1 дала бы по ним ошибки. Ссылка на фикстуру соседнего продукта bhl-cli сохранена: документационные ссылки на соседние деревья допустимы (D-055). Воспроизводимость прежних кандидатов проверена сборкой CLI той же ревизии по git archive: 0.1.1 изc7ed8e2даёт 5e7922f9fd630b31b70fab2e5b3a8eb1f80ee8b87dd51d9b99c024e528d8d8bf, 0.1.0 изa17c027— 9b3adb7a7ea361f178303874c7ab3721ba8d4956af9367e51f6b599497953007, обе суммы совпадают с записями результатов. Имена путей внутри tarball задаются префиксом bhs-spec-<version>/ и относительными путями от корня сборки, поэтому сборка из products/bhs-spec/spec и из копии того же содержимого вне лаборатории даёт байт-идентичный артефакт. Сборка 0.1.1 из текущего дерева отличается от кандидатаc7ed8e2ровно README.md при том же составе — 58 файлов; зафиксированные суммы не переписаны, следствие записано комментарием к BHL-062. Потребители пути переведены: tests/lab-connection.test.mjs, tests/spec-docs.test.mjs, tests/spec-schema-copy.test.mjs, tests/spec-schemas.test.mjs и products/bhl-cli/tests/normative-sync.test.mjs (переходный откат на spec/ удалён вместе с переходной записью реестра, переходных состояний в products.yaml не осталось). Ссылки перенацелены в README корня, AGENTS.md, products/bhl-cli/README.md, products/bhs-implementations/README.md и двух его SKILL.md, sources/README.md, одной записи results/ и текстовом пути seed в карточке библиотеки. Добавлено README продуктового дерева с раскладкой, местной командой качества и тем, что в дерево не входит; отдельный package.json не заводили — его version создал бы второй источник версии стандарта, которая живёт в CHANGELOG.yaml. Проверки: корневой quality gate — npm run check 0 ошибок и 0 предупреждений при 3 продуктах, npm test 60/60, backlog doctor без дубликатов и циклов; местная валидация дерева — 43 файла, 0 диагностик; products/bhl-cli — 56/56 из корня и из дерева, в изолированной копии через rsync 55 зелёных и 1 пропуск сверки норматива вне лаборатории, npm pack изнутри дерева — 23 файла без тестов и фикстур; products/bhs-implementations — 5/5 и в изолированной копии проходит без установки.
472 lines
26 KiB
JavaScript
472 lines
26 KiB
JavaScript
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { parseDocument, isMap } from 'yaml';
|
|
import { marked } from 'marked';
|
|
import Ajv2020 from 'ajv/dist/2020.js';
|
|
|
|
const MODULE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
|
|
const statuses = new Set(['draft', 'ready', 'archived']);
|
|
// Порог длины kebab-case id (D-031); именован по BHL-043/L1 вместо встроенного 64.
|
|
const MAX_ID_LENGTH = 64;
|
|
const validId = (value) => typeof value === 'string'
|
|
&& value.length <= MAX_ID_LENGTH && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);
|
|
const nonempty = (value) => typeof value === 'string' && value.trim().length > 0;
|
|
const slash = (value) => value.split(path.sep).join('/');
|
|
const lineAt = (text, offset) => text.slice(0, Math.max(0, offset)).split('\n').length;
|
|
|
|
// Only delimit frontmatter here; YAML and Markdown are parsed by their libraries.
|
|
function frontmatter(text) {
|
|
return /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
}
|
|
|
|
function links(tokens) {
|
|
const result = [];
|
|
marked.walkTokens(tokens, (token) => {
|
|
if (token.type === 'link' || token.type === 'image') result.push(token);
|
|
});
|
|
return result;
|
|
}
|
|
|
|
function plain(tokens) {
|
|
return tokens.map((token) => token.tokens ? plain(token.tokens) : (token.text ?? '')).join('').trim();
|
|
}
|
|
|
|
function findTable(tokens, columns) {
|
|
return tokens.find((token) => token.type === 'table' && token.header.length === columns.length
|
|
&& token.header.every((cell, index) => plain(cell.tokens) === columns[index]));
|
|
}
|
|
|
|
// Relative Markdown destinations are the explicit local-file contract.
|
|
function destination(root, from, href) {
|
|
if (!href || href.startsWith('#') || href.startsWith('//')) return {};
|
|
if (/^(?:file:|[a-z]:[\\/])/i.test(href)) return { invalid: true };
|
|
if (/^[a-z][a-z\d+.-]*:/i.test(href)) return {};
|
|
let decoded;
|
|
try { decoded = decodeURIComponent(href.split(/[?#]/, 1)[0]); }
|
|
catch { return { invalid: true }; }
|
|
if (path.posix.isAbsolute(decoded) || path.win32.isAbsolute(decoded)) return { invalid: true };
|
|
const absolute = path.resolve(root, path.dirname(from), decoded.replaceAll('\\', '/'));
|
|
const relative = path.relative(root, absolute);
|
|
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
return { invalid: true };
|
|
}
|
|
return { file: slash(relative), absolute };
|
|
}
|
|
|
|
function privacyWarnings(file, text, warn) {
|
|
const safeUser = /^(?:user(?:name)?|example(?:-user)?|test(?:-user)?|synthetic(?:-user)?|placeholder|redacted|public|default)$/i;
|
|
for (const [index, line] of text.split(/\r?\n/).entries()) {
|
|
const personal = [...line.matchAll(/(?:[a-z]:[\\/]Users[\\/]|\/(?:Users|home)\/)([^\\/\s<>"'`]+)(?:[\\/]|(?=\s|$))/gi)]
|
|
.some((match) => !safeUser.test(match[1]) && !match[1].startsWith('$'));
|
|
if (personal) warn(file, index + 1, 'personal-path', 'Возможный персональный абсолютный путь.');
|
|
const candidates = line.match(/\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,}|sk-(?:proj-)?[A-Za-z0-9_-]{24,}|AKIA[A-Z0-9]{16})\b/g) ?? [];
|
|
const suspicious = candidates.some((value) => !/example|placeholder|redacted|synthetic/i.test(value)
|
|
&& new Set(value.replace(/^[^-_]*[-_]/, '')).size >= 8);
|
|
if (suspicious || /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(line)) {
|
|
warn(file, index + 1, 'secret', 'Возможный секрет или приватный ключ.');
|
|
}
|
|
}
|
|
}
|
|
|
|
export function checkRepository(directory) {
|
|
const root = path.resolve(directory);
|
|
const errors = [];
|
|
const warnings = [];
|
|
const files = new Map();
|
|
const markdown = new Map();
|
|
const error = (file, line, category, message) => errors.push({ file, line, category, message });
|
|
const warn = (file, line, category, message) => warnings.push({ file, line, category, message });
|
|
const isFile = (file) => {
|
|
try { return statSync(path.join(root, file)).isFile(); } catch { return false; }
|
|
};
|
|
const isDirectory = (file) => {
|
|
try { return statSync(path.join(root, file)).isDirectory(); } catch { return false; }
|
|
};
|
|
// Silent listing: an absent tracker directory is not a registry problem.
|
|
const namesIn = (relative) => {
|
|
try {
|
|
return readdirSync(path.join(root, relative), { withFileTypes: true })
|
|
.filter((entry) => entry.isFile()).map((entry) => entry.name.toLowerCase());
|
|
} catch { return []; }
|
|
};
|
|
let productCount = 0;
|
|
|
|
function walk(relative = '') {
|
|
let entries;
|
|
try { entries = readdirSync(path.join(root, relative), { withFileTypes: true }); }
|
|
catch { error(slash(relative) || '.', 1, 'read', 'Не удалось прочитать каталог.'); return; }
|
|
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
// Local runtime state: Pi keeps transcripts, credentials and installed
|
|
// packages under .pi, and none of that is library material. Context
|
|
// reports under reports/ are one-off deliverables of information
|
|
// requests: the project must not depend on their existence (D-051).
|
|
if (['.git', '.pi', '.artifacts', 'reports', 'node_modules'].includes(entry.name)) continue;
|
|
const file = slash(path.join(relative, entry.name));
|
|
if (entry.isDirectory()) { walk(file); continue; }
|
|
if (!entry.isFile()) continue; // Do not traverse symlinks or external trees.
|
|
try {
|
|
const buffer = readFileSync(path.join(root, file));
|
|
const expectedText = /\.(?:md|mjs|cjs|js|json|ya?ml|txt|csv|html|css|svg)$/i.test(file);
|
|
let text;
|
|
try {
|
|
if (buffer.includes(0)) throw new Error('binary');
|
|
text = new TextDecoder('utf-8', { fatal: true }).decode(buffer);
|
|
} catch {
|
|
if (expectedText) error(file, 1, 'encoding', 'Текстовый файл должен быть в UTF-8 без нулевых байтов.');
|
|
continue;
|
|
}
|
|
files.set(file, text);
|
|
privacyWarnings(file, text, warn);
|
|
if (file.endsWith('.md')) {
|
|
const match = frontmatter(text);
|
|
const body = match ? text.slice(match[0].length) : text;
|
|
markdown.set(file, marked.lexer(body));
|
|
}
|
|
} catch {
|
|
error(file, 1, 'read', 'Не удалось прочитать файл.');
|
|
}
|
|
}
|
|
}
|
|
walk();
|
|
|
|
// .pi holds Pi runtime state, but the project's Pi settings are versioned:
|
|
// that one file gets the same privacy review as any other tracked file.
|
|
for (const file of ['.pi/agent/settings.json']) {
|
|
try {
|
|
const text = readFileSync(path.join(root, file), 'utf8');
|
|
files.set(file, text);
|
|
privacyWarnings(file, text, warn);
|
|
} catch { /* Absent local state is not a structural problem. */ }
|
|
}
|
|
|
|
function metadata(file) {
|
|
if (!files.has(file)) { error(file, 1, 'missing-file', 'Обязательный текстовый файл отсутствует.'); return null; }
|
|
const text = files.get(file);
|
|
const match = frontmatter(text);
|
|
if (!match) { error(file, 1, 'frontmatter', 'Нужен YAML frontmatter между строками --- .'); return null; }
|
|
try {
|
|
const doc = parseDocument(match[1], { prettyErrors: false, uniqueKeys: true });
|
|
if (doc.errors.length || doc.warnings.length || !isMap(doc.contents)) {
|
|
// Never print parser messages: they can contain source values.
|
|
const line = (doc.errors[0]?.linePos?.[0]?.line ?? 1) + 1;
|
|
error(file, line, 'yaml', 'Некорректный YAML frontmatter; требуется отображение с уникальными ключами.');
|
|
return null;
|
|
}
|
|
return { data: doc.toJS({ maxAliasCount: 50 }), body: text.slice(match[0].length) };
|
|
} catch {
|
|
error(file, 1, 'yaml', 'Не удалось разобрать YAML frontmatter.');
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function directories(relative) {
|
|
try {
|
|
return readdirSync(path.join(root, relative), { withFileTypes: true })
|
|
.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
} catch {
|
|
error(relative, 1, 'missing-directory', 'Обязательный каталог отсутствует или недоступен.');
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function skill(file, folder) {
|
|
const meta = metadata(file);
|
|
if (!meta) return;
|
|
const { name, description } = meta.data;
|
|
if (!validId(name)) error(file, 2, 'skill-name', `Нужен name в kebab-case длиной до ${MAX_ID_LENGTH} символов.`);
|
|
if (name !== folder) error(file, 2, 'skill-folder', 'Имя навыка должно совпадать с папкой.');
|
|
if (!nonempty(description) || description.length > 1024) {
|
|
error(file, 2, 'skill-description', 'Нужен непустой description длиной до 1024 символов.');
|
|
}
|
|
if (!meta.body.trim()) error(file, 1, 'skill-body', 'У навыка отсутствуют инструкции.');
|
|
}
|
|
|
|
const materials = new Map();
|
|
const ids = new Set();
|
|
for (const folder of directories('library')) {
|
|
const base = `library/${folder}`;
|
|
const card = `${base}/README.md`;
|
|
const meta = metadata(card);
|
|
const artifacts = ['PROMPT.md', 'SKILL.md'].filter((name) => isFile(`${base}/${name}`));
|
|
if (!artifacts.length) error(card, 1, 'artifact', 'Нужен PROMPT.md и/или SKILL.md.');
|
|
if (artifacts.includes('SKILL.md')) skill(`${base}/SKILL.md`, folder);
|
|
if (!meta) continue;
|
|
const { id, title, status } = meta.data;
|
|
if (!validId(id)) error(card, 2, 'card-id', `Нужен id в kebab-case длиной до ${MAX_ID_LENGTH} символов.`);
|
|
if (id !== folder) error(card, 2, 'card-folder', 'id должен совпадать с папкой материала.');
|
|
if (!nonempty(title)) error(card, 2, 'card-title', 'Нужен непустой title.');
|
|
if (!statuses.has(status)) error(card, 2, 'card-status', 'Допустимы только draft, ready, archived.');
|
|
if (!(markdown.get(card) ?? []).some((token) => token.type === 'paragraph'
|
|
&& /^Происхождение:\s*\S/.test(plain(token.tokens)))) {
|
|
error(card, 1, 'card-origin', 'Нужен непустой абзац «Происхождение: …».');
|
|
}
|
|
if (typeof id === 'string' && ids.has(id)) error(card, 2, 'duplicate-id', 'Идентификатор материала повторяется.');
|
|
ids.add(id);
|
|
materials.set(card, { title, status, artifacts: artifacts.map((name) => `${base}/${name}`) });
|
|
}
|
|
|
|
for (const folder of directories('.agents/skills')) skill(`.agents/skills/${folder}/SKILL.md`, folder);
|
|
|
|
for (const [file, tokens] of markdown) {
|
|
for (const token of links(tokens)) {
|
|
const target = destination(root, file, token.href);
|
|
const line = lineAt(files.get(file), files.get(file).indexOf(token.raw));
|
|
if (target.invalid) error(file, line, 'local-link', 'Локальная ссылка должна вести внутрь репозитория относительным путём.');
|
|
else if (target.absolute && !existsSync(target.absolute)) {
|
|
error(file, line, 'missing-link', 'Локальная ссылка ведёт к отсутствующему файлу или каталогу.');
|
|
}
|
|
}
|
|
}
|
|
|
|
const catalogFile = 'CATALOG.md';
|
|
const columns = ['Материал', 'Задача', 'Артефакты', 'Статус', 'Ссылка'];
|
|
const table = findTable(markdown.get(catalogFile) ?? [], columns);
|
|
if (!table) error(catalogFile, 1, 'catalog-table', 'Нужна таблица: Материал, Задача, Артефакты, Статус, Ссылка.');
|
|
const seen = new Set();
|
|
for (const row of table?.rows ?? []) {
|
|
const cardLinks = links(row[4].tokens);
|
|
const target = cardLinks.length === 1 ? destination(root, catalogFile, cardLinks[0].href).file : null;
|
|
const material = materials.get(target);
|
|
const line = lineAt(files.get(catalogFile), files.get(catalogFile).indexOf(row[0].text));
|
|
if (!material) { error(catalogFile, line, 'catalog-entry', 'Строка должна ссылаться на карточку существующего материала.'); continue; }
|
|
if (seen.has(target)) error(catalogFile, line, 'catalog-duplicate', 'Материал повторяется в каталоге.');
|
|
seen.add(target);
|
|
if (plain(row[0].tokens) !== material.title) error(catalogFile, line, 'catalog-title', 'Название не совпадает с title карточки.');
|
|
if (!plain(row[1].tokens)) error(catalogFile, line, 'catalog-purpose', 'Укажите задачу материала.');
|
|
if (plain(row[3].tokens) !== material.status) error(catalogFile, line, 'catalog-status', 'Статус не совпадает с карточкой.');
|
|
const artifactLinks = links(row[2].tokens).map((token) => destination(root, catalogFile, token.href).file);
|
|
if (artifactLinks.length !== material.artifacts.length
|
|
|| material.artifacts.some((artifact) => !artifactLinks.includes(artifact))) {
|
|
error(catalogFile, line, 'catalog-artifacts', 'Ссылки артефактов должны соответствовать PROMPT.md и SKILL.md материала.');
|
|
}
|
|
}
|
|
for (const card of materials.keys()) {
|
|
if (!seen.has(card)) error(card, 1, 'catalog-missing', 'Материал отсутствует в каталоге.');
|
|
}
|
|
|
|
// Source files live outside the library. Check the recorded relationships,
|
|
// never read the source project or interpret its instructions here.
|
|
const projectRecords = new Map();
|
|
const sourceColumns = ['Исходный файл', 'SHA-256', 'Связанные материалы'];
|
|
const linkedFiles = (file) => links(markdown.get(file) ?? [])
|
|
.map((token) => destination(root, file, token.href).file).filter(Boolean);
|
|
for (const [file, tokens] of markdown) {
|
|
if (!/^sources\/[^/]+\.md$/.test(file) || file === 'sources/README.md') continue;
|
|
const table = findTable(tokens, sourceColumns);
|
|
if (!frontmatter(files.get(file)) && !table) continue;
|
|
const meta = metadata(file);
|
|
if (!meta || (!Object.hasOwn(meta.data, 'project') && !table)) continue;
|
|
if (!validId(meta.data.project) || meta.data.project !== path.posix.basename(file, '.md')) {
|
|
error(file, 2, 'source-project', 'Нужен project в kebab-case, совпадающий с именем файла.');
|
|
}
|
|
const cards = new Set();
|
|
projectRecords.set(file, cards);
|
|
// Registry v2 (BHL-033, D-008): every project record states its standard
|
|
// attachment — profile, target version, access policy — or an explicit gap.
|
|
const recordText = files.get(file) ?? '';
|
|
const sectionStart = recordText.indexOf('## Подключение к стандарту');
|
|
if (sectionStart === -1) {
|
|
error(file, 1, 'source-standard', 'Нужен раздел «Подключение к стандарту» с полями Профиль, Версия стандарта, Политика доступа.');
|
|
} else {
|
|
const rest = recordText.slice(sectionStart + '## Подключение к стандарту'.length);
|
|
const sectionEnd = rest.search(/^## /m);
|
|
const body = sectionEnd === -1 ? rest : rest.slice(0, sectionEnd);
|
|
for (const key of ['Профиль', 'Версия стандарта', 'Политика доступа']) {
|
|
const row = new RegExp(`^- ${key}: (.+)$`, 'm').exec(body);
|
|
if (!row) {
|
|
error(file, 1, 'source-standard', `В разделе «Подключение к стандарту» нет строки «- ${key}:».`);
|
|
} else if (row[1].trimStart().startsWith('пробел') && !/^пробел — .{3,}$/.test(row[1].trim())) {
|
|
error(file, 1, 'source-standard', `Пробел по «${key}» требует причины после « — ».`);
|
|
}
|
|
}
|
|
}
|
|
if (!table?.rows.length) {
|
|
error(file, 1, 'source-table', 'Нужна непустая таблица: Исходный файл, SHA-256, Связанные материалы.');
|
|
continue;
|
|
}
|
|
const sourcePaths = new Set();
|
|
for (const row of table.rows) {
|
|
const sourcePath = plain(row[0].tokens).replaceAll('\\', '/');
|
|
const line = lineAt(files.get(file), files.get(file).indexOf(row[0].text));
|
|
if (!sourcePath || sourcePath === '.' || sourcePath.startsWith('/')
|
|
|| /^[a-z][a-z\d+.-]*:/i.test(sourcePath) || sourcePath.split('/').includes('..')) {
|
|
error(file, line, 'source-path', 'Исходный файл задаётся относительным путём внутри проекта.');
|
|
}
|
|
if (sourcePaths.has(sourcePath)) error(file, line, 'source-duplicate', 'Исходный файл повторяется в таблице проекта.');
|
|
sourcePaths.add(sourcePath);
|
|
if (!/^[a-f0-9]{64}$/.test(plain(row[1].tokens))) {
|
|
error(file, line, 'source-hash', 'Нужен SHA-256: 64 шестнадцатеричных символа в нижнем регистре.');
|
|
}
|
|
const targets = links(row[2].tokens).map((token) => destination(root, file, token.href).file);
|
|
if (!targets.length || targets.some((target) => !materials.has(target))) {
|
|
error(file, line, 'source-material', 'Укажите ссылки на существующие карточки материалов.');
|
|
}
|
|
for (const target of targets) if (materials.has(target)) cards.add(target);
|
|
}
|
|
for (const card of cards) {
|
|
if (!linkedFiles(card).includes(file)) {
|
|
error(card, 1, 'source-backlink', 'В карточке нет обратной ссылки на запись проекта-источника.');
|
|
}
|
|
}
|
|
}
|
|
for (const card of materials.keys()) {
|
|
for (const source of linkedFiles(card)) {
|
|
if (projectRecords.has(source) && !projectRecords.get(source).has(card)) {
|
|
error(card, 1, 'source-unmapped', 'Карточка ссылается на проект, но не связана ни с одним его исходным файлом.');
|
|
}
|
|
}
|
|
}
|
|
// A project subdirectory (handoffs and friends) without its provenance record
|
|
// is an orphan: the record was forgotten during intake (found 2026-11-28).
|
|
for (const file of files.keys()) {
|
|
const match = /^sources\/([^/]+)\/.+/.exec(file);
|
|
if (match && !files.has(`sources/${match[1]}.md`)) {
|
|
error(file, 1, 'source-orphan', 'Файлы каталога проекта без записи происхождения sources/<project-id>.md.');
|
|
}
|
|
}
|
|
// Product registry (D-054): the lab's own products are declared here and
|
|
// nowhere else. The schema is a lab artifact, deliberately outside the
|
|
// normative spec tree — products.yaml describes the laboratory, not the standard.
|
|
const registryFile = 'products.yaml';
|
|
const schemaFile = 'schemas/products.schema.json';
|
|
const readJson = (file) => {
|
|
const text = files.get(file);
|
|
if (text === undefined) return null;
|
|
try { return JSON.parse(text); } catch { return null; }
|
|
};
|
|
const schema = readJson(schemaFile) ?? (() => {
|
|
try { return JSON.parse(readFileSync(path.join(MODULE_ROOT, schemaFile), 'utf8')); } catch { return null; }
|
|
})();
|
|
if (!schema) {
|
|
error(schemaFile, 1, 'products-schema', 'Схема реестра продуктов отсутствует или не читается как JSON.');
|
|
}
|
|
if (!files.has(registryFile)) {
|
|
error(registryFile, 1, 'products-registry', 'Реестр продуктов лаборатории отсутствует.');
|
|
} else {
|
|
const registryText = files.get(registryFile);
|
|
let registry = null;
|
|
try {
|
|
const doc = parseDocument(registryText, { prettyErrors: false, uniqueKeys: true });
|
|
if (!doc.errors.length && !doc.warnings.length && isMap(doc.contents)) registry = doc.toJS({ maxAliasCount: 50 });
|
|
} catch { /* Reported below without source values. */ }
|
|
if (!registry) {
|
|
const doc = (() => { try { return parseDocument(registryText, { prettyErrors: true, uniqueKeys: true }); } catch { return null; } })();
|
|
const line = (doc?.errors?.[0]?.line ?? 1) || 1;
|
|
error(registryFile, line, 'products-registry', 'Реестр продуктов должен быть YAML-отображением, разобранным без ошибок.');
|
|
} else if (schema) {
|
|
const ajv = new Ajv2020({ strict: true, strictTypes: false, allErrors: true });
|
|
let validate;
|
|
try {
|
|
validate = ajv.compile(schema);
|
|
} catch {
|
|
error(schemaFile, 1, 'products-schema', 'Схема реестра продуктов не компилируется как JSON Schema.');
|
|
}
|
|
if (validate && !validate(registry)) {
|
|
for (const issue of validate.errors ?? []) {
|
|
const where = issue.instancePath ? issue.instancePath.replace(/^\//, '') : '.';
|
|
const detail = issue.keyword === 'required'
|
|
? 'Отсутствует обязательное поле.'
|
|
: issue.keyword === 'additionalProperties'
|
|
? 'Неизвестное поле не описано схемой.'
|
|
: issue.keyword === 'oneOf'
|
|
? 'Значение не соответствует ни одному допустимому варианту схемы.'
|
|
: 'Значение не удовлетворяет схеме.';
|
|
error(registryFile, 1, 'products-schema', `Нарушение схемы реестра в «${where}»: ${detail}`);
|
|
}
|
|
}
|
|
}
|
|
if (registry) {
|
|
const products = Array.isArray(registry.products) ? registry.products : [];
|
|
const areas = Array.isArray(registry.areas) ? registry.areas : [];
|
|
const transition = Array.isArray(registry.transition) ? registry.transition : [];
|
|
const productIds = new Set();
|
|
const areaIds = new Set();
|
|
const trees = new Map();
|
|
for (const product of products) {
|
|
const id = product?.id;
|
|
if (typeof id !== 'string' || !id) continue;
|
|
if (productIds.has(id)) error(registryFile, 1, 'products-duplicate', 'Идентификатор продукта повторяется в реестре.');
|
|
productIds.add(id);
|
|
if (typeof product.tree === 'string') trees.set(product.tree, id);
|
|
}
|
|
for (const area of areas) {
|
|
const id = area?.id;
|
|
if (typeof id !== 'string' || !id) continue;
|
|
if (areaIds.has(id)) error(registryFile, 1, 'products-duplicate', 'Идентификатор области управления повторяется в реестре.');
|
|
areaIds.add(id);
|
|
if (productIds.has(id)) error(registryFile, 1, 'products-duplicate', 'Один идентификатор объявлен продуктом и областью управления.');
|
|
}
|
|
const transitionTrees = new Set();
|
|
for (const entry of transition) {
|
|
if (typeof entry?.tree !== 'string') continue;
|
|
transitionTrees.add(entry.tree);
|
|
if (!trees.has(entry.tree)) {
|
|
error(registryFile, 1, 'products-transition', 'Переходная запись ссылается на дерево, не объявленное ни одним продуктом.');
|
|
}
|
|
if (isDirectory(entry.tree)) {
|
|
error(registryFile, 1, 'products-transition', 'Переходная запись осталась для уже созданного дерева; удалите её.');
|
|
}
|
|
if (typeof entry.task === 'string' && isDirectory('backlog/tasks')
|
|
&& !namesIn('backlog/tasks').some((name) => name === entry.task.toLowerCase()
|
|
|| name.startsWith(`${entry.task.toLowerCase()} - `))) {
|
|
error(registryFile, 1, 'products-transition', 'Переходная запись ссылается на несуществующую задачу миграции.');
|
|
}
|
|
}
|
|
for (const tree of trees.keys()) {
|
|
if (!isDirectory(tree) && !transitionTrees.has(tree)) {
|
|
error(registryFile, 1, 'products-tree', 'Объявленное продуктовое дерево отсутствует, и переходная запись для него не заведена.');
|
|
}
|
|
}
|
|
// Backlog projects must resolve to a registered product or a declared
|
|
// management area. The reverse is not required: an unused area is fine.
|
|
const configText = files.get('backlog.config.yml');
|
|
if (configText === undefined) {
|
|
error('backlog.config.yml', 1, 'products-project', 'Конфигурация трекера отсутствует, сверка проектов с реестром невозможна.');
|
|
} else {
|
|
let projects = null;
|
|
try {
|
|
const doc = parseDocument(configText, { prettyErrors: false, uniqueKeys: true });
|
|
const value = doc.toJS({ maxAliasCount: 50 })?.projects;
|
|
if (Array.isArray(value)) projects = value;
|
|
} catch { /* Reported below. */ }
|
|
if (!projects) {
|
|
error('backlog.config.yml', 1, 'products-project', 'В конфигурации трекера нет списка projects, сверка с реестром невозможна.');
|
|
} else {
|
|
for (const project of projects) {
|
|
if (!productIds.has(project) && !areaIds.has(project)) {
|
|
error('backlog.config.yml', 1, 'products-project', 'Проект трекера не объявлен ни продуктом, ни областью управления в реестре.');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
productCount = productIds.size;
|
|
} else {
|
|
productCount = 0;
|
|
}
|
|
}
|
|
|
|
return { errors, warnings, materials: materials.size, projects: projectRecords.size, products: productCount };
|
|
}
|
|
|
|
export function formatDiagnostics(result) {
|
|
return [
|
|
...result.errors.map((item) => `ERROR ${item.file}:${item.line} [${item.category}] ${item.message}`),
|
|
...result.warnings.map((item) => `WARN ${item.file}:${item.line} [${item.category}] ${item.message}`),
|
|
`Материалов: ${result.materials}; проектов-источников: ${result.projects}; продуктов: ${result.products}; ошибок: ${result.errors.length}; предупреждений: ${result.warnings.length}.`,
|
|
].join('\n');
|
|
}
|
|
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
const root = MODULE_ROOT;
|
|
try {
|
|
const result = checkRepository(root);
|
|
console.log(formatDiagnostics(result));
|
|
process.exitCode = result.errors.length ? 1 : 0;
|
|
} catch {
|
|
console.error('ERROR .:1 [check] Проверка прервана; подробности источников не выводятся.');
|
|
process.exitCode = 1;
|
|
}
|
|
}
|