/** work-store.mjs — storage, indexing, and validation for `.debug/work` orders (zero external deps). */ import fs from 'node:fs' import path from 'node:path' import { resolveStorageRoot } from './paths.mjs' export const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ export const ORDER_ID = /^[0-9]{8}-[a-z0-9]+(?:-[a-z0-9]+)*$/ export const DATE = /^\d{4}-\d{2}-\d{2}$/ export const STATUSES = ['draft', 'active', 'review'] export const GATES = ['bare', 'go', 'frontend', 'full', 'smoke'] export const RETIRE_KINDS = ['code', 'test', 'comment', 'doc', 'none', 'pending'] export const VERIFY_RESULTS = ['pass', 'fail', 'skip'] export const LOOSE = [/\.tmp\./i, /\.log$/i, /^repro-/i, /-draft/i, /\.bak$/i] export const DAY = 24 * 60 * 60 * 1000 const RANK = { draft: 0, active: 1, review: 2 } const ALLOWED_META_KEYS = new Set([ 'schema', 'id', 'title', 'status', 'owner', 'reviewer', 'created', 'updated', 'branch', 'worktree', 'depends', 'paths', 'tests', 'gate', 'gateArgs', 'measurements', 'acceptance', 'verification', 'handoff', 'history', ]) export const TEMPLATE = fs.readFileSync(path.join(import.meta.dirname, 'work-template.md'), 'utf8') export function today() { const now = new Date() const pad = (value) => String(value).padStart(2, '0') return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}` } export function isInside(parent, child) { const rel = path.relative(parent, child) return rel === '' || (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel)) } function safeRelative(value) { return typeof value === 'string' && value !== '' && !path.isAbsolute(value) && !value.split(/[\\/]/).includes('..') } function stripDotSlash(value) { return value.replace(/^\.[\\/]/, '') } function isStringArray(value) { return Array.isArray(value) && value.every((item) => typeof item === 'string') } function overlaps(left, right) { const a = left.split(path.sep).join('/').replace(/\/+$/, '') const b = right.split(path.sep).join('/').replace(/\/+$/, '') return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`) } export function collectDurableDocs(storage) { const docs = ['README.md', 'README.en.md', 'CHANGELOG.md', 'AGENTS.md'] const docsDir = path.join(storage, 'docs') if (fs.existsSync(docsDir)) { const walk = (dir, prefix) => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const rel = `${prefix}/${entry.name}` if (entry.isDirectory()) walk(path.join(dir, entry.name), rel) else if (entry.name.endsWith('.md')) docs.push(rel) } } walk(docsDir, 'docs') } return docs } function schemaProblems(meta, name) { const problems = [] if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) { return [`${name}: work block must be a JSON object`] } for (const key of Object.keys(meta)) { if (!ALLOWED_META_KEYS.has(key)) problems.push(`${name}: unexpected field "${key}"`) } for (const key of ALLOWED_META_KEYS) { if (!(key in meta)) problems.push(`${name}: missing required field "${key}"`) } if (meta.schema !== 1) problems.push(`${name}: schema must be 1`) if (typeof meta.id !== 'string' || !ORDER_ID.test(meta.id)) { problems.push(`${name}: id "${meta.id}" must match YYYYMMDD-slug`) } if (typeof meta.title !== 'string' || meta.title.trim() === '') { problems.push(`${name}: title must be a non-empty string`) } if (!STATUSES.includes(meta.status)) { problems.push(`${name}: status "${meta.status}" must be one of ${STATUSES.join(', ')}`) } if (typeof meta.owner !== 'string') problems.push(`${name}: owner must be a string`) if (meta.reviewer !== null && typeof meta.reviewer !== 'string') { problems.push(`${name}: reviewer must be a string or null`) } if (typeof meta.created !== 'string' || !DATE.test(meta.created)) { problems.push(`${name}: created must be YYYY-MM-DD`) } if (typeof meta.updated !== 'string' || !DATE.test(meta.updated)) { problems.push(`${name}: updated must be YYYY-MM-DD`) } if (meta.branch !== null && typeof meta.branch !== 'string') { problems.push(`${name}: branch must be a string or null`) } if (meta.worktree !== null && typeof meta.worktree !== 'string') { problems.push(`${name}: worktree must be a string or null`) } if (!isStringArray(meta.depends)) problems.push(`${name}: depends must be an array of strings`) if (!isStringArray(meta.paths)) problems.push(`${name}: paths must be an array of strings`) if (!isStringArray(meta.tests)) problems.push(`${name}: tests must be an array of strings`) if (!GATES.includes(meta.gate)) { problems.push(`${name}: gate "${meta.gate}" must be one of ${GATES.join(', ')}`) } if (!isStringArray(meta.gateArgs)) problems.push(`${name}: gateArgs must be an array of strings`) if (!Array.isArray(meta.measurements)) { problems.push(`${name}: measurements must be an array`) } else { for (const [idx, m] of meta.measurements.entries()) { if (m === null || typeof m !== 'object' || Array.isArray(m)) { problems.push(`${name}: measurements[${idx}] must be an object`) continue } if (typeof m.item !== 'string' || m.item.trim() === '') problems.push(`${name}: measurements[${idx}].item must be non-empty`) if (typeof m.value !== 'string' || m.value.trim() === '') problems.push(`${name}: measurements[${idx}].value must be non-empty`) if (typeof m.source !== 'string' || m.source.trim() === '') problems.push(`${name}: measurements[${idx}].source must be non-empty`) if (m.enforced !== null && typeof m.enforced !== 'string') problems.push(`${name}: measurements[${idx}].enforced must be string or null`) if (!RETIRE_KINDS.includes(m.retire)) problems.push(`${name}: measurements[${idx}].retire must be one of ${RETIRE_KINDS.join(', ')}`) if (m.note !== undefined && m.note !== null && typeof m.note !== 'string') { problems.push(`${name}: measurements[${idx}].note must be string or null`) } } } if (!Array.isArray(meta.acceptance)) { problems.push(`${name}: acceptance must be an array`) } else { for (const [idx, entry] of meta.acceptance.entries()) { if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { problems.push(`${name}: acceptance[${idx}] must be an object`) continue } if (typeof entry.id !== 'string' || entry.id.trim() === '') problems.push(`${name}: acceptance[${idx}].id must be non-empty`) if (typeof entry.text !== 'string' || entry.text.trim() === '') problems.push(`${name}: acceptance[${idx}].text must be non-empty`) if (typeof entry.check !== 'string' || entry.check.trim() === '') problems.push(`${name}: acceptance[${idx}].check must be non-empty`) } } if (!Array.isArray(meta.verification)) { problems.push(`${name}: verification must be an array`) } else { for (const [idx, entry] of meta.verification.entries()) { if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { problems.push(`${name}: verification[${idx}] must be an object`) continue } if (typeof entry.at !== 'string' || !DATE.test(entry.at)) problems.push(`${name}: verification[${idx}].at must be YYYY-MM-DD`) if (typeof entry.command !== 'string' || entry.command.trim() === '') problems.push(`${name}: verification[${idx}].command must be non-empty`) if (!VERIFY_RESULTS.includes(entry.result)) problems.push(`${name}: verification[${idx}].result must be pass, fail, or skip`) if (entry.evidence !== undefined && entry.evidence !== null && typeof entry.evidence !== 'string') { problems.push(`${name}: verification[${idx}].evidence must be string or null`) } } } if (meta.handoff === null || typeof meta.handoff !== 'object' || Array.isArray(meta.handoff)) { problems.push(`${name}: handoff must be an object`) } else { if (typeof meta.handoff.state !== 'string') problems.push(`${name}: handoff.state must be a string`) if (typeof meta.handoff.next !== 'string') problems.push(`${name}: handoff.next must be a string`) if (!isStringArray(meta.handoff.blockers)) problems.push(`${name}: handoff.blockers must be an array of strings`) if (meta.handoff.lastCommand !== null && typeof meta.handoff.lastCommand !== 'string') { problems.push(`${name}: handoff.lastCommand must be string or null`) } } if (!Array.isArray(meta.history) || meta.history.length === 0) { problems.push(`${name}: history must be a non-empty array`) } else { for (const [idx, entry] of meta.history.entries()) { if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { problems.push(`${name}: history[${idx}] must be an object`) continue } if (typeof entry.at !== 'string' || !DATE.test(entry.at)) problems.push(`${name}: history[${idx}].at must be YYYY-MM-DD`) if (!STATUSES.includes(entry.status)) problems.push(`${name}: history[${idx}].status is invalid`) if (typeof entry.by !== 'string' || entry.by.trim() === '') problems.push(`${name}: history[${idx}].by must be non-empty`) } } return problems } export function createWorkStore(storageRoot = resolveStorageRoot()) { const STORAGE = path.resolve(storageRoot) const DEBUG = path.join(STORAGE, '.debug') const WORK = path.join(DEBUG, 'work') const INDEX = path.join(WORK, 'index.json') const LOCK = path.join(WORK, '.lock') function relative(file) { return path.relative(STORAGE, file).split(path.sep).join('/') } function existsIn(base, value) { return safeRelative(value) && fs.existsSync(path.resolve(base, stripDotSlash(value))) } function existsAt(value) { return existsIn(STORAGE, value) } function readOrder(dir) { const file = path.join(dir, 'work.md') const text = fs.readFileSync(file, 'utf8') const match = text.match(/^/) if (match === null) throw new Error(`${relative(file)}: no work block at the top`) let meta try { meta = JSON.parse(match[1]) } catch (error) { throw new Error(`${relative(file)}: the work block is not valid JSON (${error.message})`) } return { dir, file, text, meta } } function writeOrder(order, meta) { const block = `` const text = order.text.replace(/^/, block) fs.writeFileSync(order.file, text) order.text = text order.meta = meta } function orderDirs() { if (!fs.existsSync(WORK)) return [] return fs.readdirSync(WORK, { withFileTypes: true }) .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')) .map((entry) => path.join(WORK, entry.name)) } function readAll() { const orders = [] const problems = [] const warnings = [] for (const dir of orderDirs()) { const file = path.join(dir, 'work.md') if (!fs.existsSync(file)) { warnings.push(`${relative(dir)}: no work.md — run \`node scripts/debug/work.mjs gc\``) continue } try { orders.push(readOrder(dir)) } catch (error) { problems.push(error.message) } } return { orders, problems, warnings } } function indexData(orders) { const sorted = [...orders].sort((a, b) => a.meta.id.localeCompare(b.meta.id)) return { version: 1, updated: sorted.map((order) => order.meta.updated).sort().at(-1) ?? null, orders: sorted.map((order) => ({ id: order.meta.id, title: order.meta.title, status: order.meta.status, owner: order.meta.owner, updated: order.meta.updated, paths: order.meta.paths, gate: order.meta.gate, })), } } function withLock(fn) { fs.mkdirSync(WORK, { recursive: true }) let fd = null const started = Date.now() while (fd === null) { try { fd = fs.openSync(LOCK, 'wx') fs.writeFileSync(fd, String(process.pid)) } catch (error) { if (error.code !== 'EEXIST') throw error try { if (Date.now() - fs.statSync(LOCK).mtimeMs > 10_000) fs.rmSync(LOCK, { force: true }) } catch { // Holder released the lock between open and stat. } if (Date.now() - started > 5_000) throw new Error('work: index lock is busy') Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50) } } try { return fn() } finally { fs.closeSync(fd) fs.rmSync(LOCK, { force: true }) } } function syncIndex() { withLock(() => { const valid = readAll().orders.filter((order) => schemaProblems(order.meta, order.meta?.id ?? 'order').length === 0) const text = `${JSON.stringify(indexData(valid), null, 2)}\n` if (!fs.existsSync(INDEX) || fs.readFileSync(INDEX, 'utf8') !== text) fs.writeFileSync(INDEX, text) }) } function dirSize(dir) { if (!fs.existsSync(dir)) return 0 let total = 0 for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const child = path.join(dir, entry.name) if (entry.isSymbolicLink()) continue total += entry.isDirectory() ? dirSize(child) : fs.statSync(child).size } return total } function validateOrder(order, all) { const name = `work/${path.basename(order.dir)}` const problems = schemaProblems(order.meta, name) const meta = order.meta if (meta === null || typeof meta !== 'object') return problems if (meta.id !== path.basename(order.dir)) { problems.push(`${name}: id "${meta.id}" does not match directory "${path.basename(order.dir)}"`) } if (typeof meta.created === 'string' && typeof meta.updated === 'string' && meta.created > meta.updated) { problems.push(`${name}: updated is earlier than created`) } const history = Array.isArray(meta.history) ? meta.history : [] let rank = -1 for (const entry of history) { if (entry === null || typeof entry !== 'object') continue const next = RANK[entry.status] ?? -1 if (next < rank) problems.push(`${name}: history goes back from a later status to "${entry.status}"`) rank = next } const last = history.at(-1) if (last !== null && typeof last === 'object' && last.status !== meta.status) { problems.push(`${name}: last history entry is "${last.status}", not "${meta.status}"`) } if (meta.status !== 'draft') { if (typeof meta.owner !== 'string' || meta.owner === '') problems.push(`${name}: an active order needs an owner`) if (typeof meta.branch !== 'string' || meta.branch === '') problems.push(`${name}: an active order needs a branch`) } if (Array.isArray(meta.paths)) { for (const value of meta.paths) { if (!safeRelative(value)) problems.push(`${name}: path "${value}" must stay inside the repository`) else if (meta.status !== 'draft' && !existsAt(value)) problems.push(`${name}: path "${value}" does not exist`) } } if (Array.isArray(meta.tests)) { for (const value of meta.tests) { if (!safeRelative(value)) problems.push(`${name}: test "${value}" must stay inside the repository`) else if (meta.status !== 'draft' && !existsAt(value)) problems.push(`${name}: test "${value}" does not exist`) } } if (meta.status === 'review') { if (!Array.isArray(meta.verification) || !meta.verification.some((entry) => entry.result === 'pass')) { problems.push(`${name}: review needs at least one passing verification`) } if (!Array.isArray(meta.acceptance) || meta.acceptance.length === 0) { problems.push(`${name}: review needs at least one acceptance criterion`) } } for (const measurement of Array.isArray(meta.measurements) ? meta.measurements : []) { if (measurement === null || typeof measurement !== 'object') continue if (meta.status === 'review' && measurement.retire === 'pending') { problems.push(`${name}: measurement "${measurement.item}" still says pending`) } if (measurement.enforced !== null && measurement.enforced !== undefined) { if (!safeRelative(measurement.enforced) || !existsAt(measurement.enforced)) { problems.push(`${name}: measurement "${measurement.item}" names "${measurement.enforced}", which does not exist`) } } else if (meta.status === 'review' && measurement.retire !== 'none') { problems.push(`${name}: measurement "${measurement.item}" has no enforced path for retire "${measurement.retire}"`) } } for (const entry of Array.isArray(meta.acceptance) ? meta.acceptance : []) { if (entry === null || typeof entry !== 'object' || typeof entry.check !== 'string') continue const check = entry.check if (check.startsWith('test:')) { const value = check.slice(5).trim() if (!existsAt(value)) problems.push(`${name}: acceptance ${entry.id} names a test path that does not exist: ${value}`) } else if (check.startsWith('shot:')) { const value = check.slice(5).trim() if (!existsIn(order.dir, value)) problems.push(`${name}: acceptance ${entry.id} names a shot that does not exist: ${value}`) } else if (!check.startsWith('manual:') && !check.startsWith('command:')) { problems.push(`${name}: acceptance ${entry.id} must start with test:, shot:, manual:, or command:`) } else if (check.slice(check.indexOf(':') + 1).trim() === '') { problems.push(`${name}: acceptance ${entry.id} has an empty ${check.split(':')[0]} check`) } } for (const entry of Array.isArray(meta.depends) ? meta.depends : []) { if (typeof entry !== 'string') continue if (entry === meta.id) problems.push(`${name}: depends on itself`) else if (!all.some((other) => other.meta.id === entry)) problems.push(`${name}: depends on "${entry}", which is not an order`) } if (typeof meta.worktree === 'string' && meta.worktree !== '') { const tree = path.resolve(STORAGE, meta.worktree) if (!isInside(DEBUG, tree)) problems.push(`${name}: worktree "${meta.worktree}" must stay under .debug/`) } return problems } /** A clean checkout without `.debug/work` has no orders to validate. */ function checkWorkOrders() { const { orders, problems, warnings } = readAll() for (const order of orders) problems.push(...validateOrder(order, orders)) const live = orders.filter((order) => order.meta.status === 'active' || order.meta.status === 'review') for (let i = 0; i < live.length; i += 1) { for (let j = i + 1; j < live.length; j += 1) { const left = live[i].meta const right = live[j].meta if (!Array.isArray(left.paths) || !Array.isArray(right.paths)) continue const overlap = left.paths.some((a) => right.paths.some((b) => overlaps(a, b))) const leftDepends = Array.isArray(left.depends) ? left.depends : [] const rightDepends = Array.isArray(right.depends) ? right.depends : [] const related = leftDepends.includes(right.id) || rightDepends.includes(left.id) if (overlap && !related) { problems.push(`work: ${left.id} and ${right.id} own overlapping paths; make one depend on the other`) } } } const valid = orders.filter((order) => schemaProblems(order.meta, order.meta?.id ?? 'order').length === 0) const expectedIndex = `${JSON.stringify(indexData(valid), null, 2)}\n` const actualIndex = fs.existsSync(INDEX) ? fs.readFileSync(INDEX, 'utf8') : '' if ((orders.length > 0 || actualIndex !== '') && actualIndex !== expectedIndex) { problems.push('work: index.json is stale — run `node scripts/debug/work.mjs list`') } const ids = new Set(valid.map((order) => order.meta.id)) if (ids.size > 0) { for (const file of collectDurableDocs(STORAGE)) { const full = path.join(STORAGE, file) if (!fs.existsSync(full)) continue const text = fs.readFileSync(full, 'utf8') for (const id of ids) { if (text.includes(id)) problems.push(`${file}: names work order ${id} — durable documents do not cite work orders`) } } } if (fs.existsSync(DEBUG)) { const loose = fs.readdirSync(DEBUG, { withFileTypes: true }) .filter((entry) => entry.isFile() && LOOSE.some((pattern) => pattern.test(entry.name)) && Date.now() - fs.statSync(path.join(DEBUG, entry.name)).mtimeMs > DAY) .map((entry) => entry.name) if (loose.length > 0) { const sample = loose.slice(0, 3).join(', ') warnings.push(`${loose.length} loose temporary file(s) older than 24 hours under .debug (${sample}${loose.length > 3 ? ', …' : ''}) — run \`node scripts/debug/work.mjs gc --yes\``) } } const bytes = dirSize(WORK) if (bytes > 1024 ** 3) { warnings.push(`.debug/work holds ${(bytes / 1024 ** 3).toFixed(1)} GB — close finished orders or run work gc`) } return { problems, warnings, count: orders.length } } return { STORAGE, DEBUG, WORK, INDEX, TEMPLATE, relative, existsAt, readOrder, writeOrder, orderDirs, readAll, syncIndex, dirSize, validateOrder, checkWorkOrders, } }