#!/usr/bin/env node /** * check.mjs — enforce `.debug/` workspace and durable documentation hygiene: * 1. Validate `.debug/work/` work orders (passes cleanly when absent, e.g. in CI) * 2. Validate `.debug/tmp/` session ownership records (passes cleanly when absent) * 3. Reject stray top-level entries under `.debug/` outside DEBUG_HOMES * 4. Reject concrete `.debug/work/` or `.debug/tmp/` references in durable docs * 5. Reject broken relative links/anchors and `- **Title**: description` list slogans in durable docs */ import fs from 'node:fs' import path from 'node:path' import { DEBUG_HOMES, debugPath, resolveStorageRoot } from './paths.mjs' import { createTemporaryFiles } from './temporary-files.mjs' import { collectDurableDocs, createWorkStore, isInside } from './work-store.mjs' const CONCRETE_DEBUG_REF = /\.debug\/(?:work\/\d{8}-[a-z0-9]+(?:-[a-z0-9]+)*|tmp\/[a-z0-9-]+-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i const BOLD_COLON_BULLET = /^\s*(?:[-*+]|\d+\.)\s+\*\*[^*\r\n]+\*\*\s*[::]/ const EXTERNAL_TARGET = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i function stripFencedBlocks(markdown) { const lines = markdown.replaceAll('\r\n', '\n').split('\n') let fence = null return lines.map((line) => { const match = line.match(/^\s*(`{3,}|~{3,})/) if (match) { const marker = match[1] if (fence === null) { fence = marker[0] return '' } if (marker[0] === fence) { fence = null return '' } } return fence === null ? line : '' }) } function collectAnchors(markdown) { const anchors = new Set() const counts = new Map() for (const m of markdown.matchAll(/\bid=["']([^"']+)["']/g)) { anchors.add(m[1]) } for (const line of stripFencedBlocks(markdown)) { const h = line.match(/^#{1,6}\s+(.+?)\s*#*\s*$/) if (!h) continue const plain = h[1] .replace(/<[^>]+>/g, '') .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') .replace(/`([^`]+)`/g, '$1') .trim() .toLowerCase() .replace(/[^\p{L}\p{N}\s_-]/gu, '') .trim() .replace(/\s+/g, '-') if (!plain) continue const seen = counts.get(plain) ?? 0 counts.set(plain, seen + 1) anchors.add(seen === 0 ? plain : `${plain}-${seen}`) } return anchors } function extractRelativeTargets(lines) { const targets = [] for (let i = 0; i < lines.length; i += 1) { const withoutCode = lines[i].replace(/`[^`]*`/g, '') for (const m of withoutCode.matchAll(/!?\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g)) { targets.push({ line: i + 1, raw: m[1] }) } for (const m of withoutCode.matchAll(/\b(?:href|src|srcset)=["']([^"']+)["']/g)) { const first = m[1].split(',')[0].trim().split(/\s+/)[0] if (first) targets.push({ line: i + 1, raw: first }) } } return targets } function checkDocHygiene(storage, problems) { const anchorCache = new Map() const getAnchors = (absPath) => { if (!anchorCache.has(absPath)) { anchorCache.set(absPath, collectAnchors(fs.readFileSync(absPath, 'utf8'))) } return anchorCache.get(absPath) } const durable = collectDurableDocs(storage) const linkDocs = [...durable] if (fs.existsSync(path.join(storage, 'NOTICE.md')) && !linkDocs.includes('NOTICE.md')) { linkDocs.push('NOTICE.md') } for (const file of linkDocs) { const full = path.join(storage, file) if (!fs.existsSync(full)) continue const text = fs.readFileSync(full, 'utf8') const lines = stripFencedBlocks(text) if (durable.includes(file)) { const match = text.match(CONCRETE_DEBUG_REF) if (match !== null) { problems.push(`${file}: cites temporary debug instance "${match[0]}" — durable documents never reference concrete .debug/ instances`) } for (let i = 0; i < lines.length; i += 1) { if (BOLD_COLON_BULLET.test(lines[i])) { problems.push(`${file}:${i + 1}: uses "- **Title**: description" list style — write a plain declarative sentence instead`) } } } for (const { line, raw } of extractRelativeTargets(lines)) { if (!raw || EXTERNAL_TARGET.test(raw)) continue const [rawPath, rawFrag = ''] = raw.split('#') const decodedPath = decodeURIComponent(rawPath) const targetPath = decodedPath === '' ? full : path.resolve(path.dirname(full), decodedPath) if (!isInside(storage, targetPath)) { problems.push(`${file}:${line}: relative link "${raw}" leaves repository root`) continue } if (!fs.existsSync(targetPath)) { problems.push(`${file}:${line}: broken relative link "${raw}"`) continue } if (rawFrag !== '' && targetPath.toLowerCase().endsWith('.md')) { const frag = decodeURIComponent(rawFrag).toLowerCase() const anchors = getAnchors(targetPath) if (!anchors.has(frag) && !anchors.has(decodeURIComponent(rawFrag))) { problems.push(`${file}:${line}: broken heading anchor "#${rawFrag}" in "${raw}"`) } } } } } export function checkDebugHygiene(root = resolveStorageRoot()) { const storage = path.resolve(root) const problems = [] const warnings = [] const workResult = createWorkStore(storage).checkWorkOrders() const tmpResult = createTemporaryFiles(storage).check() problems.push(...workResult.problems, ...tmpResult.problems) warnings.push(...workResult.warnings, ...tmpResult.warnings) const debugDir = debugPath(storage) if (fs.existsSync(debugDir)) { const strays = fs.readdirSync(debugDir).filter((name) => !DEBUG_HOMES.includes(name)) if (strays.length > 0) { problems.push( `.debug: ${strays.length} entry/entries outside declared homes (${DEBUG_HOMES.join(', ')}): ` + `${strays.slice(0, 5).join(', ')}${strays.length > 5 ? ', …' : ''} — ` + 'use `node scripts/debug/tmp.mjs` for scratch or `scripts/debug/paths.mjs` for tool outputs', ) } } checkDocHygiene(storage, problems) return { problems, warnings, orderCount: workResult.count } } if (path.resolve(process.argv[1] ?? '') === path.resolve(import.meta.dirname, 'check.mjs')) { const { problems, warnings, orderCount } = checkDebugHygiene() for (const warning of warnings) console.warn(`debug-check: ${warning}`) for (const problem of problems) console.error(`debug-check: ${problem}`) if (problems.length > 0) { console.error(`debug-check: ${problems.length} problem(s) found`) process.exitCode = 1 } else { console.log(`debug-check: clean (${orderCount} work order(s), homes: ${DEBUG_HOMES.join(', ')})`) } }