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'; const statuses = new Set(['draft', 'ready', 'archived']); const validId = (value) => typeof value === 'string' && value.length <= 64 && /^[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; } }; 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. if (entry.name === '.git' || entry.name === '.pi' || entry.name === 'node_modules') 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 длиной до 64 символов.'); 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 длиной до 64 символов.'); 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); 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/.md.'); } } return { errors, warnings, materials: materials.size, projects: projectRecords.size }; } 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.errors.length}; предупреждений: ${result.warnings.length}.`, ].join('\n'); } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); 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; } }