import { createHash } from 'node:crypto'; import { readFileSync, readdirSync, statSync } from 'node:fs'; import path from 'node:path'; import { parseDocument, isMap } from 'yaml'; import type { TaskCard } from './types.ts'; export interface ReadResult { cards: TaskCard[]; errors: string[]; } export interface ReaderOptions { /** Repository root: card paths are reported relative to it. */ repoRoot: string; /** Directory holding the tracker files, relative to repoRoot or absolute. */ backlogDir: string; } const FRONTMATTER = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u; function sectionBody(text: string, marker: string): string { const begin = ``; const end = ``; const start = text.indexOf(begin); if (start === -1) { return ''; } const rest = text.slice(start + begin.length); const stop = rest.indexOf(end); return stop === -1 ? '' : rest.slice(0, stop).trim(); } function asString(value: unknown): string | null { if (typeof value === 'string' && value.trim() !== '') { return value.trim(); } if (typeof value === 'number' || typeof value === 'boolean') { return String(value); } return null; } function asStringList(value: unknown): string[] { if (Array.isArray(value)) { return value.filter((item): item is string => typeof item === 'string' && item !== ''); } if (typeof value === 'string' && value.trim() !== '') { return [value.trim()]; } return []; } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } function parseFrontmatter(text: string): Record | null { const match = FRONTMATTER.exec(text); if (match === null) { return null; } const doc = parseDocument(match[1] ?? '', { prettyErrors: false, uniqueKeys: true }); if (doc.errors.length > 0 || !isMap(doc.contents)) { return null; } const value: unknown = doc.toJS({ maxAliasCount: 50 }); return isRecord(value) ? value : null; } /** Acceptance criterion texts only: `- [x] #3 text` becomes `text`. */ function acceptanceCriteria(body: string): string[] { const lines: string[] = []; for (const raw of body.split(/\r?\n/u)) { const line = raw.trim(); if (!/^[-*+]\s*\[[ xX]\]/u.test(line)) { continue; } const text = line.replace(/^[-*+]\s*\[[ xX]\]\s*(?:#\d+\s+)?/u, '').trim(); if (text !== '') { lines.push(text); } } return lines; } function listMarkdownFiles(directory: string): string[] { let entries; try { entries = readdirSync(directory, { withFileTypes: true }); } catch { return []; } return entries .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.md')) .map((entry) => path.join(directory, entry.name)) .sort((left, right) => (left < right ? -1 : 1)); } function relativePosix(repoRoot: string, absolute: string): string { return path.relative(repoRoot, absolute).split(path.sep).join('/'); } interface Identity { id: string; title: string; status: string; } function identity(meta: Record): Identity | null { const id = asString(meta['id']); const title = asString(meta['title']); const status = asString(meta['status']); if (id === null || title === null || status === null) { return null; } return { id, title, status }; } function parentOf(meta: Record): string | null { return asString(meta['parent_task_id']) ?? asString(meta['parent']); } function readCard( repoRoot: string, absolute: string, archivedByLocation: boolean, ): TaskCard | null { const bytes = readFileSync(absolute); const text = bytes.toString('utf8'); const meta = parseFrontmatter(text); if (meta === null) { return null; } const who = identity(meta); if (who === null) { return null; } const dependencies = asStringList(meta['dependencies']); return { ...who, archived: archivedByLocation || meta['archived'] === true, path: relativePosix(repoRoot, absolute), type: asString(meta['type']), priority: asString(meta['priority']), project: asString(meta['project']), labels: asStringList(meta['labels']), milestone: asString(meta['milestone']), parentId: parentOf(meta), dependencies, description: sectionBody(text, 'SECTION:DESCRIPTION'), acceptanceCriteria: acceptanceCriteria(sectionBody(text, 'AC')), fileHash: createHash('sha256').update(bytes).digest('hex'), }; } function compareIds(left: string, right: string): number { if (left < right) { return -1; } if (left > right) { return 1; } return 0; } interface Source { directory: string; archived: boolean; } function readSource(source: Source, repoRoot: string): { cards: TaskCard[]; errors: string[] } { const cards: TaskCard[] = []; const errors: string[] = []; if (!statSyncExists(source.directory)) { return { cards, errors }; } for (const file of listMarkdownFiles(source.directory)) { const card = readCard(repoRoot, file, source.archived); if (card === null) { errors.push(`Не разобрана карточка ${relativePosix(repoRoot, file)}.`); continue; } cards.push(card); } return { cards, errors }; } /** * Reads task cards straight from the tracker files (D-060). Read-only: the * tracker stays the only source of truth and nothing here writes to it. */ export function readCards(options: ReaderOptions): ReadResult { const repoRoot = path.resolve(options.repoRoot); const backlogDir = path.isAbsolute(options.backlogDir) ? path.resolve(options.backlogDir) : path.resolve(repoRoot, options.backlogDir); const sources: Source[] = [ { directory: path.join(backlogDir, 'tasks'), archived: false }, { directory: path.join(backlogDir, 'archive', 'tasks'), archived: true }, ]; const cards: TaskCard[] = []; const errors: string[] = []; const seen = new Set(); for (const source of sources) { const read = readSource(source, repoRoot); errors.push(...read.errors); for (const card of read.cards) { if (seen.has(card.id)) { errors.push(`Идентификатор ${card.id} повторяется в прочитанных файлах.`); continue; } seen.add(card.id); cards.push(card); } } cards.sort((left, right) => compareIds(left.id, right.id)); return { cards, errors }; } function statSyncExists(directory: string): boolean { try { return statSync(directory).isDirectory(); } catch { return false; } }